@livedigital/client 3.60.0 → 3.61.0-encoded-screenshare.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -26,7 +26,7 @@ MERCHANTABLITY OR NON-INFRINGEMENT.
26
26
 
27
27
  See the Apache Version 2.0 License for specific language governing permissions
28
28
  and limitations under the License.
29
- ***************************************************************************** */!function(e){!function(t){var r="object"==typeof globalThis?globalThis:"object"==typeof u?u:"object"==typeof self?self:"object"==typeof this?this:function(){try{return Function("return this;")()}catch(e){}}()||function(){try{return(0,eval)("(function() { return this; })()")}catch(e){}}(),n=i(e);function i(e,t){return function(r,n){Object.defineProperty(e,r,{configurable:!0,writable:!0,value:n}),t&&t(r,n)}}void 0!==r.Reflect&&(n=i(r.Reflect,n)),function(e,t){var r=Object.prototype.hasOwnProperty,n="function"==typeof Symbol,i=n&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",s=n&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",o="function"==typeof Object.create,a={__proto__:[]}instanceof Array,c=!o&&!a,d={create:o?function(){return le(Object.create(null))}:a?function(){return le({__proto__:null})}:function(){return le({})},has:c?function(e,t){return r.call(e,t)}:function(e,t){return t in e},get:c?function(e,t){return r.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},u=Object.getPrototypeOf(Function),l="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:ce(),p="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:de(),h="function"==typeof WeakMap?WeakMap:ue(),f=n?Symbol.for("@reflect-metadata:registry"):void 0,m=ie(),g=se(m);function v(e,t,r,n){if(F(r)){if(!G(e))throw new TypeError;if(!$(t))throw new TypeError;return R(e,t)}if(!G(e))throw new TypeError;if(!V(t))throw new TypeError;if(!V(n)&&!F(n)&&!j(n))throw new TypeError;return j(n)&&(n=void 0),k(e,t,r=z(r),n)}function y(e,t){function r(r,n){if(!V(r))throw new TypeError;if(!F(n)&&!J(n))throw new TypeError;M(e,t,r,n)}return r}function b(e,t,r,n){if(!V(r))throw new TypeError;return F(n)||(n=z(n)),M(e,t,r,n)}function _(e,t,r){if(!V(t))throw new TypeError;return F(r)||(r=z(r)),D(e,t,r)}function E(e,t,r){if(!V(t))throw new TypeError;return F(r)||(r=z(r)),I(e,t,r)}function w(e,t,r){if(!V(t))throw new TypeError;return F(r)||(r=z(r)),A(e,t,r)}function S(e,t,r){if(!V(t))throw new TypeError;return F(r)||(r=z(r)),O(e,t,r)}function C(e,t){if(!V(e))throw new TypeError;return F(t)||(t=z(t)),N(e,t)}function P(e,t){if(!V(e))throw new TypeError;return F(t)||(t=z(t)),L(e,t)}function T(e,t,r){if(!V(t))throw new TypeError;if(F(r)||(r=z(r)),!V(t))throw new TypeError;F(r)||(r=z(r));var n=ae(t,r,!1);return!F(n)&&n.OrdinaryDeleteMetadata(e,t,r)}function R(e,t){for(var r=e.length-1;r>=0;--r){var n=(0,e[r])(t);if(!F(n)&&!j(n)){if(!$(n))throw new TypeError;t=n}}return t}function k(e,t,r,n){for(var i=e.length-1;i>=0;--i){var s=(0,e[i])(t,r,n);if(!F(s)&&!j(s)){if(!V(s))throw new TypeError;n=s}}return n}function D(e,t,r){if(I(e,t,r))return!0;var n=re(t);return!j(n)&&D(e,n,r)}function I(e,t,r){var n=ae(t,r,!1);return!F(n)&&H(n.OrdinaryHasOwnMetadata(e,t,r))}function A(e,t,r){if(I(e,t,r))return O(e,t,r);var n=re(t);return j(n)?void 0:A(e,n,r)}function O(e,t,r){var n=ae(t,r,!1);if(!F(n))return n.OrdinaryGetOwnMetadata(e,t,r)}function M(e,t,r,n){ae(r,n,!0).OrdinaryDefineOwnMetadata(e,t,r,n)}function N(e,t){var r=L(e,t),n=re(e);if(null===n)return r;var i=N(n,t);if(i.length<=0)return r;if(r.length<=0)return i;for(var s=new p,o=[],a=0,c=r;a<c.length;a++){var d=c[a];s.has(d)||(s.add(d),o.push(d))}for(var u=0,l=i;u<l.length;u++){d=l[u];s.has(d)||(s.add(d),o.push(d))}return o}function L(e,t){var r=ae(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function x(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 F(e){return void 0===e}function j(e){return null===e}function U(e){return"symbol"==typeof e}function V(e){return"object"==typeof e?null!==e:"function"==typeof e}function B(e,t){switch(x(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var r=3===t?"string":5===t?"number":"default",n=K(e,i);if(void 0!==n){var s=n.call(e,r);if(V(s))throw new TypeError;return s}return W(e,"default"===r?"number":r)}function W(e,t){if("string"===t){var r=e.toString;if(Y(r))if(!V(i=r.call(e)))return i;if(Y(n=e.valueOf))if(!V(i=n.call(e)))return i}else{var n;if(Y(n=e.valueOf))if(!V(i=n.call(e)))return i;var i,s=e.toString;if(Y(s))if(!V(i=s.call(e)))return i}throw new TypeError}function H(e){return!!e}function q(e){return""+e}function z(e){var t=B(e,3);return U(t)?t:q(t)}function G(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function Y(e){return"function"==typeof e}function $(e){return"function"==typeof e}function J(e){switch(x(e)){case 3:case 4:return!0;default:return!1}}function Q(e,t){return e===t||e!=e&&t!=t}function K(e,t){var r=e[t];if(null!=r){if(!Y(r))throw new TypeError;return r}}function Z(e){var t=K(e,s);if(!Y(t))throw new TypeError;var r=t.call(e);if(!V(r))throw new TypeError;return r}function X(e){return e.value}function ee(e){var t=e.next();return!t.done&&t}function te(e){var t=e.return;t&&t.call(e)}function re(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===u)return t;if(t!==u)return t;var r=e.prototype,n=r&&Object.getPrototypeOf(r);if(null==n||n===Object.prototype)return t;var i=n.constructor;return"function"!=typeof i||i===e?t:i}function ne(){var e,r,n,i;F(f)||void 0===t.Reflect||f in t.Reflect||"function"!=typeof t.Reflect.defineMetadata||(e=oe(t.Reflect));var s=new h,o={registerProvider:a,getProvider:d,setProvider:m};return o;function a(t){if(!Object.isExtensible(o))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===t:break;case F(r):r=t;break;case r===t:break;case F(n):n=t;break;case n===t:break;default:void 0===i&&(i=new p),i.add(t)}}function c(t,s){if(!F(r)){if(r.isProviderFor(t,s))return r;if(!F(n)){if(n.isProviderFor(t,s))return r;if(!F(i))for(var o=Z(i);;){var a=ee(o);if(!a)return;var c=X(a);if(c.isProviderFor(t,s))return te(o),c}}}if(!F(e)&&e.isProviderFor(t,s))return e}function d(e,t){var r,n=s.get(e);return F(n)||(r=n.get(t)),F(r)?(F(r=c(e,t))||(F(n)&&(n=new l,s.set(e,n)),n.set(t,r)),r):r}function u(e){if(F(e))throw new TypeError;return r===e||n===e||!F(i)&&i.has(e)}function m(e,t,r){if(!u(r))throw new Error("Metadata provider not registered.");var n=d(e,t);if(n!==r){if(!F(n))return!1;var i=s.get(e);F(i)&&(i=new l,s.set(e,i)),i.set(t,r)}return!0}}function ie(){var e;return!F(f)&&V(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[f]),F(e)&&(e=ne()),!F(f)&&V(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,f,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function se(e){var t=new h,r={isProviderFor:function(e,r){var n=t.get(e);return!F(n)&&n.has(r)},OrdinaryDefineOwnMetadata:o,OrdinaryHasOwnMetadata:i,OrdinaryGetOwnMetadata:s,OrdinaryOwnMetadataKeys:a,OrdinaryDeleteMetadata:c};return m.registerProvider(r),r;function n(n,i,s){var o=t.get(n),a=!1;if(F(o)){if(!s)return;o=new l,t.set(n,o),a=!0}var c=o.get(i);if(F(c)){if(!s)return;if(c=new l,o.set(i,c),!e.setProvider(n,i,r))throw o.delete(i),a&&t.delete(n),new Error("Wrong provider for target.")}return c}function i(e,t,r){var i=n(t,r,!1);return!F(i)&&H(i.has(e))}function s(e,t,r){var i=n(t,r,!1);if(!F(i))return i.get(e)}function o(e,t,r,i){n(r,i,!0).set(e,t)}function a(e,t){var r=[],i=n(e,t,!1);if(F(i))return r;for(var s=Z(i.keys()),o=0;;){var a=ee(s);if(!a)return r.length=o,r;var c=X(a);try{r[o]=c}catch(e){try{te(s)}finally{throw e}}o++}}function c(e,r,i){var s=n(r,i,!1);if(F(s))return!1;if(!s.delete(e))return!1;if(0===s.size){var o=t.get(r);F(o)||(o.delete(i),0===o.size&&t.delete(o))}return!0}}function oe(e){var t=e.defineMetadata,r=e.hasOwnMetadata,n=e.getOwnMetadata,i=e.getOwnMetadataKeys,s=e.deleteMetadata,o=new h,a={isProviderFor:function(e,t){var r=o.get(e);return!(F(r)||!r.has(t))||!!i(e,t).length&&(F(r)&&(r=new p,o.set(e,r)),r.add(t),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:n,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:s};return a}function ae(e,t,r){var n=m.getProvider(e,t);if(!F(n))return n;if(r){if(m.setProvider(e,t,g))return g;throw new Error("Illegal state.")}}function ce(){var e={},t=[],r=function(){function e(e,t,r){this._index=0,this._keys=e,this._values=t,this._selector=r}return e.prototype["@@iterator"]=function(){return this},e.prototype[s]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var r=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:r,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}(),n=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 r=this._find(e,!0);return this._values[r]=t,this},t.prototype.delete=function(t){var r=this._find(t,!1);if(r>=0){for(var n=this._keys.length,i=r+1;i<n;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,Q(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 r(this._keys,this._values,i)},t.prototype.values=function(){return new r(this._keys,this._values,o)},t.prototype.entries=function(){return new r(this._keys,this._values,a)},t.prototype["@@iterator"]=function(){return this.entries()},t.prototype[s]=function(){return this.entries()},t.prototype._find=function(e,t){if(!Q(this._cacheKey,e)){this._cacheIndex=-1;for(var r=0;r<this._keys.length;r++)if(Q(this._keys[r],e)){this._cacheIndex=r;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();return n;function i(e,t){return e}function o(e,t){return t}function a(e,t){return[e,t]}}function de(){return function(){function e(){this._map=new l}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.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[s]=function(){return this.keys()},e}()}function ue(){var e=16,t=d.create(),n=i();return function(){function e(){this._key=i()}return e.prototype.has=function(e){var t=s(e,!1);return void 0!==t&&d.has(t,this._key)},e.prototype.get=function(e){var t=s(e,!1);return void 0!==t?d.get(t,this._key):void 0},e.prototype.set=function(e,t){return s(e,!0)[this._key]=t,this},e.prototype.delete=function(e){var t=s(e,!1);return void 0!==t&&delete t[this._key]},e.prototype.clear=function(){this._key=i()},e}();function i(){var e;do{e="@@WeakMap@@"+c()}while(d.has(t,e));return t[e]=!0,e}function s(e,t){if(!r.call(e,n)){if(!t)return;Object.defineProperty(e,n,{value:d.create()})}return e[n]}function o(e,t){for(var r=0;r<t;++r)e[r]=255*Math.random()|0;return e}function a(e){if("function"==typeof Uint8Array){var t=new Uint8Array(e);return"undefined"!=typeof crypto?crypto.getRandomValues(t):"undefined"!=typeof msCrypto?msCrypto.getRandomValues(t):o(t,e),t}return o(new Array(e),e)}function c(){var t=a(e);t[6]=79&t[6]|64,t[8]=191&t[8]|128;for(var r="",n=0;n<e;++n){var i=t[n];4!==n&&6!==n&&8!==n||(r+="-"),i<16&&(r+="0"),r+=i.toString(16).toLowerCase()}return r}}function le(e){return e.__=void 0,delete e.__,e}e("decorate",v),e("metadata",y),e("defineMetadata",b),e("hasMetadata",_),e("hasOwnMetadata",E),e("getMetadata",w),e("getOwnMetadata",S),e("getMetadataKeys",C),e("getOwnMetadataKeys",P),e("deleteMetadata",T)}(n,r),void 0===r.Reflect&&(r.Reflect=e)}()}(d||(d={}));var h=["inject","multi_inject","name","unmanaged","named","optional"],f="Request",m="Singleton",g="Transient",v="ConstantValue",y="Constructor",b="DynamicValue",_="Factory",E="Function",w="Instance",S="Invalid",C="Provider",P="ClassProperty",T="ConstructorArgument",R="Variable",k=0;function D(){return k++}var I=function(){function e(e,t){this.id=D(),this.activated=!1,this.serviceIdentifier=e,this.scope=t,this.type=S,this.constraint=function(e){return!0},this.implementationType=null,this.cache=null,this.factory=null,this.provider=null,this.onActivation=null,this.onDeactivation=null,this.dynamicValue=null}return e.prototype.clone=function(){var t=new e(this.serviceIdentifier,this.scope);return t.activated=t.scope===m&&this.activated,t.implementationType=this.implementationType,t.dynamicValue=this.dynamicValue,t.scope=this.scope,t.type=this.type,t.factory=this.factory,t.provider=this.provider,t.constraint=this.constraint,t.onActivation=this.onActivation,t.onDeactivation=this.onDeactivation,t.cache=this.cache,t},e}(),A="No matching bindings found for serviceIdentifier:",O="The @inject @multiInject @tagged and @named decorators must be applied to the parameters of a class constructor or a class property.",M=function(e,t){return"onDeactivation() error in class "+e+": "+t},N=function(){function e(){}return e.prototype.getConstructorMetadata=function(e){return{compilerGeneratedMetadata:Reflect.getMetadata("inversify:paramtypes",e),userGeneratedMetadata:Reflect.getMetadata("inversify:tagged",e)||{}}},e.prototype.getPropertiesMetadata=function(e){return Reflect.getMetadata("inversify:tagged_props",e)||[]},e}(),L=0,x=1;function F(e){return e instanceof RangeError||"Maximum call stack size exceeded"===e.message}function j(e){return"function"==typeof e?e.name:"symbol"==typeof e?e.toString():e}function U(e,t,r){var n="",i=r(e,t);return 0!==i.length&&(n="\nRegistered bindings:",i.forEach((function(e){var t="Object";null!==e.implementationType&&(t=W(e.implementationType)),n=n+"\n "+t,e.constraint.metaData&&(n=n+" - "+e.constraint.metaData)}))),n}function V(e,t){return null!==e.parentRequest&&(e.parentRequest.serviceIdentifier===t||V(e.parentRequest,t))}function B(e){e.childRequests.forEach((function(e){if(V(e,e.serviceIdentifier)){var t=function(e){return function e(t,r){void 0===r&&(r=[]);var n=j(t.serviceIdentifier);return r.push(n),null!==t.parentRequest?e(t.parentRequest,r):r}(e).reverse().join(" --\x3e ")}(e);throw new Error("Circular dependency found: "+t)}B(e)}))}function W(e){if(e.name)return e.name;var t=e.toString(),r=t.match(/^function\s*([^\s(]+)/);return r?r[1]:"Anonymous function: "+t}var H=function(){function e(e){this.id=D(),this.container=e}return e.prototype.addPlan=function(e){this.plan=e},e.prototype.setCurrentRequest=function(e){this.currentRequest=e},e}(),q=function(){function e(e,t){this.key=e,this.value=t}return e.prototype.toString=function(){return"named"===this.key?"named: "+String(this.value).toString()+" ":"tagged: { key:"+this.key.toString()+", value: "+String(this.value)+" }"},e}(),z=function(e,t){this.parentContext=e,this.rootRequest=t},G=function(){function e(e){this._cb=e}return e.prototype.unwrap=function(){return this._cb()},e}(),Y=function(){function e(e){this.str=e}return e.prototype.startsWith=function(e){return 0===this.str.indexOf(e)},e.prototype.endsWith=function(e){var t,r=e.split("").reverse().join("");return t=this.str.split("").reverse().join(""),this.startsWith.call({str:t},r)},e.prototype.contains=function(e){return-1!==this.str.indexOf(e)},e.prototype.equals=function(e){return this.str===e},e.prototype.value=function(){return this.str},e}(),$=function(){function e(e,t,r,n){this.id=D(),this.type=e,this.serviceIdentifier=r;var i="symbol"==typeof t?function(e){return e.toString().slice(7,-1)}(t):t;this.name=new Y(i||""),this.identifier=t,this.metadata=new Array;var s=null;"string"==typeof n?s=new q("named",n):n instanceof q&&(s=n),null!==s&&this.metadata.push(s)}return e.prototype.hasTag=function(e){for(var t=0,r=this.metadata;t<r.length;t++){if(r[t].key===e)return!0}return!1},e.prototype.isArray=function(){return this.hasTag("multi_inject")},e.prototype.matchesArray=function(e){return this.matchesTag("multi_inject")(e)},e.prototype.isNamed=function(){return this.hasTag("named")},e.prototype.isTagged=function(){return this.metadata.some((function(e){return h.every((function(t){return e.key!==t}))}))},e.prototype.isOptional=function(){return this.matchesTag("optional")(!0)},e.prototype.getNamedTag=function(){return this.isNamed()?this.metadata.filter((function(e){return"named"===e.key}))[0]:null},e.prototype.getCustomTags=function(){return this.isTagged()?this.metadata.filter((function(e){return h.every((function(t){return e.key!==t}))})):null},e.prototype.matchesNamedTag=function(e){return this.matchesTag("named")(e)},e.prototype.matchesTag=function(e){var t=this;return function(r){for(var n=0,i=t.metadata;n<i.length;n++){var s=i[n];if(s.key===e&&s.value===r)return!0}return!1}},e}(),J=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))};function Q(e,t,r,n){var i=e.getConstructorMetadata(r),s=i.compilerGeneratedMetadata;if(void 0===s)throw new Error("Missing required @injectable annotation in: "+t+".");var o=i.userGeneratedMetadata,a=Object.keys(o),c=0===r.length&&a.length>0,d=a.length>r.length,u=function(e,t,r,n,i){for(var s=[],o=0;o<i;o++){var a=K(o,e,t,r,n);null!==a&&s.push(a)}return s}(n,t,s,o,c||d?a.length:r.length),l=X(e,r,t);return J(J([],u,!0),l,!0)}function K(e,t,r,n,i){var s=i[e.toString()]||[],o=te(s),a=!0!==o.unmanaged,c=n[e],d=o.inject||o.multiInject;if((c=d||c)instanceof G&&(c=c.unwrap()),a){if(!t&&(c===Object||c===Function||void 0===c))throw new Error("Missing required @inject or @multiInject annotation in: argument "+e+" in class "+r+".");var u=new $(T,o.targetName,c);return u.metadata=s,u}return null}function Z(e,t,r,n){var i=e||t;if(void 0===i){var s="Missing required @injectable annotation in: for property "+String(r)+" in class "+n+".";throw new Error(s)}return i}function X(e,t,r){for(var n=e.getPropertiesMetadata(t),i=[],s=Object.getOwnPropertySymbols(n),o=0,a=Object.keys(n).concat(s);o<a.length;o++){var c=a[o],d=n[c],u=te(d),l=u.targetName||c,p=Z(u.inject,u.multiInject,c,r),h=new $(P,l,p);h.metadata=d,i.push(h)}var f=Object.getPrototypeOf(t.prototype).constructor;if(f!==Object){var m=X(e,f,r);i=J(J([],i,!0),m,!0)}return i}function ee(e,t){var r=Object.getPrototypeOf(t.prototype).constructor;if(r!==Object){var n=Q(e,W(r),r,!0),i=n.map((function(e){return e.metadata.filter((function(e){return"unmanaged"===e.key}))})),s=[].concat.apply([],i).length,o=n.length-s;return o>0?o:ee(e,r)}return 0}function te(e){var t={};return e.forEach((function(e){t[e.key.toString()]=e.value})),{inject:t.inject,multiInject:t.multi_inject,targetName:t.name,unmanaged:t.unmanaged}}var re=function(){function e(e,t,r,n,i){this.id=D(),this.serviceIdentifier=e,this.parentContext=t,this.parentRequest=r,this.target=i,this.childRequests=[],this.bindings=Array.isArray(n)?n:[n],this.requestScope=null===r?new Map:null}return e.prototype.addChildRequest=function(t,r,n){var i=new e(t,this.parentContext,this,r,n);return this.childRequests.push(i),i},e}();function ne(e){return e._bindingDictionary}function ie(e,t,r,n,i){var s=oe(r.container,i.serviceIdentifier),o=[];return s.length===L&&r.container.options.autoBindInjectable&&"function"==typeof i.serviceIdentifier&&e.getConstructorMetadata(i.serviceIdentifier).compilerGeneratedMetadata&&(r.container.bind(i.serviceIdentifier).toSelf(),s=oe(r.container,i.serviceIdentifier)),o=t?s:s.filter((function(e){var t=new re(e.serviceIdentifier,r,n,e,i);return e.constraint(t)})),function(e,t,r,n){switch(t.length){case L:if(r.isOptional())return t;var i=j(e),s=A;throw s+=function(e,t){if(t.isTagged()||t.isNamed()){var r="",n=t.getNamedTag(),i=t.getCustomTags();return null!==n&&(r+=n.toString()+"\n"),null!==i&&i.forEach((function(e){r+=e.toString()+"\n"}))," "+e+"\n "+e+" - "+r}return" "+e}(i,r),s+=U(n,i,oe),new Error(s);case x:return t;default:if(r.isArray())return t;s="Ambiguous match found for serviceIdentifier: "+(i=j(e));throw s+=U(n,i,oe),new Error(s)}}(i.serviceIdentifier,o,i,r.container),o}function se(e,t,r,n,i,s){var o,a;if(null===i){o=ie(e,t,n,null,s),a=new re(r,n,null,o,s);var c=new z(n,a);n.addPlan(c)}else o=ie(e,t,n,i,s),a=i.addChildRequest(s.serviceIdentifier,o,s);o.forEach((function(t){var r=null;if(s.isArray())r=a.addChildRequest(t.serviceIdentifier,t,s);else{if(t.cache)return;r=a}if(t.type===w&&null!==t.implementationType){var i=function(e,t){return Q(e,W(t),t,!1)}(e,t.implementationType);if(!n.container.options.skipBaseClassChecks){var o=ee(e,t.implementationType);if(i.length<o){var c=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return"The number of constructor arguments in the derived class "+e[0]+" must be >= than the number of constructor arguments of its base class."}(W(t.implementationType));throw new Error(c)}}i.forEach((function(t){se(e,!1,t.serviceIdentifier,n,r,t)}))}}))}function oe(e,t){var r=[],n=ne(e);return n.hasKey(t)?r=n.get(t):null!==e.parent&&(r=oe(e.parent,t)),r}function ae(e,t,r,n,i,s,o,a){void 0===a&&(a=!1);var c=new H(t),d=function(e,t,r,n,i,s){var o=new q(e?"multi_inject":"inject",r),a=new $(t,n,r,o);if(void 0!==i){var c=new q(i,s);a.metadata.push(c)}return a}(r,n,i,"",s,o);try{return se(e,a,i,c,null,d),c}catch(e){throw F(e)&&B(c.plan.rootRequest),e}}function ce(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&"function"==typeof e.then}function de(e){return!!ce(e)||Array.isArray(e)&&e.some(ce)}var ue,le=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},pe=function(e,t){var r,n,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,a])}}},he=function(e,t,r){e.has(t.id)||e.set(t.id,r)},fe=function(e,t){e.cache=t,e.activated=!0,ce(t)&&me(e,t)},me=function(e,t){return le(void 0,void 0,void 0,(function(){var r,n;return pe(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,t];case 1:return r=i.sent(),e.cache=r,[3,3];case 2:throw n=i.sent(),e.cache=null,e.activated=!1,n;case 3:return[2]}}))}))};!function(e){e.DynamicValue="toDynamicValue",e.Factory="toFactory",e.Provider="toProvider"}(ue||(ue={}));var ge=function(){return ge=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},ge.apply(this,arguments)},ve=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},ye=function(e,t){var r,n,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,a])}}},be=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))};function _e(e,t,r){var n;if(t.length>0){var i=function(e,t){return e.reduce((function(e,r){var n=t(r);return r.target.type===T?e.constructorInjections.push(n):(e.propertyRequests.push(r),e.propertyInjections.push(n)),e.isAsync||(e.isAsync=de(n)),e}),{constructorInjections:[],propertyInjections:[],propertyRequests:[],isAsync:!1})}(t,r),s=ge(ge({},i),{constr:e});n=i.isAsync?function(e){return ve(this,void 0,void 0,(function(){var t,r;return ye(this,(function(n){switch(n.label){case 0:return[4,we(e.constructorInjections)];case 1:return t=n.sent(),[4,we(e.propertyInjections)];case 2:return r=n.sent(),[2,Ee(ge(ge({},e),{constructorInjections:t,propertyInjections:r}))]}}))}))}(s):Ee(s)}else n=new e;return n}function Ee(e){var t,r=new((t=e.constr).bind.apply(t,be([void 0],e.constructorInjections,!1)));return e.propertyRequests.forEach((function(t,n){var i=t.target.identifier,s=e.propertyInjections[n];t.target.isOptional()&&void 0===s||(r[i]=s)})),r}function we(e){return ve(this,void 0,void 0,(function(){var t,r,n,i;return ye(this,(function(s){for(t=[],r=0,n=e;r<n.length;r++)i=n[r],Array.isArray(i)?t.push(Promise.all(i)):t.push(i);return[2,Promise.all(t)]}))}))}function Se(e,t){var r=function(e,t){var r,n;if(Reflect.hasMetadata("post_construct",e)){var i=Reflect.getMetadata("post_construct",e);try{return null===(n=(r=t)[i.value])||void 0===n?void 0:n.call(r)}catch(t){if(t instanceof Error)throw new Error((s=e.name,o=t.message,"@postConstruct error in class "+s+": "+o))}}var s,o}(e,t);return ce(r)?r.then((function(){return t})):t}function Ce(e,t){e.scope!==m&&function(e,t){var r="Class cannot be instantiated in "+(e.scope===f?"request":"transient")+" scope.";if("function"==typeof e.onDeactivation)throw new Error(M(t.name,r));if(Reflect.hasMetadata("pre_destroy",t))throw new Error("@preDestroy error in class "+t.name+": "+r)}(e,t)}var Pe=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},Te=function(e,t){var r,n,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,a])}}},Re=function(e){return function(t){t.parentContext.setCurrentRequest(t);var r=t.bindings,n=t.childRequests,i=t.target&&t.target.isArray(),s=!(t.parentRequest&&t.parentRequest.target&&t.target&&t.parentRequest.target.matchesArray(t.target.serviceIdentifier));if(i&&s)return n.map((function(t){return Re(e)(t)}));if(!t.target.isOptional()||0!==r.length){var o=r[0];return Ae(e,t,o)}}},ke=function(e,t){var r=function(e){switch(e.type){case _:return{factory:e.factory,factoryType:ue.Factory};case C:return{factory:e.provider,factoryType:ue.Provider};case b:return{factory:e.dynamicValue,factoryType:ue.DynamicValue};default:throw new Error("Unexpected factory type "+e.type)}}(e);return function(e,t){try{return e()}catch(e){throw F(e)&&(e=t()),e}}((function(){return r.factory.bind(e)(t)}),(function(){return new Error((e=r.factoryType,n=t.currentRequest.serviceIdentifier.toString(),"It looks like there is a circular dependency in one of the '"+e+"' bindings. Please investigate bindings with service identifier '"+n+"'."));var e,n}))},De=function(e,t,r){var n,i=t.childRequests;switch(function(e){var t=null;switch(e.type){case v:case E:t=e.cache;break;case y:case w:t=e.implementationType;break;case b:t=e.dynamicValue;break;case C:t=e.provider;break;case _:t=e.factory}if(null===t){var r=j(e.serviceIdentifier);throw new Error("Invalid binding type: "+r)}}(r),r.type){case v:case E:n=r.cache;break;case y:n=r.implementationType;break;case w:n=function(e,t,r,n){Ce(e,t);var i=_e(t,r,n);return ce(i)?i.then((function(e){return Se(t,e)})):Se(t,i)}(r,r.implementationType,i,Re(e));break;default:n=ke(r,t.parentContext)}return n},Ie=function(e,t,r){var n=function(e,t){return t.scope===m&&t.activated?t.cache:t.scope===f&&e.has(t.id)?e.get(t.id):null}(e,t);return null!==n||function(e,t,r){t.scope===m&&fe(t,r),t.scope===f&&he(e,t,r)}(e,t,n=r()),n},Ae=function(e,t,r){return Ie(e,r,(function(){var n=De(e,t,r);return n=ce(n)?n.then((function(e){return Oe(t,r,e)})):Oe(t,r,n)}))};function Oe(e,t,r){var n,i=Me(e.parentContext,t,r),s=Fe(e.parentContext.container),o=s.next();do{n=o.value;var a=e.parentContext,c=e.serviceIdentifier,d=xe(n,c);i=ce(i)?Le(d,a,i):Ne(d,a,i),o=s.next()}while(!0!==o.done&&!ne(n).hasKey(e.serviceIdentifier));return i}var Me=function(e,t,r){return"function"==typeof t.onActivation?t.onActivation(e,r):r},Ne=function(e,t,r){for(var n=e.next();!n.done;){if(ce(r=n.value(t,r)))return Le(e,t,r);n=e.next()}return r},Le=function(e,t,r){return Pe(void 0,void 0,void 0,(function(){var n,i;return Te(this,(function(s){switch(s.label){case 0:return[4,r];case 1:n=s.sent(),i=e.next(),s.label=2;case 2:return i.done?[3,4]:[4,i.value(t,n)];case 3:return n=s.sent(),i=e.next(),[3,2];case 4:return[2,n]}}))}))},xe=function(e,t){var r=e._activations;return r.hasKey(t)?r.get(t).values():[].values()},Fe=function(e){for(var t=[e],r=e.parent;null!==r;)t.push(r),r=r.parent;return{next:function(){var e=t.pop();return void 0!==e?{done:!1,value:e}:{done:!0,value:void 0}}}};var je=function(e,t){var r=e.parentRequest;return null!==r&&(!!t(r)||je(r,t))},Ue=function(e){return function(t){var r=function(r){return null!==r&&null!==r.target&&r.target.matchesTag(e)(t)};return r.metaData=new q(e,t),r}},Ve=Ue("named"),Be=function(e){return function(t){var r=null;if(null!==t){if(r=t.bindings[0],"string"==typeof e)return r.serviceIdentifier===e;var n=t.bindings[0].implementationType;return e===n}return!1}},We=function(){function e(e){this._binding=e}return e.prototype.when=function(e){return this._binding.constraint=e,new He(this._binding)},e.prototype.whenTargetNamed=function(e){return this._binding.constraint=Ve(e),new He(this._binding)},e.prototype.whenTargetIsDefault=function(){return this._binding.constraint=function(e){return null!==e&&(null!==e.target&&!e.target.isNamed()&&!e.target.isTagged())},new He(this._binding)},e.prototype.whenTargetTagged=function(e,t){return this._binding.constraint=Ue(e)(t),new He(this._binding)},e.prototype.whenInjectedInto=function(e){return this._binding.constraint=function(t){return null!==t&&Be(e)(t.parentRequest)},new He(this._binding)},e.prototype.whenParentNamed=function(e){return this._binding.constraint=function(t){return null!==t&&Ve(e)(t.parentRequest)},new He(this._binding)},e.prototype.whenParentTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&Ue(e)(t)(r.parentRequest)},new He(this._binding)},e.prototype.whenAnyAncestorIs=function(e){return this._binding.constraint=function(t){return null!==t&&je(t,Be(e))},new He(this._binding)},e.prototype.whenNoAncestorIs=function(e){return this._binding.constraint=function(t){return null!==t&&!je(t,Be(e))},new He(this._binding)},e.prototype.whenAnyAncestorNamed=function(e){return this._binding.constraint=function(t){return null!==t&&je(t,Ve(e))},new He(this._binding)},e.prototype.whenNoAncestorNamed=function(e){return this._binding.constraint=function(t){return null!==t&&!je(t,Ve(e))},new He(this._binding)},e.prototype.whenAnyAncestorTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&je(r,Ue(e)(t))},new He(this._binding)},e.prototype.whenNoAncestorTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&!je(r,Ue(e)(t))},new He(this._binding)},e.prototype.whenAnyAncestorMatches=function(e){return this._binding.constraint=function(t){return null!==t&&je(t,e)},new He(this._binding)},e.prototype.whenNoAncestorMatches=function(e){return this._binding.constraint=function(t){return null!==t&&!je(t,e)},new He(this._binding)},e}(),He=function(){function e(e){this._binding=e}return e.prototype.onActivation=function(e){return this._binding.onActivation=e,new We(this._binding)},e.prototype.onDeactivation=function(e){return this._binding.onDeactivation=e,new We(this._binding)},e}(),qe=function(){function e(e){this._binding=e,this._bindingWhenSyntax=new We(this._binding),this._bindingOnSyntax=new He(this._binding)}return e.prototype.when=function(e){return this._bindingWhenSyntax.when(e)},e.prototype.whenTargetNamed=function(e){return this._bindingWhenSyntax.whenTargetNamed(e)},e.prototype.whenTargetIsDefault=function(){return this._bindingWhenSyntax.whenTargetIsDefault()},e.prototype.whenTargetTagged=function(e,t){return this._bindingWhenSyntax.whenTargetTagged(e,t)},e.prototype.whenInjectedInto=function(e){return this._bindingWhenSyntax.whenInjectedInto(e)},e.prototype.whenParentNamed=function(e){return this._bindingWhenSyntax.whenParentNamed(e)},e.prototype.whenParentTagged=function(e,t){return this._bindingWhenSyntax.whenParentTagged(e,t)},e.prototype.whenAnyAncestorIs=function(e){return this._bindingWhenSyntax.whenAnyAncestorIs(e)},e.prototype.whenNoAncestorIs=function(e){return this._bindingWhenSyntax.whenNoAncestorIs(e)},e.prototype.whenAnyAncestorNamed=function(e){return this._bindingWhenSyntax.whenAnyAncestorNamed(e)},e.prototype.whenAnyAncestorTagged=function(e,t){return this._bindingWhenSyntax.whenAnyAncestorTagged(e,t)},e.prototype.whenNoAncestorNamed=function(e){return this._bindingWhenSyntax.whenNoAncestorNamed(e)},e.prototype.whenNoAncestorTagged=function(e,t){return this._bindingWhenSyntax.whenNoAncestorTagged(e,t)},e.prototype.whenAnyAncestorMatches=function(e){return this._bindingWhenSyntax.whenAnyAncestorMatches(e)},e.prototype.whenNoAncestorMatches=function(e){return this._bindingWhenSyntax.whenNoAncestorMatches(e)},e.prototype.onActivation=function(e){return this._bindingOnSyntax.onActivation(e)},e.prototype.onDeactivation=function(e){return this._bindingOnSyntax.onDeactivation(e)},e}(),ze=function(){function e(e){this._binding=e}return e.prototype.inRequestScope=function(){return this._binding.scope=f,new qe(this._binding)},e.prototype.inSingletonScope=function(){return this._binding.scope=m,new qe(this._binding)},e.prototype.inTransientScope=function(){return this._binding.scope=g,new qe(this._binding)},e}(),Ge=function(){function e(e){this._binding=e,this._bindingWhenSyntax=new We(this._binding),this._bindingOnSyntax=new He(this._binding),this._bindingInSyntax=new ze(e)}return e.prototype.inRequestScope=function(){return this._bindingInSyntax.inRequestScope()},e.prototype.inSingletonScope=function(){return this._bindingInSyntax.inSingletonScope()},e.prototype.inTransientScope=function(){return this._bindingInSyntax.inTransientScope()},e.prototype.when=function(e){return this._bindingWhenSyntax.when(e)},e.prototype.whenTargetNamed=function(e){return this._bindingWhenSyntax.whenTargetNamed(e)},e.prototype.whenTargetIsDefault=function(){return this._bindingWhenSyntax.whenTargetIsDefault()},e.prototype.whenTargetTagged=function(e,t){return this._bindingWhenSyntax.whenTargetTagged(e,t)},e.prototype.whenInjectedInto=function(e){return this._bindingWhenSyntax.whenInjectedInto(e)},e.prototype.whenParentNamed=function(e){return this._bindingWhenSyntax.whenParentNamed(e)},e.prototype.whenParentTagged=function(e,t){return this._bindingWhenSyntax.whenParentTagged(e,t)},e.prototype.whenAnyAncestorIs=function(e){return this._bindingWhenSyntax.whenAnyAncestorIs(e)},e.prototype.whenNoAncestorIs=function(e){return this._bindingWhenSyntax.whenNoAncestorIs(e)},e.prototype.whenAnyAncestorNamed=function(e){return this._bindingWhenSyntax.whenAnyAncestorNamed(e)},e.prototype.whenAnyAncestorTagged=function(e,t){return this._bindingWhenSyntax.whenAnyAncestorTagged(e,t)},e.prototype.whenNoAncestorNamed=function(e){return this._bindingWhenSyntax.whenNoAncestorNamed(e)},e.prototype.whenNoAncestorTagged=function(e,t){return this._bindingWhenSyntax.whenNoAncestorTagged(e,t)},e.prototype.whenAnyAncestorMatches=function(e){return this._bindingWhenSyntax.whenAnyAncestorMatches(e)},e.prototype.whenNoAncestorMatches=function(e){return this._bindingWhenSyntax.whenNoAncestorMatches(e)},e.prototype.onActivation=function(e){return this._bindingOnSyntax.onActivation(e)},e.prototype.onDeactivation=function(e){return this._bindingOnSyntax.onDeactivation(e)},e}(),Ye=function(){function e(e){this._binding=e}return e.prototype.to=function(e){return this._binding.type=w,this._binding.implementationType=e,new Ge(this._binding)},e.prototype.toSelf=function(){if("function"!=typeof this._binding.serviceIdentifier)throw new Error("The toSelf function can only be applied when a constructor is used as service identifier");var e=this._binding.serviceIdentifier;return this.to(e)},e.prototype.toConstantValue=function(e){return this._binding.type=v,this._binding.cache=e,this._binding.dynamicValue=null,this._binding.implementationType=null,this._binding.scope=m,new qe(this._binding)},e.prototype.toDynamicValue=function(e){return this._binding.type=b,this._binding.cache=null,this._binding.dynamicValue=e,this._binding.implementationType=null,new Ge(this._binding)},e.prototype.toConstructor=function(e){return this._binding.type=y,this._binding.implementationType=e,this._binding.scope=m,new qe(this._binding)},e.prototype.toFactory=function(e){return this._binding.type=_,this._binding.factory=e,this._binding.scope=m,new qe(this._binding)},e.prototype.toFunction=function(e){if("function"!=typeof e)throw new Error("Value provided to function binding must be a function!");var t=this.toConstantValue(e);return this._binding.type=E,this._binding.scope=m,t},e.prototype.toAutoFactory=function(e){return this._binding.type=_,this._binding.factory=function(t){return function(){return t.container.get(e)}},this._binding.scope=m,new qe(this._binding)},e.prototype.toAutoNamedFactory=function(e){return this._binding.type=_,this._binding.factory=function(t){return function(r){return t.container.getNamed(e,r)}},new qe(this._binding)},e.prototype.toProvider=function(e){return this._binding.type=C,this._binding.provider=e,this._binding.scope=m,new qe(this._binding)},e.prototype.toService=function(e){this.toDynamicValue((function(t){return t.container.get(e)}))},e}(),$e=function(){function e(){}return e.of=function(t,r,n,i,s){var o=new e;return o.bindings=t,o.middleware=r,o.deactivations=i,o.activations=n,o.moduleActivationStore=s,o},e}();var Je=function(){function e(){this._map=new Map}return e.prototype.getMap=function(){return this._map},e.prototype.add=function(e,t){if(null==e)throw new Error("NULL argument");if(null==t)throw new Error("NULL argument");var r=this._map.get(e);void 0!==r?r.push(t):this._map.set(e,[t])},e.prototype.get=function(e){if(null==e)throw new Error("NULL argument");var t=this._map.get(e);if(void 0!==t)return t;throw new Error("Key Not Found")},e.prototype.remove=function(e){if(null==e)throw new Error("NULL argument");if(!this._map.delete(e))throw new Error("Key Not Found")},e.prototype.removeIntersection=function(e){var t=this;this.traverse((function(r,n){var i=e.hasKey(r)?e.get(r):void 0;if(void 0!==i){var s=n.filter((function(e){return!i.some((function(t){return e===t}))}));t._setValue(r,s)}}))},e.prototype.removeByCondition=function(e){var t=this,r=[];return this._map.forEach((function(n,i){for(var s=[],o=0,a=n;o<a.length;o++){var c=a[o];e(c)?r.push(c):s.push(c)}t._setValue(i,s)})),r},e.prototype.hasKey=function(e){if(null==e)throw new Error("NULL argument");return this._map.has(e)},e.prototype.clone=function(){var t=new e;return this._map.forEach((function(e,r){e.forEach((function(e){return t.add(r,"object"==typeof(n=e)&&null!==n&&"clone"in n&&"function"==typeof n.clone?e.clone():e);var n}))})),t},e.prototype.traverse=function(e){this._map.forEach((function(t,r){e(r,t)}))},e.prototype._setValue=function(e,t){t.length>0?this._map.set(e,t):this._map.delete(e)},e}(),Qe=function(){function e(){this._map=new Map}return e.prototype.remove=function(e){if(this._map.has(e)){var t=this._map.get(e);return this._map.delete(e),t}return this._getEmptyHandlersStore()},e.prototype.addDeactivation=function(e,t,r){this._getModuleActivationHandlers(e).onDeactivations.add(t,r)},e.prototype.addActivation=function(e,t,r){this._getModuleActivationHandlers(e).onActivations.add(t,r)},e.prototype.clone=function(){var t=new e;return this._map.forEach((function(e,r){t._map.set(r,{onActivations:e.onActivations.clone(),onDeactivations:e.onDeactivations.clone()})})),t},e.prototype._getModuleActivationHandlers=function(e){var t=this._map.get(e);return void 0===t&&(t=this._getEmptyHandlersStore(),this._map.set(e,t)),t},e.prototype._getEmptyHandlersStore=function(){return{onActivations:new Je,onDeactivations:new Je}},e}(),Ke=function(){return Ke=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},Ke.apply(this,arguments)},Ze=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},Xe=function(e,t){var r,n,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,a])}}},et=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))},tt=function(){function e(e){var t=e||{};if("object"!=typeof t)throw new Error("Invalid Container constructor argument. Container options must be an object.");if(void 0===t.defaultScope)t.defaultScope=g;else if(t.defaultScope!==m&&t.defaultScope!==g&&t.defaultScope!==f)throw new Error('Invalid Container option. Default scope must be a string ("singleton" or "transient").');if(void 0===t.autoBindInjectable)t.autoBindInjectable=!1;else if("boolean"!=typeof t.autoBindInjectable)throw new Error("Invalid Container option. Auto bind injectable must be a boolean");if(void 0===t.skipBaseClassChecks)t.skipBaseClassChecks=!1;else if("boolean"!=typeof t.skipBaseClassChecks)throw new Error("Invalid Container option. Skip base check must be a boolean");this.options={autoBindInjectable:t.autoBindInjectable,defaultScope:t.defaultScope,skipBaseClassChecks:t.skipBaseClassChecks},this.id=D(),this._bindingDictionary=new Je,this._snapshots=[],this._middleware=null,this._activations=new Je,this._deactivations=new Je,this.parent=null,this._metadataReader=new N,this._moduleActivationStore=new Qe}return e.merge=function(t,r){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];var s=new e,o=et([t,r],n,!0).map((function(e){return ne(e)})),a=ne(s);function c(e,t){e.traverse((function(e,r){r.forEach((function(e){t.add(e.serviceIdentifier,e.clone())}))}))}return o.forEach((function(e){c(e,a)})),s},e.prototype.load=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var r=this._getContainerModuleHelpersFactory(),n=0,i=e;n<i.length;n++){var s=i[n],o=r(s.id);s.registry(o.bindFunction,o.unbindFunction,o.isboundFunction,o.rebindFunction,o.unbindAsyncFunction,o.onActivationFunction,o.onDeactivationFunction)}},e.prototype.loadAsync=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ze(this,void 0,void 0,(function(){var t,r,n,i,s;return Xe(this,(function(o){switch(o.label){case 0:t=this._getContainerModuleHelpersFactory(),r=0,n=e,o.label=1;case 1:return r<n.length?(i=n[r],s=t(i.id),[4,i.registry(s.bindFunction,s.unbindFunction,s.isboundFunction,s.rebindFunction,s.unbindAsyncFunction,s.onActivationFunction,s.onDeactivationFunction)]):[3,4];case 2:o.sent(),o.label=3;case 3:return r++,[3,1];case 4:return[2]}}))}))},e.prototype.unload=function(){for(var e=this,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];t.forEach((function(t){var r=e._removeModuleBindings(t.id);e._deactivateSingletons(r),e._removeModuleHandlers(t.id)}))},e.prototype.unloadAsync=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ze(this,void 0,void 0,(function(){var t,r,n,i;return Xe(this,(function(s){switch(s.label){case 0:t=0,r=e,s.label=1;case 1:return t<r.length?(n=r[t],i=this._removeModuleBindings(n.id),[4,this._deactivateSingletonsAsync(i)]):[3,4];case 2:s.sent(),this._removeModuleHandlers(n.id),s.label=3;case 3:return t++,[3,1];case 4:return[2]}}))}))},e.prototype.bind=function(e){var t=this.options.defaultScope||g,r=new I(e,t);return this._bindingDictionary.add(e,r),new Ye(r)},e.prototype.rebind=function(e){return this.unbind(e),this.bind(e)},e.prototype.rebindAsync=function(e){return Ze(this,void 0,void 0,(function(){return Xe(this,(function(t){switch(t.label){case 0:return[4,this.unbindAsync(e)];case 1:return t.sent(),[2,this.bind(e)]}}))}))},e.prototype.unbind=function(e){if(this._bindingDictionary.hasKey(e)){var t=this._bindingDictionary.get(e);this._deactivateSingletons(t)}this._removeServiceFromDictionary(e)},e.prototype.unbindAsync=function(e){return Ze(this,void 0,void 0,(function(){var t;return Xe(this,(function(r){switch(r.label){case 0:return this._bindingDictionary.hasKey(e)?(t=this._bindingDictionary.get(e),[4,this._deactivateSingletonsAsync(t)]):[3,2];case 1:r.sent(),r.label=2;case 2:return this._removeServiceFromDictionary(e),[2]}}))}))},e.prototype.unbindAll=function(){var e=this;this._bindingDictionary.traverse((function(t,r){e._deactivateSingletons(r)})),this._bindingDictionary=new Je},e.prototype.unbindAllAsync=function(){return Ze(this,void 0,void 0,(function(){var e,t=this;return Xe(this,(function(r){switch(r.label){case 0:return e=[],this._bindingDictionary.traverse((function(r,n){e.push(t._deactivateSingletonsAsync(n))})),[4,Promise.all(e)];case 1:return r.sent(),this._bindingDictionary=new Je,[2]}}))}))},e.prototype.onActivation=function(e,t){this._activations.add(e,t)},e.prototype.onDeactivation=function(e,t){this._deactivations.add(e,t)},e.prototype.isBound=function(e){var t=this._bindingDictionary.hasKey(e);return!t&&this.parent&&(t=this.parent.isBound(e)),t},e.prototype.isCurrentBound=function(e){return this._bindingDictionary.hasKey(e)},e.prototype.isBoundNamed=function(e,t){return this.isBoundTagged(e,"named",t)},e.prototype.isBoundTagged=function(e,t,r){var n=!1;if(this._bindingDictionary.hasKey(e)){var i=this._bindingDictionary.get(e),s=function(e,t,r,n){var i=new $(R,"",t,new q(r,n)),s=new H(e);return new re(t,s,null,[],i)}(this,e,t,r);n=i.some((function(e){return e.constraint(s)}))}return!n&&this.parent&&(n=this.parent.isBoundTagged(e,t,r)),n},e.prototype.snapshot=function(){this._snapshots.push($e.of(this._bindingDictionary.clone(),this._middleware,this._activations.clone(),this._deactivations.clone(),this._moduleActivationStore.clone()))},e.prototype.restore=function(){var e=this._snapshots.pop();if(void 0===e)throw new Error("No snapshot available to restore.");this._bindingDictionary=e.bindings,this._activations=e.activations,this._deactivations=e.deactivations,this._middleware=e.middleware,this._moduleActivationStore=e.moduleActivationStore},e.prototype.createChild=function(t){var r=new e(t||this.options);return r.parent=this,r},e.prototype.applyMiddleware=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=this._middleware?this._middleware:this._planAndResolve();this._middleware=e.reduce((function(e,t){return t(e)}),r)},e.prototype.applyCustomMetadataReader=function(e){this._metadataReader=e},e.prototype.get=function(e){var t=this._getNotAllArgs(e,!1);return this._getButThrowIfAsync(t)},e.prototype.getAsync=function(e){return Ze(this,void 0,void 0,(function(){var t;return Xe(this,(function(r){return t=this._getNotAllArgs(e,!1),[2,this._get(t)]}))}))},e.prototype.getTagged=function(e,t,r){var n=this._getNotAllArgs(e,!1,t,r);return this._getButThrowIfAsync(n)},e.prototype.getTaggedAsync=function(e,t,r){return Ze(this,void 0,void 0,(function(){var n;return Xe(this,(function(i){return n=this._getNotAllArgs(e,!1,t,r),[2,this._get(n)]}))}))},e.prototype.getNamed=function(e,t){return this.getTagged(e,"named",t)},e.prototype.getNamedAsync=function(e,t){return this.getTaggedAsync(e,"named",t)},e.prototype.getAll=function(e){var t=this._getAllArgs(e);return this._getButThrowIfAsync(t)},e.prototype.getAllAsync=function(e){var t=this._getAllArgs(e);return this._getAll(t)},e.prototype.getAllTagged=function(e,t,r){var n=this._getNotAllArgs(e,!0,t,r);return this._getButThrowIfAsync(n)},e.prototype.getAllTaggedAsync=function(e,t,r){var n=this._getNotAllArgs(e,!0,t,r);return this._getAll(n)},e.prototype.getAllNamed=function(e,t){return this.getAllTagged(e,"named",t)},e.prototype.getAllNamedAsync=function(e,t){return this.getAllTaggedAsync(e,"named",t)},e.prototype.resolve=function(e){var t=this.isBound(e);t||this.bind(e).toSelf();var r=this.get(e);return t||this.unbind(e),r},e.prototype._preDestroy=function(e,t){var r,n;if(Reflect.hasMetadata("pre_destroy",e))return null===(n=(r=t)[Reflect.getMetadata("pre_destroy",e).value])||void 0===n?void 0:n.call(r)},e.prototype._removeModuleHandlers=function(e){var t=this._moduleActivationStore.remove(e);this._activations.removeIntersection(t.onActivations),this._deactivations.removeIntersection(t.onDeactivations)},e.prototype._removeModuleBindings=function(e){return this._bindingDictionary.removeByCondition((function(t){return t.moduleId===e}))},e.prototype._deactivate=function(e,t){var r=this,n=Object.getPrototypeOf(t).constructor;try{if(this._deactivations.hasKey(e.serviceIdentifier)){var i=this._deactivateContainer(t,this._deactivations.get(e.serviceIdentifier).values());if(ce(i))return this._handleDeactivationError(i.then((function(){return r._propagateContainerDeactivationThenBindingAndPreDestroyAsync(e,t,n)})),n)}var s=this._propagateContainerDeactivationThenBindingAndPreDestroy(e,t,n);if(ce(s))return this._handleDeactivationError(s,n)}catch(e){if(e instanceof Error)throw new Error(M(n.name,e.message))}},e.prototype._handleDeactivationError=function(e,t){return Ze(this,void 0,void 0,(function(){var r;return Xe(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,e];case 1:return n.sent(),[3,3];case 2:if((r=n.sent())instanceof Error)throw new Error(M(t.name,r.message));return[3,3];case 3:return[2]}}))}))},e.prototype._deactivateContainer=function(e,t){for(var r=this,n=t.next();n.value;){var i=n.value(e);if(ce(i))return i.then((function(){return r._deactivateContainerAsync(e,t)}));n=t.next()}},e.prototype._deactivateContainerAsync=function(e,t){return Ze(this,void 0,void 0,(function(){var r;return Xe(this,(function(n){switch(n.label){case 0:r=t.next(),n.label=1;case 1:return r.value?[4,r.value(e)]:[3,3];case 2:return n.sent(),r=t.next(),[3,1];case 3:return[2]}}))}))},e.prototype._getContainerModuleHelpersFactory=function(){var e=this,t=function(e,t){e._binding.moduleId=t},r=function(r){return function(n){var i=e.rebind(n);return t(i,r),i}},n=function(t){return function(r,n){e._moduleActivationStore.addActivation(t,r,n),e.onActivation(r,n)}},i=function(t){return function(r,n){e._moduleActivationStore.addDeactivation(t,r,n),e.onDeactivation(r,n)}};return function(s){return{bindFunction:(o=s,function(r){var n=e.bind(r);return t(n,o),n}),isboundFunction:function(t){return e.isBound(t)},onActivationFunction:n(s),onDeactivationFunction:i(s),rebindFunction:r(s),unbindFunction:function(t){return e.unbind(t)},unbindAsyncFunction:function(t){return e.unbindAsync(t)}};var o}},e.prototype._getAll=function(e){return Promise.all(this._get(e))},e.prototype._get=function(e){var t=Ke(Ke({},e),{contextInterceptor:function(e){return e},targetType:R});if(this._middleware){var r=this._middleware(t);if(null==r)throw new Error("Invalid return type in middleware. Middleware must return!");return r}return this._planAndResolve()(t)},e.prototype._getButThrowIfAsync=function(e){var t=this._get(e);if(de(t))throw new Error("You are attempting to construct '"+e.serviceIdentifier+"' in a synchronous way\n but it has asynchronous dependencies.");return t},e.prototype._getAllArgs=function(e){return{avoidConstraints:!0,isMultiInject:!0,serviceIdentifier:e}},e.prototype._getNotAllArgs=function(e,t,r,n){return{avoidConstraints:!1,isMultiInject:t,serviceIdentifier:e,key:r,value:n}},e.prototype._planAndResolve=function(){var e=this;return function(t){var r=ae(e._metadataReader,e,t.isMultiInject,t.targetType,t.serviceIdentifier,t.key,t.value,t.avoidConstraints);return function(e){return Re(e.plan.rootRequest.requestScope)(e.plan.rootRequest)}(r=t.contextInterceptor(r))}},e.prototype._deactivateIfSingleton=function(e){var t=this;if(e.activated)return ce(e.cache)?e.cache.then((function(r){return t._deactivate(e,r)})):this._deactivate(e,e.cache)},e.prototype._deactivateSingletons=function(e){for(var t=0,r=e;t<r.length;t++){var n=r[t];if(ce(this._deactivateIfSingleton(n)))throw new Error("Attempting to unbind dependency with asynchronous destruction (@preDestroy or onDeactivation)")}},e.prototype._deactivateSingletonsAsync=function(e){return Ze(this,void 0,void 0,(function(){var t=this;return Xe(this,(function(r){switch(r.label){case 0:return[4,Promise.all(e.map((function(e){return t._deactivateIfSingleton(e)})))];case 1:return r.sent(),[2]}}))}))},e.prototype._propagateContainerDeactivationThenBindingAndPreDestroy=function(e,t,r){return this.parent?this._deactivate.bind(this.parent)(e,t):this._bindingDeactivationAndPreDestroy(e,t,r)},e.prototype._propagateContainerDeactivationThenBindingAndPreDestroyAsync=function(e,t,r){return Ze(this,void 0,void 0,(function(){return Xe(this,(function(n){switch(n.label){case 0:return this.parent?[4,this._deactivate.bind(this.parent)(e,t)]:[3,2];case 1:return n.sent(),[3,4];case 2:return[4,this._bindingDeactivationAndPreDestroyAsync(e,t,r)];case 3:n.sent(),n.label=4;case 4:return[2]}}))}))},e.prototype._removeServiceFromDictionary=function(e){try{this._bindingDictionary.remove(e)}catch(t){throw new Error("Could not unbind serviceIdentifier: "+j(e))}},e.prototype._bindingDeactivationAndPreDestroy=function(e,t,r){var n=this;if("function"==typeof e.onDeactivation){var i=e.onDeactivation(t);if(ce(i))return i.then((function(){return n._preDestroy(r,t)}))}return this._preDestroy(r,t)},e.prototype._bindingDeactivationAndPreDestroyAsync=function(e,t,r){return Ze(this,void 0,void 0,(function(){return Xe(this,(function(n){switch(n.label){case 0:return"function"!=typeof e.onDeactivation?[3,2]:[4,e.onDeactivation(t)];case 1:n.sent(),n.label=2;case 2:return[4,this._preDestroy(r,t)];case 3:return n.sent(),[2]}}))}))},e}();function rt(e,t,r,n){!function(e){if(void 0!==e)throw new Error(O)}(t),it("inversify:tagged",e,r.toString(),n)}function nt(e){var t=[];if(Array.isArray(e)){var r=function(e){for(var t=new Set,r=0,n=e;r<n.length;r++){var i=n[r];if(t.has(i))return i;t.add(i)}}((t=e).map((function(e){return e.key})));if(void 0!==r)throw new Error("Metadata key was used more than once in a parameter: "+r.toString())}else t=[e];return t}function it(e,t,r,n){var i=nt(n),s={};Reflect.hasOwnMetadata(e,t)&&(s=Reflect.getMetadata(e,t));var o=s[r];if(void 0===o)o=[];else for(var a=function(e){if(i.some((function(t){return t.key===e.key})))throw new Error("Metadata key was used more than once in a parameter: "+e.key.toString())},c=0,d=o;c<d.length;c++){a(d[c])}o.push.apply(o,i),s[r]=o,Reflect.defineMetadata(e,s,t)}function st(e){return function(t,r,n){"number"==typeof n?rt(t,r,n,e):function(e,t,r){if(void 0!==e.prototype)throw new Error(O);it("inversify:tagged_props",e.constructor,t,r)}(t,r,e)}}function ot(){return function(e){if(Reflect.hasOwnMetadata("inversify:paramtypes",e))throw new Error("Cannot apply @injectable decorator multiple times.");var t=Reflect.getMetadata("design:paramtypes",e)||[];return Reflect.defineMetadata("inversify:paramtypes",t,e),e}}var at,ct=(at="inject",function(e){return function(t,r,n){if(void 0===e){var i="function"==typeof t?t.name:t.constructor.name;throw new Error("@inject called with undefined this could mean that the class "+i+" has a circular dependency problem. You can use a LazyServiceIdentifier to overcome this limitation.")}return st(new q(at,e))(t,r,n)}});const dt=3,ut=4,lt=6,pt=7;var ht;!function(e){e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.OK=200]="OK",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.TooManyRequests=429]="TooManyRequests",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout"}(ht||(ht={}));const ft=String("3.60.0-lk-7102-join-credentials.1");var mt;const gt={customerId:String("89c41ecf3b3f46fef5dfa9f96842014c21d4901c"),sdk_url:String("https://effectssdk.ai/sdk/audio/"),api_url:String("https://effectssdk.ai/sdk/session/"),version:"2.3.5"},vt={customerId:String("89c41ecf3b3f46fef5dfa9f96842014c21d4901c"),sdk_url:String("https://effectssdk.ai/sdk/"),api_url:String("https://effectssdk.ai/sdk/session/")},yt=()=>{};let bt=class{constructor(e){var t,r,n,i,s,o,a,d,u,l;mt.set(this,void 0),c(this,mt,{denoiser:null!==(t=e.denoiser)&&void 0!==t?t:"rnnoise",asdk:Object.assign(Object.assign({},gt),e.asdk),signalingServerUrl:null!==(r=e.signalingServerUrl)&&void 0!==r?r:String("https://signaling-api.livedigital.space/v1"),analyticsApiUrl:null!==(n=e.analyticsApiUrl)&&void 0!==n?n:String("https://moodhood-analytics.livedigital.space/v1"),logLevel:null!==(i=e.logLevel)&&void 0!==i?i:dt,sendAnalytics:null!==(s=e.sendAnalytics)&&void 0!==s&&s,onLogMessage:null!==(o=e.onLogMessage)&&void 0!==o?o:yt,onIssues:null!==(a=e.onIssues)&&void 0!==a?a:yt,disableWid:null!==(d=e.disableWid)&&void 0!==d&&d,effectsSDKParams:Object.assign(Object.assign({},vt),e.effectsSDKParams),onNetworkScoresUpdated:null!==(u=e.onNetworkScoresUpdated)&&void 0!==u?u:yt,getStatsInterval:null!==(l=e.getStatsInterval)&&void 0!==l?l:5e3,staticFilesPath:e.staticFilesPath||window.location.origin},"f")}get(e){return a(this,mt,"f")[e]}set(e,t){a(this,mt,"f")[e]=t}};mt=new WeakMap,bt=n([ot(),s("design:paramtypes",[Object])],bt);var _t,Et=bt,wt={exports:{}},St="object"==typeof Reflect?Reflect:null,Ct=St&&"function"==typeof St.apply?St.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};_t=St&&"function"==typeof St.ownKeys?St.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var Pt=Number.isNaN||function(e){return e!=e};function Tt(){Tt.init.call(this)}wt.exports=Tt,wt.exports.once=function(e,t){return new Promise((function(r,n){function i(r){e.removeListener(t,s),n(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}xt(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&xt(e,"error",t,r)}(e,i,{once:!0})}))},Tt.EventEmitter=Tt,Tt.prototype._events=void 0,Tt.prototype._eventsCount=0,Tt.prototype._maxListeners=void 0;var Rt=10;function kt(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function Dt(e){return void 0===e._maxListeners?Tt.defaultMaxListeners:e._maxListeners}function It(e,t,r,n){var i,s,o,a;if(kt(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),(i=Dt(e))>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,console&&console.warn&&console.warn(a)}return e}function At(){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 Ot(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=At.bind(n);return i.listener=r,n.wrapFn=i,i}function Mt(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(i):Lt(i,i.length)}function Nt(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function Lt(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function xt(e,t,r,n){if("function"==typeof e.on)n.once?e.once(t,r):e.on(t,r);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 i(s){n.once&&e.removeEventListener(t,i),r(s)}))}}Object.defineProperty(Tt,"defaultMaxListeners",{enumerable:!0,get:function(){return Rt},set:function(e){if("number"!=typeof e||e<0||Pt(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Rt=e}}),Tt.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},Tt.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||Pt(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},Tt.prototype.getMaxListeners=function(){return Dt(this)},Tt.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var n="error"===e,i=this._events;if(void 0!==i)n=n&&void 0===i.error;else if(!n)return!1;if(n){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[e];if(void 0===a)return!1;if("function"==typeof a)Ct(a,this,t);else{var c=a.length,d=Lt(a,c);for(r=0;r<c;++r)Ct(d[r],this,t)}return!0},Tt.prototype.addListener=function(e,t){return It(this,e,t,!1)},Tt.prototype.on=Tt.prototype.addListener,Tt.prototype.prependListener=function(e,t){return It(this,e,t,!0)},Tt.prototype.once=function(e,t){return kt(t),this.on(e,Ot(this,e,t)),this},Tt.prototype.prependOnceListener=function(e,t){return kt(t),this.prependListener(e,Ot(this,e,t)),this},Tt.prototype.removeListener=function(e,t){var r,n,i,s,o;if(kt(t),void 0===(n=this._events))return this;if(void 0===(r=n[e]))return this;if(r===t||r.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,i),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},Tt.prototype.off=Tt.prototype.removeListener,Tt.prototype.removeAllListeners=function(e){var t,r,n;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var i,s=Object.keys(r);for(n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[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},Tt.prototype.listeners=function(e){return Mt(this,e,!0)},Tt.prototype.rawListeners=function(e){return Mt(this,e,!1)},Tt.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Nt.call(e,t)},Tt.prototype.listenerCount=Nt,Tt.prototype.eventNames=function(){return this._eventsCount>0?_t(this._events):[]};class Ft extends wt.exports.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}emit(e,...t){return super.emit(e,...t)}safeEmit(e,...t){try{return super.emit(e,...t)}catch(t){try{super.emit("listenererror",e,t)}catch(e){}return!!super.listenerCount(e)}}on(e,t){return super.on(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.on(e,t),this}removeListener(e,t){return super.off(e,t),this}once(e,t){return super.once(e,t),this}prependListener(e,t){return super.prependListener(e,t),this}prependOnceListener(e,t){return super.prependOnceListener(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}}Error;const jt=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0}],Ut=({from:e,seen:t,to_:r,forceEnumerable:n})=>{const i=r||(Array.isArray(e)?[]:{});t.push(e);for(const[r,s]of Object.entries(e))"function"!=typeof s&&(s&&"object"==typeof s?t.includes(e[r])?i[r]="[Circular]":i[r]=Ut({from:e[r],seen:t.slice(),forceEnumerable:n}):i[r]=s);for(const{property:t,enumerable:r}of jt)"string"==typeof e[t]&&Object.defineProperty(i,t,{value:e[t],enumerable:!!n||r,configurable:!0,writable:!0});return i};var Vt=e=>"object"==typeof e&&null!==e?Ut({from:e,seen:[],forceEnumerable:!0}):"function"==typeof e?`[Function: ${e.name||"anonymous"}]`:e;class Bt extends Error{constructor(e,t){var r;if(t instanceof Bt)return super(t.message),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this.errorCode=t.errorCode,void(this.cause=t.cause);const n=Vt(t),i=null!==(r=(e=>{if("string"==typeof e)return e;if(e instanceof Error)return e.message;if(e&&"object"==typeof e&&"message"in e){const t=e.message;return"string"==typeof t?t:void 0}})(n))&&void 0!==r?r:"Operation failed";super(i),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this.errorCode=e,this.cause=Vt(n)}}var Wt,Ht,qt,zt;function Gt(){}function Yt(){Yt.init.call(this)}function $t(e){return void 0===e._maxListeners?Yt.defaultMaxListeners:e._maxListeners}function Jt(e,t,r){if(t)e.call(r);else for(var n=e.length,i=nr(e,n),s=0;s<n;++s)i[s].call(r)}function Qt(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,s=nr(e,i),o=0;o<i;++o)s[o].call(r,n)}function Kt(e,t,r,n,i){if(t)e.call(r,n,i);else for(var s=e.length,o=nr(e,s),a=0;a<s;++a)o[a].call(r,n,i)}function Zt(e,t,r,n,i,s){if(t)e.call(r,n,i,s);else for(var o=e.length,a=nr(e,o),c=0;c<o;++c)a[c].call(r,n,i,s)}function Xt(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,s=nr(e,i),o=0;o<i;++o)s[o].apply(r,n)}function er(e,t,r,n){var i,s,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]):(s=e._events=new Gt,e._eventsCount=0),o){if("function"==typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),!o.warned&&(i=$t(e))&&i>0&&o.length>i){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else o=s[t]=r,++e._eventsCount;return e}function tr(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}function rr(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function nr(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}Gt.prototype=Object.create(null),Yt.EventEmitter=Yt,Yt.usingDomains=!1,Yt.prototype.domain=void 0,Yt.prototype._events=void 0,Yt.prototype._maxListeners=void 0,Yt.defaultMaxListeners=10,Yt.init=function(){this.domain=null,Yt.usingDomains&&(void 0).active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Gt,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Yt.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},Yt.prototype.getMaxListeners=function(){return $t(this)},Yt.prototype.emit=function(e){var t,r,n,i,s,o,a,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=o[e]))return!1;var u="function"==typeof r;switch(n=arguments.length){case 1:Jt(r,u,this);break;case 2:Qt(r,u,this,arguments[1]);break;case 3:Kt(r,u,this,arguments[1],arguments[2]);break;case 4:Zt(r,u,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),s=1;s<n;s++)i[s-1]=arguments[s];Xt(r,u,this,i)}return!0},Yt.prototype.addListener=function(e,t){return er(this,e,t,!1)},Yt.prototype.on=Yt.prototype.addListener,Yt.prototype.prependListener=function(e,t){return er(this,e,t,!0)},Yt.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,tr(this,e,t)),this},Yt.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,tr(this,e,t)),this},Yt.prototype.removeListener=function(e,t){var r,n,i,s,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(n=this._events))return this;if(!(r=n[e]))return this;if(r===t||r.listener&&r.listener===t)0==--this._eventsCount?this._events=new Gt:(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new Gt,this;delete n[e]}else!function(e,t){for(var r=t,n=r+1,i=e.length;n<i;r+=1,n+=1)e[r]=e[n];e.pop()}(r,i);n.removeListener&&this.emit("removeListener",e,o||t)}return this},Yt.prototype.off=function(e,t){return this.removeListener(e,t)},Yt.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new Gt,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new Gt:delete r[e]),this;if(0===arguments.length){for(var n,i=Object.keys(r),s=0;s<i.length;++s)"removeListener"!==(n=i[s])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=new Gt,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},Yt.prototype.listeners=function(e){var t,r=this._events;return r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[]},Yt.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):rr.call(e,t)},Yt.prototype.listenerCount=rr,Yt.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class ir extends Yt{}!function(e){e.Issue="issue",e.NetworkScoresUpdated="network-scores-updated",e.StatsParsingFinished="stats-parsing-finished"}(Wt||(Wt={})),function(e){e.Network="network",e.CPU="cpu",e.Server="server",e.Stream="stream"}(Ht||(Ht={})),function(e){e.OutboundNetworkQuality="outbound-network-quality",e.InboundNetworkQuality="inbound-network-quality",e.OutboundNetworkMediaLatency="outbound-network-media-latency",e.InboundNetworkMediaLatency="inbound-network-media-latency",e.NetworkMediaSyncFailure="network-media-sync-failure",e.OutboundNetworkThroughput="outbound-network-throughput",e.InboundNetworkThroughput="inbound-network-throughput",e.EncoderCPUThrottling="encoder-cpu-throttling",e.DecoderCPUThrottling="decoder-cpu-throttling",e.ServerIssue="server-issue",e.UnknownVideoDecoderIssue="unknown-video-decoder",e.LowInboundMOS="low-inbound-mean-opinion-score",e.LowOutboundMOS="low-outbound-mean-opinion-score",e.FrozenVideoTrack="frozen-video-track",e.MissingVideoStreamData="missing-video-stream-data",e.MissingAudioStreamData="missing-audio-stream-data"}(qt||(qt={})),function(e){e[e.BAD=2.1]="BAD",e[e.POOR=2.6]="POOR",e[e.FAIR=3.1]="FAIR",e[e.GOOD=3.8]="GOOD",e[e.EXCELLENT=4.3]="EXCELLENT"}(zt||(zt={}));class sr extends Yt{static STATS_REPORT_READY_EVENT="stats-report-ready";static STATS_REPORTS_PARSED="stats-reports-parsed";isStopped=!1;reportTimer;getStatsInterval;compositeStatsParser;constructor(e){super(),this.compositeStatsParser=e.compositeStatsParser,this.getStatsInterval=e.getStatsInterval??1e4}get isRunning(){return!!this.reportTimer&&!this.isStopped}startReporting(){if(this.reportTimer)return;const e=()=>setTimeout((()=>{this.isStopped?this.reportTimer=void 0:this.parseReports().finally((()=>{this.reportTimer=e()}))}),this.getStatsInterval);this.isStopped=!1,this.reportTimer=e()}stopReporting(){this.isStopped=!0,this.reportTimer&&(clearTimeout(this.reportTimer),this.reportTimer=void 0)}async parseReports(){const e=Date.now(),t=await this.compositeStatsParser.parse(),r=Date.now()-e;this.emit(sr.STATS_REPORTS_PARSED,{timeTaken:r,reportItems:t}),t.forEach((e=>{this.emit(sr.STATS_REPORT_READY_EVENT,e)}))}}const or=()=>{const e=new Map;return t=>{const{taskId:r,delayMs:n,maxJitterMs:i,callback:s}=t,o=Math.ceil(Math.random()*(i||0)),a=e.get(r);a&&clearTimeout(a);const c=setTimeout((()=>{s(),e.delete(r)}),n+o);e.set(r,c)}};class ar{#e={};#t=or();calculate(e){const{connection:{id:t}}=e,{mos:r,stats:n}=this.calculateOutboundScore(e)||{},{mos:i,stats:s}=this.calculateInboundScore(e)||{};return this.#e[t]=e,this.#t({taskId:t,delayMs:35e3,callback:()=>delete this.#e[t]}),{outbound:r,inbound:i,connectionId:t,statsSamples:{inboundStatsSample:s,outboundStatsSample:n}}}calculateOutboundScore(e){const t=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!t.length)return;const r=this.#e[e.connection.id];if(!r)return;const n=[...r.remote?.audio.inbound||[],...r.remote?.video.inbound||[]],{packetsSent:i}=e.connection,s=r.connection.packetsSent,o=t.reduce(((e,t)=>{const r=n.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=1e3*c/t.length,u=i-s,l=o.packetsLost-o.lastPacketsLost,p=u&&l?Math.round(100*l/(u+l)):0;return{mos:this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:p}),stats:{avgJitter:d,rtt:a,packetsLoss:p}}}calculateInboundScore(e){const t=[...e.audio?.inbound,...e.video?.inbound];if(!t.length)return;const r=this.#e[e.connection.id];if(!r)return;const n=[...r.video?.inbound,...r.audio?.inbound],{packetsReceived:i}=e.connection,s=r.connection.packetsReceived,o=t.reduce(((e,t)=>{const r=n.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=1e3*c/t.length,u=i-s,l=o.packetsLost-o.lastPacketsLost,p=u&&l?Math.round(100*l/(u+l)):0;return{mos:this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:p}),stats:{avgJitter:d,rtt:a,packetsLoss:p}}}calculateMOS({avgJitter:e,rtt:t,packetsLoss:r}){const n=t+2*e+10;let i=n<160?93.2-n/40:93.2-(n-120)/10;i-=2.5*r;const s=1+.035*i+7e-6*i*(i-60)*(100-i);return Math.max(0,Math.min(5,s))}}class cr{#r=new Map;#n;#i;#t=or();constructor(e={}){this.#n=e.statsCleanupTtlMs??35e3,this.#i=e.maxParsedStatsStorageSize??5}detect(e,t){const r={...e,networkScores:{...t,statsSamples:t?.statsSamples||{}}},n=this.performDetection(r);return this.setLastProcessedStats(e.connection.id,r),this.performPrevStatsCleanup({connectionId:e.connection.id}),n}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:r}=e;this.#r.has(t)&&this.#t({taskId:t,delayMs:this.#n,callback:()=>{this.deleteLastProcessedStats(t),"function"==typeof r&&r()}})}setLastProcessedStats(e,t){if(!e||t.connection.id!==e)return;const r=this.#r.get(e)??[];r.push(t),r.length>this.#i&&r.shift(),this.#r.set(e,r)}getLastProcessedStats(e){const t=this.#r.get(e);return t?.[t.length-1]}getAllLastProcessedStats(e){return this.#r.get(e)??[]}deleteLastProcessedStats(e){this.#r.delete(e)}}class dr extends cr{#s;constructor(e={}){super(e),this.#s=e.availableOutgoingBitrateThreshold??1e5}performDetection(e){const t=[],{availableOutgoingBitrate:r}=e.connection;if(void 0===r)return t;const n=e.audio.outbound.reduce(((e,t)=>e+t.targetBitrate),0),i=e.video.outbound.reduce(((e,t)=>e+t.bitrate),0);if(!n&&!i)return t;const s={availableOutgoingBitrate:r,videoStreamsTotalBitrate:i,audioStreamsTotalTargetBitrate:n};return n>r||i>0&&r<this.#s?(t.push({statsSample:s,type:Ht.Network,reason:qt.OutboundNetworkThroughput}),t):t}}class ur extends cr{#o;#a;#c;#d;constructor(e={}){super(e),this.#o=e.highPacketLossThresholdPct??5,this.#a=e.highJitterThreshold??200,this.#c=e.highJitterBufferDelayThresholdMs??500,this.#d=e.highRttThresholdMs??250}performDetection(e){return this.processData(e)}processData(e){const t=[],r=[...e.audio?.inbound,...e.video?.inbound];if(!r.length)return t;const n=this.getLastProcessedStats(e.connection.id);if(!n)return t;const i=[...n.video?.inbound,...n.audio?.inbound],{packetsReceived:s}=e.connection,o=n.connection.packetsReceived,a=r.reduce(((e,t)=>{const r=i.find((e=>e.ssrc===t.ssrc)),n=r?.jitterBufferDelay||0,s=r?.jitterBufferEmittedCount||0,o=t.jitterBufferDelay-n,a=t.jitterBufferEmittedCount-s,c=o&&a?1e3*o/a:0;return{sumJitter:e.sumJitter+t.jitter,sumJitterBufferDelayMs:e.sumJitterBufferDelayMs+c,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,sumJitterBufferDelayMs:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:d,sumJitterBufferDelayMs:u}=a,l=1e3*d/r.length,p=u/r.length,h=s-o,f=a.packetsLost-a.lastPacketsLost,m=h&&f?Math.round(100*f/(h+f)):0,g=m>this.#o,v=l>=this.#a,y=c>=this.#d,b=p>this.#c,_=y&&!v&&!g,E=g&&v,w=v&&b,S={rtt:c,packetLossPct:m,avgJitter:l,avgJitterBufferDelay:p};return(v||g)&&t.push({statsSample:S,type:Ht.Network,reason:qt.InboundNetworkQuality,iceCandidate:e.connection.local.id}),_&&t.push({statsSample:S,type:Ht.Server,reason:qt.ServerIssue,iceCandidate:e.connection.remote.id}),E&&t.push({statsSample:S,type:Ht.Network,reason:qt.InboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),w&&t.push({statsSample:S,type:Ht.Network,reason:qt.NetworkMediaSyncFailure,iceCandidate:e.connection.local.id}),t}}class lr extends cr{#u;constructor(e={}){super(e),this.#u=e.correctedSamplesThresholdPct??5}performDetection(e){return this.processData(e)}processData(e){const t=e.audio.inbound,r=[],n=this.getLastProcessedStats(e.connection.id)?.audio.inbound;return n?(t.forEach((e=>{const t=n.find((t=>t.ssrc===e.ssrc));if(!t)return;const i=e.track.insertedSamplesForDeceleration+e.track.removedSamplesForAcceleration,s=t.track.insertedSamplesForDeceleration+t.track.removedSamplesForAcceleration;if(i===s)return;const o=e.track.totalSamplesReceived-t.track.totalSamplesReceived;if(0===o)return;const a=i-s,c=Math.round(100*a/o),d={correctedSamplesPct:c};c>this.#u&&r.push({statsSample:d,type:Ht.Network,reason:qt.NetworkMediaSyncFailure,ssrc:e.ssrc})})),r):r}}class pr extends cr{#o;#a;constructor(e={}){super(e),this.#o=e.highPacketLossThresholdPct??5,this.#a=e.highJitterThreshold??200}performDetection(e){return this.processData(e)}processData(e){const t=[],r=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!r.length)return t;const n=this.getLastProcessedStats(e.connection.id);if(!n)return t;const i=[...n.remote?.audio.inbound||[],...n.remote?.video.inbound||[]],{packetsSent:s}=e.connection,o=n.connection.packetsSent,a=r.reduce(((e,t)=>{const r=i.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:d}=a,u=1e3*d/r.length,l=s-o,p=a.packetsLost-a.lastPacketsLost,h=l&&p?Math.round(100*p/(l+p)):0,f=h>this.#o,m=u>=this.#a,g=m||f,v={rtt:c,avgJitter:u,packetLossPct:h};return f&&m&&t.push({statsSample:v,type:Ht.Network,reason:qt.OutboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),g&&t.push({statsSample:v,type:Ht.Network,reason:qt.OutboundNetworkQuality,iceCandidate:e.connection.local.id}),t}}class hr extends cr{performDetection(e){return this.processData(e)}processData(e){const t=e.video.outbound.filter((e=>"none"!==e.qualityLimitationReason)),r=[],n=this.getLastProcessedStats(e.connection.id)?.video.outbound;return n?(t.forEach((e=>{const t=n.find((t=>t.ssrc===e.ssrc));if(!t)return;const i={qualityLimitationReason:e.qualityLimitationReason};e.framesSent>t.framesSent||("cpu"===e.qualityLimitationReason&&r.push({statsSample:i,type:Ht.CPU,reason:qt.EncoderCPUThrottling,ssrc:e.ssrc}),"bandwidth"===e.qualityLimitationReason&&r.push({statsSample:i,type:Ht.Network,reason:qt.OutboundNetworkThroughput,ssrc:e.ssrc}))})),r):r}}class fr extends cr{UNKNOWN_DECODER="unknown";#l={};performDetection(e){return this.processData(e)}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:r}=e;super.performPrevStatsCleanup({...e,cleanupCallback:()=>{delete this.#l[t],"function"==typeof r&&r()}})}processData(e){const t=[],{id:r}=e.connection,n=this.getLastProcessedStats(r)?.video.inbound;return e.video.inbound.forEach((e=>{const{decoderImplementation:i,ssrc:s}=e,o=n?.find((e=>e.ssrc===s));if(o)if(i===this.UNKNOWN_DECODER){if(!this.hadLastDecoderWithIssue(r,s)){this.setLastDecoderWithIssue(r,s,this.UNKNOWN_DECODER);const n={mimeType:e.mimeType,decoderImplementation:i};t.push({ssrc:s,statsSample:n,type:Ht.Stream,reason:qt.UnknownVideoDecoderIssue,trackIdentifier:e.track.trackIdentifier})}}else this.setLastDecoderWithIssue(r,s,void 0)})),t}setLastDecoderWithIssue(e,t,r){const n=this.#l[e]??{};void 0===r?delete n[t]:n[t]=r,this.#l[e]=n}hadLastDecoderWithIssue(e,t){const r=this.#l[e];return(r&&r[t])===this.UNKNOWN_DECODER}}const mr=e=>e.reduce(((e,t)=>e+t),0)/e.length,gr=(e,t,r=30)=>{const n=[];for(let r=1;r<t.length;r+=1){const i=t[r]?.video?.inbound.find((t=>t.ssrc===e));if(!i)continue;const s=t[r-1]?.video?.inbound?.find((t=>t.ssrc===e));if(!i||!s)continue;const o=i.timestamp-s.timestamp,a=i.framesDecoded-s.framesDecoded;if(a>0){const e=o/a;n.push(e)}}return!(n.length<=1)&&(e=>{const t=((e,t)=>t.reduce(((t,r)=>t+(r-e)**2),0)/t.length)(mr(e),e);return Math.sqrt(t)})(n)>r},vr=(e,t)=>{for(let r=1;r<t.length;r+=1){const n=t[r].video.inbound.find((t=>t.ssrc===e));if(!n)continue;const i=t[r-1].video.inbound.find((t=>t.ssrc===e)),s=n.frameWidth!==i?.frameWidth,o=n.frameHeight!==i?.frameHeight;if(s||o)return!0}return!1};class yr extends cr{#p;#h;#f;constructor(e={}){super(),this.#p=e.avgFreezeDurationThresholdMs??1e3,this.#h=e.frozenDurationThresholdPct??30,this.#f=e.minMosQuality??zt.BAD}performDetection(e){const t=e.networkScores.inbound;return void 0!==t&&t<=this.#f?[]:this.processData(e)}processData(e){const t=[],r=this.getAllLastProcessedStats(e.connection.id);if(0===r.length)return[];const n=e.video.inbound.map((t=>{const n=r[r.length-1].video.inbound.find((e=>e.ssrc===t.ssrc));if(!n)return;if(vr(t.ssrc,[r[r.length-1],e]))return;if(gr(t.ssrc,r))return;const i=t.freezeCount-(n.freezeCount??0),s=1e3*(t.totalFreezesDuration-(n.totalFreezesDuration??0)),o=i>0?s/i:0,a=s/(t.timestamp-n.timestamp)*100;return a>this.#h||o>this.#p?{ssrc:t.ssrc,avgFreezeDurationMs:o,frozenDurationPct:a}:void 0})).filter((e=>void 0!==e));return n.length>0&&(t.push({type:Ht.Stream,reason:qt.FrozenVideoTrack,statsSample:{ssrcs:n.map((e=>e.ssrc))}}),this.deleteLastProcessedStats(e.connection.id)),t}}class br extends cr{#m;#g;#f;constructor(e={}){super(e),this.#m=e.volatilityThreshold??8,this.#g=e.affectedStreamsPercentThreshold??30,this.#f=e.minMosQuality??zt.BAD}performDetection(e){return[...this.getAllLastProcessedStats(e.connection.id),e].find((e=>void 0!==e.networkScores.inbound&&e.networkScores.inbound<=this.#f))?[]:this.processData(e)}processData(e){const t=[],r=[...this.getAllLastProcessedStats(e.connection.id),e],n=e.video.inbound.map((e=>{if(r.length<5)return;if(vr(e.ssrc,r))return;const t=[];for(let n=0;n<r.length-1;n+=1){const i=r[n].video.inbound.find((t=>t.ssrc===e.ssrc));void 0!==i?.framesPerSecond&&t.push(i.framesPerSecond)}if(t.length<5)return;if(gr(e.ssrc,r))return;const n=(e=>{if(0===e.length)throw new Error("Cannot calculate volatility for empty array");const t=mr(e);return 0===t?0:e.reduce(((e,r)=>e+Math.abs(r-t)),0)/e.length*100/t})(t);return n>this.#m?{ssrc:e.ssrc,allFps:t,volatility:n}:void 0})).filter((e=>Boolean(e)));if(0===n.length)return t;const i=n.length/(e.video.inbound.length/100);return i>this.#g&&(t.push({type:Ht.CPU,reason:qt.DecoderCPUThrottling,statsSample:{affectedStreamsPercent:i,throtthedStreams:n}}),this.deleteLastProcessedStats(e.connection.id)),t}}class _r extends cr{#v=new Map;#y;#b;constructor(e={}){super(),this.#y=e.timeoutMs??15e3,this.#b=e.steps??3}performDetection(e){return this.processData(e)}processData(e){const t=[],r=[...this.getAllLastProcessedStats(e.connection.id),e];if(r.length<this.#b)return t;const n=r.slice(-this.#b),i=n.map((e=>e.video.inbound)),s=n.map((e=>e.audio.inbound));return t.push(...this.detectMissingData(s,Ht.Stream,qt.MissingAudioStreamData)),t.push(...this.detectMissingData(i,Ht.Stream,qt.MissingVideoStreamData)),new Set(this.#v.keys()).forEach((e=>{const t=this.#v.get(e);t&&Date.now()-t>this.#y&&this.removeMarkedIssue(e)})),t}detectMissingData(e,t,r){const n=[],i=e.pop(),s=_r.mapStatsByTrackId(e);return i.forEach((e=>{const i=e.track.trackIdentifier,o=s.get(i);if(!Array.isArray(o)||0===o.length)return;if(e.track.detached||e.track.ended)return;if(!_r.isAllBytesReceivedDidntChange(e.bytesReceived,o))return void this.removeMarkedIssue(i);if(!this.markIssue(i))return;const a={bytesReceived:e.bytesReceived};n.push({type:t,reason:r,statsSample:a,trackIdentifier:i})})),n}static mapStatsByTrackId(e){const t=new Map;return e.forEach((e=>{e.forEach((e=>{const r=t.get(e.track.trackIdentifier)||[];r.push(e),t.set(e.track.trackIdentifier,r)}))})),t}static isAllBytesReceivedDidntChange(e,t){for(let r=0;r<t.length;r+=1)if(t[r].bytesReceived!==e)return!1;return!0}markIssue(e){const t=Date.now(),r=this.#v.get(e);return(!r||t-r>this.#y)&&(this.#v.set(e,t),!0)}removeMarkedIssue(e){this.#v.delete(e)}}const Er=e=>"closed"===e.iceConnectionState||"closed"===e.connectionState,wr=(e,t,r)=>8*((e,t,r)=>{if(!t)return 0;const n=e[r],i=t[r];if(null==n||null==i)return 0;const s=Math.floor(e.timestamp)-Math.floor(t.timestamp);return 0===s?0:(Number(n)-Number(i))/s*1e3})(e,t,r);class Sr{connections=[];statsParser;constructor(e){this.statsParser=e.statsParser}listConnections(){return[...this.connections]}addPeerConnection(e){this.connections.push({id:e.id??String(Date.now()+Math.random().toString(32)),pc:e.pc})}removePeerConnection(e){const t=this.connections.findIndex((({pc:t})=>t===e.pc));t>=0&&this.removeConnectionsByIndexes([t])}async parse(){const e=[],t=this.connections.map((async(t,r)=>{if(!Er(t.pc))return this.statsParser.parse(t);e.unshift(r)}));return e.length&&this.removeConnectionsByIndexes(e),(await Promise.all(t)).filter((e=>void 0!==e))}removeConnectionsByIndexes(e){e.forEach((e=>{this.connections.splice(e,1)}))}}class Cr{prevStats=new Map;scheduleTask=or();allowedReportTypes=new Set(["candidate-pair","inbound-rtp","outbound-rtp","remote-outbound-rtp","remote-inbound-rtp","track","transport"]);ignoreSSRCList;logger;constructor(e){this.ignoreSSRCList=e.ignoreSSRCList??[],this.logger=e.logger}get previouslyParsedStatsConnectionsIds(){return[...this.prevStats.keys()]}async parse(e){if(!Er(e.pc))return this.getConnectionStats(e);this.logger.debug("Skip stats parsing. Connection is closed.",{connection:e})}async getConnectionStats(e){const{pc:t,id:r}=e;try{const n=Date.now(),i=t.getReceivers().filter((e=>e.track?.enabled)),s=t.getSenders().filter((e=>e.track?.enabled)),o=await Promise.all(i.map((e=>e.getStats()))),a=await Promise.all(s.map((e=>e.getStats())));return{id:r,stats:this.mapReportsStats([...o,...a],e),timeTaken:Date.now()-n}}catch(e){return void this.logger.error("Failed to get stats for PC",{id:r,pc:t,error:e})}}mapReportsStats(e,t){const r={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{},remote:{video:{inbound:[],outbound:[]},audio:{inbound:[],outbound:[]}}};e.forEach((e=>{e.forEach((t=>{this.allowedReportTypes.has(t.type)&&this.updateMappedStatsWithReportItemData(t,r,e)}))}));const{id:n}=t,i=this.prevStats.get(n);return i&&this.propagateStatsWithRateValues(r,i.stats),this.prevStats.set(n,{stats:r,ts:Date.now()}),this.scheduleTask({taskId:n,delayMs:35e3,callback:()=>this.prevStats.delete(n)}),r}updateMappedStatsWithReportItemData(e,t,r){const n=e.type;if("candidate-pair"===n&&"succeeded"===e.state&&e.nominated)return void(t.connection=this.prepareConnectionStats(e,r));const i=this.getMediaType(e);if(!i)return;const s=e.ssrc;if(!s||!this.ignoreSSRCList.includes(s))if("outbound-rtp"!==n)if("inbound-rtp"!==n)"remote-outbound-rtp"!==n?"remote-inbound-rtp"===n&&(this.mapConnectionStatsIfNecessary(t,e,r),t.remote[i].inbound.push({...e})):t.remote[i].outbound.push({...e});else{const n=r.get(e.trackId)||r.get(e.mediaSourceId)||{};this.mapConnectionStatsIfNecessary(t,e,r);const s={...e,track:{...n}};t[i].inbound.push(s)}else{const n=r.get(e.trackId)||r.get(e.mediaSourceId)||{},s={...e,track:{...n}};t[i].outbound.push(s)}}getMediaType(e){const t=e.mediaType||e.kind;if(!["audio","video"].includes(t)){const{id:t}=e;if(!t)return;return String(t).includes("Video")?"video":String(t).includes("Audio")?"audio":void 0}return t}propagateStatsWithRateValues(e,t){e.audio.inbound.forEach((e=>{const r=t.audio.inbound.find((({id:t})=>t===e.id));e.bitrate=wr(e,r,"bytesReceived"),e.packetRate=wr(e,r,"packetsReceived")})),e.audio.outbound.forEach((e=>{const r=t.audio.outbound.find((({id:t})=>t===e.id));e.bitrate=wr(e,r,"bytesSent"),e.packetRate=wr(e,r,"packetsSent")})),e.video.inbound.forEach((e=>{const r=t.video.inbound.find((({id:t})=>t===e.id));e.bitrate=wr(e,r,"bytesReceived"),e.packetRate=wr(e,r,"packetsReceived")})),e.video.outbound.forEach((e=>{const r=t.video.outbound.find((({id:t})=>t===e.id));e.bitrate=wr(e,r,"bytesSent"),e.packetRate=wr(e,r,"packetsSent")}))}mapConnectionStatsIfNecessary(e,t,r){if(e.connection.id||!t.transportId)return;const n=r.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=r.get(n.selectedCandidatePairId);e.connection=this.prepareConnectionStats(t,r)}}prepareConnectionStats(e,t){if(!e||!t)return{};const r={...e};if(r.remoteCandidateId){const e=t.get(r.remoteCandidateId);r.remote={...e}}if(r.localCandidateId){const e=t.get(r.localCandidateId);r.local={...e}}return r}}class Pr{eventEmitter;#_=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;autoAddPeerConnections;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new ir,e.onIssues&&this.eventEmitter.on(Wt.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(Wt.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new hr,new ur,new pr,new lr,new dr,new fr,new yr,new br,new _r],this.networkScoresCalculator=e.networkScoresCalculator??new ar,this.compositeStatsParser=e.compositeStatsParser??new Sr({statsParser:new Cr({ignoreSSRCList:e.ignoreSSRCList,logger:this.logger})}),this.statsReporter=e.statsReporter??new sr({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.autoAddPeerConnections=e.autoAddPeerConnections??!0,this.autoAddPeerConnections&&this.wrapRTCPeerConnection(),this.statsReporter.on(sr.STATS_REPORT_READY_EVENT,(e=>{const t=this.calculateNetworkScores(e.stats);this.detectIssues({data:e.stats},t)})),this.statsReporter.on(sr.STATS_REPORTS_PARSED,(t=>{const r={timeTaken:t.timeTaken,ts:Date.now()};e.onStats&&e.onStats(t.reportItems),this.eventEmitter.emit(Wt.StatsParsingFinished,r)}))}watchNewPeerConnections(){if(!this.autoAddPeerConnections)throw new Error("Auto add peer connections was disabled in the constructor.");this.#_?this.logger.warn("WebRTCIssueDetector is already started. Skip processing"):(this.logger.info("Start watching peer connections"),this.#_=!0,this.statsReporter.startReporting())}stopWatchingNewPeerConnections(){this.#_?(this.logger.info("Stop watching peer connections"),this.#_=!1,this.statsReporter.stopReporting()):this.logger.warn("WebRTCIssueDetector is already stopped. Skip processing")}handleNewPeerConnection(e,t){this.#_||!this.autoAddPeerConnections?(this.#_||!1!==this.autoAddPeerConnections||(this.logger.info("Starting stats reporting for new peer connection"),this.#_=!0,this.statsReporter.startReporting()),this.logger.debug("Handling new peer connection",e),this.compositeStatsParser.addPeerConnection({pc:e,id:t})):this.logger.debug("Skip handling new peer connection. Detector is not running",e)}emitIssues(e){this.eventEmitter.emit(Wt.Issue,e)}detectIssues({data:e},t){const r=this.detectors.reduce(((r,n)=>[...r,...n.detect(e,t)]),[]);r.length>0&&this.emitIssues(r)}calculateNetworkScores(e){const t=this.networkScoresCalculator.calculate(e);return this.eventEmitter.emit(Wt.NetworkScoresUpdated,t),t}wrapRTCPeerConnection(){if(!window.RTCPeerConnection)return void this.logger.warn("No RTCPeerConnection found in browser window. Skipping");const e=window.RTCPeerConnection,t=e=>this.handleNewPeerConnection(e);function r(r){const n=new e(r);return t(n),n}r.prototype=e.prototype,window.RTCPeerConnection=r}}const Tr=Array.from({length:256},((e,t)=>(t+256).toString(16).slice(1)));function Rr(e=24){const t=new Uint8Array(e);crypto.getRandomValues(t);let r="";for(let e=0;e<t.length;e++)r+=Tr[t[e]];return r}let kr,Dr=!1;const Ir=()=>{try{return Dr?null:window.localStorage}catch(e){return console.error("Get local storage error",{error:Vt(e)}),e instanceof Error&&"SecurityError"===e.name&&(Dr=!0),null}};function Ar(e){const t=Ir();if(!t)return null;try{const r=t.getItem(e);return r?JSON.parse(r):null}catch(e){return null}}const Or=()=>{if(kr)return kr;const e=Ar("clientUniqueId");if(e)return kr=e,e;const t=Rr(12);return kr=t,function(e,t){const r=Ir();if(r)try{r.setItem(e,JSON.stringify(t))}catch(e){console.error(e)}}("clientUniqueId",t),t},Mr=()=>{const e=Ar("clientUniqueId");return e||(null!=kr?kr:Or())};var Nr,Lr,xr,Fr,jr,Ur;let Vr=class{constructor(){Nr.set(this,void 0),Lr.set(this,void 0),xr.set(this,void 0),Fr.set(this,void 0),jr.set(this,void 0),Ur.set(this,{})}get meta(){return Object.assign(Object.assign({clUId:Mr()},a(this,Ur,"f")),{peerId:a(this,Nr,"f"),channelId:a(this,Lr,"f"),appId:a(this,xr,"f"),datacenterName:a(this,Fr,"f"),nodeId:a(this,jr,"f")})}setPeerId(e){c(this,Nr,e,"f")}setChannelId(e){c(this,Lr,e,"f")}setAppId(e){c(this,xr,e,"f")}setDatacenterName(e){c(this,Fr,e,"f")}setNodeId(e){c(this,jr,e,"f")}setExternalMeta(e){c(this,Ur,e,"f")}clear(){c(this,Nr,void 0,"f"),c(this,Lr,void 0,"f"),c(this,xr,void 0,"f"),c(this,Fr,void 0,"f"),c(this,Ur,{},"f")}};Nr=new WeakMap,Lr=new WeakMap,xr=new WeakMap,Fr=new WeakMap,jr=new WeakMap,Ur=new WeakMap,Vr=n([ot()],Vr);const Br="peer.updateAppData",Wr="channel-event",Hr="peer-joined",qr="peer-left",zr="channel-activity-confirmation-required",Gr="channel-activity-confirmation-acquired",Yr="channel-activity-confirmation-expired",$r="channel-rejoin-required",Jr="devices-list-updated",Qr="transport-connection-timeout",Kr="track-force-closed",Zr="track-failed",Xr="active-speaker-changed",en="channel-state-inconsistent",tn="connection-lost",rn="connection-restored",nn="forced-disconnect",sn="denoiser-initializing",on="channel-state-synced",an="denoiser-enabled",cn="denoiser-disabled",dn="denoiser-fallback",un="denoiser-failed",ln="effects-enabled",pn="effects-disabled",hn="effects-failed",fn="network-scores-updated",mn="volume-changed",gn="track-produced",vn="track-unproduced",yn="track-paused",bn="track-resumed",_n="track-closed",En="track-reopened",wn="track-failed",Sn="media-published",Cn="media-unpublished",Pn="publisher-paused",Tn="publisher-resumed",Rn="track-start",kn="track-end",Dn="track-paused",In="track-resumed",An="track-failed",On="app-data-updated",Mn="produce-permissions-changed",Nn="groups-changed",Ln="peer.newProducer",xn="producer.close",Fn="producer.setMaxSpatialLayer",jn="producer.requestMaxSpatialLayer",Un="consumer.close",Vn="consumer.pause",Bn="consumer.resume",Wn="consumer.changeConsumerPreferredLayers",Hn="transport.connectionTimeout",qn="transport-state";var zn;!function(e){e.CloseProducer="CloseProducer",e.Mute="Mute",e.Resume="Resume",e.Join="Join",e.Release="Release"}(zn||(zn={}));class Gn extends Error{constructor(e,t,r){super(null!=e?e:"Unexpected Livedigital SDK error"),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this.errorCode=null!=t?t:"unknown_error",this.meta=r}}class Yn extends Gn{constructor(e,t,r){super(null!=e?e:Yn.DEFAULT_MESSAGE,null!=t?t:"not_found",r)}}Yn.DEFAULT_MESSAGE="Requested resource was not found";class $n extends Gn{constructor(e,t,r){super(null!=e?e:$n.DEFAULT_MESSAGE,null!=t?t:"something_went_wrong",r)}}$n.DEFAULT_MESSAGE="Request failed";class Jn extends Gn{constructor(e,t,r){super(null!=e?e:Jn.DEFAULT_MESSAGE,null!=t?t:"timeout",r)}}Jn.DEFAULT_MESSAGE="Request timed out";const Qn=e=>e instanceof Yn||e instanceof Jn||(e=>{var t;return e instanceof $n&&void 0===(null===(t=e.meta)||void 0===t?void 0:t.status)})(e);class Kn extends Gn{constructor(e,t,r){super(null!=e?e:Kn.DEFAULT_MESSAGE,null!=t?t:"need_joined_to_channel",r)}}Kn.DEFAULT_MESSAGE="Peer must join the channel before performing this request";class Zn extends Gn{constructor(e,t,r){super(null!=e?e:Zn.DEFAULT_MESSAGE,null!=t?t:"unsupported_error",r)}}Zn.UNSUPPORTED_DEVICE_CODE="unsupported_device_error",Zn.UNSUPPORTED_OPERATION_CODE="unsupported_operation_error",Zn.DEFAULT_MESSAGE="Unsupported operation";const Xn=e=>{let t;try{t=JSON.stringify(e)}catch(e){throw new Bt("app_data_stringify_failed",e)}if(!((new TextEncoder).encode(t).length<=2048))throw new Bt("app_data_size_exceeded")};var ei={exports:{}},ti=l(ei.exports=function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=90)}({17:function(e,t,r){t.__esModule=!0,t.default=void 0;var n=r(18),i=function(){function e(){}return e.getFirstMatch=function(e,t){var r=t.match(e);return r&&r.length>0&&r[1]||""},e.getSecondMatch=function(e,t){var r=t.match(e);return r&&r.length>1&&r[2]||""},e.matchAndReturnConst=function(e,t,r){if(e.test(t))return r},e.getWindowsVersionName=function(e){switch(e){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},e.getMacOSVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),10===t[0])switch(t[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}},e.getAndroidVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0},e.getVersionPrecision=function(e){return e.split(".").length},e.compareVersions=function(t,r,n){void 0===n&&(n=!1);var i=e.getVersionPrecision(t),s=e.getVersionPrecision(r),o=Math.max(i,s),a=0,c=e.map([t,r],(function(t){var r=o-e.getVersionPrecision(t),n=t+new Array(r+1).join(".0");return e.map(n.split("."),(function(e){return new Array(20-e.length).join("0")+e})).reverse()}));for(n&&(a=o-Math.min(i,s)),o-=1;o>=a;){if(c[0][o]>c[1][o])return 1;if(c[0][o]===c[1][o]){if(o===a)return 0;o-=1}else if(c[0][o]<c[1][o])return-1}},e.map=function(e,t){var r,n=[];if(Array.prototype.map)return Array.prototype.map.call(e,t);for(r=0;r<e.length;r+=1)n.push(t(e[r]));return n},e.find=function(e,t){var r,n;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(r=0,n=e.length;r<n;r+=1){var i=e[r];if(t(i,r))return i}},e.assign=function(e){for(var t,r,n=e,i=arguments.length,s=new Array(i>1?i-1:0),o=1;o<i;o++)s[o-1]=arguments[o];if(Object.assign)return Object.assign.apply(Object,[e].concat(s));var a=function(){var e=s[t];"object"==typeof e&&null!==e&&Object.keys(e).forEach((function(t){n[t]=e[t]}))};for(t=0,r=s.length;t<r;t+=1)a();return e},e.getBrowserAlias=function(e){return n.BROWSER_ALIASES_MAP[e]},e.getBrowserTypeByAlias=function(e){return n.BROWSER_MAP[e]||""},e}();t.default=i,e.exports=t.default},18:function(e,t,r){t.__esModule=!0,t.ENGINE_MAP=t.OS_MAP=t.PLATFORMS_MAP=t.BROWSER_MAP=t.BROWSER_ALIASES_MAP=void 0,t.BROWSER_ALIASES_MAP={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},t.BROWSER_MAP={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},t.PLATFORMS_MAP={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},t.OS_MAP={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},t.ENGINE_MAP={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"}},90:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(91))&&n.__esModule?n:{default:n},s=r(18);function o(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}var a=function(){function e(){}var t,r,n;return e.getParser=function(e,t){if(void 0===t&&(t=!1),"string"!=typeof e)throw new Error("UserAgent should be a string");return new i.default(e,t)},e.parse=function(e){return new i.default(e).getResult()},t=e,n=[{key:"BROWSER_MAP",get:function(){return s.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return s.ENGINE_MAP}},{key:"OS_MAP",get:function(){return s.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return s.PLATFORMS_MAP}}],(r=null)&&o(t.prototype,r),n&&o(t,n),e}();t.default=a,e.exports=t.default},91:function(e,t,r){t.__esModule=!0,t.default=void 0;var n=c(r(92)),i=c(r(93)),s=c(r(94)),o=c(r(95)),a=c(r(17));function c(e){return e&&e.__esModule?e:{default:e}}var d=function(){function e(e,t){if(void 0===t&&(t=!1),null==e||""===e)throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},!0!==t&&this.parse()}var t=e.prototype;return t.getUA=function(){return this._ua},t.test=function(e){return e.test(this._ua)},t.parseBrowser=function(){var e=this;this.parsedResult.browser={};var t=a.default.find(n.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.browser=t.describe(this.getUA())),this.parsedResult.browser},t.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},t.getBrowserName=function(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},t.getBrowserVersion=function(){return this.getBrowser().version},t.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},t.parseOS=function(){var e=this;this.parsedResult.os={};var t=a.default.find(i.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os},t.getOSName=function(e){var t=this.getOS().name;return e?String(t).toLowerCase()||"":t||""},t.getOSVersion=function(){return this.getOS().version},t.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},t.getPlatformType=function(e){void 0===e&&(e=!1);var t=this.getPlatform().type;return e?String(t).toLowerCase()||"":t||""},t.parsePlatform=function(){var e=this;this.parsedResult.platform={};var t=a.default.find(s.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform},t.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},t.getEngineName=function(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},t.parseEngine=function(){var e=this;this.parsedResult.engine={};var t=a.default.find(o.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine},t.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},t.getResult=function(){return a.default.assign({},this.parsedResult)},t.satisfies=function(e){var t=this,r={},n=0,i={},s=0;if(Object.keys(e).forEach((function(t){var o=e[t];"string"==typeof o?(i[t]=o,s+=1):"object"==typeof o&&(r[t]=o,n+=1)})),n>0){var o=Object.keys(r),c=a.default.find(o,(function(e){return t.isOS(e)}));if(c){var d=this.satisfies(r[c]);if(void 0!==d)return d}var u=a.default.find(o,(function(e){return t.isPlatform(e)}));if(u){var l=this.satisfies(r[u]);if(void 0!==l)return l}}if(s>0){var p=Object.keys(i),h=a.default.find(p,(function(e){return t.isBrowser(e,!0)}));if(void 0!==h)return this.compareVersion(i[h])}},t.isBrowser=function(e,t){void 0===t&&(t=!1);var r=this.getBrowserName().toLowerCase(),n=e.toLowerCase(),i=a.default.getBrowserTypeByAlias(n);return t&&i&&(n=i.toLowerCase()),n===r},t.compareVersion=function(e){var t=[0],r=e,n=!1,i=this.getBrowserVersion();if("string"==typeof i)return">"===e[0]||"<"===e[0]?(r=e.substr(1),"="===e[1]?(n=!0,r=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?r=e.substr(1):"~"===e[0]&&(n=!0,r=e.substr(1)),t.indexOf(a.default.compareVersions(i,r,n))>-1},t.isOS=function(e){return this.getOSName(!0)===String(e).toLowerCase()},t.isPlatform=function(e){return this.getPlatformType(!0)===String(e).toLowerCase()},t.isEngine=function(e){return this.getEngineName(!0)===String(e).toLowerCase()},t.is=function(e,t){return void 0===t&&(t=!1),this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)},t.some=function(e){var t=this;return void 0===e&&(e=[]),e.some((function(e){return t.is(e)}))},e}();t.default=d,e.exports=t.default},92:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=/version\/(\d+(\.?_?\d+)+)/i,o=[{test:[/googlebot/i],describe:function(e){var t={name:"Googlebot"},r=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/opera/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opr\/|opios/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/SamsungBrowser/i],describe:function(e){var t={name:"Samsung Internet for Android"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Whale/i],describe:function(e){var t={name:"NAVER Whale Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MZBrowser/i],describe:function(e){var t={name:"MZ Browser"},r=i.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/focus/i],describe:function(e){var t={name:"Focus"},r=i.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/swing/i],describe:function(e){var t={name:"Swing"},r=i.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/coast/i],describe:function(e){var t={name:"Opera Coast"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(e){var t={name:"Opera Touch"},r=i.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/yabrowser/i],describe:function(e){var t={name:"Yandex Browser"},r=i.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/ucbrowser/i],describe:function(e){var t={name:"UC Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Maxthon|mxios/i],describe:function(e){var t={name:"Maxthon"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/epiphany/i],describe:function(e){var t={name:"Epiphany"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/puffin/i],describe:function(e){var t={name:"Puffin"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sleipnir/i],describe:function(e){var t={name:"Sleipnir"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/k-meleon/i],describe:function(e){var t={name:"K-Meleon"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/micromessenger/i],describe:function(e){var t={name:"WeChat"},r=i.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/qqbrowser/i],describe:function(e){var t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},r=i.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/msie|trident/i],describe:function(e){var t={name:"Internet Explorer"},r=i.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/\sedg\//i],describe:function(e){var t={name:"Microsoft Edge"},r=i.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/edg([ea]|ios)/i],describe:function(e){var t={name:"Microsoft Edge"},r=i.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/vivaldi/i],describe:function(e){var t={name:"Vivaldi"},r=i.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/seamonkey/i],describe:function(e){var t={name:"SeaMonkey"},r=i.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sailfish/i],describe:function(e){var t={name:"Sailfish"},r=i.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return r&&(t.version=r),t}},{test:[/silk/i],describe:function(e){var t={name:"Amazon Silk"},r=i.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/phantom/i],describe:function(e){var t={name:"PhantomJS"},r=i.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/slimerjs/i],describe:function(e){var t={name:"SlimerJS"},r=i.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t={name:"BlackBerry"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t={name:"WebOS Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/bada/i],describe:function(e){var t={name:"Bada"},r=i.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/tizen/i],describe:function(e){var t={name:"Tizen"},r=i.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/qupzilla/i],describe:function(e){var t={name:"QupZilla"},r=i.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/firefox|iceweasel|fxios/i],describe:function(e){var t={name:"Firefox"},r=i.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/electron/i],describe:function(e){var t={name:"Electron"},r=i.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MiuiBrowser/i],describe:function(e){var t={name:"Miui"},r=i.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/chromium/i],describe:function(e){var t={name:"Chromium"},r=i.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/chrome|crios|crmo/i],describe:function(e){var t={name:"Chrome"},r=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/GSA/i],describe:function(e){var t={name:"Google Search"},r=i.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t={name:"Android Browser"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/playstation 4/i],describe:function(e){var t={name:"PlayStation 4"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/safari|applewebkit/i],describe:function(e){var t={name:"Safari"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/.*/i],describe:function(e){var t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:i.default.getFirstMatch(t,e),version:i.default.getSecondMatch(t,e)}}}];t.default=o,e.exports=t.default},93:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18),o=[{test:[/Roku\/DVP/],describe:function(e){var t=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:s.OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe:function(e){var t=i.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe:function(e){var t=i.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),r=i.default.getWindowsVersionName(t);return{name:s.OS_MAP.Windows,version:t,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e){var t={name:s.OS_MAP.iOS},r=i.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return r&&(t.version=r),t}},{test:[/macintosh/i],describe:function(e){var t=i.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),r=i.default.getMacOSVersionName(t),n={name:s.OS_MAP.MacOS,version:t};return r&&(n.versionName=r),n}},{test:[/(ipod|iphone|ipad)/i],describe:function(e){var t=i.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:s.OS_MAP.iOS,version:t}}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t=i.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),r=i.default.getAndroidVersionName(t),n={name:s.OS_MAP.Android,version:t};return r&&(n.versionName=r),n}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t=i.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),r={name:s.OS_MAP.WebOS};return t&&t.length&&(r.version=t),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t=i.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||i.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||i.default.getFirstMatch(/\bbb(\d+)/i,e);return{name:s.OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe:function(e){var t=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe:function(e){var t=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:function(){return{name:s.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:s.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e){var t=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.PlayStation4,version:t}}}];t.default=o,e.exports=t.default},94:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18),o=[{test:[/googlebot/i],describe:function(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe:function(e){var t=i.default.getFirstMatch(/(can-l01)/i,e)&&"Nova",r={type:s.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(r.model=t),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet}}},{test:function(e){var t=e.test(/ipod|iphone/i),r=e.test(/like (ipod|iphone)/i);return t&&!r},describe:function(e){var t=i.default.getFirstMatch(/(ipod|iphone)/i,e);return{type:s.PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"blackberry"===e.getBrowserName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e){return"bada"===e.getBrowserName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"windows phone"===e.getBrowserName()},describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(e){var t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(!0)&&t>=3},describe:function(){return{type:s.PLATFORMS_MAP.tablet}}},{test:function(e){return"android"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"macos"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e){return"windows"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.desktop}}},{test:function(e){return"linux"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.desktop}}},{test:function(e){return"playstation 4"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.tv}}},{test:function(e){return"roku"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.tv}}}];t.default=o,e.exports=t.default},95:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18),o=[{test:function(e){return"microsoft edge"===e.getBrowserName(!0)},describe:function(e){if(/\sedg\//i.test(e))return{name:s.ENGINE_MAP.Blink};var t=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:s.ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe:function(e){var t={name:s.ENGINE_MAP.Trident},r=i.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){return e.test(/presto/i)},describe:function(e){var t={name:s.ENGINE_MAP.Presto},r=i.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=e.test(/gecko/i),r=e.test(/like gecko/i);return t&&!r},describe:function(e){var t={name:s.ENGINE_MAP.Gecko},r=i.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:s.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e){var t={name:s.ENGINE_MAP.WebKit},r=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}}];t.default=o,e.exports=t.default}}));function ri(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ni(e,t){const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;let i=!0;return r.forEach((r=>{const n=e[r],s=t[r],o=ri(n)&&ri(s);(o&&!ni(n,s)||!o&&n!==s)&&(i=!1)})),i}function ii(e,t,r=!1){let n=null;return function(...i){return o(this,void 0,void 0,(function*(){const s=r&&!n;"number"==typeof n&&clearTimeout(n),n=setTimeout((()=>o(this,void 0,void 0,(function*(){n=null,r||(yield e.apply(this,i))}))),t),s&&(yield e.apply(this,i))}))}}function si(e,t){return o(this,void 0,void 0,(function*(){try{return yield e()}catch(e){return void(null==t||t(e))}}))}var oi,ai;exports.TrackLabel=void 0,(oi=exports.TrackLabel||(exports.TrackLabel={})).Camera="camera",oi.CameraPreview="camera-preview",oi.Microphone="microphone",oi.MicrophonePreview="microphone-preview",oi.ScreenVideo="screen-video",oi.ScreenAudio="screen-audio",oi.CustomVideo="custom-video",oi.CustomAudio="custom-audio",oi.Unknown="unknown",exports.DeviceErrors=void 0,(ai=exports.DeviceErrors||(exports.DeviceErrors={})).NotFoundError="NotFoundError",ai.NoDevices="NoDevices",ai.DeviceIsBusy="DeviceIsBusy",ai.NotAllowedError="NotAllowedError",ai.RequestDevicesUnknownError="RequestDevicesUnknownError";const ci=e=>{var t,r;return null!==(r=null===(t=e.rtpCapabilities.codecs)||void 0===t?void 0:t.reduce(((e,t)=>{var r;const n=null===(r=t.mimeType)||void 0===r?void 0:r.toLowerCase();return n&&!e.includes(n)&&e.push(n),e}),[]))&&void 0!==r?r:[]},di=e=>["video/vp9","vp9"].includes(e.toLowerCase()),ui=e=>"opus"!==e;class li{sleepMs(e){return o(this,void 0,void 0,(function*(){yield new Promise((t=>setTimeout(t,e)))}))}now(){return new Date(Date.now())}}const pi=new li,hi=(e,...t)=>o(void 0,[e,...t],void 0,(function*(e,t={}){var r,n,i,s;const o=null!==(r=t.maxRetries)&&void 0!==r?r:2,a=null!==(n=t.minBackoffDelayMs)&&void 0!==n?n:50;let c,d=0;for(;d<o;){d+=1;try{return yield e()}catch(e){if(c=e,t.logger&&t.logger.info("Action retry failed",{currentAttempt:d,actionName:t.actionName,error:Vt(e)}),null===(i=t.abortOnError)||void 0===i?void 0:i.call(t,e))throw c;if(t.onError&&(yield t.onError(e)),d<o){const e=Math.pow(2,d-1)*a;yield pi.sleepMs(Math.min(e,null!==(s=t.maxBackoffDelayMs)&&void 0!==s?s:e))}}}throw null!=c?c:new Error("retryAsync logic failed")}));var fi;!function(e){e.Config="Config",e.Engine="Engine",e.System="System",e.Media="Media",e.Network="Network",e.MediaEventHandler="MediaEventHandler",e.ChannelEventHandler="ChannelEventHandler",e.ChannelAudioObserverEventHandler="ChannelAudioObserverEventHandler",e.ChannelAudioObserverMissingProducerRestorer="ChannelAudioObserverMissingProducerRestorer",e.ChannelStateSynchronizer="ChannelStateSynchronizer",e.ChannelStateSyncEventHandler="ChannelStateSyncEventHandler",e.CompositeStatsParser="CompositeStatsParser",e.PeriodicStatsReporter="PeriodicStatsReporter",e.WIDIgnoreSsrcList="WIDIgnoreSsrcList",e.WebRTCIssueDetector="WebRTCIssueDetector",e.NetworkScoresUpdatedEventHandler="NetworkScoresUpdatedEventHandler",e.WIDStatsAdapter="WIDStatsAdapter",e.ScoresCalculator="ScoresCalculator",e.LoggerFactory="LoggerFactory",e.MediaStreamTrackManager="MediaStreamTrackManager",e.EventsQueue="EventsQueue",e.ClientEventEmitter="ClientEventEmitter",e.Peers="Peers",e.CallState="CallState",e.RemotePeerTracks="RemotePeerTracks",e.MyPeer="MyPeer",e.InternalEventEmitter="InternalEventEmitter",e.PeerTrackFactory="PeerTrackFactory",e.PeerFactory="PeerFactory",e.PeerConsumerFactory="PeerConsumerFactory",e.AudioTrackFactory="AudioTrackFactory",e.VideoTrackFactory="VideoTrackFactory",e.AudioTrackProcessorFactory="AudioTrackProcessorFactory",e.IntegrationsService="IntegrationsService",e.ProcessorsCache="ProcessorsCache",e.StatsHandler="StatsHandler",e.DataChannelsManager="DataChannelsManager",e.WIDHandler="WIDHandler",e.AnalyticsApiClient="AnalyticsApiClient",e.TransportsStatsProvider="TransportsStatsProvider",e.LocalMutex="LocalMutex",e.PeersStorage="PeersStorage",e.SignalingApiClient="SignalingApiClient",e.DatachannelHeartbeater="DatachannelHeartbeater",e.SignalingHeartbeater="SignalingHeartbeater",e.PendingClosureProducerStorage="PendingClosureProducerStorage",e.ProducerCloseManager="ProducerCloseManager",e.NetworkTransportPolicyManager="NetworkTransportPolicyManager",e.ClientMetaProvider="ClientMetaProvider",e.TransportStateMonitor="TransportStateMonitor",e.IceRecoveryService="IceRecoveryService"}(fi||(fi={}));let mi=class{constructor(){this.isJoined=!1,this.isChannelJoining=!1}reset(){this.appId=void 0,this.channelId=void 0,this.isJoined=!1,this.isChannelJoining=!1}};function gi(){let e=0,t=0;for(let r=0;r<28;r+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<r,0==(128&n))return this.assertBounds(),[e,t]}let r=this.buf[this.pos++];if(e|=(15&r)<<28,t=(112&r)>>4,0==(128&r))return this.assertBounds(),[e,t];for(let r=3;r<=31;r+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<r,0==(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function vi(e,t,r){for(let n=0;n<28;n+=7){const i=e>>>n,s=!(i>>>7==0&&0==t),o=255&(s?128|i:i);if(r.push(o),!s)return}const n=e>>>28&15|(7&t)<<4,i=!(t>>3==0);if(r.push(255&(i?128|n:n)),i){for(let e=3;e<31;e+=7){const n=t>>>e,i=!(n>>>7==0),s=255&(i?128|n:n);if(r.push(s),!i)return}r.push(t>>>31&1)}}mi=n([ot()],mi);function yi(e){const t="-"===e[0];t&&(e=e.slice(1));const r=1e6;let n=0,i=0;function s(t,s){const o=Number(e.slice(t,s));i*=r,n=n*r+o,n>=4294967296&&(i+=n/4294967296|0,n%=4294967296)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),t?Ei(n,i):_i(n,i)}function bi(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(4294967296*t+e);const r=16777215&(e>>>24|t<<8),n=t>>16&65535;let i=(16777215&e)+6777216*r+6710656*n,s=r+8147497*n,o=2*n;const a=1e7;return i>=a&&(s+=Math.floor(i/a),i%=a),s>=a&&(o+=Math.floor(s/a),s%=a),o.toString()+wi(s)+wi(i)}function _i(e,t){return{lo:0|e,hi:0|t}}function Ei(e,t){return t=~t,e?e=1+~e:t+=1,_i(e,t)}const wi=e=>{const t=String(e);return"0000000".slice(t.length)+t};function Si(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let r=0;r<9;r++)t.push(127&e|128),e>>=7;t.push(1)}}function Ci(){let e=this.buf[this.pos++],t=127&e;if(0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,0==(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;0!=(128&e)&&t<10;t++)e=this.buf[this.pos++];if(0!=(128&e))throw new Error("invalid varint");return this.assertBounds(),t>>>0}const Pi=Ti();function Ti(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),n=BigInt("0"),i=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>r||n<t)throw new Error(`invalid int64: ${e}`);return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>i||t<n)throw new Error(`invalid uint64: ${e}`);return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,r)=>(e.setInt32(0,t,!0),e.setInt32(4,r,!0),e.getBigInt64(0,!0)),uDec:(t,r)=>(e.setInt32(0,t,!0),e.setInt32(4,r,!0),e.getBigUint64(0,!0))}}return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),Ri(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),ki(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),Ri(e),yi(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),ki(e),yi(e)),dec:(e,t)=>function(e,t){let r=_i(e,t);const n=2147483648&r.hi;n&&(r=Ei(r.lo,r.hi));const i=bi(r.lo,r.hi);return n?"-"+i:i}(e,t),uDec:(e,t)=>bi(e,t)}}function Ri(e){if(!/^-?[0-9]+$/.test(e))throw new Error("invalid int64: "+e)}function ki(e){if(!/^[0-9]+$/.test(e))throw new Error("invalid uint64: "+e)}const Di=Symbol.for("@bufbuild/protobuf/text-encoding");function Ii(){if(null==globalThis[Di]){const e=new globalThis.TextEncoder,t=new globalThis.TextDecoder;globalThis[Di]={encodeUtf8:t=>e.encode(t),decodeUtf8:e=>t.decode(e),checkUtf8(e){try{return encodeURIComponent(e),!0}catch(e){return!1}}}}return globalThis[Di]}var Ai;!function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(Ai||(Ai={}));const Oi=34028234663852886e22,Mi=-34028234663852886e22;class Ni{constructor(e=Ii().encodeUtf8){this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),r=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],r),r+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Fi(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return xi(e),Si(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.encodeUtf8(e);return this.uint32(t.byteLength),this.raw(t)}float(e){!function(e){if("string"==typeof e){const t=e;if(e=Number(e),Number.isNaN(e)&&"NaN"!==t)throw new Error("invalid float32: "+t)}else if("number"!=typeof e)throw new Error("invalid float32: "+typeof e);if(Number.isFinite(e)&&(e>Oi||e<Mi))throw new Error("invalid float32: "+e)}(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Fi(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){xi(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return xi(e),Si(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),r=new DataView(t.buffer),n=Pi.enc(e);return r.setInt32(0,n.lo,!0),r.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),r=new DataView(t.buffer),n=Pi.uEnc(e);return r.setInt32(0,n.lo,!0),r.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=Pi.enc(e);return vi(t.lo,t.hi,this.buf),this}sint64(e){const t=Pi.enc(e),r=t.hi>>31;return vi(t.lo<<1^r,(t.hi<<1|t.lo>>>31)^r,this.buf),this}uint64(e){const t=Pi.uEnc(e);return vi(t.lo,t.hi,this.buf),this}}class Li{constructor(e,t=Ii().decodeUtf8){this.decodeUtf8=t,this.varint64=gi,this.uint32=Ci,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.uint32(),t=e>>>3,r=7&e;if(t<=0||r<0||r>5)throw new Error("illegal tag: field no "+t+" wire type "+r);return[t,r]}skip(e,t){let r=this.pos;switch(e){case Ai.Varint:for(;128&this.buf[this.pos++];);break;case Ai.Bit64:this.pos+=4;case Ai.Bit32:this.pos+=4;break;case Ai.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Ai.StartGroup:for(;;){const[e,r]=this.tag();if(r===Ai.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(r,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(r,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return Pi.dec(...this.varint64())}uint64(){return Pi.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),r=-(1&e);return e=(e>>>1|(1&t)<<31)^r,t=t>>>1^r,Pi.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Pi.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Pi.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.decodeUtf8(this.bytes())}}function xi(e){if("string"==typeof e)e=Number(e);else if("number"!=typeof e)throw new Error("invalid int32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int32: "+e)}function Fi(e){if("string"==typeof e)e=Number(e);else if("number"!=typeof e)throw new Error("invalid uint32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint32: "+e)}const ji={encode:(e,t=new Ni)=>(0!==e.time&&t.uint32(8).int64(e.time),t),decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={time:0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(8!==e)break;i.time=Ui(r.int64());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON(e){return{time:(t=e.time,null!=t?globalThis.Number(e.time):0)};var t},toJSON(e){const t={};return 0!==e.time&&(t.time=Math.round(e.time)),t},create:e=>ji.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={time:0};return r.time=null!==(t=e.time)&&void 0!==t?t:0,r}};function Ui(e){const t=globalThis.Number(e.toString());if(t>globalThis.Number.MAX_SAFE_INTEGER)throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");if(t<globalThis.Number.MIN_SAFE_INTEGER)throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");return t}var Vi;function Bi(e){switch(e){case 0:case"NULL_VALUE":return Vi.NULL_VALUE;default:return Vi.UNRECOGNIZED}}!function(e){e[e.NULL_VALUE=0]="NULL_VALUE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Vi||(Vi={}));const Wi={encode:(e,t=new Ni)=>(Object.entries(e.fields).forEach((([e,r])=>{void 0!==r&&Hi.encode({key:e,value:r},t.uint32(10).fork()).join()})),t),decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={fields:{}};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:{if(10!==e)break;const t=Hi.decode(r,r.uint32());void 0!==t.value&&(i.fields[t.key]=t.value);continue}}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({fields:Gi(e.fields)?Object.entries(e.fields).reduce(((e,[t,r])=>(e[t]=r,e)),{}):{}}),toJSON(e){const t={};if(e.fields){const r=Object.entries(e.fields);r.length>0&&(t.fields={},r.forEach((([e,r])=>{t.fields[e]=r})))}return t},create:e=>Wi.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={fields:{}};return r.fields=Object.entries(null!==(t=e.fields)&&void 0!==t?t:{}).reduce(((e,[t,r])=>(void 0!==r&&(e[t]=r),e)),{}),r},wrap(e){const t={fields:{}};if(void 0!==e)for(const r of Object.keys(e))t.fields[r]=e[r];return t},unwrap(e){const t={};if(e.fields)for(const r of Object.keys(e.fields))t[r]=e.fields[r];return t}};const Hi={encode:(e,t=new Ni)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&qi.encode(qi.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={key:"",value:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.key=r.string();continue;case 2:if(18!==e)break;i.value=qi.unwrap(qi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:Yi(e.key)?globalThis.String(e.key):"",value:Yi(null==e?void 0:e.value)?e.value:void 0}),toJSON(e){const t={};return""!==e.key&&(t.key=e.key),void 0!==e.value&&(t.value=e.value),t},create:e=>Hi.fromPartial(null!=e?e:{}),fromPartial(e){var t,r;const n={key:"",value:void 0};return n.key=null!==(t=e.key)&&void 0!==t?t:"",n.value=null!==(r=e.value)&&void 0!==r?r:void 0,n}};const qi={encode:(e,t=new Ni)=>(void 0!==e.nullValue&&t.uint32(8).int32(e.nullValue),void 0!==e.numberValue&&t.uint32(17).double(e.numberValue),void 0!==e.stringValue&&t.uint32(26).string(e.stringValue),void 0!==e.boolValue&&t.uint32(32).bool(e.boolValue),void 0!==e.structValue&&Wi.encode(Wi.wrap(e.structValue),t.uint32(42).fork()).join(),void 0!==e.listValue&&zi.encode(zi.wrap(e.listValue),t.uint32(50).fork()).join(),t),decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(8!==e)break;i.nullValue=r.int32();continue;case 2:if(17!==e)break;i.numberValue=r.double();continue;case 3:if(26!==e)break;i.stringValue=r.string();continue;case 4:if(32!==e)break;i.boolValue=r.bool();continue;case 5:if(42!==e)break;i.structValue=Wi.unwrap(Wi.decode(r,r.uint32()));continue;case 6:if(50!==e)break;i.listValue=zi.unwrap(zi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({nullValue:Yi(e.nullValue)?Bi(e.nullValue):void 0,numberValue:Yi(e.numberValue)?globalThis.Number(e.numberValue):void 0,stringValue:Yi(e.stringValue)?globalThis.String(e.stringValue):void 0,boolValue:Yi(e.boolValue)?globalThis.Boolean(e.boolValue):void 0,structValue:Gi(e.structValue)?e.structValue:void 0,listValue:globalThis.Array.isArray(e.listValue)?[...e.listValue]:void 0}),toJSON(e){const t={};return void 0!==e.nullValue&&(t.nullValue=function(e){switch(e){case Vi.NULL_VALUE:return"NULL_VALUE";case Vi.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.nullValue)),void 0!==e.numberValue&&(t.numberValue=e.numberValue),void 0!==e.stringValue&&(t.stringValue=e.stringValue),void 0!==e.boolValue&&(t.boolValue=e.boolValue),void 0!==e.structValue&&(t.structValue=e.structValue),void 0!==e.listValue&&(t.listValue=e.listValue),t},create:e=>qi.fromPartial(null!=e?e:{}),fromPartial(e){var t,r,n,i,s,o;const a={nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0};return a.nullValue=null!==(t=e.nullValue)&&void 0!==t?t:void 0,a.numberValue=null!==(r=e.numberValue)&&void 0!==r?r:void 0,a.stringValue=null!==(n=e.stringValue)&&void 0!==n?n:void 0,a.boolValue=null!==(i=e.boolValue)&&void 0!==i?i:void 0,a.structValue=null!==(s=e.structValue)&&void 0!==s?s:void 0,a.listValue=null!==(o=e.listValue)&&void 0!==o?o:void 0,a},wrap(e){const t={nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0};if(null===e)t.nullValue=Vi.NULL_VALUE;else if("boolean"==typeof e)t.boolValue=e;else if("number"==typeof e)t.numberValue=e;else if("string"==typeof e)t.stringValue=e;else if(globalThis.Array.isArray(e))t.listValue=e;else if("object"==typeof e)t.structValue=e;else if(void 0!==e)throw new globalThis.Error("Unsupported any value type: "+typeof e);return t},unwrap:e=>void 0!==e.stringValue?e.stringValue:void 0!==(null==e?void 0:e.numberValue)?e.numberValue:void 0!==(null==e?void 0:e.boolValue)?e.boolValue:void 0!==(null==e?void 0:e.structValue)?e.structValue:void 0!==(null==e?void 0:e.listValue)?e.listValue:void 0!==(null==e?void 0:e.nullValue)?null:void 0};const zi={encode(e,t=new Ni){for(const r of e.values)qi.encode(qi.wrap(r),t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={values:[]};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.values.push(qi.unwrap(qi.decode(r,r.uint32())));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({values:globalThis.Array.isArray(null==e?void 0:e.values)?[...e.values]:[]}),toJSON(e){var t;const r={};return(null===(t=e.values)||void 0===t?void 0:t.length)&&(r.values=e.values),r},create:e=>zi.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={values:[]};return r.values=(null===(t=e.values)||void 0===t?void 0:t.map((e=>e)))||[],r},wrap(e){const t={values:[]};return t.values=null!=e?e:[],t},unwrap:e=>(null==e?void 0:e.hasOwnProperty("values"))&&globalThis.Array.isArray(e.values)?e.values:e};function Gi(e){return"object"==typeof e&&null!==e}function Yi(e){return null!=e}const $i={encode:(e,t=new Ni)=>(Object.entries(e.event).forEach((([e,r])=>{void 0!==r&&Ji.encode({key:e,value:r},t.uint32(10).fork()).join()})),t),decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={event:{}};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:{if(10!==e)break;const t=Ji.decode(r,r.uint32());void 0!==t.value&&(i.event[t.key]=t.value);continue}}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON(e){return{event:(t=e.event,"object"==typeof t&&null!==t?Object.entries(e.event).reduce(((e,[t,r])=>(e[t]=r,e)),{}):{})};var t},toJSON(e){const t={};if(e.event){const r=Object.entries(e.event);r.length>0&&(t.event={},r.forEach((([e,r])=>{t.event[e]=r})))}return t},create:e=>$i.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={event:{}};return r.event=Object.entries(null!==(t=e.event)&&void 0!==t?t:{}).reduce(((e,[t,r])=>(void 0!==r&&(e[t]=r),e)),{}),r}};const Ji={encode:(e,t=new Ni)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&qi.encode(qi.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={key:"",value:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.key=r.string();continue;case 2:if(18!==e)break;i.value=qi.unwrap(qi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:Qi(e.key)?globalThis.String(e.key):"",value:Qi(null==e?void 0:e.value)?e.value:void 0}),toJSON(e){const t={};return""!==e.key&&(t.key=e.key),void 0!==e.value&&(t.value=e.value),t},create:e=>Ji.fromPartial(null!=e?e:{}),fromPartial(e){var t,r;const n={key:"",value:void 0};return n.key=null!==(t=e.key)&&void 0!==t?t:"",n.value=null!==(r=e.value)&&void 0!==r?r:void 0,n}};function Qi(e){return null!=e}var Ki,Zi;function Xi(e){switch(e){case 0:case"PEER_GROUP_UNSPECIFIED":return Ki.PEER_GROUP_UNSPECIFIED;case 1:case"PEER_GROUP_MODERATOR":return Ki.PEER_GROUP_MODERATOR;case 2:case"PEER_GROUP_USER":return Ki.PEER_GROUP_USER;default:return Ki.UNRECOGNIZED}}function es(e){switch(e){case Ki.PEER_GROUP_UNSPECIFIED:return"PEER_GROUP_UNSPECIFIED";case Ki.PEER_GROUP_MODERATOR:return"PEER_GROUP_MODERATOR";case Ki.PEER_GROUP_USER:return"PEER_GROUP_USER";case Ki.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function ts(e){switch(e){case 0:case"PRODUCER_LABEL_UNSPECIFIED":return Zi.PRODUCER_LABEL_UNSPECIFIED;case 1:case"PRODUCER_LABEL_CAMERA":return Zi.PRODUCER_LABEL_CAMERA;case 2:case"PRODUCER_LABEL_MICROPHONE":return Zi.PRODUCER_LABEL_MICROPHONE;case 3:case"PRODUCER_LABEL_SCREEN_VIDEO":return Zi.PRODUCER_LABEL_SCREEN_VIDEO;case 4:case"PRODUCER_LABEL_SCREEN_AUDIO":return Zi.PRODUCER_LABEL_SCREEN_AUDIO;case 5:case"PRODUCER_LABEL_CUSTOM_VIDEO":return Zi.PRODUCER_LABEL_CUSTOM_VIDEO;case 6:case"PRODUCER_LABEL_CUSTOM_AUDIO":return Zi.PRODUCER_LABEL_CUSTOM_AUDIO;case 7:case"PRODUCER_LABEL_UNKNOWN":return Zi.PRODUCER_LABEL_UNKNOWN;default:return Zi.UNRECOGNIZED}}function rs(e){switch(e){case Zi.PRODUCER_LABEL_UNSPECIFIED:return"PRODUCER_LABEL_UNSPECIFIED";case Zi.PRODUCER_LABEL_CAMERA:return"PRODUCER_LABEL_CAMERA";case Zi.PRODUCER_LABEL_MICROPHONE:return"PRODUCER_LABEL_MICROPHONE";case Zi.PRODUCER_LABEL_SCREEN_VIDEO:return"PRODUCER_LABEL_SCREEN_VIDEO";case Zi.PRODUCER_LABEL_SCREEN_AUDIO:return"PRODUCER_LABEL_SCREEN_AUDIO";case Zi.PRODUCER_LABEL_CUSTOM_VIDEO:return"PRODUCER_LABEL_CUSTOM_VIDEO";case Zi.PRODUCER_LABEL_CUSTOM_AUDIO:return"PRODUCER_LABEL_CUSTOM_AUDIO";case Zi.PRODUCER_LABEL_UNKNOWN:return"PRODUCER_LABEL_UNKNOWN";case Zi.UNRECOGNIZED:default:return"UNRECOGNIZED"}}!function(e){e[e.PEER_GROUP_UNSPECIFIED=0]="PEER_GROUP_UNSPECIFIED",e[e.PEER_GROUP_MODERATOR=1]="PEER_GROUP_MODERATOR",e[e.PEER_GROUP_USER=2]="PEER_GROUP_USER",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ki||(Ki={})),function(e){e[e.PRODUCER_LABEL_UNSPECIFIED=0]="PRODUCER_LABEL_UNSPECIFIED",e[e.PRODUCER_LABEL_CAMERA=1]="PRODUCER_LABEL_CAMERA",e[e.PRODUCER_LABEL_MICROPHONE=2]="PRODUCER_LABEL_MICROPHONE",e[e.PRODUCER_LABEL_SCREEN_VIDEO=3]="PRODUCER_LABEL_SCREEN_VIDEO",e[e.PRODUCER_LABEL_SCREEN_AUDIO=4]="PRODUCER_LABEL_SCREEN_AUDIO",e[e.PRODUCER_LABEL_CUSTOM_VIDEO=5]="PRODUCER_LABEL_CUSTOM_VIDEO",e[e.PRODUCER_LABEL_CUSTOM_AUDIO=6]="PRODUCER_LABEL_CUSTOM_AUDIO",e[e.PRODUCER_LABEL_UNKNOWN=7]="PRODUCER_LABEL_UNKNOWN",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Zi||(Zi={}));const ns={encode(e,t=new Ni){t.uint32(10).fork();for(const r of e.groups)t.int32(r);t.join(),t.uint32(18).fork();for(const r of e.producePermissions)t.int32(r);t.join(),t.uint32(26).fork();for(const r of e.changedProducePermissions)t.int32(r);return t.join(),t},decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={groups:[],producePermissions:[],changedProducePermissions:[]};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(8===e){i.groups.push(r.int32());continue}if(10===e){const e=r.uint32()+r.pos;for(;r.pos<e;)i.groups.push(r.int32());continue}break;case 2:if(16===e){i.producePermissions.push(r.int32());continue}if(18===e){const e=r.uint32()+r.pos;for(;r.pos<e;)i.producePermissions.push(r.int32());continue}break;case 3:if(24===e){i.changedProducePermissions.push(r.int32());continue}if(26===e){const e=r.uint32()+r.pos;for(;r.pos<e;)i.changedProducePermissions.push(r.int32());continue}}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({groups:globalThis.Array.isArray(null==e?void 0:e.groups)?e.groups.map((e=>Xi(e))):[],producePermissions:globalThis.Array.isArray(null==e?void 0:e.producePermissions)?e.producePermissions.map((e=>ts(e))):[],changedProducePermissions:globalThis.Array.isArray(null==e?void 0:e.changedProducePermissions)?e.changedProducePermissions.map((e=>ts(e))):[]}),toJSON(e){var t,r,n;const i={};return(null===(t=e.groups)||void 0===t?void 0:t.length)&&(i.groups=e.groups.map((e=>es(e)))),(null===(r=e.producePermissions)||void 0===r?void 0:r.length)&&(i.producePermissions=e.producePermissions.map((e=>rs(e)))),(null===(n=e.changedProducePermissions)||void 0===n?void 0:n.length)&&(i.changedProducePermissions=e.changedProducePermissions.map((e=>rs(e)))),i},create:e=>ns.fromPartial(null!=e?e:{}),fromPartial(e){var t,r,n;const i={groups:[],producePermissions:[],changedProducePermissions:[]};return i.groups=(null===(t=e.groups)||void 0===t?void 0:t.map((e=>e)))||[],i.producePermissions=(null===(r=e.producePermissions)||void 0===r?void 0:r.map((e=>e)))||[],i.changedProducePermissions=(null===(n=e.changedProducePermissions)||void 0===n?void 0:n.map((e=>e)))||[],i}};const is={encode:(e,t=new Ni)=>(0!==e.seconds&&t.uint32(8).int64(e.seconds),0!==e.nanos&&t.uint32(16).int32(e.nanos),t),decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={seconds:0,nanos:0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(8!==e)break;i.seconds=ss(r.int64());continue;case 2:if(16!==e)break;i.nanos=r.int32();continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({seconds:os(e.seconds)?globalThis.Number(e.seconds):0,nanos:os(e.nanos)?globalThis.Number(e.nanos):0}),toJSON(e){const t={};return 0!==e.seconds&&(t.seconds=Math.round(e.seconds)),0!==e.nanos&&(t.nanos=Math.round(e.nanos)),t},create:e=>is.fromPartial(null!=e?e:{}),fromPartial(e){var t,r;const n={seconds:0,nanos:0};return n.seconds=null!==(t=e.seconds)&&void 0!==t?t:0,n.nanos=null!==(r=e.nanos)&&void 0!==r?r:0,n}};function ss(e){const t=globalThis.Number(e.toString());if(t>globalThis.Number.MAX_SAFE_INTEGER)throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");if(t<globalThis.Number.MIN_SAFE_INTEGER)throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");return t}function os(e){return null!=e}var as;function cs(e){switch(e){case 0:case"PRODUCER_KIND_UNSPECIFIED":return as.PRODUCER_KIND_UNSPECIFIED;case 1:case"PRODUCER_KIND_AUDIO":return as.PRODUCER_KIND_AUDIO;case 2:case"PRODUCER_KIND_VIDEO":return as.PRODUCER_KIND_VIDEO;default:return as.UNRECOGNIZED}}!function(e){e[e.PRODUCER_KIND_UNSPECIFIED=0]="PRODUCER_KIND_UNSPECIFIED",e[e.PRODUCER_KIND_AUDIO=1]="PRODUCER_KIND_AUDIO",e[e.PRODUCER_KIND_VIDEO=2]="PRODUCER_KIND_VIDEO",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(as||(as={}));const ds={encode(e,t=new Ni){""!==e.id&&t.uint32(10).string(e.id),0!==e.kind&&t.uint32(16).int32(e.kind),0!==e.label&&t.uint32(24).int32(e.label),""!==e.peerId&&t.uint32(34).string(e.peerId),!1!==e.paused&&t.uint32(40).bool(e.paused);for(const r of e.encodings)qi.encode(qi.wrap(r),t.uint32(50).fork()).join();return void 0!==e.maxSpatialLayer&&t.uint32(56).uint32(e.maxSpatialLayer),t},decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={id:"",kind:0,label:0,peerId:"",paused:!1,encodings:[],maxSpatialLayer:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.id=r.string();continue;case 2:if(16!==e)break;i.kind=r.int32();continue;case 3:if(24!==e)break;i.label=r.int32();continue;case 4:if(34!==e)break;i.peerId=r.string();continue;case 5:if(40!==e)break;i.paused=r.bool();continue;case 6:if(50!==e)break;i.encodings.push(qi.unwrap(qi.decode(r,r.uint32())));continue;case 7:if(56!==e)break;i.maxSpatialLayer=r.uint32();continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({id:us(e.id)?globalThis.String(e.id):"",kind:us(e.kind)?cs(e.kind):0,label:us(e.label)?ts(e.label):0,peerId:us(e.peerId)?globalThis.String(e.peerId):"",paused:!!us(e.paused)&&globalThis.Boolean(e.paused),encodings:globalThis.Array.isArray(null==e?void 0:e.encodings)?[...e.encodings]:[],maxSpatialLayer:us(e.maxSpatialLayer)?globalThis.Number(e.maxSpatialLayer):void 0}),toJSON(e){var t;const r={};return""!==e.id&&(r.id=e.id),0!==e.kind&&(r.kind=function(e){switch(e){case as.PRODUCER_KIND_UNSPECIFIED:return"PRODUCER_KIND_UNSPECIFIED";case as.PRODUCER_KIND_AUDIO:return"PRODUCER_KIND_AUDIO";case as.PRODUCER_KIND_VIDEO:return"PRODUCER_KIND_VIDEO";case as.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.kind)),0!==e.label&&(r.label=rs(e.label)),""!==e.peerId&&(r.peerId=e.peerId),!1!==e.paused&&(r.paused=e.paused),(null===(t=e.encodings)||void 0===t?void 0:t.length)&&(r.encodings=e.encodings),void 0!==e.maxSpatialLayer&&(r.maxSpatialLayer=Math.round(e.maxSpatialLayer)),r},create:e=>ds.fromPartial(null!=e?e:{}),fromPartial(e){var t,r,n,i,s,o,a;const c={id:"",kind:0,label:0,peerId:"",paused:!1,encodings:[],maxSpatialLayer:void 0};return c.id=null!==(t=e.id)&&void 0!==t?t:"",c.kind=null!==(r=e.kind)&&void 0!==r?r:0,c.label=null!==(n=e.label)&&void 0!==n?n:0,c.peerId=null!==(i=e.peerId)&&void 0!==i?i:"",c.paused=null!==(s=e.paused)&&void 0!==s&&s,c.encodings=(null===(o=e.encodings)||void 0===o?void 0:o.map((e=>e)))||[],c.maxSpatialLayer=null!==(a=e.maxSpatialLayer)&&void 0!==a?a:void 0,c}};function us(e){return null!=e}var ls;function ps(e){switch(e){case 0:case"PEER_ROLE_UNSPECIFIED":return ls.PEER_ROLE_UNSPECIFIED;case 1:case"PEER_ROLE_HOST":return ls.PEER_ROLE_HOST;case 2:case"PEER_ROLE_AUDIENCE":return ls.PEER_ROLE_AUDIENCE;default:return ls.UNRECOGNIZED}}!function(e){e[e.PEER_ROLE_UNSPECIFIED=0]="PEER_ROLE_UNSPECIFIED",e[e.PEER_ROLE_HOST=1]="PEER_ROLE_HOST",e[e.PEER_ROLE_AUDIENCE=2]="PEER_ROLE_AUDIENCE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(ls||(ls={}));const hs={encode(e,t=new Ni){""!==e.id&&t.uint32(10).string(e.id);for(const r of e.channelIds)t.uint32(18).string(r);for(const r of e.producers)ds.encode(r,t.uint32(26).fork()).join();""!==e.uid&&t.uint32(50).string(e.uid),""!==e.appId&&t.uint32(58).string(e.appId),Object.entries(e.appData).forEach((([e,r])=>{void 0!==r&&fs.encode({key:e,value:r},t.uint32(66).fork()).join()})),0!==e.role&&t.uint32(72).int32(e.role),void 0!==e.loginDate&&is.encode(function(e){const t=Math.trunc(e.getTime()/1e3),r=e.getTime()%1e3*1e6;return{seconds:t,nanos:r}}(e.loginDate),t.uint32(82).fork()).join(),t.uint32(90).fork();for(const r of e.groups)t.int32(r);t.join(),t.uint32(98).fork();for(const r of e.producePermissions)t.int32(r);return t.join(),t},decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={id:"",channelIds:[],producers:[],uid:"",appId:"",appData:{},role:0,loginDate:void 0,groups:[],producePermissions:[]};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.id=r.string();continue;case 2:if(18!==e)break;i.channelIds.push(r.string());continue;case 3:if(26!==e)break;i.producers.push(ds.decode(r,r.uint32()));continue;case 6:if(50!==e)break;i.uid=r.string();continue;case 7:if(58!==e)break;i.appId=r.string();continue;case 8:{if(66!==e)break;const t=fs.decode(r,r.uint32());void 0!==t.value&&(i.appData[t.key]=t.value);continue}case 9:if(72!==e)break;i.role=r.int32();continue;case 10:if(82!==e)break;i.loginDate=ms(is.decode(r,r.uint32()));continue;case 11:if(88===e){i.groups.push(r.int32());continue}if(90===e){const e=r.uint32()+r.pos;for(;r.pos<e;)i.groups.push(r.int32());continue}break;case 12:if(96===e){i.producePermissions.push(r.int32());continue}if(98===e){const e=r.uint32()+r.pos;for(;r.pos<e;)i.producePermissions.push(r.int32());continue}}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON(e){return{id:vs(e.id)?globalThis.String(e.id):"",channelIds:globalThis.Array.isArray(null==e?void 0:e.channelIds)?e.channelIds.map((e=>globalThis.String(e))):[],producers:globalThis.Array.isArray(null==e?void 0:e.producers)?e.producers.map((e=>ds.fromJSON(e))):[],uid:vs(e.uid)?globalThis.String(e.uid):"",appId:vs(e.appId)?globalThis.String(e.appId):"",appData:(t=e.appData,"object"==typeof t&&null!==t?Object.entries(e.appData).reduce(((e,[t,r])=>(e[t]=r,e)),{}):{}),role:vs(e.role)?ps(e.role):0,loginDate:vs(e.loginDate)?gs(e.loginDate):void 0,groups:globalThis.Array.isArray(null==e?void 0:e.groups)?e.groups.map((e=>Xi(e))):[],producePermissions:globalThis.Array.isArray(null==e?void 0:e.producePermissions)?e.producePermissions.map((e=>ts(e))):[]};var t},toJSON(e){var t,r,n,i;const s={};if(""!==e.id&&(s.id=e.id),(null===(t=e.channelIds)||void 0===t?void 0:t.length)&&(s.channelIds=e.channelIds),(null===(r=e.producers)||void 0===r?void 0:r.length)&&(s.producers=e.producers.map((e=>ds.toJSON(e)))),""!==e.uid&&(s.uid=e.uid),""!==e.appId&&(s.appId=e.appId),e.appData){const t=Object.entries(e.appData);t.length>0&&(s.appData={},t.forEach((([e,t])=>{s.appData[e]=t})))}return 0!==e.role&&(s.role=function(e){switch(e){case ls.PEER_ROLE_UNSPECIFIED:return"PEER_ROLE_UNSPECIFIED";case ls.PEER_ROLE_HOST:return"PEER_ROLE_HOST";case ls.PEER_ROLE_AUDIENCE:return"PEER_ROLE_AUDIENCE";case ls.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.role)),void 0!==e.loginDate&&(s.loginDate=e.loginDate.toISOString()),(null===(n=e.groups)||void 0===n?void 0:n.length)&&(s.groups=e.groups.map((e=>es(e)))),(null===(i=e.producePermissions)||void 0===i?void 0:i.length)&&(s.producePermissions=e.producePermissions.map((e=>rs(e)))),s},create:e=>hs.fromPartial(null!=e?e:{}),fromPartial(e){var t,r,n,i,s,o,a,c,d,u;const l={id:"",channelIds:[],producers:[],uid:"",appId:"",appData:{},role:0,loginDate:void 0,groups:[],producePermissions:[]};return l.id=null!==(t=e.id)&&void 0!==t?t:"",l.channelIds=(null===(r=e.channelIds)||void 0===r?void 0:r.map((e=>e)))||[],l.producers=(null===(n=e.producers)||void 0===n?void 0:n.map((e=>ds.fromPartial(e))))||[],l.uid=null!==(i=e.uid)&&void 0!==i?i:"",l.appId=null!==(s=e.appId)&&void 0!==s?s:"",l.appData=Object.entries(null!==(o=e.appData)&&void 0!==o?o:{}).reduce(((e,[t,r])=>(void 0!==r&&(e[t]=r),e)),{}),l.role=null!==(a=e.role)&&void 0!==a?a:0,l.loginDate=null!==(c=e.loginDate)&&void 0!==c?c:void 0,l.groups=(null===(d=e.groups)||void 0===d?void 0:d.map((e=>e)))||[],l.producePermissions=(null===(u=e.producePermissions)||void 0===u?void 0:u.map((e=>e)))||[],l}};const fs={encode:(e,t=new Ni)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&qi.encode(qi.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={key:"",value:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.key=r.string();continue;case 2:if(18!==e)break;i.value=qi.unwrap(qi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:vs(e.key)?globalThis.String(e.key):"",value:vs(null==e?void 0:e.value)?e.value:void 0}),toJSON(e){const t={};return""!==e.key&&(t.key=e.key),void 0!==e.value&&(t.value=e.value),t},create:e=>fs.fromPartial(null!=e?e:{}),fromPartial(e){var t,r;const n={key:"",value:void 0};return n.key=null!==(t=e.key)&&void 0!==t?t:"",n.value=null!==(r=e.value)&&void 0!==r?r:void 0,n}};function ms(e){let t=1e3*(e.seconds||0);return t+=(e.nanos||0)/1e6,new globalThis.Date(t)}function gs(e){return e instanceof globalThis.Date?e:"string"==typeof e?new globalThis.Date(e):ms(is.fromJSON(e))}function vs(e){return null!=e}const ys={encode(e,t=new Ni){for(const r of e.peers)hs.encode(r,t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={peers:[]};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.peers.push(hs.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({peers:globalThis.Array.isArray(null==e?void 0:e.peers)?e.peers.map((e=>hs.fromJSON(e))):[]}),toJSON(e){var t;const r={};return(null===(t=e.peers)||void 0===t?void 0:t.length)&&(r.peers=e.peers.map((e=>hs.toJSON(e)))),r},create:e=>ys.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={peers:[]};return r.peers=(null===(t=e.peers)||void 0===t?void 0:t.map((e=>hs.fromPartial(e))))||[],r}};const bs={encode:(e,t=new Ni)=>(""!==e.id&&t.uint32(10).string(e.id),!1!==e.paused&&t.uint32(16).bool(e.paused),t),decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={id:"",paused:!1};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.id=r.string();continue;case 2:if(16!==e)break;i.paused=r.bool();continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({id:ws(e.id)?globalThis.String(e.id):"",paused:!!ws(e.paused)&&globalThis.Boolean(e.paused)}),toJSON(e){const t={};return""!==e.id&&(t.id=e.id),!1!==e.paused&&(t.paused=e.paused),t},create:e=>bs.fromPartial(null!=e?e:{}),fromPartial(e){var t,r;const n={id:"",paused:!1};return n.id=null!==(t=e.id)&&void 0!==t?t:"",n.paused=null!==(r=e.paused)&&void 0!==r&&r,n}};const _s={encode(e,t=new Ni){""!==e.id&&t.uint32(10).string(e.id);for(const r of e.producers)bs.encode(r,t.uint32(18).fork()).join();return void 0!==e.appDataHash&&t.uint32(26).string(e.appDataHash),t},decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={id:"",producers:[],appDataHash:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.id=r.string();continue;case 2:if(18!==e)break;i.producers.push(bs.decode(r,r.uint32()));continue;case 3:if(26!==e)break;i.appDataHash=r.string();continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({id:ws(e.id)?globalThis.String(e.id):"",producers:globalThis.Array.isArray(null==e?void 0:e.producers)?e.producers.map((e=>bs.fromJSON(e))):[],appDataHash:ws(e.appDataHash)?globalThis.String(e.appDataHash):void 0}),toJSON(e){var t;const r={};return""!==e.id&&(r.id=e.id),(null===(t=e.producers)||void 0===t?void 0:t.length)&&(r.producers=e.producers.map((e=>bs.toJSON(e)))),void 0!==e.appDataHash&&(r.appDataHash=e.appDataHash),r},create:e=>_s.fromPartial(null!=e?e:{}),fromPartial(e){var t,r,n;const i={id:"",producers:[],appDataHash:void 0};return i.id=null!==(t=e.id)&&void 0!==t?t:"",i.producers=(null===(r=e.producers)||void 0===r?void 0:r.map((e=>bs.fromPartial(e))))||[],i.appDataHash=null!==(n=e.appDataHash)&&void 0!==n?n:void 0,i}};const Es={encode(e,t=new Ni){for(const r of e.peers)_s.encode(r,t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={peers:[]};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.peers.push(_s.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({peers:globalThis.Array.isArray(null==e?void 0:e.peers)?e.peers.map((e=>_s.fromJSON(e))):[]}),toJSON(e){var t;const r={};return(null===(t=e.peers)||void 0===t?void 0:t.length)&&(r.peers=e.peers.map((e=>_s.toJSON(e)))),r},create:e=>Es.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={peers:[]};return r.peers=(null===(t=e.peers)||void 0===t?void 0:t.map((e=>_s.fromPartial(e))))||[],r}};function ws(e){return null!=e}var Ss;function Cs(e){switch(e){case 0:case"CHANNEL_EVENT_TYPE_UNSPECIFIED":return Ss.CHANNEL_EVENT_TYPE_UNSPECIFIED;case 1:case"CHANNEL_EVENT_TYPE_CHANNEL_STATE":return Ss.CHANNEL_EVENT_TYPE_CHANNEL_STATE;case 2:case"CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT":return Ss.CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT;case 3:case"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED":return Ss.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED;case 4:case"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED":return Ss.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED;case 5:case"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED":return Ss.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED;case 6:case"CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED":return Ss.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED;case 7:case"CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED":return Ss.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED;case 8:case"CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT":return Ss.CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT;case 14:case"CHANNEL_EVENT_TYPE_PEER_JOINED":return Ss.CHANNEL_EVENT_TYPE_PEER_JOINED;case 15:case"CHANNEL_EVENT_TYPE_PEER_LEFT":return Ss.CHANNEL_EVENT_TYPE_PEER_LEFT;case 16:case"CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED":return Ss.CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED;case 17:case"CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED":return Ss.CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED;case 18:case"CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED":return Ss.CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED;default:return Ss.UNRECOGNIZED}}function Ps(e){switch(e){case Ss.CHANNEL_EVENT_TYPE_UNSPECIFIED:return"CHANNEL_EVENT_TYPE_UNSPECIFIED";case Ss.CHANNEL_EVENT_TYPE_CHANNEL_STATE:return"CHANNEL_EVENT_TYPE_CHANNEL_STATE";case Ss.CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT:return"CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT";case Ss.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED:return"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED";case Ss.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED:return"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED";case Ss.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED:return"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED";case Ss.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED:return"CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED";case Ss.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED:return"CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED";case Ss.CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT:return"CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT";case Ss.CHANNEL_EVENT_TYPE_PEER_JOINED:return"CHANNEL_EVENT_TYPE_PEER_JOINED";case Ss.CHANNEL_EVENT_TYPE_PEER_LEFT:return"CHANNEL_EVENT_TYPE_PEER_LEFT";case Ss.CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED:return"CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED";case Ss.CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED:return"CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED";case Ss.CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED:return"CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED";case Ss.UNRECOGNIZED:default:return"UNRECOGNIZED"}}!function(e){e[e.CHANNEL_EVENT_TYPE_UNSPECIFIED=0]="CHANNEL_EVENT_TYPE_UNSPECIFIED",e[e.CHANNEL_EVENT_TYPE_CHANNEL_STATE=1]="CHANNEL_EVENT_TYPE_CHANNEL_STATE",e[e.CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT=2]="CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT",e[e.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED=3]="CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED",e[e.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED=4]="CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED",e[e.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED=5]="CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED",e[e.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED=6]="CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED",e[e.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED=7]="CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED",e[e.CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT=8]="CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT",e[e.CHANNEL_EVENT_TYPE_PEER_JOINED=14]="CHANNEL_EVENT_TYPE_PEER_JOINED",e[e.CHANNEL_EVENT_TYPE_PEER_LEFT=15]="CHANNEL_EVENT_TYPE_PEER_LEFT",e[e.CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED=16]="CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED",e[e.CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED=17]="CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED",e[e.CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED=18]="CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ss||(Ss={}));const Ts={encode:(e,t=new Ni)=>(0!==e.eventType&&t.uint32(8).int32(e.eventType),void 0!==e.channelState&&ys.encode(e.channelState,t.uint32(18).fork()).join(),void 0!==e.channelStateShort&&Es.encode(e.channelStateShort,t.uint32(26).fork()).join(),void 0!==e.channelActivityConfirmationTime&&ji.encode(e.channelActivityConfirmationTime,t.uint32(34).fork()).join(),void 0!==e.channelManagementEvent&&$i.encode(e.channelManagementEvent,t.uint32(42).fork()).join(),void 0!==e.channelProducePermissions&&ns.encode(e.channelProducePermissions,t.uint32(50).fork()).join(),void 0!==e.peer&&hs.encode(e.peer,t.uint32(58).fork()).join(),t),decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={eventType:0,channelState:void 0,channelStateShort:void 0,channelActivityConfirmationTime:void 0,channelManagementEvent:void 0,channelProducePermissions:void 0,peer:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(8!==e)break;i.eventType=r.int32();continue;case 2:if(18!==e)break;i.channelState=ys.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.channelStateShort=Es.decode(r,r.uint32());continue;case 4:if(34!==e)break;i.channelActivityConfirmationTime=ji.decode(r,r.uint32());continue;case 5:if(42!==e)break;i.channelManagementEvent=$i.decode(r,r.uint32());continue;case 6:if(50!==e)break;i.channelProducePermissions=ns.decode(r,r.uint32());continue;case 7:if(58!==e)break;i.peer=hs.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({eventType:Rs(e.eventType)?Cs(e.eventType):0,channelState:Rs(e.channelState)?ys.fromJSON(e.channelState):void 0,channelStateShort:Rs(e.channelStateShort)?Es.fromJSON(e.channelStateShort):void 0,channelActivityConfirmationTime:Rs(e.channelActivityConfirmationTime)?ji.fromJSON(e.channelActivityConfirmationTime):void 0,channelManagementEvent:Rs(e.channelManagementEvent)?$i.fromJSON(e.channelManagementEvent):void 0,channelProducePermissions:Rs(e.channelProducePermissions)?ns.fromJSON(e.channelProducePermissions):void 0,peer:Rs(e.peer)?hs.fromJSON(e.peer):void 0}),toJSON(e){const t={};return 0!==e.eventType&&(t.eventType=Ps(e.eventType)),void 0!==e.channelState&&(t.channelState=ys.toJSON(e.channelState)),void 0!==e.channelStateShort&&(t.channelStateShort=Es.toJSON(e.channelStateShort)),void 0!==e.channelActivityConfirmationTime&&(t.channelActivityConfirmationTime=ji.toJSON(e.channelActivityConfirmationTime)),void 0!==e.channelManagementEvent&&(t.channelManagementEvent=$i.toJSON(e.channelManagementEvent)),void 0!==e.channelProducePermissions&&(t.channelProducePermissions=ns.toJSON(e.channelProducePermissions)),void 0!==e.peer&&(t.peer=hs.toJSON(e.peer)),t},create:e=>Ts.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={eventType:0,channelState:void 0,channelStateShort:void 0,channelActivityConfirmationTime:void 0,channelManagementEvent:void 0,channelProducePermissions:void 0,peer:void 0};return r.eventType=null!==(t=e.eventType)&&void 0!==t?t:0,r.channelState=void 0!==e.channelState&&null!==e.channelState?ys.fromPartial(e.channelState):void 0,r.channelStateShort=void 0!==e.channelStateShort&&null!==e.channelStateShort?Es.fromPartial(e.channelStateShort):void 0,r.channelActivityConfirmationTime=void 0!==e.channelActivityConfirmationTime&&null!==e.channelActivityConfirmationTime?ji.fromPartial(e.channelActivityConfirmationTime):void 0,r.channelManagementEvent=void 0!==e.channelManagementEvent&&null!==e.channelManagementEvent?$i.fromPartial(e.channelManagementEvent):void 0,r.channelProducePermissions=void 0!==e.channelProducePermissions&&null!==e.channelProducePermissions?ns.fromPartial(e.channelProducePermissions):void 0,r.peer=void 0!==e.peer&&null!==e.peer?hs.fromPartial(e.peer):void 0,r}};function Rs(e){return null!=e}const ks={encode:(e,t=new Ni)=>(""!==e.id&&t.uint32(10).string(e.id),""!==e.peerId&&t.uint32(18).string(e.peerId),""!==e.producerPeerId&&t.uint32(26).string(e.producerPeerId),void 0!==e.spatialLayer&&t.uint32(32).uint32(e.spatialLayer),void 0!==e.temporalLayer&&t.uint32(40).uint32(e.temporalLayer),t),decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={id:"",peerId:"",producerPeerId:"",spatialLayer:void 0,temporalLayer:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.id=r.string();continue;case 2:if(18!==e)break;i.peerId=r.string();continue;case 3:if(26!==e)break;i.producerPeerId=r.string();continue;case 4:if(32!==e)break;i.spatialLayer=r.uint32();continue;case 5:if(40!==e)break;i.temporalLayer=r.uint32();continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({id:Ds(e.id)?globalThis.String(e.id):"",peerId:Ds(e.peerId)?globalThis.String(e.peerId):"",producerPeerId:Ds(e.producerPeerId)?globalThis.String(e.producerPeerId):"",spatialLayer:Ds(e.spatialLayer)?globalThis.Number(e.spatialLayer):void 0,temporalLayer:Ds(e.temporalLayer)?globalThis.Number(e.temporalLayer):void 0}),toJSON(e){const t={};return""!==e.id&&(t.id=e.id),""!==e.peerId&&(t.peerId=e.peerId),""!==e.producerPeerId&&(t.producerPeerId=e.producerPeerId),void 0!==e.spatialLayer&&(t.spatialLayer=Math.round(e.spatialLayer)),void 0!==e.temporalLayer&&(t.temporalLayer=Math.round(e.temporalLayer)),t},create:e=>ks.fromPartial(null!=e?e:{}),fromPartial(e){var t,r,n,i,s;const o={id:"",peerId:"",producerPeerId:"",spatialLayer:void 0,temporalLayer:void 0};return o.id=null!==(t=e.id)&&void 0!==t?t:"",o.peerId=null!==(r=e.peerId)&&void 0!==r?r:"",o.producerPeerId=null!==(n=e.producerPeerId)&&void 0!==n?n:"",o.spatialLayer=null!==(i=e.spatialLayer)&&void 0!==i?i:void 0,o.temporalLayer=null!==(s=e.temporalLayer)&&void 0!==s?s:void 0,o}};function Ds(e){return null!=e}const Is={encode:(e,t=new Ni)=>(""!==e.producerId&&t.uint32(10).string(e.producerId),0!==e.spatialLayer&&t.uint32(16).uint32(e.spatialLayer),t),decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={producerId:"",spatialLayer:0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.producerId=r.string();continue;case 2:if(16!==e)break;i.spatialLayer=r.uint32();continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({producerId:As(e.producerId)?globalThis.String(e.producerId):"",spatialLayer:As(e.spatialLayer)?globalThis.Number(e.spatialLayer):0}),toJSON(e){const t={};return""!==e.producerId&&(t.producerId=e.producerId),0!==e.spatialLayer&&(t.spatialLayer=Math.round(e.spatialLayer)),t},create:e=>Is.fromPartial(null!=e?e:{}),fromPartial(e){var t,r;const n={producerId:"",spatialLayer:0};return n.producerId=null!==(t=e.producerId)&&void 0!==t?t:"",n.spatialLayer=null!==(r=e.spatialLayer)&&void 0!==r?r:0,n}};function As(e){return null!=e}var Os,Ms;function Ns(e){switch(e){case 0:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED":return Os.TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED;case 1:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS":return Os.TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS;case 2:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE":return Os.TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE;default:return Os.UNRECOGNIZED}}function Ls(e){switch(e){case 0:case"TRANSPORT_DIRECTION_UNSPECIFIED":return Ms.TRANSPORT_DIRECTION_UNSPECIFIED;case 1:case"TRANSPORT_DIRECTION_SEND":return Ms.TRANSPORT_DIRECTION_SEND;case 2:case"TRANSPORT_DIRECTION_RECEIVE":return Ms.TRANSPORT_DIRECTION_RECEIVE;default:return Ms.UNRECOGNIZED}}!function(e){e[e.TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED=0]="TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED",e[e.TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS=1]="TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS",e[e.TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE=2]="TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Os||(Os={})),function(e){e[e.TRANSPORT_DIRECTION_UNSPECIFIED=0]="TRANSPORT_DIRECTION_UNSPECIFIED",e[e.TRANSPORT_DIRECTION_SEND=1]="TRANSPORT_DIRECTION_SEND",e[e.TRANSPORT_DIRECTION_RECEIVE=2]="TRANSPORT_DIRECTION_RECEIVE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ms||(Ms={}));const xs={encode:(e,t=new Ni)=>(""!==e.transportId&&t.uint32(10).string(e.transportId),0!==e.timeout&&t.uint32(16).uint32(e.timeout),0!==e.direction&&t.uint32(24).int32(e.direction),0!==e.reason&&t.uint32(32).int32(e.reason),t),decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={transportId:"",timeout:0,direction:0,reason:0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.transportId=r.string();continue;case 2:if(16!==e)break;i.timeout=r.uint32();continue;case 3:if(24!==e)break;i.direction=r.int32();continue;case 4:if(32!==e)break;i.reason=r.int32();continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({transportId:Fs(e.transportId)?globalThis.String(e.transportId):"",timeout:Fs(e.timeout)?globalThis.Number(e.timeout):0,direction:Fs(e.direction)?Ls(e.direction):0,reason:Fs(e.reason)?Ns(e.reason):0}),toJSON(e){const t={};return""!==e.transportId&&(t.transportId=e.transportId),0!==e.timeout&&(t.timeout=Math.round(e.timeout)),0!==e.direction&&(t.direction=function(e){switch(e){case Ms.TRANSPORT_DIRECTION_UNSPECIFIED:return"TRANSPORT_DIRECTION_UNSPECIFIED";case Ms.TRANSPORT_DIRECTION_SEND:return"TRANSPORT_DIRECTION_SEND";case Ms.TRANSPORT_DIRECTION_RECEIVE:return"TRANSPORT_DIRECTION_RECEIVE";case Ms.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.direction)),0!==e.reason&&(t.reason=function(e){switch(e){case Os.TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED";case Os.TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS";case Os.TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE";case Os.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.reason)),t},create:e=>xs.fromPartial(null!=e?e:{}),fromPartial(e){var t,r,n,i;const s={transportId:"",timeout:0,direction:0,reason:0};return s.transportId=null!==(t=e.transportId)&&void 0!==t?t:"",s.timeout=null!==(r=e.timeout)&&void 0!==r?r:0,s.direction=null!==(n=e.direction)&&void 0!==n?n:0,s.reason=null!==(i=e.reason)&&void 0!==i?i:0,s}};function Fs(e){return null!=e}var js;function Us(e){switch(e){case 0:case"MEDIA_EVENT_TYPE_UNSPECIFIED":return js.MEDIA_EVENT_TYPE_UNSPECIFIED;case 1:case"MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT":return js.MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT;case 2:case"MEDIA_EVENT_TYPE_PRODUCER_CREATED":return js.MEDIA_EVENT_TYPE_PRODUCER_CREATED;case 3:case"MEDIA_EVENT_TYPE_PRODUCER_PAUSED":return js.MEDIA_EVENT_TYPE_PRODUCER_PAUSED;case 4:case"MEDIA_EVENT_TYPE_PRODUCER_RESUMED":return js.MEDIA_EVENT_TYPE_PRODUCER_RESUMED;case 5:case"MEDIA_EVENT_TYPE_PRODUCER_CLOSED":return js.MEDIA_EVENT_TYPE_PRODUCER_CLOSED;case 6:case"MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED":return js.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED;case 7:case"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED":return js.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED;case 8:case"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED":return js.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED;case 9:case"MEDIA_EVENT_TYPE_CONSUMER_CLOSED":return js.MEDIA_EVENT_TYPE_CONSUMER_CLOSED;case 10:case"MEDIA_EVENT_TYPE_CONSUMER_PAUSED":return js.MEDIA_EVENT_TYPE_CONSUMER_PAUSED;case 11:case"MEDIA_EVENT_TYPE_CONSUMER_RESUMED":return js.MEDIA_EVENT_TYPE_CONSUMER_RESUMED;case 12:case"MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED":return js.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED;default:return js.UNRECOGNIZED}}function Vs(e){switch(e){case js.MEDIA_EVENT_TYPE_UNSPECIFIED:return"MEDIA_EVENT_TYPE_UNSPECIFIED";case js.MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT:return"MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT";case js.MEDIA_EVENT_TYPE_PRODUCER_CREATED:return"MEDIA_EVENT_TYPE_PRODUCER_CREATED";case js.MEDIA_EVENT_TYPE_PRODUCER_PAUSED:return"MEDIA_EVENT_TYPE_PRODUCER_PAUSED";case js.MEDIA_EVENT_TYPE_PRODUCER_RESUMED:return"MEDIA_EVENT_TYPE_PRODUCER_RESUMED";case js.MEDIA_EVENT_TYPE_PRODUCER_CLOSED:return"MEDIA_EVENT_TYPE_PRODUCER_CLOSED";case js.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED:return"MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED";case js.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED:return"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED";case js.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED:return"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED";case js.MEDIA_EVENT_TYPE_CONSUMER_CLOSED:return"MEDIA_EVENT_TYPE_CONSUMER_CLOSED";case js.MEDIA_EVENT_TYPE_CONSUMER_PAUSED:return"MEDIA_EVENT_TYPE_CONSUMER_PAUSED";case js.MEDIA_EVENT_TYPE_CONSUMER_RESUMED:return"MEDIA_EVENT_TYPE_CONSUMER_RESUMED";case js.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED:return"MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED";case js.UNRECOGNIZED:default:return"UNRECOGNIZED"}}!function(e){e[e.MEDIA_EVENT_TYPE_UNSPECIFIED=0]="MEDIA_EVENT_TYPE_UNSPECIFIED",e[e.MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT=1]="MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT",e[e.MEDIA_EVENT_TYPE_PRODUCER_CREATED=2]="MEDIA_EVENT_TYPE_PRODUCER_CREATED",e[e.MEDIA_EVENT_TYPE_PRODUCER_PAUSED=3]="MEDIA_EVENT_TYPE_PRODUCER_PAUSED",e[e.MEDIA_EVENT_TYPE_PRODUCER_RESUMED=4]="MEDIA_EVENT_TYPE_PRODUCER_RESUMED",e[e.MEDIA_EVENT_TYPE_PRODUCER_CLOSED=5]="MEDIA_EVENT_TYPE_PRODUCER_CLOSED",e[e.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED=6]="MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED",e[e.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED=7]="MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED",e[e.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED=8]="MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED",e[e.MEDIA_EVENT_TYPE_CONSUMER_CLOSED=9]="MEDIA_EVENT_TYPE_CONSUMER_CLOSED",e[e.MEDIA_EVENT_TYPE_CONSUMER_PAUSED=10]="MEDIA_EVENT_TYPE_CONSUMER_PAUSED",e[e.MEDIA_EVENT_TYPE_CONSUMER_RESUMED=11]="MEDIA_EVENT_TYPE_CONSUMER_RESUMED",e[e.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED=12]="MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(js||(js={}));const Bs={encode:(e,t=new Ni)=>(0!==e.eventType&&t.uint32(8).int32(e.eventType),void 0!==e.producer&&ds.encode(e.producer,t.uint32(18).fork()).join(),void 0!==e.consumer&&ks.encode(e.consumer,t.uint32(26).fork()).join(),void 0!==e.producerSpatialLayerRequest&&Is.encode(e.producerSpatialLayerRequest,t.uint32(34).fork()).join(),void 0!==e.transportConnectionTimeout&&xs.encode(e.transportConnectionTimeout,t.uint32(42).fork()).join(),t),decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={eventType:0,producer:void 0,consumer:void 0,producerSpatialLayerRequest:void 0,transportConnectionTimeout:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(8!==e)break;i.eventType=r.int32();continue;case 2:if(18!==e)break;i.producer=ds.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.consumer=ks.decode(r,r.uint32());continue;case 4:if(34!==e)break;i.producerSpatialLayerRequest=Is.decode(r,r.uint32());continue;case 5:if(42!==e)break;i.transportConnectionTimeout=xs.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({eventType:Ws(e.eventType)?Us(e.eventType):0,producer:Ws(e.producer)?ds.fromJSON(e.producer):void 0,consumer:Ws(e.consumer)?ks.fromJSON(e.consumer):void 0,producerSpatialLayerRequest:Ws(e.producerSpatialLayerRequest)?Is.fromJSON(e.producerSpatialLayerRequest):void 0,transportConnectionTimeout:Ws(e.transportConnectionTimeout)?xs.fromJSON(e.transportConnectionTimeout):void 0}),toJSON(e){const t={};return 0!==e.eventType&&(t.eventType=Vs(e.eventType)),void 0!==e.producer&&(t.producer=ds.toJSON(e.producer)),void 0!==e.consumer&&(t.consumer=ks.toJSON(e.consumer)),void 0!==e.producerSpatialLayerRequest&&(t.producerSpatialLayerRequest=Is.toJSON(e.producerSpatialLayerRequest)),void 0!==e.transportConnectionTimeout&&(t.transportConnectionTimeout=xs.toJSON(e.transportConnectionTimeout)),t},create:e=>Bs.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={eventType:0,producer:void 0,consumer:void 0,producerSpatialLayerRequest:void 0,transportConnectionTimeout:void 0};return r.eventType=null!==(t=e.eventType)&&void 0!==t?t:0,r.producer=void 0!==e.producer&&null!==e.producer?ds.fromPartial(e.producer):void 0,r.consumer=void 0!==e.consumer&&null!==e.consumer?ks.fromPartial(e.consumer):void 0,r.producerSpatialLayerRequest=void 0!==e.producerSpatialLayerRequest&&null!==e.producerSpatialLayerRequest?Is.fromPartial(e.producerSpatialLayerRequest):void 0,r.transportConnectionTimeout=void 0!==e.transportConnectionTimeout&&null!==e.transportConnectionTimeout?xs.fromPartial(e.transportConnectionTimeout):void 0,r}};function Ws(e){return null!=e}const Hs={encode:(e,t=new Ni)=>(0!==e.id&&t.uint32(8).int32(e.id),void 0!==e.channelEvent&&Ts.encode(e.channelEvent,t.uint32(18).fork()).join(),void 0!==e.mediaEvent&&Bs.encode(e.mediaEvent,t.uint32(26).fork()).join(),t),decode(e,t){const r=e instanceof Li?e:new Li(e),n=void 0===t?r.len:r.pos+t,i={id:0,channelEvent:void 0,mediaEvent:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(8!==e)break;i.id=r.int32();continue;case 2:if(18!==e)break;i.channelEvent=Ts.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.mediaEvent=Bs.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({id:qs(e.id)?globalThis.Number(e.id):0,channelEvent:qs(e.channelEvent)?Ts.fromJSON(e.channelEvent):void 0,mediaEvent:qs(e.mediaEvent)?Bs.fromJSON(e.mediaEvent):void 0}),toJSON(e){const t={};return 0!==e.id&&(t.id=Math.round(e.id)),void 0!==e.channelEvent&&(t.channelEvent=Ts.toJSON(e.channelEvent)),void 0!==e.mediaEvent&&(t.mediaEvent=Bs.toJSON(e.mediaEvent)),t},create:e=>Hs.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={id:0,channelEvent:void 0,mediaEvent:void 0};return r.id=null!==(t=e.id)&&void 0!==t?t:0,r.channelEvent=void 0!==e.channelEvent&&null!==e.channelEvent?Ts.fromPartial(e.channelEvent):void 0,r.mediaEvent=void 0!==e.mediaEvent&&null!==e.mediaEvent?Bs.fromPartial(e.mediaEvent):void 0,r}};function qs(e){return null!=e}var zs,Gs,Ys,$s,Js,Qs,Ks,Zs;let Xs=class{constructor(e){zs.set(this,[]),Gs.set(this,!1),Ys.set(this,!1),$s.set(this,void 0),Js.set(this,void 0),Qs.set(this,new Map),Ks.set(this,void 0),Zs.set(this,new Set),c(this,Ks,e("EventsQueue"),"f")}setMediaEventHandler(e){c(this,$s,e,"f"),a(this,Ks,"f").info("Media event handler set",{case:"EventsQueue"})}setChannelEventHandler(e){c(this,Js,e,"f"),a(this,Ks,"f").info("Channel event handler set",{case:"EventsQueue"})}subscribe(e){c(this,Zs,new Set,"f");let t=0;const r=e=>{try{const r=this.processMessageChunk(e);if(!r||!this.isPendingMessageFullyReceived(r))return;const n=this.finalizeMessageBytes(r),i=Hs.decode(n);i.id&&(a(this,Zs,"f").has(i.id)&&a(this,Ks,"f").warn("Received duplicate message",{case:"EventsQueue",lastReceivedMsgId:t,currentReceivedMsgId:i.id}),i.id>t+1&&a(this,Ks,"f").warn("Received out of order message",{case:"EventsQueue",lastReceivedMsgId:t,currentReceivedMsgId:i.id})),a(this,Zs,"f").add(i.id),t=i.id,this.push(i)}catch(e){a(this,Ks,"f").error("Failed to parse channel message",{error:Vt(e),case:"EventsQueue"})}},n=()=>{e.removeListener("message",r),e.removeListener("close",n)};e.on("close",n),e.on("message",r),a(this,Ks,"f").info("Subscribed to data channel",{case:"EventsQueue"})}push(e){a(this,zs,"f").push(e),this.process()}process(){return o(this,void 0,void 0,(function*(){if(!a(this,Gs,"f")&&!a(this,Ys,"f")){for(c(this,Ys,!0,"f");!a(this,Gs,"f")&&a(this,zs,"f").length>0;){const e=a(this,zs,"f").shift();if(e)try{if(e.channelEvent&&a(this,Js,"f")){a(this,Ks,"f").debug("Handle channel event",{case:"EventsQueue",id:e.id,type:Ps(e.channelEvent.eventType),event:e.channelEvent}),yield a(this,Js,"f").call(this,e.channelEvent);continue}if(e.mediaEvent&&a(this,$s,"f")){a(this,Ks,"f").debug("Handle media event",{case:"EventsQueue",id:e.id,type:Vs(e.mediaEvent.eventType),event:e.mediaEvent}),yield a(this,$s,"f").call(this,e.mediaEvent);continue}a(this,Ks,"f").warn("Received unknown message",{message:e,case:"EventsQueue"})}catch(t){a(this,Ks,"f").error("Failed to handle event",{case:"EventsQueue",id:e.id,error:Vt(t)})}}c(this,Ys,!1,"f"),!a(this,Gs,"f")&&a(this,zs,"f").length>0&&queueMicrotask((()=>{this.process()}))}}))}processMessageChunk(e){const t=new Uint8Array(e);if(t.length<12)return void a(this,Ks,"f").warn("Chunk too small",{case:"EventsQueue",bytesLength:t.length});const{msgId:r,index:n,total:i}=this.parseMessageChunkHeader(t),s=t.slice(12);a(this,Qs,"f").has(r)||a(this,Qs,"f").set(r,{msgId:r,total:i,received:[]});const o=a(this,Qs,"f").get(r);if(o)return o.received[n]=s,o.msgId=r,o;a(this,Ks,"f").warn("Chunk buffer entry not found for msgId",{msgId:r,case:"EventsQueue"})}parseMessageChunkHeader(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{msgId:t.getUint32(0),index:t.getUint32(4),total:t.getUint32(8)}}isPendingMessageFullyReceived(e){return e.received.filter(Boolean).length===e.total}finalizeMessageBytes(e){const t=new Uint8Array(e.received.reduce(((e,t)=>e+t.length),0));let r=0;for(const n of e.received)t.set(n,r),r+=n.length;return a(this,Qs,"f").delete(e.msgId),t}pause(){c(this,Gs,!0,"f")}size(){return a(this,zs,"f").length}resume(){c(this,Gs,!1,"f"),this.process()}isMessageReceived(e){return a(this,Zs,"f").has(e)}};zs=new WeakMap,Gs=new WeakMap,Ys=new WeakMap,$s=new WeakMap,Js=new WeakMap,Qs=new WeakMap,Ks=new WeakMap,Zs=new WeakMap,Xs=n([ot(),i(0,ct(fi.LoggerFactory)),s("design:paramtypes",[Function])],Xs);var eo=Xs;function to(e){return{id:e.id,appId:e.appId,role:e.role,groups:e.groups,producePermissions:e.producePermissions}}let ro=class{get(){return this.peer}set(e){this.peer=e}delete(){this.peer=void 0}get canPublish(){var e;return"host"===(null===(e=this.peer)||void 0===e?void 0:e.role)}};ro=n([ot()],ro);const no=["no media section found for reuseMid","Duplicate a=msid lines detected"];class io extends Gn{constructor(e,t,r){super(null!=e?e:io.DEFAULT_MESSAGE,null!=t?t:"already_connected",r)}}var so,oo,ao;io.DEFAULT_MESSAGE="Peer is already connected";let co=class{constructor(e,t,r,n,i,s,o,a,d){this.state=e,this.myPeer=t,this.clientEventEmitter=n,this.dataChannelsManager=i,this.signalingApiClient=s,this.datachannelHeartbeater=o,this.signalingHeartbeater=a,this.iceRecoveryService=d,so.set(this,0),oo.set(this,void 0),ao.set(this,void 0),this.peersLoaded=!1,c(this,ao,r("Network"),"f"),c(this,oo,new Ft,"f")}get isNetworkActive(){var e,t,r,n;return["connected","new"].includes(null!==(t=null===(e=this.receiveTransport)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"")&&["connected","new"].includes(null!==(n=null===(r=this.sendTransport)||void 0===r?void 0:r.connectionState)&&void 0!==n?n:"")}get observer(){return a(this,oo,"f")}removeEventListeners(){const{sendTransport:e,receiveTransport:t,signalingTransport:r}=this;if(e){["connect","produce","connectionstatechange"].forEach((t=>e.removeAllListeners(t)))}if(t){["connect","produce","connectionstatechange"].forEach((e=>t.removeAllListeners(e)))}if(r){["connect","produce","producedata","connectionstatechange"].forEach((e=>r.removeAllListeners(e)))}}reset(){this.datachannelHeartbeater.dispose(),this.signalingHeartbeater.dispose(),this.heartbeatDataProducer=void 0,this.peersLoaded=!1,this.stopRestartIceAttempts(),this.removeEventListeners(),this.closeAllDataChannels(),this.closeSendTransport(),this.closeReceiveTransport(),this.closeConnectionTransport()}closeRemoteProducer(e){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.closeProducer(e)}))}closeSendTransport(){this.sendTransport?(this.closeTransport(this.sendTransport),this.sendTransport=void 0):a(this,ao,"f").debug("closeSendTransport()",{message:"No available send transport"})}closeReceiveTransport(){this.receiveTransport?(this.closeTransport(this.receiveTransport),this.receiveTransport=void 0):a(this,ao,"f").debug("closeReceiveTransport()",{message:"No available receive transport"})}closeConnectionTransport(){this.signalingTransport?(this.closeTransport(this.signalingTransport),this.signalingTransport=void 0):a(this,ao,"f").debug("closeConnectionTransport()",{message:"No available connection transport"})}closeTransport(e){try{e.close(),a(this,ao,"f").debug("closeTransport()",{transportId:e.id,direction:e.direction})}catch(t){a(this,ao,"f").error("closeTransport()",{error:t,transportId:e.id,direction:e.direction})}}createSendTransport(e){return o(this,void 0,void 0,(function*(){this.sendTransport&&(a(this,ao,"f").warn("createSendTransport()",{message:"Send transport already exists, closing previous"}),this.closeSendTransport());const{data:t}=yield this.signalingApiClient.transport.createTransport({localDirection:"send"}),r=e.createSendTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return a(this,ao,"f").debug("createSendTransport()",{transportId:r.id,direction:r.direction,preferRelay:this.preferRelay}),this.sendTransport=r,this.subscribeCommonTransportEvents(r),r}))}createRecvTransport(e){return o(this,void 0,void 0,(function*(){this.receiveTransport&&(a(this,ao,"f").warn("createRecvTransport()",{message:"Receive transport already exists, closing previous"}),this.closeReceiveTransport());const{data:t}=yield this.signalingApiClient.transport.createTransport({localDirection:"receive"}),r=e.createRecvTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return a(this,ao,"f").debug("createReceiveTransport()",{transportId:r.id,direction:r.direction,preferRelay:this.preferRelay}),this.receiveTransport=r,this.subscribeCommonTransportEvents(r),r}))}createSignalingTransport(e){return o(this,void 0,void 0,(function*(){this.signalingTransport&&(a(this,ao,"f").warn("createSignalingTransport()",{message:"Signaling transport already exists, closing previous"}),this.closeConnectionTransport());const{data:t}=yield this.signalingApiClient.transport.createTransport({localDirection:"receive",tcpOnly:!0}),r=e.createSendTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return a(this,ao,"f").debug("createConnectionTransport()",{transportId:r.id,direction:r.direction,tcpOnly:!0}),this.signalingTransport=r,this.subscribeCommonTransportEvents(r),r}))}restartIce(e){return o(this,void 0,void 0,(function*(){return yield this.iceRecoveryService.restartIce(e)}))}createConsumer(e){return o(this,arguments,void 0,(function*({producerId:e,rtpCapabilities:t,producerPeerId:r}){const n=this.receiveTransport;if(!n)throw a(this,ao,"f").error("createConsumer()",{reason:"missing receive transport"}),new Error("Failed to create consumer due to missing receive transport");a(this,ao,"f").debug("createConsumer()",{producerId:e});const i=yield this.signalingApiClient.consumer.createConsumer({producerId:e,transportId:n.id,rtpCapabilities:t,producerPeerId:r,forceCloseExisting:!0}).then((({data:e})=>this.toRemoteConsumerOptions(e))).catch((t=>{throw(Qn(t)?a(this,ao,"f").debug.bind(a(this,ao,"f")):a(this,ao,"f").error.bind(a(this,ao,"f")))("Failed to get consumer options",{producerId:e,producerPeerId:r,error:Vt(t)}),t})),s=yield n.consume(i).catch((t=>{throw t instanceof Error&&no.some((e=>t.message.includes(e)))&&(a(this,ao,"f").error("createConsumer() reached irrecoverable mediasoup state",{producerId:e,producerPeerId:r,error:Vt(t)}),this.signalingApiClient.abortPendingRequests("channel-rejoin"),this.clientEventEmitter.safeEmit($r)),t})),{producerPaused:o}=i;return o&&"audio"!==s.kind&&s.pause(),a(this,ao,"f").debug("Consumer created",{consumerId:s.id,label:s.appData.label,isProducerPaused:o}),{consumer:s,isProducerPaused:o}}))}initializeHeartbeats(){return o(this,void 0,void 0,(function*(){this.signalingHeartbeater.start();const e=this.sendTransport;if(!e)throw a(this,ao,"f").error("createHeartbeatProducer()",{reason:"missing send transport"}),new Error("Failed to create data producer");const t=yield e.produceData({label:"heart-beater",protocol:"heartbeat"});this.heartbeatDataProducer=t,t.once("transportclose",(()=>{var e;null===(e=this.heartbeatDataProducer)||void 0===e||e.close(),this.heartbeatDataProducer=void 0,this.datachannelHeartbeater.dispose()})),this.datachannelHeartbeater.init(e,t)}))}createKeepAliveConsumer(){return o(this,void 0,void 0,(function*(){const e=this.signalingTransport;if(!e)return void a(this,ao,"f").error("createKeepAliveConsumer()",{reason:"missing signaling transport"});const t=yield e.produceData({label:"consumers-scores",protocol:"keepalive"});t.once("open",(()=>{t.send(new Uint8Array(0))})),t.once("transportclose",(()=>{t.close()}))}))}get channelMessagesDataConsumer(){return this.dataChannelsManager.channelMessagesDataConsumer}closeRemoteConsumer(e){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.closeConsumer(e)}))}resumeRemoteConsumer(e){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.resumeConsumer(e)}))}pauseRemoteProducer(e){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.pauseProducer(e)}))}resumeRemoteProducer(e){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.resumeProducer(e)}))}pauseRemoteConsumer(e){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.pauseConsumer(e)}))}updatePeerAppData(e){return o(this,arguments,void 0,(function*({appData:e}){yield this.signalingApiClient.appData.updateSelfPeerAppData({appData:e})}))}setProducerMaxSpatialLayer(e,t){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.setProducerMaxSpatialLayer(e,{maxSpatialLayer:t})}))}requestProducerMaxSpatialLayer(e,t){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.requestProducerMaxSpatialLayer(e,{spatialLayer:t})}))}changePeerProducePermissions(e,t){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.peers.changePeerProducePermissions(e,{producePermissions:null==t?void 0:t.map((e=>e))})}))}addPeerProducePermission(e,t){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.peers.addPeerProducePermissions(e,t)}))}removePeerProducePermission(e,t){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.peers.removePeerProducePermissions(e,t)}))}updateConsumerPreferredLayers(e,t,r){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.updateConsumerPreferredLayers(e,{spatialLayer:t,temporalLayer:r})}))}requestConsumerKeyFrame(e){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.requestConsumerKeyFrame(e)}))}ping(){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.ping.pingPeer()}))}getTransportsStateInfo(){return o(this,void 0,void 0,(function*(){const[e,t]=yield Promise.all([this.getParsedTransportStats(this.receiveTransport),this.getParsedTransportStats(this.sendTransport)]);return{receive:e,send:t}}))}setPreferRelay(e){this.preferRelay=e,e||c(this,so,0,"f")}getPreferRelay(){var e;return null!==(e=this.preferRelay)&&void 0!==e&&e}isRelayEnforced(){return this.getPreferRelay()&&a(this,so,"f")>Date.now()}enforceRelay(e){c(this,so,Date.now()+e,"f"),this.preferRelay=!0,a(this,ao,"f").info("enforceRelay()",{durationMs:e,relayEnforcedUntil:a(this,so,"f")})}getChannelPeers(e){return o(this,void 0,void 0,(function*(){var t;const{data:r}=yield this.signalingApiClient.peers.getPeers({role:e});this.peersLoaded=!0;return{peers:(null!==(t=r.items)&&void 0!==t?t:[]).map((e=>this.mapPeerResponse(e)))}}))}createAllDataChannels(){return o(this,void 0,void 0,(function*(){if(!this.receiveTransport)throw new Bt("create_data_channels_failed",new Error("Receive transport is not created"));yield this.dataChannelsManager.createAudioObserver(this.receiveTransport),yield this.dataChannelsManager.createChannelMessagesDataConsumer(this.receiveTransport)}))}closeAllDataChannels(){this.dataChannelsManager.closeAudioObserver(),this.dataChannelsManager.closeChannelMessagesDataConsumer()}waitForReceiveTransportConnected(e){return o(this,arguments,void 0,(function*({onReceiveTransportFailed:e}){if(!this.receiveTransport)throw new Error("receiveTransport is not initialized");if("connected"===(yield this.waitForTransportTerminalState(this.receiveTransport)))return;yield e(),yield this.waitForIceRestartStateTransition(this.receiveTransport);const t=yield this.waitForTransportTerminalState(this.receiveTransport);if("connected"!==t)throw new Error(`receiveTransport connection failed after relay escalation: ${t}`)}))}triggerChannelStateEvent(e){return o(this,void 0,void 0,(function*(){const{data:t}=yield this.signalingApiClient.channel.triggerChannelStateEvent({role:e});if("number"!=typeof t.messageId)throw new Error("Invalid channel state event response");return t.messageId}))}waitForChannelMessagesDataConsumerConnected(){return o(this,void 0,void 0,(function*(){if(!this.dataChannelsManager.channelMessagesDataConsumer)throw new Error("channelMessagesDataConsumer is not initialized");yield this.waitForDataConsumerConnected(this.dataChannelsManager.channelMessagesDataConsumer)}))}waitForIceRestartStateTransition(e){return o(this,arguments,void 0,(function*(e,t=1e4){"failed"===e.connectionState&&(yield new Promise((r=>{const n=setTimeout((()=>{i(),r()}),t),i=()=>{clearTimeout(n),e.off("connectionstatechange",s)},s=()=>{i(),r()};e.on("connectionstatechange",s)})))}))}waitForTransportTerminalState(e){return o(this,arguments,void 0,(function*(e,t=6e4){if("connected"===e.connectionState)return e.connectionState;if("failed"===e.connectionState)return e.connectionState;if("closed"===e.connectionState)throw new Error(`receiveTransport connection failed: ${e.connectionState}`);return yield new Promise(((r,n)=>{const i=setTimeout((()=>{s(),r(e.connectionState)}),t),s=()=>{clearTimeout(i),e.off("connectionstatechange",o)},o=()=>{["connected","failed"].includes(e.connectionState)?(s(),r(e.connectionState)):"closed"===e.connectionState&&(s(),n(new Error(`receiveTransport connection failed: ${e.connectionState}`)))};e.on("connectionstatechange",o)}))}))}waitForDataConsumerConnected(e){return o(this,arguments,void 0,(function*(e,t=6e4){if(!e)throw new Error("Data consumer is not initialized");"open"!==e.readyState&&(yield new Promise(((r,n)=>{const i=setTimeout((()=>{s(),n(new Error("Timed out waiting for data consumer to connect"))}),t),s=()=>{clearTimeout(i),e.off("open",o),e.off("close",a)},o=()=>{s(),r()},a=()=>{s(),n(new Error(`Data consumer closed unexpectedly: ${e.readyState}`))};e.on("open",o),e.on("close",a)})))}))}getParsedTransportStats(e){return o(this,void 0,void 0,(function*(){if(e)try{const t=Array.from((yield e.getStats()).values()),r=t.find((e=>"local-candidate"===e.type)),n=t.find((e=>"remote-candidate"===e.type)),i=t.find((e=>"transport"===e.type));return{dtlsState:null==i?void 0:i.dtlsState,iceState:null==i?void 0:i.iceState,dtlsRole:null==i?void 0:i.dtlsRole,iceRole:null==i?void 0:i.iceRole,selectedCandidatePairChanges:null==i?void 0:i.selectedCandidatePairChanges,tlsVersion:null==i?void 0:i.tlsVersion,localCandidateState:{ip:null==r?void 0:r.ip,address:null==r?void 0:r.address,port:null==r?void 0:r.port,protocol:null==r?void 0:r.protocol,candidateType:null==r?void 0:r.candidateType},remoteCandidateState:{ip:null==n?void 0:n.ip,address:null==n?void 0:n.address,port:null==n?void 0:n.port,protocol:null==n?void 0:n.protocol,candidateType:null==n?void 0:n.candidateType}}}catch(e){return void(e instanceof Error&&"InvalidStateError"===e.name?a(this,ao,"f").debug.bind(a(this,ao,"f")):a(this,ao,"f").error.bind(a(this,ao,"f")))("getParsedTransportStats()",{error:e})}else a(this,ao,"f").debug("getParsedTransportStats()",{message:"Transport is missing"})}))}logTransportDetails(e){return o(this,void 0,void 0,(function*(){var t,r,n,i;let s;try{s=yield e.getStats()}catch(t){return void a(this,ao,"f").error("Failed to log detailed WebRTC transport stats",{error:Vt(t),transportId:e.id,reason:"failed to parse getStats"})}try{const o=[...s],[,c]=null!==(t=o.find((([,e])=>"transport"===(null==e?void 0:e.type))))&&void 0!==t?t:[],[,d]=null!==(r=o.find((([,e])=>"candidate-pair"===e.type&&"succeeded"===e.state&&e.nominated)))&&void 0!==r?r:[],u=s.get(String(null!==(n=null==d?void 0:d.localCandidateId)&&void 0!==n?n:"-")),l=s.get(String(null!==(i=null==d?void 0:d.remoteCandidateId)&&void 0!==i?i:"-")),p={hasNominatedPair:!!d,transportId:e.id,iceRole:null==c?void 0:c.iceRole,iceState:null==c?void 0:c.iceState,dtlsRole:null==c?void 0:c.dtlsRole,dtlsState:null==c?void 0:c.dtlsState,local:{address:null==u?void 0:u.address,candidateType:null==u?void 0:u.candidateType,foundation:null==u?void 0:u.foundation,networkType:null==u?void 0:u.networkType,isRemote:null==u?void 0:u.isRemote,port:null==u?void 0:u.port,protocol:null==u?void 0:u.protocol,relatedAddress:null==u?void 0:u.relatedAddress,relatedPort:null==u?void 0:u.relatedPort,transportId:null==u?void 0:u.transportId,relayProtocol:null==u?void 0:u.relayProtocol,url:null==u?void 0:u.url},remote:{address:null==l?void 0:l.address,candidateType:null==l?void 0:l.candidateType,foundation:null==l?void 0:l.foundation,isRemote:null==l?void 0:l.isRemote,port:null==l?void 0:l.port,protocol:null==l?void 0:l.protocol,transportId:null==l?void 0:l.transportId}};(null==d?void 0:d.totalRoundTripTime)&&(null==d?void 0:d.responsesReceived)&&(p.pairRoundTripTime=Math.round(d.totalRoundTripTime/d.responsesReceived*1e3)),a(this,ao,"f").info("Detailed WebRTC transport stats",p)}catch(t){a(this,ao,"f").error("Failed to log detailed WebRTC transport stats",{error:Vt(t),transportId:e.id,reason:"-"})}}))}stopRestartIceAttempts(){this.iceRecoveryService.cancelAll()}toRemoteConsumerOptions(e){const{producerPaused:t}=e,n=r(e,["producerPaused"]);return Object.assign(Object.assign({},n),{producerPaused:t})}mapPeerResponse(e){var t,r,n,i,s,o,a,c;return{id:e.id,channelIds:null!==(t=e.channelIds)&&void 0!==t?t:[],groups:null!==(r=e.groups)&&void 0!==r?r:[],producePermissions:null!==(n=e.producePermissions)&&void 0!==n?n:[],appId:null!==(s=null!==(i=e.appId)&&void 0!==i?i:this.state.appId)&&void 0!==s?s:"",producers:(null!==(o=e.producers)&&void 0!==o?o:[]).map((e=>this.mapProducer(e))),uid:e.uid,appData:null!==(a=e.appData)&&void 0!==a?a:{},role:null!==(c=e.role)&&void 0!==c?c:"audience",loginDate:e.loginDate?new Date(e.loginDate):new Date}}mapProducer(e){var t;return{id:e.id,kind:e.kind,peerId:e.peerId,label:e.label,paused:null!==(t=e.paused)&&void 0!==t&&t,encodings:[],maxSpatialLayer:0}}connectTransport(e,t){return o(this,void 0,void 0,(function*(){try{yield this.signalingApiClient.transport.connectTransport(e,{dtlsParameters:t})}catch(t){if(t instanceof io)return void a(this,ao,"f").warn("connectTransport() transport already connected",{transportId:e});throw t}}))}subscribeCommonTransportEvents(e){e.on("connect",((t,r,n)=>o(this,[t,r,n],void 0,(function*({dtlsParameters:t},r,n){try{yield this.connectTransport(e.id,t),r(),a(this,ao,"f").debug(`${e.direction}Transport.connect()`,{transportId:e.id,dtlsRole:t.role}),setTimeout((()=>o(this,void 0,void 0,(function*(){return yield this.logTransportDetails(e)}))),2e3),setTimeout((()=>o(this,void 0,void 0,(function*(){return yield this.checkTransportState(e)}))),15e3)}catch(t){a(this,ao,"f").error(`${e.direction}Transport.on('connect')`,{error:t}),n(t)}})))),e.on("produce",((t,r,n)=>o(this,void 0,void 0,(function*(){try{const{data:n}=yield this.signalingApiClient.transport.produceMediaToTransport(e.id,{kind:t.kind,rtpParameters:t.rtpParameters,appData:t.appData,forceCloseExisting:!0}),i=n.id;r({id:i}),a(this,ao,"f").debug(`${e.direction}Transport.produce()`,{producerId:i,transportId:e.id,kind:t.kind})}catch(r){(Qn(r)?a(this,ao,"f").info.bind(a(this,ao,"f")):a(this,ao,"f").error.bind(a(this,ao,"f")))(`${e.direction}Transport.produce()`,{error:Vt(r),transportId:e.id,kind:t.kind}),n(r)}})))),e.on("producedata",((t,r,n)=>o(this,void 0,void 0,(function*(){try{const{data:n}=yield this.signalingApiClient.transport.produceDataToTransport(e.id,{label:t.label,sctpStreamParameters:t.sctpStreamParameters,appData:t.appData});r({id:n.id}),a(this,ao,"f").debug(`${e.direction}Transport.produceData()`,{producerId:n.id,transportId:e.id,sctpStreamParameters:t.sctpStreamParameters,label:t.label})}catch(r){(Qn(r)?a(this,ao,"f").info.bind(a(this,ao,"f")):a(this,ao,"f").error.bind(a(this,ao,"f")))(`${e.direction}Transport.produceData()`,{error:Vt(r),transportId:e.id,sctpStreamParameters:t.sctpStreamParameters,label:t.label}),n(r)}})))),e.on("connectionstatechange",(t=>{if(this.isStaleTransport(e))a(this,ao,"f").info("Transport.state ignored (stale transport)",{state:t,direction:e.direction,transportId:e.id});else{if(a(this,ao,"f").info(`${e.direction}Transport.state`,{state:t}),["closed","connected"].includes(t))return a(this,oo,"f").safeEmit(qn,{state:t,direction:e.direction}),this.iceRecoveryService.handleConnectionStateChange(e,t),void("connected"===t&&(a(this,oo,"f").safeEmit(qn,{state:"reconnected",direction:e.direction}),setTimeout((()=>{this.logTransportDetails(e).catch((e=>{a(this,ao,"f").debug("Failed to log transport details",{error:Vt(e)})}))}),1500)));a(this,oo,"f").safeEmit(qn,{state:t,direction:e.direction}),["disconnected","failed"].includes(t)&&this.iceRecoveryService.handleConnectionStateChange(e,t)}})),e.on("icegatheringstatechange",(t=>{a(this,ao,"f").info("icegatheringstatechange",{state:t,transportId:e.id,transportDirection:e.direction})}))}checkTransportState(e){return o(this,void 0,void 0,(function*(){if(!this.isStaleTransport(e))try{const t=yield this.getParsedTransportStats(e);if(!t)return;const r="send"===e.direction?"send":"receive";if("connected"!==t.iceState)return this.clientEventEmitter.emit(Qr,{direction:r,reason:"ice"}),void a(this,ao,"f").warn(Hn,{reason:"ice",transportId:e.id,direction:r});"connected"!==t.dtlsState&&(this.clientEventEmitter.emit(Qr,{direction:r,reason:"dtls"}),a(this,ao,"f").warn(Hn,{reason:"dtls",transportId:e.id,direction:r}))}catch(t){a(this,ao,"f").error("checkTransportState()",{error:Vt(t),transportId:e.id,direction:e.direction})}}))}isStaleTransport(e){return e.closed||e!==this.sendTransport&&e!==this.receiveTransport}};so=new WeakMap,oo=new WeakMap,ao=new WeakMap,co=n([ot(),i(0,ct(fi.CallState)),i(1,ct(fi.MyPeer)),i(2,ct(fi.LoggerFactory)),i(3,ct(fi.ClientEventEmitter)),i(4,ct(fi.DataChannelsManager)),i(5,ct(fi.SignalingApiClient)),i(6,ct(fi.DatachannelHeartbeater)),i(7,ct(fi.SignalingHeartbeater)),i(8,ct(fi.IceRecoveryService)),s("design:paramtypes",[mi,ro,Function,Ft,Function,Function,Function,Function,Function])],co);var uo=co;let lo=class{constructor(){this.peers=new Map}has(e){return this.peers.has(e)}set(e,t){this.peers.set(e,t)}get(e){return this.peers.get(e)}delete(e){return this.peers.delete(e)}all(){return Array.from(this.peers.values())}hosts(){return this.all().filter((e=>"host"===e.role))}audience(){return this.all().filter((e=>"audience"===e.role))}clear(){this.peers.clear()}};lo=n([ot()],lo);var po=lo;let ho=class{constructor(e,t,r,n,i){this.myPeer=e,this.network=t,this.peerFactory=r,this.clientEventEmitter=n,this.peersStorage=i}has(e){return this.peersStorage.has(e)}set(e,t){e===this.myPeer.id&&this.myPeer.set(t),this.peersStorage.set(e,t)}get(e){return this.peersStorage.get(e)}delete(e){return e===this.myPeer.id&&this.myPeer.delete(),this.peersStorage.delete(e)}remove(e){return o(this,void 0,void 0,(function*(){const t=this.get(e);t&&(yield t.reset(),this.delete(e),this.clientEventEmitter.safeEmit(qr,e))}))}all(){return this.peersStorage.all()}hosts(){return this.peersStorage.hosts()}audience(){return this.peersStorage.audience()}reset(){return o(this,void 0,void 0,(function*(){yield Promise.all(this.peersStorage.all().map((e=>o(this,void 0,void 0,(function*(){return yield e.reset()}))))),this.peersStorage.clear()}))}load(e){return o(this,void 0,void 0,(function*(){const{peers:t}=yield this.network.getChannelPeers(e);t.filter((e=>!this.has(e.id))).forEach((e=>this.add(e,!1)))}))}add(e,t=!0){const r=this.get(e.id);if(r)return r;const n=this.peerFactory(e);return this.set(n.id,n),t&&this.clientEventEmitter.safeEmit(Hr,n),n}isModerator(e){if(void 0===e)return!1;const t=this.get(e);return!!t&&t.isModerator}};function fo(e,t){var r,n;if(0===t.length)return e;for(r=0,n=t.length;r<n;r++)e=(e<<5)-e+t.charCodeAt(r),e|=0;return e<0?-2*e:e}function mo(e,t,r,n){var i=fo(fo(fo(e,r),function(e){return Object.prototype.toString.call(e)}(t)),typeof t);if(null===t)return fo(i,"null");if(void 0===t)return fo(i,"undefined");if("object"==typeof t||"function"==typeof t){if(-1!==n.indexOf(t))return fo(i,"[Circular]"+r);n.push(t);var s=function(e,t,r){return Object.keys(t).sort().reduce((function(e,n){return mo(e,t[n],n,r)}),e)}(i,t,n);if(!("valueOf"in t)||"function"!=typeof t.valueOf)return s;try{return fo(s,String(t.valueOf()))}catch(e){return fo(s,"[valueOf exception]"+(e.stack||e.message))}}return fo(i,t.toString())}ho=n([ot(),i(0,ct(fi.MyPeer)),i(1,ct(fi.Network)),i(2,ct(fi.PeerFactory)),i(3,ct(fi.ClientEventEmitter)),i(4,ct(fi.PeersStorage)),s("design:paramtypes",[ro,uo,Function,Ft,po])],ho);var go=function(e){return function(e,t){for(;e.length<t;)e="0"+e;return e}(mo(0,e,"",[]).toString(16),8)};const vo=new Set(["ENOTFOUND","ENETUNREACH","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_CRL","UNABLE_TO_DECRYPT_CERT_SIGNATURE","UNABLE_TO_DECRYPT_CRL_SIGNATURE","UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY","CERT_SIGNATURE_FAILURE","CRL_SIGNATURE_FAILURE","CERT_NOT_YET_VALID","CERT_HAS_EXPIRED","CRL_NOT_YET_VALID","CRL_HAS_EXPIRED","ERROR_IN_CERT_NOT_BEFORE_FIELD","ERROR_IN_CERT_NOT_AFTER_FIELD","ERROR_IN_CRL_LAST_UPDATE_FIELD","ERROR_IN_CRL_NEXT_UPDATE_FIELD","OUT_OF_MEM","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","CERT_CHAIN_TOO_LONG","CERT_REVOKED","INVALID_CA","PATH_LENGTH_EXCEEDED","INVALID_PURPOSE","CERT_UNTRUSTED","CERT_REJECTED","HOSTNAME_MISMATCH"]);function yo(e){return!e.response&&(!!e.code&&(!["ERR_CANCELED","ECONNABORTED"].includes(e.code)&&(e=>!vo.has(e&&e.code))(e)))}const bo=["get","head","options"],_o=bo.concat(["put","delete"]);function Eo(e){return"ECONNABORTED"!==e.code&&(!e.response||429===e.response.status||e.response.status>=500&&e.response.status<=599)}function wo(e){return!!e.config?.method&&(Eo(e)&&-1!==_o.indexOf(e.config.method))}function So(e){return yo(e)||wo(e)}function Co(e){const t=e?.response?.headers["retry-after"];if(!t)return 0;let r=1e3*(Number(t)||0);return 0===r&&(r=(new Date(t).valueOf()||0)-Date.now()),Math.max(0,r)}const Po={retries:3,retryCondition:So,retryDelay:function(e=0,t){return Math.max(0,Co(t))},shouldResetTimeout:!1,onRetry:()=>{},onMaxRetryTimesExceeded:()=>{},validateResponse:null};function To(e,t,r=!1){const n=function(e,t){return{...Po,...t,...e["axios-retry"]}}(e,t||{});return n.retryCount=n.retryCount||0,n.lastRequestTime&&!r||(n.lastRequestTime=Date.now()),e["axios-retry"]=n,n}const Ro=(e,t)=>{const r=e.interceptors.request.use((e=>(To(e,t,!0),e["axios-retry"]?.validateResponse&&(e.validateStatus=()=>!1),e))),n=e.interceptors.response.use(null,(async r=>{const{config:n}=r;if(!n)return Promise.reject(r);const i=To(n,t);return r.response&&i.validateResponse?.(r.response)?r.response:await async function(e,t){const{retries:r,retryCondition:n}=e,i=(e.retryCount||0)<r&&n(t);if("object"==typeof i)try{return!1!==await i}catch(e){return!1}return i}(i,r)?async function(e,t,r,n){t.retryCount+=1;const{retryDelay:i,shouldResetTimeout:s,onRetry:o}=t,a=i(t.retryCount,r);if(function(e,t){e.defaults.agent===t.agent&&delete t.agent,e.defaults.httpAgent===t.httpAgent&&delete t.httpAgent,e.defaults.httpsAgent===t.httpsAgent&&delete t.httpsAgent}(e,n),!s&&n.timeout&&t.lastRequestTime){const e=Date.now()-t.lastRequestTime,i=n.timeout-e-a;if(i<=0)return Promise.reject(r);n.timeout=i}return n.transformRequest=[e=>e],await o(t.retryCount,r,n),n.signal?.aborted?Promise.resolve(e(n)):new Promise((t=>{const r=()=>{clearTimeout(i),t(e(n))},i=setTimeout((()=>{t(e(n)),n.signal?.removeEventListener&&n.signal.removeEventListener("abort",r)}),a);n.signal?.addEventListener&&n.signal.addEventListener("abort",r,{once:!0})}))}(e,i,r,n):(await async function(e,t){e.retryCount>=e.retries&&await e.onMaxRetryTimesExceeded(t,e.retryCount)}(i,r),Promise.reject(r))}));return{requestInterceptorId:r,responseInterceptorId:n}};function ko(e,t){return function(){return e.apply(t,arguments)}}Ro.isNetworkError=yo,Ro.isSafeRequestError=function(e){return!!e.config?.method&&(Eo(e)&&-1!==bo.indexOf(e.config.method))},Ro.isIdempotentRequestError=wo,Ro.isNetworkOrIdempotentRequestError=So,Ro.exponentialDelay=function(e=0,t,r=100){const n=2**e*r,i=Math.max(n,Co(t));return i+.2*i*Math.random()},Ro.linearDelay=function(e=100){return(t=0,r)=>{const n=t*e;return Math.max(n,Co(r))}},Ro.isRetryableError=Eo;const{toString:Do}=Object.prototype,{getPrototypeOf:Io}=Object,{iterator:Ao,toStringTag:Oo}=Symbol,Mo=(No=Object.create(null),e=>{const t=Do.call(e);return No[t]||(No[t]=t.slice(8,-1).toLowerCase())});var No;const Lo=e=>(e=e.toLowerCase(),t=>Mo(t)===e),xo=e=>t=>typeof t===e,{isArray:Fo}=Array,jo=xo("undefined");const Uo=Lo("ArrayBuffer");const Vo=xo("string"),Bo=xo("function"),Wo=xo("number"),Ho=e=>null!==e&&"object"==typeof e,qo=e=>{if("object"!==Mo(e))return!1;const t=Io(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Oo in e||Ao in e)},zo=Lo("Date"),Go=Lo("File"),Yo=Lo("Blob"),$o=Lo("FileList"),Jo=Lo("URLSearchParams"),[Qo,Ko,Zo,Xo]=["ReadableStream","Request","Response","Headers"].map(Lo);function ea(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,i;if("object"!=typeof e&&(e=[e]),Fo(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{const i=r?Object.getOwnPropertyNames(e):Object.keys(e),s=i.length;let o;for(n=0;n<s;n++)o=i[n],t.call(null,e[o],o,e)}}function ta(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,i=r.length;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}const ra="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,na=e=>!jo(e)&&e!==ra;const ia=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Io(Uint8Array)),sa=Lo("HTMLFormElement"),oa=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),aa=Lo("RegExp"),ca=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};ea(r,((r,i)=>{let s;!1!==(s=t(r,i,e))&&(n[i]=s||r)})),Object.defineProperties(e,n)};const da=Lo("AsyncFunction"),ua=(la="function"==typeof setImmediate,pa=Bo(ra.postMessage),la?setImmediate:pa?(ha=`axios@${Math.random()}`,fa=[],ra.addEventListener("message",(({source:e,data:t})=>{e===ra&&t===ha&&fa.length&&fa.shift()()}),!1),e=>{fa.push(e),ra.postMessage(ha,"*")}):e=>setTimeout(e));var la,pa,ha,fa;const ma="undefined"!=typeof queueMicrotask?queueMicrotask.bind(ra):"undefined"!=typeof process&&process.nextTick||ua;var ga={isArray:Fo,isArrayBuffer:Uo,isBuffer:function(e){return null!==e&&!jo(e)&&null!==e.constructor&&!jo(e.constructor)&&Bo(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Bo(e.append)&&("formdata"===(t=Mo(e))||"object"===t&&Bo(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Uo(e.buffer),t},isString:Vo,isNumber:Wo,isBoolean:e=>!0===e||!1===e,isObject:Ho,isPlainObject:qo,isReadableStream:Qo,isRequest:Ko,isResponse:Zo,isHeaders:Xo,isUndefined:jo,isDate:zo,isFile:Go,isBlob:Yo,isRegExp:aa,isFunction:Bo,isStream:e=>Ho(e)&&Bo(e.pipe),isURLSearchParams:Jo,isTypedArray:ia,isFileList:$o,forEach:ea,merge:function e(){const{caseless:t}=na(this)&&this||{},r={},n=(n,i)=>{const s=t&&ta(r,i)||i;qo(r[s])&&qo(n)?r[s]=e(r[s],n):qo(n)?r[s]=e({},n):Fo(n)?r[s]=n.slice():r[s]=n};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&ea(arguments[e],n);return r},extend:(e,t,r,{allOwnKeys:n}={})=>(ea(t,((t,n)=>{r&&Bo(t)?e[n]=ko(t,r):e[n]=t}),{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let i,s,o;const a={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),s=i.length;s-- >0;)o=i[s],n&&!n(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==r&&Io(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:Mo,kindOfTest:Lo,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(Fo(e))return e;let t=e.length;if(!Wo(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Ao]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:sa,hasOwnProperty:oa,hasOwnProp:oa,reduceDescriptors:ca,freezeMethods:e=>{ca(e,((t,r)=>{if(Bo(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];Bo(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach((e=>{r[e]=!0}))};return Fo(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:ta,global:ra,isContextDefined:na,isSpecCompliantForm:function(e){return!!(e&&Bo(e.append)&&"FormData"===e[Oo]&&e[Ao])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(Ho(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const i=Fo(e)?[]:{};return ea(e,((e,t)=>{const s=r(e,n+1);!jo(s)&&(i[t]=s)})),t[n]=void 0,i}}return e};return r(e,0)},isAsyncFn:da,isThenable:e=>e&&(Ho(e)||Bo(e))&&Bo(e.then)&&Bo(e.catch),setImmediate:ua,asap:ma,isIterable:e=>null!=e&&Bo(e[Ao])};function va(e,t,r,n,i){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),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}ga.inherits(va,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:ga.toJSONObject(this.config),code:this.code,status:this.status}}});const ya=va.prototype,ba={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{ba[e]={value:e}})),Object.defineProperties(va,ba),Object.defineProperty(ya,"isAxiosError",{value:!0}),va.from=(e,t,r,n,i,s)=>{const o=Object.create(ya);return ga.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),va.call(o,e.message,t,r,n,i),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function _a(e){return ga.isPlainObject(e)||ga.isArray(e)}function Ea(e){return ga.endsWith(e,"[]")?e.slice(0,-2):e}function wa(e,t,r){return e?e.concat(t).map((function(e,t){return e=Ea(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const Sa=ga.toFlatObject(ga,{},null,(function(e){return/^is[A-Z]/.test(e)}));function Ca(e,t,r){if(!ga.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=ga.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!ga.isUndefined(t[e])}))).metaTokens,i=r.visitor||d,s=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&ga.isSpecCompliantForm(t);if(!ga.isFunction(i))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(ga.isDate(e))return e.toISOString();if(ga.isBoolean(e))return e.toString();if(!a&&ga.isBlob(e))throw new va("Blob is not supported. Use a Buffer instead.");return ga.isArrayBuffer(e)||ga.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,r,i){let a=e;if(e&&!i&&"object"==typeof e)if(ga.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(ga.isArray(e)&&function(e){return ga.isArray(e)&&!e.some(_a)}(e)||(ga.isFileList(e)||ga.endsWith(r,"[]"))&&(a=ga.toArray(e)))return r=Ea(r),a.forEach((function(e,n){!ga.isUndefined(e)&&null!==e&&t.append(!0===o?wa([r],n,s):null===o?r:r+"[]",c(e))})),!1;return!!_a(e)||(t.append(wa(i,r,s),c(e)),!1)}const u=[],l=Object.assign(Sa,{defaultVisitor:d,convertValue:c,isVisitable:_a});if(!ga.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!ga.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+n.join("."));u.push(r),ga.forEach(r,(function(r,s){!0===(!(ga.isUndefined(r)||null===r)&&i.call(t,r,ga.isString(s)?s.trim():s,n,l))&&e(r,n?n.concat(s):[s])})),u.pop()}}(e),t}function Pa(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function Ta(e,t){this._pairs=[],e&&Ca(e,this,t)}const Ra=Ta.prototype;function ka(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Da(e,t,r){if(!t)return e;const n=r&&r.encode||ka;ga.isFunction(r)&&(r={serialize:r});const i=r&&r.serialize;let s;if(s=i?i(t,r):ga.isURLSearchParams(t)?t.toString():new Ta(t,r).toString(n),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}Ra.append=function(e,t){this._pairs.push([e,t])},Ra.toString=function(e){const t=e?function(t){return e.call(this,t,Pa)}:Pa;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var Ia=class{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){ga.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},Aa={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Oa={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Ta,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const Ma="undefined"!=typeof window&&"undefined"!=typeof document,Na="object"==typeof navigator&&navigator||void 0,La=Ma&&(!Na||["ReactNative","NativeScript","NS"].indexOf(Na.product)<0),xa="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Fa=Ma&&window.location.href||"http://localhost";var ja={...Object.freeze({__proto__:null,hasBrowserEnv:Ma,hasStandardBrowserWebWorkerEnv:xa,hasStandardBrowserEnv:La,navigator:Na,origin:Fa}),...Oa};function Ua(e){function t(e,r,n,i){let s=e[i++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=i>=e.length;if(s=!s&&ga.isArray(n)?n.length:s,a)return ga.hasOwnProp(n,s)?n[s]=[n[s],r]:n[s]=r,!o;n[s]&&ga.isObject(n[s])||(n[s]=[]);return t(e,r,n[s],i)&&ga.isArray(n[s])&&(n[s]=function(e){const t={},r=Object.keys(e);let n;const i=r.length;let s;for(n=0;n<i;n++)s=r[n],t[s]=e[s];return t}(n[s])),!o}if(ga.isFormData(e)&&ga.isFunction(e.entries)){const r={};return ga.forEachEntry(e,((e,n)=>{t(function(e){return ga.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null}const Va={transitional:Aa,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,i=ga.isObject(e);i&&ga.isHTMLForm(e)&&(e=new FormData(e));if(ga.isFormData(e))return n?JSON.stringify(Ua(e)):e;if(ga.isArrayBuffer(e)||ga.isBuffer(e)||ga.isStream(e)||ga.isFile(e)||ga.isBlob(e)||ga.isReadableStream(e))return e;if(ga.isArrayBufferView(e))return e.buffer;if(ga.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Ca(e,new ja.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return ja.isNode&&ga.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=ga.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Ca(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return i||n?(t.setContentType("application/json",!1),function(e,t,r){if(ga.isString(e))try{return(t||JSON.parse)(e),ga.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Va.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(ga.isResponse(e)||ga.isReadableStream(e))return e;if(e&&ga.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw va.from(e,va.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:ja.classes.FormData,Blob:ja.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ga.forEach(["delete","get","head","post","put","patch"],(e=>{Va.headers[e]={}}));var Ba=Va;const Wa=ga.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const Ha=Symbol("internals");function qa(e){return e&&String(e).trim().toLowerCase()}function za(e){return!1===e||null==e?e:ga.isArray(e)?e.map(za):String(e)}function Ga(e,t,r,n,i){return ga.isFunction(n)?n.call(this,t,r):(i&&(t=r),ga.isString(t)?ga.isString(n)?-1!==t.indexOf(n):ga.isRegExp(n)?n.test(t):void 0:void 0)}class Ya{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function i(e,t,r){const i=qa(t);if(!i)throw new Error("header name must be a non-empty string");const s=ga.findKey(n,i);(!s||void 0===n[s]||!0===r||void 0===r&&!1!==n[s])&&(n[s||t]=za(e))}const s=(e,t)=>ga.forEach(e,((e,r)=>i(e,r,t)));if(ga.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(ga.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let r,n,i;return e&&e.split("\n").forEach((function(e){i=e.indexOf(":"),r=e.substring(0,i).trim().toLowerCase(),n=e.substring(i+1).trim(),!r||t[r]&&Wa[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t);else if(ga.isObject(e)&&ga.isIterable(e)){let r,n,i={};for(const t of e){if(!ga.isArray(t))throw TypeError("Object iterator must return a key-value pair");i[n=t[0]]=(r=i[n])?ga.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}s(i,t)}else null!=e&&i(t,e,r);return this}get(e,t){if(e=qa(e)){const r=ga.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(ga.isFunction(t))return t.call(this,e,r);if(ga.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=qa(e)){const r=ga.findKey(this,e);return!(!r||void 0===this[r]||t&&!Ga(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function i(e){if(e=qa(e)){const i=ga.findKey(r,e);!i||t&&!Ga(0,r[i],i,t)||(delete r[i],n=!0)}}return ga.isArray(e)?e.forEach(i):i(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const i=t[r];e&&!Ga(0,this[i],i,e,!0)||(delete this[i],n=!0)}return n}normalize(e){const t=this,r={};return ga.forEach(this,((n,i)=>{const s=ga.findKey(r,i);if(s)return t[s]=za(n),void delete t[i];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(i):String(i).trim();o!==i&&delete t[i],t[o]=za(n),r[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return ga.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&ga.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[Ha]=this[Ha]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=qa(e);t[n]||(!function(e,t){const r=ga.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,i){return this[n].call(this,t,e,r,i)},configurable:!0})}))}(r,e),t[n]=!0)}return ga.isArray(e)?e.forEach(n):n(e),this}}Ya.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),ga.reduceDescriptors(Ya.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),ga.freezeMethods(Ya);var $a=Ya;function Ja(e,t){const r=this||Ba,n=t||r,i=$a.from(n.headers);let s=n.data;return ga.forEach(e,(function(e){s=e.call(r,s,i.normalize(),t?t.status:void 0)})),i.normalize(),s}function Qa(e){return!(!e||!e.__CANCEL__)}function Ka(e,t,r){va.call(this,null==e?"canceled":e,va.ERR_CANCELED,t,r),this.name="CanceledError"}function Za(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new va("Request failed with status code "+r.status,[va.ERR_BAD_REQUEST,va.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}ga.inherits(Ka,va,{__CANCEL__:!0});const Xa=(e,t,r=3)=>{let n=0;const i=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let i,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=n[o];i||(i=c),r[s]=a,n[s]=c;let u=o,l=0;for(;u!==s;)l+=r[u++],u%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-i<t)return;const p=d&&c-d;return p?Math.round(1e3*l/p):void 0}}(50,250);return function(e,t){let r,n,i=0,s=1e3/t;const o=(t,s=Date.now())=>{i=s,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-i;a>=s?o(e,t):(r=e,n||(n=setTimeout((()=>{n=null,o(r)}),s-a)))},()=>r&&o(r)]}((r=>{const s=r.loaded,o=r.lengthComputable?r.total:void 0,a=s-n,c=i(a);n=s;e({loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:r,lengthComputable:null!=o,[t?"download":"upload"]:!0})}),r)},ec=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},tc=e=>(...t)=>ga.asap((()=>e(...t)));var rc=ja.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,ja.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(ja.origin),ja.navigator&&/(msie|trident)/i.test(ja.navigator.userAgent)):()=>!0,nc=ja.hasStandardBrowserEnv?{write(e,t,r,n,i,s){const o=[e+"="+encodeURIComponent(t)];ga.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),ga.isString(n)&&o.push("path="+n),ga.isString(i)&&o.push("domain="+i),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function ic(e,t,r){let n=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(n||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const sc=e=>e instanceof $a?{...e}:e;function oc(e,t){t=t||{};const r={};function n(e,t,r,n){return ga.isPlainObject(e)&&ga.isPlainObject(t)?ga.merge.call({caseless:n},e,t):ga.isPlainObject(t)?ga.merge({},t):ga.isArray(t)?t.slice():t}function i(e,t,r,i){return ga.isUndefined(t)?ga.isUndefined(e)?void 0:n(void 0,e,0,i):n(e,t,0,i)}function s(e,t){if(!ga.isUndefined(t))return n(void 0,t)}function o(e,t){return ga.isUndefined(t)?ga.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,i,s){return s in t?n(r,i):s in e?n(void 0,r):void 0}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,r)=>i(sc(e),sc(t),0,!0)};return ga.forEach(Object.keys(Object.assign({},e,t)),(function(n){const s=c[n]||i,o=s(e[n],t[n],n);ga.isUndefined(o)&&s!==a||(r[n]=o)})),r}var ac=e=>{const t=oc({},e);let r,{data:n,withXSRFToken:i,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=$a.from(a),t.url=Da(ic(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),ga.isFormData(n))if(ja.hasStandardBrowserEnv||ja.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map((e=>e.trim())).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(ja.hasStandardBrowserEnv&&(i&&ga.isFunction(i)&&(i=i(t)),i||!1!==i&&rc(t.url))){const e=s&&o&&nc.read(o);e&&a.set(s,e)}return t};var cc="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){const n=ac(e);let i=n.data;const s=$a.from(n.headers).normalize();let o,a,c,d,u,{responseType:l,onUploadProgress:p,onDownloadProgress:h}=n;function f(){d&&d(),u&&u(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let m=new XMLHttpRequest;function g(){if(!m)return;const n=$a.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());Za((function(e){t(e),f()}),(function(e){r(e),f()}),{data:l&&"text"!==l&&"json"!==l?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:n,config:e,request:m}),m=null}m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout,"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(g)},m.onabort=function(){m&&(r(new va("Request aborted",va.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new va("Network Error",va.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const i=n.transitional||Aa;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new va(t,i.clarifyTimeoutError?va.ETIMEDOUT:va.ECONNABORTED,e,m)),m=null},void 0===i&&s.setContentType(null),"setRequestHeader"in m&&ga.forEach(s.toJSON(),(function(e,t){m.setRequestHeader(t,e)})),ga.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),l&&"json"!==l&&(m.responseType=n.responseType),h&&([c,u]=Xa(h,!0),m.addEventListener("progress",c)),p&&m.upload&&([a,d]=Xa(p),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",d)),(n.cancelToken||n.signal)&&(o=t=>{m&&(r(!t||t.type?new Ka(null,e,m):t),m.abort(),m=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));const v=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);v&&-1===ja.protocols.indexOf(v)?r(new va("Unsupported protocol "+v+":",va.ERR_BAD_REQUEST,e)):m.send(i||null)}))};var dc=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const i=function(e){if(!r){r=!0,o();const t=e instanceof Error?e:this.reason;n.abort(t instanceof va?t:new Ka(t instanceof Error?t.message:t))}};let s=t&&setTimeout((()=>{s=null,i(new va(`timeout ${t} of ms exceeded`,va.ETIMEDOUT))}),t);const o=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)})),e=null)};e.forEach((e=>e.addEventListener("abort",i)));const{signal:a}=n;return a.unsubscribe=()=>ga.asap(o),a}};const uc=function*(e,t){let r=e.byteLength;if(!t||r<t)return void(yield e);let n,i=0;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},lc=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},pc=(e,t,r,n)=>{const i=async function*(e,t){for await(const r of lc(e))yield*uc(r,t)}(e,t);let s,o=0,a=e=>{s||(s=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await i.next();if(t)return a(),void e.close();let s=n.byteLength;if(r){let e=o+=s;r(e)}e.enqueue(new Uint8Array(n))}catch(e){throw a(e),e}},cancel:e=>(a(e),i.return())},{highWaterMark:2})},hc="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,fc=hc&&"function"==typeof ReadableStream,mc=hc&&("function"==typeof TextEncoder?(gc=new TextEncoder,e=>gc.encode(e)):async e=>new Uint8Array(await new Response(e).arrayBuffer()));var gc;const vc=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},yc=fc&&vc((()=>{let e=!1;const t=new Request(ja.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),bc=fc&&vc((()=>ga.isReadableStream(new Response("").body))),_c={stream:bc&&(e=>e.body)};var Ec;hc&&(Ec=new Response,["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!_c[e]&&(_c[e]=ga.isFunction(Ec[e])?t=>t[e]():(t,r)=>{throw new va(`Response type '${e}' is not supported`,va.ERR_NOT_SUPPORT,r)})})));const wc=async(e,t)=>{const r=ga.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(ga.isBlob(e))return e.size;if(ga.isSpecCompliantForm(e)){const t=new Request(ja.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return ga.isArrayBufferView(e)||ga.isArrayBuffer(e)?e.byteLength:(ga.isURLSearchParams(e)&&(e+=""),ga.isString(e)?(await mc(e)).byteLength:void 0)})(t):r};var Sc=hc&&(async e=>{let{url:t,method:r,data:n,signal:i,cancelToken:s,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:d,headers:u,withCredentials:l="same-origin",fetchOptions:p}=ac(e);d=d?(d+"").toLowerCase():"text";let h,f=dc([i,s&&s.toAbortSignal()],o);const m=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let g;try{if(c&&yc&&"get"!==r&&"head"!==r&&0!==(g=await wc(u,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if(ga.isFormData(n)&&(e=r.headers.get("content-type"))&&u.setContentType(e),r.body){const[e,t]=ec(g,Xa(tc(c)));n=pc(r.body,65536,e,t)}}ga.isString(l)||(l=l?"include":"omit");const i="credentials"in Request.prototype;h=new Request(t,{...p,signal:f,method:r.toUpperCase(),headers:u.normalize().toJSON(),body:n,duplex:"half",credentials:i?l:void 0});let s=await fetch(h,p);const o=bc&&("stream"===d||"response"===d);if(bc&&(a||o&&m)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=s[t]}));const t=ga.toFiniteNumber(s.headers.get("content-length")),[r,n]=a&&ec(t,Xa(tc(a),!0))||[];s=new Response(pc(s.body,65536,r,(()=>{n&&n(),m&&m()})),e)}d=d||"text";let v=await _c[ga.findKey(_c,d)||"text"](s,e);return!o&&m&&m(),await new Promise(((t,r)=>{Za(t,r,{data:v,headers:$a.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:h})}))}catch(t){if(m&&m(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new va("Network Error",va.ERR_NETWORK,e,h),{cause:t.cause||t});throw va.from(t,t&&t.code,e,h)}});const Cc={http:null,xhr:cc,fetch:Sc};ga.forEach(Cc,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));const Pc=e=>`- ${e}`,Tc=e=>ga.isFunction(e)||null===e||!1===e;var Rc=e=>{e=ga.isArray(e)?e:[e];const{length:t}=e;let r,n;const i={};for(let s=0;s<t;s++){let t;if(r=e[s],n=r,!Tc(r)&&(n=Cc[(t=String(r)).toLowerCase()],void 0===n))throw new va(`Unknown adapter '${t}'`);if(n)break;i[t||"#"+s]=n}if(!n){const e=Object.entries(i).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new va("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(Pc).join("\n"):" "+Pc(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n};function kc(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Ka(null,e)}function Dc(e){kc(e),e.headers=$a.from(e.headers),e.data=Ja.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Rc(e.adapter||Ba.adapter)(e).then((function(t){return kc(e),t.data=Ja.call(e,e.transformResponse,t),t.headers=$a.from(t.headers),t}),(function(t){return Qa(t)||(kc(e),t&&t.response&&(t.response.data=Ja.call(e,e.transformResponse,t.response),t.response.headers=$a.from(t.response.headers))),Promise.reject(t)}))}const Ic={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Ic[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const Ac={};Ic.transitional=function(e,t,r){function n(e,t){return"[Axios v1.10.0] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,i,s)=>{if(!1===e)throw new va(n(i," has been removed"+(t?" in "+t:"")),va.ERR_DEPRECATED);return t&&!Ac[i]&&(Ac[i]=!0,console.warn(n(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,i,s)}},Ic.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};var Oc={assertOptions:function(e,t,r){if("object"!=typeof e)throw new va("options must be an object",va.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let i=n.length;for(;i-- >0;){const s=n[i],o=t[s];if(o){const t=e[s],r=void 0===t||o(t,s,e);if(!0!==r)throw new va("option "+s+" must be "+r,va.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new va("Unknown option "+s,va.ERR_BAD_OPTION)}},validators:Ic};const Mc=Oc.validators;class Nc{constructor(e){this.defaults=e||{},this.interceptors={request:new Ia,response:new Ia}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const r=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=oc(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:i}=t;void 0!==r&&Oc.assertOptions(r,{silentJSONParsing:Mc.transitional(Mc.boolean),forcedJSONParsing:Mc.transitional(Mc.boolean),clarifyTimeoutError:Mc.transitional(Mc.boolean)},!1),null!=n&&(ga.isFunction(n)?t.paramsSerializer={serialize:n}:Oc.assertOptions(n,{encode:Mc.function,serialize:Mc.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Oc.assertOptions(t,{baseUrl:Mc.spelling("baseURL"),withXsrfToken:Mc.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=i&&ga.merge(i.common,i[t.method]);i&&ga.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete i[e]})),t.headers=$a.concat(s,i);const o=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))}));const c=[];let d;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let u,l=0;if(!a){const e=[Dc.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),u=e.length,d=Promise.resolve(t);l<u;)d=d.then(e[l++],e[l++]);return d}u=o.length;let p=t;for(l=0;l<u;){const e=o[l++],t=o[l++];try{p=e(p)}catch(e){t.call(this,e);break}}try{d=Dc.call(this,p)}catch(e){return Promise.reject(e)}for(l=0,u=c.length;l<u;)d=d.then(c[l++],c[l++]);return d}getUri(e){return Da(ic((e=oc(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}}ga.forEach(["delete","get","head","options"],(function(e){Nc.prototype[e]=function(t,r){return this.request(oc(r||{},{method:e,url:t,data:(r||{}).data}))}})),ga.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,i){return this.request(oc(i||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}Nc.prototype[e]=t(),Nc.prototype[e+"Form"]=t(!0)}));var Lc=Nc;class xc{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,i){r.reason||(r.reason=new Ka(e,n,i),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;const t=new xc((function(t){e=t}));return{token:t,cancel:e}}}var Fc=xc;const jc={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(jc).forEach((([e,t])=>{jc[t]=e}));var Uc=jc;const Vc=function e(t){const r=new Lc(t),n=ko(Lc.prototype.request,r);return ga.extend(n,Lc.prototype,r,{allOwnKeys:!0}),ga.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(oc(t,r))},n}(Ba);Vc.Axios=Lc,Vc.CanceledError=Ka,Vc.CancelToken=Fc,Vc.isCancel=Qa,Vc.VERSION="1.10.0",Vc.toFormData=Ca,Vc.AxiosError=va,Vc.Cancel=Vc.CanceledError,Vc.all=function(e){return Promise.all(e)},Vc.spread=function(e){return function(t){return e.apply(null,t)}},Vc.isAxiosError=function(e){return ga.isObject(e)&&!0===e.isAxiosError},Vc.mergeConfig=oc,Vc.AxiosHeaders=$a,Vc.formToJSON=e=>Ua(ga.isHTMLForm(e)?new FormData(e):e),Vc.getAdapter=Rc,Vc.HttpStatusCode=Uc,Vc.default=Vc;var Bc=Vc;class Wc extends Gn{constructor(e,t,r){super(null!=e?e:Wc.DEFAULT_MESSAGE,null!=t?t:"already_created",r)}}Wc.DEFAULT_MESSAGE="Resource has already been created";class Hc extends Gn{constructor(e,t,r){super(null!=e?e:Hc.DEFAULT_MESSAGE,null!=t?t:"forbidden",r)}}Hc.DEFAULT_MESSAGE="Forbidden";class qc extends Gn{constructor(e,t,r){super(null!=e?e:qc.DEFAULT_MESSAGE,null!=t?t:"invalid_request",r)}}qc.DEFAULT_MESSAGE="Invalid request";class zc extends Gn{constructor(e,t,r){super(null!=e?e:zc.DEFAULT_MESSAGE,null!=t?t:"too_many_requests",r)}}zc.DEFAULT_MESSAGE="Too many requests";class Gc extends Gn{constructor(e,t,r){super(null!=e?e:Gc.DEFAULT_MESSAGE,null!=t?t:"unauthorized",r)}}Gc.DEFAULT_MESSAGE="Unauthorized";const Yc=e=>(t,r,n)=>new e(t,r,n),$c={check_access_fail:Yc(Hc),join_room_fail:Yc(qc),need_joined_to_channel:Yc(Kn),forbidden:Yc(Hc),not_found:Yc(Yn),invalid_request:Yc(qc),invalid_payload:Yc(qc),already_created:Yc(Wc),too_many_requests:Yc(zc),something_went_wrong:Yc($n),di_error:Yc(qc),resources_lock_error:Yc(qc),already_connected:Yc(io),timeout:Yc(Jn),unauthorized:Yc(Gc)},Jc=e=>{if(!(e=>"object"==typeof e&&null!==e&&!Array.isArray(e))(e))return!1;const{error:t,errorCode:r}=e;return!(void 0!==t&&"string"!=typeof t||void 0!==r&&"string"!=typeof r)},Qc=(e,t)=>{var r,n,i,s;const o={};return t&&Object.keys(t).length>0&&(o.response=t),"number"==typeof(null===(r=e.response)||void 0===r?void 0:r.status)&&(o.status=e.response.status),(null===(n=e.response)||void 0===n?void 0:n.statusText)&&(o.statusText=e.response.statusText),e.code&&(o.axiosCode=e.code),(null===(i=e.config)||void 0===i?void 0:i.url)&&(o.url=e.config.url),(null===(s=e.config)||void 0===s?void 0:s.method)&&(o.method=e.config.method),Object.keys(o).length>0?o:void 0};var Kc;!function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"}(Kc||(Kc={}));const Zc=["/ping","/ice-parameters"];let Xc=class extends class extends class{constructor(e={}){var{securityWorker:t,secure:n,format:i}=e,s=r(e,["securityWorker","secure","format"]);this.securityData=null,this.setSecurityData=e=>{this.securityData=e},this.request=e=>o(this,void 0,void 0,(function*(){var{secure:t,path:n,type:i,query:s,format:o,body:a}=e,c=r(e,["secure","path","type","query","format","body"]);const d=("boolean"==typeof t?t:this.secure)&&this.securityWorker&&(yield this.securityWorker(this.securityData))||{},u=this.mergeRequestParams(c,d),l=o||this.format||void 0;return i===Kc.FormData&&a&&null!==a&&"object"==typeof a&&(a=this.createFormData(a)),i===Kc.Text&&a&&null!==a&&"string"!=typeof a&&(a=JSON.stringify(a)),this.instance.request(Object.assign(Object.assign({},u),{headers:Object.assign(Object.assign({},u.headers||{}),i&&i!==Kc.FormData?{"Content-Type":i}:{}),params:s,responseType:l,data:a,url:n}))})),this.instance=Bc.create(Object.assign(Object.assign({},s),{baseURL:s.baseURL||"signaling.livedigital.space/v1"})),this.secure=n,this.format=i,this.securityWorker=t}mergeRequestParams(e,t){const r=e.method||t&&t.method;return Object.assign(Object.assign(Object.assign(Object.assign({},this.instance.defaults),e),t||{}),{headers:Object.assign(Object.assign(Object.assign({},r&&this.instance.defaults.headers[r.toLowerCase()]||{}),e.headers||{}),t&&t.headers||{})})}stringifyFormItem(e){return"object"==typeof e&&null!==e?JSON.stringify(e):`${e}`}createFormData(e){return Object.keys(e||{}).reduce(((t,r)=>{const n=e[r],i=n instanceof Array?n:[n];for(const e of i){const n=e instanceof Blob||e instanceof File;t.append(r,n?e:this.stringifyFormItem(e))}return t}),new FormData)}}{constructor(){super(...arguments),this.peers={getPeers:(e,t={})=>this.request(Object.assign({path:"/peers",method:"GET",query:e,secure:!0,format:"json"},t)),registerPeer:(e,t={})=>this.request(Object.assign({path:"/peers",method:"POST",body:e,secure:!0,type:Kc.Json,format:"json"},t)),disconnectPeer:(e={})=>this.request(Object.assign({path:"/peers",method:"DELETE",secure:!0},e)),changePeerProducePermissions:(e,t,r={})=>this.request(Object.assign({path:`/peers/${e}/produce-permissions`,method:"PUT",body:t,secure:!0,type:Kc.Json},r)),addPeerProducePermissions:(e,t,r={})=>this.request(Object.assign({path:`/peers/${e}/produce-permissions/${t}`,method:"POST",secure:!0},r)),removePeerProducePermissions:(e,t,r={})=>this.request(Object.assign({path:`/peers/${e}/produce-permissions/${t}`,method:"DELETE",secure:!0},r))},this.router={getRtpCapabilities:(e={})=>this.request(Object.assign({path:"/router/rtp-capabilities",method:"GET",secure:!0,format:"json"},e))},this.channel={confirmChannelActivity:(e={})=>this.request(Object.assign({path:"/channel/activity",method:"PATCH",secure:!0},e)),triggerChannelStateEvent:(e,t={})=>this.request(Object.assign({path:"/channel/peers-state-message-id",method:"GET",query:e,secure:!0,format:"json"},t))},this.ping={pingPeer:(e={})=>this.request(Object.assign({path:"/ping",method:"POST",secure:!0},e))},this.appData={updateSelfPeerAppData:(e,t={})=>this.request(Object.assign({path:"/app-data",method:"PUT",body:e,secure:!0,type:Kc.Json},t))},this.producer={getGeneralDataProducer:(e={})=>this.request(Object.assign({path:"/producer/general-data",method:"GET",secure:!0,format:"json"},e)),getAudioObserverProducer:(e={})=>this.request(Object.assign({path:"/producer/audio-observer",method:"GET",secure:!0,format:"json"},e)),getChannelStateSyncDataProducer:(e={})=>this.request(Object.assign({path:"/producer/channel-state-sync-data",method:"GET",secure:!0,format:"json"},e)),closeProducer:(e,t={})=>this.request(Object.assign({path:`/producer/${e}`,method:"DELETE",secure:!0},t)),pauseProducer:(e,t={})=>this.request(Object.assign({path:`/producer/${e}/actions/pause`,method:"POST",secure:!0},t)),resumeProducer:(e,t={})=>this.request(Object.assign({path:`/producer/${e}/actions/resume`,method:"POST",secure:!0},t)),requestProducerMaxSpatialLayer:(e,t,r={})=>this.request(Object.assign({path:`/producer/${e}/max-spatial-layer`,method:"POST",body:t,secure:!0,type:Kc.Json},r)),setProducerMaxSpatialLayer:(e,t,r={})=>this.request(Object.assign({path:`/producer/${e}/max-spatial-layer`,method:"PUT",body:t,secure:!0,type:Kc.Json},r))},this.consumer={createConsumer:(e,t={})=>this.request(Object.assign({path:"/consumer",method:"POST",body:e,secure:!0,type:Kc.Json,format:"json"},t)),closeConsumer:(e,t={})=>this.request(Object.assign({path:`/consumer/${e}`,method:"DELETE",secure:!0},t)),pauseConsumer:(e,t={})=>this.request(Object.assign({path:`/consumer/${e}/actions/pause`,method:"POST",secure:!0},t)),resumeConsumer:(e,t={})=>this.request(Object.assign({path:`/consumer/${e}/actions/resume`,method:"POST",secure:!0},t)),updateConsumerPreferredLayers:(e,t,r={})=>this.request(Object.assign({path:`/consumer/${e}/preferred-layers`,method:"PUT",body:t,secure:!0,type:Kc.Json},r)),requestConsumerKeyFrame:(e,t={})=>this.request(Object.assign({path:`/consumer/${e}/key-frame`,method:"POST",secure:!0},t))},this.dataConsumer={createDataConsumer:(e,t={})=>this.request(Object.assign({path:"/data-consumer",method:"POST",body:e,secure:!0,type:Kc.Json,format:"json"},t))},this.transport={createTransport:(e,t={})=>this.request(Object.assign({path:"/transport",method:"POST",body:e,secure:!0,type:Kc.Json,format:"json"},t)),getTransportIceParameters:(e,t={})=>this.request(Object.assign({path:`/transport/${e}/ice-parameters`,method:"GET",secure:!0,format:"json"},t)),connectTransport:(e,t,r={})=>this.request(Object.assign({path:`/transport/${e}/connect`,method:"PUT",body:t,secure:!0,type:Kc.Json},r)),produceMediaToTransport:(e,t,r={})=>this.request(Object.assign({path:`/transport/${e}/media-producer`,method:"PUT",body:t,secure:!0,type:Kc.Json,format:"json"},r)),produceDataToTransport:(e,t,r={})=>this.request(Object.assign({path:`/transport/${e}/data-producer`,method:"PUT",body:t,secure:!0,type:Kc.Json,format:"json"},r)),closeTransport:(e,t={})=>this.request(Object.assign({path:`/transport/${e}`,method:"DELETE",secure:!0},t))}}}{constructor(e){super({baseURL:String("https://signaling-api.livedigital.space/v1"),securityWorker:e=>{if(!e)return;const t={};return e.token&&(t.Authorization=`Bearer ${e.token}`),e.peerApiVersion&&(t["x-peer-api-version"]=String(e.peerApiVersion)),e.datacenterType&&(t["x-datacenter-type"]=e.datacenterType),e.preferredDC&&(t["x-datacenter-name"]=e.preferredDC),{headers:t}}}),this.config=e,this.errorListeners=new Set,this.abortController=new AbortController,this.instance.interceptors.request.use((e=>(!e.signal&&this.abortController&&(e.signal=this.abortController.signal),e))),Ro(this.instance,{retries:3,shouldResetTimeout:!0,retryDelay:e=>Math.min(300*Math.pow(2,e-1),2e3)+300*Math.random(),retryCondition:e=>{var t,r;return"ERR_CANCELED"!==e.code&&(("string"!=typeof(r=null===(t=e.config)||void 0===t?void 0:t.url)||!Zc.some((e=>r.includes(e))))&&(Ro.isNetworkError(e)||"ECONNABORTED"===e.code&&!e.response))}}),this.instance.interceptors.response.use((e=>e),(e=>{const t=(e=>{var t,r;if(!Bc.isAxiosError(e))return e instanceof Error?e:new $n;const n=e;if(!n.response){const e=Qc(n),r=n.message||$n.DEFAULT_MESSAGE,i=null!==(t=n.code)&&void 0!==t?t:"network_error";return new $n(r,i,e)}const i=Jc(n.response.data)?n.response.data:void 0,s="string"==typeof(null==i?void 0:i.errorCode)?i.errorCode:void 0,o="string"==typeof(null==i?void 0:i.error)?i.error:void 0,a=(o&&o.trim().length>0?o:n.message)||$n.DEFAULT_MESSAGE,c=Qc(n,i);if(s){const e=$c[s];return e?e(a,s,c):new $n(a,s,c)}const d=null!==(r=n.code)&&void 0!==r?r:"number"==typeof n.response.status?`http_${n.response.status}`:"something_went_wrong";return new $n(a,d,c)})(e);throw this.notifyErrorListeners(t),t})),this.instance.defaults.timeout=7e3;const t=this.config.get("signalingServerUrl");t&&(this.instance.defaults.baseURL=t)}abortPendingRequests(e){this.abortController.abort(e),this.abortController=new AbortController}addErrorListener(e){return this.errorListeners.add(e),()=>{this.errorListeners.delete(e)}}notifyErrorListeners(e){this.errorListeners.forEach((t=>{try{t(e)}catch(e){}}))}};Xc=n([ot(),i(0,ct(fi.Config)),s("design:paramtypes",[Et])],Xc);var ed=Xc;class td{constructor(e){this.missingPeers=e.missingPeers,this.missingProducers=e.missingProducers,this.consumersWithInconsistentState=e.consumersWithInconsistentState,this.producersWithInconsistentState=e.producersWithInconsistentState,this.peersWithInconsistentAppData=e.peersWithInconsistentAppData}hasInconsistencyCases(){return this.missingPeers.length>0||this.missingProducers.length>0||this.consumersWithInconsistentState.length>0||this.producersWithInconsistentState.length>0||this.peersWithInconsistentAppData.length>0}}class rd{constructor(e){this.missingPeers=[],this.missingProducers=[],this.consumersWithInconsistentState=[],this.producersWithInconsistentState=[],this.peersWithInconsistentAppData=[],this.localState=e.localState,this.remoteState=e.remoteState}check(){return this.resetPreviousCheckResults(),this.remoteState.peers.forEach((e=>{const t=this.findLocalPeerById(e.id);if(!t)return void this.missingPeers.push(e.id);t.appDataHash!==e.appDataHash&&this.peersWithInconsistentAppData.push(e.id),e.producers.forEach((e=>{const r=this.findLocalProducerById(t,e.id);if(!r)return void this.missingProducers.push(e.id);if(this.isLocalProducerStateChangedRecently(r))return;if(r.paused!==e.paused)return void this.producersWithInconsistentState.push(e.id);const n=this.findLocalConsumerByProducerId(t,e.id);n&&n.paused!==e.paused&&this.consumersWithInconsistentState.push(n.id),r||this.missingProducers.push(e.id)}))})),new td({missingPeers:this.missingPeers,missingProducers:this.missingProducers,consumersWithInconsistentState:this.consumersWithInconsistentState,producersWithInconsistentState:this.producersWithInconsistentState,peersWithInconsistentAppData:this.peersWithInconsistentAppData})}getMissingPeers(){return this.missingPeers}getMissingProducers(){return this.missingProducers}getConsumersWithInconsistentState(){return this.consumersWithInconsistentState}getProducersWithInconsistentState(){return this.producersWithInconsistentState}getPeersWithInconsistentAppData(){return this.peersWithInconsistentAppData}findLocalPeerById(e){return this.localState.peers.find((t=>t.id===e))}findLocalConsumerByProducerId(e,t){var r;return null===(r=e.consumers)||void 0===r?void 0:r.find((e=>e.producerId===t))}findLocalProducerById(e,t){return e.producers.find((e=>e.id===t))}resetPreviousCheckResults(){this.missingPeers=[],this.missingProducers=[],this.consumersWithInconsistentState=[],this.producersWithInconsistentState=[],this.peersWithInconsistentAppData=[]}isLocalProducerStateChangedRecently(e){return Date.now()-e.stateChangedAt<5e3}}var nd,id,sd,od,ad,cd,dd;!function(e){e.MissingPeer="missing-peer",e.MissingProducer="missing-producer",e.IncorrectProducerState="incorrect-producer-state",e.IncorrectConsumerState="incorrect-consumer-state",e.IncorrectAppData="incorrect-app-data"}(nd||(nd={}));let ud=class{constructor(e,t,r,n,i,s,o){var a;this.network=t,this.callState=r,this.peersStorage=n,this.clientEventEmitter=i,this.signalingApiClient=s,this.webRtcIssueDetector=o,id.set(this,void 0),sd.set(this,void 0),od.set(this,[]),ad.set(this,!1),cd.set(this,{inbound:4.3,outbound:4.3}),dd.set(this,(new Date).getTime()-15e3),c(this,sd,null===(a=this.webRtcIssueDetector)||void 0===a?void 0:a.eventEmitter,"f"),c(this,id,e("ChannelStateSyncEventHandler"),"f"),this.debouncedHandleChannelStateEvent=ii(this.handleChannelStateEvent.bind(this),3e3),this.listenNetworkScoresUpdatedEvents()}handleChannelStateShort(e){return o(this,void 0,void 0,(function*(){try{yield this.debouncedHandleChannelStateEvent(e)}catch(e){a(this,id,"f").error("handleChannelStateSyncEvent()",{error:Vt(e)})}}))}handleChannelStateEvent(e){return o(this,void 0,void 0,(function*(){if(a(this,ad,"f"))a(this,id,"f").warn("Channel state event is already being handled, skipping new event",{case:"handleChannelStateEvent"});else{c(this,ad,!0,"f");try{yield this.collectProbableInconsistencyCases(e);const t=this.getConfirmedInconsistencyResult();if(!(null==t?void 0:t.hasInconsistencyCases()))return;if(this.isRestoreStateRequestToEarly())return void a(this,id,"f").info("Inconsistency detected, but restore skipped",Object.assign({},t));this.handleConfirmedInconsistencyResult(t)}finally{c(this,ad,!1,"f")}}}))}getLastInconsistencyCheckResult(){return a(this,od,"f")[a(this,od,"f").length-1]}handleConfirmedInconsistencyResult(e){e.missingPeers.forEach((e=>{this.clientEventEmitter.safeEmit(en,{peerId:e,peersLoaded:this.network.peersLoaded,sdkInstances:Array.from(window._sdkMarks||[]).length,type:nd.MissingPeer})})),e.missingProducers.forEach((e=>{this.clientEventEmitter.safeEmit(en,{producerId:e,type:nd.MissingProducer})})),e.producersWithInconsistentState.forEach((e=>{this.clientEventEmitter.safeEmit(en,{producerId:e,type:nd.IncorrectProducerState})})),e.peersWithInconsistentAppData.forEach((e=>{this.clientEventEmitter.safeEmit(en,{peerId:e,type:nd.IncorrectAppData})}))}getConfirmedInconsistencyResult(){const e=this.getLastInconsistencyCheckResult();if(!e)return;return new td({missingPeers:this.getConfirmedMissingPeers(e.missingPeers),missingProducers:this.getConfirmedMissingProducers(e.missingProducers),consumersWithInconsistentState:this.getConfirmedConsumersWithInconsistencState(e.consumersWithInconsistentState),producersWithInconsistentState:this.getConfirmedProducersWithInconsistencState(e.producersWithInconsistentState),peersWithInconsistentAppData:this.getConfirmedPeersWithInconsistentAppData(e.missingPeers)})}collectProbableInconsistencyCases(e){return o(this,void 0,void 0,(function*(){const t=new rd({remoteState:e,localState:this.getLocalState()}).check();if(this.rotateLastProbableInconsistencyCheckResults(t),!t.hasInconsistencyCases())return;if(this.isBadNetworkScore())return void this.resetLastProbableInconsistencyCheckResults();(yield this.getIsConnectionActive())&&this.callState.isJoined&&this.network.isNetworkActive||this.resetLastProbableInconsistencyCheckResults()}))}resetLastProbableInconsistencyCheckResults(){c(this,od,[],"f")}rotateLastProbableInconsistencyCheckResults(e){4===a(this,od,"f").length&&a(this,od,"f").shift(),a(this,od,"f").push(e)}isReachedMaxCheckRetries(e,t,r=4){let n=0;return a(this,od,"f").forEach((r=>{r[e].includes(t)&&(n+=1)})),n>=r}getConfirmedMissingPeers(e){return e.filter((e=>this.isReachedMaxCheckRetries("missingPeers",e)))}getConfirmedMissingProducers(e){return e.filter((e=>this.isReachedMaxCheckRetries("missingProducers",e)))}getConfirmedConsumersWithInconsistencState(e){return e.filter((e=>this.isReachedMaxCheckRetries("consumersWithInconsistentState",e,1)))}getConfirmedProducersWithInconsistencState(e){return e.filter((e=>this.isReachedMaxCheckRetries("producersWithInconsistentState",e)))}getConfirmedPeersWithInconsistentAppData(e){return e.filter((e=>this.isReachedMaxCheckRetries("peersWithInconsistentAppData",e)))}getLocalState(){return{peers:this.peersStorage.hosts().map((e=>({id:e.id,appDataHash:go(e.appData),producers:e.getProducers().map((e=>({id:e.id,paused:e.paused,stateChangedAt:e.getStateChangedAt()}))),consumers:e.getConsumersState()})))}}getIsConnectionActive(){return o(this,void 0,void 0,(function*(){try{return!!this.network.isNetworkActive&&(yield this.signalingApiClient.ping.pingPeer(),!0)}catch(e){return!1}}))}listenNetworkScoresUpdatedEvents(){a(this,sd,"f")&&a(this,sd,"f").on(Wt.NetworkScoresUpdated,(e=>{e.inbound&&(a(this,cd,"f").inbound=e.inbound),e.outbound&&(a(this,cd,"f").outbound=e.outbound)}))}isBadNetworkScore(){const{inbound:e,outbound:t}=a(this,cd,"f");return e<=2.6||t<=2.6}compareCheckedAndRestoredResults(e,t){return new td({missingPeers:e.missingPeers.filter((e=>!t.missingPeers.includes(e))),missingProducers:e.missingProducers.filter((e=>!t.missingProducers.includes(e))),consumersWithInconsistentState:e.consumersWithInconsistentState.filter((e=>!t.fixedConsumersState.includes(e))),producersWithInconsistentState:e.producersWithInconsistentState.filter((e=>!t.fixedProducersState.includes(e))),peersWithInconsistentAppData:e.peersWithInconsistentAppData.filter((e=>!t.restoredAppDataPeers.includes(e)))})}isRestoreStateRequestToEarly(){return(new Date).getTime()-a(this,dd,"f")<=15e3}};id=new WeakMap,sd=new WeakMap,od=new WeakMap,ad=new WeakMap,cd=new WeakMap,dd=new WeakMap,ud=n([ot(),i(0,ct(fi.LoggerFactory)),i(1,ct(fi.Network)),i(2,ct(fi.CallState)),i(3,ct(fi.PeersStorage)),i(4,ct(fi.ClientEventEmitter)),i(5,ct(fi.SignalingApiClient)),i(6,ct(fi.WebRTCIssueDetector)),s("design:paramtypes",[Function,uo,mi,po,Ft,ed,Pr])],ud);var ld=ud,pd={},hd={exports:{}},fd=1e3,md=6e4,gd=60*md,vd=24*gd,yd=function(e,t){t=t||{};var r=typeof e;if("string"===r&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return 6048e5*r;case"days":case"day":case"d":return r*vd;case"hours":case"hour":case"hrs":case"hr":case"h":return r*gd;case"minutes":case"minute":case"mins":case"min":case"m":return r*md;case"seconds":case"second":case"secs":case"sec":case"s":return 1e3*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(e);if("number"===r&&isFinite(e))return t.long?function(e){var t=Math.abs(e);if(t>=vd)return bd(e,t,vd,"day");if(t>=gd)return bd(e,t,gd,"hour");if(t>=md)return bd(e,t,md,"minute");if(t>=1e3)return bd(e,t,1e3,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=vd)return Math.round(e/vd)+"d";if(t>=gd)return Math.round(e/gd)+"h";if(t>=md)return Math.round(e/md)+"m";if(t>=fd)return Math.round(e/fd)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function bd(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}var _d=function(e){function t(e){let n,i,s,o=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,i)=>{if("%%"===n)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];n=s.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e,t){let r=0,n=0,i=-1,s=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(i=n,s=r,n++):(r++,n++);else{if(-1===i)return!1;n=i+1,s++,r=s}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(n(e,r))return!1;for(const r of t.names)if(n(e,r))return!0;return!1},t.humanize=yd,t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=_d(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(hd,hd.exports);var Ed={};Object.defineProperty(Ed,"__esModule",{value:!0});var wd={},Sd={};Object.defineProperty(Sd,"__esModule",{value:!0}),Sd.Logger=void 0;const Cd=hd.exports,Pd="mediasoup-client";Sd.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Cd.default)(`${Pd}:${e}`),this._warn=(0,Cd.default)(`${Pd}:WARN:${e}`),this._error=(0,Cd.default)(`${Pd}:ERROR:${e}`)):(this._debug=(0,Cd.default)(Pd),this._warn=(0,Cd.default)(`${Pd}:WARN`),this._error=(0,Cd.default)(`${Pd}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};var Td={};Object.defineProperty(Td,"__esModule",{value:!0}),Td.EnhancedEventEmitter=void 0;const Rd=wt.exports,kd=new Sd.Logger("EnhancedEventEmitter");class Dd extends Rd.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}close(){super.removeAllListeners()}emit(e,...t){return super.emit(e,...t)}safeEmit(e,...t){try{return super.emit(e,...t)}catch(t){kd.error("safeEmit() | event listener threw an error [eventName:%s]:%o",e,t);try{super.emit("listenererror",e,t)}catch(e){}return Boolean(super.listenerCount(e))}}on(e,t){return super.on(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.on(e,t),this}prependListener(e,t){return super.prependListener(e,t),this}once(e,t){return super.once(e,t),this}prependOnceListener(e,t){return super.prependOnceListener(e,t),this}removeListener(e,t){return super.off(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}rawListeners(e){return super.rawListeners(e)}}Td.EnhancedEventEmitter=Dd;var Id={};Object.defineProperty(Id,"__esModule",{value:!0}),Id.InvalidStateError=Id.UnsupportedError=void 0;class Ad extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ad):this.stack=new Error(e).stack}}Id.UnsupportedError=Ad;class Od extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Od):this.stack=new Error(e).stack}}Id.InvalidStateError=Od;var Md={};Object.defineProperty(Md,"__esModule",{value:!0}),Md.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))},Md.generateRandomNumber=function(){return Math.round(1e7*Math.random())},Md.deepFreeze=function e(t){const r=Reflect.ownKeys(t);for(const n of r){const r=t[n];(r&&"object"==typeof r||"function"==typeof r)&&e(r)}return Object.freeze(t)};var Nd={},Ld={},xd={},Fd={exports:{}};var jd=function(e){function t(e){let n,i,s,o=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,i)=>{if("%%"===n)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];n=s.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e,t){let r=0,n=0,i=-1,s=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(i=n,s=r,n++):(r++,n++);else{if(-1===i)return!1;n=i+1,s++,r=s}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(n(e,r))return!1;for(const r of t.names)if(n(e,r))return!0;return!1},t.humanize=yd,t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=jd(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Fd,Fd.exports),Object.defineProperty(xd,"__esModule",{value:!0}),xd.Logger=void 0;const Ud=Fd.exports,Vd="h264-profile-level-id";xd.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Ud.default)(`${Vd}:${e}`),this._warn=(0,Ud.default)(`${Vd}:WARN:${e}`),this._error=(0,Ud.default)(`${Vd}:ERROR:${e}`)):(this._debug=(0,Ud.default)(Vd),this._warn=(0,Ud.default)(`${Vd}:WARN`),this._error=(0,Ud.default)(`${Vd}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}},Object.defineProperty(Ld,"__esModule",{value:!0}),Ld.ProfileLevelId=Ld.Level=Ld.Profile=void 0,Ld.parseProfileLevelId=Qd,Ld.profileLevelIdToString=Kd,Ld.profileToString=function(e){switch(e){case Wd.ConstrainedBaseline:return"ConstrainedBaseline";case Wd.Baseline:return"Baseline";case Wd.Main:return"Main";case Wd.ConstrainedHigh:return"ConstrainedHigh";case Wd.High:return"High";case Wd.PredictiveHigh444:return"PredictiveHigh444";default:return void Bd.warn(`profileToString() | unrecognized profile ${e}`)}},Ld.levelToString=function(e){switch(e){case Hd.L1_b:return"1b";case Hd.L1:return"1";case Hd.L1_1:return"1.1";case Hd.L1_2:return"1.2";case Hd.L1_3:return"1.3";case Hd.L2:return"2";case Hd.L2_1:return"2.1";case Hd.L2_2:return"2.2";case Hd.L3:return"3";case Hd.L3_1:return"3.1";case Hd.L3_2:return"3.2";case Hd.L4:return"4";case Hd.L4_1:return"4.1";case Hd.L4_2:return"4.2";case Hd.L5:return"5";case Hd.L5_1:return"5.1";case Hd.L5_2:return"5.2";default:return void Bd.warn(`levelToString() | unrecognized level ${e}`)}},Ld.parseSdpProfileLevelId=Zd,Ld.isSameProfile=function(e={},t={}){const r=Zd(e),n=Zd(t);return Boolean(r&&n&&r.profile===n.profile)},Ld.isSameProfileAndLevel=function(e={},t={}){const r=Zd(e),n=Zd(t);return Boolean(r&&n&&r.profile===n.profile&&r.level==n.level)},Ld.generateProfileLevelIdStringForAnswer=function(e={},t={}){if(!e["profile-level-id"]&&!t["profile-level-id"])return void Bd.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");const r=Zd(e),n=Zd(t);if(!r)throw new TypeError("invalid local_profile_level_id");if(!n)throw new TypeError("invalid remote_profile_level_id");if(r.profile!==n.profile)throw new TypeError("H264 Profile mismatch");const i=eu(e)&&eu(t),s=r.level,o=n.level,a=function(e,t){return function(e,t){if(e===Hd.L1_b)return t!==Hd.L1&&t!==Hd.L1_b;if(t===Hd.L1_b)return e!==Hd.L1;return e<t}(e,t)?e:t}(s,o),c=i?s:a;return Bd.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${r.profile}, level:${c}]`),Kd(new qd(r.profile,c))},Ld.supportedLevel=function(e,t){for(let r=Jd.length-1;r>=0;--r){const n=Jd[r];if(256*n.max_macroblock_frame_size<=e&&n.max_macroblocks_per_second<=t*n.max_macroblock_frame_size)return Bd.debug(`supportedLevel() | result [max_frame_pixel_count:${e}, max_fps:${t}, level:${n.level}]`),n.level}return void Bd.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${e}, max_fps:${t}]`)};const Bd=new xd.Logger;var Wd,Hd;!function(e){e[e.ConstrainedBaseline=1]="ConstrainedBaseline",e[e.Baseline=2]="Baseline",e[e.Main=3]="Main",e[e.ConstrainedHigh=4]="ConstrainedHigh",e[e.High=5]="High",e[e.PredictiveHigh444=6]="PredictiveHigh444"}(Wd||(Ld.Profile=Wd={})),function(e){e[e.L1_b=0]="L1_b",e[e.L1=10]="L1",e[e.L1_1=11]="L1_1",e[e.L1_2=12]="L1_2",e[e.L1_3=13]="L1_3",e[e.L2=20]="L2",e[e.L2_1=21]="L2_1",e[e.L2_2=22]="L2_2",e[e.L3=30]="L3",e[e.L3_1=31]="L3_1",e[e.L3_2=32]="L3_2",e[e.L4=40]="L4",e[e.L4_1=41]="L4_1",e[e.L4_2=42]="L4_2",e[e.L5=50]="L5",e[e.L5_1=51]="L5_1",e[e.L5_2=52]="L5_2"}(Hd||(Ld.Level=Hd={}));class qd{profile;level;constructor(e,t){this.profile=e,this.level=t}}Ld.ProfileLevelId=qd;const zd=new qd(Wd.ConstrainedBaseline,Hd.L3_1);class Gd{mask;masked_value;constructor(e){this.mask=~Xd("x",e),this.masked_value=Xd("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}}class Yd{profile_idc;profile_iop;profile;constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}}const $d=[new Yd(66,new Gd("x1xx0000"),Wd.ConstrainedBaseline),new Yd(77,new Gd("1xxx0000"),Wd.ConstrainedBaseline),new Yd(88,new Gd("11xx0000"),Wd.ConstrainedBaseline),new Yd(66,new Gd("x0xx0000"),Wd.Baseline),new Yd(88,new Gd("10xx0000"),Wd.Baseline),new Yd(77,new Gd("0x0x0000"),Wd.Main),new Yd(100,new Gd("00000000"),Wd.High),new Yd(100,new Gd("00001100"),Wd.ConstrainedHigh),new Yd(244,new Gd("00000000"),Wd.PredictiveHigh444)],Jd=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:Hd.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:Hd.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:Hd.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:Hd.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:Hd.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:Hd.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:Hd.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:Hd.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:Hd.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:Hd.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:Hd.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:Hd.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:Hd.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:Hd.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:Hd.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:Hd.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:Hd.L5_2}];function Qd(e){if("string"!=typeof e||6!==e.length)return;const t=parseInt(e,16);if(0===t)return;const r=255&t,n=t>>8&255,i=t>>16&255;let s;switch(r){case Hd.L1_1:s=0!=(16&n)?Hd.L1_b:Hd.L1_1;break;case Hd.L1:case Hd.L1_2:case Hd.L1_3:case Hd.L2:case Hd.L2_1:case Hd.L2_2:case Hd.L3:case Hd.L3_1:case Hd.L3_2:case Hd.L4:case Hd.L4_1:case Hd.L4_2:case Hd.L5:case Hd.L5_1:case Hd.L5_2:s=r;break;default:return void Bd.warn(`parseProfileLevelId() | unrecognized level_idc [str:${e}, level_idc:${r}]`)}for(const t of $d)if(i===t.profile_idc&&t.profile_iop.isMatch(n))return Bd.debug(`parseProfileLevelId() | result [str:${e}, profile:${t.profile}, level:${s}]`),new qd(t.profile,s);Bd.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${e}, profile_idc:${i}, profile_iop:${n}]`)}function Kd(e){if(e.level==Hd.L1_b)switch(e.profile){case Wd.ConstrainedBaseline:return"42f00b";case Wd.Baseline:return"42100b";case Wd.Main:return"4d100b";default:return void Bd.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${e.profile}`)}let t;switch(e.profile){case Wd.ConstrainedBaseline:t="42e0";break;case Wd.Baseline:t="4200";break;case Wd.Main:t="4d00";break;case Wd.ConstrainedHigh:t="640c";break;case Wd.High:t="6400";break;case Wd.PredictiveHigh444:t="f400";break;default:return void Bd.warn(`profileLevelIdToString() | unrecognized profile ${e.profile}`)}let r=e.level.toString(16);return 1===r.length&&(r=`0${r}`),`${t}${r}`}function Zd(e={}){const t=e["profile-level-id"];return t?Qd(t):zd}function Xd(e,t){return Number(t[0]===e)<<7|Number(t[1]===e)<<6|Number(t[2]===e)<<5|Number(t[3]===e)<<4|Number(t[4]===e)<<3|Number(t[5]===e)<<2|Number(t[6]===e)<<1|Number(t[7]===e)<<0}function eu(e={}){const t=e["level-asymmetry-allowed"];return!0===t||1===t||"1"===t}Object.defineProperty(Nd,"__esModule",{value:!0}),Nd.validateAndNormalizeRtpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(e.codecs&&!Array.isArray(e.codecs))throw new TypeError("caps.codecs is not an array");e.codecs||(e.codecs=[]);for(const t of e.codecs)iu(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)ou(t)},Nd.validateAndNormalizeRtpParameters=nu,Nd.validateAndNormalizeSctpStreamParameters=function(e){if("object"!=typeof e)throw new TypeError("params is not an object");if("number"!=typeof e.streamId)throw new TypeError("missing params.streamId");let t=!1;"boolean"==typeof e.ordered?t=!0:e.ordered=!0;if(e.maxPacketLifeTime&&"number"!=typeof e.maxPacketLifeTime)throw new TypeError("invalid params.maxPacketLifeTime");if(e.maxRetransmits&&"number"!=typeof e.maxRetransmits)throw new TypeError("invalid params.maxRetransmits");if(e.maxPacketLifeTime&&e.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(t&&e.ordered&&(e.maxPacketLifeTime||e.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");t||!e.maxPacketLifeTime&&!e.maxRetransmits||(e.ordered=!1);if(e.label&&"string"!=typeof e.label)throw new TypeError("invalid params.label");if(e.protocol&&"string"!=typeof e.protocol)throw new TypeError("invalid params.protocol")},Nd.validateSctpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(!e.numStreams||"object"!=typeof e.numStreams)throw new TypeError("missing caps.numStreams");!function(e){if("object"!=typeof e)throw new TypeError("numStreams is not an object");if("number"!=typeof e.OS)throw new TypeError("missing numStreams.OS");if("number"!=typeof e.MIS)throw new TypeError("missing numStreams.MIS")}(e.numStreams)},Nd.getExtendedRtpCapabilities=function(e,t,r){const n={codecs:[],headerExtensions:[]};if(r)for(const r of e.codecs??[]){if(lu(r))continue;const e=(t.codecs??[]).find((e=>pu(e,r,{strict:!0,modify:!0})));if(!e)continue;const i={kind:r.kind,mimeType:r.mimeType,clockRate:r.clockRate,channels:r.channels,localPayloadType:r.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:e.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:r.parameters??{},remoteParameters:e.parameters??{},rtcpFeedback:fu(r,e)};n.codecs.push(i)}else for(const r of t.codecs??[]){if(lu(r))continue;const t=(e.codecs??[]).find((e=>pu(e,r,{strict:!0,modify:!0})));if(!t)continue;const i={kind:t.kind,mimeType:t.mimeType,clockRate:t.clockRate,channels:t.channels,localPayloadType:t.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:r.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:t.parameters??{},remoteParameters:r.parameters??{},rtcpFeedback:fu(t,r)};n.codecs.push(i)}for(const r of n.codecs){const n=e.codecs.find((e=>lu(e)&&e.parameters?.apt===r.localPayloadType)),i=t.codecs.find((e=>lu(e)&&e.parameters?.apt===r.remotePayloadType));n&&i&&(r.localRtxPayloadType=n.preferredPayloadType,r.remoteRtxPayloadType=i.preferredPayloadType)}for(const r of t.headerExtensions){const t=e.headerExtensions.find((e=>hu(e,r)));if(!t)continue;const i={kind:r.kind,uri:r.uri,sendId:t.preferredId,recvId:r.preferredId,encrypt:t.preferredEncrypt??!1,direction:"sendrecv"};switch(r.direction){case"sendrecv":i.direction="sendrecv";break;case"recvonly":i.direction="sendonly";break;case"sendonly":i.direction="recvonly";break;case"inactive":i.direction="inactive"}n.headerExtensions.push(i)}return n},Nd.getRecvRtpCapabilities=function(e){return uu({direction:"recvonly",extendedRtpCapabilities:e})},Nd.getSendRtpCapabilities=function(e){return uu({direction:"sendonly",extendedRtpCapabilities:e})},Nd.getSendingRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const n of t.codecs){if(n.kind!==e)continue;const t={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.localParameters,rtcpFeedback:n.rtcpFeedback};if(r.codecs.push(t),n.localRtxPayloadType){const e={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const n of t.headerExtensions){if(n.kind&&n.kind!==e||"sendrecv"!==n.direction&&"sendonly"!==n.direction)continue;const t={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};r.headerExtensions.push(t)}return r},Nd.getSendingRemoteRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const n of t.codecs){if(n.kind!==e)continue;const t={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.remoteParameters,rtcpFeedback:n.rtcpFeedback};if(r.codecs.push(t),n.localRtxPayloadType){const e={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const n of t.headerExtensions){if(n.kind&&n.kind!==e||"sendrecv"!==n.direction&&"sendonly"!==n.direction)continue;const t={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};r.headerExtensions.push(t)}if(r.headerExtensions.some((e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.uri)))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"goog-remb"!==e.type));else if(r.headerExtensions.some((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.uri)))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"transport-cc"!==e.type));else for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"transport-cc"!==e.type&&"goog-remb"!==e.type));return r},Nd.reduceCodecs=function(e,t){const r=[];if(t){for(let n=0;n<e.length;++n)if(pu(e[n],t,{strict:!0})){r.push(e[n]),lu(e[n+1])&&r.push(e[n+1]);break}if(0===r.length)throw new TypeError("no matching codec found")}else r.push(e[0]),lu(e[1])&&r.push(e[1]);return r},Nd.generateProbatorRtpParameters=function(e){nu(e=ru.clone(e));const t={mid:"probator",codecs:[],headerExtensions:[],encodings:[{ssrc:1234}],rtcp:{cname:"probator"}};return t.codecs.push(e.codecs[0]),t.codecs[0].payloadType=127,t.headerExtensions=e.headerExtensions,t},Nd.canSend=function(e,t){return(t.codecs??[]).some((t=>t.kind===e))},Nd.canReceive=function(e,t){if(nu(e),0===e.codecs.length)return!1;const r=e.codecs[0];return(t.codecs??[]).some((e=>e.preferredPayloadType===r.payloadType))};const tu=Ld,ru=Md;function nu(e){if("object"!=typeof e)throw new TypeError("params is not an object");if(e.mid&&"string"!=typeof e.mid)throw new TypeError("params.mid is not a string");if(!Array.isArray(e.codecs))throw new TypeError("missing params.codecs");for(const t of e.codecs)au(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("params.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)cu(t);if(e.encodings&&!Array.isArray(e.encodings))throw new TypeError("params.encodings is not an array");e.encodings||(e.encodings=[]);for(const t of e.encodings)du(t);if(e.rtcp&&"object"!=typeof e.rtcp)throw new TypeError("params.rtcp is not an object");e.rtcp||(e.rtcp={}),function(e){if("object"!=typeof e)throw new TypeError("rtcp is not an object");if(e.cname&&"string"!=typeof e.cname)throw new TypeError("invalid rtcp.cname");e.reducedSize&&"boolean"==typeof e.reducedSize||(e.reducedSize=!0)}(e.rtcp)}function iu(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const r=t.exec(e.mimeType);if(!r)throw new TypeError("invalid codec.mimeType");if(e.kind=r[1].toLowerCase(),"number"!=typeof e.preferredPayloadType)throw new TypeError("missing codec.preferredPayloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===e.kind?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError(`invalid codec parameter [key:${t}s, value:${r}]`);if("apt"===t&&"number"!=typeof r)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)su(t)}function su(e){if("object"!=typeof e)throw new TypeError("fb is not an object");if(!e.type||"string"!=typeof e.type)throw new TypeError("missing fb.type");e.parameter&&"string"==typeof e.parameter||(e.parameter="")}function ou(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if("audio"!==e.kind&&"video"!==e.kind)throw new TypeError("invalid ext.kind");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.preferredId)throw new TypeError("missing ext.preferredId");if(e.preferredEncrypt&&"boolean"!=typeof e.preferredEncrypt)throw new TypeError("invalid ext.preferredEncrypt");if(e.preferredEncrypt||(e.preferredEncrypt=!1),e.direction&&"string"!=typeof e.direction)throw new TypeError("invalid ext.direction");e.direction||(e.direction="sendrecv")}function au(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const r=t.exec(e.mimeType);if(!r)throw new TypeError("invalid codec.mimeType");if("number"!=typeof e.payloadType)throw new TypeError("missing codec.payloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===r[1].toLowerCase()?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError(`invalid codec parameter [key:${t}s, value:${r}]`);if("apt"===t&&"number"!=typeof r)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)su(t)}function cu(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.id)throw new TypeError("missing ext.id");if(e.encrypt&&"boolean"!=typeof e.encrypt)throw new TypeError("invalid ext.encrypt");e.encrypt||(e.encrypt=!1),e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError("invalid header extension parameter")}}function du(e){if("object"!=typeof e)throw new TypeError("encoding is not an object");if(e.ssrc&&"number"!=typeof e.ssrc)throw new TypeError("invalid encoding.ssrc");if(e.rid&&"string"!=typeof e.rid)throw new TypeError("invalid encoding.rid");if(e.rtx&&"object"!=typeof e.rtx)throw new TypeError("invalid encoding.rtx");if(e.rtx&&"number"!=typeof e.rtx.ssrc)throw new TypeError("missing encoding.rtx.ssrc");if(e.dtx&&"boolean"==typeof e.dtx||(e.dtx=!1),e.scalabilityMode&&"string"!=typeof e.scalabilityMode)throw new TypeError("invalid encoding.scalabilityMode")}function uu({direction:e,extendedRtpCapabilities:t}){const r={codecs:[],headerExtensions:[]};for(const e of t.codecs){const t={kind:e.kind,mimeType:e.mimeType,preferredPayloadType:e.remotePayloadType,clockRate:e.clockRate,channels:e.channels,parameters:e.localParameters,rtcpFeedback:e.rtcpFeedback};if(r.codecs.push(t),!e.remoteRtxPayloadType)continue;const n={kind:e.kind,mimeType:`${e.kind}/rtx`,preferredPayloadType:e.remoteRtxPayloadType,clockRate:e.clockRate,parameters:{apt:e.remotePayloadType},rtcpFeedback:[]};r.codecs.push(n)}for(const n of t.headerExtensions){if("sendrecv"!==n.direction&&n.direction!==e)continue;const t={kind:n.kind,uri:n.uri,preferredId:n.recvId,preferredEncrypt:n.encrypt??!1,direction:n.direction};r.headerExtensions.push(t)}return r}function lu(e){return!!e&&/.+\/rtx$/i.test(e.mimeType)}function pu(e,t,{strict:r=!1,modify:n=!1}={}){const i=e.mimeType.toLowerCase();if(i!==t.mimeType.toLowerCase())return!1;if(e.clockRate!==t.clockRate)return!1;if(e.channels!==t.channels)return!1;switch(i){case"video/h264":if(r){if((e.parameters["packetization-mode"]??0)!==(t.parameters["packetization-mode"]??0))return!1;if(!tu.isSameProfile(e.parameters,t.parameters))return!1;let r;try{r=tu.generateProfileLevelIdStringForAnswer(e.parameters,t.parameters)}catch(e){return!1}n&&(r?(e.parameters["profile-level-id"]=r,t.parameters["profile-level-id"]=r):(delete e.parameters["profile-level-id"],delete t.parameters["profile-level-id"]))}break;case"video/vp9":if(r){if((e.parameters["profile-id"]??0)!==(t.parameters["profile-id"]??0))return!1}}return!0}function hu(e,t){return(!e.kind||!t.kind||e.kind===t.kind)&&e.uri===t.uri}function fu(e,t){const r=[];for(const n of e.rtcpFeedback??[]){const e=(t.rtcpFeedback??[]).find((e=>e.type===n.type&&(e.parameter===n.parameter||!e.parameter&&!n.parameter)));e&&r.push(e)}return r}var mu={},gu={},vu={},yu={};Object.defineProperty(yu,"__esModule",{value:!0}),yu.Logger=void 0;const bu=hd.exports,_u="awaitqueue";yu.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=bu(`awaitqueue:${e}`),this._warn=bu(`awaitqueue:WARN:${e}`),this._error=bu(`awaitqueue:ERROR:${e}`)):(this._debug=bu(_u),this._warn=bu("awaitqueue:WARN"),this._error=bu("awaitqueue:ERROR")),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};var Eu={};Object.defineProperty(Eu,"__esModule",{value:!0}),Eu.AwaitQueueRemovedTaskError=Eu.AwaitQueueStoppedError=void 0;class wu extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,wu)}}Eu.AwaitQueueStoppedError=wu;class Su extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Su)}}Eu.AwaitQueueRemovedTaskError=Su,Object.defineProperty(vu,"__esModule",{value:!0}),vu.AwaitQueue=void 0;const Cu=Eu,Pu=new yu.Logger("AwaitQueue");vu.AwaitQueue=class{pendingTasks=new Map;nextTaskId=0;constructor(){Pu.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t,r){if(t=t??e.name,Pu.debug(`push() [name:${t}, options:%o]`,r),"function"!=typeof e)throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch(e){}return new Promise(((n,i)=>{if(t&&r?.removeOngoingTasksWithSameName)for(const e of this.pendingTasks.values())e.name===t&&e.reject(new Cu.AwaitQueueRemovedTaskError,{canExecuteNextTask:!1});const s={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:e=>{if(s.completed)return;s.completed=!0,this.pendingTasks.delete(s.id),Pu.debug(`resolving task [name:${s.name}]`),n(e);const[t]=this.pendingTasks.values();t&&!t.executedAt&&this.execute(t)},reject:(e,{canExecuteNextTask:t})=>{if(!s.completed&&(s.completed=!0,this.pendingTasks.delete(s.id),Pu.debug(`rejecting task [name:${s.name}]: %s`,String(e)),i(e),t)){const[e]=this.pendingTasks.values();e&&!e.executedAt&&this.execute(e)}}};this.pendingTasks.set(s.id,s),1===this.pendingTasks.size&&this.execute(s)}))}stop(){Pu.debug("stop()");for(const e of this.pendingTasks.values())Pu.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Cu.AwaitQueueStoppedError,{canExecuteNextTask:!1})}remove(e){Pu.debug(`remove() [taskIdx:${e}]`);const t=Array.from(this.pendingTasks.values())[e];t?t.reject(new Cu.AwaitQueueRemovedTaskError,{canExecuteNextTask:!0}):Pu.debug(`stop() | no task with given idx [taskIdx:${e}]`)}dump(){const e=Date.now();let t=0;return Array.from(this.pendingTasks.values()).map((r=>({idx:t++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:e-r.enqueuedAt,executionTime:r.executedAt?e-r.executedAt:0})))}async execute(e){if(Pu.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const t=await e.task();e.resolve(t)}catch(t){e.reject(t,{canExecuteNextTask:!0})}}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AwaitQueueRemovedTaskError=e.AwaitQueueStoppedError=e.AwaitQueue=void 0;var t=vu;Object.defineProperty(e,"AwaitQueue",{enumerable:!0,get:function(){return t.AwaitQueue}});var r=Eu;Object.defineProperty(e,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return r.AwaitQueueStoppedError}}),Object.defineProperty(e,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return r.AwaitQueueRemovedTaskError}})}(gu);var Tu={};Object.defineProperty(Tu,"__esModule",{value:!0}),Tu.Producer=void 0;const Ru=Td,ku=Id,Du=new Sd.Logger("Producer");class Iu extends Ru.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new Ru.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:r,track:n,rtpParameters:i,stopTracks:s,disableTrackOnPause:o,zeroRtpOnPause:a,appData:c}){super(),Du.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=r,this._track=n,this._kind=n.kind,this._rtpParameters=i,this._paused=!!o&&!n.enabled,this._maxSpatialLayer=void 0,this._stopTracks=s,this._disableTrackOnPause=o,this._zeroRtpOnPause=a,this._appData=c??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get rtpSender(){return this._rtpSender}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Du.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Du.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new ku.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){Du.debug("pause()"),this._closed?Du.error("pause() | Producer closed"):(this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&new Promise(((e,t)=>{this.safeEmit("@pause",e,t)})).catch((()=>{})),this._observer.safeEmit("pause"))}resume(){Du.debug("resume()"),this._closed?Du.error("resume() | Producer closed"):(this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&new Promise(((e,t)=>{this.safeEmit("@resume",e,t)})).catch((()=>{})),this._observer.safeEmit("resume"))}async replaceTrack({track:e}){if(Du.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch(e){}throw new ku.InvalidStateError("closed")}if("ended"===e?.readyState)throw new ku.InvalidStateError("track ended");e!==this._track?(await new Promise(((t,r)=>{this.safeEmit("@replacetrack",e,t,r)})),this.destroyTrack(),this._track=e,this._track&&this._disableTrackOnPause&&(this._paused?this._paused&&(this._track.enabled=!1):this._track.enabled=!0),this.handleTrack()):Du.debug("replaceTrack() | same track, ignored")}async setMaxSpatialLayer(e){if(this._closed)throw new ku.InvalidStateError("closed");if("video"!==this._kind)throw new ku.UnsupportedError("not a video Producer");if("number"!=typeof e)throw new TypeError("invalid spatialLayer");e!==this._maxSpatialLayer&&(await new Promise(((t,r)=>{this.safeEmit("@setmaxspatiallayer",e,t,r)})).catch((()=>{})),this._maxSpatialLayer=e)}async setRtpEncodingParameters(e){if(this._closed)throw new ku.InvalidStateError("closed");if("object"!=typeof e)throw new TypeError("invalid params");await new Promise(((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)}))}onTrackEnded(){Du.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track&&this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){if(this._track)try{this._track.removeEventListener("ended",this.onTrackEnded),this._stopTracks&&this._track.stop()}catch(e){}}}Tu.Producer=Iu;var Au={};Object.defineProperty(Au,"__esModule",{value:!0}),Au.Consumer=void 0;const Ou=Td,Mu=Id,Nu=new Sd.Logger("Consumer");class Lu extends Ou.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new Ou.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:r,rtpReceiver:n,track:i,rtpParameters:s,appData:o}){super(),Nu.debug("constructor()"),this._id=e,this._localId=t,this._producerId=r,this._rtpReceiver=n,this._track=i,this._rtpParameters=s,this._paused=!i.enabled,this._appData=o??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get producerId(){return this._producerId}get closed(){return this._closed}get kind(){return this._track.kind}get rtpReceiver(){return this._rtpReceiver}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Nu.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Nu.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Mu.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){Nu.debug("pause()"),this._closed?Nu.error("pause() | Consumer closed"):this._paused?Nu.debug("pause() | Consumer is already paused"):(this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause"))}resume(){Nu.debug("resume()"),this._closed?Nu.error("resume() | Consumer closed"):this._paused?(this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")):Nu.debug("resume() | Consumer is already resumed")}onTrackEnded(){Nu.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){try{this._track.removeEventListener("ended",this.onTrackEnded),this._track.stop()}catch(e){}}}Au.Consumer=Lu;var xu={};Object.defineProperty(xu,"__esModule",{value:!0}),xu.DataProducer=void 0;const Fu=Td,ju=Id,Uu=new Sd.Logger("DataProducer");class Vu extends Fu.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new Fu.EnhancedEventEmitter;constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:n}){super(),Uu.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=r,this._appData=n??{},this.handleDataChannel()}get id(){return this._id}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get bufferedAmount(){return this._dataChannel.bufferedAmount}get bufferedAmountLowThreshold(){return this._dataChannel.bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._dataChannel.bufferedAmountLowThreshold=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Uu.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Uu.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(Uu.debug("send()"),this._closed)throw new ju.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(Uu.debug('DataChannel "open" event'),this.safeEmit("open"))})),this._dataChannel.addEventListener("error",(e=>{if(this._closed)return;const t=e.error??new Error("unknown DataChannel error");"sctp-failure"===e.error?.errorDetail?Uu.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):Uu.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(Uu.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))})),this._dataChannel.addEventListener("message",(()=>{this._closed||Uu.warn('DataChannel "message" event in a DataProducer, message discarded')})),this._dataChannel.addEventListener("bufferedamountlow",(()=>{this._closed||this.safeEmit("bufferedamountlow")}))}}xu.DataProducer=Vu;var Bu={};Object.defineProperty(Bu,"__esModule",{value:!0}),Bu.DataConsumer=void 0;const Wu=Td,Hu=new Sd.Logger("DataConsumer");class qu extends Wu.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new Wu.EnhancedEventEmitter;constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:n,appData:i}){super(),Hu.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=r,this._sctpStreamParameters=n,this._appData=i??{},this.handleDataChannel()}get id(){return this._id}get dataProducerId(){return this._dataProducerId}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get binaryType(){return this._dataChannel.binaryType}set binaryType(e){this._dataChannel.binaryType=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Hu.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Hu.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(Hu.debug('DataChannel "open" event'),this.safeEmit("open"))})),this._dataChannel.addEventListener("error",(e=>{if(this._closed)return;const t=e.error??new Error("unknown DataChannel error");"sctp-failure"===e.error?.errorDetail?Hu.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):Hu.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(Hu.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))})),this._dataChannel.addEventListener("message",(e=>{this._closed||this.safeEmit("message",e.data)}))}}Bu.DataConsumer=qu,Object.defineProperty(mu,"__esModule",{value:!0}),mu.Transport=void 0;const zu=gu,Gu=Td,Yu=Id,$u=Md,Ju=Nd,Qu=Tu,Ku=Au,Zu=xu,Xu=Bu,el=new Sd.Logger("Transport");class tl{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class rl extends Gu.EnhancedEventEmitter{_id;_closed=!1;_direction;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_canProduceByKind;_maxSctpMessageSize;_handler;_iceGatheringState="new";_connectionState="new";_appData;_producers=new Map;_consumers=new Map;_dataProducers=new Map;_dataConsumers=new Map;_probatorConsumerCreated=!1;_awaitQueue=new zu.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new Gu.EnhancedEventEmitter;constructor({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d,handlerFactory:u,getSendExtendedRtpCapabilities:l,recvRtpCapabilities:p,canProduceByKind:h}){super(),el.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._getSendExtendedRtpCapabilities=l,this._recvRtpCapabilities=p,this._canProduceByKind=h,this._maxSctpMessageSize=s?s.maxMessageSize:null;const f=$u.clone(c)??{};delete f.iceServers,delete f.iceTransportPolicy,delete f.bundlePolicy,delete f.rtcpMuxPolicy,this._handler=u.factory({direction:e,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:f,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities}),this._appData=d??{},this.handleHandler()}get id(){return this._id}get closed(){return this._closed}get direction(){return this._direction}get handler(){return this._handler}get iceGatheringState(){return this._iceGatheringState}get connectionState(){return this._connectionState}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){if(!this._closed){el.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(const e of this._producers.values())e.transportClosed();this._producers.clear();for(const e of this._consumers.values())e.transportClosed();this._consumers.clear();for(const e of this._dataProducers.values())e.transportClosed();this._dataProducers.clear();for(const e of this._dataConsumers.values())e.transportClosed();this._dataConsumers.clear(),this._observer.safeEmit("close"),super.close(),this._observer.close()}}async getStats(){if(this._closed)throw new Yu.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(el.debug("restartIce()"),this._closed)throw new Yu.InvalidStateError("closed");if(!e)throw new TypeError("missing iceParameters");return this._awaitQueue.push((async()=>await this._handler.restartIce(e)),"transport.restartIce()")}async updateIceServers({iceServers:e}={}){if(el.debug("updateIceServers()"),this._closed)throw new Yu.InvalidStateError("closed");if(!Array.isArray(e))throw new TypeError("missing iceServers");return this._awaitQueue.push((async()=>this._handler.updateIceServers(e)),"transport.updateIceServers()")}async produce({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s,stopTracks:o=!0,disableTrackOnPause:a=!0,zeroRtpOnPause:c=!1,onRtpSender:d,appData:u={}}={}){if(el.debug("produce() [track:%o]",e),this._closed)throw new Yu.InvalidStateError("closed");if(!e)throw new TypeError("missing track");if("send"!==this._direction)throw new Yu.UnsupportedError("not a sending Transport");if(!this._canProduceByKind[e.kind])throw new Yu.UnsupportedError(`cannot produce ${e.kind}`);if("ended"===e.readyState)throw new Yu.InvalidStateError("track ended");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("produce"))throw new TypeError('no "produce" listener set into this transport');if(u&&"object"!=typeof u)throw new TypeError("if given, appData must be an object");return this._awaitQueue.push((async()=>{let l;if(r&&!Array.isArray(r))throw TypeError("encodings must be an array");0===r?.length?l=void 0:r&&(l=r.map((e=>{const t={active:!0};return!1===e.active&&(t.active=!1),"boolean"==typeof e.dtx&&(t.dtx=e.dtx),"string"==typeof e.scalabilityMode&&(t.scalabilityMode=e.scalabilityMode),"number"==typeof e.scaleResolutionDownBy&&(t.scaleResolutionDownBy=e.scaleResolutionDownBy),"number"==typeof e.maxBitrate&&(t.maxBitrate=e.maxBitrate),"number"==typeof e.maxFramerate&&(t.maxFramerate=e.maxFramerate),"boolean"==typeof e.adaptivePtime&&(t.adaptivePtime=e.adaptivePtime),"string"==typeof e.priority&&(t.priority=e.priority),"string"==typeof e.networkPriority&&(t.networkPriority=e.networkPriority),t})));const{localId:p,rtpParameters:h,rtpSender:f}=await this._handler.send({track:e,streamId:t,encodings:l,codecOptions:n,headerExtensionOptions:i,codec:s,onRtpSender:d});try{Ju.validateAndNormalizeRtpParameters(h);const{id:t}=await new Promise(((t,r)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:h,appData:u},t,r)})),r=new Qu.Producer({id:t,localId:p,rtpSender:f,track:e,rtpParameters:h,stopTracks:o,disableTrackOnPause:a,zeroRtpOnPause:c,appData:u});return this._producers.set(r.id,r),this.handleProducer(r),this._observer.safeEmit("newproducer",r),r}catch(e){throw this._handler.stopSending(p).catch((()=>{})),e}}),"transport.produce()").catch((t=>{if(o)try{e.stop()}catch(e){}throw t}))}async consume({id:e,producerId:t,kind:r,rtpParameters:n,streamId:i,onRtpReceiver:s,appData:o={}}){if(el.debug("consume()"),this._closed)throw new Yu.InvalidStateError("closed");if("recv"!==this._direction)throw new Yu.UnsupportedError("not a receiving Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing producerId");if("audio"!==r&&"video"!==r)throw new TypeError(`invalid kind '${r}'`);if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(o&&"object"!=typeof o)throw new TypeError("if given, appData must be an object");const a=$u.clone(n);if(!Ju.canReceive(a,this._recvRtpCapabilities))throw new Yu.UnsupportedError("cannot consume this Producer");const c=new tl({id:e,producerId:t,kind:r,rtpParameters:a,streamId:i,onRtpReceiver:s,appData:o});return this._pendingConsumerTasks.push(c),queueMicrotask((()=>{this._closed||!1===this._consumerCreationInProgress&&this.createPendingConsumers()})),c.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:r,label:n="",protocol:i="",appData:s={}}={}){if(el.debug("produceData()"),this._closed)throw new Yu.InvalidStateError("closed");if("send"!==this._direction)throw new Yu.UnsupportedError("not a sending Transport");if(!this._maxSctpMessageSize)throw new Yu.UnsupportedError("SCTP not enabled by remote Transport");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("producedata"))throw new TypeError('no "producedata" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");return(t||r)&&(e=!1),this._awaitQueue.push((async()=>{const{dataChannel:o,sctpStreamParameters:a}=await this._handler.sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i});Ju.validateAndNormalizeSctpStreamParameters(a);const{id:c}=await new Promise(((e,t)=>{this.safeEmit("producedata",{sctpStreamParameters:a,label:n,protocol:i,appData:s},e,t)})),d=new Zu.DataProducer({id:c,dataChannel:o,sctpStreamParameters:a,appData:s});return this._dataProducers.set(d.id,d),this.handleDataProducer(d),this._observer.safeEmit("newdataproducer",d),d}),"transport.produceData()")}async consumeData({id:e,dataProducerId:t,sctpStreamParameters:r,label:n="",protocol:i="",appData:s={}}){if(el.debug("consumeData()"),this._closed)throw new Yu.InvalidStateError("closed");if("recv"!==this._direction)throw new Yu.UnsupportedError("not a receiving Transport");if(!this._maxSctpMessageSize)throw new Yu.UnsupportedError("SCTP not enabled by remote Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing dataProducerId");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");const o=$u.clone(r);return Ju.validateAndNormalizeSctpStreamParameters(o),this._awaitQueue.push((async()=>{const{dataChannel:r}=await this._handler.receiveDataChannel({sctpStreamParameters:o,label:n,protocol:i}),a=new Xu.DataConsumer({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:o,appData:s});return this._dataConsumers.set(a.id,a),this.handleDataConsumer(a),this._observer.safeEmit("newdataconsumer",a),a}),"transport.consumeData()")}createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingConsumerTasks.length)return void el.debug("createPendingConsumers() | there is no Consumer to be created");const e=[...this._pendingConsumerTasks];let t;this._pendingConsumerTasks=[];const r=[];for(const t of e){const{id:e,kind:n,rtpParameters:i,streamId:s,onRtpReceiver:o}=t.consumerOptions;r.push({trackId:e,kind:n,rtpParameters:i,streamId:s,onRtpReceiver:o})}try{const n=await this._handler.receive(r);for(let r=0;r<n.length;++r){const i=e[r],s=n[r],{id:o,producerId:a,kind:c,rtpParameters:d,appData:u}=i.consumerOptions,{localId:l,rtpReceiver:p,track:h}=s,f=new Ku.Consumer({id:o,localId:l,producerId:a,rtpReceiver:p,track:h,rtpParameters:d,appData:u});this._consumers.set(f.id,f),this.handleConsumer(f),this._probatorConsumerCreated||t||"video"!==c||(t=f),this._observer.safeEmit("newconsumer",f),i.resolve(f)}}catch(t){for(const r of e)r.reject(t)}if(t)try{const e=Ju.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:e}]),el.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(e){el.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",e)}}),"transport.createPendingConsumers()").then((()=>{this._consumerCreationInProgress=!1,this._pendingConsumerTasks.length>0&&this.createPendingConsumers()})).catch((()=>{}))}pausePendingConsumers(){this._consumerPauseInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingPauseConsumers.size)return void el.debug("pausePendingConsumers() | there is no Consumer to be paused");const e=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{const t=e.map((e=>e.localId));await this._handler.pauseReceiving(t)}catch(e){el.error("pausePendingConsumers() | failed to pause Consumers:",e)}}),"transport.pausePendingConsumers()").then((()=>{this._consumerPauseInProgress=!1,this._pendingPauseConsumers.size>0&&this.pausePendingConsumers()})).catch((()=>{}))}resumePendingConsumers(){this._consumerResumeInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingResumeConsumers.size)return void el.debug("resumePendingConsumers() | there is no Consumer to be resumed");const e=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{const t=e.map((e=>e.localId));await this._handler.resumeReceiving(t)}catch(e){el.error("resumePendingConsumers() | failed to resume Consumers:",e)}}),"transport.resumePendingConsumers()").then((()=>{this._consumerResumeInProgress=!1,this._pendingResumeConsumers.size>0&&this.resumePendingConsumers()})).catch((()=>{}))}closePendingConsumers(){this._consumerCloseInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingCloseConsumers.size)return void el.debug("closePendingConsumers() | there is no Consumer to be closed");const e=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(e.map((e=>e.localId)))}catch(e){el.error("closePendingConsumers() | failed to close Consumers:",e)}}),"transport.closePendingConsumers()").then((()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()})).catch((()=>{}))}handleHandler(){const e=this._handler;e.on("@connect",(({dtlsParameters:e},t,r)=>{this._closed?r(new Yu.InvalidStateError("closed")):this.safeEmit("connect",{dtlsParameters:e},t,r)})),e.on("@icegatheringstatechange",(e=>{e!==this._iceGatheringState&&(el.debug("ICE gathering state changed to %s",e),this._iceGatheringState=e,this._closed||this.safeEmit("icegatheringstatechange",e))})),e.on("@icecandidateerror",(e=>{el.warn(`ICE candidate error [url:${e.url}, localAddress:${e.address}, localPort:${e.port}]: ${e.errorCode} "${e.errorText}"`),this.safeEmit("icecandidateerror",e)})),e.on("@connectionstatechange",(e=>{e!==this._connectionState&&(el.debug("connection state changed to %s",e),this._connectionState=e,this._closed||this.safeEmit("connectionstatechange",e))}))}handleProducer(e){e.on("@close",(()=>{this._producers.delete(e.id),this._closed||this._awaitQueue.push((async()=>await this._handler.stopSending(e.localId)),"producer @close event").catch((e=>el.warn("producer.close() failed:%o",e)))})),e.on("@pause",((t,r)=>{this._awaitQueue.push((async()=>await this._handler.pauseSending(e.localId)),"producer @pause event").then(t).catch(r)})),e.on("@resume",((t,r)=>{this._awaitQueue.push((async()=>await this._handler.resumeSending(e.localId)),"producer @resume event").then(t).catch(r)})),e.on("@replacetrack",((t,r,n)=>{this._awaitQueue.push((async()=>await this._handler.replaceTrack(e.localId,t)),"producer @replacetrack event").then(r).catch(n)})),e.on("@setmaxspatiallayer",((t,r,n)=>{this._awaitQueue.push((async()=>await this._handler.setMaxSpatialLayer(e.localId,t)),"producer @setmaxspatiallayer event").then(r).catch(n)})),e.on("@setrtpencodingparameters",((t,r,n)=>{this._awaitQueue.push((async()=>await this._handler.setRtpEncodingParameters(e.localId,t)),"producer @setrtpencodingparameters event").then(r).catch(n)})),e.on("@getstats",((t,r)=>{if(this._closed)return r(new Yu.InvalidStateError("closed"));this._handler.getSenderStats(e.localId).then(t).catch(r)}))}handleConsumer(e){e.on("@close",(()=>{this._consumers.delete(e.id),this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.delete(e.id),this._closed||(this._pendingCloseConsumers.set(e.id,e),!1===this._consumerCloseInProgress&&this.closePendingConsumers())})),e.on("@pause",(()=>{this._pendingResumeConsumers.has(e.id)&&this._pendingResumeConsumers.delete(e.id),this._pendingPauseConsumers.set(e.id,e),queueMicrotask((()=>{this._closed||!1===this._consumerPauseInProgress&&this.pausePendingConsumers()}))})),e.on("@resume",(()=>{this._pendingPauseConsumers.has(e.id)&&this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.set(e.id,e),queueMicrotask((()=>{this._closed||!1===this._consumerResumeInProgress&&this.resumePendingConsumers()}))})),e.on("@getstats",((t,r)=>{if(this._closed)return r(new Yu.InvalidStateError("closed"));this._handler.getReceiverStats(e.localId).then(t).catch(r)}))}handleDataProducer(e){e.on("@close",(()=>{this._dataProducers.delete(e.id)}))}handleDataConsumer(e){e.on("@close",(()=>{this._dataConsumers.delete(e.id)}))}}mu.Transport=rl;var nl={},il={},sl={},ol={exports:{}},al=ol.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:/^(\w*) (\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:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s 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:"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"},{push:"msid",reg:/^msid:([\w-]+)(?: ([\w-]+))?/,names:["id","appdata"],format:"msid:%s %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",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{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":"",t+=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"},{push:"invalid",names:["value"]}]};Object.keys(al).forEach((function(e){al[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,n){var i=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:i&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:i?r[e.name]:r;!function(e,r,n,i){if(i&&!n)r[i]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(r[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},n=ol.exports,i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(i).forEach((function(e){var t=e[0],i=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(i))return r(c,o,i)}})),t.media=s,t};var s=function(e,r){var n=r.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&r.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 r=[],n=e.split(" ").map(t),i=0;i<n.length;i+=3)r.push({component:n[i],ip:n[i+1],port:n[i+2]});return r},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 r,n=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),n=!0),{scid:r,paused:n}}))}))}}(sl);var cl=ol.exports,dl=/%[sdv%]/g,ul=function(e){var t=1,r=arguments,n=r.length;return e.replace(dl,(function(e){if(t>=n)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}}))},ll=function(e,t,r){var n=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var i=0;i<t.names.length;i+=1){var s=t.names[i];t.name?n.push(r[t.name][s]):n.push(r[t.names[i]])}else n.push(r[t.name]);return ul.apply(null,n)},pl=["v","o","s","i","u","e","p","c","b","t","r","z","a"],hl=["i","c","b","a"],fl=sl,ml=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 r=t.outerOrder||pl,n=t.innerOrder||hl,i=[];return r.forEach((function(t){cl[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(ll(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(ll(t,r,e))}))}))})),e.media.forEach((function(e){i.push(ll("m",cl.m[0],e)),n.forEach((function(t){cl[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(ll(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(ll(t,r,e))}))}))}))})),i.join("\r\n")+"\r\n"},gl=ol.exports;il.grammar=gl,il.write=ml,il.parse=fl.parse,il.parseParams=fl.parseParams,il.parseFmtpConfig=fl.parseFmtpConfig,il.parsePayloads=fl.parsePayloads,il.parseRemoteCandidates=fl.parseRemoteCandidates,il.parseImageAttributes=fl.parseImageAttributes,il.parseSimulcastStreamList=fl.parseSimulcastStreamList;var vl={};Object.defineProperty(vl,"__esModule",{value:!0}),vl.parse=function(e){const t=yl.exec(e??"");return t?{spatialLayers:Number(t[1]),temporalLayers:Number(t[2])}:{spatialLayers:1,temporalLayers:1}};const yl=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");var bl={},_l={};Object.defineProperty(_l,"__esModule",{value:!0}),_l.OfferMediaSection=_l.AnswerMediaSection=_l.MediaSection=void 0;const El=il,wl=Md;class Sl{_mediaObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r}){if(this._mediaObject={type:"",port:0,protocol:"",payloads:"",rtp:[],fmtp:[]},e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(const e of t){const t={foundation:e.foundation,component:1,ip:e.address??e.ip,port:e.port,priority:e.priority,transport:e.protocol,type:e.type};e.tcpType&&(t.tcptype=e.tcpType),this._mediaObject.candidates.push(t)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}r&&this.setDtlsRole(r.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return 0===this._mediaObject.port}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause()}close(){this.disable(),this._mediaObject.port=0,delete this._mediaObject.candidates,delete this._mediaObject.endOfCandidates,delete this._mediaObject.iceUfrag,delete this._mediaObject.icePwd,delete this._mediaObject.iceOptions,this._mediaObject.rtp=[],this._mediaObject.fmtp=[],delete this._mediaObject.rtcp,delete this._mediaObject.rtcpFb,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}}_l.MediaSection=Sl;_l.AnswerMediaSection=class extends Sl{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,offerMediaObject:s,offerRtpParameters:o,answerRtpParameters:a,codecOptions:c}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(s.mid),this._mediaObject.type=s.type,this._mediaObject.protocol=s.protocol,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),s.type){case"audio":case"video":this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(const e of a.codecs){const t={payload:e.payloadType,codec:Cl(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r=wl.clone(e.parameters)??{};let n=wl.clone(e.rtcpFeedback)??[];if(c){const{opusStereo:t,opusFec:i,opusDtx:s,opusMaxPlaybackRate:a,opusMaxAverageBitrate:d,opusPtime:u,opusNack:l,videoGoogleStartBitrate:p,videoGoogleMaxBitrate:h,videoGoogleMinBitrate:f}=c,m=o.codecs.find((t=>t.payloadType===e.payloadType));switch(e.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":void 0!==t&&(m.parameters["sprop-stereo"]=t?1:0,r.stereo=t?1:0),void 0!==i&&(m.parameters.useinbandfec=i?1:0,r.useinbandfec=i?1:0),void 0!==s&&(m.parameters.usedtx=s?1:0,r.usedtx=s?1:0),void 0!==a&&(r.maxplaybackrate=a),void 0!==d&&(r.maxaveragebitrate=d),void 0!==u&&(m.parameters.ptime=u,r.ptime=u),l||(m.rtcpFeedback=m.rtcpFeedback.filter((e=>"nack"!==e.type||e.parameter)),n=n.filter((e=>"nack"!==e.type||e.parameter)));break;case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":case"video/av1":void 0!==p&&(r["x-google-start-bitrate"]=p),void 0!==h&&(r["x-google-max-bitrate"]=h),void 0!==f&&(r["x-google-min-bitrate"]=f)}}const i={payload:e.payloadType,config:""};for(const e of Object.keys(r))i.config&&(i.config+=";"),i.config+=`${e}=${r[e]}`;i.config&&this._mediaObject.fmtp.push(i);for(const t of n)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=a.codecs.map((e=>e.payloadType)).join(" "),this._mediaObject.ext=[];for(const e of a.headerExtensions){(s.ext??[]).some((t=>t.uri===e.uri))&&this._mediaObject.ext.push({uri:e.uri,value:e.id})}if("extmap-allow-mixed"===s.extmapAllowMixed&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),s.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:s.simulcast.list1},this._mediaObject.rids=[];for(const e of s.rids??[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}else if(s.simulcast_03){this._mediaObject.simulcast_03={value:s.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(const e of s.rids??[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";break;case"application":"number"==typeof s.sctpPort?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize):s.sctpmap&&(this._mediaObject.payloads=String(n.port),this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:n.port,maxMessageSize:n.maxMessageSize})}}setDtlsRole(e){switch(e){case"client":this._mediaObject.setup="active";break;case"server":this._mediaObject.setup="passive";break;case"auto":this._mediaObject.setup="actpass"}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(e){if(!this._mediaObject.simulcast?.list1)return;const t={};for(const r of e)r.rid&&(t[r.rid]=r);const r=this._mediaObject.simulcast.list1,n=El.parseSimulcastStreamList(r);for(const e of n)for(const r of e)r.paused=!t[r.scid]?.active;this._mediaObject.simulcast.list1=n.map((e=>e.map((e=>`${e.paused?"~":""}${e.scid}`)).join(","))).join(";")}};function Cl(e){const t=new RegExp("^(audio|video)/(.+)","i").exec(e.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}_l.OfferMediaSection=class extends Sl{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,mid:s,kind:o,offerRtpParameters:a,streamId:c,trackId:d}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(s),this._mediaObject.type=o,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.protocol=n?"UDP/DTLS/SCTP":"UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",o){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=[{id:c,appdata:d}];for(const e of a.codecs){const t={payload:e.payloadType,codec:Cl(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r={payload:e.payloadType,config:""};for(const t of Object.keys(e.parameters??{}))r.config&&(r.config+=";"),r.config+=`${t}=${e.parameters[t]}`;r.config&&this._mediaObject.fmtp.push(r);for(const t of e.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=a.codecs.map((e=>e.payloadType)).join(" "),this._mediaObject.ext=[];for(const e of a.headerExtensions)this._mediaObject.ext.push({uri:e.uri,value:e.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";const e=a.encodings[0],t=e.ssrc,r=e.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],t&&a.rtcp.cname&&this._mediaObject.ssrcs.push({id:t,attribute:"cname",value:a.rtcp.cname}),r&&(a.rtcp.cname&&this._mediaObject.ssrcs.push({id:r,attribute:"cname",value:a.rtcp.cname}),t&&this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${t} ${r}`}));break}case"application":this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}},Object.defineProperty(bl,"__esModule",{value:!0}),bl.RemoteSdp=void 0;const Pl=il,Tl=_l,Rl=pd,kl=["av1","h264"],Dl=new Sd.Logger("RemoteSdp");bl.RemoteSdp=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i}){if(this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=r,this._sctpParameters=n,this._plainRtpParameters=i,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:`mediasoup-client-v${Rl.version}`},name:"-",timing:{start:0,stop:0},media:[]},this._sdpObject.iceOptions="ice2",e?.iceLite&&(this._sdpObject.icelite="ice-lite"),r){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};const e=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:r.fingerprints[e-1].algorithm,hash:r.fingerprints[e-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){Dl.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(const t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){Dl.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(const t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){Dl.debug("setSessionExtmapAllowMixed()"),this._sdpObject.extmapAllowMixed="extmap-allow-mixed"}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){const t=this._mediaSections[e];if(t.closed)return{idx:e,reuseMid:t.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:e,reuseMid:t,offerRtpParameters:r,answerRtpParameters:n,codecOptions:i}){const s=new Tl.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e,offerRtpParameters:r,answerRtpParameters:n,codecOptions:i}),o=s.getObject();o.rtp.find((e=>kl.includes(e.codec.toLowerCase())))||(o.ext=o.ext?.filter((e=>"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"!==e.uri))),t?this.replaceMediaSection(s,t):this._midToIndex.has(s.mid)?this.replaceMediaSection(s):this.addMediaSection(s)}receive({mid:e,kind:t,offerRtpParameters:r,streamId:n,trackId:i}){this.setSessionExtmapAllowMixed();const s=new Tl.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,mid:e,kind:t,offerRtpParameters:r,streamId:n,trackId:i}),o=this._mediaSections.find((e=>e.closed&&e.getObject().type===t));o?this.replaceMediaSection(s,o.mid):this.addMediaSection(s)}pauseMediaSection(e){this.findMediaSection(e).pause()}resumeSendingMediaSection(e){this.findMediaSection(e).resume()}resumeReceivingMediaSection(e){this.findMediaSection(e).resume()}disableMediaSection(e){this.findMediaSection(e).disable()}closeMediaSection(e){const t=this.findMediaSection(e);return e===this._firstMid?(Dl.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",e),this.disableMediaSection(e),!1):(t.close(),this.regenerateBundleMids(),!0)}muxMediaSectionSimulcast(e,t){const r=this.findMediaSection(e);r.muxSimulcastStreams(t),this.replaceMediaSection(r)}sendSctpAssociation({offerMediaObject:e}){const t=new Tl.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this.addMediaSection(t)}receiveSctpAssociation(){const e=new Tl.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application"});this.addMediaSection(e)}getSdp(){return this._sdpObject.origin.sessionVersion++,Pl.write(this._sdpObject)}addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this.regenerateBundleMids()}replaceMediaSection(e,t){if("string"==typeof t){const r=this._midToIndex.get(t);if(void 0===r)throw new Error(`no media section found for reuseMid '${t}'`);const n=this._mediaSections[r];this._mediaSections[r]=e,this._midToIndex.delete(n.mid),this._midToIndex.set(e.mid,r),this._sdpObject.media[r]=e.getObject(),this.regenerateBundleMids()}else{const t=this._midToIndex.get(e.mid);if(void 0===t)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[t]=e,this._sdpObject.media[t]=e.getObject()}}findMediaSection(e){const t=this._midToIndex.get(e);if(void 0===t)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter((e=>!e.closed)).map((e=>e.mid)).join(" "))}};var Il={};Object.defineProperty(Il,"__esModule",{value:!0}),Il.extractRtpCapabilities=function({sdpObject:e}){const t=new Map,r=new Map;for(const n of e.media){const e=n.type;switch(e){case"audio":case"video":break;default:continue}for(const r of n.rtp){const n={kind:e,mimeType:`${e}/${r.codec}`,preferredPayloadType:r.payload,clockRate:r.rate,channels:r.encoding,parameters:{},rtcpFeedback:[]};t.set(n.preferredPayloadType,n)}for(const e of n.fmtp??[]){const r=Al.parseParams(e.config),n=t.get(e.payload);n&&(r?.hasOwnProperty("profile-level-id")&&(r["profile-level-id"]=String(r["profile-level-id"])),n.parameters=r)}for(const r of n.rtcpFb??[]){const n={type:r.type,parameter:r.subtype};if(n.parameter||delete n.parameter,"*"!==r.payload){const e=t.get(Number(r.payload));if(!e)continue;e.rtcpFeedback.push(n)}else for(const r of t.values())r.kind!==e||/.+\/rtx$/i.test(r.mimeType)||r.rtcpFeedback.push(n)}for(const t of n.ext??[]){if(t["encrypt-uri"])continue;const n={kind:e,uri:t.uri,preferredId:t.value};r.set(n.preferredId,n)}}return{codecs:Array.from(t.values()),headerExtensions:Array.from(r.values())}},Il.extractDtlsParameters=function({sdpObject:e}){let t,r=e.setup,n=e.fingerprint;if(!r||!n){const t=(e.media??[]).find((e=>0!==e.port));t&&(r=r??t.setup,n=n??t.fingerprint)}if(!r)throw new Error("no a=setup found at SDP session or media level");if(!n)throw new Error("no a=fingerprint found at SDP session or media level");switch(r){case"active":t="client";break;case"passive":t="server";break;case"actpass":t="auto"}return{role:t,fingerprints:[{algorithm:n.type,value:n.hash}]}},Il.getCname=function({offerMediaObject:e}){const t=(e.ssrcs??[]).find((e=>"cname"===e.attribute));if(!t)return"";return t.value},Il.applyCodecParameters=function({offerRtpParameters:e,answerMediaObject:t}){for(const r of e.codecs){const e=r.mimeType.toLowerCase();if("audio/opus"!==e)continue;const n=(t.rtp??[]).find((e=>e.payload===r.payloadType));if(!n)continue;t.fmtp=t.fmtp??[];let i=t.fmtp.find((e=>e.payload===r.payloadType));i||(i={payload:r.payloadType,config:""},t.fmtp.push(i));const s=Al.parseParams(i.config);switch(e){case"audio/opus":{const e=r.parameters?.["sprop-stereo"];void 0!==e&&(s.stereo=Number(e)?1:0);break}}i.config="";for(const e of Object.keys(s))i.config&&(i.config+=";"),i.config+=`${e}=${s[e]}`}},Il.addHeaderExtension=function({offerMediaObject:e,headerExtensionUri:t,headerExtensionId:r}){e.ext||(e.ext=[]);e.ext.push({uri:t,value:r})};const Al=il;var Ol={};Object.defineProperty(Ol,"__esModule",{value:!0}),Ol.getRtpEncodings=function({offerMediaObject:e,codecs:t}){const r=new Set;for(const t of e.ssrcs??[]){const e=t.id;e&&r.add(e)}if(0===r.size)throw new Error("no a=ssrc lines found");const n=new Map;for(const t of e.ssrcGroups??[]){if("FID"!==t.semantics)continue;const e=t.ssrcs.split(/\s+/),i=Number(e[0]),s=Number(e[1]);r.has(i)&&(r.delete(i),r.delete(s),n.set(i,s))}for(const e of r)n.set(e,void 0);const i=[];for(const[e,r]of n){const n={ssrc:e};r&&t.length>1&&(n.rtx={ssrc:r}),i.push(n)}return i},Ol.addLegacySimulcast=function({offerMediaObject:e,numStreams:t}){if(t<=1)throw new TypeError("numStreams must be greater than 1");const r=(e.ssrcs??[]).find((e=>"msid"===e.attribute));if(!r)throw new Error("a=ssrc line with msid information not found");const[n,i]=r.value.split(" "),s=Number(r.id);let o;(e.ssrcGroups??[]).some((e=>{if("FID"!==e.semantics)return!1;const t=e.ssrcs.split(/\s+/);return Number(t[0])===s&&(o=Number(t[1]),!0)}));const a=(e.ssrcs??[]).find((e=>"cname"===e.attribute));if(!a)throw new Error("a=ssrc line with cname information not found");const c=a.value,d=[],u=[];for(let e=0;e<t;++e)d.push(s+e),o&&u.push(o+e);e.ssrcGroups=[],e.ssrcs=[],e.ssrcGroups.push({semantics:"SIM",ssrcs:d.join(" ")});for(const t of d)e.ssrcs.push({id:t,attribute:"cname",value:c}),e.ssrcs.push({id:t,attribute:"msid",value:`${n} ${i}`});for(let t=0;t<u.length;++t){const r=d[t],s=u[t];e.ssrcs.push({id:s,attribute:"cname",value:c}),e.ssrcs.push({id:s,attribute:"msid",value:`${n} ${i}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${r} ${s}`})}};var Ml={};Object.defineProperty(Ml,"__esModule",{value:!0}),Ml.addNackSupportForOpus=function(e){for(const t of e.codecs??[])"audio/opus"!==t.mimeType.toLowerCase()&&"audio/multiopus"!==t.mimeType.toLowerCase()||t.rtcpFeedback?.some((e=>"nack"===e.type&&!e.parameter))||(t.rtcpFeedback||(t.rtcpFeedback=[]),t.rtcpFeedback.push({type:"nack"}))},Ml.addHeaderExtensionSupport=function(e,t){let r;const n=e.headerExtensions?.find((e=>e.uri===t.uri));if(n){if(n.kind===t.kind)return;r=n.preferredId}e.headerExtensions||(e.headerExtensions=[]);if(void 0===r){r=1;const t=new Set(e.headerExtensions.map((e=>e.preferredId)));for(;t.has(r);)++r}const i={kind:t.kind,uri:t.uri,preferredId:r,preferredEncrypt:!1,direction:t.direction};e.headerExtensions.push(i)},Ml.getMsidStreamIdAndTrackId=function(e){if(!e||"string"!=typeof e)return{msidStreamId:void 0,msidTrackId:void 0};const[t,r]=e.trim().split(/\s+/);if(!t)return{msidStreamId:void 0,msidTrackId:void 0};return{msidStreamId:t,msidTrackId:r}},Object.defineProperty(nl,"__esModule",{value:!0}),nl.Chrome111=void 0;const Nl=il,Ll=Td,xl=Nd,Fl=Id,jl=vl,Ul=bl,Vl=Il,Bl=Ol,Wl=Ml,Hl=new Sd.Logger("Chrome111"),ql={OS:65535,MIS:65535};class zl extends Ll.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:"Chrome111",factory:e=>new zl(e),getNativeRtpCapabilities:async({direction:e})=>{Hl.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e,sendEncodings:[{scalabilityMode:"L3T3"}]});const r=await t.createOffer();try{t.close()}catch(e){}t=void 0;const n=Nl.parse(r.sdp);return zl.getLocalRtpCapabilities(n)}catch(e){try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(Hl.debug("getNativeSctpCapabilities()"),{numStreams:ql})}}static getLocalRtpCapabilities(e,t=[]){const r=Vl.extractRtpCapabilities({sdpObject:e});xl.validateAndNormalizeRtpCapabilities(r),Wl.addNackSupportForOpus(r);for(const e of t)Wl.addHeaderExtensionSupport(r,e);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Hl.debug("constructor()"),this._direction=e,this._remoteSdp=new Ul.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(Hl.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Chrome111"}close(){if(Hl.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch(e){}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),Hl.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Hl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Hl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Hl.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s,onRtpSender:o}){if(this.assertNotClosed(),this.assertSendDirection(),Hl.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1){let e=1;for(const t of r){const r=t.scalabilityMode?(0,jl.parse)(t.scalabilityMode).temporalLayers:3;r>e&&(e=r)}r.forEach(((t,r)=>{t.rid=`r${r}`,t.scalabilityMode=`L1T${e}`}))}const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});o&&o(c.sender);let d=await this._pc.createOffer(),u=Nl.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const l=[];l.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});const p=zl.getLocalRtpCapabilities(u,l),h=this._getSendExtendedRtpCapabilities(p),f=xl.getSendingRtpParameters(e.kind,h);f.codecs=xl.reduceCodecs(f.codecs,s);const m=xl.getSendingRemoteRtpParameters(e.kind,h);if(m.codecs=xl.reduceCodecs(m.codecs,s),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u}),i?.absCaptureTime){const e=u.media[a.idx];Vl.addHeaderExtension({offerMediaObject:e,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"===e.uri)).id}),d={type:"offer",sdp:Nl.write(u)}}Hl.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const g=c.mid;f.mid=g,u=Nl.parse(this._pc.localDescription.sdp);const v=u.media[a.idx];if(f.rtcp.cname=Vl.getCname({offerMediaObject:v}),f.msid=`${t??this._sendStream.id} ${e.id}`,r)if(1===r.length){const e=Bl.getRtpEncodings({offerMediaObject:v,codecs:f.codecs});Object.assign(e[0],r[0]),f.encodings=e}else f.encodings=r;else f.encodings=Bl.getRtpEncodings({offerMediaObject:v,codecs:f.codecs});this._remoteSdp.send({offerMediaObject:v,reuseMid:a.reuseMid,offerRtpParameters:f,answerRtpParameters:m,codecOptions:n});const y={type:"answer",sdp:this._remoteSdp.getSdp()};return Hl.debug("send() | calling pc.setRemoteDescription() [answer:%o]",y),await this._pc.setRemoteDescription(y),this._mapMidTransceiver.set(g,c),{localId:g,rtpParameters:f,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),Hl.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Hl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Hl.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Hl.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Hl.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();Hl.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Hl.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Hl.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Hl.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Hl.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Hl.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Hl.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};Hl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%ql.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Nl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Hl.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Hl.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;Hl.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=Wl.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=Nl.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));Vl.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Nl.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Hl.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Hl.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hl.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Hl.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hl.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Hl.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hl.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Hl.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Hl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Nl.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Hl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Nl.parse(this._pc.localDescription.sdp));const r=Vl.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}};assertNotClosed(){if(this._closed)throw new Fl.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}nl.Chrome111=zl;var Gl={};Object.defineProperty(Gl,"__esModule",{value:!0}),Gl.Chrome74=void 0;const Yl=il,$l=Td,Jl=Nd,Ql=Id,Kl=vl,Zl=bl,Xl=Il,ep=Ol,tp=Ml,rp=new Sd.Logger("Chrome74"),np={OS:1024,MIS:1024};class ip extends $l.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:"Chrome74",factory:e=>new ip(e),getNativeRtpCapabilities:async({direction:e})=>{rp.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});const r=await t.createOffer();try{t.close()}catch(e){}t=void 0;const n=Yl.parse(r.sdp);return ip.getLocalRtpCapabilities(n)}catch(e){try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(rp.debug("getNativeSctpCapabilities()"),{numStreams:np})}}static getLocalRtpCapabilities(e,t=[]){const r=Xl.extractRtpCapabilities({sdpObject:e});Jl.validateAndNormalizeRtpCapabilities(r),tp.addNackSupportForOpus(r);for(const e of t)tp.addHeaderExtensionSupport(r,e);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),rp.debug("constructor()"),this._direction=e,this._remoteSdp=new Zl.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(rp.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Chrome74"}close(){if(rp.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch(e){}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),rp.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),rp.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});rp.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};rp.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};rp.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();rp.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s}){this.assertNotClosed(),this.assertSendDirection(),rp.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach(((e,t)=>{e.rid=`r${t}`}));const o=this._remoteSdp.getNextMediaSectionIdx(),a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});let c=await this._pc.createOffer(),d=Yl.parse(c.sdp);d.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const u=[];u.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});const l=ip.getLocalRtpCapabilities(d,u),p=this._getSendExtendedRtpCapabilities(l),h=Jl.getSendingRtpParameters(e.kind,p);h.codecs=Jl.reduceCodecs(h.codecs,s);const f=Jl.getSendingRemoteRtpParameters(e.kind,p);f.codecs=Jl.reduceCodecs(f.codecs,s),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:d});let m=!1;const g=(0,Kl.parse)((r??[{}])[0].scalabilityMode);let v;1===r?.length&&g.spatialLayers>1&&"video/vp9"===h.codecs[0].mimeType.toLowerCase()&&(rp.debug("send() | enabling legacy simulcast for VP9 SVC"),m=!0,d=Yl.parse(c.sdp),v=d.media[o.idx],ep.addLegacySimulcast({offerMediaObject:v,numStreams:g.spatialLayers}),c={type:"offer",sdp:Yl.write(d)}),rp.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),i?.absCaptureTime&&(v=d.media[o.idx],Xl.addHeaderExtension({offerMediaObject:v,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:f.headerExtensions.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"===e.uri)).id}),c={type:"offer",sdp:Yl.write(d)}),await this._pc.setLocalDescription(c);const y=a.mid;if(h.mid=y,d=Yl.parse(this._pc.localDescription.sdp),v=d.media[o.idx],h.rtcp.cname=Xl.getCname({offerMediaObject:v}),h.msid=`${t??this._sendStream.id} ${e.id}`,r)if(1===r.length){let e=ep.getRtpEncodings({offerMediaObject:v,codecs:h.codecs});Object.assign(e[0],r[0]),m&&(e=[e[0]]),h.encodings=e}else h.encodings=r;else h.encodings=ep.getRtpEncodings({offerMediaObject:v,codecs:h.codecs});if(h.encodings.length>1&&("video/vp8"===h.codecs[0].mimeType.toLowerCase()||"video/h264"===h.codecs[0].mimeType.toLowerCase()))for(const e of h.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${g.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:v,reuseMid:o.reuseMid,offerRtpParameters:h,answerRtpParameters:f,codecOptions:n});const b={type:"answer",sdp:this._remoteSdp.getSdp()};return rp.debug("send() | calling pc.setRemoteDescription() [answer:%o]",b),await this._pc.setRemoteDescription(b),this._mapMidTransceiver.set(y,a),{localId:y,rtpParameters:h,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),rp.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();rp.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};rp.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),rp.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();rp.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};rp.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),rp.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();rp.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};rp.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?rp.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):rp.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),rp.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();rp.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};rp.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),rp.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();rp.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};rp.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};rp.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%np.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Yl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),rp.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};rp.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;rp.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=tp.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};rp.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer();const s=Yl.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));Xl.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Yl.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),rp.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){rp.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};rp.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();rp.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){rp.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};rp.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();rp.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){rp.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};rp.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();rp.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};rp.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};rp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Yl.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}rp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Yl.parse(this._pc.localDescription.sdp));const r=Xl.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}};assertNotClosed(){if(this._closed)throw new Ql.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Gl.Chrome74=ip;var sp={};Object.defineProperty(sp,"__esModule",{value:!0}),sp.Firefox120=void 0;const op=il,ap=Td,cp=Id,dp=Nd,up=vl,lp=bl,pp=Il,hp=Ol,fp=Ml,mp=new Sd.Logger("Firefox120"),gp={OS:16,MIS:2048};class vp extends ap.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:"Firefox120",factory:e=>new vp(e),getNativeRtpCapabilities:async({direction:e})=>{mp.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});const r=document.createElement("canvas");r.getContext("2d");const n=r.captureStream().getVideoTracks()[0];try{t.addTransceiver("audio",{direction:e}),t.addTransceiver(n,{direction:e,sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});const i=await t.createOffer();try{r.remove()}catch(e){}try{n.stop()}catch(e){}try{t.close()}catch(e){}t=void 0;const s=op.parse(i.sdp);return vp.getLocalRtpCapabilities(s)}catch(e){try{r.remove()}catch(e){}try{n.stop()}catch(e){}try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(mp.debug("getNativeSctpCapabilities()"),{numStreams:gp})}}static getLocalRtpCapabilities(e){const t=pp.extractRtpCapabilities({sdpObject:e});return dp.validateAndNormalizeRtpCapabilities(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),mp.debug("constructor()"),this._direction=e,this._remoteSdp=new lp.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(mp.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Firefox120"}close(){if(mp.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch(e){}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){throw this.assertNotClosed(),new cp.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),mp.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});mp.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};mp.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};mp.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();mp.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,codec:i,onRtpSender:s}){this.assertNotClosed(),this.assertSendDirection(),mp.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach(((e,t)=>{e.rid=`r${t}`}));const o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});s&&s(o.sender);const a=await this._pc.createOffer();let c=op.parse(a.sdp);c.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const d=vp.getLocalRtpCapabilities(c),u=this._getSendExtendedRtpCapabilities(d),l=dp.getSendingRtpParameters(e.kind,u);l.codecs=dp.reduceCodecs(l.codecs,i);const p=dp.getSendingRemoteRtpParameters(e.kind,u);p.codecs=dp.reduceCodecs(p.codecs,i),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:c});const h=(0,up.parse)((r??[{}])[0].scalabilityMode);mp.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const f=o.mid;l.mid=f,c=op.parse(this._pc.localDescription.sdp);const m=c.media[c.media.length-1];if(l.rtcp.cname=pp.getCname({offerMediaObject:m}),l.msid=`${t??this._sendStream.id} ${e.id}`,r)if(1===r.length){const e=hp.getRtpEncodings({offerMediaObject:m,codecs:l.codecs});Object.assign(e[0],r[0]),l.encodings=e}else l.encodings=r;else l.encodings=hp.getRtpEncodings({offerMediaObject:m,codecs:l.codecs});if(l.encodings.length>1&&("video/vp8"===l.codecs[0].mimeType.toLowerCase()||"video/h264"===l.codecs[0].mimeType.toLowerCase()))for(const e of l.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${h.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:m,offerRtpParameters:l,answerRtpParameters:p,codecOptions:n});const g={type:"answer",sdp:this._remoteSdp.getSdp()};return mp.debug("send() | calling pc.setRemoteDescription() [answer:%o]",g),await this._pc.setRemoteDescription(g),this._mapMidTransceiver.set(f,o),{localId:f,rtpParameters:l,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),mp.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);const r=await this._pc.createOffer();mp.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};mp.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),mp.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();mp.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};mp.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),mp.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();mp.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};mp.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?mp.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):mp.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),mp.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();mp.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};mp.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),mp.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();mp.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};mp.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};mp.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%gp.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=op.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),mp.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};mp.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;mp.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=fp.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};mp.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=op.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,o=r.get(e),a=s.media.find((e=>String(e.mid)===o));pp.applyCodecParameters({offerRtpParameters:n,answerMediaObject:a}),i={type:"answer",sdp:op.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),mp.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){mp.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};mp.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();mp.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){mp.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};mp.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();mp.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){mp.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};mp.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();mp.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};mp.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};mp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=op.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}mp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=op.parse(this._pc.localDescription.sdp));const r=pp.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}};assertNotClosed(){if(this._closed)throw new cp.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}sp.Firefox120=vp;var yp={};Object.defineProperty(yp,"__esModule",{value:!0}),yp.Safari12=void 0;const bp=il,_p=Td,Ep=Nd,wp=Id,Sp=vl,Cp=bl,Pp=Il,Tp=Ol,Rp=Ml,kp=new Sd.Logger("Safari12"),Dp={OS:65535,MIS:65535};class Ip extends _p.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:"Safari12",factory:e=>new Ip(e),getNativeRtpCapabilities:async({direction:e})=>{kp.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});const r=await t.createOffer();try{t.close()}catch(e){}t=void 0;const n=bp.parse(r.sdp);return Ip.getLocalRtpCapabilities(n)}catch(e){try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(kp.debug("getNativeSctpCapabilities()"),{numStreams:Dp})}}static getLocalRtpCapabilities(e,t=[]){const r=Pp.extractRtpCapabilities({sdpObject:e});Ep.validateAndNormalizeRtpCapabilities(r),Rp.addNackSupportForOpus(r);for(const e of t)Rp.addHeaderExtensionSupport(r,e);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),kp.debug("constructor()"),this._direction=e,this._remoteSdp=new Cp.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.addEventListener("icecandidateerror",(e=>{this.emit("@icecandidateerror",e)})),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(kp.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Safari12"}close(){if(kp.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch(e){}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),kp.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),kp.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});kp.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};kp.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};kp.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();kp.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s,onRtpSender:o}){this.assertNotClosed(),this.assertSendDirection(),kp.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});o&&o(c.sender);let d=await this._pc.createOffer(),u=bp.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const l=[];l.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});const p=Ip.getLocalRtpCapabilities(u,l),h=this._getSendExtendedRtpCapabilities(p),f=Ep.getSendingRtpParameters(e.kind,h);f.codecs=Ep.reduceCodecs(f.codecs,s);const m=Ep.getSendingRemoteRtpParameters(e.kind,h);let g;m.codecs=Ep.reduceCodecs(m.codecs,s),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});const v=(0,Sp.parse)((r??[{}])[0].scalabilityMode);r&&r.length>1&&(kp.debug("send() | enabling legacy simulcast"),u=bp.parse(d.sdp),g=u.media[a.idx],Tp.addLegacySimulcast({offerMediaObject:g,numStreams:r.length}),d={type:"offer",sdp:bp.write(u)}),i?.absCaptureTime&&(g=u.media[a.idx],Pp.addHeaderExtension({offerMediaObject:g,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"===e.uri)).id}),d={type:"offer",sdp:bp.write(u)}),kp.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const y=c.mid;if(f.mid=y,u=bp.parse(this._pc.localDescription.sdp),g=u.media[a.idx],f.rtcp.cname=Pp.getCname({offerMediaObject:g}),f.msid=`${t??this._sendStream.id} ${e.id}`,f.encodings=Tp.getRtpEncodings({offerMediaObject:g,codecs:f.codecs}),r)for(let e=0;e<f.encodings.length;++e)r[e]&&Object.assign(f.encodings[e],r[e]);if(f.encodings.length>1&&("video/vp8"===f.codecs[0].mimeType.toLowerCase()||"video/h264"===f.codecs[0].mimeType.toLowerCase()))for(const e of f.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${v.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:g,reuseMid:a.reuseMid,offerRtpParameters:f,answerRtpParameters:m,codecOptions:n});const b={type:"answer",sdp:this._remoteSdp.getSdp()};return kp.debug("send() | calling pc.setRemoteDescription() [answer:%o]",b),await this._pc.setRemoteDescription(b),this._mapMidTransceiver.set(y,c),{localId:y,rtpParameters:f,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;kp.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();kp.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};kp.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),kp.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();kp.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};kp.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),kp.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();kp.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};kp.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?kp.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):kp.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),kp.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();kp.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};kp.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),kp.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();kp.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};kp.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};kp.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Dp.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=bp.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),kp.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};kp.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;kp.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=Rp.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};kp.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=bp.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));Pp.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:bp.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),kp.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){kp.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};kp.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();kp.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){kp.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};kp.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();kp.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){kp.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};kp.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();kp.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};kp.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};kp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=bp.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}kp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=bp.parse(this._pc.localDescription.sdp));const r=Pp.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}};assertNotClosed(){if(this._closed)throw new wp.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}yp.Safari12=Ip;var Ap={};Object.defineProperty(Ap,"__esModule",{value:!0}),Ap.ReactNative106=void 0;const Op=il,Mp=Td,Np=Nd,Lp=Id,xp=vl,Fp=bl,jp=Il,Up=Ol,Vp=Ml,Bp=new Sd.Logger("ReactNative106"),Wp={OS:65535,MIS:65535};class Hp extends Mp.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:"ReactNative106",factory:e=>new Hp(e),getNativeRtpCapabilities:async({direction:e})=>{Bp.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});const r=await t.createOffer();try{t.close()}catch(e){}t=void 0;const n=Op.parse(r.sdp);return Hp.getLocalRtpCapabilities(n)}catch(e){try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(Bp.debug("getNativeSctpCapabilities()"),{numStreams:Wp})}}static getLocalRtpCapabilities(e,t=[]){const r=jp.extractRtpCapabilities({sdpObject:e});Np.validateAndNormalizeRtpCapabilities(r),Vp.addNackSupportForOpus(r);for(const e of t)Vp.addHeaderExtensionSupport(r,e);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Bp.debug("constructor()"),this._direction=e,this._remoteSdp=new Fp.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(Bp.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"ReactNative106"}close(){if(Bp.debug("close()"),!this._closed){this._closed=!0,this._sendStream.release(!1);try{this._pc.close()}catch(e){}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),Bp.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Bp.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Bp.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Bp.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Bp.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Bp.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s,onRtpSender:o}){this.assertNotClosed(),this.assertSendDirection(),Bp.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach(((e,t)=>{e.rid=`r${t}`}));const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});o&&o(c.sender);let d=await this._pc.createOffer(),u=Op.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const l=[];l.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});const p=Hp.getLocalRtpCapabilities(u,l),h=this._getSendExtendedRtpCapabilities(p),f=Np.getSendingRtpParameters(e.kind,h);f.codecs=Np.reduceCodecs(f.codecs,s);const m=Np.getSendingRemoteRtpParameters(e.kind,h);m.codecs=Np.reduceCodecs(m.codecs,s),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let g=!1;const v=(0,xp.parse)((r??[{}])[0].scalabilityMode);let y;1===r?.length&&v.spatialLayers>1&&"video/vp9"===f.codecs[0].mimeType.toLowerCase()&&(Bp.debug("send() | enabling legacy simulcast for VP9 SVC"),g=!0,u=Op.parse(d.sdp),y=u.media[a.idx],Up.addLegacySimulcast({offerMediaObject:y,numStreams:v.spatialLayers}),d={type:"offer",sdp:Op.write(u)}),i?.absCaptureTime&&(y=u.media[a.idx],jp.addHeaderExtension({offerMediaObject:y,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"===e.uri)).id}),d={type:"offer",sdp:Op.write(u)}),Bp.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);let b=c.mid??void 0;if(b||Bp.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),f.mid=b,u=Op.parse(this._pc.localDescription.sdp),y=u.media[a.idx],f.rtcp.cname=jp.getCname({offerMediaObject:y}),f.msid=`${t??this._sendStream.id} ${e.id}`,r)if(1===r.length){let e=Up.getRtpEncodings({offerMediaObject:y,codecs:f.codecs});Object.assign(e[0],r[0]),g&&(e=[e[0]]),f.encodings=e}else f.encodings=r;else f.encodings=Up.getRtpEncodings({offerMediaObject:y,codecs:f.codecs});if(f.encodings.length>1&&("video/vp8"===f.codecs[0].mimeType.toLowerCase()||"video/h264"===f.codecs[0].mimeType.toLowerCase()))for(const e of f.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${v.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:y,reuseMid:a.reuseMid,offerRtpParameters:f,answerRtpParameters:m,codecOptions:n});const _={type:"answer",sdp:this._remoteSdp.getSdp()};return Bp.debug("send() | calling pc.setRemoteDescription() [answer:%o]",_),await this._pc.setRemoteDescription(_),b||(b=c.mid,f.mid=b),this._mapMidTransceiver.set(b,c),{localId:b,rtpParameters:f,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Bp.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Bp.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Bp.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Bp.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Bp.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Bp.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Bp.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();Bp.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Bp.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Bp.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Bp.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Bp.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Bp.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Bp.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Bp.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Bp.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Bp.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};Bp.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Wp.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Op.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Bp.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Bp.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;Bp.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=Vp.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Bp.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=Op.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));jp.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Op.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Bp.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Bp.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Bp.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Bp.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Bp.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Bp.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Bp.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Bp.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Bp.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Bp.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Bp.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Bp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Op.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Bp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Op.parse(this._pc.localDescription.sdp));const r=jp.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}};assertNotClosed(){if(this._closed)throw new Lp.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Ap.ReactNative106=Hp,Object.defineProperty(wd,"__esModule",{value:!0}),wd.Device=void 0,wd.detectDevice=th,wd.detectDeviceAsync=rh;const qp=Td,zp=Id,Gp=Md,Yp=Nd,$p=mu,Jp=nl,Qp=Gl,Kp=sp,Zp=yp,Xp=Ap,eh=new Sd.Logger("Device");function th(e,t){return eh.debug("detectDevice()"),e||"object"!=typeof navigator||(e=navigator.userAgent),t||"object"!=typeof navigator||(t=navigator.userAgentData),ih(e,t)}async function rh(e,t){return eh.debug("detectDeviceAsync()"),e||"object"!=typeof navigator||(e=navigator.userAgent),t||"object"!=typeof navigator||(t=navigator.userAgentData),ih(e,t)}class nh{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new qp.EnhancedEventEmitter;static async factory({handlerName:e,handlerFactory:t}={}){if(eh.debug("factory()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!e&&!t&&!(e=await rh()))throw new zp.UnsupportedError("device not supported");return new nh({handlerName:e,handlerFactory:t})}constructor({handlerName:e,handlerFactory:t}={}){if(eh.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)eh.debug("constructor() | handler given: %s",e);else{if(!(e=th()))throw new zp.UnsupportedError("device not supported");eh.debug("constructor() | detected handler: %s",e)}switch(e){case"Chrome111":this._handlerFactory=Jp.Chrome111.createFactory();break;case"Chrome74":this._handlerFactory=Qp.Chrome74.createFactory();break;case"Firefox120":this._handlerFactory=Kp.Firefox120.createFactory();break;case"Safari12":this._handlerFactory=Zp.Safari12.createFactory();break;case"ReactNative106":this._handlerFactory=Xp.ReactNative106.createFactory();break;default:throw new TypeError(`unknown handlerName "${e}"`)}}this._handlerName=this._handlerFactory.name}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){return this.recvRtpCapabilities}get recvRtpCapabilities(){if(!this._loaded)throw new zp.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sendRtpCapabilities(){if(!this._loaded)throw new zp.InvalidStateError("not loaded");return this._sendRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new zp.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e,preferLocalCodecsOrder:t=!1}){if(eh.debug("load() [routerRtpCapabilities:%o]",e),this._loaded)throw new zp.InvalidStateError("already loaded");const r=Gp.clone(e);Yp.validateAndNormalizeRtpCapabilities(r);const{getNativeRtpCapabilities:n,getNativeSctpCapabilities:i}=this._handlerFactory,s=Gp.clone(await n({direction:"recvonly"}));eh.debug("load() | got native receiving RTP capabilities:%o",s),Yp.validateAndNormalizeRtpCapabilities(s);const o=Gp.clone(await n({direction:"sendonly"}));eh.debug("load() | got native sending RTP capabilities:%o",o),Yp.validateAndNormalizeRtpCapabilities(o),this._getSendExtendedRtpCapabilities=e=>Gp.clone(Yp.getExtendedRtpCapabilities(e,r,t));const a=Yp.getExtendedRtpCapabilities(s,r,!1);this._recvRtpCapabilities=Yp.getRecvRtpCapabilities(a),eh.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),Yp.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities);const c=Yp.getExtendedRtpCapabilities(o,r,t);this._sendRtpCapabilities=Yp.getSendRtpCapabilities(c),eh.debug("load() | got sending RTP capabilities:%o",this._sendRtpCapabilities),Yp.validateAndNormalizeRtpCapabilities(this._sendRtpCapabilities),this._canProduceByKind.audio=Yp.canSend("audio",this._sendRtpCapabilities),this._canProduceByKind.video=Yp.canSend("video",this._sendRtpCapabilities),this._sctpCapabilities=await i(),Yp.validateSctpCapabilities(this._sctpCapabilities),eh.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),eh.debug("load() succeeded"),this._loaded=!0}canProduce(e){if(!this._loaded)throw new zp.InvalidStateError("not loaded");if("audio"!==e&&"video"!==e)throw new TypeError(`invalid kind "${e}"`);return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,appData:c}){return eh.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,appData:c})}createRecvTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,appData:c}){return eh.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,appData:c})}createTransport({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d}){if(!this._loaded)throw new zp.InvalidStateError("not loaded");if("string"!=typeof t)throw new TypeError("missing id");if("object"!=typeof r)throw new TypeError("missing iceParameters");if(!Array.isArray(n))throw new TypeError("missing iceCandidates");if("object"!=typeof i)throw new TypeError("missing dtlsParameters");if(s&&"object"!=typeof s)throw new TypeError("wrong sctpParameters");if(d&&"object"!=typeof d)throw new TypeError("if given, appData must be an object");const u=new $p.Transport({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d,handlerFactory:this._handlerFactory,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities,recvRtpCapabilities:this._recvRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",u),u}}function ih(e,t){eh.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',e,t);const r=function(e,t){if(eh.debug("getChromiumMajorVersion()"),sh(e,t))return void eh.debug("getChromiumMajorVersion() | this is iOS => undefined");if(oh())return void eh.debug("getChromiumMajorVersion() | this is React-Native => undefined");if(t){const e=(Array.isArray(t.brands)?t.brands:[]).find((e=>"Chromium"===e.brand));if(e){const t=Number(e.version);return eh.debug(`getChromiumMajorVersion() | Chromium major version based on NavigatorUAData => ${t}`),t}}const r=e?.match(/\b(?:Chrome|Chromium)\/(\w+)/i);if(r?.[1]){const e=Number(r[1]);return eh.debug(`getChromiumMajorVersion() | Chromium major version based on User-Agent => ${e}`),e}return void eh.debug("getChromiumMajorVersion() | this is not Chromium => undefined")}(e,t);if(r)return r>=111?(eh.debug("detectDeviceImpl() | using Chrome111 handler"),"Chrome111"):r>=74?(eh.debug("detectDeviceImpl() | using Chrome74 handler"),"Chrome74"):void eh.warn("detectDeviceImpl() | unsupported Chromium based browser/version");const n=function(e){if(eh.debug("getFirefoxMajorVersion()"),sh(e))return void eh.debug("getFirefoxMajorVersion() | this is iOS => undefined");if(oh())return void eh.debug("getFirefoxMajorVersion() | this is React-Native => undefined");const t=e?.match(/\bFirefox\/(\w+)/i);if(t?.[1]){const e=Number(t[1]);return eh.debug(`getFirefoxMajorVersion() | Firefox major version based on User-Agent => ${e}`),e}return void eh.debug("getFirefoxMajorVersion() | this is not Firefox => undefined")}(e);if(n)return n>=120?(eh.debug("detectDeviceImpl() | using Firefox120 handler"),"Firefox120"):void eh.warn("detectDeviceImpl() | unsupported Firefox browser/version");const i=function(e){if(eh.debug("getMacOSWebKitMajorVersion()"),sh(e))return void eh.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");if(oh())return void eh.debug("getMacOSWebKitMajorVersion() | this is React-Native => undefined");if(!e||!/\bSafari\b/i.test(e)||/\bChrome\b/i.test(e)||/\bChromium\b/i.test(e)||/\bFirefox\b/i.test(e))return void eh.debug("getMacOSWebKitMajorVersion() | this is not Safari => undefined");const t=e.match(/AppleWebKit\/(\w+)/i);if(t?.[1]){const e=Number(t[1]);return eh.debug(`getMacOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${e}`),e}return void eh.debug("getMacOSWebKitMajorVersion() | this is not WebKit => undefined")}(e);if(i)return i>=605?(eh.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12"):void eh.warn("detectDeviceImpl() | unsupported desktop Safari browser/version");const s=function(e){if(eh.debug("getIOSWebKitMajorVersion()"),!sh(e))return void eh.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");if(oh())return void eh.debug("getIOSWebKitMajorVersion() | this is React-Native => undefined");const t=e?.match(/AppleWebKit\/(\w+)/i);if(t?.[1]){const e=Number(t[1]);return eh.debug(`getIOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${e}`),e}return void eh.debug("getIOSWebKitMajorVersion() | this is not WebKit => undefined")}(e);return s?s>=605?(eh.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12"):void eh.warn("detectDeviceImpl() | unsupported iOS Safari based browser/version"):oh()?"undefined"!=typeof RTCPeerConnection&&"undefined"!=typeof RTCRtpTransceiver?(eh.debug("detectDeviceImpl() | using ReactNative106 handler"),"ReactNative106"):void eh.warn("detectDeviceImpl() | unsupported react-native-webrtc version without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?"):void eh.warn('detectDeviceImpl() | device not supported [userAgent:"%s", userAgentData:%o]',e,t)}function sh(e,t){return eh.debug("isIOS()"),"iOS"===t?.platform?(eh.debug("isIOS() | this is iOS based on NavigatorUAData.platform => true"),!0):t?.platform?(eh.debug("isIOS() | this is not iOS based on NavigatorUAData.platform => false"),!1):e&&/iPad|iPhone|iPod/.test(e)?(eh.debug("isIOS() | this is iOS based on User-Agent => true"),!0):"object"==typeof navigator&&"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1?(eh.debug("isIOS() | this is iPadOS 13+ based on User-Agent => true"),!0):(eh.debug("isIOS() | this is not iOS => false"),!1)}function oh(){return eh.debug("isReactNative()"),"object"==typeof navigator&&"ReactNative"===navigator.product?(eh.debug("isReactNative() | this is React-Native based on navigator.product"),!0):(eh.debug("isReactNative() | this is not React-Native => false"),!1)}wd.Device=nh;for(var ah,ch={},dh={},uh={},lh=256,ph=[];lh--;)ph[lh]=(lh+256).toString(16).substring(1);uh.v4=function(){var e,t=0,r="";if(!ah||lh+16>256){for(ah=Array(t=256);t--;)ah[t]=256*Math.random()|0;t=lh=0}for(;t<16;t++)e=ah[lh+t],r+=6==t?ph[15&e|64]:8==t?ph[63&e|128]:ph[e],1&t&&t>1&&t<11&&(r+="-");return lh++,r};var hh={};Object.defineProperty(hh,"__esModule",{value:!0}),hh.FakeEventTarget=void 0;hh.FakeEventTarget=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:"function"==typeof t?t:t.handleEvent,once:"object"==typeof r&&!0===r.once}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter((e=>e.callback!==("function"==typeof t?t:t.handleEvent))))}dispatchEvent(e){if(!e||"string"!=typeof e.type)throw new Error("invalid event object");const t=this.listeners[e.type];if(!t)return!0;for(const r of[...t]){try{r.callback.call(this,e)}catch(e){setTimeout((()=>{throw e}),0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}};var fh={};Object.defineProperty(fh,"__esModule",{value:!0}),fh.FakeEvent=void 0;fh.FakeEvent=class{NONE=0;CAPTURING_PHASE=1;AT_TARGET=2;BUBBLING_PHASE=3;type;bubbles;cancelable;defaultPrevented=!1;composed=!1;currentTarget=null;eventPhase=u.NONE;isTrusted=!0;target=null;timeStamp=0;cancelBubble=!1;returnValue=!0;srcElement=null;constructor(e,t={}){this.type=e,this.bubbles=t.bubbles??!1,this.cancelable=t.cancelable??!1}preventDefault(){this.cancelable&&(this.defaultPrevented=!0)}stopPropagation(){}stopImmediatePropagation(){}composedPath(){return[]}initEvent(e,t,r){}};var mh={};Object.defineProperty(mh,"__esModule",{value:!0}),mh.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))},Object.defineProperty(dh,"__esModule",{value:!0}),dh.FakeMediaStreamTrack=void 0;const gh=uh,vh=hh,yh=fh,bh=mh;class _h extends vh.FakeEventTarget{#E;#w;#S;#C;#P;#T;#R;#k;#D;#I;#A;#O=null;#M=null;#N=null;#L=null;#x=null;constructor({kind:e,id:t,label:r,contentHint:n,enabled:i,muted:s,readyState:o,capabilities:a,constraints:c,settings:d,data:u}){super(),this.#E=t??(0,gh.v4)(),this.#w=e,this.#S=r??"",this.#R=n??"",this.#P=i??!0,this.#T=s??!1,this.#C=o??"live",this.#k=a??{},this.#D=c??{},this.#I=d??{},this.#A=u??{}}get id(){return this.#E}get kind(){return this.#w}get label(){return this.#S}get contentHint(){return this.#R}set contentHint(e){this.#R=e}get enabled(){return this.#P}set enabled(e){const t=this.#P!==e;this.#P=e,t&&this.dispatchEvent(new yh.FakeEvent("enabledchange"))}get muted(){return this.#T}get readyState(){return this.#C}get data(){return this.#A}set data(e){this.#A=e}get onmute(){return this.#O}set onmute(e){this.#O&&this.removeEventListener("mute",this.#O),this.#O=e,e&&this.addEventListener("mute",e)}get onunmute(){return this.#M}set onunmute(e){this.#M&&this.removeEventListener("unmute",this.#M),this.#M=e,e&&this.addEventListener("unmute",e)}get onended(){return this.#N}set onended(e){this.#N&&this.removeEventListener("ended",this.#N),this.#N=e,e&&this.addEventListener("ended",e)}get onenabledchange(){return this.#L}set onenabledchange(e){this.#L&&this.removeEventListener("enabledchange",this.#L),this.#L=e,e&&this.addEventListener("enabledchange",e)}get onstopped(){return this.#x}set onstopped(e){this.#x&&this.removeEventListener("stopped",this.#x),this.#x=e,e&&this.addEventListener("stopped",e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}stop(){"ended"!==this.#C&&(this.#C="ended",this.dispatchEvent(new yh.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new _h({id:e??(0,gh.v4)(),kind:this.#w,label:this.#S,contentHint:this.#R,enabled:this.#P,muted:this.#T,readyState:this.#C,capabilities:(0,bh.clone)(this.#k),constraints:(0,bh.clone)(this.#D),settings:(0,bh.clone)(this.#I),data:t??(0,bh.clone)(this.#A)})}getCapabilities(){return this.#k}getConstraints(){return this.#D}async applyConstraints(e={}){return this.#D=e,Promise.resolve()}getSettings(){return this.#I}remoteStop(){"ended"!==this.#C&&(this.#C="ended",this.dispatchEvent(new yh.FakeEvent("stopped")),this.dispatchEvent(new yh.FakeEvent("ended")))}remoteMute(){this.#T||(this.#T=!0,this.dispatchEvent(new yh.FakeEvent("mute")))}remoteUnmute(){this.#T&&(this.#T=!1,this.dispatchEvent(new yh.FakeEvent("unmute")))}}dh.FakeMediaStreamTrack=_h;var Eh={};Object.defineProperty(Eh,"__esModule",{value:!0}),Eh.FakeEventTarget=void 0;Eh.FakeEventTarget=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:"function"==typeof t?t:t.handleEvent,once:"object"==typeof r&&!0===r.once}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter((e=>e.callback!==("function"==typeof t?t:t.handleEvent))))}dispatchEvent(e){if(!e||"string"!=typeof e.type)throw new Error("invalid event object");const t=this.listeners[e.type];if(!t)return!0;for(const r of[...t]){try{r.callback.call(this,e)}catch(e){setTimeout((()=>{throw e}),0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}},Object.defineProperty(ch,"__esModule",{value:!0}),ch.FakeHandler=void 0;const wh=dh,Sh=Td,Ch=Md,Ph=Nd,Th=Id,Rh=Eh,kh=new Sd.Logger("FakeHandler");class Dh extends Sh.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${Ch.generateRandomNumber()}`;_defaultSendStreamId=`${Ch.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:"FakeHandler",factory:t=>new Dh(t,e),getNativeRtpCapabilities:async({direction:t})=>(kh.debug("getNativeRtpCapabilities() [direction:%o]",t),Dh.getLocalRtpCapabilities(e)),getNativeSctpCapabilities:async()=>(kh.debug("getNativeSctpCapabilities()"),e.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(e){const t=e.generateNativeRtpCapabilities();return Ph.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),kh.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return"FakeHandler"}close(){kh.debug("close()"),this._closed||(this._closed=!0,super.close())}setIceGatheringState(e){this.emit("@icegatheringstatechange",e)}setConnectionState(e){this.emit("@connectionstatechange",e)}async updateIceServers(e){this.assertNotClosed(),kh.debug("updateIceServers()")}async restartIce(e){this.assertNotClosed(),kh.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:e,streamId:t,encodings:r,codecOptions:n,codec:i}){this.assertNotClosed(),kh.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});const s=Dh.getLocalRtpCapabilities(this._fakeParameters),o=this._getSendExtendedRtpCapabilities(s),a=Ph.getSendingRtpParameters(e.kind,o);a.codecs=Ph.reduceCodecs(a.codecs,i);const c=a.codecs.some((e=>/.+\/rtx$/i.test(e.mimeType)));a.mid=`mid-${Ch.generateRandomNumber()}`,a.msid=`${t??"-"} ${e.id}`,r||(r=[{}]);for(const e of r)e.ssrc=Ch.generateRandomNumber(),c&&(e.rtx={ssrc:Ch.generateRandomNumber()});a.encodings=r,a.rtcp={cname:this._cname,reducedSize:!0,mux:!0},a.msid=`${t??this._defaultSendStreamId} ${e.id}`;const d=this._nextLocalId++;return this._tracks.set(d,e),{localId:String(d),rtpParameters:a}}async stopSending(e){if(kh.debug("stopSending() [localId:%s]",e),!this._closed){if(!this._tracks.has(Number(e)))throw new Error("local track not found");this._tracks.delete(Number(e))}}async pauseSending(e){this.assertNotClosed()}async resumeSending(e){this.assertNotClosed()}async replaceTrack(e,t){this.assertNotClosed(),t?kh.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):kh.debug("replaceTrack() [localId:%s, no track]",e),this._tracks.delete(Number(e)),this._tracks.set(Number(e),t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),kh.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),kh.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t)}async getSenderStats(e){return this.assertNotClosed(),new Map}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),kh.debug("sendDataChannel()");return{dataChannel:new Ih({id:this._nextSctpStreamId++,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}),sctpStreamParameters:{streamId:this._nextSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r}}}async receive(e){this.assertNotClosed();const t=[];for(const r of e){const{trackId:e,kind:n}=r;this._transportReady||await this.setupTransport({localDtlsRole:"client"}),kh.debug("receive() [trackId:%s, kind:%s]",e,n);const i=this._nextLocalId++,s=new wh.FakeMediaStreamTrack({kind:n});this._tracks.set(i,s),t.push({localId:String(i),track:s})}return t}async stopReceiving(e){if(!this._closed)for(const t of e)kh.debug("stopReceiving() [localId:%s]",t),this._tracks.delete(Number(t))}async pauseReceiving(e){this.assertNotClosed()}async resumeReceiving(e){this.assertNotClosed()}async getReceiverStats(e){return this.assertNotClosed(),new Map}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"client"}),kh.debug("receiveDataChannel()");return{dataChannel:new Ih({id:e.streamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:t,protocol:r})}}async setupTransport({localDtlsRole:e,localSdpObject:t}){const r=Ch.clone(this._fakeParameters.generateLocalDtlsParameters());e&&(r.role=e),this.emit("@connectionstatechange","connecting"),await new Promise(((e,t)=>this.emit("@connect",{dtlsParameters:r},e,t))),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Th.InvalidStateError("method called in a closed handler")}}ch.FakeHandler=Dh;class Ih extends Rh.FakeEventTarget{_id;_negotiated=!0;_ordered;_maxPacketLifeTime;_maxRetransmits;_label;_protocol;_readyState="connecting";_bufferedAmount=0;_bufferedAmountLowThreshold=0;_binaryType="arraybuffer";_onopen=null;_onclosing=null;_onclose=null;_onmessage=null;_onbufferedamountlow=null;_onerror=null;constructor({id:e,ordered:t=!0,maxPacketLifeTime:r=null,maxRetransmits:n=null,label:i="",protocol:s=""}){super(),kh.debug(`constructor() [id:${e}, ordered:${t}, maxPacketLifeTime:${r}, maxRetransmits:${n}, label:${i}, protocol:${s}`),this._id=e,this._ordered=t,this._maxPacketLifeTime=r,this._maxRetransmits=n,this._label=i,this._protocol=s}get id(){return this._id}get negotiated(){return this._negotiated}get ordered(){return this._ordered}get maxPacketLifeTime(){return this._maxPacketLifeTime}get maxRetransmits(){return this._maxRetransmits}get label(){return this._label}get protocol(){return this._protocol}get readyState(){return this._readyState}get bufferedAmount(){return this._bufferedAmount}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._bufferedAmountLowThreshold=e}get binaryType(){return this._binaryType}set binaryType(e){this._binaryType=e}get onopen(){return this._onopen}set onopen(e){this._onopen&&this.removeEventListener("open",this._onopen),this._onopen=e,e&&this.addEventListener("open",e)}get onclosing(){return this._onclosing}set onclosing(e){this._onclosing&&this.removeEventListener("closing",this._onclosing),this._onclosing=e,e&&this.addEventListener("closing",e)}get onclose(){return this._onclose}set onclose(e){this._onclose&&this.removeEventListener("close",this._onclose),this._onclose=e,e&&this.addEventListener("close",e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage&&this.removeEventListener("message",this._onmessage),this._onmessage=e,e&&this.addEventListener("message",e)}get onbufferedamountlow(){return this._onbufferedamountlow}set onbufferedamountlow(e){this._onbufferedamountlow&&this.removeEventListener("bufferedamountlow",this._onbufferedamountlow),this._onbufferedamountlow=e,e&&this.addEventListener("bufferedamountlow",e)}get onerror(){return this._onerror}set onerror(e){this._onerror&&this.removeEventListener("error",this._onerror),this._onerror=e,e&&this.addEventListener("error",e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}close(){["closing","closed"].includes(this._readyState)||(this._readyState="closed")}send(e){if("open"!==this._readyState)throw new Th.InvalidStateError("not open")}}var Ah={};Object.defineProperty(Ah,"__esModule",{value:!0}),Ah.generateRouterRtpCapabilities=function(){return Oh.deepFreeze({codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}},{mimeType:"video/H264",kind:"video",preferredPayloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:105,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"profile-id":0,"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:106,clockRate:9e4,rtcpFeedback:[],parameters:{apt:105}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",preferredId:2,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",preferredId:3,preferredEncrypt:!1,direction:"recvonly"},{kind:"audio",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:11,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:12,preferredEncrypt:!1,direction:"sendrecv"}]})},Ah.generateNativeRtpCapabilities=function(){return{codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:111,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{minptime:10,useinbandfec:1}},{mimeType:"audio/ISAC",kind:"audio",preferredPayloadType:103,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/CN",kind:"audio",preferredPayloadType:106,clockRate:32e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/foo",kind:"audio",preferredPayloadType:107,clockRate:9e4,channels:4,rtcpFeedback:[{type:"foo-qwe-qwe"}],parameters:{foo:"lalala"}},{mimeType:"video/BAZCODEC",kind:"video",preferredPayloadType:100,clockRate:9e4,rtcpFeedback:[{type:"foo"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[],parameters:{apt:100}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:96,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:97,clockRate:9e4,rtcpFeedback:[],parameters:{apt:96}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:98,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{"profile-id":0}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:99,clockRate:9e4,rtcpFeedback:[],parameters:{apt:98}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:2},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:3},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:4},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay",preferredId:6},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type",preferredId:7},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing",preferredId:8},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10}]}},Ah.generateNativeSctpCapabilities=function(){return Oh.deepFreeze({numStreams:{OS:2048,MIS:2048}})},Ah.generateLocalDtlsParameters=function(){return Oh.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"82:5A:68:3D:36:C3:0A:DE:AF:E7:32:43:D2:88:83:57:AC:2D:65:E5:80:C4:B6:FB:AF:1A:A0:21:9F:6D:0C:AD"}],role:"auto"})},Ah.generateTransportRemoteParameters=function(){return{id:Mh(),iceParameters:Oh.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:Oh.deepFreeze([{foundation:"udpcandidate",address:"9.9.9.9",ip:"9.9.9.9",port:40533,priority:1078862079,protocol:"udp",type:"host",tcpType:"passive"},{foundation:"udpcandidate",address:"9.9.9.9",ip:"9:9:9:9:9:9",port:41333,priority:1078862089,protocol:"udp",type:"host",tcpType:"passive"}]),dtlsParameters:Oh.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"A9:F4:E0:D2:74:D3:0F:D9:CA:A5:2F:9F:7F:47:FA:F0:C4:72:DD:73:49:D0:3B:14:90:20:51:30:1B:90:8E:71"},{algorithm:"sha-384",value:"03:D9:0B:87:13:98:F6:6D:BC:FC:92:2E:39:D4:E1:97:32:61:30:56:84:70:81:6E:D1:82:97:EA:D9:C1:21:0F:6B:C5:E7:7F:E1:97:0C:17:97:6E:CF:B3:EF:2E:74:B0"},{algorithm:"sha-512",value:"84:27:A4:28:A4:73:AF:43:02:2A:44:68:FF:2F:29:5C:3B:11:9A:60:F4:A8:F0:F5:AC:A0:E3:49:3E:B1:34:53:A9:85:CE:51:9B:ED:87:5E:B8:F4:8E:3D:FA:20:51:B8:96:EE:DA:56:DC:2F:5C:62:79:15:23:E0:21:82:2B:2C"}],role:"auto"}),sctpParameters:Oh.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}},Ah.generateProducerRemoteParameters=function(){return Oh.deepFreeze({id:Mh()})},Ah.generateConsumerRemoteParameters=function({id:e,codecMimeType:t}={}){switch(t){case"audio/opus":return{id:e??Mh(),producerId:Mh(),kind:"audio",rtpParameters:Oh.deepFreeze({codecs:[{mimeType:"audio/opus",payloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}}],encodings:[{ssrc:46687003}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",id:10}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"audio/ISAC":return{id:e??Mh(),producerId:Mh(),kind:"audio",rtpParameters:Oh.deepFreeze({codecs:[{mimeType:"audio/ISAC",payloadType:111,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}}],encodings:[{ssrc:46687004}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/VP8":return{id:e??Mh(),producerId:Mh(),kind:"video",rtpParameters:Oh.deepFreeze({codecs:[{mimeType:"video/VP8",payloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",payloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}}],encodings:[{ssrc:99991111,rtx:{ssrc:99991112}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/H264":return{id:e??Mh(),producerId:Mh(),kind:"video",rtpParameters:Oh.deepFreeze({codecs:[{mimeType:"video/H264",payloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",payloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}}],encodings:[{ssrc:99991113,rtx:{ssrc:99991114}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};default:throw new TypeError(`unknown codecMimeType '${t}'`)}},Ah.generateDataProducerRemoteParameters=function(){return Oh.deepFreeze({id:Mh()})},Ah.generateDataConsumerRemoteParameters=function({id:e}={}){return{id:e??Mh(),dataProducerId:Mh(),sctpStreamParameters:Oh.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}};const Oh=Md;function Mh(){return String(Oh.generateRandomNumber())}!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.debug=e.testFakeParameters=e.FakeHandler=e.enhancedEvents=e.ortc=e.parseScalabilityMode=e.detectDeviceAsync=e.detectDevice=e.Device=e.version=e.types=void 0;const t=hd.exports;e.debug=t.default,e.types=Ed,e.version="3.18.8";var r=wd;Object.defineProperty(e,"Device",{enumerable:!0,get:function(){return r.Device}}),Object.defineProperty(e,"detectDevice",{enumerable:!0,get:function(){return r.detectDevice}}),Object.defineProperty(e,"detectDeviceAsync",{enumerable:!0,get:function(){return r.detectDeviceAsync}});var n=vl;Object.defineProperty(e,"parseScalabilityMode",{enumerable:!0,get:function(){return n.parse}}),e.ortc=Nd,e.enhancedEvents=Td;var i=ch;Object.defineProperty(e,"FakeHandler",{enumerable:!0,get:function(){return i.FakeHandler}}),e.testFakeParameters=Ah}(pd);const Nh=[{scaleResolutionDownBy:4,maxBitrate:15e4,maxFramerate:12},{scaleResolutionDownBy:2,maxBitrate:35e4,maxFramerate:18},{scaleResolutionDownBy:1,maxBitrate:9e5,maxFramerate:24}],Lh=[{maxBitrate:1e6,dtx:!0}],xh=[{maxBitrate:4e4,dtx:!0}],Fh={width:1280,height:720},jh=0,Uh=2,Vh=0;function Bh(e,t){e.onload=function(){this.onerror=this.onload=null,t(null,e)},e.onerror=function(){this.onerror=this.onload=null,t(new Error("Failed to load "+this.src),e)}}function Wh(e,t){e.onreadystatechange=function(){"complete"!=this.readyState&&"loaded"!=this.readyState||(this.onreadystatechange=null,t(null,e))}}const Hh=new li,qh=e=>o(void 0,void 0,void 0,(function*(){return yield new Promise(((t,r)=>{!function(e,t,r){var n=document.head||document.getElementsByTagName("head")[0],i=document.createElement("script");"function"==typeof t&&(r=t,t={}),t=t||{},r=r||function(){},i.type=t.type||"text/javascript",i.charset=t.charset||"utf8",i.async=!("async"in t)||!!t.async,i.src=e,t.attrs&&function(e,t){for(var r in t)e.setAttribute(r,t[r])}(i,t.attrs),t.text&&(i.text=""+t.text),("onload"in i?Bh:Wh)(i,r),i.onload||Bh(i,r),n.appendChild(i)}(e,((e,n)=>{e?r(e):t(n)}))}))})),zh=(e,...t)=>o(void 0,[e,...t],void 0,(function*(e,t=3,r=500){let n=0;for(;n<t;)try{return void(yield qh(e))}catch(e){if(n+=1,!(n<t))throw e;yield Hh.sleepMs(r)}}));var Gh;let Yh=class{constructor(){Gh.set(this,new Map)}add(e,t,r){const n=this.getKey(e,t);if(a(this,Gh,"f").has(n))throw new Error("Attempt to rewrite cached track processor");a(this,Gh,"f").set(n,r)}get(e,t){return a(this,Gh,"f").get(this.getKey(e,t))}has(e,t){return a(this,Gh,"f").has(this.getKey(e,t))}getKey(e,t){return`${e}:${t}`}reset(){for(const e of a(this,Gh,"f").values())try{e.stopProcessing(),e.release()}catch(e){}a(this,Gh,"f").clear()}};var $h,Jh;Gh=new WeakMap,Yh=n([ot()],Yh);let Qh=class{constructor(e,t,r,n){this.config=e,this.processorsCache=t,this.audioTrackProcessorFactory=r,$h.set(this,new Map),Jh.set(this,void 0),c(this,Jh,n("IntegrationsService"),"f")}init(){const e=this.config.get("denoiser");if("asdk"===e){a(this,Jh,"f").info("Start integration of ASDK",{denoiser:e});const t=this.integrateASDK();t.catch((e=>{a(this,Jh,"f").warn("ASDK integration failed, will fallback to RNNoise on demand",{error:String(e)})}));const r={integrated:!1,initPromise:t};a(this,$h,"f").set("asdk",r)}else{a(this,Jh,"f").info("Start integration of RNNoise",{denoiser:e});const t=this.integrateRNNoise();t.catch((e=>{a(this,Jh,"f").warn("RNNoise integration failed",{error:String(e)})}));const r={integrated:!1,initPromise:t};a(this,$h,"f").set("rnnoise",r)}}integrateASDK(){return o(this,void 0,void 0,(function*(){const e=this.config.get("asdk"),t=this.config.get("staticFilesPath");if(!window.atsvb){const i=`https://effectssdk.ai/sdk/audio/dev/${e.version}/atsvb-web.js`;let s=i;if(e.localDir){const r=`${e.localDir}/${e.version}/atsvb-web.js`;s=new URL(r,t).href}yield(r=s,n=i,o(void 0,void 0,void 0,(function*(){try{yield zh(r)}catch(e){if(!n)throw e;yield zh(n)}})))}var r,n;if(!window.atsvb)throw a(this,Jh,"f").info("Audio Effects SDK is not loaded, skipping initialization",{case:"initAudioSDK"}),new Error("windows.atsvb is still missing");const i=this.audioTrackProcessorFactory({trackLabel:exports.TrackLabel.Microphone});yield i.init(),this.processorsCache.add("asdk",exports.TrackLabel.Microphone,i);const s=a(this,$h,"f").get("asdk");if(!s)throw Error("IntegrationContext is missing for ASDK");s.integrated=!0}))}get audio(){return"asdk"===this.config.get("denoiser")?this.getASDKState():this.getRNNoiseState()}getASDKState(){var e,t;const r=a(this,$h,"f").get("asdk");return{type:"asdk",enabled:Boolean(r),isInitialized:null!==(e=null==r?void 0:r.integrated)&&void 0!==e&&e,waitForInitialization:null!==(t=null==r?void 0:r.initPromise)&&void 0!==t?t:Promise.resolve()}}getRNNoiseState(){var e,t;const r=a(this,$h,"f").get("rnnoise");return{type:"rnnoise",enabled:Boolean(r),isInitialized:null!==(e=null==r?void 0:r.integrated)&&void 0!==e&&e,waitForInitialization:null!==(t=null==r?void 0:r.initPromise)&&void 0!==t?t:Promise.resolve()}}integrateRNNoise(){return o(this,void 0,void 0,(function*(){const e=yield function(e){return o(this,void 0,void 0,(function*(){if(!window.WebAssembly)throw new Error("Webassembly not supported");const t=yield fetch(`${e}/rnnoise-processor.wasm`);return yield WebAssembly.instantiate(yield t.arrayBuffer())}))}(this.config.get("staticFilesPath")),t=this.audioTrackProcessorFactory({trackLabel:exports.TrackLabel.Microphone,noiseSuppressor:e});this.processorsCache.add("rnnoise",exports.TrackLabel.Microphone,t);const r=a(this,$h,"f").get("rnnoise");if(!r)throw Error("IntegrationContext is missing for RNNoise");r.integrated=!0}))}reset(){a(this,$h,"f").clear()}};function Kh(e,t){return(r,n,i)=>{const s=i.value,a=null!=t?t:n;return i.value=function(...t){return o(this,void 0,void 0,(function*(){return yield function(e,t,r){return o(this,void 0,void 0,(function*(){let n;const i=new Promise(((e,i)=>{n=setTimeout((()=>{i(new Jn(`Operation "${t}" timed out after ${r}ms`,"operation_timeout",{operation:t,timeoutMs:r}))}),r)}));return yield Promise.race([e,i]).finally((()=>{clearTimeout(n)}))}))}(s.apply(this,t),a,e)}))},i}}var Zh,Xh,ef,tf,rf,nf,sf,of,af,cf,df,uf,lf,pf,hf,ff,mf,gf,vf;$h=new WeakMap,Jh=new WeakMap,Qh=n([ot(),i(0,ct(fi.Config)),i(1,ct(fi.ProcessorsCache)),i(2,ct(fi.AudioTrackProcessorFactory)),i(3,ct(fi.LoggerFactory)),s("design:paramtypes",[Et,Yh,Function,Function])],Qh);class yf{constructor(e){var t,r;Zh.set(this,void 0),Xh.set(this,void 0),ef.set(this,void 0),tf.set(this,void 0),rf.set(this,void 0),nf.set(this,void 0),sf.set(this,0),c(this,Zh,e.logger,"f"),c(this,Xh,e.getMetrics,"f"),c(this,ef,null!==(t=e.pollIntervalMs)&&void 0!==t?t:15e3,"f"),c(this,tf,null!==(r=e.minLogIntervalMs)&&void 0!==r?r:6e4,"f")}start(){void 0===a(this,rf,"f")&&c(this,rf,setInterval((()=>this.tick()),a(this,ef,"f")),"f")}stop(){void 0!==a(this,rf,"f")&&(clearInterval(a(this,rf,"f")),c(this,rf,void 0,"f"))}tick(){const e=a(this,Xh,"f").call(this);if(!e)return;const t={fps:Math.round(e.fps),segmentationInferenceTime:Math.round(e.segmentationInferenceTime),fullFrameDrawTime:Math.round(e.fullFrameDrawTime)},r=`fps=${t.fps}|seg=${t.segmentationInferenceTime}|draw=${t.fullFrameDrawTime}`;if(r===a(this,nf,"f"))return;void 0!==a(this,nf,"f")&&Date.now()-a(this,sf,"f")<a(this,tf,"f")||(a(this,Zh,"f").info("effects_metrics",{metrics:t}),c(this,nf,r,"f"),c(this,sf,Date.now(),"f"))}}Zh=new WeakMap,Xh=new WeakMap,ef=new WeakMap,tf=new WeakMap,rf=new WeakMap,nf=new WeakMap,sf=new WeakMap,function(e){e.INFO="info",e.WARNING="warning",e.ERROR="error"}(gf||(gf={})),function(e){e.TSVB="tsvb",e.COMPONENTS_SYSTEM="components_system",e.SRTEAM_PROCESSOR="stream_processor",e.ML_INFERENCE="ml_inference",e.PRESET_INIT="preset_init",e.RENDERER="renderer",e.RECORDER="recorder",e.EFFECT_VIRTUAL_BACKGROUND="effect_virtual_background",e.EFFECT_COLOR_CORRECTION="effect_color_correction",e.EFFECT_COLOR_FILTER="effect_color_filter",e.EFFECT_SMART_ZOOM="effect_smart_zoom",e.EFFECT_LOW_LIGHT="effect_low_light"}(vf||(vf={}));class bf{constructor(e){of.set(this,void 0),af.set(this,void 0),cf.set(this,{lowLighter:!1,colorCorrector:!1,faceDetector:!1,segmentation:!1}),df.set(this,null),uf.set(this,void 0),lf.set(this,!1),pf.set(this,!1),hf.set(this,void 0),ff.set(this,void 0),mf.set(this,void 0);const{loggerFactory:t}=e;if(c(this,af,t("EffectsSDKTrackProcessor"),"f"),c(this,hf,e.onModelsLoaded,"f"),!e.customerId)throw new Error("Customer ID must be provided");c(this,of,new window.tsvb(e.customerId),"f"),a(this,of,"f").onError(this.tsvbErrorHandler.bind(this)),a(this,of,"f").onReady=this.onReady.bind(this);const r=e.config.get("staticFilesPath"),{localDir:n,version:i}=e.config.get("effectsSDKParams"),s=n&&i?`${r}/esdk/${null!=i?i:"3.8.0"}`:`https://effectssdk.ai/sdk/web/${null!=i?i:"3.8.0"}`,o={preset:"balanced",provider:"webgpu",sdk_url:e.sdk_url,api_url:e.api_url,test_inference:!0,wasmPaths:{"ort-wasm.wasm":`${s}/ort-wasm.wasm`,"ort-wasm-simd.wasm":`${s}/ort-wasm-simd.wasm`,"ort-wasm-simd.jsep.wasm":`${s}/ort-wasm-simd.jsep.wasm`}};a(this,of,"f").config(o)}init(){return o(this,void 0,void 0,(function*(){yield a(this,of,"f").preload(),yield a(this,of,"f").cache(),c(this,lf,!0,"f")}))}awaitReady(){return o(this,void 0,void 0,(function*(){yield new Promise((e=>{const t=setInterval((()=>{this.isModelsLoaded&&(clearInterval(t),e())}),100)}))}))}setOnRuntimeError(e){c(this,ff,e,"f")}tsvbErrorHandler(e){var t,n;const{emitter:i,type:s}=e,o=r(e,["emitter","type"]),c=null!=i?i:"N/A emitter";s===gf.ERROR&&(a(this,af,"f").error(c,Object.assign({error:Vt(e)},o)),null===(t=a(this,ff,"f"))||void 0===t||t.call(this,e)),s===gf.WARNING&&a(this,af,"f").warn(c,Object.assign({},o)),s===gf.INFO&&a(this,af,"f").debug(c,Object.assign({},o)),i===vf.ML_INFERENCE&&(o.message.toLocaleLowerCase().includes("init lowlighter")&&(a(this,cf,"f").lowLighter=!0),o.message.toLocaleLowerCase().includes("init colorcorrector")&&(a(this,cf,"f").colorCorrector=!0),o.message.toLocaleLowerCase().includes("init facedetector")&&(a(this,cf,"f").faceDetector=!0),o.message.toLocaleLowerCase().includes("init segmentation")&&(a(this,cf,"f").segmentation=!0),this.isModelsLoaded&&(null===(n=a(this,hf,"f"))||void 0===n||n.call(this)))}get isModelsLoaded(){return a(this,cf,"f").colorCorrector&&a(this,cf,"f").faceDetector&&a(this,cf,"f").lowLighter&&a(this,cf,"f").segmentation}get modelsLoadProgress(){return Object.values(a(this,cf,"f")).filter(Boolean).length/Object.keys(a(this,cf,"f")).length}get isReady(){return a(this,pf,"f")&&a(this,lf,"f")}setOnLoadModels(e){c(this,hf,e,"f"),this.isModelsLoaded&&a(this,hf,"f").call(this)}onReady(){c(this,pf,!0,"f"),a(this,af,"f").debug("onReady()",{description:"ESDK is ready"}),this.updateEffects(a(this,uf,"f")),c(this,mf,new yf({logger:a(this,af,"f"),getMetrics:()=>a(this,of,"f").getMetrics()}),"f"),a(this,mf,"f").start()}processTrack(e){var t,r,n;if(a(this,df,"f")===e||"ended"===e.readyState)return null!==(r=null===(t=a(this,of,"f").getStream())||void 0===t?void 0:t.getVideoTracks()[0])&&void 0!==r?r:e;this.stopProcessing();try{a(this,of,"f").useStream(new MediaStream([e]));const t=null===(n=a(this,of,"f").getStream())||void 0===n?void 0:n.getVideoTracks()[0];return t?(c(this,df,e,"f"),t):e}catch(t){throw a(this,af,"f").error("processTrack()",{error:t,track:e}),new Bt("esdk_process_track_failed",t)}}stopProcessing(){var e;null===(e=a(this,mf,"f"))||void 0===e||e.stop(),c(this,mf,void 0,"f");try{a(this,of,"f").clear(),a(this,of,"f").stop()}catch(e){a(this,af,"f").error("stopProcessing()",{error:e})}finally{c(this,df,null,"f"),c(this,pf,!1,"f")}}updateEffects(e){var t,r,n,i,s,o,d,u,l,p,h,f,m,g,v,y,b,_,E,w,S,C;if(c(this,uf,e,"f"),!a(this,pf,"f"))return void a(this,af,"f").warn("updateEffects()",{description:"Esdk pipeline not ready"});if(!a(this,uf,"f")||0===Object.keys(a(this,uf,"f")).length)return void a(this,of,"f").stop();let P=0;if((null===(t=a(this,uf,"f"))||void 0===t?void 0:t.blur)&&!(null===(r=a(this,uf,"f"))||void 0===r?void 0:r.backgroundColor)?(a(this,of,"f").setBlur(a(this,uf,"f").blur),P+=1):a(this,of,"f").clearBlur(),void 0!==(null===(n=a(this,uf,"f"))||void 0===n?void 0:n.background)?(a(this,of,"f").setBackground(a(this,uf,"f").background),P+=1):void 0!==(null===(i=a(this,uf,"f"))||void 0===i?void 0:i.backgroundColor)?(a(this,of,"f").setBackgroundColor(null===(s=a(this,uf,"f"))||void 0===s?void 0:s.backgroundColor),a(this,of,"f").setBackground("color"),P+=1):a(this,of,"f").clearBackground(),(null===(o=a(this,uf,"f"))||void 0===o?void 0:o.beautification)?(a(this,of,"f").enableBeautification(),a(this,of,"f").setBeautificationLevel(a(this,uf,"f").beautification),P+=1):a(this,of,"f").disableBeautification(),(null===(d=a(this,uf,"f"))||void 0===d?void 0:d.lowLightEffect)?(a(this,of,"f").enableLowLightEffect(),a(this,of,"f").setLowLightEffectPower(a(this,uf,"f").lowLightEffect),P+=1):a(this,of,"f").disableLowLightEffect(),(null===(u=a(this,uf,"f"))||void 0===u?void 0:u.colorCorrector)?(a(this,of,"f").enableColorCorrector(),a(this,of,"f").setColorCorrectorPower(a(this,uf,"f").colorCorrector),P+=1):a(this,of,"f").disableColorCorrector(),(null===(l=a(this,uf,"f"))||void 0===l?void 0:l.smartZoom)?(a(this,of,"f").enableSmartZoom(),a(this,of,"f").setFaceArea(a(this,uf,"f").smartZoom),P+=1):a(this,of,"f").disableSmartZoom(),(null===(p=a(this,uf,"f"))||void 0===p?void 0:p.layout)?(a(this,of,"f").setLayout(a(this,uf,"f").layout),P+=1):a(this,of,"f").setLayout("center"),(null===(h=a(this,uf,"f"))||void 0===h?void 0:h.colorFilter)&&(null===(f=a(this,uf,"f"))||void 0===f?void 0:f.colorFilter.power)&&(null===(m=a(this,uf,"f"))||void 0===m?void 0:m.colorFilter.url)?(a(this,of,"f").setColorFilterConfig({lut:a(this,uf,"f").colorFilter.url,power:a(this,uf,"f").colorFilter.power}),a(this,of,"f").enableColorFilter(),P+=1):a(this,of,"f").disableColorFilter(),null===(g=a(this,uf,"f"))||void 0===g?void 0:g.lowerThird){const e=a(this,of,"f").createComponent({component:a(this,uf,"f").lowerThird.type,options:null!==(v=a(this,uf,"f").lowerThird.options)&&void 0!==v?v:{}});null===(_=null===(b=null===(y=a(this,of,"f").components)||void 0===y?void 0:y.lowerThird)||void 0===b?void 0:b.hideLowerThird)||void 0===_||_.call(b),a(this,of,"f").addComponent(e,"lowerThird"),a(this,of,"f").components.lowerThird.showLowerThird(),P+=1}else null===(S=null===(w=null===(E=a(this,of,"f").components)||void 0===E?void 0:E.lowerThird)||void 0===w?void 0:w.hideLowerThird)||void 0===S||S.call(w);(null===(C=a(this,uf,"f"))||void 0===C?void 0:C.sharpness)?(a(this,of,"f").setSharpnessEffectConfig(a(this,uf,"f").sharpness),P+=1):a(this,of,"f").disableSharpnessEffect(),P>2?a(this,of,"f").enableFrameSkipping():a(this,of,"f").disableFrameSkipping(),a(this,of,"f").run()}}of=new WeakMap,af=new WeakMap,cf=new WeakMap,df=new WeakMap,uf=new WeakMap,lf=new WeakMap,pf=new WeakMap,hf=new WeakMap,ff=new WeakMap,mf=new WeakMap,n([Kh(15e3,"EffectsSDKTrackProcessor.init"),s("design:type",Function),s("design:paramtypes",[]),s("design:returntype",Promise)],bf.prototype,"init",null),n([Kh(15e3),s("design:type",Function),s("design:paramtypes",[]),s("design:returntype",Promise)],bf.prototype,"awaitReady",null);const _f=new Set(["width","height","aspectRatio","frameRate","facingMode","resizeMode","displaySurface","logicalSurface","cursor"]),Ef=e=>e instanceof DOMException&&"OverconstrainedError"===e.name&&"constraint"in e&&"string"==typeof e.constraint,wf=(e,t)=>{const r=e.getSettings()[t];return void 0===r?"unknown":String(r)};class Sf extends Bt{constructor(e,t,{errorCode:r,actual:n}){const{constraint:i}=e,s=((e,t)=>_f.has(t)||void 0!==e.video&&!1!==e.video?"video":"audio")(t,i),o=((e,t,r)=>{const n="audio"===t?e.audio:e.video;if(!n||!0===n)return"unknown";const i=n[r];return void 0===i?"unknown":"object"==typeof i?JSON.stringify(i):String(i)})(t,s,i),a=n?`Requested: ${o}, Actual: ${n}`:`Requested: ${o}`;super(r,Object.assign(Object.assign(Object.assign(Object.assign({},Vt(e)),{constraint:i,requested:o}),n?{actual:n}:{}),{message:a})),this.constraint=i,this.requested=o,this.actual=n}}const Cf=e=>"rtx"!==e.mimeType;var Pf,Tf,Rf;class kf{constructor({track:e}){Pf.set(this,1e4),Tf.set(this,0),Rf.set(this,void 0),this.startCleanupTimer(),e.addEventListener("ended",(()=>{clearInterval(a(this,Rf,"f")),c(this,Rf,void 0,"f")}),{once:!0})}touchLastReceivedStatsTimestamp(){c(this,Tf,Date.now(),"f")}startCleanupTimer(){c(this,Rf,setInterval((()=>{a(this,Tf,"f")>0&&Date.now()-a(this,Tf,"f")>=a(this,Pf,"f")&&this.cleanupStats()}),a(this,Pf,"f")),"f")}}var Df,If,Af,Of,Mf,Nf,Lf,xf,Ff,jf,Uf,Vf,Bf,Wf,Hf,qf,zf,Gf,Yf,$f,Jf,Qf,Kf;Pf=new WeakMap,Tf=new WeakMap,Rf=new WeakMap;class Zf extends kf{constructor({track:e,statsHandler:t,widStatsAdapter:r,scoresCalculator:n,isStaticContent:i}){super({track:e}),Df.set(this,void 0),If.set(this,void 0),Af.set(this,void 0),Of.set(this,void 0),Mf.set(this,void 0),Nf.set(this,void 0),Lf.set(this,void 0),this.handleWebRTCStats(e,t),c(this,Nf,r,"f"),c(this,Mf,n,"f"),c(this,Lf,i,"f")}get videoWebRTCStats(){var e,t,r,n,i;return null!==(r=null===(t=null===(e=a(this,Df,"f"))||void 0===e?void 0:e.find((e=>e.outbound.active)))||void 0===t?void 0:t.outbound)&&void 0!==r?r:null===(i=null===(n=a(this,Df,"f"))||void 0===n?void 0:n[0])||void 0===i?void 0:i.outbound}get audioWebRTCStats(){var e;return null===(e=a(this,If,"f"))||void 0===e?void 0:e.outbound}get scores(){return{Qv:a(this,Af,"f"),Qa:a(this,Of,"f")}}handleWebRTCStats(e,t){e.addEventListener("ended",(()=>{t.removeOutboundVideoHandler(e.id),t.removeOutboundAudioHandler(e.id)}),{once:!0}),"video"!==e.kind?t.addOutboundAudioHandler(e.id,this.setAudioWebRTCStats.bind(this)):t.addOutboundVideoHandler(e.id,this.setVideoWebRTCStats.bind(this))}setVideoWebRTCStats(e){this.touchLastReceivedStatsTimestamp();const t=e.filter((e=>e.outbound.active)),r=[];t.forEach((e=>{var t;const n=null===(t=a(this,Df,"f"))||void 0===t?void 0:t.find((t=>t.outbound.ssrc===e.outbound.ssrc)),i=a(this,Nf,"f").adaptOutboundVideoStats({stats:e.outbound,remoteInboundStats:e.remoteInbound,prevStats:n,isStaticContent:a(this,Lf,"f")});r.push(a(this,Mf,"f").calculateVideoMOS(i))})),c(this,Af,r.length>0?Math.min(...r):void 0,"f"),c(this,Df,e,"f")}setAudioWebRTCStats(e){var t,r;this.touchLastReceivedStatsTimestamp();const n=a(this,If,"f")?{outbound:a(this,If,"f").outbound,remoteInbound:a(this,If,"f").remoteInbound}:void 0,i=a(this,Nf,"f").adaptOutboundAudioStats({stats:e.outbound,remoteInboundStats:e.remoteInbound,fec:null===(t=Ar("qosOutboundFec"))||void 0===t||t,dtx:null===(r=Ar("qosOutboundDtx"))||void 0===r||r,prevStats:n});c(this,Of,a(this,Mf,"f").calculateAudioMOS(i),"f"),c(this,If,e,"f")}cleanupStats(){c(this,Df,void 0,"f"),c(this,If,void 0,"f"),c(this,Af,void 0,"f"),c(this,Of,void 0,"f")}}Df=new WeakMap,If=new WeakMap,Af=new WeakMap,Of=new WeakMap,Mf=new WeakMap,Nf=new WeakMap,Lf=new WeakMap;class Xf{constructor(e){xf.set(this,void 0),Ff.set(this,void 0),this.encoderConfig={},this.label=exports.TrackLabel.Unknown,jf.set(this,void 0),Uf.set(this,void 0),Vf.set(this,void 0),Bf.set(this,void 0),Wf.set(this,void 0),Hf.set(this,void 0),qf.set(this,void 0),zf.set(this,void 0),Gf.set(this,!0),Yf.set(this,void 0),$f.set(this,void 0),Jf.set(this,void 0),Qf.set(this,void 0),Kf.set(this,void 0);const{mediaStreamTrack:t,internalEventEmitter:r,constraints:n,mediaStreamTrackManager:i,media:s,myPeer:o,network:a,producerCloseManager:d,mutex:u,loggerFactory:l,loggerNamespace:p,statsHandler:h,widStatsAdapter:f,scoresCalculator:m}=e;c(this,xf,t,"f"),c(this,Wf,r,"f"),c(this,Hf,n,"f"),c(this,qf,i,"f"),c(this,zf,new Ft,"f"),this.logger=l(p),c(this,Yf,u,"f"),c(this,Uf,s,"f"),c(this,jf,o,"f"),c(this,Vf,a,"f"),c(this,Bf,d,"f"),c(this,Jf,h,"f"),c(this,Qf,f,"f"),c(this,Kf,m,"f"),c(this,$f,new Zf({track:t,statsHandler:h,widStatsAdapter:f,scoresCalculator:m}),"f")}get videoWebRTCStats(){return a(this,$f,"f").videoWebRTCStats}get audioWebRTCStats(){return a(this,$f,"f").audioWebRTCStats}get connectionScores(){return a(this,$f,"f").scores}get logCtx(){return{label:this.getLabel(),id:this.id,kind:this.kind,producerId:this.producerId,paused:this.isPaused,published:this.isPublished}}get observer(){return a(this,zf,"f")}get mediaStreamTrack(){return a(this,xf,"f")}get originalTrack(){return a(this,Ff,"f")}get id(){return this.mediaStreamTrack.id}get kind(){return this.mediaStreamTrack.kind}get producerId(){var e;return null===(e=this.producer)||void 0===e?void 0:e.id}get isPublished(){return!!this.producer&&!this.producer.closed}get isPaused(){var e,t;return null!==(t=null===(e=this.producer)||void 0===e?void 0:e.paused)&&void 0!==t&&t}get internalEventEmitter(){return a(this,Wf,"f")}getLabel(){return this.label}setLabel(e){if("string"!=typeof(t=e)||!Object.values(exports.TrackLabel).includes(t))throw this.logger.error("setLabel()",{message:"Invalid track label",label:e}),new Bt("invalid_track_label",new Error(`Invalid track label: ${e}`));var t;this.label=e}setEncoderConfig(e){this.encoderConfig=e}getEncoderConfig(){return this.encoderConfig}setProducer(e){this.producer=e}setStopTrackOnPause(e){this.isPublished||c(this,Gf,e,"f")}getProducer(){return this.producer}setOriginalTrack(){c(this,Ff,this.mediaStreamTrack,"f")}closeProducer(){return o(this,arguments,void 0,(function*(e=!0){const t=yield a(this,Yf,"f").lock(zn.CloseProducer);if(!this.producer)return void t();const{producerId:r}=this;r&&(yield a(this,Bf,"f").close(this.getLabel(),r)),this.producer.close(),this.producer=void 0,e&&this.stopMediaStreamTrack(),t()}))}setPriority(e){return o(this,void 0,void 0,(function*(){this.producer?(yield this.producer.setRtpEncodingParameters({priority:e}),this.logger.debug("setPriority()",{label:this.getLabel(),priority:e})):this.logger.debug("setPriority()",{priority:e,reason:"Not published yet"})}))}stopMediaStreamTrack(){this.mediaStreamTrack.stop(),this.mediaStreamTrack.dispatchEvent(new Event("ended")),this.stopOriginalTrack()}stopOriginalTrack(){a(this,Ff,"f")&&(a(this,Ff,"f").stop(),c(this,Ff,void 0,"f"))}buildProduceEncodings(){return[]}produce(e){return o(this,arguments,void 0,(function*({codecOptions:e,preferredCodec:t,transformParams:r,keyFrameRequestDelay:n}){var i,s,o,c;if(!a(this,jf,"f").canPublish)throw this.logger.error("produce()",{message:"Not enough access to produce"}),new Bt("not_enough_access",new Error("Not enough access to produce"));if(!a(this,Vf,"f").sendTransport)throw this.logger.error("produce()",{message:"Send transport not initialized"}),new Bt("send_transport_not_initialized",new Error("Send transport not initialized"));if(this.producer)throw new Bt("track_already_produced",new Error("Track already produced"));const d=this.getLabel();if([exports.TrackLabel.CameraPreview,exports.TrackLabel.MicrophonePreview].includes(d))throw this.logger.error("produce()",{message:"Cannot produce a preview track",label:d,track:this.logCtx}),new Bt("track_publish_failed",new Error("Cannot produce preview track"));try{yield a(this,Bf,"f").ensureNoPending(this.getLabel()),yield a(this,Vf,"f").ping();const{rtpCapabilities:{codecs:d}}=a(this,Uf,"f").mediasoupDevice,u=null==d?void 0:d.find((e=>e.mimeType.toLowerCase()===`${this.kind}/${t}`)),l=0,p=this.buildProduceEncodings(),h=this.prepareProducerEncodings({codec:u,encodings:p,maxSpatialLayer:p.length-1}),f={trackTransformParams:r,peerId:String(a(this,jf,"f").id),label:this.getLabel(),maxSpatialLayer:l,encodings:h,codecOptions:e,preferredCodec:t,codec:u,keyFrameRequestDelay:n},m=yield a(this,Vf,"f").sendTransport.produce({track:this.mediaStreamTrack,encodings:h.length?h:void 0,codecOptions:e,codec:u,stopTracks:!1,disableTrackOnPause:!0,zeroRtpOnPause:!0,appData:f});return this.setProducer(m),(null===(s=null===(i=this.producer)||void 0===i?void 0:i.track)||void 0===s?void 0:s.id)!==a(this,xf,"f").id&&(this.logger.info("Producer initialized with old track, updating",{oldTrackId:null===(c=null===(o=this.producer)||void 0===o?void 0:o.track)||void 0===c?void 0:c.id,newTrackId:a(this,xf,"f").id}),yield this.replaceTrack(a(this,xf,"f"))),this.logger.debug("produce()",{track:this.logCtx,encodings:p,codecOptions:e}),m}catch(e){throw(Qn(e)?this.logger.debug.bind(this.logger):this.logger.error.bind(this.logger))("produce()",{error:Vt(e),track:this.logCtx}),new Bt("track_publish_failed",e)}}))}setNetworkProducerMaxSpatialLayer(e,t){return o(this,void 0,void 0,(function*(){yield a(this,Vf,"f").setProducerMaxSpatialLayer(e,t)}))}publish(){return o(this,void 0,void 0,(function*(){yield this.produce({}),this.internalEventEmitter.emit(gn,this)}))}unpublish(){return o(this,arguments,void 0,(function*(e=!0){if(this.producer)try{e&&this.stopMediaStreamTrack(),this.internalEventEmitter.emit(vn,this),this.producer&&(yield this.closeProducer()),this.logger.debug("unpublish()",{track:this.logCtx})}catch(e){this.logger.error("unpublish()",{error:e})}}))}pauseRemoteProducer(e){return o(this,void 0,void 0,(function*(){yield a(this,Vf,"f").pauseRemoteProducer(e)}))}resumeRemoteProducer(e){return o(this,void 0,void 0,(function*(){yield a(this,Vf,"f").resumeRemoteProducer(e)}))}mute(e){return o(this,void 0,void 0,(function*(){const t=yield a(this,Yf,"f").lock(zn.Mute);if(!this.producer)return this.logger.debug("pause()",{message:"Track is not published",track:this.logCtx}),void t();try{if(this.producer.pause(),this.logger.debug("pause()",{track:this.logCtx}),a(this,Gf,"f"))return null==e||e(),a(this,xf,"f").stop(),this.stopOriginalTrack(),this.internalEventEmitter.emit(_n,this),void(yield this.pauseRemoteProducer(this.producer.id));yield this.pauseRemoteProducer(this.producer.id),this.internalEventEmitter.emit(yn,this)}catch(e){throw(Qn(e)?this.logger.debug.bind(this.logger):this.logger.error.bind(this.logger))("pause()",{error:Vt(e),track:this.logCtx}),yield a(this,Uf,"f").deleteTrack(this),this.internalEventEmitter.emit(wn,this),new Bt("track_pause_failed",e)}finally{t()}}))}resume(){return o(this,void 0,void 0,(function*(){const e=yield a(this,Yf,"f").lock(zn.Resume);if(!this.producer)return this.logger.debug("resume()",{message:"Track is not published",track:this.logCtx}),void e();try{if(this.logger.debug("resume()",{track:this.logCtx}),a(this,Gf,"f"))return yield this.reopenMediaStreamTrack(),yield this.resumeProducer(),void this.internalEventEmitter.emit(En,this);yield this.resumeProducer(),this.internalEventEmitter.emit(bn,this)}catch(e){if(Ef(e)){const t=new Sf(e,a(this,Hf,"f"),{errorCode:"track_resume_overconstrained",actual:wf(a(this,xf,"f"),e.constraint)});throw this.logger.error("resume()",{error:Vt(t),track:this.logCtx}),t}throw(Qn(e)?this.logger.debug.bind(this.logger):this.logger.error.bind(this.logger))("resume()",{error:Vt(e),track:this.logCtx}),new Bt("track_resume_failed",e)}finally{e()}}))}getInfo(){return o(this,void 0,void 0,(function*(){const{width:e,height:t,frameRate:r,aspectRatio:n}=a(this,xf,"f").getSettings();return{trackId:a(this,xf,"f").id,readyState:a(this,xf,"f").readyState,kind:this.kind,label:this.label,width:e,height:t,frameRate:r,aspectRatio:n,paused:this.isPaused,trackOutboundStats:yield this.getStats()}}))}getStats(){return o(this,void 0,void 0,(function*(){var e,t,r,n,i;try{return{producerId:null===(e=this.producer)||void 0===e?void 0:e.id,codec:null===(t=this.producer)||void 0===t?void 0:t.rtpParameters.codecs.find((e=>Cf(e))),dtlsState:null===(i=null===(n=null===(r=this.producer)||void 0===r?void 0:r.rtpSender)||void 0===n?void 0:n.transport)||void 0===i?void 0:i.state,rtcStats:yield this.getOutboundRTPStreamStats()}}catch(e){return void this.logger.debug("getStats()",{error:e})}}))}replaceTrack(e){return o(this,void 0,void 0,(function*(){var t;try{c(this,xf,e,"f"),this.internalEventEmitter.emit(En,this),this.observer.safeEmit("track-changed",{track:e}),yield null===(t=this.producer)||void 0===t?void 0:t.replaceTrack({track:e}),c(this,$f,new Zf({track:e,statsHandler:a(this,Jf,"f"),widStatsAdapter:a(this,Qf,"f"),scoresCalculator:a(this,Kf,"f")}),"f")}catch(e){(e instanceof Error&&"InvalidStateError"===e.name?this.logger.debug.bind(this.logger):this.logger.error.bind(this.logger))("replaceTrack()",{error:e})}}))}resumeProducer(){return o(this,void 0,void 0,(function*(){this.producer?(yield this.resumeRemoteProducer(this.producer.id),this.producer.resume()):this.logger.debug("resumeProducer()",{message:"Track not produced yet",track:this.logCtx})}))}reopenMediaStreamTrack(){return o(this,void 0,void 0,(function*(){var e;const t=yield a(this,qf,"f").createMediaStreamTrack({label:this.label,constraints:a(this,Hf,"f")});c(this,xf,t,"f"),yield null===(e=this.producer)||void 0===e?void 0:e.replaceTrack({track:t})}))}prepareProducerEncodings(e){const{encodings:t,codec:r,maxSpatialLayer:n}=e;return t.length?t.length>1&&r&&di(r.mimeType)?[t[n]||t[0]]:t:[]}getOutboundRTPStreamStats(){return o(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>{const r=(...n)=>o(this,[...n],void 0,(function*(n=0){if(!this.producer)throw new Error("Producer is missed");try{const i=yield this.producer.getStats(),s=Array.from(i.values()).find((e=>"outbound-rtp"===e.type));if(!s&&n<5)return void setTimeout((()=>o(this,void 0,void 0,(function*(){return yield r(n+1)}))),150);n>=5&&!s&&t(new Error("OutboundRTPStreamStat not exist")),e(s)}catch(e){t(new Error("Can not get RTCStatsReport")),this.logger.debug("getOutboundRTPStreamStats()",{error:e})}}));r().catch((e=>{this.logger.debug("Error executing getRTCStatsReport",{case:"DefaultBaseTrack",error:Vt(e)})}))}))}))}}var em,tm,rm,nm;xf=new WeakMap,Ff=new WeakMap,jf=new WeakMap,Uf=new WeakMap,Vf=new WeakMap,Bf=new WeakMap,Wf=new WeakMap,Hf=new WeakMap,qf=new WeakMap,zf=new WeakMap,Gf=new WeakMap,Yf=new WeakMap,$f=new WeakMap,Jf=new WeakMap,Qf=new WeakMap,Kf=new WeakMap;class im extends Xf{constructor(e){super(e),this.transformParams={},em.set(this,void 0),tm.set(this,void 0),rm.set(this,void 0),nm.set(this,!1),c(this,tm,e,"f"),c(this,rm,e.clientEventEmitter,"f")}get logCtx(){return{label:this.getLabel(),id:this.id,kind:this.kind,producerId:this.producerId,paused:this.isPaused,published:this.isPublished,isEffectsProcessing:this.isEffectsProcessing}}get isEffectsProcessing(){return Boolean(a(this,em,"f"))}getEncoderConfig(){return this.encoderConfig}getCodecOptions(){var e;return{videoGoogleStartBitrate:null!==(e=this.getEncoderConfig().videoGoogleStartBitrate)&&void 0!==e?e:1e3}}getPreferredCodec(){const{preferredCodec:e}=this.getEncoderConfig();return e||(this.getLabel()===exports.TrackLabel.ScreenVideo?"vp8":"h264")}getEncodings(){var e;return null!==(e=this.getEncoderConfig().encodings)&&void 0!==e?e:Nh}buildProduceEncodings(){return this.getEncodings()}setTransformParams(e){this.transformParams=e}setMaxSpatialLayer(e){return o(this,void 0,void 0,(function*(){const t=this.getProducer();t?(yield t.setMaxSpatialLayer(e),this.logger.debug("setMaxSpatialLayer()",{label:this.getLabel(),spatialLayer:e})):this.logger.debug("setMaxSpatialLayer()",{message:"Not produced yet"})}))}getMaxSpatialLayer(){const e=this.getProducer();if(e)return e.maxSpatialLayer;this.logger.debug("getMaxSpatialLayer()",{message:"Not produced yet"})}enableEffects(){return o(this,void 0,void 0,(function*(){if(!a(this,nm,"f")){c(this,nm,!0,"f");try{if(a(this,em,"f"))return void this.logger.debug("enableEffects()",{description:"Track is already processed"});if("ended"===this.mediaStreamTrack.readyState)return void this.logger.debug("Track already ended",{case:"enableEffects"});if(!a(this,tm,"f").media.effectsSDKInitialized)return void this.logger.debug("Effects SDK not initialized",{case:"enableEffects"});const e=Date.now();yield this.performEnableEffects();const t=Date.now();this.logger.info("enableEffects() time",{time:(t-e)/1e3}),this.logger.info("enableEffects()",{track:this.logCtx}),a(this,rm,"f").emit(ln)}catch(e){this.logger.warn("enableEffects()",{track:this.logCtx,error:Vt(e)}),a(this,rm,"f").emit(hn,{cause:"Failed to enable video effects",operation:"enable",error:e}),this.disableEffects().catch((e=>{this.logger.warn("Failed to this.disableEffects() in catch{}",{track:this.logCtx,error:Vt(e)})}))}finally{c(this,nm,!1,"f")}}}))}disableEffects(){return o(this,arguments,void 0,(function*(e=!0){if(a(this,em,"f"))try{yield this.performDisableEffects(e),this.logger.info("disableEffects()",{track:this.logCtx}),a(this,rm,"f").emit(pn)}catch(e){this.logger.warn("disableEffects()",{track:this.logCtx,error:e}),a(this,rm,"f").emit(hn,{cause:"Failed to disable video effects",operation:"disable",error:e})}else this.logger.debug("disableEffects()",{description:"Track is not processed"})}))}publish(){return o(this,arguments,void 0,(function*(e={}){var t;const r=yield this.produce({preferredCodec:this.getPreferredCodec(),transformParams:this.transformParams,codecOptions:this.getCodecOptions(),keyFrameRequestDelay:null!==(t=e.keyFrameRequestDelay)&&void 0!==t?t:0});yield this.setupVideoProducer(r),this.internalEventEmitter.emit(gn,this)}))}setupVideoProducer(e){return o(this,void 0,void 0,(function*(){const t=this.buildProduceEncodings(),r=e.rtpSender,n=()=>/Safari/i.test(navigator.userAgent);if(t.length&&r&&n()){const e=r.getParameters();t.forEach((({maxBitrate:t,scaleResolutionDownBy:r},n)=>{e.encodings[n]&&(e.encodings[n].maxBitrate=t,e.encodings[n].scaleResolutionDownBy=r)})),yield r.setParameters(e)}if(t.length&&r&&di(this.getPreferredCodec())&&!n()){const e=t.length>1?[t[0]||t[0]]:t;yield r.setParameters(Object.assign(Object.assign({},r.getParameters()),{encodings:e}))}else yield e.setMaxSpatialLayer(0);yield this.setNetworkProducerMaxSpatialLayer(e.id,0)}))}adjustEncodingPresetToCurrentMaxSpatialLayer(e){return o(this,void 0,void 0,(function*(){var t;if(!di(this.getPreferredCodec()))return;const{rtpSender:r}=null!==(t=this.getProducer())&&void 0!==t?t:{};if(!r)return void this.logger.debug("No rtpSender found in producer to change encodings",{maxSpatialLayer:e,trackId:this.id,producerId:this.producerId});const{encodings:n=[]}=this.getEncoderConfig(),i=n[e];if(!i)return void this.logger.warn("Skipping RTPSender params update. No target encoding found",{initialEncodings:n});this.logger.debug("Adjusting encoding parameters to max spatial layer",{targetEncoding:i,maxSpatialLayer:e});const s=r.getParameters();yield r.setParameters(Object.assign(Object.assign({},s),{encodings:[Object.assign(Object.assign({},s.encodings[0]),i)]}))}))}applyEffects(e){return o(this,void 0,void 0,(function*(){var t;try{!this.isEffectsProcessing&&Object.keys(e).length>0&&(yield this.enableEffects()),null===(t=a(this,em,"f"))||void 0===t||t.updateEffects(e)}catch(e){a(this,rm,"f").emit(hn,{cause:"Failed to apply video effects",operation:"apply",error:e})}}))}resetEffects(){var e;null===(e=a(this,em,"f"))||void 0===e||e.updateEffects({})}setOnLoadModels(e){var t;null===(t=a(this,em,"f"))||void 0===t||t.setOnLoadModels(e)}get modelsLoadProgress(){var e,t;return null!==(t=null===(e=a(this,em,"f"))||void 0===e?void 0:e.modelsLoadProgress)&&void 0!==t?t:0}pause(){return o(this,void 0,void 0,(function*(){yield this.mute((()=>{var e;a(this,em,"f")&&(null===(e=a(this,em,"f"))||void 0===e||e.stopProcessing(),c(this,em,void 0,"f"))}))}))}performEnableEffects(){return o(this,void 0,void 0,(function*(){const{media:e}=a(this,tm,"f");c(this,em,yield e.createEffectsSDKTrackProcessor(this.getLabel()),"f"),a(this,em,"f").setOnRuntimeError((e=>{a(this,rm,"f").emit(hn,{cause:`Video effects runtime error: ${e.message}`,operation:"runtime",error:e})})),this.setOriginalTrack();const t=a(this,em,"f").processTrack(this.mediaStreamTrack);yield this.replaceTrack(t)}))}performDisableEffects(e){return o(this,void 0,void 0,(function*(){var t;null===(t=a(this,em,"f"))||void 0===t||t.stopProcessing(),c(this,em,void 0,"f"),e&&this.originalTrack&&(yield this.replaceTrack(this.originalTrack))}))}}var sm,om;em=new WeakMap,tm=new WeakMap,rm=new WeakMap,nm=new WeakMap,n([Kh(1e4,"DefaultVideoTrack.enableEffects"),s("design:type",Function),s("design:paramtypes",[]),s("design:returntype",Promise)],im.prototype,"performEnableEffects",null),n([Kh(1e4,"DefaultVideoTrack.disableEffects"),s("design:type",Function),s("design:paramtypes",[Boolean]),s("design:returntype",Promise)],im.prototype,"performDisableEffects",null);let am=om=class{constructor(e){sm.set(this,void 0),c(this,sm,e("MediaStreamTrackManager"),"f")}createMediaStreamTrack(e){return o(this,arguments,void 0,(function*({label:e,constraints:t}){if(om.isDisplayMedia(e)){const[e]=yield this.createDisplayMediaTracks(t);return e}const[r]=yield this.createUserMediaTracks(t);return r}))}static isDisplayMedia(e){return[exports.TrackLabel.ScreenVideo,exports.TrackLabel.ScreenAudio].includes(e)}createUserMediaTracks(e){return o(this,void 0,void 0,(function*(){try{const t=yield navigator.mediaDevices.getUserMedia(e);return a(this,sm,"f").debug("createUserMediaTracks() stream created",{streamId:t.id}),t.getTracks()}catch(t){if(Ef(t)){throw new Sf(t,e,{errorCode:"create_track_overconstrained"})}throw t}}))}createDisplayMediaTracks(e){return o(this,void 0,void 0,(function*(){try{const t=yield navigator.mediaDevices.getDisplayMedia(e);return a(this,sm,"f").debug("getDisplayMediaTracks() stream created",{streamId:t.id}),t.getTracks()}catch(t){if(Ef(t)){throw new Sf(t,e,{errorCode:"create_screen_track_overconstrained"})}throw t}}))}};sm=new WeakMap,am=om=n([ot(),i(0,ct(fi.LoggerFactory)),s("design:paramtypes",[Function])],am);var cm,dm,um,lm,pm,hm,fm,mm=am;let gm=class{constructor(e,t,r,n,i,s,o,a,d){this.config=e,this.loggerFactory=t,this.audioTrackFactory=r,this.clientEventEmitter=n,this.integrationsService=i,this.processorsCache=s,this.videoTrackFactory=o,this.mediaStreamTrackManager=a,this.signalingApiClient=d,this.isDeviceLoaded=!1,this.tracks=new Map,cm.set(this,void 0),dm.set(this,null),um.set(this,!1),lm.set(this,new Map),pm.set(this,!1),hm.set(this,!1),fm.set(this,void 0);const u=this.config.get("effectsSDKParams");c(this,fm,this.config.get("denoiser"),"f"),c(this,cm,this.loggerFactory("Media"),"f"),c(this,dm,null!=u?u:null,"f")}get mediasoupDevice(){var e;return null!==(e=this.device)&&void 0!==e||(this.device=this.createDevice()),this.device}get effectsSDKInitialized(){return a(this,um,"f")}get effectsSDKParams(){return a(this,dm,"f")}getTrackByLabel(e){return Array.from(this.tracks.values()).find((t=>t.getLabel()===e))}loadDevice(e){return o(this,void 0,void 0,(function*(){this.isDeviceLoaded||(yield this.mediasoupDevice.load({routerRtpCapabilities:e}),this.isDeviceLoaded=!0)}))}getTrackCodec(e){const{rtpCapabilities:t,rtpCapabilities:{codecs:r}}=this.mediasoupDevice;if(r)return r.find((t=>t.mimeType.toLowerCase()===`${e.kind}/${e.getPreferredCodec()}`));a(this,cm,"f").error("getTrackCodec()",{label:e.getLabel,rtpCapabilities:t})}createTracks({constraints:e,mediaStreamTracks:t}){return t.map((t=>{const r={mediaStreamTrack:t,constraints:e};let n;return n="audio"===t.kind?this.audioTrackFactory(Object.assign(Object.assign({},r),{loggerNamespace:"AudioTrack"})):this.videoTrackFactory(Object.assign(Object.assign({},r),{loggerNamespace:"VideoTrack"})),a(this,cm,"f").debug("createTrack() track created",{trackId:n.id,kind:n.kind}),n}))}createUserMediaTracks(e){return o(this,void 0,void 0,(function*(){const t=yield this.mediaStreamTrackManager.createUserMediaTracks(e);return this.createTracks({constraints:e,mediaStreamTracks:t})}))}createDisplayMediaTracks(e){return o(this,void 0,void 0,(function*(){const t=yield this.mediaStreamTrackManager.createDisplayMediaTracks(e);return this.createTracks({constraints:e,mediaStreamTracks:t})}))}createCustomMediaTrack(e,t){return this.createTracks({constraints:t,mediaStreamTracks:[e]})[0]}deleteTrack(e){return o(this,void 0,void 0,(function*(){if(!this.tracks.has(e.id))return;const t={trackId:e.id,label:e.getLabel(),producerId:e.producerId};try{"disableNoiseSuppression"in e&&(yield e.disableNoiseSuppression()),"disableEffects"in e&&(yield e.disableEffects(!1))}catch(e){a(this,cm,"f").debug("deleteTrack() disable effects error",Object.assign({error:e},t))}try{this.tracks.delete(e.id),e.stopMediaStreamTrack(),yield e.closeProducer()}catch(e){(e instanceof Yn?a(this,cm,"f").debug.bind(a(this,cm,"f")):a(this,cm,"f").error.bind(a(this,cm,"f")))("deleteTrack()",{error:e})}finally{a(this,cm,"f").debug("deleteTrack()",t)}}))}getAllTracks(){return Array.from(this.tracks.values())}publishedTracks(){return this.getAllTracks().filter((e=>e.isPublished))}clearTracks(){try{this.getAllTracks().forEach((e=>e.stopMediaStreamTrack()))}catch(e){a(this,cm,"f").debug("clearTracks() error",{error:e})}finally{this.tracks.clear()}}unpublishTracks(){return o(this,void 0,void 0,(function*(){try{yield Promise.all(this.publishedTracks().map((e=>o(this,void 0,void 0,(function*(){return yield e.unpublish(!1)})))))}catch(e){(Qn(e)?a(this,cm,"f").debug.bind(a(this,cm,"f")):a(this,cm,"f").warn.bind(a(this,cm,"f")))("unpublishTracks()",{error:e})}}))}setTrack(e){this.tracks.set(e.id,e)}initEffectsSDK(){return o(this,void 0,void 0,(function*(){if(a(this,um,"f"))return!0;if(!a(this,dm,"f"))throw a(this,cm,"f").error("Effects SDK config params not provided",{case:"initEffectsSDK"}),new Bt("effects_sdk_config_missing",new Error("Effects SDK config not provided"));const e=(e,t)=>o(this,void 0,void 0,(function*(){if(!window.tsvb)return a(this,cm,"f").info("Effects SDK not loaded, skipping initialization",{case:"initEffectsSDK"}),void e(!1);a(this,cm,"f").debug("Effects SDK initializing",{case:"initEffectsSDK"});try{a(this,lm,"f").set(exports.TrackLabel.Camera,yield this.createEffectsSDKTrackProcessor(exports.TrackLabel.Camera)),a(this,lm,"f").set(exports.TrackLabel.CameraPreview,yield this.createEffectsSDKTrackProcessor(exports.TrackLabel.CameraPreview)),c(this,um,!0,"f"),a(this,cm,"f").info("Effects SDK initialized",{case:"initEffectsSDK"}),e(!0)}catch(e){a(this,cm,"f").error("Failed to initialize Effects SDK",{error:e,case:"initEffectsSDK"}),t(e)}}));return yield new Promise(((t,r)=>{if(!window.tsvb)return a(this,cm,"f").debug("Effects SDK tsvb-web.js is not ready, waiting",{case:"initEffectsSDK"}),void window.addEventListener("load",(()=>o(this,void 0,void 0,(function*(){return yield e(t,r)}))));e(t,r).catch((e=>{a(this,cm,"f").error("Failed to execute init() in initEffectsSDK",{error:Vt(e)})}))}))}))}initDenoiser(e,t){return o(this,void 0,void 0,(function*(){if(!a(this,pm,"f"))try{c(this,pm,!0,"f"),this.clientEventEmitter.emit(sn,!0);try{yield this.integrationsService.audio.waitForInitialization}catch(e){"asdk"===a(this,fm,"f")&&(c(this,hm,!0,"f"),c(this,fm,"rnnoise","f"),this.config.set("denoiser",a(this,fm,"f")),a(this,cm,"f").debug("Set config to rnnoise denoiser",{case:"Denoiser",error:Vt(e),type:this.config.get("denoiser")}),this.clientEventEmitter.emit(dn),this.integrationsService.init(),yield this.integrationsService.audio.waitForInitialization)}a(this,cm,"f").debug("Denoiser initialized, activating",{case:"Denoiser",type:this.integrationsService.audio.type,trackLabel:e.getLabel()});const r=e,n=this.processorsCache.get(a(this,fm,"f"),exports.TrackLabel.Microphone);if(!n)return void a(this,cm,"f").error("No cached trackProcessor found",{case:"Denoiser",trackLabel:e.getLabel(),type:this.integrationsService.audio.type});"asdk"===n.type&&n.setOnError(((r,n)=>{this.clientEventEmitter.emit(sn,!0),this.fallbackToRNoise(e,{reason:r,options:t,error:n}).catch((t=>{a(this,cm,"f").error("Failed to fallback to RNNoise through onError",{case:"Denoiser",type:a(this,fm,"f"),error:Vt(t),label:e.getLabel()})})).then((()=>{this.clientEventEmitter.emit(sn,!1)})).catch((()=>{}))})),r.setTrackProcessor(n),a(this,cm,"f").debug("Denoiser trackProcessor set, check if activation is needed",{case:"Denoiser",type:a(this,fm,"f"),shouldEnableDenoiser:null==t?void 0:t.noiseSuppression,trackLabel:e.getLabel()}),(null==t?void 0:t.noiseSuppression)&&(yield e.enableNoiseSuppression())}catch(r){if(a(this,cm,"f").warn("Failed to start noise suppression, featured original track",{case:"Denoiser",type:a(this,fm,"f"),error:Vt(r),label:e.getLabel()}),"asdk"===a(this,fm,"f"))try{a(this,cm,"f").warn("Fallback to RNNoise",{error:Vt(r)}),yield this.fallbackToRNoise(e,{options:t,reason:"ASDK init error",error:r})}catch(t){a(this,cm,"f").error("Failed to fallback to RNNoise through catch",{case:"Denoiser",type:a(this,fm,"f"),error:Vt(t),label:e.getLabel()})}}finally{this.clientEventEmitter.emit(sn,!1),c(this,pm,!1,"f")}}))}fallbackToRNoise(e,t){return o(this,void 0,void 0,(function*(){var r;if(a(this,hm,"f"))return;if(c(this,hm,!0,"f"),"rnnoise"===a(this,fm,"f"))return;this.clientEventEmitter.emit(dn),a(this,cm,"f").warn("Fallback to RNNoise",{reason:null==t?void 0:t.reason,error:Vt(null==t?void 0:t.error),case:"Denoiser"});const n=e;yield n.disableNoiseSuppression(),n.unsetTrackProcessor(),c(this,fm,"rnnoise","f"),this.config.set("denoiser",a(this,fm,"f")),a(this,cm,"f").debug("Set config to rnnoise denoiser",{case:"Denoiser",type:this.config.get("denoiser")}),this.integrationsService.init(),yield this.integrationsService.audio.waitForInitialization;const i=this.processorsCache.get(a(this,fm,"f"),exports.TrackLabel.Microphone);i?(n.setTrackProcessor(i),(null===(r=null==t?void 0:t.options)||void 0===r?void 0:r.noiseSuppression)&&(yield n.enableNoiseSuppression())):a(this,cm,"f").error("No cached trackProcessor found",{case:"Denoiser",trackLabel:e.getLabel(),type:this.integrationsService.audio.type})}))}createEffectsSDKTrackProcessor(e){return o(this,void 0,void 0,(function*(){var t,r,n;if(e){const t=a(this,lm,"f").get(e);if(t)return t}if(!a(this,dm,"f"))throw a(this,cm,"f").error("Effects SDK config params not provided",{case:"initEffectsSDK"}),new Bt("effects_sdk_config_missing",new Error("Effects SDK config not provided"));const i=new bf({loggerFactory:this.loggerFactory,customerId:null===(t=this.config.get("effectsSDKParams"))||void 0===t?void 0:t.customerId,sdk_url:null===(r=this.config.get("effectsSDKParams"))||void 0===r?void 0:r.sdk_url,api_url:null===(n=this.config.get("effectsSDKParams"))||void 0===n?void 0:n.api_url,config:this.config});return yield i.init(),a(this,cm,"f").info("Track effects processor initialized",{trackLabel:e}),i}))}handleProducerSetMaxSpatialLayer(e){return o(this,arguments,void 0,(function*({producerId:e,spatialLayer:t}){const r=this.getAllTracks().find((t=>{var r;return(null===(r=t.getProducer())||void 0===r?void 0:r.id)===e}));if(!r)return void a(this,cm,"f").warn("producerRequestMaxSpatialLayer()",{message:"Producer not found"});if(!(r instanceof im))return void a(this,cm,"f").warn("producerRequestMaxSpatialLayer()",{message:"Wrong producer kind"});const n=null!=t?t:jh,i=r.getMaxSpatialLayer();i!==n?(r.getEncodings().length>1&&(yield r.setMaxSpatialLayer(n)),yield this.signalingApiClient.producer.setProducerMaxSpatialLayer(e,{maxSpatialLayer:n}),yield r.adjustEncodingPresetToCurrentMaxSpatialLayer(n)):a(this,cm,"f").debug("producerRequestMaxSpatialLayer()",{message:"Skip set max spatial layer",requestedSpatialLayer:n,currentMaxSpatialLayer:i})}))}static getVideoTrackTransformParams(e){var t,r;const n=e.getSettings();return{width:null!==(t=n.width)&&void 0!==t?t:Fh.width,height:null!==(r=n.height)&&void 0!==r?r:Fh.height}}static getScreenVideoTrackParams(e){var t,r;return{videoTrackOptions:null!==(t=null==e?void 0:e.video)&&void 0!==t?t:{frameRate:{max:20},width:{max:Fh.width},height:{max:Fh.height}},encoderConfig:null!==(r=null==e?void 0:e.videoEncoderConfig)&&void 0!==r?r:{encodings:Lh}}}static getCameraVideoTrackParams(e){var t,r;return{videoTrackOptions:null!==(t=null==e?void 0:e.video)&&void 0!==t?t:{frameRate:{max:24},width:{max:Fh.width},height:{max:Fh.height}},encoderConfig:null!==(r=null==e?void 0:e.encoderConfig)&&void 0!==r?r:{encodings:Nh}}}createDevice(){const e=(e=>{const t=null!=e?e:null===navigator||void 0===navigator?void 0:navigator.userAgent;if(!t)return;const r=ti.getParser(t);return r.satisfies({"yandex browser":">=25"})&&"iOS"===r.getOSName()?void 0:r.satisfies({"yandex browser":">=23.7"})?"Chrome111":r.satisfies({"yandex browser":">=22"})?"Chrome74":r.satisfies({"Samsung Internet for Android":">=17"})?"Chrome111":void 0})();return a(this,cm,"f").debug("Creating a media device",{handlerName:null!=e?e:"not specified"}),new pd.Device({handlerName:e})}};cm=new WeakMap,dm=new WeakMap,um=new WeakMap,lm=new WeakMap,pm=new WeakMap,hm=new WeakMap,fm=new WeakMap,gm=n([ot(),i(0,ct(fi.Config)),i(1,ct(fi.LoggerFactory)),i(2,ct(fi.AudioTrackFactory)),i(3,ct(fi.ClientEventEmitter)),i(4,ct(fi.IntegrationsService)),i(5,ct(fi.ProcessorsCache)),i(6,ct(fi.VideoTrackFactory)),i(7,ct(fi.MediaStreamTrackManager)),i(8,ct(fi.SignalingApiClient)),s("design:paramtypes",[Et,Function,Function,Ft,Qh,Yh,Function,mm,ed])],gm);var vm=gm;const ym={[as.PRODUCER_KIND_VIDEO]:"video",[as.PRODUCER_KIND_AUDIO]:"audio"},bm={[ls.PEER_ROLE_HOST]:"host",[ls.PEER_ROLE_AUDIENCE]:"audience"},_m={[Zi.PRODUCER_LABEL_CAMERA]:exports.TrackLabel.Camera,[Zi.PRODUCER_LABEL_MICROPHONE]:exports.TrackLabel.Microphone,[Zi.PRODUCER_LABEL_SCREEN_VIDEO]:exports.TrackLabel.ScreenVideo,[Zi.PRODUCER_LABEL_SCREEN_AUDIO]:exports.TrackLabel.ScreenAudio,[Zi.PRODUCER_LABEL_CUSTOM_VIDEO]:exports.TrackLabel.CustomVideo,[Zi.PRODUCER_LABEL_CUSTOM_AUDIO]:exports.TrackLabel.CustomAudio,[Zi.PRODUCER_LABEL_UNKNOWN]:exports.TrackLabel.Unknown,[Zi.PRODUCER_LABEL_UNSPECIFIED]:exports.TrackLabel.Unknown},Em={[Ki.PEER_GROUP_MODERATOR]:"moderator",[Ki.PEER_GROUP_USER]:"user"},wm=e=>{const t=ym[e];if(!t)throw new Error(`Unknown producer kind: ${e}`);return t},Sm=e=>{const t=Em[e];if(!t)throw new Error(`Unknown peer group: ${e}`);return t},Cm=e=>{const t=_m[e];if(!t)throw new Error(`Unknown producer label: ${e}`);return t},Pm=e=>{const t=bm[e];if(!t)throw new Error(`Unknown peer role: ${e}`);return t},Tm=e=>({id:e.id,channelIds:e.channelIds,groups:e.groups.map(Sm),producePermissions:e.producePermissions.map(Cm),appId:e.appId,producers:e.producers.map(Rm),uid:e.uid,appData:e.appData,role:Pm(e.role),loginDate:e.loginDate}),Rm=e=>{var t;return{id:e.id,kind:wm(e.kind),label:Cm(e.label),peerId:e.peerId,paused:e.paused,encodings:e.encodings,maxSpatialLayer:null!==(t=e.maxSpatialLayer)&&void 0!==t?t:0}},km=e=>{switch(e){case"moderator":return Ki.PEER_GROUP_MODERATOR;case"user":return Ki.PEER_GROUP_USER;default:return Ki.PEER_GROUP_UNSPECIFIED}};var Dm;let Im=class{constructor(e,t,r,n,i,s,o){this.network=e,this.media=t,this.myPeer=r,this.eventsQueue=n,this.clientEventEmitter=i,this.peers=s,Dm.set(this,void 0),c(this,Dm,o("ChannelStateSyncEventHandler"),"f"),this.debouncedTriggerChannelStateEvent=ii(this.triggerChannelStateEvent.bind(this),3e3),this.watchNetworkState()}handleChannelStateEvent(e){return o(this,void 0,void 0,(function*(){this.network.peersLoaded?yield this.restoreState(e):this.loadChannelState(e),this.clientEventEmitter.emit(on)}))}watchNetworkState(){this.clientEventEmitter.on(rn,(()=>{this.debouncedTriggerChannelStateEvent()}))}triggerChannelStateEvent(){return o(this,void 0,void 0,(function*(){const e=()=>o(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>o(this,void 0,void 0,(function*(){const r=yield this.network.triggerChannelStateEvent("host"),n=setTimeout((()=>{this.eventsQueue.isMessageReceived(r)?(a(this,Dm,"f").info("Channel state event received",{case:"ChannelStateSynchronizer.triggerChannelStateEvent"}),e()):t(new Error("Channel state event not received"))}),5e3),i=()=>{clearTimeout(n),this.clientEventEmitter.off(tn,i),e()};this.clientEventEmitter.on(tn,i)}))))}));try{yield hi(e,{maxRetries:5,actionName:"triggerChannelStateEventWithRetry",logger:a(this,Dm,"f")})}catch(e){(Qn(e)?a(this,Dm,"f").debug.bind(a(this,Dm,"f")):a(this,Dm,"f").warn.bind(a(this,Dm,"f")))("Failed to trigger channel state event",{case:"ChannelStateSynchronizer.triggerChannelStateEvent",error:Vt(e)})}}))}loadChannelState(e){a(this,Dm,"f").info("Loading channel state",{case:"loadChannelState"});try{const t=this.peers.hosts().map((e=>e.shortData)),r=e.peers.filter((e=>e.role===ls.PEER_ROLE_HOST));this.setMissingPeers(t,r),this.restoreLocalPeersState(r),this.network.peersLoaded=!0}catch(e){a(this,Dm,"f").error("Failed to load channel state",{case:"loadState",error:Vt(e)})}}restoreState(e){return o(this,void 0,void 0,(function*(){const{peers:t}=e,r={missingPeers:[],removedPeers:[],missingProducers:[],removedProducers:[],fixedProducersState:[],fixedConsumersState:[],restoredAppDataPeers:[]};try{if(!this.network.isNetworkActive)return a(this,Dm,"f").info("Connection inactive, skipping restore local state",{case:"restoreLocalState"}),r;a(this,Dm,"f").info("Restoring local state",{case:"restoreLocalState"});const e=this.peers.hosts().map((e=>e.shortData)),n=t.filter((e=>e.role===ls.PEER_ROLE_HOST)),{removedProducers:i,fixedProducersState:s}=yield this.restoreRemoteProducersState(n);r.fixedProducersState.push(...s),r.removedProducers.push(...i),r.removedPeers.push(...this.removeUnnecessaryPeers(e,n)),r.missingPeers.push(...this.setMissingPeers(e,n));const o=this.restoreLocalPeersState(n);return r.missingProducers.push(...o.missingProducers),r.removedProducers.push(...o.removedProducers),r.restoredAppDataPeers.push(...o.restoredAppDataPeers),r.fixedProducersState.push(...o.fixedProducersState),r.fixedConsumersState.push(...o.fixedConsumersState),r}catch(e){return a(this,Dm,"f").info("Failed to restore local state",{case:"restoreLocalState",error:Vt(e)}),r}}))}restoreRemoteProducersState(e){return o(this,void 0,void 0,(function*(){const t={removedProducers:[],fixedProducersState:[]},r=this.myPeer.get(),n=e.find((e=>e.id===this.myPeer.id));if(!r||!n)return t;const i=new Map;this.media.getAllTracks().forEach((e=>{e.producerId&&i.set(e.producerId,e)}));const s=new Set(i.keys()),c=n.producers.filter((e=>!s.has(e.id)));yield Promise.all(c.map((e=>o(this,void 0,void 0,(function*(){yield this.network.closeRemoteProducer(e.id),r.producers.delete(e.id),t.removedProducers.push(e.id),a(this,Dm,"f").info("Unnecessary local producer closed",{case:"restoreLocalState",removedProducerId:e.id,removedProducerPeerId:e.peerId})})))));const d=[];for(const e of n.producers){const t=i.get(e.id);t&&(t.isPaused!==e.paused&&d.push({cp:e,localTrack:t}))}return yield Promise.all(d.map((e=>o(this,[e],void 0,(function*({cp:e,localTrack:r}){r.isPaused?yield this.network.pauseRemoteProducer(e.id):yield this.network.resumeRemoteProducer(e.id),t.fixedProducersState.push(e.id),e.paused=r.isPaused,a(this,Dm,"f").info("Remote producer state repaired",{case:"restoreLocalState",removedProducerId:e.id,removedProducerPeerId:e.peerId,paused:r.isPaused})}))))),t}))}removeUnnecessaryPeers(e,t){const r=[];return e.filter((e=>!t.find((t=>t.id===e.id)))).forEach((e=>{this.peers.remove(e.id).catch((e=>{a(this,Dm,"f").error("Failed to remove peer",{error:Vt(e)})})),r.push(e.id),a(this,Dm,"f").info("Unnecessary peer removed",{case:"restoreLocalState",removedPeerId:e.id})})),r}setMissingPeers(e,t){const r=[];return t.forEach((t=>{if(e.find((e=>e.id===t.id)))return;const n=this.peers.add(Tm(t));r.push(n.id),a(this,Dm,"f").info("Missing peer added to storage",{case:"restoreLocalState",peerId:t.id})})),r}restoreLocalPeersState(e){const t=new Map(e.map((e=>[e.id,e]))),r=this.peers.hosts(),n={removedProducers:[],missingProducers:[],restoredAppDataPeers:[],fixedConsumersState:[],fixedProducersState:[]};return r.forEach((e=>{const r=t.get(e.id);if(!r)return void a(this,Dm,"f").info("Found new local peer, skip restoring state",{case:"restoreLocalState",newPeerId:e.id});n.removedProducers.push(...this.removeUnnecessaryProducers(e,r));this.restoreAppData(e,r)&&n.restoredAppDataPeers.push(e.id);const{fixedProducersState:i,fixedConsumersState:s,missingProducers:o}=this.restoreTracksState(e,r);n.fixedProducersState.push(...i),n.fixedConsumersState.push(...s),n.missingProducers.push(...o)})),a(this,Dm,"f").info("Peers state restored",{case:"restoreLocalState"}),n}removeUnnecessaryProducers(e,t){const r=[];return e.getProducers().filter((e=>!t.producers.find((t=>t.id===e.id)))).forEach((t=>{e.observer.safeEmit(xn,t),r.push(t.id),a(this,Dm,"f").info("Unnecessary producer removed",{case:"restoreLocalState",removedProducerId:t.id,removedProducerPeerId:t.peerId})})),r}restoreTracksState(e,t){const r={missingProducers:[],fixedProducersState:[],fixedConsumersState:[]};return t.producers.forEach((t=>{var n;const i=e.producers.get(t.id);if(!i)return e.observer.safeEmit(Ln,Rm(t)),r.missingProducers.push(t.id),void a(this,Dm,"f").info("Missing producer added to storage",{case:"restoreLocalState",producerId:t.id,producerPeerId:t.peerId});const{paused:s}=t;if(i.paused!==s){i.setPaused(s);const n=i.paused?Pn:Tn;e.observer.safeEmit(n,{producerId:i.id,kind:i.kind,label:i.label,paused:i.paused}),r.fixedProducersState.push(t.id),a(this,Dm,"f").info("Producer state fixed",{case:"restoreLocalState",producerId:t.id,producerPeerId:t.peerId})}const o=e.tracks.get(i.label);if((null==o?void 0:o.consumerId)&&(null===(n=o.consumer)||void 0===n?void 0:n.paused)!==t.paused){const{consumerId:n}=o,s=i.paused?Vn:Bn;e.observer.safeEmit(s,n),r.fixedConsumersState.push(n),a(this,Dm,"f").info("Consumer state fixed",{case:"restoreLocalState",consumerId:n,consumerProducerId:t.id,consumerProducerPeerId:t.peerId})}})),r}restoreAppData(e,t){return!ni(e.appData,t.appData)&&(e.observer.emit(Br,t.appData),a(this,Dm,"f").info("Application data restored",{case:"restoreLocalState",peerId:e.id,appData:t.appData}),!0)}};Dm=new WeakMap,Im=n([ot(),i(0,ct(fi.Network)),i(1,ct(fi.Media)),i(2,ct(fi.MyPeer)),i(3,ct(fi.EventsQueue)),i(4,ct(fi.ClientEventEmitter)),i(5,ct(fi.Peers)),i(6,ct(fi.LoggerFactory)),s("design:paramtypes",[uo,vm,ro,eo,Ft,ho,Function])],Im);var Am,Om=Im;let Mm=class{constructor(e,t,r,n,i){this.peers=e,this.clientEventEmitter=t,this.channelStateSyncEventHandler=n,this.channelStateSynchronizer=i,Am.set(this,void 0),c(this,Am,r("ChannelEvents"),"f")}handleChannelEvent(e){return o(this,void 0,void 0,(function*(){switch(e.eventType){case Ss.CHANNEL_EVENT_TYPE_CHANNEL_STATE:yield this.handleChannelState(e);break;case Ss.CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT:this.handleChannelStateShort(e);break;case Ss.CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT:this.handleChannelManagementEvent(e);break;case Ss.CHANNEL_EVENT_TYPE_PEER_JOINED:this.handlePeerJoined(e);break;case Ss.CHANNEL_EVENT_TYPE_PEER_LEFT:this.handlePeerLeft(e);break;case Ss.CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED:this.handlePeerAppDataChanged(e);break;case Ss.CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED:this.handlePeerGroupsChanged(e);break;case Ss.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED:this.handleChannelActivityConfirmationAcquired();break;case Ss.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED:this.handleChannelActivityConfirmationExpired();break;case Ss.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED:this.handleChannelActivityConfirmationRequired(e);break;case Ss.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED:this.handleChannelProducePermissionsChanged(e);break;case Ss.CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED:this.handlePeerProducePermissionsChanged(e);break;case Ss.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED:this.handleChannelProducePermissionsDeleted(e);break;default:throw new Error(`Unsupported event type: ${e.eventType}`)}}))}handleChannelManagementEvent(e){if(!e.channelManagementEvent)throw new Error("Missing channelManagementEvent in CHANNEL_MANAGEMENT_EVENT");const t=e.channelManagementEvent.event;if(t.eventName===nn)return this.clientEventEmitter.safeEmit(nn),void a(this,Am,"f").debug("New forced disconnect event",{event:t});this.clientEventEmitter.safeEmit(Wr,t),a(this,Am,"f").debug("New channel event",{event:t})}handlePeerJoined(e){if(!e.peer)throw new Error("Missing peer in PEER_APP_DATA_CHANGED event");const t=this.peers.add(Tm(e.peer));a(this,Am,"f").debug("Peer joined to the channel",{peer:to(t)})}handlePeerLeft(e){if(!e.peer)throw new Error("Missing peer in PEER_LEFT event");this.peers.remove(e.peer.id).catch((e=>{a(this,Am,"f").debug("Failed to remove peer",{error:Vt(e)})})),a(this,Am,"f").debug("Peer left the channel",{peerId:e.peer.id})}handleChannelState(e){return o(this,void 0,void 0,(function*(){if(!e.channelState)throw new Error("Missing channelState in CHANNEL_STATE event");try{yield this.channelStateSynchronizer.handleChannelStateEvent(e.channelState)}catch(e){a(this,Am,"f").error("Failed to restore channel state",{case:"restoreLocalState",error:Vt(e)})}}))}handleChannelStateShort(e){if(!e.channelStateShort)throw new Error("Missing channelStateShort in CHANNEL_STATE_SHORT event");this.channelStateSyncEventHandler.handleChannelStateShort(e.channelStateShort).catch((e=>{a(this,Am,"f").error("Failed to handle channel state short event",{error:Vt(e)})}))}handlePeerAppDataChanged(e){if(!e.peer)throw new Error("Missing peer in PEER_APP_DATA_CHANGED event");const t=this.peers.get(e.peer.id);t&&t.observer.emit(Br,e.peer.appData)}handlePeerGroupsChanged(e){if(!e.peer)throw new Error("Missing peer in PEER_GROUP_CHANGED event");const t=this.peers.get(e.peer.id);null==t||t.handleGroupsChange(e.peer.groups.map(Sm))}handleChannelActivityConfirmationExpired(){this.clientEventEmitter.safeEmit(Yr),a(this,Am,"f").info("Notify the channel that it has disconnected due to the activity confirmation expiring",{})}handleChannelActivityConfirmationAcquired(){this.clientEventEmitter.safeEmit(Gr),a(this,Am,"f").info("Notify the channel that the activity has been acquired.",{})}handleChannelActivityConfirmationRequired(e){if(!e.channelActivityConfirmationTime)throw new Error("Missing channelActivityConfirmationTime in CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED event");const t=e.channelActivityConfirmationTime;this.clientEventEmitter.safeEmit(zr,t),a(this,Am,"f").info("Notify the channel that activity confirmation is required",{event:e.channelActivityConfirmationTime})}handleChannelProducePermissionsChanged(e){if(!e.channelProducePermissions)throw new Error("Missing channelProducePermissions in CHANNEL_PRODUCE_PERMISSIONS_CHANGED event");const{groups:t}=e.channelProducePermissions,r=this.peers.all().filter((e=>e.groups.some((e=>t.includes(km(e)))))),n=e.channelProducePermissions.producePermissions.map(Cm),i=e.channelProducePermissions.changedProducePermissions.map(Cm);r.forEach((e=>{const t=Array.from(new Set([...e.producePermissions,...i])).filter((e=>!i.includes(e)||n.includes(e)));e.handleProducePermissionsChange(t)})),a(this,Am,"f").info("Peers changed produce permissions",{groups:t,producePermissions:n})}handlePeerProducePermissionsChanged(e){if(!e.peer)throw new Error("Missing peer in PEER_PRODUCE_PERMISSIONS_CHANGED event");const t=this.peers.get(e.peer.id);if(!t)return;const r=e.peer.producePermissions.map(Cm);t.handleProducePermissionsChange(r)}handleChannelProducePermissionsDeleted(e){if(!e.channelProducePermissions)throw new Error("Missing channelProducePermissions in CHANNEL_PRODUCE_PERMISSIONS_DELETED event");const{groups:t}=e.channelProducePermissions,r=this.peers.all().filter((e=>e.groups.some((e=>t.includes(km(e)))))),n=e.channelProducePermissions.producePermissions.map(Cm);r.forEach((e=>{const t=e.producePermissions.filter((e=>!n.includes(e)));e.handleProducePermissionsChange(t)})),a(this,Am,"f").info("Peers deleted produce permissions",{groups:t,producePermissions:n})}};Am=new WeakMap,Mm=n([ot(),i(0,ct(fi.Peers)),i(1,ct(fi.ClientEventEmitter)),i(2,ct(fi.LoggerFactory)),i(3,ct(fi.ChannelStateSyncEventHandler)),i(4,ct(fi.ChannelStateSynchronizer)),s("design:paramtypes",[ho,Ft,Function,ld,Om])],Mm);var Nm=Mm,Lm={},xm=u&&u.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(Lm,"__esModule",{value:!0});var Fm,jm,Um=Lm.AwaitQueue=class{constructor({ClosedErrorClass:e=Error,StoppedErrorClass:t=Error,RemovedTaskErrorClass:r=Error}={ClosedErrorClass:Error,StoppedErrorClass:Error,RemovedTaskErrorClass:Error}){this.closed=!1,this.pendingTasks=[],this.ClosedErrorClass=Error,this.StoppedErrorClass=Error,this.RemovedTaskErrorClass=Error,this.ClosedErrorClass=e,this.StoppedErrorClass=t,this.RemovedTaskErrorClass=r}get size(){return this.pendingTasks.length}close(){if(!this.closed){this.closed=!0;for(const e of this.pendingTasks)e.stopped=!0,e.reject(new this.ClosedErrorClass("AwaitQueue closed"));this.pendingTasks.length=0}}push(e,t){return xm(this,void 0,void 0,(function*(){if(this.closed)throw new this.ClosedErrorClass("AwaitQueue closed");if("function"!=typeof e)throw new TypeError("given task is not a function");if(!e.name&&t)try{Object.defineProperty(e,"name",{value:t})}catch(e){}return new Promise(((r,n)=>{const i={task:e,name:t,resolve:r,reject:n,stopped:!1,enqueuedAt:new Date,executedAt:void 0};this.pendingTasks.push(i),1===this.pendingTasks.length&&this.next()}))}))}removeTask(e){if(0===e)throw new TypeError("cannot remove task with index 0");const t=this.pendingTasks[e];t&&(this.pendingTasks.splice(e,1),t.reject(new this.RemovedTaskErrorClass("task removed from the queue")))}stop(){if(!this.closed){for(const e of this.pendingTasks)e.stopped=!0,e.reject(new this.StoppedErrorClass("AwaitQueue stopped"));this.pendingTasks.length=0}}dump(){const e=new Date;let t=0;return this.pendingTasks.map((r=>({idx:t++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt.getTime()-r.enqueuedAt.getTime():e.getTime()-r.enqueuedAt.getTime(),executingTime:r.executedAt?e.getTime()-r.executedAt.getTime():0})))}next(){return xm(this,void 0,void 0,(function*(){const e=this.pendingTasks[0];e&&(yield this.executeTask(e),this.pendingTasks.shift(),this.next())}))}executeTask(e){return xm(this,void 0,void 0,(function*(){if(!e.stopped){e.executedAt=new Date;try{const t=yield e.task();if(e.stopped)return;e.resolve(t)}catch(t){if(e.stopped)return;e.reject(t)}}}))}};let Vm=class{constructor(e,t,r,n,i){this.media=e,this.internalEventEmitter=t,this.peersStorage=r,this.clientEventEmitter=n,Fm.set(this,new Um),jm.set(this,void 0),c(this,jm,i("MediaEvents"),"f")}handleMediaEvent(e){var t;switch(e.eventType){case js.MEDIA_EVENT_TYPE_PRODUCER_CREATED:this.handleProducerCreated(e);break;case js.MEDIA_EVENT_TYPE_PRODUCER_CLOSED:this.handleProducerClosed(e);break;case js.MEDIA_EVENT_TYPE_PRODUCER_PAUSED:this.handleProducerPaused(e);break;case js.MEDIA_EVENT_TYPE_PRODUCER_RESUMED:this.handleProducerResumed(e);break;case js.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED:this.handleProducerMaxSpatialLayerChanged(e);break;case js.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED:this.handleProducerRequestMaxSpatialLayer(e).catch((e=>{a(this,jm,"f").error("Failed to handle producer max spatial layer requested event",{error:Vt(e)})}));break;case js.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED:this.handleProducerForciblyClosed(e).catch((e=>{a(this,jm,"f").error("Failed to handle producer forcibly closed event",{error:Vt(e)})}));break;case js.MEDIA_EVENT_TYPE_CONSUMER_CLOSED:a(this,jm,"f").debug("Close consumer event received, skip",{consumerId:null===(t=e.consumer)||void 0===t?void 0:t.id});break;case js.MEDIA_EVENT_TYPE_CONSUMER_RESUMED:this.handleConsumerResumed(e);break;case js.MEDIA_EVENT_TYPE_CONSUMER_PAUSED:this.handleConsumerPaused(e);break;case js.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED:this.handleConsumerPreferredLayersChanged(e);break;case js.MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT:this.handleTransportConnectionTimeout(e);break;default:throw new Error(`Unsupported event type: ${e.eventType}`)}}handleProducerCreated(e){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_CREATED");const t=this.peersStorage.get(e.producer.peerId);null==t||t.observer.safeEmit(Ln,Rm(e.producer))}handleProducerClosed(e){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_CLOSED");const t=this.peersStorage.get(e.producer.peerId);null==t||t.observer.safeEmit(xn,Rm(e.producer))}handleProducerPaused(e){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_PAUSED");const t=this.peersStorage.get(e.producer.peerId),r=null==t?void 0:t.producers.get(e.producer.id);t?r?(r.setPaused(!0),t.observer.safeEmit(Pn,{producerId:r.id,kind:r.kind,label:r.label,paused:r.paused})):t.observer.safeEmit(Ln,Object.assign(Object.assign({},Rm(e.producer)),{paused:!0})):a(this,jm,"f").debug("Peer not found for producer paused event",{peerId:e.producer.peerId})}handleProducerResumed(e){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_RESUMED");const t=this.peersStorage.get(e.producer.peerId),r=null==t?void 0:t.producers.get(e.producer.id);t?r?(r.setPaused(!1),t.observer.safeEmit(Tn,{producerId:r.id,kind:r.kind,label:r.label,paused:r.paused})):t.observer.safeEmit(Ln,Object.assign(Object.assign({},Rm(e.producer)),{paused:!1})):a(this,jm,"f").debug("Peer not found for producer resumed event",{peerId:e.producer.peerId})}handleProducerMaxSpatialLayerChanged(e){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED");if(void 0===e.producer.maxSpatialLayer)return;const t=this.peersStorage.get(e.producer.peerId);null==t||t.observer.safeEmit(Fn,{peerId:e.producer.peerId,producerId:e.producer.id,spatialLayer:e.producer.maxSpatialLayer})}handleProducerRequestMaxSpatialLayer(e){return o(this,void 0,void 0,(function*(){if(!e.producerSpatialLayerRequest)throw new Error("Missing producerSpatialLayerRequest in MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED");const{producerId:t,spatialLayer:r}=e.producerSpatialLayerRequest;yield a(this,Fm,"f").push((()=>o(this,void 0,void 0,(function*(){yield this.media.handleProducerSetMaxSpatialLayer({producerId:t,spatialLayer:r})}))),jn)}))}handleProducerForciblyClosed(e){return o(this,void 0,void 0,(function*(){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED");const t=Cm(e.producer.label),r=this.media.getTrackByLabel(t);if(!r)return;r.stopMediaStreamTrack(),this.internalEventEmitter.safeEmit(_n,r);const n={label:t};this.clientEventEmitter.emit(Kr,n),yield this.media.deleteTrack(r)}))}handleConsumerResumed(e){if(!e.consumer)throw new Error("Missing consumer in MEDIA_EVENT_TYPE_CONSUMER_RESUMED");const t=this.peersStorage.get(e.consumer.producerPeerId);null==t||t.observer.safeEmit(Bn,e.consumer.id)}handleConsumerPaused(e){if(!e.consumer)throw new Error("Missing consumer in MEDIA_EVENT_TYPE_CONSUMER_PAUSED");const t=this.peersStorage.get(e.consumer.producerPeerId);null==t||t.observer.safeEmit(Vn,e.consumer.id)}handleConsumerPreferredLayersChanged(e){var t;if(!e.consumer)throw new Error("Missing consumer in MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED");if(void 0===e.consumer.spatialLayer)return;const r=e.consumer.producerPeerId||e.consumer.peerId,n=this.peersStorage.get(r);null==n||n.observer.safeEmit(Wn,{consumerId:e.consumer.id,spatialLayer:e.consumer.spatialLayer,temporalLayer:null!==(t=e.consumer.temporalLayer)&&void 0!==t?t:Vh})}handleTransportConnectionTimeout(e){if(!e.transportConnectionTimeout)throw new Error("Missing transportConnectionTimeout in MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT");a(this,jm,"f").info("Transport connection timed out",{transportId:e.transportConnectionTimeout.transportId,direction:e.transportConnectionTimeout.direction,timeout:e.transportConnectionTimeout.timeout,reason:e.transportConnectionTimeout.reason})}};Fm=new WeakMap,jm=new WeakMap,Vm=n([ot(),i(0,ct(fi.Media)),i(1,ct(fi.InternalEventEmitter)),i(2,ct(fi.PeersStorage)),i(3,ct(fi.ClientEventEmitter)),i(4,ct(fi.LoggerFactory)),s("design:paramtypes",[vm,Ft,po,Ft,Function])],Vm);var Bm,Wm=Vm;let Hm=class{constructor(){Bm.set(this,new Map)}set(e,t){a(this,Bm,"f").set(e,{label:e,producerId:t})}get(e){return a(this,Bm,"f").get(e)}has(e){return a(this,Bm,"f").has(e)}delete(e){a(this,Bm,"f").delete(e)}entries(){return Array.from(a(this,Bm,"f").values())}};Bm=new WeakMap,Hm=n([ot()],Hm);var qm,zm=Hm;let Gm=class{constructor(e,t,r){this.network=e,this.storage=t,qm.set(this,void 0),c(this,qm,r("ProducerCloseManager"),"f")}close(e,t){return o(this,void 0,void 0,(function*(){try{const r=yield this.sendCloseRequest(t);if(this.storage.delete(e),!r)return;a(this,qm,"f").info("Remote producer closed",{label:e,producerId:t})}catch(r){this.storage.set(e,t);(Qn(r)?a(this,qm,"f").debug.bind(a(this,qm,"f")):a(this,qm,"f").warn.bind(a(this,qm,"f")))("Failed to close remote producer, queued for retry",{label:e,producerId:t,error:Vt(r)})}}))}ensureNoPending(e){return o(this,void 0,void 0,(function*(){const t=this.storage.get(e);t&&(yield this.flushEntry(t))}))}flushPending(){return o(this,void 0,void 0,(function*(){const e=this.storage.entries();for(const t of e)try{yield this.flushEntry(t)}catch(e){}}))}flushEntry(e){return o(this,void 0,void 0,(function*(){try{yield hi((()=>o(this,void 0,void 0,(function*(){yield this.sendCloseRequest(e.producerId)}))),{maxRetries:5,minBackoffDelayMs:200,maxBackoffDelayMs:1e3,actionName:"closeRemoteProducer",logger:a(this,qm,"f")}),this.storage.delete(e.label),a(this,qm,"f").info("Pending remote producer closed",{label:e.label,producerId:e.producerId})}catch(t){throw a(this,qm,"f").debug("Failed to close pending remote producer",{label:e.label,producerId:e.producerId,error:Vt(t)}),t}}))}sendCloseRequest(e){return o(this,void 0,void 0,(function*(){try{return yield this.network.closeRemoteProducer(e),!0}catch(t){if(t instanceof Yn)return a(this,qm,"f").debug("Remote producer maybe already closed",{producerId:e}),!1;throw t}}))}};qm=new WeakMap,Gm=n([ot(),i(0,ct(fi.Network)),i(1,ct(fi.PendingClosureProducerStorage)),i(2,ct(fi.LoggerFactory)),s("design:paramtypes",[Function,zm,Function])],Gm);var Ym,$m,Jm,Qm,Km,Zm,Xm,eg=Gm;const tg=["send","recv"];let rg=Xm=class{constructor(e,t){this.network=e,this.loggerFactory=t,Ym.set(this,!1),$m.set(this,new Map),Jm.set(this,new Set),Qm.set(this,new Map),Km.set(this,void 0),Zm.set(this,void 0),this.handleTransportState=({state:e,direction:t})=>{if(!a(this,Ym,"f"))return;if(a(this,Jm,"f").has(t))return;if(a(this,Qm,"f").has(t))return;if(!["disconnected","failed"].includes(e))return;const r=this.recordDisconnectAndGetCount(t);r&&(r<=3||(a(this,Zm,"f").info("transport instability detected. Escalating to relay",{direction:t,disconnectCount:r}),this.triggerRelayEscalation(t).catch((e=>{a(this,Zm,"f").warn("Failed to escalate to relay",{direction:t,error:Vt(e)})}))))},c(this,Zm,this.loggerFactory("NetworkTransportPolicyManager"),"f")}setRelayEscalationHandler(e){c(this,Km,e,"f")}startMonitoring(){a(this,Ym,"f")||(this.refreshDirectionRelayState(),a(this,$m,"f").clear(),c(this,Ym,!0,"f"),this.network.observer.on(qn,this.handleTransportState))}stopMonitoring(){a(this,Ym,"f")&&(this.network.observer.off(qn,this.handleTransportState),c(this,Ym,!1,"f"),a(this,$m,"f").clear())}changeIceTransportPolicy(e){return o(this,void 0,void 0,(function*(){yield Promise.all(a(this,Qm,"f").values()),yield Promise.all(tg.map((t=>o(this,void 0,void 0,(function*(){return yield this.applyRelayPolicy(t,e)}))))),a(this,$m,"f").clear(),"all"!==e?this.stopMonitoring():a(this,Jm,"f").clear()}))}triggerRelayEscalation(e){return o(this,void 0,void 0,(function*(){if(a(this,Km,"f"))return a(this,$m,"f").clear(),void(yield a(this,Km,"f").call(this));yield this.escalateDirectionToRelay(e)}))}recordDisconnectAndGetCount(e){var t;const r=Date.now(),n=null!==(t=a(this,$m,"f").get(e))&&void 0!==t?t:[],i=n[n.length-1];if(Xm.isDuplicateDisconnect(i,r))return;const s=Xm.getDisconnectsInWindow(n,r);return s.push(r),a(this,$m,"f").set(e,s),s.length}applyRelayPolicy(e,t){return o(this,void 0,void 0,(function*(){const r=this.getTransportByDirection(e);if(!r)return;const n=Xm.getPeerConnection(r);n&&(n.setConfiguration(Object.assign(Object.assign({},n.getConfiguration()),{iceTransportPolicy:t})),yield this.network.restartIce(r),"relay"===t?a(this,Jm,"f").add(e):a(this,Jm,"f").delete(e))}))}escalateDirectionToRelay(e){return o(this,void 0,void 0,(function*(){if(a(this,Jm,"f").has(e))return;const t=a(this,Qm,"f").get(e);if(t)return void(yield t);const r=(()=>o(this,void 0,void 0,(function*(){yield this.applyRelayPolicy(e,"relay"),a(this,$m,"f").delete(e)})))();a(this,Qm,"f").set(e,r);try{yield r}finally{a(this,Qm,"f").delete(e)}}))}refreshDirectionRelayState(){tg.forEach((e=>{const t=this.getTransportByDirection(e),r=Xm.getPeerConnection(t);"relay"!==(null==r?void 0:r.getConfiguration().iceTransportPolicy)?a(this,Jm,"f").delete(e):a(this,Jm,"f").add(e)}))}getTransportByDirection(e){return"send"===e?this.network.sendTransport:this.network.receiveTransport}static getPeerConnection(e){var t;return null===(t=null==e?void 0:e.handler)||void 0===t?void 0:t._pc}static getDisconnectsInWindow(e,t){const r=t-3e4;return e.filter((e=>e>=r))}static isDuplicateDisconnect(e,t){return"number"==typeof e&&t-e<400}};Ym=new WeakMap,$m=new WeakMap,Jm=new WeakMap,Qm=new WeakMap,Km=new WeakMap,Zm=new WeakMap,rg=Xm=n([ot(),i(0,ct(fi.Network)),i(1,ct(fi.LoggerFactory)),s("design:paramtypes",[uo,Function])],rg);var ng=rg;const ig=new Error("request for lock canceled");var sg=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class og{constructor(e,t=ig){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise(((r,n)=>{const i={resolve:r,reject:n,weight:e,priority:t},s=ag(this._queue,(e=>t<=e.priority));-1===s&&e<=this._value?this._dispatchItem(i):this._queue.splice(s+1,0,i)}))}runExclusive(e){return sg(this,arguments,void 0,(function*(e,t=1,r=0){const[n,i]=yield this.acquire(t,r);try{return yield e(n)}finally{i()}}))}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise((r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),function(e,t){const r=ag(e,(e=>t.priority<=e.priority));e.splice(r+1,0,t)}(this._weightedWaiters[e-1],{resolve:r,priority:t})}))}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach((e=>e.reject(this._cancelError))),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(0===this._queue.length)for(let e=this._value;e>0;e--){const t=this._weightedWaiters[e-1];t&&(t.forEach((e=>e.resolve())),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let t=this._value;t>0;t--){const r=this._weightedWaiters[t-1];if(!r)continue;const n=r.findIndex((t=>t.priority<=e));(-1===n?r:r.splice(0,n)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(0===this._queue.length||this._queue[0].priority<t)&&e<=this._value}}function ag(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1}var cg,dg=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class ug{constructor(e){this._semaphore=new og(1,e)}acquire(){return dg(this,arguments,void 0,(function*(e=0){const[,t]=yield this._semaphore.acquire(1,e);return t}))}runExclusive(e,t=0){return this._semaphore.runExclusive((()=>e()),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}let lg=class{constructor(){cg.set(this,new Map)}lock(e){return o(this,void 0,void 0,(function*(){let t=a(this,cg,"f").get(e);return t||(t=new ug,a(this,cg,"f").set(e,t)),t.isLocked()&&(yield t.waitForUnlock()),yield t.acquire()}))}isLocked(e){const t=a(this,cg,"f").get(e);return!!t&&t.isLocked()}waitForUnlock(e){return o(this,void 0,void 0,(function*(){const t=a(this,cg,"f").get(e);(null==t?void 0:t.isLocked())?yield t.waitForUnlock():yield Promise.resolve()}))}};cg=new WeakMap,lg=n([ot()],lg);var pg,hg=lg;class fg extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="MediaDeviceAccessError",this.code=e}}let mg=class{constructor(e,t){this.clientEventEmitter=e,this.isEnableVideoDevicesLock=!1,this.isEnableAudioDevicesLock=!1,this.isDevicesDetected=!1,this.availableVideoDevices=[],this.availableAudioDevices=[],this.availableAudioOutputDevices=[],pg.set(this,void 0),c(this,pg,t("System"),"f"),this.deviceChangeHandler=this.deviceChangeHandler.bind(this),this.listenDevices()}setIsEnableVideoDevicesLock(e){this.isEnableVideoDevicesLock=e}setIsEnableAudioDevicesLock(e){this.isEnableAudioDevicesLock=e}setAvailableVideoDevices(e){this.availableVideoDevices=e}setAvailableAudioDevices(e){this.availableAudioDevices=e}setAvailableAudioOutputDevices(e){this.availableAudioOutputDevices=e}requestMediaDevicesAccess(){return o(this,arguments,void 0,(function*(e={video:!0,audio:!0}){try{return(yield navigator.mediaDevices.getUserMedia(e)).getTracks()}catch(t){a(this,pg,"f").error("getUserMedia()",{error:t,constraints:e});const r=t instanceof Error?t.name:void 0;if("NotAllowedError"===r)throw new fg(exports.DeviceErrors.NotAllowedError);if("NotReadableError"===r)throw new fg(exports.DeviceErrors.DeviceIsBusy);if("NotFoundError"===r)throw new fg(exports.DeviceErrors.NotFoundError);throw new fg(exports.DeviceErrors.RequestDevicesUnknownError)}}))}hasAvailableMediaDevicesList(){return o(this,void 0,void 0,(function*(){const e=yield navigator.mediaDevices.enumerateDevices();if(0===e.length)return!0;return e.every((e=>e.deviceId&&e.label))}))}refreshAvailableMediaDevicesList(){return o(this,void 0,void 0,(function*(){const e=yield navigator.mediaDevices.enumerateDevices(),t=[],r=[],n=[];e.forEach((e=>{""!==e.deviceId&&("videoinput"===e.kind&&t.push(e),"audioinput"===e.kind&&r.push(e),"audiooutput"===e.kind&&n.push(e))})),this.setAvailableVideoDevices(t),this.setAvailableAudioDevices(r),this.setAvailableAudioOutputDevices(n);const i=({label:e,kind:t})=>({label:e,kind:t});return a(this,pg,"f").info("Devices list updated",{videoDevices:t.map(i),audioDevices:r.map(i),audioOutputDevices:n.map(i)}),e}))}detectDevices(e){return o(this,void 0,void 0,(function*(){if(this.isDevicesDetected&&!e)return this.getAvailableMediaDevices();this.resetDeviceAvailability();(yield this.hasAvailableMediaDevicesList())||(yield this.tryToAccessDevices()),this.isDevicesDetected=!0,yield this.refreshAvailableMediaDevicesList();const t=this.getAvailableMediaDevices();return a(this,pg,"f").debug("detectDevices()",{availability:t.availability,audio:t.audio,video:t.video,audioOutput:t.audioOutput}),t}))}deviceChangeHandler(){return o(this,void 0,void 0,(function*(){if(!this.isDevicesDetected)return;yield this.refreshAvailableMediaDevicesList();const e=this.getAvailableMediaDevices();this.clientEventEmitter.safeEmit(Jr,e)}))}resetDeviceAvailability(){this.audioDeviceAvailability=void 0,this.videoDeviceAvailability=void 0,this.audioOutputDeviceAvailability=void 0}getAvailableMediaDevices(){return{audio:this.availableAudioDevices,video:this.availableVideoDevices,audioOutput:this.availableAudioOutputDevices,availability:{audio:this.getDeviceAvailability("audio"),video:this.getDeviceAvailability("video"),audioOutput:this.getDeviceAvailability("audioOutput")}}}getDeviceAvailability(e){var t;const r={audio:this.availableAudioDevices,video:this.availableVideoDevices,audioOutput:this.availableAudioOutputDevices},n={audio:this.audioDeviceAvailability,video:this.videoDeviceAvailability,audioOutput:this.audioOutputDeviceAvailability};return r[e].length>0?{available:!0}:null!==(t=n[e])&&void 0!==t?t:{available:!1,reason:"not_found"}}listenDevices(){navigator.mediaDevices.addEventListener("devicechange",this.deviceChangeHandler)}requestMediaDeviceAccessAvailability(e){return o(this,void 0,void 0,(function*(){try{return(yield this.requestMediaDevicesAccess({[e]:!0})).forEach((e=>e.stop())),{available:!0}}catch(e){if(e instanceof fg){if(e.code===exports.DeviceErrors.NotAllowedError)return{available:!1,reason:"not_allowed"};if(e.code===exports.DeviceErrors.NotFoundError)return{available:!1,reason:"not_found"};if(e.code===exports.DeviceErrors.DeviceIsBusy)return{available:!1,reason:"device_is_busy"}}throw e}}))}tryToAccessDevices(){return o(this,void 0,void 0,(function*(){try{(yield this.requestMediaDevicesAccess()).forEach((e=>e.stop()))}catch(e){if(!(e instanceof fg))throw e;if(e.code===exports.DeviceErrors.DeviceIsBusy)return;if(e.code===exports.DeviceErrors.RequestDevicesUnknownError)throw e;this.audioDeviceAvailability=yield this.requestMediaDeviceAccessAvailability("audio"),this.videoDeviceAvailability=yield this.requestMediaDeviceAccessAvailability("video")}}))}};pg=new WeakMap,mg=n([ot(),i(0,ct(fi.ClientEventEmitter)),i(1,ct(fi.LoggerFactory)),s("design:paramtypes",[Ft,Function])],mg);var gg,vg=mg;class yg{constructor({transport:e,statsHandler:t}){gg.set(this,void 0),this.handleWebRTCStats(e,t)}get connectionStats(){return a(this,gg,"f")}handleWebRTCStats(e,t){t.addConnectionHandler(e.id,this.setConnectionStats.bind(this)),e.observer.once("close",(()=>{t.removeConnectionHandler(e.id)}))}setConnectionStats(e){c(this,gg,e,"f")}}gg=new WeakMap;function bg(e,t){return t.find((t=>t.ssrc===e))}function _g(e,t,r){return Math.max(t,Math.min(e,r))}function Eg(e,t=2){return Number(e.toFixed(t))}function wg(e){return _g(Eg(e),1,5)}function Sg(e,t){if(0===e.length)throw new Error("Cannot compute percentile of empty array");if(1===e.length)return e[0];const r=t*(e.length-1),n=Math.floor(r),i=Math.ceil(r),s=r-n;return Eg(e[n]+s*(e[i]-e[n]))}var Cg,Pg,Tg,Rg,kg;let Dg=class{constructor(){Cg.set(this,new Map),Pg.set(this,new Map),Tg.set(this,new Map),Rg.set(this,new Map),kg.set(this,new Map)}handle(e){e.forEach((({id:e,stats:t})=>{var r;null===(r=a(this,Cg,"f").get(e))||void 0===r||r(t.connection),t.video.inbound.forEach((e=>{var r;return null===(r=a(this,Pg,"f").get(e.trackIdentifier))||void 0===r?void 0:r({inbound:e,connection:t.connection})})),t.audio.inbound.forEach((e=>{var r;return null===(r=a(this,Tg,"f").get(e.trackIdentifier))||void 0===r?void 0:r({inbound:e,connection:t.connection})}));const n=new Map;t.video.outbound.forEach((e=>{const r=bg(e.ssrc,t.remote.video.inbound);if(!r)return;const i={outbound:e,remoteInbound:r,connection:t.connection},s=n.get(e.mid);s?s.push(i):n.set(e.mid,[i])})),n.forEach((e=>{var t,r;const n=null===(t=e.find((e=>e.outbound.track.trackIdentifier)))||void 0===t?void 0:t.outbound.track.trackIdentifier;n&&(null===(r=a(this,Rg,"f").get(n))||void 0===r||r(e))})),t.audio.outbound.forEach((e=>{var r;const n=bg(e.ssrc,t.remote.audio.inbound);n&&(null===(r=a(this,kg,"f").get(e.track.trackIdentifier))||void 0===r||r({outbound:e,remoteInbound:n,connection:t.connection}))}))}))}addConnectionHandler(e,t){a(this,Cg,"f").set(e,t)}addInboundVideoHandler(e,t){a(this,Pg,"f").set(e,t)}addInboundAudioHandler(e,t){a(this,Tg,"f").set(e,t)}addOutboundVideoHandler(e,t){a(this,Rg,"f").set(e,t)}addOutboundAudioHandler(e,t){a(this,kg,"f").set(e,t)}removeConnectionHandler(e){a(this,Cg,"f").delete(e)}removeInboundVideoHandler(e){a(this,Pg,"f").delete(e)}removeInboundAudioHandler(e){a(this,Tg,"f").delete(e)}removeOutboundVideoHandler(e){a(this,Rg,"f").delete(e)}removeOutboundAudioHandler(e){a(this,kg,"f").delete(e)}clear(){a(this,Cg,"f").clear(),a(this,Pg,"f").clear(),a(this,Tg,"f").clear(),a(this,Rg,"f").clear(),a(this,kg,"f").clear()}};Cg=new WeakMap,Pg=new WeakMap,Tg=new WeakMap,Rg=new WeakMap,kg=new WeakMap,Dg=n([ot()],Dg);var Ig,Ag,Og,Mg,Ng,Lg,xg,Fg,jg=Dg;let Ug=class{constructor(e,t){var r;Ig.set(this,!1),Ag.set(this,void 0),Og.set(this,void 0),Mg.set(this,void 0),Ng.set(this,void 0),Lg.set(this,void 0),xg.set(this,void 0),Fg.set(this,.5),c(this,Ag,e("IntegrationsService"),"f"),c(this,xg,t,"f"),c(this,Fg,null!==(r=Ar("qosQPercentile"))&&void 0!==r?r:a(this,Fg,"f"),"f")}init({sendTransportConnectionManager:e,receiveTransportConnectionManager:t,media:r,peers:n}){c(this,Og,e,"f"),c(this,Mg,t,"f"),c(this,Ng,r,"f"),c(this,Lg,n,"f"),c(this,Ig,!0,"f")}getStats(){try{return this.doGetStats()}catch(e){return a(this,Ag,"f").error("Failed to get stats",{error:Vt(e)}),{}}}clear(){c(this,Og,void 0,"f"),c(this,Mg,void 0,"f"),c(this,Ng,void 0,"f"),c(this,Lg,void 0,"f")}doGetStats(){var e,t,r,n;if(!a(this,Ig,"f"))throw new Error("TransportsStatsProvider is not initialized");const i={};if(null===(t=null===(e=a(this,Og,"f"))||void 0===e?void 0:e.connectionStats)||void 0===t?void 0:t.id){const e=this.calculateOutboundTracksResultQValues();i.outbound=Object.assign(Object.assign({},a(this,Og,"f").connectionStats),{bitrate:this.calculateOutboundTracksBitrate(),Qav:e.Qav,Qa:e.Qa,Qv:e.Qv})}if(null===(n=null===(r=a(this,Mg,"f"))||void 0===r?void 0:r.connectionStats)||void 0===n?void 0:n.id){const e=this.calculateInboundTracksResultQValues();i.inbound=Object.assign(Object.assign({},a(this,Mg,"f").connectionStats),{bitrate:this.calculateInboundTracksBitrate(),Qav:e.Qav,Qa:e.Qa,Qv:e.Qv})}return i}calculateInboundTracksBitrate(){if(void 0===a(this,Lg,"f"))throw new Error("Peers is undefined");return a(this,Lg,"f").hosts().reduce(((e,t)=>{if(t.isMe)return e;return e+Array.from(t.tracks.values()).reduce(((e,t)=>{var r,n;const i="video"===t.kind?null===(r=t.videoWebRTCStats)||void 0===r?void 0:r.bitrate:null===(n=t.audioWebRTCStats)||void 0===n?void 0:n.bitrate;return e+(null!=i?i:0)}),0)}),0)}calculateInboundTracksResultQValues(){if(void 0===a(this,Lg,"f"))throw new Error("Peers prop is not defined");const e=[],t=[],r=[];for(const n of a(this,Lg,"f").hosts()){if(n.isMe)continue;const{Qa:i,Qv:s}=this.getWorstQValues(Array.from(n.tracks.values()));void 0!==i&&t.push(i),void 0!==s&&r.push(s);const o=void 0===i||void 0===s?null!=i?i:s:a(this,xg,"f").calculateAVCompositeMOS(i,s);void 0!==o&&e.push(o)}const n=(e,t)=>e-t;return e.sort(n),t.sort(n),r.sort(n),{Qav:e.length>0?Sg(e,a(this,Fg,"f")):void 0,Qa:t.length>0?Sg(t,a(this,Fg,"f")):void 0,Qv:r.length>0?Sg(r,a(this,Fg,"f")):void 0}}calculateOutboundTracksResultQValues(){var e;if(void 0===a(this,Ng,"f"))throw new Error("Media prop is not defined");const t=a(this,Ng,"f").getAllTracks().filter((e=>e.isPublished)),{Qa:r,Qv:n}=this.getWorstQValues(t);let i;return void 0!==r&&void 0!==n&&(i=a(this,xg,"f").calculateAVCompositeMOS(r,n)),{Qav:null!==(e=null!=i?i:r)&&void 0!==e?e:n,Qa:r,Qv:n}}calculateOutboundTracksBitrate(){if(void 0===a(this,Ng,"f"))throw new Error("Media is undefined");return a(this,Ng,"f").getAllTracks().reduce(((e,t)=>{var r,n;if(!t.isPublished)return e;const i="video"===t.kind?null===(r=t.videoWebRTCStats)||void 0===r?void 0:r.bitrate:null===(n=t.audioWebRTCStats)||void 0===n?void 0:n.bitrate;return e+(null!=i?i:0)}),0)}getWorstQValues(e){let t,r;for(const n of e){const{Qa:e,Qv:i}=n.connectionScores;void 0!==e&&(void 0===t||e<t)&&(t=e),void 0!==i&&(void 0===r||i<r)&&(r=i)}return{Qa:t,Qv:r}}};Ig=new WeakMap,Ag=new WeakMap,Og=new WeakMap,Mg=new WeakMap,Ng=new WeakMap,Lg=new WeakMap,xg=new WeakMap,Fg=new WeakMap,Ug=n([ot(),i(0,ct(fi.LoggerFactory)),i(1,ct(fi.ScoresCalculator)),s("design:paramtypes",[Function,Function])],Ug);var Vg=Ug;const Bg={vp8:40,vp9:40,h264:25},Wg={mobile:[.1558,1.0348,-.0181,-.4048],pc:[.1526,.8788,.0086,-.2242],tv:[.1496,1.0267,-.0248,-.3477]},Hg={video:{codecFactors:{vp9:1.2,vp8:1,h264:1}},defaults:{audio:{ssrc:-1,packetLoss:0,bufferDelay:50,roundTripTime:50,fec:!0,bitrate:0,dtx:!1},video:{ssrc:-1,packetLoss:0,bufferDelay:0,roundTripTime:50,codec:"vp8",width:640,height:480,expectedWidth:640,expectedHeight:480,frameRate:20,expectedFrameRate:20,bitrate:0}}};var qg,zg,Gg;exports.ScoresCalculator=class{constructor(e){this.config=this.mergeConfig(e)}calculateAudioMOS(e){const t=this.normalizeAudioStats(e),r=20+t.bufferDelay+t.roundTripTime/2,n=t.packetLoss;let i=0;i=t.dtx?8:t.bitrate>0?_g(55-4.6*Math.log(t.bitrate),0,30):6;const s=_g(100-(i+(100-i)*n/(n+(t.fec?20:10)))-(.03*r+(r>150?.1*(r-150):0)),0,100);return wg(1+.035*s+s*(s-60)*(100-s)*7/1e6)}calculateVideoMOS(e){var t,r,n,i,s,o;const a=this.normalizeVideoStats(e),c=a.expectedWidth*a.expectedHeight;if(!a.frameRate||!c||void 0===a.bitrate)return 1;const d=a.codec&&null!==(n=null===(r=null===(t=this.config.video)||void 0===t?void 0:t.codecFactors)||void 0===r?void 0:r[a.codec.toLowerCase()])&&void 0!==n?n:1,u=a.bufferDelay+a.roundTripTime/2,l=d*a.bitrate/c/a.frameRate,p=_g(.56*Math.log(l)+5.36,1,5),h=!0===a.decreaseOutboundPenalty&&"none"===a.qualityLimitationReason,f=null!==(o=Bg[null!==(s=null===(i=a.codec)||void 0===i?void 0:i.toLowerCase())&&void 0!==s?s:""])&&void 0!==o?o:40,m=void 0!==a.averageQP&&a.averageQP<f;return wg((h||!0===a.isStaticContent||m?Math.max(p,4):p)-(a.expectedFrameRate>0?1.9*Math.log(a.expectedFrameRate/a.frameRate):0)-.002*u)}calculateAVCompositeMOS(e,t,r){const[n,i,s,o]=Wg[null!=r?r:"pc"];return wg(n*e+i*t+s*e*t+o)}mergeConfig(e){var t;return e?{video:{codecFactors:Object.assign(Object.assign({},Hg.video.codecFactors),null===(t=e.video)||void 0===t?void 0:t.codecFactors)}}:Hg}normalizeAudioStats(e){return Object.assign(Object.assign({},Hg.defaults.audio),e)}normalizeVideoStats(e){const t=Object.assign(Object.assign({},Hg.defaults.video),e);return void 0!==e.width&&void 0===e.expectedWidth&&(t.expectedWidth=e.width),void 0!==e.height&&void 0===e.expectedHeight&&(t.expectedHeight=e.height),void 0!==e.frameRate&&void 0===e.expectedFrameRate&&(t.expectedFrameRate=e.frameRate),t}},exports.ScoresCalculator=n([ot(),s("design:paramtypes",[Object])],exports.ScoresCalculator);let Yg=class{constructor(e,t,r,n,i,s,o,a,d,u,l,p,h,f,m,g,v,y,b,_,E,w,S,C,P){var T;this.state=e,this.myPeer=t,this.integrationsService=n,this.processorsCache=i,this.mediaEventHandler=s,this.channelEventsHandler=o,this.peerTrackFactory=a,this.peers=d,this.peersStorage=u,this.system=l,this.media=p,this.network=h,this.networkTransportPolicyManager=f,this.producerCloseManager=m,this.signalingApiClient=g,this.eventsQueue=v,this.clientEventEmitter=y,this.internalEventEmitter=b,this.statsHandler=_,this.transportsStatsProvider=E,this.localMutex=w,this.scoresCalculatorInstance=S,this.clientMetaProvider=C,this.webRtcIssueDetector=P,qg.set(this,void 0),this.rejoinRequested=!1,this.isReleasing=!1,zg.set(this,!1),Gg.set(this,!1),this.mark=Rr(),this.handleSignalingError=e=>{this.isReleasing||!this.isChannelJoined||this.state.isChannelJoining||e instanceof Kn&&this.triggerRejoinEventIfAppropriate(e.errorCode)},c(this,qg,r("Engine"),"f"),this.watchNetworkState(),this.watchDocumentUnload(),this.watchInternalEvents(),this.signalingApiClient.addErrorListener(this.handleSignalingError),T=this.mark,window._sdkMarks||(window._sdkMarks=new Set),window._sdkMarks.add(T)}get isChannelJoined(){return this.state.isJoined}get scoresCalculator(){return this.scoresCalculatorInstance}initialize(){return o(this,void 0,void 0,(function*(){var e,t;try{const{data:r}=yield this.signalingApiClient.router.getRtpCapabilities(),{rtpCapabilities:n}=r;this.integrationsService.init(),yield this.media.loadDevice(n),a(this,qg,"f").info("Supported capabilities",{codecs:ci(this.media.mediasoupDevice)}),yield this.initTransports(),this.network.channelMessagesDataConsumer&&(this.eventsQueue.setChannelEventHandler(this.channelEventsHandler.handleChannelEvent.bind(this.channelEventsHandler)),this.eventsQueue.setMediaEventHandler(this.mediaEventHandler.handleMediaEvent.bind(this.mediaEventHandler)),this.eventsQueue.subscribe(this.network.channelMessagesDataConsumer)),a(this,qg,"f").debug("initialize()",{sendTransportId:null===(e=this.network.sendTransport)||void 0===e?void 0:e.id,recvTransportId:null===(t=this.network.receiveTransport)||void 0===t?void 0:t.id})}catch(e){a(this,qg,"f").error("initialize()",{error:e});const t=e instanceof Error&&"UnsupportedError"===e.name&&"device not supported"===e.message,r=e instanceof Error&&"RTCPeerConnection is not defined"===e.message;if(t||r)throw new Zn("Device not supported",Zn.UNSUPPORTED_DEVICE_CODE);if(e instanceof Gn)throw e;throw new Bt("initialize_engine_error",e)}}))}release(e){return o(this,void 0,void 0,(function*(){var t;if(this.isReleasing)return;const r=this.myPeer.get(),n={case:"release",applicationId:this.state.appId,channelId:this.state.channelId,peerId:null!==(t=null==r?void 0:r.id)&&void 0!==t?t:this.myPeerId,peerRole:null==r?void 0:r.role,isJoined:this.state.isJoined,isChannelJoining:this.state.isChannelJoining,rejoinRequested:this.rejoinRequested};this.isReleasing=!0;const i=yield this.localMutex.lock(zn.Release);try{this.signalingApiClient.abortPendingRequests("release"),e||this.media.clearTracks(),yield Promise.all([si((()=>o(this,void 0,void 0,(function*(){return yield this.peers.reset()})))),si((()=>o(this,void 0,void 0,(function*(){return yield this.media.unpublishTracks()})))),si((()=>o(this,void 0,void 0,(function*(){return yield this.signalingApiClient.peers.disconnectPeer()}))))]),this.cleanup(),a(this,qg,"f").debug("release()",n)}catch(e){a(this,qg,"f").error("Failed to release",Object.assign(Object.assign({},n),{error:Vt(e)}))}finally{this.isReleasing=!1,i()}}))}getPeers(){return this.peers.all()}get myPeerId(){return this.myPeer.id}confirmActivity(){return o(this,void 0,void 0,(function*(){try{yield this.signalingApiClient.channel.confirmChannelActivity()}catch(e){throw new Bt("confirm_activity_failed",e)}}))}join(e){return o(this,arguments,void 0,(function*({token:e,appData:t,isP2pCall:r,preferredDC:n}){if(this.isChannelJoined)throw new Bt("method_not_available_when_joined");const i=yield this.localMutex.lock(zn.Join);try{a(this,qg,"f").debug("join()",{appData:t,isP2pCall:r}),this.state.isChannelJoining=!0,this.signalingApiClient.abortPendingRequests("join"),this.signalingApiClient.setSecurityData({token:e,peerApiVersion:8,datacenterType:r?"p2p":"common",preferredDC:n});const{data:s,headers:o}=yield this.signalingApiClient.peers.registerPeer({appData:t}),{appId:c,channelId:d,peerId:u}=s,l=String(o["x-datacenter-name"]),p=String(o["x-node-id"]);this.myPeer.id=u,this.state.appId=c,this.state.channelId=d,this.clientMetaProvider.setPeerId(u),this.clientMetaProvider.setChannelId(d),this.clientMetaProvider.setAppId(c),this.clientMetaProvider.setDatacenterName(l),this.clientMetaProvider.setNodeId(p),yield this.initialize(),this.state.isJoined=!0,a(this,qg,"f").info("Successfully joined channel",{channelId:d,datacenterName:l})}catch(e){throw this.signalingApiClient.abortPendingRequests("join"),yield this.release(),a(this,qg,"f").error("join()",{error:e}),new Bt("join_failed",e)}finally{this.state.isChannelJoining=!1,this.rejoinRequested=!1,i()}}))}requestChannelStateSync(){return o(this,void 0,void 0,(function*(){yield this.network.waitForReceiveTransportConnected({onReceiveTransportFailed:()=>o(this,void 0,void 0,(function*(){this.network.reset(),this.network.enforceRelay(12e4),yield this.initTransports()}))}),yield this.network.waitForChannelMessagesDataConsumerConnected(),this.state.isJoined=!0,this.networkTransportPolicyManager.setRelayEscalationHandler((()=>{this.network.enforceRelay(12e4),this.triggerRejoinEventIfAppropriate("relay_escalation")})),this.networkTransportPolicyManager.startMonitoring();hi((()=>o(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>o(this,void 0,void 0,(function*(){if(!this.isChannelJoined||this.rejoinRequested||this.state.isChannelJoining)return e();const r=yield this.network.triggerChannelStateEvent("host"),n=setTimeout((()=>{this.eventsQueue.isMessageReceived(r)?(a(this,qg,"f").info("Channel state event received",{case:"Engine.requestChannelStateSync"}),e()):t(new Bt("channel_state_event_not_received",new Error("Channel state event not received")))}),5e3),i=()=>{clearTimeout(n),this.clientEventEmitter.off(tn,i),e()};this.clientEventEmitter.on(tn,i)}))))}))),{minBackoffDelayMs:0,maxBackoffDelayMs:0,maxRetries:10,actionName:"triggerChannelStateEventWithRetry",logger:a(this,qg,"f")}).catch((e=>{(Qn(e)?a(this,qg,"f").debug.bind(a(this,qg,"f")):a(this,qg,"f").error.bind(a(this,qg,"f")))("Failed to request channel state event",{case:"Engine.requestChannelStateSync",error:Vt(e)})}))}))}updateAppData(e){return o(this,void 0,void 0,(function*(){const t=this.myPeer.get();if(!t)throw new Bt("need_joined_to_channel",new Error("Need join to channel first"));try{Xn(e)}catch(e){throw a(this,qg,"f").error("updateAppData() validation failed",{error:e}),new Bt("invalid_app_data",e)}try{yield this.network.updatePeerAppData({peerId:t.id,appData:e})}catch(e){throw(Qn(e)?a(this,qg,"f").debug.bind(a(this,qg,"f")):a(this,qg,"f").error.bind(a(this,qg,"f")))("updateAppData()",{error:Vt(e)}),new Bt("update_app_data_failed",e)}}))}createCameraVideoTrack(e){return o(this,void 0,void 0,(function*(){const t=vm.getCameraVideoTrackParams(e);try{const[r]=yield this.media.createUserMediaTracks({audio:!1,video:t.videoTrackOptions});return r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof im&&(r.setLabel((null==e?void 0:e.isPreview)?exports.TrackLabel.CameraPreview:exports.TrackLabel.Camera),r.setEncoderConfig(t.encoderConfig),r.setTransformParams(vm.getVideoTrackTransformParams(r.mediaStreamTrack))),this.media.setTrack(r),a(this,qg,"f").debug("createCameraVideoTrack()",{trackParams:t}),r}catch(e){throw a(this,qg,"f").error("createCameraVideoTrack()",{error:e,trackParams:t}),new Bt("create_camera_track_failed",e)}}))}createMicrophoneAudioTrack(e){return o(this,void 0,void 0,(function*(){try{const[t]=yield this.media.createUserMediaTracks({video:!1,audio:null==e?void 0:e.audio}),r=(null==e?void 0:e.isPreview)?exports.TrackLabel.MicrophonePreview:exports.TrackLabel.Microphone;return t.setLabel(r),t.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),(null==e?void 0:e.encoderConfig)&&t.setEncoderConfig(e.encoderConfig),"audio"!==t.kind||t.getLabel()!==exports.TrackLabel.Microphone||a(this,Gg,"f")||this.media.initDenoiser(t,e).catch((t=>{this.clientEventEmitter.emit(un,{cause:"Failed to initialize denoiser",error:t}),a(this,qg,"f").error("Failed to execute initDenoiser",{case:"Denoiser",options:e,error:Vt(t)})})),this.media.setTrack(t),a(this,qg,"f").debug("createMicrophoneAudioTrack()",{options:e,trackLabel:t.getLabel()}),t}catch(t){throw a(this,qg,"f").error("createMicrophoneAudioTrack()",{error:t,options:e}),new Bt("create_microphone_track_failed",t)}}))}createScreenMediaTracks(e){return o(this,void 0,void 0,(function*(){const t=vm.getScreenVideoTrackParams(e);try{const r=yield this.media.createDisplayMediaTracks({audio:null==e?void 0:e.audio,video:null==e?void 0:e.video});return r.forEach((r=>{if(r.mediaStreamTrack.addEventListener("ended",(()=>{r.unpublish().catch((e=>{a(this,qg,"f").error("Failed to unpublish screen track",{error:Vt(e)})}))}),{once:!0}),r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof im){r.setLabel(exports.TrackLabel.ScreenVideo),r.setEncoderConfig(t.encoderConfig);const e=vm.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(e),this.media.setTrack(r),void a(this,qg,"f").debug("createScreenMediaTrack()",{trackParams:t,transformParams:e,label:r.logCtx})}r.setLabel(exports.TrackLabel.ScreenAudio),(null==e?void 0:e.audioEncoderConfig)&&r.setEncoderConfig(e.audioEncoderConfig),this.media.setTrack(r),a(this,qg,"f").debug("createScreenMediaTrack()",{trackParams:null==e?void 0:e.audio,encoderConfig:null==e?void 0:e.audioEncoderConfig})})),r}catch(e){throw a(this,qg,"f").error("createScreenMediaTrack()",{error:e,trackParams:t}),new Bt("create_screen_tracks_failed",e)}}))}createCustomAudioTrack(e){if(!e.audioTrack)throw new Bt("missing_audio_track",new Error("options.audioTrack is required"));try{const t=this.media.createCustomMediaTrack(e.audioTrack,{audio:e.audio});return t.mediaStreamTrack.addEventListener("ended",(()=>{t.unpublish().catch((e=>{a(this,qg,"f").error("Failed to unpublish custom audio track",{track:t,error:Vt(e)})}))}),{once:!0}),t.setStopTrackOnPause(Boolean(e.stopTrackOnPause)),t.setLabel(exports.TrackLabel.CustomAudio),e.audioEncoderConfig&&t.setEncoderConfig(e.audioEncoderConfig),this.media.setTrack(t),a(this,qg,"f").debug("createCustomAudioTrack()",{trackParams:e.audio,encoderConfig:e.audioEncoderConfig}),t}catch(t){throw a(this,qg,"f").error("createCustomAudioTrack()",{error:t,trackParams:e.audioTrack}),new Bt("create_custom_audio_track_failed",t)}}createCustomVideoTrack(e){const t=vm.getScreenVideoTrackParams(e);if(!e.videoTrack)throw new Bt("missing_video_track",new Error("options.videoTrack is required"));try{const r=this.media.createCustomMediaTrack(e.videoTrack,{video:e.video});r.mediaStreamTrack.addEventListener("ended",(()=>{r.unpublish().catch((e=>{a(this,qg,"f").error("Failed to unpublish custom video track",{track:r,error:Vt(e)})}))}),{once:!0}),r.mediaStreamTrack.contentHint="customVideo",r.setLabel(exports.TrackLabel.CustomVideo),r.setEncoderConfig(t.encoderConfig);const n=vm.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(n),this.media.setTrack(r),a(this,qg,"f").debug("createCustomVideoTrack()",{trackParams:t,transformParams:n,label:r.logCtx}),r}catch(e){throw a(this,qg,"f").error("createCustomVideoTrack()",{error:e,trackParams:t}),new Bt("create_custom_video_track_failed",e)}}deleteTrack(e){return o(this,void 0,void 0,(function*(){try{yield this.media.deleteTrack(e)}catch(e){throw new Bt("delete_track_failed",e)}}))}transportsStats(){return this.transportsStatsProvider.getStats()}setSignalingServerUrl(e){if(this.isChannelJoined||this.rejoinRequested||this.state.isChannelJoining)throw new Bt("method_not_available_when_joined",new Error("Method not available when joined channel"));this.signalingApiClient.instance.defaults.baseURL=e}cleanup(){var e;this.signalingApiClient.abortPendingRequests("cleanup"),this.rejoinRequested=!1,c(this,zg,!1,"f"),this.networkTransportPolicyManager.stopMonitoring(),this.state.reset(),this.network.reset(),this.peersStorage.clear(),this.transportsStatsProvider.clear(),this.statsHandler.clear(),this.integrationsService.reset(),null===(e=this.webRtcIssueDetector)||void 0===e||e.stopWatchingNewPeerConnections(),this.processorsCache.reset(),this.clientMetaProvider.clear()}watchInternalEvents(){this.internalEventEmitter.on(gn,(e=>o(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.internalEventEmitter.on(vn,(e=>o(this,void 0,void 0,(function*(){var t,r;const n=null===(t=this.myPeer.get())||void 0===t?void 0:t.tracks.get(e.getLabel());null===(r=null==n?void 0:n.close())||void 0===r||r.catch((e=>{a(this,qg,"f").debug("Failed to close peerTrack",{error:Vt(e)})})),yield this.media.deleteTrack(e)})))),this.internalEventEmitter.on(yn,(e=>{var t,r;const n=null===(t=this.myPeer.get())||void 0===t?void 0:t.tracks.get(e.getLabel());null===(r=null==n?void 0:n.pause())||void 0===r||r.catch((e=>{a(this,qg,"f").debug("Failed to pause peerTrack",{error:Vt(e)})}))})),this.internalEventEmitter.on(bn,(e=>{var t,r;const n=null===(t=this.myPeer.get())||void 0===t?void 0:t.tracks.get(e.getLabel());null===(r=null==n?void 0:n.resume())||void 0===r||r.catch((e=>{a(this,qg,"f").debug("Failed to resume peerTrack",{error:Vt(e)})}))})),this.internalEventEmitter.on(_n,(e=>{var t,r;const n=null===(t=this.myPeer.get())||void 0===t?void 0:t.tracks.get(e.getLabel());null===(r=null==n?void 0:n.close())||void 0===r||r.catch((e=>{a(this,qg,"f").debug("Failed to close peerTrack",{error:Vt(e)})}))})),this.internalEventEmitter.on(En,(e=>o(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.internalEventEmitter.on(wn,(e=>{this.clientEventEmitter.safeEmit(Zr,{label:e.getLabel()})}))}createSelfPeerTrack(e){return o(this,void 0,void 0,(function*(){var t;if(!this.myPeer.id)return;const r=this.peers.get(this.myPeer.id);if(!r)return;yield null===(t=r.tracks.get(e.getLabel()))||void 0===t?void 0:t.close();const n=this.peerTrackFactory({label:e.getLabel(),mediaStreamTrack:e.mediaStreamTrack,muted:!1,paused:e.isPaused,onClose:()=>{},peerEventEmitter:r.observer});r.tracks.set(n.label,n)}))}triggerRejoinEventIfAppropriate(e){!this.isChannelJoined||this.isReleasing||this.state.isChannelJoining||this.rejoinRequested||(a(this,qg,"f").info("Triggering channel rejoin required event",{reason:e}),this.signalingApiClient.abortPendingRequests("channel-rejoin"),this.rejoinRequested=!0,this.clientEventEmitter.emit($r))}watchNetworkState(){this.network.observer.on(qn,(({state:e,direction:t})=>{if(!this.isReleasing&&(["disconnected","failed"].includes(e)&&this.isChannelJoined&&!a(this,zg,"f")&&(c(this,zg,!0,"f"),a(this,qg,"f").info("connection lost",{channel:"webrtc-transport",direction:t}),this.clientEventEmitter.safeEmit(tn)),"reconnected"===e&&this.isChannelJoined&&a(this,qg,"f").info("connection restored",{channel:"webrtc-transport",direction:t}),"reconnected"===e&&this.isChannelJoined&&a(this,zg,"f"))){if(![this.network.receiveTransport,this.network.sendTransport].every((e=>"connected"===(null==e?void 0:e.connectionState)||"new"===(null==e?void 0:e.connectionState))))return;c(this,zg,!1,"f"),this.clientEventEmitter.safeEmit(rn),this.producerCloseManager.flushPending().catch((e=>{a(this,qg,"f").warn("Failed to flush pending remote producers",{error:Vt(e)})}))}}))}watchDocumentUnload(){try{window.addEventListener("unload",(()=>{var e,t;null===(e=this.network.sendTransport)||void 0===e||e.close(),null===(t=this.network.receiveTransport)||void 0===t||t.close()}))}catch(e){a(this,qg,"f").error("Failed to add watchDocumentUnload listener",{channelId:this.state.channelId,error:Vt(e)})}}initTransports(){return o(this,void 0,void 0,(function*(){const[e,t]=yield this.createSendRecvTransports();this.registerNewTransports(e,t),yield this.network.initializeHeartbeats();const{isChromiumBased:r}=(e=>{var t;const r=null!=e?e:"undefined"!=typeof navigator?navigator.userAgent:void 0;if(!r)return{isMobile:!1,isChromiumBased:!1};const n=ti.getParser(r),i=n.getPlatformType(!0),s="mobile"===i||"tablet"===i,o=n.getEngineName().toLowerCase(),a=null!==(t=n.satisfies({chrome:">=0",chromium:">=0","chromium webview":">=0",edge:">=0",opera:">=0","opera coast":">=0","samsung internet for android":">=0","yandex browser":">=0",electron:">=0"}))&&void 0!==t&&t;return{isMobile:s,isChromiumBased:"blink"===o||a&&"webkit"!==o}})();r||(yield this.network.createSignalingTransport(this.media.mediasoupDevice),yield this.network.createKeepAliveConsumer()),yield this.network.createAllDataChannels()}))}registerNewTransports(e,t){var r,n;null===(r=this.webRtcIssueDetector)||void 0===r||r.handleNewPeerConnection(e.handler._pc,e.id),null===(n=this.webRtcIssueDetector)||void 0===n||n.handleNewPeerConnection(t.handler._pc,t.id),this.transportsStatsProvider.clear(),this.transportsStatsProvider.init({media:this.media,peers:this.peers,receiveTransportConnectionManager:new yg({transport:t,statsHandler:this.statsHandler}),sendTransportConnectionManager:new yg({transport:e,statsHandler:this.statsHandler})}),this.network.channelMessagesDataConsumer&&this.eventsQueue.subscribe(this.network.channelMessagesDataConsumer)}createSendRecvTransports(){return o(this,void 0,void 0,(function*(){const[e,t]=yield Promise.allSettled([this.network.createSendTransport(this.media.mediasoupDevice),this.network.createRecvTransport(this.media.mediasoupDevice)]);if(("rejected"===e.status||"rejected"===t.status)&&(this.network.closeSendTransport(),this.network.closeReceiveTransport()),"rejected"===e.status)throw new Bt("create_send_transport_failed",e.reason);if("rejected"===t.status)throw new Bt("create_recv_transport_failed",t.reason);return[e.value,t.value]}))}};qg=new WeakMap,zg=new WeakMap,Gg=new WeakMap,Yg=n([ot(),i(0,ct(fi.CallState)),i(1,ct(fi.MyPeer)),i(2,ct(fi.LoggerFactory)),i(3,ct(fi.IntegrationsService)),i(4,ct(fi.ProcessorsCache)),i(5,ct(fi.MediaEventHandler)),i(6,ct(fi.ChannelEventHandler)),i(7,ct(fi.PeerTrackFactory)),i(8,ct(fi.Peers)),i(9,ct(fi.PeersStorage)),i(10,ct(fi.System)),i(11,ct(fi.Media)),i(12,ct(fi.Network)),i(13,ct(fi.NetworkTransportPolicyManager)),i(14,ct(fi.ProducerCloseManager)),i(15,ct(fi.SignalingApiClient)),i(16,ct(fi.EventsQueue)),i(17,ct(fi.ClientEventEmitter)),i(18,ct(fi.InternalEventEmitter)),i(19,ct(fi.StatsHandler)),i(20,ct(fi.TransportsStatsProvider)),i(21,ct(fi.LocalMutex)),i(22,ct(fi.ScoresCalculator)),i(23,ct(fi.ClientMetaProvider)),i(24,ct(fi.WebRTCIssueDetector)),s("design:paramtypes",[mi,ro,Function,Qh,Yh,Wm,Nm,Function,Object,po,vg,vm,uo,ng,eg,ed,eo,Ft,Ft,jg,Vg,hg,exports.ScoresCalculator,Vr,Pr])],Yg);var $g=Yg,Jg="undefined"!=typeof Symbol&&Symbol,Qg=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var n=Object.getOwnPropertySymbols(e);if(1!==n.length||n[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var i=Object.getOwnPropertyDescriptor(e,t);if(42!==i.value||!0!==i.enumerable)return!1}return!0},Kg="Function.prototype.bind called on incompatible ",Zg=Array.prototype.slice,Xg=Object.prototype.toString,ev=function(e){var t=this;if("function"!=typeof t||"[object Function]"!==Xg.call(t))throw new TypeError(Kg+t);for(var r,n=Zg.call(arguments,1),i=function(){if(this instanceof r){var i=t.apply(this,n.concat(Zg.call(arguments)));return Object(i)===i?i:this}return t.apply(e,n.concat(Zg.call(arguments)))},s=Math.max(0,t.length-n.length),o=[],a=0;a<s;a++)o.push("$"+a);if(r=Function("binder","return function ("+o.join(",")+"){ return binder.apply(this,arguments); }")(i),t.prototype){var c=function(){};c.prototype=t.prototype,r.prototype=new c,c.prototype=null}return r},tv=Function.prototype.bind||ev,rv="Function.prototype.bind called on incompatible ",nv=Array.prototype.slice,iv=Object.prototype.toString,sv=function(e){var t=this;if("function"!=typeof t||"[object Function]"!==iv.call(t))throw new TypeError(rv+t);for(var r,n=nv.call(arguments,1),i=function(){if(this instanceof r){var i=t.apply(this,n.concat(nv.call(arguments)));return Object(i)===i?i:this}return t.apply(e,n.concat(nv.call(arguments)))},s=Math.max(0,t.length-n.length),o=[],a=0;a<s;a++)o.push("$"+a);if(r=Function("binder","return function ("+o.join(",")+"){ return binder.apply(this,arguments); }")(i),t.prototype){var c=function(){};c.prototype=t.prototype,r.prototype=new c,c.prototype=null}return r},ov=(Function.prototype.bind||sv).call(Function.call,Object.prototype.hasOwnProperty),av=SyntaxError,cv=Function,dv=TypeError,uv=function(e){try{return cv('"use strict"; return ('+e+").constructor;")()}catch(e){}},lv=Object.getOwnPropertyDescriptor;if(lv)try{lv({},"")}catch(Ht){lv=null}var pv=function(){throw new dv},hv=lv?function(){try{return pv}catch(e){try{return lv(arguments,"callee").get}catch(e){return pv}}}():pv,fv="function"==typeof Jg&&"function"==typeof Symbol&&"symbol"==typeof Jg("foo")&&"symbol"==typeof Symbol("bar")&&Qg(),mv=Object.getPrototypeOf||function(e){return e.__proto__},gv={},vv="undefined"==typeof Uint8Array?undefined:mv(Uint8Array),yv={"%AggregateError%":"undefined"==typeof AggregateError?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":fv?mv([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":gv,"%AsyncGenerator%":gv,"%AsyncGeneratorFunction%":gv,"%AsyncIteratorPrototype%":gv,"%Atomics%":"undefined"==typeof Atomics?undefined:Atomics,"%BigInt%":"undefined"==typeof BigInt?undefined:BigInt,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?undefined:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?undefined:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?undefined:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?undefined:FinalizationRegistry,"%Function%":cv,"%GeneratorFunction%":gv,"%Int8Array%":"undefined"==typeof Int8Array?undefined:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":fv?mv(mv([][Symbol.iterator]())):undefined,"%JSON%":"object"==typeof JSON?JSON:undefined,"%Map%":"undefined"==typeof Map?undefined:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&fv?mv((new Map)[Symbol.iterator]()):undefined,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?undefined:Promise,"%Proxy%":"undefined"==typeof Proxy?undefined:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?undefined:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?undefined:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&fv?mv((new Set)[Symbol.iterator]()):undefined,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":fv?mv(""[Symbol.iterator]()):undefined,"%Symbol%":fv?Symbol:undefined,"%SyntaxError%":av,"%ThrowTypeError%":hv,"%TypedArray%":vv,"%TypeError%":dv,"%Uint8Array%":"undefined"==typeof Uint8Array?undefined:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?undefined:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?undefined:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?undefined:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?undefined:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?undefined:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?undefined:WeakSet},bv=function e(t){var r;if("%AsyncFunction%"===t)r=uv("async function () {}");else if("%GeneratorFunction%"===t)r=uv("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=uv("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&(r=mv(i.prototype))}return yv[t]=r,r},_v={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},Ev=tv,wv=ov,Sv=Ev.call(Function.call,Array.prototype.concat),Cv=Ev.call(Function.apply,Array.prototype.splice),Pv=Ev.call(Function.call,String.prototype.replace),Tv=Ev.call(Function.call,String.prototype.slice),Rv=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,kv=/\\(\\)?/g,Dv=function(e){var t=Tv(e,0,1),r=Tv(e,-1);if("%"===t&&"%"!==r)throw new av("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new av("invalid intrinsic syntax, expected opening `%`");var n=[];return Pv(e,Rv,(function(e,t,r,i){n[n.length]=r?Pv(i,kv,"$1"):t||e})),n},Iv=function(e,t){var r,n=e;if(wv(_v,n)&&(n="%"+(r=_v[n])[0]+"%"),wv(yv,n)){var i=yv[n];if(i===gv&&(i=bv(n)),void 0===i&&!t)throw new dv("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:i}}throw new av("intrinsic "+e+" does not exist!")},Av=function(e,t){if("string"!=typeof e||0===e.length)throw new dv("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new dv('"allowMissing" argument must be a boolean');var r=Dv(e),n=r.length>0?r[0]:"",i=Iv("%"+n+"%",t),s=i.name,o=i.value,a=!1,c=i.alias;c&&(n=c[0],Cv(r,Sv([0,1],c)));for(var d=1,u=!0;d<r.length;d+=1){var l=r[d],p=Tv(l,0,1),h=Tv(l,-1);if(('"'===p||"'"===p||"`"===p||'"'===h||"'"===h||"`"===h)&&p!==h)throw new av("property names with quotes must have matching quotes");if("constructor"!==l&&u||(a=!0),wv(yv,s="%"+(n+="."+l)+"%"))o=yv[s];else if(null!=o){if(!(l in o)){if(!t)throw new dv("base intrinsic for "+e+" exists, but the property is not available.");return}if(lv&&d+1>=r.length){var f=lv(o,l);o=(u=!!f)&&"get"in f&&!("originalValue"in f.get)?f.get:o[l]}else u=wv(o,l),o=o[l];u&&!a&&(yv[s]=o)}}return o},Ov={exports:{}};!function(e){var t=tv,r=Av,n=r("%Function.prototype.apply%"),i=r("%Function.prototype.call%"),s=r("%Reflect.apply%",!0)||t.call(i,n),o=r("%Object.getOwnPropertyDescriptor%",!0),a=r("%Object.defineProperty%",!0),c=r("%Math.max%");if(a)try{a({},"a",{value:1})}catch(e){a=null}e.exports=function(e){var r=s(t,i,arguments);if(o&&a){var n=o(r,"length");n.configurable&&a(r,"length",{value:1+c(0,e.length-(arguments.length-1))})}return r};var d=function(){return s(t,n,arguments)};a?a(e.exports,"apply",{value:d}):e.exports.apply=d}(Ov);var Mv=Av,Nv=Ov.exports,Lv=Nv(Mv("String.prototype.indexOf")),xv=p(Object.freeze({__proto__:null,default:{}})),Fv="function"==typeof Map&&Map.prototype,jv=Object.getOwnPropertyDescriptor&&Fv?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Uv=Fv&&jv&&"function"==typeof jv.get?jv.get:null,Vv=Fv&&Map.prototype.forEach,Bv="function"==typeof Set&&Set.prototype,Wv=Object.getOwnPropertyDescriptor&&Bv?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,Hv=Bv&&Wv&&"function"==typeof Wv.get?Wv.get:null,qv=Bv&&Set.prototype.forEach,zv="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,Gv="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,Yv="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,$v=Boolean.prototype.valueOf,Jv=Object.prototype.toString,Qv=Function.prototype.toString,Kv=String.prototype.match,Zv="function"==typeof BigInt?BigInt.prototype.valueOf:null,Xv=Object.getOwnPropertySymbols,ey="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,ty="function"==typeof Symbol&&"object"==typeof Symbol.iterator,ry=Object.prototype.propertyIsEnumerable,ny=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null),iy=xv.custom,sy=iy&&uy(iy)?iy:null,oy="function"==typeof Symbol&&void 0!==Symbol.toStringTag?Symbol.toStringTag:null;function ay(e,t,r){var n="double"===(r.quoteStyle||t)?'"':"'";return n+e+n}function cy(e){return String(e).replace(/"/g,"&quot;")}function dy(e){return!("[object Array]"!==hy(e)||oy&&"object"==typeof e&&oy in e)}function uy(e){if(ty)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!ey)return!1;try{return ey.call(e),!0}catch(e){}return!1}var ly=Object.prototype.hasOwnProperty||function(e){return e in this};function py(e,t){return ly.call(e,t)}function hy(e){return Jv.call(e)}function fy(e,t){if(e.indexOf)return e.indexOf(t);for(var r=0,n=e.length;r<n;r++)if(e[r]===t)return r;return-1}function my(e,t){if(e.length>t.maxStringLength){var r=e.length-t.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return my(e.slice(0,t.maxStringLength),t)+n}return ay(e.replace(/(['\\])/g,"\\$1").replace(/[\x00-\x1f]/g,gy),"single",t)}function gy(e){var t=e.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return r?"\\"+r:"\\x"+(t<16?"0":"")+t.toString(16).toUpperCase()}function vy(e){return"Object("+e+")"}function yy(e){return e+" { ? }"}function by(e,t,r,n){return e+" ("+t+") {"+(n?_y(r,n):r.join(", "))+"}"}function _y(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+e.join(","+r)+"\n"+t.prev}function Ey(e,t){var r=dy(e),n=[];if(r){n.length=e.length;for(var i=0;i<e.length;i++)n[i]=py(e,i)?t(e[i],e):""}var s,o="function"==typeof Xv?Xv(e):[];if(ty){s={};for(var a=0;a<o.length;a++)s["$"+o[a]]=o[a]}for(var c in e)py(e,c)&&(r&&String(Number(c))===c&&c<e.length||ty&&s["$"+c]instanceof Symbol||(/[^\w$]/.test(c)?n.push(t(c,e)+": "+t(e[c],e)):n.push(c+": "+t(e[c],e))));if("function"==typeof Xv)for(var d=0;d<o.length;d++)ry.call(e,o[d])&&n.push("["+t(o[d])+"]: "+t(e[o[d]],e));return n}var wy=Av,Sy=function(e,t){var r=Mv(e,!!t);return"function"==typeof r&&Lv(e,".prototype.")>-1?Nv(r):r},Cy=function e(t,r,n,i){var s=r||{};if(py(s,"quoteStyle")&&"single"!==s.quoteStyle&&"double"!==s.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(py(s,"maxStringLength")&&("number"==typeof s.maxStringLength?s.maxStringLength<0&&s.maxStringLength!==1/0:null!==s.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var o=!py(s,"customInspect")||s.customInspect;if("boolean"!=typeof o&&"symbol"!==o)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(py(s,"indent")&&null!==s.indent&&"\t"!==s.indent&&!(parseInt(s.indent,10)===s.indent&&s.indent>0))throw new TypeError('options "indent" must be "\\t", an integer > 0, or `null`');if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return my(t,s);if("number"==typeof t)return 0===t?1/0/t>0?"0":"-0":String(t);if("bigint"==typeof t)return String(t)+"n";var a=void 0===s.depth?5:s.depth;if(void 0===n&&(n=0),n>=a&&a>0&&"object"==typeof t)return dy(t)?"[Array]":"[Object]";var c=function(e,t){var r;if("\t"===e.indent)r="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;r=Array(e.indent+1).join(" ")}return{base:r,prev:Array(t+1).join(r)}}(s,n);if(void 0===i)i=[];else if(fy(i,t)>=0)return"[Circular]";function d(t,r,o){if(r&&(i=i.slice()).push(r),o){var a={depth:s.depth};return py(s,"quoteStyle")&&(a.quoteStyle=s.quoteStyle),e(t,a,n+1,i)}return e(t,s,n+1,i)}if("function"==typeof t){var u=function(e){if(e.name)return e.name;var t=Kv.call(Qv.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),l=Ey(t,d);return"[Function"+(u?": "+u:" (anonymous)")+"]"+(l.length>0?" { "+l.join(", ")+" }":"")}if(uy(t)){var p=ty?String(t).replace(/^(Symbol\(.*\))_[^)]*$/,"$1"):ey.call(t);return"object"!=typeof t||ty?p:vy(p)}if(function(e){if(!e||"object"!=typeof e)return!1;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return!0;return"string"==typeof e.nodeName&&"function"==typeof e.getAttribute}(t)){for(var h="<"+String(t.nodeName).toLowerCase(),f=t.attributes||[],m=0;m<f.length;m++)h+=" "+f[m].name+"="+ay(cy(f[m].value),"double",s);return h+=">",t.childNodes&&t.childNodes.length&&(h+="..."),h+="</"+String(t.nodeName).toLowerCase()+">"}if(dy(t)){if(0===t.length)return"[]";var g=Ey(t,d);return c&&!function(e){for(var t=0;t<e.length;t++)if(fy(e[t],"\n")>=0)return!1;return!0}(g)?"["+_y(g,c)+"]":"[ "+g.join(", ")+" ]"}if(function(e){return!("[object Error]"!==hy(e)||oy&&"object"==typeof e&&oy in e)}(t)){var v=Ey(t,d);return 0===v.length?"["+String(t)+"]":"{ ["+String(t)+"] "+v.join(", ")+" }"}if("object"==typeof t&&o){if(sy&&"function"==typeof t[sy])return t[sy]();if("symbol"!==o&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Uv||!e||"object"!=typeof e)return!1;try{Uv.call(e);try{Hv.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var y=[];return Vv.call(t,(function(e,r){y.push(d(r,t,!0)+" => "+d(e,t))})),by("Map",Uv.call(t),y,c)}if(function(e){if(!Hv||!e||"object"!=typeof e)return!1;try{Hv.call(e);try{Uv.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var b=[];return qv.call(t,(function(e){b.push(d(e,t))})),by("Set",Hv.call(t),b,c)}if(function(e){if(!zv||!e||"object"!=typeof e)return!1;try{zv.call(e,zv);try{Gv.call(e,Gv)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return yy("WeakMap");if(function(e){if(!Gv||!e||"object"!=typeof e)return!1;try{Gv.call(e,Gv);try{zv.call(e,zv)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return yy("WeakSet");if(function(e){if(!Yv||!e||"object"!=typeof e)return!1;try{return Yv.call(e),!0}catch(e){}return!1}(t))return yy("WeakRef");if(function(e){return!("[object Number]"!==hy(e)||oy&&"object"==typeof e&&oy in e)}(t))return vy(d(Number(t)));if(function(e){if(!e||"object"!=typeof e||!Zv)return!1;try{return Zv.call(e),!0}catch(e){}return!1}(t))return vy(d(Zv.call(t)));if(function(e){return!("[object Boolean]"!==hy(e)||oy&&"object"==typeof e&&oy in e)}(t))return vy($v.call(t));if(function(e){return!("[object String]"!==hy(e)||oy&&"object"==typeof e&&oy in e)}(t))return vy(d(String(t)));if(!function(e){return!("[object Date]"!==hy(e)||oy&&"object"==typeof e&&oy in e)}(t)&&!function(e){return!("[object RegExp]"!==hy(e)||oy&&"object"==typeof e&&oy in e)}(t)){var _=Ey(t,d),E=ny?ny(t)===Object.prototype:t instanceof Object||t.constructor===Object,w=t instanceof Object?"":"null prototype",S=!E&&oy&&Object(t)===t&&oy in t?hy(t).slice(8,-1):w?"Object":"",C=(E||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(S||w?"["+[].concat(S||[],w||[]).join(": ")+"] ":"");return 0===_.length?C+"{}":c?C+"{"+_y(_,c)+"}":C+"{ "+_.join(", ")+" }"}return String(t)},Py=wy("%TypeError%"),Ty=wy("%WeakMap%",!0),Ry=wy("%Map%",!0),ky=Sy("WeakMap.prototype.get",!0),Dy=Sy("WeakMap.prototype.set",!0),Iy=Sy("WeakMap.prototype.has",!0),Ay=Sy("Map.prototype.get",!0),Oy=Sy("Map.prototype.set",!0),My=Sy("Map.prototype.has",!0),Ny=function(e,t){for(var r,n=e;null!==(r=n.next);n=r)if(r.key===t)return n.next=r.next,r.next=e.next,e.next=r,r},Ly=String.prototype.replace,xy=/%20/g,Fy="RFC3986",jy={default:Fy,formatters:{RFC1738:function(e){return Ly.call(e,xy,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:Fy},Uy=jy,Vy=Object.prototype.hasOwnProperty,By=Array.isArray,Wy=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),Hy=function(e,t){for(var r=t&&t.plainObjects?Object.create(null):{},n=0;n<e.length;++n)void 0!==e[n]&&(r[n]=e[n]);return r},qy={arrayToObject:Hy,assign:function(e,t){return Object.keys(t).reduce((function(e,r){return e[r]=t[r],e}),e)},combine:function(e,t){return[].concat(e,t)},compact:function(e){for(var t=[{obj:{o:e},prop:"o"}],r=[],n=0;n<t.length;++n)for(var i=t[n],s=i.obj[i.prop],o=Object.keys(s),a=0;a<o.length;++a){var c=o[a],d=s[c];"object"==typeof d&&null!==d&&-1===r.indexOf(d)&&(t.push({obj:s,prop:c}),r.push(d))}return function(e){for(;e.length>1;){var t=e.pop(),r=t.obj[t.prop];if(By(r)){for(var n=[],i=0;i<r.length;++i)void 0!==r[i]&&n.push(r[i]);t.obj[t.prop]=n}}}(t),e},decode:function(e,t,r){var n=e.replace(/\+/g," ");if("iso-8859-1"===r)return n.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(n)}catch(e){return n}},encode:function(e,t,r,n,i){if(0===e.length)return e;var s=e;if("symbol"==typeof e?s=Symbol.prototype.toString.call(e):"string"!=typeof e&&(s=String(e)),"iso-8859-1"===r)return escape(s).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));for(var o="",a=0;a<s.length;++a){var c=s.charCodeAt(a);45===c||46===c||95===c||126===c||c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||i===Uy.RFC1738&&(40===c||41===c)?o+=s.charAt(a):c<128?o+=Wy[c]:c<2048?o+=Wy[192|c>>6]+Wy[128|63&c]:c<55296||c>=57344?o+=Wy[224|c>>12]+Wy[128|c>>6&63]+Wy[128|63&c]:(a+=1,c=65536+((1023&c)<<10|1023&s.charCodeAt(a)),o+=Wy[240|c>>18]+Wy[128|c>>12&63]+Wy[128|c>>6&63]+Wy[128|63&c])}return o},isBuffer:function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(By(e)){for(var r=[],n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)},merge:function e(t,r,n){if(!r)return t;if("object"!=typeof r){if(By(t))t.push(r);else{if(!t||"object"!=typeof t)return[t,r];(n&&(n.plainObjects||n.allowPrototypes)||!Vy.call(Object.prototype,r))&&(t[r]=!0)}return t}if(!t||"object"!=typeof t)return[t].concat(r);var i=t;return By(t)&&!By(r)&&(i=Hy(t,n)),By(t)&&By(r)?(r.forEach((function(r,i){if(Vy.call(t,i)){var s=t[i];s&&"object"==typeof s&&r&&"object"==typeof r?t[i]=e(s,r,n):t.push(r)}else t[i]=r})),t):Object.keys(r).reduce((function(t,i){var s=r[i];return Vy.call(t,i)?t[i]=e(t[i],s,n):t[i]=s,t}),i)}},zy=function(){var e,t,r,n={assert:function(e){if(!n.has(e))throw new Py("Side channel does not contain "+Cy(e))},get:function(n){if(Ty&&n&&("object"==typeof n||"function"==typeof n)){if(e)return ky(e,n)}else if(Ry){if(t)return Ay(t,n)}else if(r)return function(e,t){var r=Ny(e,t);return r&&r.value}(r,n)},has:function(n){if(Ty&&n&&("object"==typeof n||"function"==typeof n)){if(e)return Iy(e,n)}else if(Ry){if(t)return My(t,n)}else if(r)return function(e,t){return!!Ny(e,t)}(r,n);return!1},set:function(n,i){Ty&&n&&("object"==typeof n||"function"==typeof n)?(e||(e=new Ty),Dy(e,n,i)):Ry?(t||(t=new Ry),Oy(t,n,i)):(r||(r={key:{},next:null}),function(e,t,r){var n=Ny(e,t);n?n.value=r:e.next={key:t,next:e.next,value:r}}(r,n,i))}};return n},Gy=qy,Yy=jy,$y=Object.prototype.hasOwnProperty,Jy={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},Qy=Array.isArray,Ky=String.prototype.split,Zy=Array.prototype.push,Xy=function(e,t){Zy.apply(e,Qy(t)?t:[t])},eb=Date.prototype.toISOString,tb=Yy.default,rb={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:Gy.encode,encodeValuesOnly:!1,format:tb,formatter:Yy.formatters[tb],indices:!1,serializeDate:function(e){return eb.call(e)},skipNulls:!1,strictNullHandling:!1},nb={},ib=function e(t,r,n,i,s,o,a,c,d,u,l,p,h,f,m,g){for(var v=t,y=g,b=0,_=!1;void 0!==(y=y.get(nb))&&!_;){var E=y.get(t);if(b+=1,void 0!==E){if(E===b)throw new RangeError("Cyclic object value");_=!0}void 0===y.get(nb)&&(b=0)}if("function"==typeof c?v=c(r,v):v instanceof Date?v=l(v):"comma"===n&&Qy(v)&&(v=Gy.maybeMap(v,(function(e){return e instanceof Date?l(e):e}))),null===v){if(s)return a&&!f?a(r,rb.encoder,m,"key",p):r;v=""}if(function(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e||"symbol"==typeof e||"bigint"==typeof e}(v)||Gy.isBuffer(v)){if(a){var w=f?r:a(r,rb.encoder,m,"key",p);if("comma"===n&&f){for(var S=Ky.call(String(v),","),C="",P=0;P<S.length;++P)C+=(0===P?"":",")+h(a(S[P],rb.encoder,m,"value",p));return[h(w)+(i&&Qy(v)&&1===S.length?"[]":"")+"="+C]}return[h(w)+"="+h(a(v,rb.encoder,m,"value",p))]}return[h(r)+"="+h(String(v))]}var T,R=[];if(void 0===v)return R;if("comma"===n&&Qy(v))T=[{value:v.length>0?v.join(",")||null:void 0}];else if(Qy(c))T=c;else{var k=Object.keys(v);T=d?k.sort(d):k}for(var D=i&&Qy(v)&&1===v.length?r+"[]":r,I=0;I<T.length;++I){var A=T[I],O="object"==typeof A&&void 0!==A.value?A.value:v[A];if(!o||null!==O){var M=Qy(v)?"function"==typeof n?n(D,A):D:D+(u?"."+A:"["+A+"]");g.set(t,b);var N=zy();N.set(nb,g),Xy(R,e(O,M,n,i,s,o,a,c,d,u,l,p,h,f,m,N))}}return R},sb=qy,ob=Object.prototype.hasOwnProperty,ab=Array.isArray,cb={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:sb.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},db=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},ub=function(e,t){return e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1?e.split(","):e},lb=function(e,t,r,n){if(e){var i=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,s=/(\[[^[\]]*])/g,o=r.depth>0&&/(\[[^[\]]*])/.exec(i),a=o?i.slice(0,o.index):i,c=[];if(a){if(!r.plainObjects&&ob.call(Object.prototype,a)&&!r.allowPrototypes)return;c.push(a)}for(var d=0;r.depth>0&&null!==(o=s.exec(i))&&d<r.depth;){if(d+=1,!r.plainObjects&&ob.call(Object.prototype,o[1].slice(1,-1))&&!r.allowPrototypes)return;c.push(o[1])}return o&&c.push("["+i.slice(o.index)+"]"),function(e,t,r,n){for(var i=n?t:ub(t,r),s=e.length-1;s>=0;--s){var o,a=e[s];if("[]"===a&&r.parseArrays)o=[].concat(i);else{o=r.plainObjects?Object.create(null):{};var c="["===a.charAt(0)&&"]"===a.charAt(a.length-1)?a.slice(1,-1):a,d=parseInt(c,10);r.parseArrays||""!==c?!isNaN(d)&&a!==c&&String(d)===c&&d>=0&&r.parseArrays&&d<=r.arrayLimit?(o=[])[d]=i:"__proto__"!==c&&(o[c]=i):o={0:i}}i=o}return i}(c,t,r,n)}},pb=function(e,t){var r,n=e,i=function(e){if(!e)return rb;if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||rb.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var r=Yy.default;if(void 0!==e.format){if(!$y.call(Yy.formatters,e.format))throw new TypeError("Unknown format option provided.");r=e.format}var n=Yy.formatters[r],i=rb.filter;return("function"==typeof e.filter||Qy(e.filter))&&(i=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:rb.addQueryPrefix,allowDots:void 0===e.allowDots?rb.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:rb.charsetSentinel,delimiter:void 0===e.delimiter?rb.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:rb.encode,encoder:"function"==typeof e.encoder?e.encoder:rb.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:rb.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:rb.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:rb.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:rb.strictNullHandling}}(t);"function"==typeof i.filter?n=(0,i.filter)("",n):Qy(i.filter)&&(r=i.filter);var s,o=[];if("object"!=typeof n||null===n)return"";s=t&&t.arrayFormat in Jy?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var a=Jy[s];if(t&&"commaRoundTrip"in t&&"boolean"!=typeof t.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var c="comma"===a&&t&&t.commaRoundTrip;r||(r=Object.keys(n)),i.sort&&r.sort(i.sort);for(var d=zy(),u=0;u<r.length;++u){var l=r[u];i.skipNulls&&null===n[l]||Xy(o,ib(n[l],l,a,c,i.strictNullHandling,i.skipNulls,i.encode?i.encoder:null,i.filter,i.sort,i.allowDots,i.serializeDate,i.format,i.formatter,i.encodeValuesOnly,i.charset,d))}var p=o.join(i.delimiter),h=!0===i.addQueryPrefix?"?":"";return i.charsetSentinel&&("iso-8859-1"===i.charset?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),p.length>0?h+p:""},hb=function(e,t){var r=function(e){if(!e)return cb;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?cb.charset:e.charset;return{allowDots:void 0===e.allowDots?cb.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:cb.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:cb.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:cb.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:cb.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:cb.comma,decoder:"function"==typeof e.decoder?e.decoder:cb.decoder,delimiter:"string"==typeof e.delimiter||sb.isRegExp(e.delimiter)?e.delimiter:cb.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:cb.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:cb.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:cb.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:cb.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:cb.strictNullHandling}}(t);if(""===e||null==e)return r.plainObjects?Object.create(null):{};for(var n="string"==typeof e?function(e,t){var r,n={},i=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,s=t.parameterLimit===1/0?void 0:t.parameterLimit,o=i.split(t.delimiter,s),a=-1,c=t.charset;if(t.charsetSentinel)for(r=0;r<o.length;++r)0===o[r].indexOf("utf8=")&&("utf8=%E2%9C%93"===o[r]?c="utf-8":"utf8=%26%2310003%3B"===o[r]&&(c="iso-8859-1"),a=r,r=o.length);for(r=0;r<o.length;++r)if(r!==a){var d,u,l=o[r],p=l.indexOf("]="),h=-1===p?l.indexOf("="):p+1;-1===h?(d=t.decoder(l,cb.decoder,c,"key"),u=t.strictNullHandling?null:""):(d=t.decoder(l.slice(0,h),cb.decoder,c,"key"),u=sb.maybeMap(ub(l.slice(h+1),t),(function(e){return t.decoder(e,cb.decoder,c,"value")}))),u&&t.interpretNumericEntities&&"iso-8859-1"===c&&(u=db(u)),l.indexOf("[]=")>-1&&(u=ab(u)?[u]:u),ob.call(n,d)?n[d]=sb.combine(n[d],u):n[d]=u}return n}(e,r):e,i=r.plainObjects?Object.create(null):{},s=Object.keys(n),o=0;o<s.length;++o){var a=s[o],c=lb(a,n[a],r,"string"==typeof e);i=sb.merge(i,c,r)}return!0===r.allowSparse?i:sb.compact(i)},fb={formats:jy,parse:hb,stringify:pb};class mb{constructor(e){this.api=e,Ro(this.api,{retries:2,shouldResetTimeout:!0,retryDelay:e=>1500*e,retryCondition:e=>{var t,r;return/^\/?log\//.test(null!==(r=null===(t=e.config)||void 0===t?void 0:t.url)&&void 0!==r?r:"")||!1}})}batch(e){return o(this,void 0,void 0,(function*(){try{if("undefined"!=typeof CompressionStream){const t=yield function(e){return o(this,void 0,void 0,(function*(){const t=new Blob([e]).stream().pipeThrough(new CompressionStream("gzip"));return yield new Response(t).arrayBuffer()}))}(JSON.stringify(e));return void(yield this.api.post("/log/batch",t,{headers:{"Content-Encoding":"gzip","Content-Type":"application/json"}}))}yield this.api.post("/log/batch",e)}catch(e){console.info("Failed to send logs batch",e)}}))}}class gb{constructor(e){this.api=e,Ro(this.api,{retries:2,shouldResetTimeout:!0,retryDelay:e=>1500*e,retryCondition:e=>{var t,r;return/^\/?log\//.test(null!==(r=null===(t=e.config)||void 0===t?void 0:t.url)&&void 0!==r?r:"")||!1}})}sendNetworkMetrics(e){return o(this,void 0,void 0,(function*(){yield this.api.post("/analytics/network-metrics",e)}))}sendWIDMetrics(e){return o(this,void 0,void 0,(function*(){yield this.api.post("/analytics/wid-metrics",Object.assign({},e))}))}}let vb=class{constructor(e){this.api=Bc.create({baseURL:e,timeout:1e4,withCredentials:!0,paramsSerializer:e=>fb.stringify(e),headers:{"x-cl-id":Mr()}}),this.api.defaults.headers.common["Cache-Control"]="no-cache",this.api.defaults.headers.common.Pragma="no-cache",this.api.defaults.headers.common.Expires="0",this.logApi=new mb(this.api),this.metricsApi=new gb(this.api)}get log(){return this.logApi}get metrics(){return this.metricsApi}};vb=n([ot(),s("design:paramtypes",[String])],vb);var yb,bb,_b=vb;class Eb extends Gn{constructor(e,t,r){super(null!=e?e:Eb.DEFAULT_MESSAGE,null!=t?t:"invalid_payload",r)}}Eb.DEFAULT_MESSAGE="Invalid payload",function(e){e.DominantSpeaker="dominant-speaker",e.PeersVolumes="peers-volumes",e.Silence="silence"}(yb||(yb={}));let wb=class{constructor(e,t){this.peersStorage=e,bb.set(this,void 0),c(this,bb,t("ChannelAudioObserverMissingProducerRestorer"),"f")}handlePeerVolume(e){const{peerId:t,producerId:r}=e,n=this.peersStorage.get(t);if(!n)return;if(n.producers.has(r))return;const i={id:r,kind:"audio",peerId:t,label:exports.TrackLabel.Microphone,paused:!1,encodings:xh,maxSpatialLayer:0};n.observer.safeEmit(Ln,i),a(this,bb,"f").warn("Recovered missing audio producer from audio observer volume",{peerId:t,producerId:r})}};bb=new WeakMap,wb=n([ot(),i(0,ct(fi.PeersStorage)),i(1,ct(fi.LoggerFactory)),s("design:paramtypes",[po,Function])],wb);var Sb,Cb,Pb,Tb,Rb,kb=wb;let Db=Rb=class{constructor(e,t,r,n){this.peersStorage=e,this.clientEventEmitter=t,this.channelAudioObserverMissingProducerRestorer=r,Sb.set(this,void 0),Cb.set(this,void 0),Pb.set(this,void 0),Tb.set(this,void 0),c(this,Sb,n("ChannelAudioObserverEventHandler"),"f"),this.watchPeersLeave()}handle(e){try{const t=JSON.parse(e);switch(Rb.validateEventPayload(t),t.event){case yb.DominantSpeaker:this.handleDominantSpeaker(t);break;case yb.PeersVolumes:this.handlePeerVolumes(t);break;case yb.Silence:this.handleSilence()}}catch(t){a(this,Sb,"f").warn("Failed to handle audio observer event",{error:Vt(t),eventData:e})}}handleDominantSpeaker(e){const{peerId:t}=e.data,r=this.peersStorage.get(t);c(this,Pb,r,"f"),c(this,Tb,r,"f"),this.setActiveSpeaker(r)}handlePeerVolumes(e){e.volumes.forEach((e=>{var t;const{peerId:r,trackLabel:n,value:i}=e,s=this.peersStorage.get(r);if(!s)return;i>0&&!a(this,Pb,"f")&&s.id===(null===(t=a(this,Tb,"f"))||void 0===t?void 0:t.id)&&(c(this,Pb,s,"f"),this.setActiveSpeaker(s));const o=null==s?void 0:s.tracks.get(n);o&&o.setVolume(i)}))}handleSilence(){this.peersStorage.all().flatMap((e=>Array.from(e.tracks.values()))).forEach((e=>e.setVolume(0))),c(this,Pb,void 0,"f"),this.setActiveSpeaker(void 0)}watchPeersLeave(){this.clientEventEmitter.on(qr,(e=>{var t;e===(null===(t=a(this,Pb,"f"))||void 0===t?void 0:t.id)&&this.setActiveSpeaker(void 0)}))}setActiveSpeaker(e){a(this,Cb,"f")!==(null==e?void 0:e.id)&&(c(this,Cb,null==e?void 0:e.id,"f"),this.clientEventEmitter.safeEmit(Xr,{peer:e}))}static validateEventPayload(e){switch(e.event){case yb.Silence:break;case yb.DominantSpeaker:{e.data||Rb.throwInvalidPayload();const{peerId:t,producerId:r,trackLabel:n}=e.data;"string"==typeof t&&"string"==typeof r&&n===exports.TrackLabel.Microphone||Rb.throwInvalidPayload();break}case yb.PeersVolumes:Array.isArray(e.volumes)||Rb.throwInvalidPayload(),e.volumes.forEach((e=>{const{peerId:t,producerId:r,value:n,trackLabel:i}=e;"string"==typeof t&&"string"==typeof r&&"number"==typeof n&&i===exports.TrackLabel.Microphone||Rb.throwInvalidPayload()}));break;default:Rb.throwInvalidPayload()}}static throwInvalidPayload(){throw new Eb("invalid_channel_audio_observer_payload")}};Sb=new WeakMap,Cb=new WeakMap,Pb=new WeakMap,Tb=new WeakMap,Db=Rb=n([ot(),i(0,ct(fi.PeersStorage)),i(1,ct(fi.ClientEventEmitter)),i(2,ct(fi.ChannelAudioObserverMissingProducerRestorer)),i(3,ct(fi.LoggerFactory)),s("design:paramtypes",[po,Ft,kb,Function])],Db);var Ib=Db,Ab={},Ob={},Mb={},Nb={exports:{}};
29
+ ***************************************************************************** */!function(e){!function(t){var r="object"==typeof globalThis?globalThis:"object"==typeof u?u:"object"==typeof self?self:"object"==typeof this?this:function(){try{return Function("return this;")()}catch(e){}}()||function(){try{return(0,eval)("(function() { return this; })()")}catch(e){}}(),n=i(e);function i(e,t){return function(r,n){Object.defineProperty(e,r,{configurable:!0,writable:!0,value:n}),t&&t(r,n)}}void 0!==r.Reflect&&(n=i(r.Reflect,n)),function(e,t){var r=Object.prototype.hasOwnProperty,n="function"==typeof Symbol,i=n&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",s=n&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",o="function"==typeof Object.create,a={__proto__:[]}instanceof Array,c=!o&&!a,d={create:o?function(){return le(Object.create(null))}:a?function(){return le({__proto__:null})}:function(){return le({})},has:c?function(e,t){return r.call(e,t)}:function(e,t){return t in e},get:c?function(e,t){return r.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},u=Object.getPrototypeOf(Function),l="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:ce(),p="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:de(),h="function"==typeof WeakMap?WeakMap:ue(),f=n?Symbol.for("@reflect-metadata:registry"):void 0,m=ie(),g=se(m);function v(e,t,r,n){if(F(r)){if(!G(e))throw new TypeError;if(!$(t))throw new TypeError;return R(e,t)}if(!G(e))throw new TypeError;if(!V(t))throw new TypeError;if(!V(n)&&!F(n)&&!j(n))throw new TypeError;return j(n)&&(n=void 0),k(e,t,r=z(r),n)}function y(e,t){function r(r,n){if(!V(r))throw new TypeError;if(!F(n)&&!K(n))throw new TypeError;M(e,t,r,n)}return r}function b(e,t,r,n){if(!V(r))throw new TypeError;return F(n)||(n=z(n)),M(e,t,r,n)}function _(e,t,r){if(!V(t))throw new TypeError;return F(r)||(r=z(r)),D(e,t,r)}function E(e,t,r){if(!V(t))throw new TypeError;return F(r)||(r=z(r)),I(e,t,r)}function w(e,t,r){if(!V(t))throw new TypeError;return F(r)||(r=z(r)),A(e,t,r)}function S(e,t,r){if(!V(t))throw new TypeError;return F(r)||(r=z(r)),O(e,t,r)}function C(e,t){if(!V(e))throw new TypeError;return F(t)||(t=z(t)),N(e,t)}function T(e,t){if(!V(e))throw new TypeError;return F(t)||(t=z(t)),L(e,t)}function P(e,t,r){if(!V(t))throw new TypeError;if(F(r)||(r=z(r)),!V(t))throw new TypeError;F(r)||(r=z(r));var n=ae(t,r,!1);return!F(n)&&n.OrdinaryDeleteMetadata(e,t,r)}function R(e,t){for(var r=e.length-1;r>=0;--r){var n=(0,e[r])(t);if(!F(n)&&!j(n)){if(!$(n))throw new TypeError;t=n}}return t}function k(e,t,r,n){for(var i=e.length-1;i>=0;--i){var s=(0,e[i])(t,r,n);if(!F(s)&&!j(s)){if(!V(s))throw new TypeError;n=s}}return n}function D(e,t,r){if(I(e,t,r))return!0;var n=re(t);return!j(n)&&D(e,n,r)}function I(e,t,r){var n=ae(t,r,!1);return!F(n)&&H(n.OrdinaryHasOwnMetadata(e,t,r))}function A(e,t,r){if(I(e,t,r))return O(e,t,r);var n=re(t);return j(n)?void 0:A(e,n,r)}function O(e,t,r){var n=ae(t,r,!1);if(!F(n))return n.OrdinaryGetOwnMetadata(e,t,r)}function M(e,t,r,n){ae(r,n,!0).OrdinaryDefineOwnMetadata(e,t,r,n)}function N(e,t){var r=L(e,t),n=re(e);if(null===n)return r;var i=N(n,t);if(i.length<=0)return r;if(r.length<=0)return i;for(var s=new p,o=[],a=0,c=r;a<c.length;a++){var d=c[a];s.has(d)||(s.add(d),o.push(d))}for(var u=0,l=i;u<l.length;u++){d=l[u];s.has(d)||(s.add(d),o.push(d))}return o}function L(e,t){var r=ae(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function x(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 F(e){return void 0===e}function j(e){return null===e}function U(e){return"symbol"==typeof e}function V(e){return"object"==typeof e?null!==e:"function"==typeof e}function B(e,t){switch(x(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var r=3===t?"string":5===t?"number":"default",n=Q(e,i);if(void 0!==n){var s=n.call(e,r);if(V(s))throw new TypeError;return s}return W(e,"default"===r?"number":r)}function W(e,t){if("string"===t){var r=e.toString;if(Y(r))if(!V(i=r.call(e)))return i;if(Y(n=e.valueOf))if(!V(i=n.call(e)))return i}else{var n;if(Y(n=e.valueOf))if(!V(i=n.call(e)))return i;var i,s=e.toString;if(Y(s))if(!V(i=s.call(e)))return i}throw new TypeError}function H(e){return!!e}function q(e){return""+e}function z(e){var t=B(e,3);return U(t)?t:q(t)}function G(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function Y(e){return"function"==typeof e}function $(e){return"function"==typeof e}function K(e){switch(x(e)){case 3:case 4:return!0;default:return!1}}function J(e,t){return e===t||e!=e&&t!=t}function Q(e,t){var r=e[t];if(null!=r){if(!Y(r))throw new TypeError;return r}}function Z(e){var t=Q(e,s);if(!Y(t))throw new TypeError;var r=t.call(e);if(!V(r))throw new TypeError;return r}function X(e){return e.value}function ee(e){var t=e.next();return!t.done&&t}function te(e){var t=e.return;t&&t.call(e)}function re(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===u)return t;if(t!==u)return t;var r=e.prototype,n=r&&Object.getPrototypeOf(r);if(null==n||n===Object.prototype)return t;var i=n.constructor;return"function"!=typeof i||i===e?t:i}function ne(){var e,r,n,i;F(f)||void 0===t.Reflect||f in t.Reflect||"function"!=typeof t.Reflect.defineMetadata||(e=oe(t.Reflect));var s=new h,o={registerProvider:a,getProvider:d,setProvider:m};return o;function a(t){if(!Object.isExtensible(o))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===t:break;case F(r):r=t;break;case r===t:break;case F(n):n=t;break;case n===t:break;default:void 0===i&&(i=new p),i.add(t)}}function c(t,s){if(!F(r)){if(r.isProviderFor(t,s))return r;if(!F(n)){if(n.isProviderFor(t,s))return r;if(!F(i))for(var o=Z(i);;){var a=ee(o);if(!a)return;var c=X(a);if(c.isProviderFor(t,s))return te(o),c}}}if(!F(e)&&e.isProviderFor(t,s))return e}function d(e,t){var r,n=s.get(e);return F(n)||(r=n.get(t)),F(r)?(F(r=c(e,t))||(F(n)&&(n=new l,s.set(e,n)),n.set(t,r)),r):r}function u(e){if(F(e))throw new TypeError;return r===e||n===e||!F(i)&&i.has(e)}function m(e,t,r){if(!u(r))throw new Error("Metadata provider not registered.");var n=d(e,t);if(n!==r){if(!F(n))return!1;var i=s.get(e);F(i)&&(i=new l,s.set(e,i)),i.set(t,r)}return!0}}function ie(){var e;return!F(f)&&V(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[f]),F(e)&&(e=ne()),!F(f)&&V(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,f,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function se(e){var t=new h,r={isProviderFor:function(e,r){var n=t.get(e);return!F(n)&&n.has(r)},OrdinaryDefineOwnMetadata:o,OrdinaryHasOwnMetadata:i,OrdinaryGetOwnMetadata:s,OrdinaryOwnMetadataKeys:a,OrdinaryDeleteMetadata:c};return m.registerProvider(r),r;function n(n,i,s){var o=t.get(n),a=!1;if(F(o)){if(!s)return;o=new l,t.set(n,o),a=!0}var c=o.get(i);if(F(c)){if(!s)return;if(c=new l,o.set(i,c),!e.setProvider(n,i,r))throw o.delete(i),a&&t.delete(n),new Error("Wrong provider for target.")}return c}function i(e,t,r){var i=n(t,r,!1);return!F(i)&&H(i.has(e))}function s(e,t,r){var i=n(t,r,!1);if(!F(i))return i.get(e)}function o(e,t,r,i){n(r,i,!0).set(e,t)}function a(e,t){var r=[],i=n(e,t,!1);if(F(i))return r;for(var s=Z(i.keys()),o=0;;){var a=ee(s);if(!a)return r.length=o,r;var c=X(a);try{r[o]=c}catch(e){try{te(s)}finally{throw e}}o++}}function c(e,r,i){var s=n(r,i,!1);if(F(s))return!1;if(!s.delete(e))return!1;if(0===s.size){var o=t.get(r);F(o)||(o.delete(i),0===o.size&&t.delete(o))}return!0}}function oe(e){var t=e.defineMetadata,r=e.hasOwnMetadata,n=e.getOwnMetadata,i=e.getOwnMetadataKeys,s=e.deleteMetadata,o=new h,a={isProviderFor:function(e,t){var r=o.get(e);return!(F(r)||!r.has(t))||!!i(e,t).length&&(F(r)&&(r=new p,o.set(e,r)),r.add(t),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:n,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:s};return a}function ae(e,t,r){var n=m.getProvider(e,t);if(!F(n))return n;if(r){if(m.setProvider(e,t,g))return g;throw new Error("Illegal state.")}}function ce(){var e={},t=[],r=function(){function e(e,t,r){this._index=0,this._keys=e,this._values=t,this._selector=r}return e.prototype["@@iterator"]=function(){return this},e.prototype[s]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var r=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:r,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}(),n=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 r=this._find(e,!0);return this._values[r]=t,this},t.prototype.delete=function(t){var r=this._find(t,!1);if(r>=0){for(var n=this._keys.length,i=r+1;i<n;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,J(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 r(this._keys,this._values,i)},t.prototype.values=function(){return new r(this._keys,this._values,o)},t.prototype.entries=function(){return new r(this._keys,this._values,a)},t.prototype["@@iterator"]=function(){return this.entries()},t.prototype[s]=function(){return this.entries()},t.prototype._find=function(e,t){if(!J(this._cacheKey,e)){this._cacheIndex=-1;for(var r=0;r<this._keys.length;r++)if(J(this._keys[r],e)){this._cacheIndex=r;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();return n;function i(e,t){return e}function o(e,t){return t}function a(e,t){return[e,t]}}function de(){return function(){function e(){this._map=new l}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.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[s]=function(){return this.keys()},e}()}function ue(){var e=16,t=d.create(),n=i();return function(){function e(){this._key=i()}return e.prototype.has=function(e){var t=s(e,!1);return void 0!==t&&d.has(t,this._key)},e.prototype.get=function(e){var t=s(e,!1);return void 0!==t?d.get(t,this._key):void 0},e.prototype.set=function(e,t){return s(e,!0)[this._key]=t,this},e.prototype.delete=function(e){var t=s(e,!1);return void 0!==t&&delete t[this._key]},e.prototype.clear=function(){this._key=i()},e}();function i(){var e;do{e="@@WeakMap@@"+c()}while(d.has(t,e));return t[e]=!0,e}function s(e,t){if(!r.call(e,n)){if(!t)return;Object.defineProperty(e,n,{value:d.create()})}return e[n]}function o(e,t){for(var r=0;r<t;++r)e[r]=255*Math.random()|0;return e}function a(e){if("function"==typeof Uint8Array){var t=new Uint8Array(e);return"undefined"!=typeof crypto?crypto.getRandomValues(t):"undefined"!=typeof msCrypto?msCrypto.getRandomValues(t):o(t,e),t}return o(new Array(e),e)}function c(){var t=a(e);t[6]=79&t[6]|64,t[8]=191&t[8]|128;for(var r="",n=0;n<e;++n){var i=t[n];4!==n&&6!==n&&8!==n||(r+="-"),i<16&&(r+="0"),r+=i.toString(16).toLowerCase()}return r}}function le(e){return e.__=void 0,delete e.__,e}e("decorate",v),e("metadata",y),e("defineMetadata",b),e("hasMetadata",_),e("hasOwnMetadata",E),e("getMetadata",w),e("getOwnMetadata",S),e("getMetadataKeys",C),e("getOwnMetadataKeys",T),e("deleteMetadata",P)}(n,r),void 0===r.Reflect&&(r.Reflect=e)}()}(d||(d={}));var h=["inject","multi_inject","name","unmanaged","named","optional"],f="Request",m="Singleton",g="Transient",v="ConstantValue",y="Constructor",b="DynamicValue",_="Factory",E="Function",w="Instance",S="Invalid",C="Provider",T="ClassProperty",P="ConstructorArgument",R="Variable",k=0;function D(){return k++}var I=function(){function e(e,t){this.id=D(),this.activated=!1,this.serviceIdentifier=e,this.scope=t,this.type=S,this.constraint=function(e){return!0},this.implementationType=null,this.cache=null,this.factory=null,this.provider=null,this.onActivation=null,this.onDeactivation=null,this.dynamicValue=null}return e.prototype.clone=function(){var t=new e(this.serviceIdentifier,this.scope);return t.activated=t.scope===m&&this.activated,t.implementationType=this.implementationType,t.dynamicValue=this.dynamicValue,t.scope=this.scope,t.type=this.type,t.factory=this.factory,t.provider=this.provider,t.constraint=this.constraint,t.onActivation=this.onActivation,t.onDeactivation=this.onDeactivation,t.cache=this.cache,t},e}(),A="No matching bindings found for serviceIdentifier:",O="The @inject @multiInject @tagged and @named decorators must be applied to the parameters of a class constructor or a class property.",M=function(e,t){return"onDeactivation() error in class "+e+": "+t},N=function(){function e(){}return e.prototype.getConstructorMetadata=function(e){return{compilerGeneratedMetadata:Reflect.getMetadata("inversify:paramtypes",e),userGeneratedMetadata:Reflect.getMetadata("inversify:tagged",e)||{}}},e.prototype.getPropertiesMetadata=function(e){return Reflect.getMetadata("inversify:tagged_props",e)||[]},e}(),L=0,x=1;function F(e){return e instanceof RangeError||"Maximum call stack size exceeded"===e.message}function j(e){return"function"==typeof e?e.name:"symbol"==typeof e?e.toString():e}function U(e,t,r){var n="",i=r(e,t);return 0!==i.length&&(n="\nRegistered bindings:",i.forEach((function(e){var t="Object";null!==e.implementationType&&(t=W(e.implementationType)),n=n+"\n "+t,e.constraint.metaData&&(n=n+" - "+e.constraint.metaData)}))),n}function V(e,t){return null!==e.parentRequest&&(e.parentRequest.serviceIdentifier===t||V(e.parentRequest,t))}function B(e){e.childRequests.forEach((function(e){if(V(e,e.serviceIdentifier)){var t=function(e){return function e(t,r){void 0===r&&(r=[]);var n=j(t.serviceIdentifier);return r.push(n),null!==t.parentRequest?e(t.parentRequest,r):r}(e).reverse().join(" --\x3e ")}(e);throw new Error("Circular dependency found: "+t)}B(e)}))}function W(e){if(e.name)return e.name;var t=e.toString(),r=t.match(/^function\s*([^\s(]+)/);return r?r[1]:"Anonymous function: "+t}var H=function(){function e(e){this.id=D(),this.container=e}return e.prototype.addPlan=function(e){this.plan=e},e.prototype.setCurrentRequest=function(e){this.currentRequest=e},e}(),q=function(){function e(e,t){this.key=e,this.value=t}return e.prototype.toString=function(){return"named"===this.key?"named: "+String(this.value).toString()+" ":"tagged: { key:"+this.key.toString()+", value: "+String(this.value)+" }"},e}(),z=function(e,t){this.parentContext=e,this.rootRequest=t},G=function(){function e(e){this._cb=e}return e.prototype.unwrap=function(){return this._cb()},e}(),Y=function(){function e(e){this.str=e}return e.prototype.startsWith=function(e){return 0===this.str.indexOf(e)},e.prototype.endsWith=function(e){var t,r=e.split("").reverse().join("");return t=this.str.split("").reverse().join(""),this.startsWith.call({str:t},r)},e.prototype.contains=function(e){return-1!==this.str.indexOf(e)},e.prototype.equals=function(e){return this.str===e},e.prototype.value=function(){return this.str},e}(),$=function(){function e(e,t,r,n){this.id=D(),this.type=e,this.serviceIdentifier=r;var i="symbol"==typeof t?function(e){return e.toString().slice(7,-1)}(t):t;this.name=new Y(i||""),this.identifier=t,this.metadata=new Array;var s=null;"string"==typeof n?s=new q("named",n):n instanceof q&&(s=n),null!==s&&this.metadata.push(s)}return e.prototype.hasTag=function(e){for(var t=0,r=this.metadata;t<r.length;t++){if(r[t].key===e)return!0}return!1},e.prototype.isArray=function(){return this.hasTag("multi_inject")},e.prototype.matchesArray=function(e){return this.matchesTag("multi_inject")(e)},e.prototype.isNamed=function(){return this.hasTag("named")},e.prototype.isTagged=function(){return this.metadata.some((function(e){return h.every((function(t){return e.key!==t}))}))},e.prototype.isOptional=function(){return this.matchesTag("optional")(!0)},e.prototype.getNamedTag=function(){return this.isNamed()?this.metadata.filter((function(e){return"named"===e.key}))[0]:null},e.prototype.getCustomTags=function(){return this.isTagged()?this.metadata.filter((function(e){return h.every((function(t){return e.key!==t}))})):null},e.prototype.matchesNamedTag=function(e){return this.matchesTag("named")(e)},e.prototype.matchesTag=function(e){var t=this;return function(r){for(var n=0,i=t.metadata;n<i.length;n++){var s=i[n];if(s.key===e&&s.value===r)return!0}return!1}},e}(),K=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))};function J(e,t,r,n){var i=e.getConstructorMetadata(r),s=i.compilerGeneratedMetadata;if(void 0===s)throw new Error("Missing required @injectable annotation in: "+t+".");var o=i.userGeneratedMetadata,a=Object.keys(o),c=0===r.length&&a.length>0,d=a.length>r.length,u=function(e,t,r,n,i){for(var s=[],o=0;o<i;o++){var a=Q(o,e,t,r,n);null!==a&&s.push(a)}return s}(n,t,s,o,c||d?a.length:r.length),l=X(e,r,t);return K(K([],u,!0),l,!0)}function Q(e,t,r,n,i){var s=i[e.toString()]||[],o=te(s),a=!0!==o.unmanaged,c=n[e],d=o.inject||o.multiInject;if((c=d||c)instanceof G&&(c=c.unwrap()),a){if(!t&&(c===Object||c===Function||void 0===c))throw new Error("Missing required @inject or @multiInject annotation in: argument "+e+" in class "+r+".");var u=new $(P,o.targetName,c);return u.metadata=s,u}return null}function Z(e,t,r,n){var i=e||t;if(void 0===i){var s="Missing required @injectable annotation in: for property "+String(r)+" in class "+n+".";throw new Error(s)}return i}function X(e,t,r){for(var n=e.getPropertiesMetadata(t),i=[],s=Object.getOwnPropertySymbols(n),o=0,a=Object.keys(n).concat(s);o<a.length;o++){var c=a[o],d=n[c],u=te(d),l=u.targetName||c,p=Z(u.inject,u.multiInject,c,r),h=new $(T,l,p);h.metadata=d,i.push(h)}var f=Object.getPrototypeOf(t.prototype).constructor;if(f!==Object){var m=X(e,f,r);i=K(K([],i,!0),m,!0)}return i}function ee(e,t){var r=Object.getPrototypeOf(t.prototype).constructor;if(r!==Object){var n=J(e,W(r),r,!0),i=n.map((function(e){return e.metadata.filter((function(e){return"unmanaged"===e.key}))})),s=[].concat.apply([],i).length,o=n.length-s;return o>0?o:ee(e,r)}return 0}function te(e){var t={};return e.forEach((function(e){t[e.key.toString()]=e.value})),{inject:t.inject,multiInject:t.multi_inject,targetName:t.name,unmanaged:t.unmanaged}}var re=function(){function e(e,t,r,n,i){this.id=D(),this.serviceIdentifier=e,this.parentContext=t,this.parentRequest=r,this.target=i,this.childRequests=[],this.bindings=Array.isArray(n)?n:[n],this.requestScope=null===r?new Map:null}return e.prototype.addChildRequest=function(t,r,n){var i=new e(t,this.parentContext,this,r,n);return this.childRequests.push(i),i},e}();function ne(e){return e._bindingDictionary}function ie(e,t,r,n,i){var s=oe(r.container,i.serviceIdentifier),o=[];return s.length===L&&r.container.options.autoBindInjectable&&"function"==typeof i.serviceIdentifier&&e.getConstructorMetadata(i.serviceIdentifier).compilerGeneratedMetadata&&(r.container.bind(i.serviceIdentifier).toSelf(),s=oe(r.container,i.serviceIdentifier)),o=t?s:s.filter((function(e){var t=new re(e.serviceIdentifier,r,n,e,i);return e.constraint(t)})),function(e,t,r,n){switch(t.length){case L:if(r.isOptional())return t;var i=j(e),s=A;throw s+=function(e,t){if(t.isTagged()||t.isNamed()){var r="",n=t.getNamedTag(),i=t.getCustomTags();return null!==n&&(r+=n.toString()+"\n"),null!==i&&i.forEach((function(e){r+=e.toString()+"\n"}))," "+e+"\n "+e+" - "+r}return" "+e}(i,r),s+=U(n,i,oe),new Error(s);case x:return t;default:if(r.isArray())return t;s="Ambiguous match found for serviceIdentifier: "+(i=j(e));throw s+=U(n,i,oe),new Error(s)}}(i.serviceIdentifier,o,i,r.container),o}function se(e,t,r,n,i,s){var o,a;if(null===i){o=ie(e,t,n,null,s),a=new re(r,n,null,o,s);var c=new z(n,a);n.addPlan(c)}else o=ie(e,t,n,i,s),a=i.addChildRequest(s.serviceIdentifier,o,s);o.forEach((function(t){var r=null;if(s.isArray())r=a.addChildRequest(t.serviceIdentifier,t,s);else{if(t.cache)return;r=a}if(t.type===w&&null!==t.implementationType){var i=function(e,t){return J(e,W(t),t,!1)}(e,t.implementationType);if(!n.container.options.skipBaseClassChecks){var o=ee(e,t.implementationType);if(i.length<o){var c=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return"The number of constructor arguments in the derived class "+e[0]+" must be >= than the number of constructor arguments of its base class."}(W(t.implementationType));throw new Error(c)}}i.forEach((function(t){se(e,!1,t.serviceIdentifier,n,r,t)}))}}))}function oe(e,t){var r=[],n=ne(e);return n.hasKey(t)?r=n.get(t):null!==e.parent&&(r=oe(e.parent,t)),r}function ae(e,t,r,n,i,s,o,a){void 0===a&&(a=!1);var c=new H(t),d=function(e,t,r,n,i,s){var o=new q(e?"multi_inject":"inject",r),a=new $(t,n,r,o);if(void 0!==i){var c=new q(i,s);a.metadata.push(c)}return a}(r,n,i,"",s,o);try{return se(e,a,i,c,null,d),c}catch(e){throw F(e)&&B(c.plan.rootRequest),e}}function ce(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&"function"==typeof e.then}function de(e){return!!ce(e)||Array.isArray(e)&&e.some(ce)}var ue,le=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},pe=function(e,t){var r,n,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,a])}}},he=function(e,t,r){e.has(t.id)||e.set(t.id,r)},fe=function(e,t){e.cache=t,e.activated=!0,ce(t)&&me(e,t)},me=function(e,t){return le(void 0,void 0,void 0,(function(){var r,n;return pe(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,t];case 1:return r=i.sent(),e.cache=r,[3,3];case 2:throw n=i.sent(),e.cache=null,e.activated=!1,n;case 3:return[2]}}))}))};!function(e){e.DynamicValue="toDynamicValue",e.Factory="toFactory",e.Provider="toProvider"}(ue||(ue={}));var ge=function(){return ge=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},ge.apply(this,arguments)},ve=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},ye=function(e,t){var r,n,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,a])}}},be=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))};function _e(e,t,r){var n;if(t.length>0){var i=function(e,t){return e.reduce((function(e,r){var n=t(r);return r.target.type===P?e.constructorInjections.push(n):(e.propertyRequests.push(r),e.propertyInjections.push(n)),e.isAsync||(e.isAsync=de(n)),e}),{constructorInjections:[],propertyInjections:[],propertyRequests:[],isAsync:!1})}(t,r),s=ge(ge({},i),{constr:e});n=i.isAsync?function(e){return ve(this,void 0,void 0,(function(){var t,r;return ye(this,(function(n){switch(n.label){case 0:return[4,we(e.constructorInjections)];case 1:return t=n.sent(),[4,we(e.propertyInjections)];case 2:return r=n.sent(),[2,Ee(ge(ge({},e),{constructorInjections:t,propertyInjections:r}))]}}))}))}(s):Ee(s)}else n=new e;return n}function Ee(e){var t,r=new((t=e.constr).bind.apply(t,be([void 0],e.constructorInjections,!1)));return e.propertyRequests.forEach((function(t,n){var i=t.target.identifier,s=e.propertyInjections[n];t.target.isOptional()&&void 0===s||(r[i]=s)})),r}function we(e){return ve(this,void 0,void 0,(function(){var t,r,n,i;return ye(this,(function(s){for(t=[],r=0,n=e;r<n.length;r++)i=n[r],Array.isArray(i)?t.push(Promise.all(i)):t.push(i);return[2,Promise.all(t)]}))}))}function Se(e,t){var r=function(e,t){var r,n;if(Reflect.hasMetadata("post_construct",e)){var i=Reflect.getMetadata("post_construct",e);try{return null===(n=(r=t)[i.value])||void 0===n?void 0:n.call(r)}catch(t){if(t instanceof Error)throw new Error((s=e.name,o=t.message,"@postConstruct error in class "+s+": "+o))}}var s,o}(e,t);return ce(r)?r.then((function(){return t})):t}function Ce(e,t){e.scope!==m&&function(e,t){var r="Class cannot be instantiated in "+(e.scope===f?"request":"transient")+" scope.";if("function"==typeof e.onDeactivation)throw new Error(M(t.name,r));if(Reflect.hasMetadata("pre_destroy",t))throw new Error("@preDestroy error in class "+t.name+": "+r)}(e,t)}var Te=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},Pe=function(e,t){var r,n,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,a])}}},Re=function(e){return function(t){t.parentContext.setCurrentRequest(t);var r=t.bindings,n=t.childRequests,i=t.target&&t.target.isArray(),s=!(t.parentRequest&&t.parentRequest.target&&t.target&&t.parentRequest.target.matchesArray(t.target.serviceIdentifier));if(i&&s)return n.map((function(t){return Re(e)(t)}));if(!t.target.isOptional()||0!==r.length){var o=r[0];return Ae(e,t,o)}}},ke=function(e,t){var r=function(e){switch(e.type){case _:return{factory:e.factory,factoryType:ue.Factory};case C:return{factory:e.provider,factoryType:ue.Provider};case b:return{factory:e.dynamicValue,factoryType:ue.DynamicValue};default:throw new Error("Unexpected factory type "+e.type)}}(e);return function(e,t){try{return e()}catch(e){throw F(e)&&(e=t()),e}}((function(){return r.factory.bind(e)(t)}),(function(){return new Error((e=r.factoryType,n=t.currentRequest.serviceIdentifier.toString(),"It looks like there is a circular dependency in one of the '"+e+"' bindings. Please investigate bindings with service identifier '"+n+"'."));var e,n}))},De=function(e,t,r){var n,i=t.childRequests;switch(function(e){var t=null;switch(e.type){case v:case E:t=e.cache;break;case y:case w:t=e.implementationType;break;case b:t=e.dynamicValue;break;case C:t=e.provider;break;case _:t=e.factory}if(null===t){var r=j(e.serviceIdentifier);throw new Error("Invalid binding type: "+r)}}(r),r.type){case v:case E:n=r.cache;break;case y:n=r.implementationType;break;case w:n=function(e,t,r,n){Ce(e,t);var i=_e(t,r,n);return ce(i)?i.then((function(e){return Se(t,e)})):Se(t,i)}(r,r.implementationType,i,Re(e));break;default:n=ke(r,t.parentContext)}return n},Ie=function(e,t,r){var n=function(e,t){return t.scope===m&&t.activated?t.cache:t.scope===f&&e.has(t.id)?e.get(t.id):null}(e,t);return null!==n||function(e,t,r){t.scope===m&&fe(t,r),t.scope===f&&he(e,t,r)}(e,t,n=r()),n},Ae=function(e,t,r){return Ie(e,r,(function(){var n=De(e,t,r);return n=ce(n)?n.then((function(e){return Oe(t,r,e)})):Oe(t,r,n)}))};function Oe(e,t,r){var n,i=Me(e.parentContext,t,r),s=Fe(e.parentContext.container),o=s.next();do{n=o.value;var a=e.parentContext,c=e.serviceIdentifier,d=xe(n,c);i=ce(i)?Le(d,a,i):Ne(d,a,i),o=s.next()}while(!0!==o.done&&!ne(n).hasKey(e.serviceIdentifier));return i}var Me=function(e,t,r){return"function"==typeof t.onActivation?t.onActivation(e,r):r},Ne=function(e,t,r){for(var n=e.next();!n.done;){if(ce(r=n.value(t,r)))return Le(e,t,r);n=e.next()}return r},Le=function(e,t,r){return Te(void 0,void 0,void 0,(function(){var n,i;return Pe(this,(function(s){switch(s.label){case 0:return[4,r];case 1:n=s.sent(),i=e.next(),s.label=2;case 2:return i.done?[3,4]:[4,i.value(t,n)];case 3:return n=s.sent(),i=e.next(),[3,2];case 4:return[2,n]}}))}))},xe=function(e,t){var r=e._activations;return r.hasKey(t)?r.get(t).values():[].values()},Fe=function(e){for(var t=[e],r=e.parent;null!==r;)t.push(r),r=r.parent;return{next:function(){var e=t.pop();return void 0!==e?{done:!1,value:e}:{done:!0,value:void 0}}}};var je=function(e,t){var r=e.parentRequest;return null!==r&&(!!t(r)||je(r,t))},Ue=function(e){return function(t){var r=function(r){return null!==r&&null!==r.target&&r.target.matchesTag(e)(t)};return r.metaData=new q(e,t),r}},Ve=Ue("named"),Be=function(e){return function(t){var r=null;if(null!==t){if(r=t.bindings[0],"string"==typeof e)return r.serviceIdentifier===e;var n=t.bindings[0].implementationType;return e===n}return!1}},We=function(){function e(e){this._binding=e}return e.prototype.when=function(e){return this._binding.constraint=e,new He(this._binding)},e.prototype.whenTargetNamed=function(e){return this._binding.constraint=Ve(e),new He(this._binding)},e.prototype.whenTargetIsDefault=function(){return this._binding.constraint=function(e){return null!==e&&(null!==e.target&&!e.target.isNamed()&&!e.target.isTagged())},new He(this._binding)},e.prototype.whenTargetTagged=function(e,t){return this._binding.constraint=Ue(e)(t),new He(this._binding)},e.prototype.whenInjectedInto=function(e){return this._binding.constraint=function(t){return null!==t&&Be(e)(t.parentRequest)},new He(this._binding)},e.prototype.whenParentNamed=function(e){return this._binding.constraint=function(t){return null!==t&&Ve(e)(t.parentRequest)},new He(this._binding)},e.prototype.whenParentTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&Ue(e)(t)(r.parentRequest)},new He(this._binding)},e.prototype.whenAnyAncestorIs=function(e){return this._binding.constraint=function(t){return null!==t&&je(t,Be(e))},new He(this._binding)},e.prototype.whenNoAncestorIs=function(e){return this._binding.constraint=function(t){return null!==t&&!je(t,Be(e))},new He(this._binding)},e.prototype.whenAnyAncestorNamed=function(e){return this._binding.constraint=function(t){return null!==t&&je(t,Ve(e))},new He(this._binding)},e.prototype.whenNoAncestorNamed=function(e){return this._binding.constraint=function(t){return null!==t&&!je(t,Ve(e))},new He(this._binding)},e.prototype.whenAnyAncestorTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&je(r,Ue(e)(t))},new He(this._binding)},e.prototype.whenNoAncestorTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&!je(r,Ue(e)(t))},new He(this._binding)},e.prototype.whenAnyAncestorMatches=function(e){return this._binding.constraint=function(t){return null!==t&&je(t,e)},new He(this._binding)},e.prototype.whenNoAncestorMatches=function(e){return this._binding.constraint=function(t){return null!==t&&!je(t,e)},new He(this._binding)},e}(),He=function(){function e(e){this._binding=e}return e.prototype.onActivation=function(e){return this._binding.onActivation=e,new We(this._binding)},e.prototype.onDeactivation=function(e){return this._binding.onDeactivation=e,new We(this._binding)},e}(),qe=function(){function e(e){this._binding=e,this._bindingWhenSyntax=new We(this._binding),this._bindingOnSyntax=new He(this._binding)}return e.prototype.when=function(e){return this._bindingWhenSyntax.when(e)},e.prototype.whenTargetNamed=function(e){return this._bindingWhenSyntax.whenTargetNamed(e)},e.prototype.whenTargetIsDefault=function(){return this._bindingWhenSyntax.whenTargetIsDefault()},e.prototype.whenTargetTagged=function(e,t){return this._bindingWhenSyntax.whenTargetTagged(e,t)},e.prototype.whenInjectedInto=function(e){return this._bindingWhenSyntax.whenInjectedInto(e)},e.prototype.whenParentNamed=function(e){return this._bindingWhenSyntax.whenParentNamed(e)},e.prototype.whenParentTagged=function(e,t){return this._bindingWhenSyntax.whenParentTagged(e,t)},e.prototype.whenAnyAncestorIs=function(e){return this._bindingWhenSyntax.whenAnyAncestorIs(e)},e.prototype.whenNoAncestorIs=function(e){return this._bindingWhenSyntax.whenNoAncestorIs(e)},e.prototype.whenAnyAncestorNamed=function(e){return this._bindingWhenSyntax.whenAnyAncestorNamed(e)},e.prototype.whenAnyAncestorTagged=function(e,t){return this._bindingWhenSyntax.whenAnyAncestorTagged(e,t)},e.prototype.whenNoAncestorNamed=function(e){return this._bindingWhenSyntax.whenNoAncestorNamed(e)},e.prototype.whenNoAncestorTagged=function(e,t){return this._bindingWhenSyntax.whenNoAncestorTagged(e,t)},e.prototype.whenAnyAncestorMatches=function(e){return this._bindingWhenSyntax.whenAnyAncestorMatches(e)},e.prototype.whenNoAncestorMatches=function(e){return this._bindingWhenSyntax.whenNoAncestorMatches(e)},e.prototype.onActivation=function(e){return this._bindingOnSyntax.onActivation(e)},e.prototype.onDeactivation=function(e){return this._bindingOnSyntax.onDeactivation(e)},e}(),ze=function(){function e(e){this._binding=e}return e.prototype.inRequestScope=function(){return this._binding.scope=f,new qe(this._binding)},e.prototype.inSingletonScope=function(){return this._binding.scope=m,new qe(this._binding)},e.prototype.inTransientScope=function(){return this._binding.scope=g,new qe(this._binding)},e}(),Ge=function(){function e(e){this._binding=e,this._bindingWhenSyntax=new We(this._binding),this._bindingOnSyntax=new He(this._binding),this._bindingInSyntax=new ze(e)}return e.prototype.inRequestScope=function(){return this._bindingInSyntax.inRequestScope()},e.prototype.inSingletonScope=function(){return this._bindingInSyntax.inSingletonScope()},e.prototype.inTransientScope=function(){return this._bindingInSyntax.inTransientScope()},e.prototype.when=function(e){return this._bindingWhenSyntax.when(e)},e.prototype.whenTargetNamed=function(e){return this._bindingWhenSyntax.whenTargetNamed(e)},e.prototype.whenTargetIsDefault=function(){return this._bindingWhenSyntax.whenTargetIsDefault()},e.prototype.whenTargetTagged=function(e,t){return this._bindingWhenSyntax.whenTargetTagged(e,t)},e.prototype.whenInjectedInto=function(e){return this._bindingWhenSyntax.whenInjectedInto(e)},e.prototype.whenParentNamed=function(e){return this._bindingWhenSyntax.whenParentNamed(e)},e.prototype.whenParentTagged=function(e,t){return this._bindingWhenSyntax.whenParentTagged(e,t)},e.prototype.whenAnyAncestorIs=function(e){return this._bindingWhenSyntax.whenAnyAncestorIs(e)},e.prototype.whenNoAncestorIs=function(e){return this._bindingWhenSyntax.whenNoAncestorIs(e)},e.prototype.whenAnyAncestorNamed=function(e){return this._bindingWhenSyntax.whenAnyAncestorNamed(e)},e.prototype.whenAnyAncestorTagged=function(e,t){return this._bindingWhenSyntax.whenAnyAncestorTagged(e,t)},e.prototype.whenNoAncestorNamed=function(e){return this._bindingWhenSyntax.whenNoAncestorNamed(e)},e.prototype.whenNoAncestorTagged=function(e,t){return this._bindingWhenSyntax.whenNoAncestorTagged(e,t)},e.prototype.whenAnyAncestorMatches=function(e){return this._bindingWhenSyntax.whenAnyAncestorMatches(e)},e.prototype.whenNoAncestorMatches=function(e){return this._bindingWhenSyntax.whenNoAncestorMatches(e)},e.prototype.onActivation=function(e){return this._bindingOnSyntax.onActivation(e)},e.prototype.onDeactivation=function(e){return this._bindingOnSyntax.onDeactivation(e)},e}(),Ye=function(){function e(e){this._binding=e}return e.prototype.to=function(e){return this._binding.type=w,this._binding.implementationType=e,new Ge(this._binding)},e.prototype.toSelf=function(){if("function"!=typeof this._binding.serviceIdentifier)throw new Error("The toSelf function can only be applied when a constructor is used as service identifier");var e=this._binding.serviceIdentifier;return this.to(e)},e.prototype.toConstantValue=function(e){return this._binding.type=v,this._binding.cache=e,this._binding.dynamicValue=null,this._binding.implementationType=null,this._binding.scope=m,new qe(this._binding)},e.prototype.toDynamicValue=function(e){return this._binding.type=b,this._binding.cache=null,this._binding.dynamicValue=e,this._binding.implementationType=null,new Ge(this._binding)},e.prototype.toConstructor=function(e){return this._binding.type=y,this._binding.implementationType=e,this._binding.scope=m,new qe(this._binding)},e.prototype.toFactory=function(e){return this._binding.type=_,this._binding.factory=e,this._binding.scope=m,new qe(this._binding)},e.prototype.toFunction=function(e){if("function"!=typeof e)throw new Error("Value provided to function binding must be a function!");var t=this.toConstantValue(e);return this._binding.type=E,this._binding.scope=m,t},e.prototype.toAutoFactory=function(e){return this._binding.type=_,this._binding.factory=function(t){return function(){return t.container.get(e)}},this._binding.scope=m,new qe(this._binding)},e.prototype.toAutoNamedFactory=function(e){return this._binding.type=_,this._binding.factory=function(t){return function(r){return t.container.getNamed(e,r)}},new qe(this._binding)},e.prototype.toProvider=function(e){return this._binding.type=C,this._binding.provider=e,this._binding.scope=m,new qe(this._binding)},e.prototype.toService=function(e){this.toDynamicValue((function(t){return t.container.get(e)}))},e}(),$e=function(){function e(){}return e.of=function(t,r,n,i,s){var o=new e;return o.bindings=t,o.middleware=r,o.deactivations=i,o.activations=n,o.moduleActivationStore=s,o},e}();var Ke=function(){function e(){this._map=new Map}return e.prototype.getMap=function(){return this._map},e.prototype.add=function(e,t){if(null==e)throw new Error("NULL argument");if(null==t)throw new Error("NULL argument");var r=this._map.get(e);void 0!==r?r.push(t):this._map.set(e,[t])},e.prototype.get=function(e){if(null==e)throw new Error("NULL argument");var t=this._map.get(e);if(void 0!==t)return t;throw new Error("Key Not Found")},e.prototype.remove=function(e){if(null==e)throw new Error("NULL argument");if(!this._map.delete(e))throw new Error("Key Not Found")},e.prototype.removeIntersection=function(e){var t=this;this.traverse((function(r,n){var i=e.hasKey(r)?e.get(r):void 0;if(void 0!==i){var s=n.filter((function(e){return!i.some((function(t){return e===t}))}));t._setValue(r,s)}}))},e.prototype.removeByCondition=function(e){var t=this,r=[];return this._map.forEach((function(n,i){for(var s=[],o=0,a=n;o<a.length;o++){var c=a[o];e(c)?r.push(c):s.push(c)}t._setValue(i,s)})),r},e.prototype.hasKey=function(e){if(null==e)throw new Error("NULL argument");return this._map.has(e)},e.prototype.clone=function(){var t=new e;return this._map.forEach((function(e,r){e.forEach((function(e){return t.add(r,"object"==typeof(n=e)&&null!==n&&"clone"in n&&"function"==typeof n.clone?e.clone():e);var n}))})),t},e.prototype.traverse=function(e){this._map.forEach((function(t,r){e(r,t)}))},e.prototype._setValue=function(e,t){t.length>0?this._map.set(e,t):this._map.delete(e)},e}(),Je=function(){function e(){this._map=new Map}return e.prototype.remove=function(e){if(this._map.has(e)){var t=this._map.get(e);return this._map.delete(e),t}return this._getEmptyHandlersStore()},e.prototype.addDeactivation=function(e,t,r){this._getModuleActivationHandlers(e).onDeactivations.add(t,r)},e.prototype.addActivation=function(e,t,r){this._getModuleActivationHandlers(e).onActivations.add(t,r)},e.prototype.clone=function(){var t=new e;return this._map.forEach((function(e,r){t._map.set(r,{onActivations:e.onActivations.clone(),onDeactivations:e.onDeactivations.clone()})})),t},e.prototype._getModuleActivationHandlers=function(e){var t=this._map.get(e);return void 0===t&&(t=this._getEmptyHandlersStore(),this._map.set(e,t)),t},e.prototype._getEmptyHandlersStore=function(){return{onActivations:new Ke,onDeactivations:new Ke}},e}(),Qe=function(){return Qe=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},Qe.apply(this,arguments)},Ze=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},Xe=function(e,t){var r,n,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,a])}}},et=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))},tt=function(){function e(e){var t=e||{};if("object"!=typeof t)throw new Error("Invalid Container constructor argument. Container options must be an object.");if(void 0===t.defaultScope)t.defaultScope=g;else if(t.defaultScope!==m&&t.defaultScope!==g&&t.defaultScope!==f)throw new Error('Invalid Container option. Default scope must be a string ("singleton" or "transient").');if(void 0===t.autoBindInjectable)t.autoBindInjectable=!1;else if("boolean"!=typeof t.autoBindInjectable)throw new Error("Invalid Container option. Auto bind injectable must be a boolean");if(void 0===t.skipBaseClassChecks)t.skipBaseClassChecks=!1;else if("boolean"!=typeof t.skipBaseClassChecks)throw new Error("Invalid Container option. Skip base check must be a boolean");this.options={autoBindInjectable:t.autoBindInjectable,defaultScope:t.defaultScope,skipBaseClassChecks:t.skipBaseClassChecks},this.id=D(),this._bindingDictionary=new Ke,this._snapshots=[],this._middleware=null,this._activations=new Ke,this._deactivations=new Ke,this.parent=null,this._metadataReader=new N,this._moduleActivationStore=new Je}return e.merge=function(t,r){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];var s=new e,o=et([t,r],n,!0).map((function(e){return ne(e)})),a=ne(s);function c(e,t){e.traverse((function(e,r){r.forEach((function(e){t.add(e.serviceIdentifier,e.clone())}))}))}return o.forEach((function(e){c(e,a)})),s},e.prototype.load=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var r=this._getContainerModuleHelpersFactory(),n=0,i=e;n<i.length;n++){var s=i[n],o=r(s.id);s.registry(o.bindFunction,o.unbindFunction,o.isboundFunction,o.rebindFunction,o.unbindAsyncFunction,o.onActivationFunction,o.onDeactivationFunction)}},e.prototype.loadAsync=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ze(this,void 0,void 0,(function(){var t,r,n,i,s;return Xe(this,(function(o){switch(o.label){case 0:t=this._getContainerModuleHelpersFactory(),r=0,n=e,o.label=1;case 1:return r<n.length?(i=n[r],s=t(i.id),[4,i.registry(s.bindFunction,s.unbindFunction,s.isboundFunction,s.rebindFunction,s.unbindAsyncFunction,s.onActivationFunction,s.onDeactivationFunction)]):[3,4];case 2:o.sent(),o.label=3;case 3:return r++,[3,1];case 4:return[2]}}))}))},e.prototype.unload=function(){for(var e=this,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];t.forEach((function(t){var r=e._removeModuleBindings(t.id);e._deactivateSingletons(r),e._removeModuleHandlers(t.id)}))},e.prototype.unloadAsync=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ze(this,void 0,void 0,(function(){var t,r,n,i;return Xe(this,(function(s){switch(s.label){case 0:t=0,r=e,s.label=1;case 1:return t<r.length?(n=r[t],i=this._removeModuleBindings(n.id),[4,this._deactivateSingletonsAsync(i)]):[3,4];case 2:s.sent(),this._removeModuleHandlers(n.id),s.label=3;case 3:return t++,[3,1];case 4:return[2]}}))}))},e.prototype.bind=function(e){var t=this.options.defaultScope||g,r=new I(e,t);return this._bindingDictionary.add(e,r),new Ye(r)},e.prototype.rebind=function(e){return this.unbind(e),this.bind(e)},e.prototype.rebindAsync=function(e){return Ze(this,void 0,void 0,(function(){return Xe(this,(function(t){switch(t.label){case 0:return[4,this.unbindAsync(e)];case 1:return t.sent(),[2,this.bind(e)]}}))}))},e.prototype.unbind=function(e){if(this._bindingDictionary.hasKey(e)){var t=this._bindingDictionary.get(e);this._deactivateSingletons(t)}this._removeServiceFromDictionary(e)},e.prototype.unbindAsync=function(e){return Ze(this,void 0,void 0,(function(){var t;return Xe(this,(function(r){switch(r.label){case 0:return this._bindingDictionary.hasKey(e)?(t=this._bindingDictionary.get(e),[4,this._deactivateSingletonsAsync(t)]):[3,2];case 1:r.sent(),r.label=2;case 2:return this._removeServiceFromDictionary(e),[2]}}))}))},e.prototype.unbindAll=function(){var e=this;this._bindingDictionary.traverse((function(t,r){e._deactivateSingletons(r)})),this._bindingDictionary=new Ke},e.prototype.unbindAllAsync=function(){return Ze(this,void 0,void 0,(function(){var e,t=this;return Xe(this,(function(r){switch(r.label){case 0:return e=[],this._bindingDictionary.traverse((function(r,n){e.push(t._deactivateSingletonsAsync(n))})),[4,Promise.all(e)];case 1:return r.sent(),this._bindingDictionary=new Ke,[2]}}))}))},e.prototype.onActivation=function(e,t){this._activations.add(e,t)},e.prototype.onDeactivation=function(e,t){this._deactivations.add(e,t)},e.prototype.isBound=function(e){var t=this._bindingDictionary.hasKey(e);return!t&&this.parent&&(t=this.parent.isBound(e)),t},e.prototype.isCurrentBound=function(e){return this._bindingDictionary.hasKey(e)},e.prototype.isBoundNamed=function(e,t){return this.isBoundTagged(e,"named",t)},e.prototype.isBoundTagged=function(e,t,r){var n=!1;if(this._bindingDictionary.hasKey(e)){var i=this._bindingDictionary.get(e),s=function(e,t,r,n){var i=new $(R,"",t,new q(r,n)),s=new H(e);return new re(t,s,null,[],i)}(this,e,t,r);n=i.some((function(e){return e.constraint(s)}))}return!n&&this.parent&&(n=this.parent.isBoundTagged(e,t,r)),n},e.prototype.snapshot=function(){this._snapshots.push($e.of(this._bindingDictionary.clone(),this._middleware,this._activations.clone(),this._deactivations.clone(),this._moduleActivationStore.clone()))},e.prototype.restore=function(){var e=this._snapshots.pop();if(void 0===e)throw new Error("No snapshot available to restore.");this._bindingDictionary=e.bindings,this._activations=e.activations,this._deactivations=e.deactivations,this._middleware=e.middleware,this._moduleActivationStore=e.moduleActivationStore},e.prototype.createChild=function(t){var r=new e(t||this.options);return r.parent=this,r},e.prototype.applyMiddleware=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=this._middleware?this._middleware:this._planAndResolve();this._middleware=e.reduce((function(e,t){return t(e)}),r)},e.prototype.applyCustomMetadataReader=function(e){this._metadataReader=e},e.prototype.get=function(e){var t=this._getNotAllArgs(e,!1);return this._getButThrowIfAsync(t)},e.prototype.getAsync=function(e){return Ze(this,void 0,void 0,(function(){var t;return Xe(this,(function(r){return t=this._getNotAllArgs(e,!1),[2,this._get(t)]}))}))},e.prototype.getTagged=function(e,t,r){var n=this._getNotAllArgs(e,!1,t,r);return this._getButThrowIfAsync(n)},e.prototype.getTaggedAsync=function(e,t,r){return Ze(this,void 0,void 0,(function(){var n;return Xe(this,(function(i){return n=this._getNotAllArgs(e,!1,t,r),[2,this._get(n)]}))}))},e.prototype.getNamed=function(e,t){return this.getTagged(e,"named",t)},e.prototype.getNamedAsync=function(e,t){return this.getTaggedAsync(e,"named",t)},e.prototype.getAll=function(e){var t=this._getAllArgs(e);return this._getButThrowIfAsync(t)},e.prototype.getAllAsync=function(e){var t=this._getAllArgs(e);return this._getAll(t)},e.prototype.getAllTagged=function(e,t,r){var n=this._getNotAllArgs(e,!0,t,r);return this._getButThrowIfAsync(n)},e.prototype.getAllTaggedAsync=function(e,t,r){var n=this._getNotAllArgs(e,!0,t,r);return this._getAll(n)},e.prototype.getAllNamed=function(e,t){return this.getAllTagged(e,"named",t)},e.prototype.getAllNamedAsync=function(e,t){return this.getAllTaggedAsync(e,"named",t)},e.prototype.resolve=function(e){var t=this.isBound(e);t||this.bind(e).toSelf();var r=this.get(e);return t||this.unbind(e),r},e.prototype._preDestroy=function(e,t){var r,n;if(Reflect.hasMetadata("pre_destroy",e))return null===(n=(r=t)[Reflect.getMetadata("pre_destroy",e).value])||void 0===n?void 0:n.call(r)},e.prototype._removeModuleHandlers=function(e){var t=this._moduleActivationStore.remove(e);this._activations.removeIntersection(t.onActivations),this._deactivations.removeIntersection(t.onDeactivations)},e.prototype._removeModuleBindings=function(e){return this._bindingDictionary.removeByCondition((function(t){return t.moduleId===e}))},e.prototype._deactivate=function(e,t){var r=this,n=Object.getPrototypeOf(t).constructor;try{if(this._deactivations.hasKey(e.serviceIdentifier)){var i=this._deactivateContainer(t,this._deactivations.get(e.serviceIdentifier).values());if(ce(i))return this._handleDeactivationError(i.then((function(){return r._propagateContainerDeactivationThenBindingAndPreDestroyAsync(e,t,n)})),n)}var s=this._propagateContainerDeactivationThenBindingAndPreDestroy(e,t,n);if(ce(s))return this._handleDeactivationError(s,n)}catch(e){if(e instanceof Error)throw new Error(M(n.name,e.message))}},e.prototype._handleDeactivationError=function(e,t){return Ze(this,void 0,void 0,(function(){var r;return Xe(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,e];case 1:return n.sent(),[3,3];case 2:if((r=n.sent())instanceof Error)throw new Error(M(t.name,r.message));return[3,3];case 3:return[2]}}))}))},e.prototype._deactivateContainer=function(e,t){for(var r=this,n=t.next();n.value;){var i=n.value(e);if(ce(i))return i.then((function(){return r._deactivateContainerAsync(e,t)}));n=t.next()}},e.prototype._deactivateContainerAsync=function(e,t){return Ze(this,void 0,void 0,(function(){var r;return Xe(this,(function(n){switch(n.label){case 0:r=t.next(),n.label=1;case 1:return r.value?[4,r.value(e)]:[3,3];case 2:return n.sent(),r=t.next(),[3,1];case 3:return[2]}}))}))},e.prototype._getContainerModuleHelpersFactory=function(){var e=this,t=function(e,t){e._binding.moduleId=t},r=function(r){return function(n){var i=e.rebind(n);return t(i,r),i}},n=function(t){return function(r,n){e._moduleActivationStore.addActivation(t,r,n),e.onActivation(r,n)}},i=function(t){return function(r,n){e._moduleActivationStore.addDeactivation(t,r,n),e.onDeactivation(r,n)}};return function(s){return{bindFunction:(o=s,function(r){var n=e.bind(r);return t(n,o),n}),isboundFunction:function(t){return e.isBound(t)},onActivationFunction:n(s),onDeactivationFunction:i(s),rebindFunction:r(s),unbindFunction:function(t){return e.unbind(t)},unbindAsyncFunction:function(t){return e.unbindAsync(t)}};var o}},e.prototype._getAll=function(e){return Promise.all(this._get(e))},e.prototype._get=function(e){var t=Qe(Qe({},e),{contextInterceptor:function(e){return e},targetType:R});if(this._middleware){var r=this._middleware(t);if(null==r)throw new Error("Invalid return type in middleware. Middleware must return!");return r}return this._planAndResolve()(t)},e.prototype._getButThrowIfAsync=function(e){var t=this._get(e);if(de(t))throw new Error("You are attempting to construct '"+e.serviceIdentifier+"' in a synchronous way\n but it has asynchronous dependencies.");return t},e.prototype._getAllArgs=function(e){return{avoidConstraints:!0,isMultiInject:!0,serviceIdentifier:e}},e.prototype._getNotAllArgs=function(e,t,r,n){return{avoidConstraints:!1,isMultiInject:t,serviceIdentifier:e,key:r,value:n}},e.prototype._planAndResolve=function(){var e=this;return function(t){var r=ae(e._metadataReader,e,t.isMultiInject,t.targetType,t.serviceIdentifier,t.key,t.value,t.avoidConstraints);return function(e){return Re(e.plan.rootRequest.requestScope)(e.plan.rootRequest)}(r=t.contextInterceptor(r))}},e.prototype._deactivateIfSingleton=function(e){var t=this;if(e.activated)return ce(e.cache)?e.cache.then((function(r){return t._deactivate(e,r)})):this._deactivate(e,e.cache)},e.prototype._deactivateSingletons=function(e){for(var t=0,r=e;t<r.length;t++){var n=r[t];if(ce(this._deactivateIfSingleton(n)))throw new Error("Attempting to unbind dependency with asynchronous destruction (@preDestroy or onDeactivation)")}},e.prototype._deactivateSingletonsAsync=function(e){return Ze(this,void 0,void 0,(function(){var t=this;return Xe(this,(function(r){switch(r.label){case 0:return[4,Promise.all(e.map((function(e){return t._deactivateIfSingleton(e)})))];case 1:return r.sent(),[2]}}))}))},e.prototype._propagateContainerDeactivationThenBindingAndPreDestroy=function(e,t,r){return this.parent?this._deactivate.bind(this.parent)(e,t):this._bindingDeactivationAndPreDestroy(e,t,r)},e.prototype._propagateContainerDeactivationThenBindingAndPreDestroyAsync=function(e,t,r){return Ze(this,void 0,void 0,(function(){return Xe(this,(function(n){switch(n.label){case 0:return this.parent?[4,this._deactivate.bind(this.parent)(e,t)]:[3,2];case 1:return n.sent(),[3,4];case 2:return[4,this._bindingDeactivationAndPreDestroyAsync(e,t,r)];case 3:n.sent(),n.label=4;case 4:return[2]}}))}))},e.prototype._removeServiceFromDictionary=function(e){try{this._bindingDictionary.remove(e)}catch(t){throw new Error("Could not unbind serviceIdentifier: "+j(e))}},e.prototype._bindingDeactivationAndPreDestroy=function(e,t,r){var n=this;if("function"==typeof e.onDeactivation){var i=e.onDeactivation(t);if(ce(i))return i.then((function(){return n._preDestroy(r,t)}))}return this._preDestroy(r,t)},e.prototype._bindingDeactivationAndPreDestroyAsync=function(e,t,r){return Ze(this,void 0,void 0,(function(){return Xe(this,(function(n){switch(n.label){case 0:return"function"!=typeof e.onDeactivation?[3,2]:[4,e.onDeactivation(t)];case 1:n.sent(),n.label=2;case 2:return[4,this._preDestroy(r,t)];case 3:return n.sent(),[2]}}))}))},e}();function rt(e,t,r,n){!function(e){if(void 0!==e)throw new Error(O)}(t),it("inversify:tagged",e,r.toString(),n)}function nt(e){var t=[];if(Array.isArray(e)){var r=function(e){for(var t=new Set,r=0,n=e;r<n.length;r++){var i=n[r];if(t.has(i))return i;t.add(i)}}((t=e).map((function(e){return e.key})));if(void 0!==r)throw new Error("Metadata key was used more than once in a parameter: "+r.toString())}else t=[e];return t}function it(e,t,r,n){var i=nt(n),s={};Reflect.hasOwnMetadata(e,t)&&(s=Reflect.getMetadata(e,t));var o=s[r];if(void 0===o)o=[];else for(var a=function(e){if(i.some((function(t){return t.key===e.key})))throw new Error("Metadata key was used more than once in a parameter: "+e.key.toString())},c=0,d=o;c<d.length;c++){a(d[c])}o.push.apply(o,i),s[r]=o,Reflect.defineMetadata(e,s,t)}function st(e){return function(t,r,n){"number"==typeof n?rt(t,r,n,e):function(e,t,r){if(void 0!==e.prototype)throw new Error(O);it("inversify:tagged_props",e.constructor,t,r)}(t,r,e)}}function ot(){return function(e){if(Reflect.hasOwnMetadata("inversify:paramtypes",e))throw new Error("Cannot apply @injectable decorator multiple times.");var t=Reflect.getMetadata("design:paramtypes",e)||[];return Reflect.defineMetadata("inversify:paramtypes",t,e),e}}var at,ct=(at="inject",function(e){return function(t,r,n){if(void 0===e){var i="function"==typeof t?t.name:t.constructor.name;throw new Error("@inject called with undefined this could mean that the class "+i+" has a circular dependency problem. You can use a LazyServiceIdentifier to overcome this limitation.")}return st(new q(at,e))(t,r,n)}});const dt=3,ut=4,lt=6,pt=7;var ht;!function(e){e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.OK=200]="OK",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.TooManyRequests=429]="TooManyRequests",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout"}(ht||(ht={}));const ft=String("3.60.0");var mt;const gt={customerId:String("89c41ecf3b3f46fef5dfa9f96842014c21d4901c"),sdk_url:String("https://effectssdk.ai/sdk/audio/"),api_url:String("https://effectssdk.ai/sdk/session/"),version:"2.3.5"},vt={customerId:String("89c41ecf3b3f46fef5dfa9f96842014c21d4901c"),sdk_url:String("https://effectssdk.ai/sdk/"),api_url:String("https://effectssdk.ai/sdk/session/")},yt=()=>{};let bt=class{constructor(e){var t,r,n,i,s,o,a,d,u,l;mt.set(this,void 0),c(this,mt,{denoiser:null!==(t=e.denoiser)&&void 0!==t?t:"rnnoise",asdk:Object.assign(Object.assign({},gt),e.asdk),signalingServerUrl:null!==(r=e.signalingServerUrl)&&void 0!==r?r:String("https://signaling-api.livedigital.space/v1"),analyticsApiUrl:null!==(n=e.analyticsApiUrl)&&void 0!==n?n:String("https://moodhood-analytics.livedigital.space/v1"),logLevel:null!==(i=e.logLevel)&&void 0!==i?i:dt,sendAnalytics:null!==(s=e.sendAnalytics)&&void 0!==s&&s,onLogMessage:null!==(o=e.onLogMessage)&&void 0!==o?o:yt,onIssues:null!==(a=e.onIssues)&&void 0!==a?a:yt,disableWid:null!==(d=e.disableWid)&&void 0!==d&&d,effectsSDKParams:Object.assign(Object.assign({},vt),e.effectsSDKParams),onNetworkScoresUpdated:null!==(u=e.onNetworkScoresUpdated)&&void 0!==u?u:yt,getStatsInterval:null!==(l=e.getStatsInterval)&&void 0!==l?l:5e3,staticFilesPath:e.staticFilesPath||window.location.origin},"f")}get(e){return a(this,mt,"f")[e]}set(e,t){a(this,mt,"f")[e]=t}};mt=new WeakMap,bt=n([ot(),s("design:paramtypes",[Object])],bt);var _t,Et=bt,wt={exports:{}},St="object"==typeof Reflect?Reflect:null,Ct=St&&"function"==typeof St.apply?St.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};_t=St&&"function"==typeof St.ownKeys?St.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var Tt=Number.isNaN||function(e){return e!=e};function Pt(){Pt.init.call(this)}wt.exports=Pt,wt.exports.once=function(e,t){return new Promise((function(r,n){function i(r){e.removeListener(t,s),n(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}xt(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&xt(e,"error",t,r)}(e,i,{once:!0})}))},Pt.EventEmitter=Pt,Pt.prototype._events=void 0,Pt.prototype._eventsCount=0,Pt.prototype._maxListeners=void 0;var Rt=10;function kt(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function Dt(e){return void 0===e._maxListeners?Pt.defaultMaxListeners:e._maxListeners}function It(e,t,r,n){var i,s,o,a;if(kt(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),(i=Dt(e))>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,console&&console.warn&&console.warn(a)}return e}function At(){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 Ot(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=At.bind(n);return i.listener=r,n.wrapFn=i,i}function Mt(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(i):Lt(i,i.length)}function Nt(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function Lt(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function xt(e,t,r,n){if("function"==typeof e.on)n.once?e.once(t,r):e.on(t,r);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 i(s){n.once&&e.removeEventListener(t,i),r(s)}))}}Object.defineProperty(Pt,"defaultMaxListeners",{enumerable:!0,get:function(){return Rt},set:function(e){if("number"!=typeof e||e<0||Tt(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Rt=e}}),Pt.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},Pt.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||Tt(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},Pt.prototype.getMaxListeners=function(){return Dt(this)},Pt.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var n="error"===e,i=this._events;if(void 0!==i)n=n&&void 0===i.error;else if(!n)return!1;if(n){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[e];if(void 0===a)return!1;if("function"==typeof a)Ct(a,this,t);else{var c=a.length,d=Lt(a,c);for(r=0;r<c;++r)Ct(d[r],this,t)}return!0},Pt.prototype.addListener=function(e,t){return It(this,e,t,!1)},Pt.prototype.on=Pt.prototype.addListener,Pt.prototype.prependListener=function(e,t){return It(this,e,t,!0)},Pt.prototype.once=function(e,t){return kt(t),this.on(e,Ot(this,e,t)),this},Pt.prototype.prependOnceListener=function(e,t){return kt(t),this.prependListener(e,Ot(this,e,t)),this},Pt.prototype.removeListener=function(e,t){var r,n,i,s,o;if(kt(t),void 0===(n=this._events))return this;if(void 0===(r=n[e]))return this;if(r===t||r.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,i),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},Pt.prototype.off=Pt.prototype.removeListener,Pt.prototype.removeAllListeners=function(e){var t,r,n;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var i,s=Object.keys(r);for(n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[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},Pt.prototype.listeners=function(e){return Mt(this,e,!0)},Pt.prototype.rawListeners=function(e){return Mt(this,e,!1)},Pt.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Nt.call(e,t)},Pt.prototype.listenerCount=Nt,Pt.prototype.eventNames=function(){return this._eventsCount>0?_t(this._events):[]};class Ft extends wt.exports.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}emit(e,...t){return super.emit(e,...t)}safeEmit(e,...t){try{return super.emit(e,...t)}catch(t){try{super.emit("listenererror",e,t)}catch(e){}return!!super.listenerCount(e)}}on(e,t){return super.on(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.on(e,t),this}removeListener(e,t){return super.off(e,t),this}once(e,t){return super.once(e,t),this}prependListener(e,t){return super.prependListener(e,t),this}prependOnceListener(e,t){return super.prependOnceListener(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}}Error;const jt=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0}],Ut=({from:e,seen:t,to_:r,forceEnumerable:n})=>{const i=r||(Array.isArray(e)?[]:{});t.push(e);for(const[r,s]of Object.entries(e))"function"!=typeof s&&(s&&"object"==typeof s?t.includes(e[r])?i[r]="[Circular]":i[r]=Ut({from:e[r],seen:t.slice(),forceEnumerable:n}):i[r]=s);for(const{property:t,enumerable:r}of jt)"string"==typeof e[t]&&Object.defineProperty(i,t,{value:e[t],enumerable:!!n||r,configurable:!0,writable:!0});return i};var Vt=e=>"object"==typeof e&&null!==e?Ut({from:e,seen:[],forceEnumerable:!0}):"function"==typeof e?`[Function: ${e.name||"anonymous"}]`:e;class Bt extends Error{constructor(e,t){var r;if(t instanceof Bt)return super(t.message),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this.errorCode=t.errorCode,void(this.cause=t.cause);const n=Vt(t),i=null!==(r=(e=>{if("string"==typeof e)return e;if(e instanceof Error)return e.message;if(e&&"object"==typeof e&&"message"in e){const t=e.message;return"string"==typeof t?t:void 0}})(n))&&void 0!==r?r:"Operation failed";super(i),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this.errorCode=e,this.cause=Vt(n)}}var Wt,Ht,qt,zt;function Gt(){}function Yt(){Yt.init.call(this)}function $t(e){return void 0===e._maxListeners?Yt.defaultMaxListeners:e._maxListeners}function Kt(e,t,r){if(t)e.call(r);else for(var n=e.length,i=nr(e,n),s=0;s<n;++s)i[s].call(r)}function Jt(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,s=nr(e,i),o=0;o<i;++o)s[o].call(r,n)}function Qt(e,t,r,n,i){if(t)e.call(r,n,i);else for(var s=e.length,o=nr(e,s),a=0;a<s;++a)o[a].call(r,n,i)}function Zt(e,t,r,n,i,s){if(t)e.call(r,n,i,s);else for(var o=e.length,a=nr(e,o),c=0;c<o;++c)a[c].call(r,n,i,s)}function Xt(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,s=nr(e,i),o=0;o<i;++o)s[o].apply(r,n)}function er(e,t,r,n){var i,s,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]):(s=e._events=new Gt,e._eventsCount=0),o){if("function"==typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),!o.warned&&(i=$t(e))&&i>0&&o.length>i){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else o=s[t]=r,++e._eventsCount;return e}function tr(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}function rr(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function nr(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}Gt.prototype=Object.create(null),Yt.EventEmitter=Yt,Yt.usingDomains=!1,Yt.prototype.domain=void 0,Yt.prototype._events=void 0,Yt.prototype._maxListeners=void 0,Yt.defaultMaxListeners=10,Yt.init=function(){this.domain=null,Yt.usingDomains&&(void 0).active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Gt,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Yt.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},Yt.prototype.getMaxListeners=function(){return $t(this)},Yt.prototype.emit=function(e){var t,r,n,i,s,o,a,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=o[e]))return!1;var u="function"==typeof r;switch(n=arguments.length){case 1:Kt(r,u,this);break;case 2:Jt(r,u,this,arguments[1]);break;case 3:Qt(r,u,this,arguments[1],arguments[2]);break;case 4:Zt(r,u,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),s=1;s<n;s++)i[s-1]=arguments[s];Xt(r,u,this,i)}return!0},Yt.prototype.addListener=function(e,t){return er(this,e,t,!1)},Yt.prototype.on=Yt.prototype.addListener,Yt.prototype.prependListener=function(e,t){return er(this,e,t,!0)},Yt.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,tr(this,e,t)),this},Yt.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,tr(this,e,t)),this},Yt.prototype.removeListener=function(e,t){var r,n,i,s,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(n=this._events))return this;if(!(r=n[e]))return this;if(r===t||r.listener&&r.listener===t)0==--this._eventsCount?this._events=new Gt:(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new Gt,this;delete n[e]}else!function(e,t){for(var r=t,n=r+1,i=e.length;n<i;r+=1,n+=1)e[r]=e[n];e.pop()}(r,i);n.removeListener&&this.emit("removeListener",e,o||t)}return this},Yt.prototype.off=function(e,t){return this.removeListener(e,t)},Yt.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new Gt,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new Gt:delete r[e]),this;if(0===arguments.length){for(var n,i=Object.keys(r),s=0;s<i.length;++s)"removeListener"!==(n=i[s])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=new Gt,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},Yt.prototype.listeners=function(e){var t,r=this._events;return r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[]},Yt.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):rr.call(e,t)},Yt.prototype.listenerCount=rr,Yt.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class ir extends Yt{}!function(e){e.Issue="issue",e.NetworkScoresUpdated="network-scores-updated",e.StatsParsingFinished="stats-parsing-finished"}(Wt||(Wt={})),function(e){e.Network="network",e.CPU="cpu",e.Server="server",e.Stream="stream"}(Ht||(Ht={})),function(e){e.OutboundNetworkQuality="outbound-network-quality",e.InboundNetworkQuality="inbound-network-quality",e.OutboundNetworkMediaLatency="outbound-network-media-latency",e.InboundNetworkMediaLatency="inbound-network-media-latency",e.NetworkMediaSyncFailure="network-media-sync-failure",e.OutboundNetworkThroughput="outbound-network-throughput",e.InboundNetworkThroughput="inbound-network-throughput",e.EncoderCPUThrottling="encoder-cpu-throttling",e.DecoderCPUThrottling="decoder-cpu-throttling",e.ServerIssue="server-issue",e.UnknownVideoDecoderIssue="unknown-video-decoder",e.LowInboundMOS="low-inbound-mean-opinion-score",e.LowOutboundMOS="low-outbound-mean-opinion-score",e.FrozenVideoTrack="frozen-video-track",e.MissingVideoStreamData="missing-video-stream-data",e.MissingAudioStreamData="missing-audio-stream-data"}(qt||(qt={})),function(e){e[e.BAD=2.1]="BAD",e[e.POOR=2.6]="POOR",e[e.FAIR=3.1]="FAIR",e[e.GOOD=3.8]="GOOD",e[e.EXCELLENT=4.3]="EXCELLENT"}(zt||(zt={}));class sr extends Yt{static STATS_REPORT_READY_EVENT="stats-report-ready";static STATS_REPORTS_PARSED="stats-reports-parsed";isStopped=!1;reportTimer;getStatsInterval;compositeStatsParser;constructor(e){super(),this.compositeStatsParser=e.compositeStatsParser,this.getStatsInterval=e.getStatsInterval??1e4}get isRunning(){return!!this.reportTimer&&!this.isStopped}startReporting(){if(this.reportTimer)return;const e=()=>setTimeout((()=>{this.isStopped?this.reportTimer=void 0:this.parseReports().finally((()=>{this.reportTimer=e()}))}),this.getStatsInterval);this.isStopped=!1,this.reportTimer=e()}stopReporting(){this.isStopped=!0,this.reportTimer&&(clearTimeout(this.reportTimer),this.reportTimer=void 0)}async parseReports(){const e=Date.now(),t=await this.compositeStatsParser.parse(),r=Date.now()-e;this.emit(sr.STATS_REPORTS_PARSED,{timeTaken:r,reportItems:t}),t.forEach((e=>{this.emit(sr.STATS_REPORT_READY_EVENT,e)}))}}const or=()=>{const e=new Map;return t=>{const{taskId:r,delayMs:n,maxJitterMs:i,callback:s}=t,o=Math.ceil(Math.random()*(i||0)),a=e.get(r);a&&clearTimeout(a);const c=setTimeout((()=>{s(),e.delete(r)}),n+o);e.set(r,c)}};class ar{#e={};#t=or();calculate(e){const{connection:{id:t}}=e,{mos:r,stats:n}=this.calculateOutboundScore(e)||{},{mos:i,stats:s}=this.calculateInboundScore(e)||{};return this.#e[t]=e,this.#t({taskId:t,delayMs:35e3,callback:()=>delete this.#e[t]}),{outbound:r,inbound:i,connectionId:t,statsSamples:{inboundStatsSample:s,outboundStatsSample:n}}}calculateOutboundScore(e){const t=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!t.length)return;const r=this.#e[e.connection.id];if(!r)return;const n=[...r.remote?.audio.inbound||[],...r.remote?.video.inbound||[]],{packetsSent:i}=e.connection,s=r.connection.packetsSent,o=t.reduce(((e,t)=>{const r=n.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=1e3*c/t.length,u=i-s,l=o.packetsLost-o.lastPacketsLost,p=u&&l?Math.round(100*l/(u+l)):0;return{mos:this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:p}),stats:{avgJitter:d,rtt:a,packetsLoss:p}}}calculateInboundScore(e){const t=[...e.audio?.inbound,...e.video?.inbound];if(!t.length)return;const r=this.#e[e.connection.id];if(!r)return;const n=[...r.video?.inbound,...r.audio?.inbound],{packetsReceived:i}=e.connection,s=r.connection.packetsReceived,o=t.reduce(((e,t)=>{const r=n.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=1e3*c/t.length,u=i-s,l=o.packetsLost-o.lastPacketsLost,p=u&&l?Math.round(100*l/(u+l)):0;return{mos:this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:p}),stats:{avgJitter:d,rtt:a,packetsLoss:p}}}calculateMOS({avgJitter:e,rtt:t,packetsLoss:r}){const n=t+2*e+10;let i=n<160?93.2-n/40:93.2-(n-120)/10;i-=2.5*r;const s=1+.035*i+7e-6*i*(i-60)*(100-i);return Math.max(0,Math.min(5,s))}}class cr{#r=new Map;#n;#i;#t=or();constructor(e={}){this.#n=e.statsCleanupTtlMs??35e3,this.#i=e.maxParsedStatsStorageSize??5}detect(e,t){const r={...e,networkScores:{...t,statsSamples:t?.statsSamples||{}}},n=this.performDetection(r);return this.setLastProcessedStats(e.connection.id,r),this.performPrevStatsCleanup({connectionId:e.connection.id}),n}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:r}=e;this.#r.has(t)&&this.#t({taskId:t,delayMs:this.#n,callback:()=>{this.deleteLastProcessedStats(t),"function"==typeof r&&r()}})}setLastProcessedStats(e,t){if(!e||t.connection.id!==e)return;const r=this.#r.get(e)??[];r.push(t),r.length>this.#i&&r.shift(),this.#r.set(e,r)}getLastProcessedStats(e){const t=this.#r.get(e);return t?.[t.length-1]}getAllLastProcessedStats(e){return this.#r.get(e)??[]}deleteLastProcessedStats(e){this.#r.delete(e)}}class dr extends cr{#s;constructor(e={}){super(e),this.#s=e.availableOutgoingBitrateThreshold??1e5}performDetection(e){const t=[],{availableOutgoingBitrate:r}=e.connection;if(void 0===r)return t;const n=e.audio.outbound.reduce(((e,t)=>e+t.targetBitrate),0),i=e.video.outbound.reduce(((e,t)=>e+t.bitrate),0);if(!n&&!i)return t;const s={availableOutgoingBitrate:r,videoStreamsTotalBitrate:i,audioStreamsTotalTargetBitrate:n};return n>r||i>0&&r<this.#s?(t.push({statsSample:s,type:Ht.Network,reason:qt.OutboundNetworkThroughput}),t):t}}class ur extends cr{#o;#a;#c;#d;constructor(e={}){super(e),this.#o=e.highPacketLossThresholdPct??5,this.#a=e.highJitterThreshold??200,this.#c=e.highJitterBufferDelayThresholdMs??500,this.#d=e.highRttThresholdMs??250}performDetection(e){return this.processData(e)}processData(e){const t=[],r=[...e.audio?.inbound,...e.video?.inbound];if(!r.length)return t;const n=this.getLastProcessedStats(e.connection.id);if(!n)return t;const i=[...n.video?.inbound,...n.audio?.inbound],{packetsReceived:s}=e.connection,o=n.connection.packetsReceived,a=r.reduce(((e,t)=>{const r=i.find((e=>e.ssrc===t.ssrc)),n=r?.jitterBufferDelay||0,s=r?.jitterBufferEmittedCount||0,o=t.jitterBufferDelay-n,a=t.jitterBufferEmittedCount-s,c=o&&a?1e3*o/a:0;return{sumJitter:e.sumJitter+t.jitter,sumJitterBufferDelayMs:e.sumJitterBufferDelayMs+c,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,sumJitterBufferDelayMs:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:d,sumJitterBufferDelayMs:u}=a,l=1e3*d/r.length,p=u/r.length,h=s-o,f=a.packetsLost-a.lastPacketsLost,m=h&&f?Math.round(100*f/(h+f)):0,g=m>this.#o,v=l>=this.#a,y=c>=this.#d,b=p>this.#c,_=y&&!v&&!g,E=g&&v,w=v&&b,S={rtt:c,packetLossPct:m,avgJitter:l,avgJitterBufferDelay:p};return(v||g)&&t.push({statsSample:S,type:Ht.Network,reason:qt.InboundNetworkQuality,iceCandidate:e.connection.local.id}),_&&t.push({statsSample:S,type:Ht.Server,reason:qt.ServerIssue,iceCandidate:e.connection.remote.id}),E&&t.push({statsSample:S,type:Ht.Network,reason:qt.InboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),w&&t.push({statsSample:S,type:Ht.Network,reason:qt.NetworkMediaSyncFailure,iceCandidate:e.connection.local.id}),t}}class lr extends cr{#u;constructor(e={}){super(e),this.#u=e.correctedSamplesThresholdPct??5}performDetection(e){return this.processData(e)}processData(e){const t=e.audio.inbound,r=[],n=this.getLastProcessedStats(e.connection.id)?.audio.inbound;return n?(t.forEach((e=>{const t=n.find((t=>t.ssrc===e.ssrc));if(!t)return;const i=e.track.insertedSamplesForDeceleration+e.track.removedSamplesForAcceleration,s=t.track.insertedSamplesForDeceleration+t.track.removedSamplesForAcceleration;if(i===s)return;const o=e.track.totalSamplesReceived-t.track.totalSamplesReceived;if(0===o)return;const a=i-s,c=Math.round(100*a/o),d={correctedSamplesPct:c};c>this.#u&&r.push({statsSample:d,type:Ht.Network,reason:qt.NetworkMediaSyncFailure,ssrc:e.ssrc})})),r):r}}class pr extends cr{#o;#a;constructor(e={}){super(e),this.#o=e.highPacketLossThresholdPct??5,this.#a=e.highJitterThreshold??200}performDetection(e){return this.processData(e)}processData(e){const t=[],r=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!r.length)return t;const n=this.getLastProcessedStats(e.connection.id);if(!n)return t;const i=[...n.remote?.audio.inbound||[],...n.remote?.video.inbound||[]],{packetsSent:s}=e.connection,o=n.connection.packetsSent,a=r.reduce(((e,t)=>{const r=i.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:d}=a,u=1e3*d/r.length,l=s-o,p=a.packetsLost-a.lastPacketsLost,h=l&&p?Math.round(100*p/(l+p)):0,f=h>this.#o,m=u>=this.#a,g=m||f,v={rtt:c,avgJitter:u,packetLossPct:h};return f&&m&&t.push({statsSample:v,type:Ht.Network,reason:qt.OutboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),g&&t.push({statsSample:v,type:Ht.Network,reason:qt.OutboundNetworkQuality,iceCandidate:e.connection.local.id}),t}}class hr extends cr{performDetection(e){return this.processData(e)}processData(e){const t=e.video.outbound.filter((e=>"none"!==e.qualityLimitationReason)),r=[],n=this.getLastProcessedStats(e.connection.id)?.video.outbound;return n?(t.forEach((e=>{const t=n.find((t=>t.ssrc===e.ssrc));if(!t)return;const i={qualityLimitationReason:e.qualityLimitationReason};e.framesSent>t.framesSent||("cpu"===e.qualityLimitationReason&&r.push({statsSample:i,type:Ht.CPU,reason:qt.EncoderCPUThrottling,ssrc:e.ssrc}),"bandwidth"===e.qualityLimitationReason&&r.push({statsSample:i,type:Ht.Network,reason:qt.OutboundNetworkThroughput,ssrc:e.ssrc}))})),r):r}}class fr extends cr{UNKNOWN_DECODER="unknown";#l={};performDetection(e){return this.processData(e)}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:r}=e;super.performPrevStatsCleanup({...e,cleanupCallback:()=>{delete this.#l[t],"function"==typeof r&&r()}})}processData(e){const t=[],{id:r}=e.connection,n=this.getLastProcessedStats(r)?.video.inbound;return e.video.inbound.forEach((e=>{const{decoderImplementation:i,ssrc:s}=e,o=n?.find((e=>e.ssrc===s));if(o)if(i===this.UNKNOWN_DECODER){if(!this.hadLastDecoderWithIssue(r,s)){this.setLastDecoderWithIssue(r,s,this.UNKNOWN_DECODER);const n={mimeType:e.mimeType,decoderImplementation:i};t.push({ssrc:s,statsSample:n,type:Ht.Stream,reason:qt.UnknownVideoDecoderIssue,trackIdentifier:e.track.trackIdentifier})}}else this.setLastDecoderWithIssue(r,s,void 0)})),t}setLastDecoderWithIssue(e,t,r){const n=this.#l[e]??{};void 0===r?delete n[t]:n[t]=r,this.#l[e]=n}hadLastDecoderWithIssue(e,t){const r=this.#l[e];return(r&&r[t])===this.UNKNOWN_DECODER}}const mr=e=>e.reduce(((e,t)=>e+t),0)/e.length,gr=(e,t,r=30)=>{const n=[];for(let r=1;r<t.length;r+=1){const i=t[r]?.video?.inbound.find((t=>t.ssrc===e));if(!i)continue;const s=t[r-1]?.video?.inbound?.find((t=>t.ssrc===e));if(!i||!s)continue;const o=i.timestamp-s.timestamp,a=i.framesDecoded-s.framesDecoded;if(a>0){const e=o/a;n.push(e)}}return!(n.length<=1)&&(e=>{const t=((e,t)=>t.reduce(((t,r)=>t+(r-e)**2),0)/t.length)(mr(e),e);return Math.sqrt(t)})(n)>r},vr=(e,t)=>{for(let r=1;r<t.length;r+=1){const n=t[r].video.inbound.find((t=>t.ssrc===e));if(!n)continue;const i=t[r-1].video.inbound.find((t=>t.ssrc===e)),s=n.frameWidth!==i?.frameWidth,o=n.frameHeight!==i?.frameHeight;if(s||o)return!0}return!1};class yr extends cr{#p;#h;#f;constructor(e={}){super(),this.#p=e.avgFreezeDurationThresholdMs??1e3,this.#h=e.frozenDurationThresholdPct??30,this.#f=e.minMosQuality??zt.BAD}performDetection(e){const t=e.networkScores.inbound;return void 0!==t&&t<=this.#f?[]:this.processData(e)}processData(e){const t=[],r=this.getAllLastProcessedStats(e.connection.id);if(0===r.length)return[];const n=e.video.inbound.map((t=>{const n=r[r.length-1].video.inbound.find((e=>e.ssrc===t.ssrc));if(!n)return;if(vr(t.ssrc,[r[r.length-1],e]))return;if(gr(t.ssrc,r))return;const i=t.freezeCount-(n.freezeCount??0),s=1e3*(t.totalFreezesDuration-(n.totalFreezesDuration??0)),o=i>0?s/i:0,a=s/(t.timestamp-n.timestamp)*100;return a>this.#h||o>this.#p?{ssrc:t.ssrc,avgFreezeDurationMs:o,frozenDurationPct:a}:void 0})).filter((e=>void 0!==e));return n.length>0&&(t.push({type:Ht.Stream,reason:qt.FrozenVideoTrack,statsSample:{ssrcs:n.map((e=>e.ssrc))}}),this.deleteLastProcessedStats(e.connection.id)),t}}class br extends cr{#m;#g;#f;constructor(e={}){super(e),this.#m=e.volatilityThreshold??8,this.#g=e.affectedStreamsPercentThreshold??30,this.#f=e.minMosQuality??zt.BAD}performDetection(e){return[...this.getAllLastProcessedStats(e.connection.id),e].find((e=>void 0!==e.networkScores.inbound&&e.networkScores.inbound<=this.#f))?[]:this.processData(e)}processData(e){const t=[],r=[...this.getAllLastProcessedStats(e.connection.id),e],n=e.video.inbound.map((e=>{if(r.length<5)return;if(vr(e.ssrc,r))return;const t=[];for(let n=0;n<r.length-1;n+=1){const i=r[n].video.inbound.find((t=>t.ssrc===e.ssrc));void 0!==i?.framesPerSecond&&t.push(i.framesPerSecond)}if(t.length<5)return;if(gr(e.ssrc,r))return;const n=(e=>{if(0===e.length)throw new Error("Cannot calculate volatility for empty array");const t=mr(e);return 0===t?0:e.reduce(((e,r)=>e+Math.abs(r-t)),0)/e.length*100/t})(t);return n>this.#m?{ssrc:e.ssrc,allFps:t,volatility:n}:void 0})).filter((e=>Boolean(e)));if(0===n.length)return t;const i=n.length/(e.video.inbound.length/100);return i>this.#g&&(t.push({type:Ht.CPU,reason:qt.DecoderCPUThrottling,statsSample:{affectedStreamsPercent:i,throtthedStreams:n}}),this.deleteLastProcessedStats(e.connection.id)),t}}class _r extends cr{#v=new Map;#y;#b;constructor(e={}){super(),this.#y=e.timeoutMs??15e3,this.#b=e.steps??3}performDetection(e){return this.processData(e)}processData(e){const t=[],r=[...this.getAllLastProcessedStats(e.connection.id),e];if(r.length<this.#b)return t;const n=r.slice(-this.#b),i=n.map((e=>e.video.inbound)),s=n.map((e=>e.audio.inbound));return t.push(...this.detectMissingData(s,Ht.Stream,qt.MissingAudioStreamData)),t.push(...this.detectMissingData(i,Ht.Stream,qt.MissingVideoStreamData)),new Set(this.#v.keys()).forEach((e=>{const t=this.#v.get(e);t&&Date.now()-t>this.#y&&this.removeMarkedIssue(e)})),t}detectMissingData(e,t,r){const n=[],i=e.pop(),s=_r.mapStatsByTrackId(e);return i.forEach((e=>{const i=e.track.trackIdentifier,o=s.get(i);if(!Array.isArray(o)||0===o.length)return;if(e.track.detached||e.track.ended)return;if(!_r.isAllBytesReceivedDidntChange(e.bytesReceived,o))return void this.removeMarkedIssue(i);if(!this.markIssue(i))return;const a={bytesReceived:e.bytesReceived};n.push({type:t,reason:r,statsSample:a,trackIdentifier:i})})),n}static mapStatsByTrackId(e){const t=new Map;return e.forEach((e=>{e.forEach((e=>{const r=t.get(e.track.trackIdentifier)||[];r.push(e),t.set(e.track.trackIdentifier,r)}))})),t}static isAllBytesReceivedDidntChange(e,t){for(let r=0;r<t.length;r+=1)if(t[r].bytesReceived!==e)return!1;return!0}markIssue(e){const t=Date.now(),r=this.#v.get(e);return(!r||t-r>this.#y)&&(this.#v.set(e,t),!0)}removeMarkedIssue(e){this.#v.delete(e)}}const Er=e=>"closed"===e.iceConnectionState||"closed"===e.connectionState,wr=(e,t,r)=>8*((e,t,r)=>{if(!t)return 0;const n=e[r],i=t[r];if(null==n||null==i)return 0;const s=Math.floor(e.timestamp)-Math.floor(t.timestamp);return 0===s?0:(Number(n)-Number(i))/s*1e3})(e,t,r);class Sr{connections=[];statsParser;constructor(e){this.statsParser=e.statsParser}listConnections(){return[...this.connections]}addPeerConnection(e){this.connections.push({id:e.id??String(Date.now()+Math.random().toString(32)),pc:e.pc})}removePeerConnection(e){const t=this.connections.findIndex((({pc:t})=>t===e.pc));t>=0&&this.removeConnectionsByIndexes([t])}async parse(){const e=[],t=this.connections.map((async(t,r)=>{if(!Er(t.pc))return this.statsParser.parse(t);e.unshift(r)}));return e.length&&this.removeConnectionsByIndexes(e),(await Promise.all(t)).filter((e=>void 0!==e))}removeConnectionsByIndexes(e){e.forEach((e=>{this.connections.splice(e,1)}))}}class Cr{prevStats=new Map;scheduleTask=or();allowedReportTypes=new Set(["candidate-pair","inbound-rtp","outbound-rtp","remote-outbound-rtp","remote-inbound-rtp","track","transport"]);ignoreSSRCList;logger;constructor(e){this.ignoreSSRCList=e.ignoreSSRCList??[],this.logger=e.logger}get previouslyParsedStatsConnectionsIds(){return[...this.prevStats.keys()]}async parse(e){if(!Er(e.pc))return this.getConnectionStats(e);this.logger.debug("Skip stats parsing. Connection is closed.",{connection:e})}async getConnectionStats(e){const{pc:t,id:r}=e;try{const n=Date.now(),i=t.getReceivers().filter((e=>e.track?.enabled)),s=t.getSenders().filter((e=>e.track?.enabled)),o=await Promise.all(i.map((e=>e.getStats()))),a=await Promise.all(s.map((e=>e.getStats())));return{id:r,stats:this.mapReportsStats([...o,...a],e),timeTaken:Date.now()-n}}catch(e){return void this.logger.error("Failed to get stats for PC",{id:r,pc:t,error:e})}}mapReportsStats(e,t){const r={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{},remote:{video:{inbound:[],outbound:[]},audio:{inbound:[],outbound:[]}}};e.forEach((e=>{e.forEach((t=>{this.allowedReportTypes.has(t.type)&&this.updateMappedStatsWithReportItemData(t,r,e)}))}));const{id:n}=t,i=this.prevStats.get(n);return i&&this.propagateStatsWithRateValues(r,i.stats),this.prevStats.set(n,{stats:r,ts:Date.now()}),this.scheduleTask({taskId:n,delayMs:35e3,callback:()=>this.prevStats.delete(n)}),r}updateMappedStatsWithReportItemData(e,t,r){const n=e.type;if("candidate-pair"===n&&"succeeded"===e.state&&e.nominated)return void(t.connection=this.prepareConnectionStats(e,r));const i=this.getMediaType(e);if(!i)return;const s=e.ssrc;if(!s||!this.ignoreSSRCList.includes(s))if("outbound-rtp"!==n)if("inbound-rtp"!==n)"remote-outbound-rtp"!==n?"remote-inbound-rtp"===n&&(this.mapConnectionStatsIfNecessary(t,e,r),t.remote[i].inbound.push({...e})):t.remote[i].outbound.push({...e});else{const n=r.get(e.trackId)||r.get(e.mediaSourceId)||{};this.mapConnectionStatsIfNecessary(t,e,r);const s={...e,track:{...n}};t[i].inbound.push(s)}else{const n=r.get(e.trackId)||r.get(e.mediaSourceId)||{},s={...e,track:{...n}};t[i].outbound.push(s)}}getMediaType(e){const t=e.mediaType||e.kind;if(!["audio","video"].includes(t)){const{id:t}=e;if(!t)return;return String(t).includes("Video")?"video":String(t).includes("Audio")?"audio":void 0}return t}propagateStatsWithRateValues(e,t){e.audio.inbound.forEach((e=>{const r=t.audio.inbound.find((({id:t})=>t===e.id));e.bitrate=wr(e,r,"bytesReceived"),e.packetRate=wr(e,r,"packetsReceived")})),e.audio.outbound.forEach((e=>{const r=t.audio.outbound.find((({id:t})=>t===e.id));e.bitrate=wr(e,r,"bytesSent"),e.packetRate=wr(e,r,"packetsSent")})),e.video.inbound.forEach((e=>{const r=t.video.inbound.find((({id:t})=>t===e.id));e.bitrate=wr(e,r,"bytesReceived"),e.packetRate=wr(e,r,"packetsReceived")})),e.video.outbound.forEach((e=>{const r=t.video.outbound.find((({id:t})=>t===e.id));e.bitrate=wr(e,r,"bytesSent"),e.packetRate=wr(e,r,"packetsSent")}))}mapConnectionStatsIfNecessary(e,t,r){if(e.connection.id||!t.transportId)return;const n=r.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=r.get(n.selectedCandidatePairId);e.connection=this.prepareConnectionStats(t,r)}}prepareConnectionStats(e,t){if(!e||!t)return{};const r={...e};if(r.remoteCandidateId){const e=t.get(r.remoteCandidateId);r.remote={...e}}if(r.localCandidateId){const e=t.get(r.localCandidateId);r.local={...e}}return r}}class Tr{eventEmitter;#_=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;autoAddPeerConnections;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new ir,e.onIssues&&this.eventEmitter.on(Wt.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(Wt.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new hr,new ur,new pr,new lr,new dr,new fr,new yr,new br,new _r],this.networkScoresCalculator=e.networkScoresCalculator??new ar,this.compositeStatsParser=e.compositeStatsParser??new Sr({statsParser:new Cr({ignoreSSRCList:e.ignoreSSRCList,logger:this.logger})}),this.statsReporter=e.statsReporter??new sr({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.autoAddPeerConnections=e.autoAddPeerConnections??!0,this.autoAddPeerConnections&&this.wrapRTCPeerConnection(),this.statsReporter.on(sr.STATS_REPORT_READY_EVENT,(e=>{const t=this.calculateNetworkScores(e.stats);this.detectIssues({data:e.stats},t)})),this.statsReporter.on(sr.STATS_REPORTS_PARSED,(t=>{const r={timeTaken:t.timeTaken,ts:Date.now()};e.onStats&&e.onStats(t.reportItems),this.eventEmitter.emit(Wt.StatsParsingFinished,r)}))}watchNewPeerConnections(){if(!this.autoAddPeerConnections)throw new Error("Auto add peer connections was disabled in the constructor.");this.#_?this.logger.warn("WebRTCIssueDetector is already started. Skip processing"):(this.logger.info("Start watching peer connections"),this.#_=!0,this.statsReporter.startReporting())}stopWatchingNewPeerConnections(){this.#_?(this.logger.info("Stop watching peer connections"),this.#_=!1,this.statsReporter.stopReporting()):this.logger.warn("WebRTCIssueDetector is already stopped. Skip processing")}handleNewPeerConnection(e,t){this.#_||!this.autoAddPeerConnections?(this.#_||!1!==this.autoAddPeerConnections||(this.logger.info("Starting stats reporting for new peer connection"),this.#_=!0,this.statsReporter.startReporting()),this.logger.debug("Handling new peer connection",e),this.compositeStatsParser.addPeerConnection({pc:e,id:t})):this.logger.debug("Skip handling new peer connection. Detector is not running",e)}emitIssues(e){this.eventEmitter.emit(Wt.Issue,e)}detectIssues({data:e},t){const r=this.detectors.reduce(((r,n)=>[...r,...n.detect(e,t)]),[]);r.length>0&&this.emitIssues(r)}calculateNetworkScores(e){const t=this.networkScoresCalculator.calculate(e);return this.eventEmitter.emit(Wt.NetworkScoresUpdated,t),t}wrapRTCPeerConnection(){if(!window.RTCPeerConnection)return void this.logger.warn("No RTCPeerConnection found in browser window. Skipping");const e=window.RTCPeerConnection,t=e=>this.handleNewPeerConnection(e);function r(r){const n=new e(r);return t(n),n}r.prototype=e.prototype,window.RTCPeerConnection=r}}const Pr=Array.from({length:256},((e,t)=>(t+256).toString(16).slice(1)));function Rr(e=24){const t=new Uint8Array(e);crypto.getRandomValues(t);let r="";for(let e=0;e<t.length;e++)r+=Pr[t[e]];return r}let kr,Dr=!1;const Ir=()=>{try{return Dr?null:window.localStorage}catch(e){return console.error("Get local storage error",{error:Vt(e)}),e instanceof Error&&"SecurityError"===e.name&&(Dr=!0),null}};function Ar(e){const t=Ir();if(!t)return null;try{const r=t.getItem(e);return r?JSON.parse(r):null}catch(e){return null}}const Or=()=>{if(kr)return kr;const e=Ar("clientUniqueId");if(e)return kr=e,e;const t=Rr(12);return kr=t,function(e,t){const r=Ir();if(r)try{r.setItem(e,JSON.stringify(t))}catch(e){console.error(e)}}("clientUniqueId",t),t},Mr=()=>{const e=Ar("clientUniqueId");return e||(null!=kr?kr:Or())};var Nr,Lr,xr,Fr,jr,Ur;let Vr=class{constructor(){Nr.set(this,void 0),Lr.set(this,void 0),xr.set(this,void 0),Fr.set(this,void 0),jr.set(this,void 0),Ur.set(this,{})}get meta(){return Object.assign(Object.assign({clUId:Mr()},a(this,Ur,"f")),{peerId:a(this,Nr,"f"),channelId:a(this,Lr,"f"),appId:a(this,xr,"f"),datacenterName:a(this,Fr,"f"),nodeId:a(this,jr,"f")})}setPeerId(e){c(this,Nr,e,"f")}setChannelId(e){c(this,Lr,e,"f")}setAppId(e){c(this,xr,e,"f")}setDatacenterName(e){c(this,Fr,e,"f")}setNodeId(e){c(this,jr,e,"f")}setExternalMeta(e){c(this,Ur,e,"f")}clear(){c(this,Nr,void 0,"f"),c(this,Lr,void 0,"f"),c(this,xr,void 0,"f"),c(this,Fr,void 0,"f"),c(this,Ur,{},"f")}};Nr=new WeakMap,Lr=new WeakMap,xr=new WeakMap,Fr=new WeakMap,jr=new WeakMap,Ur=new WeakMap,Vr=n([ot()],Vr);const Br="peer.updateAppData",Wr="channel-event",Hr="peer-joined",qr="peer-left",zr="channel-activity-confirmation-required",Gr="channel-activity-confirmation-acquired",Yr="channel-activity-confirmation-expired",$r="channel-rejoin-required",Kr="devices-list-updated",Jr="transport-connection-timeout",Qr="track-force-closed",Zr="track-failed",Xr="active-speaker-changed",en="channel-state-inconsistent",tn="connection-lost",rn="connection-restored",nn="forced-disconnect",sn="denoiser-initializing",on="channel-state-synced",an="denoiser-enabled",cn="denoiser-disabled",dn="denoiser-fallback",un="denoiser-failed",ln="effects-enabled",pn="effects-disabled",hn="effects-failed",fn="network-scores-updated",mn="volume-changed",gn="track-produced",vn="track-unproduced",yn="track-paused",bn="track-resumed",_n="track-closed",En="track-reopened",wn="track-failed",Sn="media-published",Cn="media-unpublished",Tn="publisher-paused",Pn="publisher-resumed",Rn="track-start",kn="track-end",Dn="track-paused",In="track-resumed",An="track-failed",On="app-data-updated",Mn="produce-permissions-changed",Nn="groups-changed",Ln="peer.newProducer",xn="producer.close",Fn="producer.setMaxSpatialLayer",jn="producer.requestMaxSpatialLayer",Un="consumer.close",Vn="consumer.pause",Bn="consumer.resume",Wn="consumer.changeConsumerPreferredLayers",Hn="transport.connectionTimeout",qn="transport-state";var zn;!function(e){e.CloseProducer="CloseProducer",e.Mute="Mute",e.Resume="Resume",e.Join="Join",e.Release="Release"}(zn||(zn={}));class Gn extends Error{constructor(e,t,r){super(null!=e?e:"Unexpected Livedigital SDK error"),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this.errorCode=null!=t?t:"unknown_error",this.meta=r}}class Yn extends Gn{constructor(e,t,r){super(null!=e?e:Yn.DEFAULT_MESSAGE,null!=t?t:"not_found",r)}}Yn.DEFAULT_MESSAGE="Requested resource was not found";class $n extends Gn{constructor(e,t,r){super(null!=e?e:$n.DEFAULT_MESSAGE,null!=t?t:"something_went_wrong",r)}}$n.DEFAULT_MESSAGE="Request failed";class Kn extends Gn{constructor(e,t,r){super(null!=e?e:Kn.DEFAULT_MESSAGE,null!=t?t:"timeout",r)}}Kn.DEFAULT_MESSAGE="Request timed out";const Jn=e=>e instanceof Yn||e instanceof Kn||(e=>{var t;return e instanceof $n&&void 0===(null===(t=e.meta)||void 0===t?void 0:t.status)})(e);class Qn extends Gn{constructor(e,t,r){super(null!=e?e:Qn.DEFAULT_MESSAGE,null!=t?t:"need_joined_to_channel",r)}}Qn.DEFAULT_MESSAGE="Peer must join the channel before performing this request";class Zn extends Gn{constructor(e,t,r){super(null!=e?e:Zn.DEFAULT_MESSAGE,null!=t?t:"unsupported_error",r)}}Zn.UNSUPPORTED_DEVICE_CODE="unsupported_device_error",Zn.UNSUPPORTED_OPERATION_CODE="unsupported_operation_error",Zn.DEFAULT_MESSAGE="Unsupported operation";const Xn=e=>{let t;try{t=JSON.stringify(e)}catch(e){throw new Bt("app_data_stringify_failed",e)}if(!((new TextEncoder).encode(t).length<=2048))throw new Bt("app_data_size_exceeded")};var ei={exports:{}},ti=l(ei.exports=function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=90)}({17:function(e,t,r){t.__esModule=!0,t.default=void 0;var n=r(18),i=function(){function e(){}return e.getFirstMatch=function(e,t){var r=t.match(e);return r&&r.length>0&&r[1]||""},e.getSecondMatch=function(e,t){var r=t.match(e);return r&&r.length>1&&r[2]||""},e.matchAndReturnConst=function(e,t,r){if(e.test(t))return r},e.getWindowsVersionName=function(e){switch(e){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},e.getMacOSVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),10===t[0])switch(t[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}},e.getAndroidVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0},e.getVersionPrecision=function(e){return e.split(".").length},e.compareVersions=function(t,r,n){void 0===n&&(n=!1);var i=e.getVersionPrecision(t),s=e.getVersionPrecision(r),o=Math.max(i,s),a=0,c=e.map([t,r],(function(t){var r=o-e.getVersionPrecision(t),n=t+new Array(r+1).join(".0");return e.map(n.split("."),(function(e){return new Array(20-e.length).join("0")+e})).reverse()}));for(n&&(a=o-Math.min(i,s)),o-=1;o>=a;){if(c[0][o]>c[1][o])return 1;if(c[0][o]===c[1][o]){if(o===a)return 0;o-=1}else if(c[0][o]<c[1][o])return-1}},e.map=function(e,t){var r,n=[];if(Array.prototype.map)return Array.prototype.map.call(e,t);for(r=0;r<e.length;r+=1)n.push(t(e[r]));return n},e.find=function(e,t){var r,n;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(r=0,n=e.length;r<n;r+=1){var i=e[r];if(t(i,r))return i}},e.assign=function(e){for(var t,r,n=e,i=arguments.length,s=new Array(i>1?i-1:0),o=1;o<i;o++)s[o-1]=arguments[o];if(Object.assign)return Object.assign.apply(Object,[e].concat(s));var a=function(){var e=s[t];"object"==typeof e&&null!==e&&Object.keys(e).forEach((function(t){n[t]=e[t]}))};for(t=0,r=s.length;t<r;t+=1)a();return e},e.getBrowserAlias=function(e){return n.BROWSER_ALIASES_MAP[e]},e.getBrowserTypeByAlias=function(e){return n.BROWSER_MAP[e]||""},e}();t.default=i,e.exports=t.default},18:function(e,t,r){t.__esModule=!0,t.ENGINE_MAP=t.OS_MAP=t.PLATFORMS_MAP=t.BROWSER_MAP=t.BROWSER_ALIASES_MAP=void 0,t.BROWSER_ALIASES_MAP={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},t.BROWSER_MAP={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},t.PLATFORMS_MAP={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},t.OS_MAP={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},t.ENGINE_MAP={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"}},90:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(91))&&n.__esModule?n:{default:n},s=r(18);function o(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}var a=function(){function e(){}var t,r,n;return e.getParser=function(e,t){if(void 0===t&&(t=!1),"string"!=typeof e)throw new Error("UserAgent should be a string");return new i.default(e,t)},e.parse=function(e){return new i.default(e).getResult()},t=e,n=[{key:"BROWSER_MAP",get:function(){return s.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return s.ENGINE_MAP}},{key:"OS_MAP",get:function(){return s.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return s.PLATFORMS_MAP}}],(r=null)&&o(t.prototype,r),n&&o(t,n),e}();t.default=a,e.exports=t.default},91:function(e,t,r){t.__esModule=!0,t.default=void 0;var n=c(r(92)),i=c(r(93)),s=c(r(94)),o=c(r(95)),a=c(r(17));function c(e){return e&&e.__esModule?e:{default:e}}var d=function(){function e(e,t){if(void 0===t&&(t=!1),null==e||""===e)throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},!0!==t&&this.parse()}var t=e.prototype;return t.getUA=function(){return this._ua},t.test=function(e){return e.test(this._ua)},t.parseBrowser=function(){var e=this;this.parsedResult.browser={};var t=a.default.find(n.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.browser=t.describe(this.getUA())),this.parsedResult.browser},t.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},t.getBrowserName=function(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},t.getBrowserVersion=function(){return this.getBrowser().version},t.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},t.parseOS=function(){var e=this;this.parsedResult.os={};var t=a.default.find(i.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os},t.getOSName=function(e){var t=this.getOS().name;return e?String(t).toLowerCase()||"":t||""},t.getOSVersion=function(){return this.getOS().version},t.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},t.getPlatformType=function(e){void 0===e&&(e=!1);var t=this.getPlatform().type;return e?String(t).toLowerCase()||"":t||""},t.parsePlatform=function(){var e=this;this.parsedResult.platform={};var t=a.default.find(s.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform},t.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},t.getEngineName=function(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},t.parseEngine=function(){var e=this;this.parsedResult.engine={};var t=a.default.find(o.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine},t.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},t.getResult=function(){return a.default.assign({},this.parsedResult)},t.satisfies=function(e){var t=this,r={},n=0,i={},s=0;if(Object.keys(e).forEach((function(t){var o=e[t];"string"==typeof o?(i[t]=o,s+=1):"object"==typeof o&&(r[t]=o,n+=1)})),n>0){var o=Object.keys(r),c=a.default.find(o,(function(e){return t.isOS(e)}));if(c){var d=this.satisfies(r[c]);if(void 0!==d)return d}var u=a.default.find(o,(function(e){return t.isPlatform(e)}));if(u){var l=this.satisfies(r[u]);if(void 0!==l)return l}}if(s>0){var p=Object.keys(i),h=a.default.find(p,(function(e){return t.isBrowser(e,!0)}));if(void 0!==h)return this.compareVersion(i[h])}},t.isBrowser=function(e,t){void 0===t&&(t=!1);var r=this.getBrowserName().toLowerCase(),n=e.toLowerCase(),i=a.default.getBrowserTypeByAlias(n);return t&&i&&(n=i.toLowerCase()),n===r},t.compareVersion=function(e){var t=[0],r=e,n=!1,i=this.getBrowserVersion();if("string"==typeof i)return">"===e[0]||"<"===e[0]?(r=e.substr(1),"="===e[1]?(n=!0,r=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?r=e.substr(1):"~"===e[0]&&(n=!0,r=e.substr(1)),t.indexOf(a.default.compareVersions(i,r,n))>-1},t.isOS=function(e){return this.getOSName(!0)===String(e).toLowerCase()},t.isPlatform=function(e){return this.getPlatformType(!0)===String(e).toLowerCase()},t.isEngine=function(e){return this.getEngineName(!0)===String(e).toLowerCase()},t.is=function(e,t){return void 0===t&&(t=!1),this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)},t.some=function(e){var t=this;return void 0===e&&(e=[]),e.some((function(e){return t.is(e)}))},e}();t.default=d,e.exports=t.default},92:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=/version\/(\d+(\.?_?\d+)+)/i,o=[{test:[/googlebot/i],describe:function(e){var t={name:"Googlebot"},r=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/opera/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opr\/|opios/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/SamsungBrowser/i],describe:function(e){var t={name:"Samsung Internet for Android"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Whale/i],describe:function(e){var t={name:"NAVER Whale Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MZBrowser/i],describe:function(e){var t={name:"MZ Browser"},r=i.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/focus/i],describe:function(e){var t={name:"Focus"},r=i.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/swing/i],describe:function(e){var t={name:"Swing"},r=i.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/coast/i],describe:function(e){var t={name:"Opera Coast"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(e){var t={name:"Opera Touch"},r=i.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/yabrowser/i],describe:function(e){var t={name:"Yandex Browser"},r=i.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/ucbrowser/i],describe:function(e){var t={name:"UC Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Maxthon|mxios/i],describe:function(e){var t={name:"Maxthon"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/epiphany/i],describe:function(e){var t={name:"Epiphany"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/puffin/i],describe:function(e){var t={name:"Puffin"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sleipnir/i],describe:function(e){var t={name:"Sleipnir"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/k-meleon/i],describe:function(e){var t={name:"K-Meleon"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/micromessenger/i],describe:function(e){var t={name:"WeChat"},r=i.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/qqbrowser/i],describe:function(e){var t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},r=i.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/msie|trident/i],describe:function(e){var t={name:"Internet Explorer"},r=i.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/\sedg\//i],describe:function(e){var t={name:"Microsoft Edge"},r=i.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/edg([ea]|ios)/i],describe:function(e){var t={name:"Microsoft Edge"},r=i.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/vivaldi/i],describe:function(e){var t={name:"Vivaldi"},r=i.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/seamonkey/i],describe:function(e){var t={name:"SeaMonkey"},r=i.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sailfish/i],describe:function(e){var t={name:"Sailfish"},r=i.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return r&&(t.version=r),t}},{test:[/silk/i],describe:function(e){var t={name:"Amazon Silk"},r=i.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/phantom/i],describe:function(e){var t={name:"PhantomJS"},r=i.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/slimerjs/i],describe:function(e){var t={name:"SlimerJS"},r=i.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t={name:"BlackBerry"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t={name:"WebOS Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/bada/i],describe:function(e){var t={name:"Bada"},r=i.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/tizen/i],describe:function(e){var t={name:"Tizen"},r=i.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/qupzilla/i],describe:function(e){var t={name:"QupZilla"},r=i.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/firefox|iceweasel|fxios/i],describe:function(e){var t={name:"Firefox"},r=i.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/electron/i],describe:function(e){var t={name:"Electron"},r=i.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MiuiBrowser/i],describe:function(e){var t={name:"Miui"},r=i.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/chromium/i],describe:function(e){var t={name:"Chromium"},r=i.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/chrome|crios|crmo/i],describe:function(e){var t={name:"Chrome"},r=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/GSA/i],describe:function(e){var t={name:"Google Search"},r=i.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t={name:"Android Browser"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/playstation 4/i],describe:function(e){var t={name:"PlayStation 4"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/safari|applewebkit/i],describe:function(e){var t={name:"Safari"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/.*/i],describe:function(e){var t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:i.default.getFirstMatch(t,e),version:i.default.getSecondMatch(t,e)}}}];t.default=o,e.exports=t.default},93:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18),o=[{test:[/Roku\/DVP/],describe:function(e){var t=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:s.OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe:function(e){var t=i.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe:function(e){var t=i.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),r=i.default.getWindowsVersionName(t);return{name:s.OS_MAP.Windows,version:t,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e){var t={name:s.OS_MAP.iOS},r=i.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return r&&(t.version=r),t}},{test:[/macintosh/i],describe:function(e){var t=i.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),r=i.default.getMacOSVersionName(t),n={name:s.OS_MAP.MacOS,version:t};return r&&(n.versionName=r),n}},{test:[/(ipod|iphone|ipad)/i],describe:function(e){var t=i.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:s.OS_MAP.iOS,version:t}}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t=i.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),r=i.default.getAndroidVersionName(t),n={name:s.OS_MAP.Android,version:t};return r&&(n.versionName=r),n}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t=i.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),r={name:s.OS_MAP.WebOS};return t&&t.length&&(r.version=t),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t=i.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||i.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||i.default.getFirstMatch(/\bbb(\d+)/i,e);return{name:s.OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe:function(e){var t=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe:function(e){var t=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:function(){return{name:s.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:s.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e){var t=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.PlayStation4,version:t}}}];t.default=o,e.exports=t.default},94:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18),o=[{test:[/googlebot/i],describe:function(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe:function(e){var t=i.default.getFirstMatch(/(can-l01)/i,e)&&"Nova",r={type:s.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(r.model=t),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet}}},{test:function(e){var t=e.test(/ipod|iphone/i),r=e.test(/like (ipod|iphone)/i);return t&&!r},describe:function(e){var t=i.default.getFirstMatch(/(ipod|iphone)/i,e);return{type:s.PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"blackberry"===e.getBrowserName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e){return"bada"===e.getBrowserName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"windows phone"===e.getBrowserName()},describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(e){var t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(!0)&&t>=3},describe:function(){return{type:s.PLATFORMS_MAP.tablet}}},{test:function(e){return"android"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"macos"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e){return"windows"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.desktop}}},{test:function(e){return"linux"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.desktop}}},{test:function(e){return"playstation 4"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.tv}}},{test:function(e){return"roku"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.tv}}}];t.default=o,e.exports=t.default},95:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18),o=[{test:function(e){return"microsoft edge"===e.getBrowserName(!0)},describe:function(e){if(/\sedg\//i.test(e))return{name:s.ENGINE_MAP.Blink};var t=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:s.ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe:function(e){var t={name:s.ENGINE_MAP.Trident},r=i.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){return e.test(/presto/i)},describe:function(e){var t={name:s.ENGINE_MAP.Presto},r=i.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=e.test(/gecko/i),r=e.test(/like gecko/i);return t&&!r},describe:function(e){var t={name:s.ENGINE_MAP.Gecko},r=i.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:s.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e){var t={name:s.ENGINE_MAP.WebKit},r=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}}];t.default=o,e.exports=t.default}}));function ri(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ni(e,t){const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;let i=!0;return r.forEach((r=>{const n=e[r],s=t[r],o=ri(n)&&ri(s);(o&&!ni(n,s)||!o&&n!==s)&&(i=!1)})),i}function ii(e,t,r=!1){let n=null;return function(...i){return o(this,void 0,void 0,(function*(){const s=r&&!n;"number"==typeof n&&clearTimeout(n),n=setTimeout((()=>o(this,void 0,void 0,(function*(){n=null,r||(yield e.apply(this,i))}))),t),s&&(yield e.apply(this,i))}))}}function si(e,t){return o(this,void 0,void 0,(function*(){try{return yield e()}catch(e){return void(null==t||t(e))}}))}var oi,ai;exports.TrackLabel=void 0,(oi=exports.TrackLabel||(exports.TrackLabel={})).Camera="camera",oi.CameraPreview="camera-preview",oi.Microphone="microphone",oi.MicrophonePreview="microphone-preview",oi.ScreenVideo="screen-video",oi.ScreenAudio="screen-audio",oi.CustomVideo="custom-video",oi.CustomAudio="custom-audio",oi.Unknown="unknown",exports.DeviceErrors=void 0,(ai=exports.DeviceErrors||(exports.DeviceErrors={})).NotFoundError="NotFoundError",ai.NoDevices="NoDevices",ai.DeviceIsBusy="DeviceIsBusy",ai.NotAllowedError="NotAllowedError",ai.RequestDevicesUnknownError="RequestDevicesUnknownError";const ci=e=>{var t,r;return null!==(r=null===(t=e.rtpCapabilities.codecs)||void 0===t?void 0:t.reduce(((e,t)=>{var r;const n=null===(r=t.mimeType)||void 0===r?void 0:r.toLowerCase();return n&&!e.includes(n)&&e.push(n),e}),[]))&&void 0!==r?r:[]},di=e=>["video/vp9","vp9"].includes(e.toLowerCase()),ui=e=>"opus"!==e,li=(...e)=>o(void 0,[...e],void 0,(function*(e="vp8",t=1920,r=1080){if("vp8"!==e)return!1;if("undefined"==typeof MediaStreamTrackProcessor)return!1;if("undefined"==typeof VideoEncoder||"function"!=typeof VideoEncoder.isConfigSupported)return!1;try{const{supported:n}=yield VideoEncoder.isConfigSupported({codec:e,width:t,height:r,bitrate:25e5,framerate:30});return Boolean(n)}catch(e){return!1}}));class pi{sleepMs(e){return o(this,void 0,void 0,(function*(){yield new Promise((t=>setTimeout(t,e)))}))}now(){return new Date(Date.now())}}const hi=new pi,fi=(e,...t)=>o(void 0,[e,...t],void 0,(function*(e,t={}){var r,n,i,s;const o=null!==(r=t.maxRetries)&&void 0!==r?r:2,a=null!==(n=t.minBackoffDelayMs)&&void 0!==n?n:50;let c,d=0;for(;d<o;){d+=1;try{return yield e()}catch(e){if(c=e,t.logger&&t.logger.info("Action retry failed",{currentAttempt:d,actionName:t.actionName,error:Vt(e)}),null===(i=t.abortOnError)||void 0===i?void 0:i.call(t,e))throw c;if(t.onError&&(yield t.onError(e)),d<o){const e=Math.pow(2,d-1)*a;yield hi.sleepMs(Math.min(e,null!==(s=t.maxBackoffDelayMs)&&void 0!==s?s:e))}}}throw null!=c?c:new Error("retryAsync logic failed")}));var mi;!function(e){e.Config="Config",e.Engine="Engine",e.System="System",e.Media="Media",e.Network="Network",e.MediaEventHandler="MediaEventHandler",e.ChannelEventHandler="ChannelEventHandler",e.ChannelAudioObserverEventHandler="ChannelAudioObserverEventHandler",e.ChannelAudioObserverMissingProducerRestorer="ChannelAudioObserverMissingProducerRestorer",e.ChannelStateSynchronizer="ChannelStateSynchronizer",e.ChannelStateSyncEventHandler="ChannelStateSyncEventHandler",e.CompositeStatsParser="CompositeStatsParser",e.PeriodicStatsReporter="PeriodicStatsReporter",e.WIDIgnoreSsrcList="WIDIgnoreSsrcList",e.WebRTCIssueDetector="WebRTCIssueDetector",e.NetworkScoresUpdatedEventHandler="NetworkScoresUpdatedEventHandler",e.WIDStatsAdapter="WIDStatsAdapter",e.ScoresCalculator="ScoresCalculator",e.LoggerFactory="LoggerFactory",e.MediaStreamTrackManager="MediaStreamTrackManager",e.EventsQueue="EventsQueue",e.ClientEventEmitter="ClientEventEmitter",e.Peers="Peers",e.CallState="CallState",e.RemotePeerTracks="RemotePeerTracks",e.MyPeer="MyPeer",e.InternalEventEmitter="InternalEventEmitter",e.PeerTrackFactory="PeerTrackFactory",e.PeerFactory="PeerFactory",e.PeerConsumerFactory="PeerConsumerFactory",e.AudioTrackFactory="AudioTrackFactory",e.VideoTrackFactory="VideoTrackFactory",e.EncodedVideoTrackFactory="EncodedVideoTrackFactory",e.AudioTrackProcessorFactory="AudioTrackProcessorFactory",e.IntegrationsService="IntegrationsService",e.ProcessorsCache="ProcessorsCache",e.StatsHandler="StatsHandler",e.DataChannelsManager="DataChannelsManager",e.WIDHandler="WIDHandler",e.AnalyticsApiClient="AnalyticsApiClient",e.TransportsStatsProvider="TransportsStatsProvider",e.LocalMutex="LocalMutex",e.PeersStorage="PeersStorage",e.SignalingApiClient="SignalingApiClient",e.DatachannelHeartbeater="DatachannelHeartbeater",e.SignalingHeartbeater="SignalingHeartbeater",e.PendingClosureProducerStorage="PendingClosureProducerStorage",e.ProducerCloseManager="ProducerCloseManager",e.NetworkTransportPolicyManager="NetworkTransportPolicyManager",e.ClientMetaProvider="ClientMetaProvider",e.TransportStateMonitor="TransportStateMonitor",e.IceRecoveryService="IceRecoveryService"}(mi||(mi={}));let gi=class{constructor(){this.isJoined=!1,this.isChannelJoining=!1}reset(){this.appId=void 0,this.channelId=void 0,this.isJoined=!1,this.isChannelJoining=!1}};function vi(){let e=0,t=0;for(let r=0;r<28;r+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<r,0==(128&n))return this.assertBounds(),[e,t]}let r=this.buf[this.pos++];if(e|=(15&r)<<28,t=(112&r)>>4,0==(128&r))return this.assertBounds(),[e,t];for(let r=3;r<=31;r+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<r,0==(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function yi(e,t,r){for(let n=0;n<28;n+=7){const i=e>>>n,s=!(i>>>7==0&&0==t),o=255&(s?128|i:i);if(r.push(o),!s)return}const n=e>>>28&15|(7&t)<<4,i=!(t>>3==0);if(r.push(255&(i?128|n:n)),i){for(let e=3;e<31;e+=7){const n=t>>>e,i=!(n>>>7==0),s=255&(i?128|n:n);if(r.push(s),!i)return}r.push(t>>>31&1)}}gi=n([ot()],gi);function bi(e){const t="-"===e[0];t&&(e=e.slice(1));const r=1e6;let n=0,i=0;function s(t,s){const o=Number(e.slice(t,s));i*=r,n=n*r+o,n>=4294967296&&(i+=n/4294967296|0,n%=4294967296)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),t?wi(n,i):Ei(n,i)}function _i(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(4294967296*t+e);const r=16777215&(e>>>24|t<<8),n=t>>16&65535;let i=(16777215&e)+6777216*r+6710656*n,s=r+8147497*n,o=2*n;const a=1e7;return i>=a&&(s+=Math.floor(i/a),i%=a),s>=a&&(o+=Math.floor(s/a),s%=a),o.toString()+Si(s)+Si(i)}function Ei(e,t){return{lo:0|e,hi:0|t}}function wi(e,t){return t=~t,e?e=1+~e:t+=1,Ei(e,t)}const Si=e=>{const t=String(e);return"0000000".slice(t.length)+t};function Ci(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let r=0;r<9;r++)t.push(127&e|128),e>>=7;t.push(1)}}function Ti(){let e=this.buf[this.pos++],t=127&e;if(0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,0==(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;0!=(128&e)&&t<10;t++)e=this.buf[this.pos++];if(0!=(128&e))throw new Error("invalid varint");return this.assertBounds(),t>>>0}const Pi=Ri();function Ri(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),n=BigInt("0"),i=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>r||n<t)throw new Error(`invalid int64: ${e}`);return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>i||t<n)throw new Error(`invalid uint64: ${e}`);return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,r)=>(e.setInt32(0,t,!0),e.setInt32(4,r,!0),e.getBigInt64(0,!0)),uDec:(t,r)=>(e.setInt32(0,t,!0),e.setInt32(4,r,!0),e.getBigUint64(0,!0))}}return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),ki(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),Di(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),ki(e),bi(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),Di(e),bi(e)),dec:(e,t)=>function(e,t){let r=Ei(e,t);const n=2147483648&r.hi;n&&(r=wi(r.lo,r.hi));const i=_i(r.lo,r.hi);return n?"-"+i:i}(e,t),uDec:(e,t)=>_i(e,t)}}function ki(e){if(!/^-?[0-9]+$/.test(e))throw new Error("invalid int64: "+e)}function Di(e){if(!/^[0-9]+$/.test(e))throw new Error("invalid uint64: "+e)}const Ii=Symbol.for("@bufbuild/protobuf/text-encoding");function Ai(){if(null==globalThis[Ii]){const e=new globalThis.TextEncoder,t=new globalThis.TextDecoder;globalThis[Ii]={encodeUtf8:t=>e.encode(t),decodeUtf8:e=>t.decode(e),checkUtf8(e){try{return encodeURIComponent(e),!0}catch(e){return!1}}}}return globalThis[Ii]}var Oi;!function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(Oi||(Oi={}));const Mi=34028234663852886e22,Ni=-34028234663852886e22;class Li{constructor(e=Ai().encodeUtf8){this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),r=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],r),r+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(ji(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return Fi(e),Ci(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.encodeUtf8(e);return this.uint32(t.byteLength),this.raw(t)}float(e){!function(e){if("string"==typeof e){const t=e;if(e=Number(e),Number.isNaN(e)&&"NaN"!==t)throw new Error("invalid float32: "+t)}else if("number"!=typeof e)throw new Error("invalid float32: "+typeof e);if(Number.isFinite(e)&&(e>Mi||e<Ni))throw new Error("invalid float32: "+e)}(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){ji(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Fi(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Fi(e),Ci(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),r=new DataView(t.buffer),n=Pi.enc(e);return r.setInt32(0,n.lo,!0),r.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),r=new DataView(t.buffer),n=Pi.uEnc(e);return r.setInt32(0,n.lo,!0),r.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=Pi.enc(e);return yi(t.lo,t.hi,this.buf),this}sint64(e){const t=Pi.enc(e),r=t.hi>>31;return yi(t.lo<<1^r,(t.hi<<1|t.lo>>>31)^r,this.buf),this}uint64(e){const t=Pi.uEnc(e);return yi(t.lo,t.hi,this.buf),this}}class xi{constructor(e,t=Ai().decodeUtf8){this.decodeUtf8=t,this.varint64=vi,this.uint32=Ti,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.uint32(),t=e>>>3,r=7&e;if(t<=0||r<0||r>5)throw new Error("illegal tag: field no "+t+" wire type "+r);return[t,r]}skip(e,t){let r=this.pos;switch(e){case Oi.Varint:for(;128&this.buf[this.pos++];);break;case Oi.Bit64:this.pos+=4;case Oi.Bit32:this.pos+=4;break;case Oi.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Oi.StartGroup:for(;;){const[e,r]=this.tag();if(r===Oi.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(r,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(r,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return Pi.dec(...this.varint64())}uint64(){return Pi.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),r=-(1&e);return e=(e>>>1|(1&t)<<31)^r,t=t>>>1^r,Pi.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Pi.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Pi.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.decodeUtf8(this.bytes())}}function Fi(e){if("string"==typeof e)e=Number(e);else if("number"!=typeof e)throw new Error("invalid int32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int32: "+e)}function ji(e){if("string"==typeof e)e=Number(e);else if("number"!=typeof e)throw new Error("invalid uint32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint32: "+e)}const Ui={encode:(e,t=new Li)=>(0!==e.time&&t.uint32(8).int64(e.time),t),decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={time:0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(8!==e)break;i.time=Vi(r.int64());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON(e){return{time:(t=e.time,null!=t?globalThis.Number(e.time):0)};var t},toJSON(e){const t={};return 0!==e.time&&(t.time=Math.round(e.time)),t},create:e=>Ui.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={time:0};return r.time=null!==(t=e.time)&&void 0!==t?t:0,r}};function Vi(e){const t=globalThis.Number(e.toString());if(t>globalThis.Number.MAX_SAFE_INTEGER)throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");if(t<globalThis.Number.MIN_SAFE_INTEGER)throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");return t}var Bi;function Wi(e){switch(e){case 0:case"NULL_VALUE":return Bi.NULL_VALUE;default:return Bi.UNRECOGNIZED}}!function(e){e[e.NULL_VALUE=0]="NULL_VALUE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Bi||(Bi={}));const Hi={encode:(e,t=new Li)=>(Object.entries(e.fields).forEach((([e,r])=>{void 0!==r&&qi.encode({key:e,value:r},t.uint32(10).fork()).join()})),t),decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={fields:{}};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:{if(10!==e)break;const t=qi.decode(r,r.uint32());void 0!==t.value&&(i.fields[t.key]=t.value);continue}}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({fields:Yi(e.fields)?Object.entries(e.fields).reduce(((e,[t,r])=>(e[t]=r,e)),{}):{}}),toJSON(e){const t={};if(e.fields){const r=Object.entries(e.fields);r.length>0&&(t.fields={},r.forEach((([e,r])=>{t.fields[e]=r})))}return t},create:e=>Hi.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={fields:{}};return r.fields=Object.entries(null!==(t=e.fields)&&void 0!==t?t:{}).reduce(((e,[t,r])=>(void 0!==r&&(e[t]=r),e)),{}),r},wrap(e){const t={fields:{}};if(void 0!==e)for(const r of Object.keys(e))t.fields[r]=e[r];return t},unwrap(e){const t={};if(e.fields)for(const r of Object.keys(e.fields))t[r]=e.fields[r];return t}};const qi={encode:(e,t=new Li)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&zi.encode(zi.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={key:"",value:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.key=r.string();continue;case 2:if(18!==e)break;i.value=zi.unwrap(zi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:$i(e.key)?globalThis.String(e.key):"",value:$i(null==e?void 0:e.value)?e.value:void 0}),toJSON(e){const t={};return""!==e.key&&(t.key=e.key),void 0!==e.value&&(t.value=e.value),t},create:e=>qi.fromPartial(null!=e?e:{}),fromPartial(e){var t,r;const n={key:"",value:void 0};return n.key=null!==(t=e.key)&&void 0!==t?t:"",n.value=null!==(r=e.value)&&void 0!==r?r:void 0,n}};const zi={encode:(e,t=new Li)=>(void 0!==e.nullValue&&t.uint32(8).int32(e.nullValue),void 0!==e.numberValue&&t.uint32(17).double(e.numberValue),void 0!==e.stringValue&&t.uint32(26).string(e.stringValue),void 0!==e.boolValue&&t.uint32(32).bool(e.boolValue),void 0!==e.structValue&&Hi.encode(Hi.wrap(e.structValue),t.uint32(42).fork()).join(),void 0!==e.listValue&&Gi.encode(Gi.wrap(e.listValue),t.uint32(50).fork()).join(),t),decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(8!==e)break;i.nullValue=r.int32();continue;case 2:if(17!==e)break;i.numberValue=r.double();continue;case 3:if(26!==e)break;i.stringValue=r.string();continue;case 4:if(32!==e)break;i.boolValue=r.bool();continue;case 5:if(42!==e)break;i.structValue=Hi.unwrap(Hi.decode(r,r.uint32()));continue;case 6:if(50!==e)break;i.listValue=Gi.unwrap(Gi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({nullValue:$i(e.nullValue)?Wi(e.nullValue):void 0,numberValue:$i(e.numberValue)?globalThis.Number(e.numberValue):void 0,stringValue:$i(e.stringValue)?globalThis.String(e.stringValue):void 0,boolValue:$i(e.boolValue)?globalThis.Boolean(e.boolValue):void 0,structValue:Yi(e.structValue)?e.structValue:void 0,listValue:globalThis.Array.isArray(e.listValue)?[...e.listValue]:void 0}),toJSON(e){const t={};return void 0!==e.nullValue&&(t.nullValue=function(e){switch(e){case Bi.NULL_VALUE:return"NULL_VALUE";case Bi.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.nullValue)),void 0!==e.numberValue&&(t.numberValue=e.numberValue),void 0!==e.stringValue&&(t.stringValue=e.stringValue),void 0!==e.boolValue&&(t.boolValue=e.boolValue),void 0!==e.structValue&&(t.structValue=e.structValue),void 0!==e.listValue&&(t.listValue=e.listValue),t},create:e=>zi.fromPartial(null!=e?e:{}),fromPartial(e){var t,r,n,i,s,o;const a={nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0};return a.nullValue=null!==(t=e.nullValue)&&void 0!==t?t:void 0,a.numberValue=null!==(r=e.numberValue)&&void 0!==r?r:void 0,a.stringValue=null!==(n=e.stringValue)&&void 0!==n?n:void 0,a.boolValue=null!==(i=e.boolValue)&&void 0!==i?i:void 0,a.structValue=null!==(s=e.structValue)&&void 0!==s?s:void 0,a.listValue=null!==(o=e.listValue)&&void 0!==o?o:void 0,a},wrap(e){const t={nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0};if(null===e)t.nullValue=Bi.NULL_VALUE;else if("boolean"==typeof e)t.boolValue=e;else if("number"==typeof e)t.numberValue=e;else if("string"==typeof e)t.stringValue=e;else if(globalThis.Array.isArray(e))t.listValue=e;else if("object"==typeof e)t.structValue=e;else if(void 0!==e)throw new globalThis.Error("Unsupported any value type: "+typeof e);return t},unwrap:e=>void 0!==e.stringValue?e.stringValue:void 0!==(null==e?void 0:e.numberValue)?e.numberValue:void 0!==(null==e?void 0:e.boolValue)?e.boolValue:void 0!==(null==e?void 0:e.structValue)?e.structValue:void 0!==(null==e?void 0:e.listValue)?e.listValue:void 0!==(null==e?void 0:e.nullValue)?null:void 0};const Gi={encode(e,t=new Li){for(const r of e.values)zi.encode(zi.wrap(r),t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={values:[]};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.values.push(zi.unwrap(zi.decode(r,r.uint32())));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({values:globalThis.Array.isArray(null==e?void 0:e.values)?[...e.values]:[]}),toJSON(e){var t;const r={};return(null===(t=e.values)||void 0===t?void 0:t.length)&&(r.values=e.values),r},create:e=>Gi.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={values:[]};return r.values=(null===(t=e.values)||void 0===t?void 0:t.map((e=>e)))||[],r},wrap(e){const t={values:[]};return t.values=null!=e?e:[],t},unwrap:e=>(null==e?void 0:e.hasOwnProperty("values"))&&globalThis.Array.isArray(e.values)?e.values:e};function Yi(e){return"object"==typeof e&&null!==e}function $i(e){return null!=e}const Ki={encode:(e,t=new Li)=>(Object.entries(e.event).forEach((([e,r])=>{void 0!==r&&Ji.encode({key:e,value:r},t.uint32(10).fork()).join()})),t),decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={event:{}};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:{if(10!==e)break;const t=Ji.decode(r,r.uint32());void 0!==t.value&&(i.event[t.key]=t.value);continue}}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON(e){return{event:(t=e.event,"object"==typeof t&&null!==t?Object.entries(e.event).reduce(((e,[t,r])=>(e[t]=r,e)),{}):{})};var t},toJSON(e){const t={};if(e.event){const r=Object.entries(e.event);r.length>0&&(t.event={},r.forEach((([e,r])=>{t.event[e]=r})))}return t},create:e=>Ki.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={event:{}};return r.event=Object.entries(null!==(t=e.event)&&void 0!==t?t:{}).reduce(((e,[t,r])=>(void 0!==r&&(e[t]=r),e)),{}),r}};const Ji={encode:(e,t=new Li)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&zi.encode(zi.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={key:"",value:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.key=r.string();continue;case 2:if(18!==e)break;i.value=zi.unwrap(zi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:Qi(e.key)?globalThis.String(e.key):"",value:Qi(null==e?void 0:e.value)?e.value:void 0}),toJSON(e){const t={};return""!==e.key&&(t.key=e.key),void 0!==e.value&&(t.value=e.value),t},create:e=>Ji.fromPartial(null!=e?e:{}),fromPartial(e){var t,r;const n={key:"",value:void 0};return n.key=null!==(t=e.key)&&void 0!==t?t:"",n.value=null!==(r=e.value)&&void 0!==r?r:void 0,n}};function Qi(e){return null!=e}var Zi,Xi;function es(e){switch(e){case 0:case"PEER_GROUP_UNSPECIFIED":return Zi.PEER_GROUP_UNSPECIFIED;case 1:case"PEER_GROUP_MODERATOR":return Zi.PEER_GROUP_MODERATOR;case 2:case"PEER_GROUP_USER":return Zi.PEER_GROUP_USER;default:return Zi.UNRECOGNIZED}}function ts(e){switch(e){case Zi.PEER_GROUP_UNSPECIFIED:return"PEER_GROUP_UNSPECIFIED";case Zi.PEER_GROUP_MODERATOR:return"PEER_GROUP_MODERATOR";case Zi.PEER_GROUP_USER:return"PEER_GROUP_USER";case Zi.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function rs(e){switch(e){case 0:case"PRODUCER_LABEL_UNSPECIFIED":return Xi.PRODUCER_LABEL_UNSPECIFIED;case 1:case"PRODUCER_LABEL_CAMERA":return Xi.PRODUCER_LABEL_CAMERA;case 2:case"PRODUCER_LABEL_MICROPHONE":return Xi.PRODUCER_LABEL_MICROPHONE;case 3:case"PRODUCER_LABEL_SCREEN_VIDEO":return Xi.PRODUCER_LABEL_SCREEN_VIDEO;case 4:case"PRODUCER_LABEL_SCREEN_AUDIO":return Xi.PRODUCER_LABEL_SCREEN_AUDIO;case 5:case"PRODUCER_LABEL_CUSTOM_VIDEO":return Xi.PRODUCER_LABEL_CUSTOM_VIDEO;case 6:case"PRODUCER_LABEL_CUSTOM_AUDIO":return Xi.PRODUCER_LABEL_CUSTOM_AUDIO;case 7:case"PRODUCER_LABEL_UNKNOWN":return Xi.PRODUCER_LABEL_UNKNOWN;default:return Xi.UNRECOGNIZED}}function ns(e){switch(e){case Xi.PRODUCER_LABEL_UNSPECIFIED:return"PRODUCER_LABEL_UNSPECIFIED";case Xi.PRODUCER_LABEL_CAMERA:return"PRODUCER_LABEL_CAMERA";case Xi.PRODUCER_LABEL_MICROPHONE:return"PRODUCER_LABEL_MICROPHONE";case Xi.PRODUCER_LABEL_SCREEN_VIDEO:return"PRODUCER_LABEL_SCREEN_VIDEO";case Xi.PRODUCER_LABEL_SCREEN_AUDIO:return"PRODUCER_LABEL_SCREEN_AUDIO";case Xi.PRODUCER_LABEL_CUSTOM_VIDEO:return"PRODUCER_LABEL_CUSTOM_VIDEO";case Xi.PRODUCER_LABEL_CUSTOM_AUDIO:return"PRODUCER_LABEL_CUSTOM_AUDIO";case Xi.PRODUCER_LABEL_UNKNOWN:return"PRODUCER_LABEL_UNKNOWN";case Xi.UNRECOGNIZED:default:return"UNRECOGNIZED"}}!function(e){e[e.PEER_GROUP_UNSPECIFIED=0]="PEER_GROUP_UNSPECIFIED",e[e.PEER_GROUP_MODERATOR=1]="PEER_GROUP_MODERATOR",e[e.PEER_GROUP_USER=2]="PEER_GROUP_USER",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Zi||(Zi={})),function(e){e[e.PRODUCER_LABEL_UNSPECIFIED=0]="PRODUCER_LABEL_UNSPECIFIED",e[e.PRODUCER_LABEL_CAMERA=1]="PRODUCER_LABEL_CAMERA",e[e.PRODUCER_LABEL_MICROPHONE=2]="PRODUCER_LABEL_MICROPHONE",e[e.PRODUCER_LABEL_SCREEN_VIDEO=3]="PRODUCER_LABEL_SCREEN_VIDEO",e[e.PRODUCER_LABEL_SCREEN_AUDIO=4]="PRODUCER_LABEL_SCREEN_AUDIO",e[e.PRODUCER_LABEL_CUSTOM_VIDEO=5]="PRODUCER_LABEL_CUSTOM_VIDEO",e[e.PRODUCER_LABEL_CUSTOM_AUDIO=6]="PRODUCER_LABEL_CUSTOM_AUDIO",e[e.PRODUCER_LABEL_UNKNOWN=7]="PRODUCER_LABEL_UNKNOWN",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Xi||(Xi={}));const is={encode(e,t=new Li){t.uint32(10).fork();for(const r of e.groups)t.int32(r);t.join(),t.uint32(18).fork();for(const r of e.producePermissions)t.int32(r);t.join(),t.uint32(26).fork();for(const r of e.changedProducePermissions)t.int32(r);return t.join(),t},decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={groups:[],producePermissions:[],changedProducePermissions:[]};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(8===e){i.groups.push(r.int32());continue}if(10===e){const e=r.uint32()+r.pos;for(;r.pos<e;)i.groups.push(r.int32());continue}break;case 2:if(16===e){i.producePermissions.push(r.int32());continue}if(18===e){const e=r.uint32()+r.pos;for(;r.pos<e;)i.producePermissions.push(r.int32());continue}break;case 3:if(24===e){i.changedProducePermissions.push(r.int32());continue}if(26===e){const e=r.uint32()+r.pos;for(;r.pos<e;)i.changedProducePermissions.push(r.int32());continue}}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({groups:globalThis.Array.isArray(null==e?void 0:e.groups)?e.groups.map((e=>es(e))):[],producePermissions:globalThis.Array.isArray(null==e?void 0:e.producePermissions)?e.producePermissions.map((e=>rs(e))):[],changedProducePermissions:globalThis.Array.isArray(null==e?void 0:e.changedProducePermissions)?e.changedProducePermissions.map((e=>rs(e))):[]}),toJSON(e){var t,r,n;const i={};return(null===(t=e.groups)||void 0===t?void 0:t.length)&&(i.groups=e.groups.map((e=>ts(e)))),(null===(r=e.producePermissions)||void 0===r?void 0:r.length)&&(i.producePermissions=e.producePermissions.map((e=>ns(e)))),(null===(n=e.changedProducePermissions)||void 0===n?void 0:n.length)&&(i.changedProducePermissions=e.changedProducePermissions.map((e=>ns(e)))),i},create:e=>is.fromPartial(null!=e?e:{}),fromPartial(e){var t,r,n;const i={groups:[],producePermissions:[],changedProducePermissions:[]};return i.groups=(null===(t=e.groups)||void 0===t?void 0:t.map((e=>e)))||[],i.producePermissions=(null===(r=e.producePermissions)||void 0===r?void 0:r.map((e=>e)))||[],i.changedProducePermissions=(null===(n=e.changedProducePermissions)||void 0===n?void 0:n.map((e=>e)))||[],i}};const ss={encode:(e,t=new Li)=>(0!==e.seconds&&t.uint32(8).int64(e.seconds),0!==e.nanos&&t.uint32(16).int32(e.nanos),t),decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={seconds:0,nanos:0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(8!==e)break;i.seconds=os(r.int64());continue;case 2:if(16!==e)break;i.nanos=r.int32();continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({seconds:as(e.seconds)?globalThis.Number(e.seconds):0,nanos:as(e.nanos)?globalThis.Number(e.nanos):0}),toJSON(e){const t={};return 0!==e.seconds&&(t.seconds=Math.round(e.seconds)),0!==e.nanos&&(t.nanos=Math.round(e.nanos)),t},create:e=>ss.fromPartial(null!=e?e:{}),fromPartial(e){var t,r;const n={seconds:0,nanos:0};return n.seconds=null!==(t=e.seconds)&&void 0!==t?t:0,n.nanos=null!==(r=e.nanos)&&void 0!==r?r:0,n}};function os(e){const t=globalThis.Number(e.toString());if(t>globalThis.Number.MAX_SAFE_INTEGER)throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");if(t<globalThis.Number.MIN_SAFE_INTEGER)throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");return t}function as(e){return null!=e}var cs;function ds(e){switch(e){case 0:case"PRODUCER_KIND_UNSPECIFIED":return cs.PRODUCER_KIND_UNSPECIFIED;case 1:case"PRODUCER_KIND_AUDIO":return cs.PRODUCER_KIND_AUDIO;case 2:case"PRODUCER_KIND_VIDEO":return cs.PRODUCER_KIND_VIDEO;default:return cs.UNRECOGNIZED}}!function(e){e[e.PRODUCER_KIND_UNSPECIFIED=0]="PRODUCER_KIND_UNSPECIFIED",e[e.PRODUCER_KIND_AUDIO=1]="PRODUCER_KIND_AUDIO",e[e.PRODUCER_KIND_VIDEO=2]="PRODUCER_KIND_VIDEO",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(cs||(cs={}));const us={encode(e,t=new Li){""!==e.id&&t.uint32(10).string(e.id),0!==e.kind&&t.uint32(16).int32(e.kind),0!==e.label&&t.uint32(24).int32(e.label),""!==e.peerId&&t.uint32(34).string(e.peerId),!1!==e.paused&&t.uint32(40).bool(e.paused);for(const r of e.encodings)zi.encode(zi.wrap(r),t.uint32(50).fork()).join();return void 0!==e.maxSpatialLayer&&t.uint32(56).uint32(e.maxSpatialLayer),t},decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={id:"",kind:0,label:0,peerId:"",paused:!1,encodings:[],maxSpatialLayer:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.id=r.string();continue;case 2:if(16!==e)break;i.kind=r.int32();continue;case 3:if(24!==e)break;i.label=r.int32();continue;case 4:if(34!==e)break;i.peerId=r.string();continue;case 5:if(40!==e)break;i.paused=r.bool();continue;case 6:if(50!==e)break;i.encodings.push(zi.unwrap(zi.decode(r,r.uint32())));continue;case 7:if(56!==e)break;i.maxSpatialLayer=r.uint32();continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({id:ls(e.id)?globalThis.String(e.id):"",kind:ls(e.kind)?ds(e.kind):0,label:ls(e.label)?rs(e.label):0,peerId:ls(e.peerId)?globalThis.String(e.peerId):"",paused:!!ls(e.paused)&&globalThis.Boolean(e.paused),encodings:globalThis.Array.isArray(null==e?void 0:e.encodings)?[...e.encodings]:[],maxSpatialLayer:ls(e.maxSpatialLayer)?globalThis.Number(e.maxSpatialLayer):void 0}),toJSON(e){var t;const r={};return""!==e.id&&(r.id=e.id),0!==e.kind&&(r.kind=function(e){switch(e){case cs.PRODUCER_KIND_UNSPECIFIED:return"PRODUCER_KIND_UNSPECIFIED";case cs.PRODUCER_KIND_AUDIO:return"PRODUCER_KIND_AUDIO";case cs.PRODUCER_KIND_VIDEO:return"PRODUCER_KIND_VIDEO";case cs.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.kind)),0!==e.label&&(r.label=ns(e.label)),""!==e.peerId&&(r.peerId=e.peerId),!1!==e.paused&&(r.paused=e.paused),(null===(t=e.encodings)||void 0===t?void 0:t.length)&&(r.encodings=e.encodings),void 0!==e.maxSpatialLayer&&(r.maxSpatialLayer=Math.round(e.maxSpatialLayer)),r},create:e=>us.fromPartial(null!=e?e:{}),fromPartial(e){var t,r,n,i,s,o,a;const c={id:"",kind:0,label:0,peerId:"",paused:!1,encodings:[],maxSpatialLayer:void 0};return c.id=null!==(t=e.id)&&void 0!==t?t:"",c.kind=null!==(r=e.kind)&&void 0!==r?r:0,c.label=null!==(n=e.label)&&void 0!==n?n:0,c.peerId=null!==(i=e.peerId)&&void 0!==i?i:"",c.paused=null!==(s=e.paused)&&void 0!==s&&s,c.encodings=(null===(o=e.encodings)||void 0===o?void 0:o.map((e=>e)))||[],c.maxSpatialLayer=null!==(a=e.maxSpatialLayer)&&void 0!==a?a:void 0,c}};function ls(e){return null!=e}var ps;function hs(e){switch(e){case 0:case"PEER_ROLE_UNSPECIFIED":return ps.PEER_ROLE_UNSPECIFIED;case 1:case"PEER_ROLE_HOST":return ps.PEER_ROLE_HOST;case 2:case"PEER_ROLE_AUDIENCE":return ps.PEER_ROLE_AUDIENCE;default:return ps.UNRECOGNIZED}}!function(e){e[e.PEER_ROLE_UNSPECIFIED=0]="PEER_ROLE_UNSPECIFIED",e[e.PEER_ROLE_HOST=1]="PEER_ROLE_HOST",e[e.PEER_ROLE_AUDIENCE=2]="PEER_ROLE_AUDIENCE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(ps||(ps={}));const fs={encode(e,t=new Li){""!==e.id&&t.uint32(10).string(e.id);for(const r of e.channelIds)t.uint32(18).string(r);for(const r of e.producers)us.encode(r,t.uint32(26).fork()).join();""!==e.uid&&t.uint32(50).string(e.uid),""!==e.appId&&t.uint32(58).string(e.appId),Object.entries(e.appData).forEach((([e,r])=>{void 0!==r&&ms.encode({key:e,value:r},t.uint32(66).fork()).join()})),0!==e.role&&t.uint32(72).int32(e.role),void 0!==e.loginDate&&ss.encode(function(e){const t=Math.trunc(e.getTime()/1e3),r=e.getTime()%1e3*1e6;return{seconds:t,nanos:r}}(e.loginDate),t.uint32(82).fork()).join(),t.uint32(90).fork();for(const r of e.groups)t.int32(r);t.join(),t.uint32(98).fork();for(const r of e.producePermissions)t.int32(r);return t.join(),t},decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={id:"",channelIds:[],producers:[],uid:"",appId:"",appData:{},role:0,loginDate:void 0,groups:[],producePermissions:[]};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.id=r.string();continue;case 2:if(18!==e)break;i.channelIds.push(r.string());continue;case 3:if(26!==e)break;i.producers.push(us.decode(r,r.uint32()));continue;case 6:if(50!==e)break;i.uid=r.string();continue;case 7:if(58!==e)break;i.appId=r.string();continue;case 8:{if(66!==e)break;const t=ms.decode(r,r.uint32());void 0!==t.value&&(i.appData[t.key]=t.value);continue}case 9:if(72!==e)break;i.role=r.int32();continue;case 10:if(82!==e)break;i.loginDate=gs(ss.decode(r,r.uint32()));continue;case 11:if(88===e){i.groups.push(r.int32());continue}if(90===e){const e=r.uint32()+r.pos;for(;r.pos<e;)i.groups.push(r.int32());continue}break;case 12:if(96===e){i.producePermissions.push(r.int32());continue}if(98===e){const e=r.uint32()+r.pos;for(;r.pos<e;)i.producePermissions.push(r.int32());continue}}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON(e){return{id:ys(e.id)?globalThis.String(e.id):"",channelIds:globalThis.Array.isArray(null==e?void 0:e.channelIds)?e.channelIds.map((e=>globalThis.String(e))):[],producers:globalThis.Array.isArray(null==e?void 0:e.producers)?e.producers.map((e=>us.fromJSON(e))):[],uid:ys(e.uid)?globalThis.String(e.uid):"",appId:ys(e.appId)?globalThis.String(e.appId):"",appData:(t=e.appData,"object"==typeof t&&null!==t?Object.entries(e.appData).reduce(((e,[t,r])=>(e[t]=r,e)),{}):{}),role:ys(e.role)?hs(e.role):0,loginDate:ys(e.loginDate)?vs(e.loginDate):void 0,groups:globalThis.Array.isArray(null==e?void 0:e.groups)?e.groups.map((e=>es(e))):[],producePermissions:globalThis.Array.isArray(null==e?void 0:e.producePermissions)?e.producePermissions.map((e=>rs(e))):[]};var t},toJSON(e){var t,r,n,i;const s={};if(""!==e.id&&(s.id=e.id),(null===(t=e.channelIds)||void 0===t?void 0:t.length)&&(s.channelIds=e.channelIds),(null===(r=e.producers)||void 0===r?void 0:r.length)&&(s.producers=e.producers.map((e=>us.toJSON(e)))),""!==e.uid&&(s.uid=e.uid),""!==e.appId&&(s.appId=e.appId),e.appData){const t=Object.entries(e.appData);t.length>0&&(s.appData={},t.forEach((([e,t])=>{s.appData[e]=t})))}return 0!==e.role&&(s.role=function(e){switch(e){case ps.PEER_ROLE_UNSPECIFIED:return"PEER_ROLE_UNSPECIFIED";case ps.PEER_ROLE_HOST:return"PEER_ROLE_HOST";case ps.PEER_ROLE_AUDIENCE:return"PEER_ROLE_AUDIENCE";case ps.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.role)),void 0!==e.loginDate&&(s.loginDate=e.loginDate.toISOString()),(null===(n=e.groups)||void 0===n?void 0:n.length)&&(s.groups=e.groups.map((e=>ts(e)))),(null===(i=e.producePermissions)||void 0===i?void 0:i.length)&&(s.producePermissions=e.producePermissions.map((e=>ns(e)))),s},create:e=>fs.fromPartial(null!=e?e:{}),fromPartial(e){var t,r,n,i,s,o,a,c,d,u;const l={id:"",channelIds:[],producers:[],uid:"",appId:"",appData:{},role:0,loginDate:void 0,groups:[],producePermissions:[]};return l.id=null!==(t=e.id)&&void 0!==t?t:"",l.channelIds=(null===(r=e.channelIds)||void 0===r?void 0:r.map((e=>e)))||[],l.producers=(null===(n=e.producers)||void 0===n?void 0:n.map((e=>us.fromPartial(e))))||[],l.uid=null!==(i=e.uid)&&void 0!==i?i:"",l.appId=null!==(s=e.appId)&&void 0!==s?s:"",l.appData=Object.entries(null!==(o=e.appData)&&void 0!==o?o:{}).reduce(((e,[t,r])=>(void 0!==r&&(e[t]=r),e)),{}),l.role=null!==(a=e.role)&&void 0!==a?a:0,l.loginDate=null!==(c=e.loginDate)&&void 0!==c?c:void 0,l.groups=(null===(d=e.groups)||void 0===d?void 0:d.map((e=>e)))||[],l.producePermissions=(null===(u=e.producePermissions)||void 0===u?void 0:u.map((e=>e)))||[],l}};const ms={encode:(e,t=new Li)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&zi.encode(zi.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={key:"",value:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.key=r.string();continue;case 2:if(18!==e)break;i.value=zi.unwrap(zi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:ys(e.key)?globalThis.String(e.key):"",value:ys(null==e?void 0:e.value)?e.value:void 0}),toJSON(e){const t={};return""!==e.key&&(t.key=e.key),void 0!==e.value&&(t.value=e.value),t},create:e=>ms.fromPartial(null!=e?e:{}),fromPartial(e){var t,r;const n={key:"",value:void 0};return n.key=null!==(t=e.key)&&void 0!==t?t:"",n.value=null!==(r=e.value)&&void 0!==r?r:void 0,n}};function gs(e){let t=1e3*(e.seconds||0);return t+=(e.nanos||0)/1e6,new globalThis.Date(t)}function vs(e){return e instanceof globalThis.Date?e:"string"==typeof e?new globalThis.Date(e):gs(ss.fromJSON(e))}function ys(e){return null!=e}const bs={encode(e,t=new Li){for(const r of e.peers)fs.encode(r,t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={peers:[]};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.peers.push(fs.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({peers:globalThis.Array.isArray(null==e?void 0:e.peers)?e.peers.map((e=>fs.fromJSON(e))):[]}),toJSON(e){var t;const r={};return(null===(t=e.peers)||void 0===t?void 0:t.length)&&(r.peers=e.peers.map((e=>fs.toJSON(e)))),r},create:e=>bs.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={peers:[]};return r.peers=(null===(t=e.peers)||void 0===t?void 0:t.map((e=>fs.fromPartial(e))))||[],r}};const _s={encode:(e,t=new Li)=>(""!==e.id&&t.uint32(10).string(e.id),!1!==e.paused&&t.uint32(16).bool(e.paused),t),decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={id:"",paused:!1};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.id=r.string();continue;case 2:if(16!==e)break;i.paused=r.bool();continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({id:Ss(e.id)?globalThis.String(e.id):"",paused:!!Ss(e.paused)&&globalThis.Boolean(e.paused)}),toJSON(e){const t={};return""!==e.id&&(t.id=e.id),!1!==e.paused&&(t.paused=e.paused),t},create:e=>_s.fromPartial(null!=e?e:{}),fromPartial(e){var t,r;const n={id:"",paused:!1};return n.id=null!==(t=e.id)&&void 0!==t?t:"",n.paused=null!==(r=e.paused)&&void 0!==r&&r,n}};const Es={encode(e,t=new Li){""!==e.id&&t.uint32(10).string(e.id);for(const r of e.producers)_s.encode(r,t.uint32(18).fork()).join();return void 0!==e.appDataHash&&t.uint32(26).string(e.appDataHash),t},decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={id:"",producers:[],appDataHash:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.id=r.string();continue;case 2:if(18!==e)break;i.producers.push(_s.decode(r,r.uint32()));continue;case 3:if(26!==e)break;i.appDataHash=r.string();continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({id:Ss(e.id)?globalThis.String(e.id):"",producers:globalThis.Array.isArray(null==e?void 0:e.producers)?e.producers.map((e=>_s.fromJSON(e))):[],appDataHash:Ss(e.appDataHash)?globalThis.String(e.appDataHash):void 0}),toJSON(e){var t;const r={};return""!==e.id&&(r.id=e.id),(null===(t=e.producers)||void 0===t?void 0:t.length)&&(r.producers=e.producers.map((e=>_s.toJSON(e)))),void 0!==e.appDataHash&&(r.appDataHash=e.appDataHash),r},create:e=>Es.fromPartial(null!=e?e:{}),fromPartial(e){var t,r,n;const i={id:"",producers:[],appDataHash:void 0};return i.id=null!==(t=e.id)&&void 0!==t?t:"",i.producers=(null===(r=e.producers)||void 0===r?void 0:r.map((e=>_s.fromPartial(e))))||[],i.appDataHash=null!==(n=e.appDataHash)&&void 0!==n?n:void 0,i}};const ws={encode(e,t=new Li){for(const r of e.peers)Es.encode(r,t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={peers:[]};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.peers.push(Es.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({peers:globalThis.Array.isArray(null==e?void 0:e.peers)?e.peers.map((e=>Es.fromJSON(e))):[]}),toJSON(e){var t;const r={};return(null===(t=e.peers)||void 0===t?void 0:t.length)&&(r.peers=e.peers.map((e=>Es.toJSON(e)))),r},create:e=>ws.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={peers:[]};return r.peers=(null===(t=e.peers)||void 0===t?void 0:t.map((e=>Es.fromPartial(e))))||[],r}};function Ss(e){return null!=e}var Cs;function Ts(e){switch(e){case 0:case"CHANNEL_EVENT_TYPE_UNSPECIFIED":return Cs.CHANNEL_EVENT_TYPE_UNSPECIFIED;case 1:case"CHANNEL_EVENT_TYPE_CHANNEL_STATE":return Cs.CHANNEL_EVENT_TYPE_CHANNEL_STATE;case 2:case"CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT":return Cs.CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT;case 3:case"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED":return Cs.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED;case 4:case"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED":return Cs.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED;case 5:case"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED":return Cs.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED;case 6:case"CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED":return Cs.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED;case 7:case"CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED":return Cs.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED;case 8:case"CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT":return Cs.CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT;case 14:case"CHANNEL_EVENT_TYPE_PEER_JOINED":return Cs.CHANNEL_EVENT_TYPE_PEER_JOINED;case 15:case"CHANNEL_EVENT_TYPE_PEER_LEFT":return Cs.CHANNEL_EVENT_TYPE_PEER_LEFT;case 16:case"CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED":return Cs.CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED;case 17:case"CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED":return Cs.CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED;case 18:case"CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED":return Cs.CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED;default:return Cs.UNRECOGNIZED}}function Ps(e){switch(e){case Cs.CHANNEL_EVENT_TYPE_UNSPECIFIED:return"CHANNEL_EVENT_TYPE_UNSPECIFIED";case Cs.CHANNEL_EVENT_TYPE_CHANNEL_STATE:return"CHANNEL_EVENT_TYPE_CHANNEL_STATE";case Cs.CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT:return"CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT";case Cs.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED:return"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED";case Cs.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED:return"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED";case Cs.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED:return"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED";case Cs.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED:return"CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED";case Cs.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED:return"CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED";case Cs.CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT:return"CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT";case Cs.CHANNEL_EVENT_TYPE_PEER_JOINED:return"CHANNEL_EVENT_TYPE_PEER_JOINED";case Cs.CHANNEL_EVENT_TYPE_PEER_LEFT:return"CHANNEL_EVENT_TYPE_PEER_LEFT";case Cs.CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED:return"CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED";case Cs.CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED:return"CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED";case Cs.CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED:return"CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED";case Cs.UNRECOGNIZED:default:return"UNRECOGNIZED"}}!function(e){e[e.CHANNEL_EVENT_TYPE_UNSPECIFIED=0]="CHANNEL_EVENT_TYPE_UNSPECIFIED",e[e.CHANNEL_EVENT_TYPE_CHANNEL_STATE=1]="CHANNEL_EVENT_TYPE_CHANNEL_STATE",e[e.CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT=2]="CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT",e[e.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED=3]="CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED",e[e.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED=4]="CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED",e[e.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED=5]="CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED",e[e.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED=6]="CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED",e[e.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED=7]="CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED",e[e.CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT=8]="CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT",e[e.CHANNEL_EVENT_TYPE_PEER_JOINED=14]="CHANNEL_EVENT_TYPE_PEER_JOINED",e[e.CHANNEL_EVENT_TYPE_PEER_LEFT=15]="CHANNEL_EVENT_TYPE_PEER_LEFT",e[e.CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED=16]="CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED",e[e.CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED=17]="CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED",e[e.CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED=18]="CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Cs||(Cs={}));const Rs={encode:(e,t=new Li)=>(0!==e.eventType&&t.uint32(8).int32(e.eventType),void 0!==e.channelState&&bs.encode(e.channelState,t.uint32(18).fork()).join(),void 0!==e.channelStateShort&&ws.encode(e.channelStateShort,t.uint32(26).fork()).join(),void 0!==e.channelActivityConfirmationTime&&Ui.encode(e.channelActivityConfirmationTime,t.uint32(34).fork()).join(),void 0!==e.channelManagementEvent&&Ki.encode(e.channelManagementEvent,t.uint32(42).fork()).join(),void 0!==e.channelProducePermissions&&is.encode(e.channelProducePermissions,t.uint32(50).fork()).join(),void 0!==e.peer&&fs.encode(e.peer,t.uint32(58).fork()).join(),t),decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={eventType:0,channelState:void 0,channelStateShort:void 0,channelActivityConfirmationTime:void 0,channelManagementEvent:void 0,channelProducePermissions:void 0,peer:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(8!==e)break;i.eventType=r.int32();continue;case 2:if(18!==e)break;i.channelState=bs.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.channelStateShort=ws.decode(r,r.uint32());continue;case 4:if(34!==e)break;i.channelActivityConfirmationTime=Ui.decode(r,r.uint32());continue;case 5:if(42!==e)break;i.channelManagementEvent=Ki.decode(r,r.uint32());continue;case 6:if(50!==e)break;i.channelProducePermissions=is.decode(r,r.uint32());continue;case 7:if(58!==e)break;i.peer=fs.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({eventType:ks(e.eventType)?Ts(e.eventType):0,channelState:ks(e.channelState)?bs.fromJSON(e.channelState):void 0,channelStateShort:ks(e.channelStateShort)?ws.fromJSON(e.channelStateShort):void 0,channelActivityConfirmationTime:ks(e.channelActivityConfirmationTime)?Ui.fromJSON(e.channelActivityConfirmationTime):void 0,channelManagementEvent:ks(e.channelManagementEvent)?Ki.fromJSON(e.channelManagementEvent):void 0,channelProducePermissions:ks(e.channelProducePermissions)?is.fromJSON(e.channelProducePermissions):void 0,peer:ks(e.peer)?fs.fromJSON(e.peer):void 0}),toJSON(e){const t={};return 0!==e.eventType&&(t.eventType=Ps(e.eventType)),void 0!==e.channelState&&(t.channelState=bs.toJSON(e.channelState)),void 0!==e.channelStateShort&&(t.channelStateShort=ws.toJSON(e.channelStateShort)),void 0!==e.channelActivityConfirmationTime&&(t.channelActivityConfirmationTime=Ui.toJSON(e.channelActivityConfirmationTime)),void 0!==e.channelManagementEvent&&(t.channelManagementEvent=Ki.toJSON(e.channelManagementEvent)),void 0!==e.channelProducePermissions&&(t.channelProducePermissions=is.toJSON(e.channelProducePermissions)),void 0!==e.peer&&(t.peer=fs.toJSON(e.peer)),t},create:e=>Rs.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={eventType:0,channelState:void 0,channelStateShort:void 0,channelActivityConfirmationTime:void 0,channelManagementEvent:void 0,channelProducePermissions:void 0,peer:void 0};return r.eventType=null!==(t=e.eventType)&&void 0!==t?t:0,r.channelState=void 0!==e.channelState&&null!==e.channelState?bs.fromPartial(e.channelState):void 0,r.channelStateShort=void 0!==e.channelStateShort&&null!==e.channelStateShort?ws.fromPartial(e.channelStateShort):void 0,r.channelActivityConfirmationTime=void 0!==e.channelActivityConfirmationTime&&null!==e.channelActivityConfirmationTime?Ui.fromPartial(e.channelActivityConfirmationTime):void 0,r.channelManagementEvent=void 0!==e.channelManagementEvent&&null!==e.channelManagementEvent?Ki.fromPartial(e.channelManagementEvent):void 0,r.channelProducePermissions=void 0!==e.channelProducePermissions&&null!==e.channelProducePermissions?is.fromPartial(e.channelProducePermissions):void 0,r.peer=void 0!==e.peer&&null!==e.peer?fs.fromPartial(e.peer):void 0,r}};function ks(e){return null!=e}const Ds={encode:(e,t=new Li)=>(""!==e.id&&t.uint32(10).string(e.id),""!==e.peerId&&t.uint32(18).string(e.peerId),""!==e.producerPeerId&&t.uint32(26).string(e.producerPeerId),void 0!==e.spatialLayer&&t.uint32(32).uint32(e.spatialLayer),void 0!==e.temporalLayer&&t.uint32(40).uint32(e.temporalLayer),t),decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={id:"",peerId:"",producerPeerId:"",spatialLayer:void 0,temporalLayer:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.id=r.string();continue;case 2:if(18!==e)break;i.peerId=r.string();continue;case 3:if(26!==e)break;i.producerPeerId=r.string();continue;case 4:if(32!==e)break;i.spatialLayer=r.uint32();continue;case 5:if(40!==e)break;i.temporalLayer=r.uint32();continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({id:Is(e.id)?globalThis.String(e.id):"",peerId:Is(e.peerId)?globalThis.String(e.peerId):"",producerPeerId:Is(e.producerPeerId)?globalThis.String(e.producerPeerId):"",spatialLayer:Is(e.spatialLayer)?globalThis.Number(e.spatialLayer):void 0,temporalLayer:Is(e.temporalLayer)?globalThis.Number(e.temporalLayer):void 0}),toJSON(e){const t={};return""!==e.id&&(t.id=e.id),""!==e.peerId&&(t.peerId=e.peerId),""!==e.producerPeerId&&(t.producerPeerId=e.producerPeerId),void 0!==e.spatialLayer&&(t.spatialLayer=Math.round(e.spatialLayer)),void 0!==e.temporalLayer&&(t.temporalLayer=Math.round(e.temporalLayer)),t},create:e=>Ds.fromPartial(null!=e?e:{}),fromPartial(e){var t,r,n,i,s;const o={id:"",peerId:"",producerPeerId:"",spatialLayer:void 0,temporalLayer:void 0};return o.id=null!==(t=e.id)&&void 0!==t?t:"",o.peerId=null!==(r=e.peerId)&&void 0!==r?r:"",o.producerPeerId=null!==(n=e.producerPeerId)&&void 0!==n?n:"",o.spatialLayer=null!==(i=e.spatialLayer)&&void 0!==i?i:void 0,o.temporalLayer=null!==(s=e.temporalLayer)&&void 0!==s?s:void 0,o}};function Is(e){return null!=e}const As={encode:(e,t=new Li)=>(""!==e.producerId&&t.uint32(10).string(e.producerId),t),decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={producerId:""};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.producerId=r.string();continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON(e){return{producerId:(t=e.producerId,null!=t?globalThis.String(e.producerId):"")};var t},toJSON(e){const t={};return""!==e.producerId&&(t.producerId=e.producerId),t},create:e=>As.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={producerId:""};return r.producerId=null!==(t=e.producerId)&&void 0!==t?t:"",r}};const Os={encode:(e,t=new Li)=>(""!==e.producerId&&t.uint32(10).string(e.producerId),0!==e.spatialLayer&&t.uint32(16).uint32(e.spatialLayer),t),decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={producerId:"",spatialLayer:0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.producerId=r.string();continue;case 2:if(16!==e)break;i.spatialLayer=r.uint32();continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({producerId:Ms(e.producerId)?globalThis.String(e.producerId):"",spatialLayer:Ms(e.spatialLayer)?globalThis.Number(e.spatialLayer):0}),toJSON(e){const t={};return""!==e.producerId&&(t.producerId=e.producerId),0!==e.spatialLayer&&(t.spatialLayer=Math.round(e.spatialLayer)),t},create:e=>Os.fromPartial(null!=e?e:{}),fromPartial(e){var t,r;const n={producerId:"",spatialLayer:0};return n.producerId=null!==(t=e.producerId)&&void 0!==t?t:"",n.spatialLayer=null!==(r=e.spatialLayer)&&void 0!==r?r:0,n}};function Ms(e){return null!=e}var Ns,Ls;function xs(e){switch(e){case 0:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED":return Ns.TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED;case 1:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS":return Ns.TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS;case 2:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE":return Ns.TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE;default:return Ns.UNRECOGNIZED}}function Fs(e){switch(e){case 0:case"TRANSPORT_DIRECTION_UNSPECIFIED":return Ls.TRANSPORT_DIRECTION_UNSPECIFIED;case 1:case"TRANSPORT_DIRECTION_SEND":return Ls.TRANSPORT_DIRECTION_SEND;case 2:case"TRANSPORT_DIRECTION_RECEIVE":return Ls.TRANSPORT_DIRECTION_RECEIVE;default:return Ls.UNRECOGNIZED}}!function(e){e[e.TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED=0]="TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED",e[e.TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS=1]="TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS",e[e.TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE=2]="TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ns||(Ns={})),function(e){e[e.TRANSPORT_DIRECTION_UNSPECIFIED=0]="TRANSPORT_DIRECTION_UNSPECIFIED",e[e.TRANSPORT_DIRECTION_SEND=1]="TRANSPORT_DIRECTION_SEND",e[e.TRANSPORT_DIRECTION_RECEIVE=2]="TRANSPORT_DIRECTION_RECEIVE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Ls||(Ls={}));const js={encode:(e,t=new Li)=>(""!==e.transportId&&t.uint32(10).string(e.transportId),0!==e.timeout&&t.uint32(16).uint32(e.timeout),0!==e.direction&&t.uint32(24).int32(e.direction),0!==e.reason&&t.uint32(32).int32(e.reason),t),decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={transportId:"",timeout:0,direction:0,reason:0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(10!==e)break;i.transportId=r.string();continue;case 2:if(16!==e)break;i.timeout=r.uint32();continue;case 3:if(24!==e)break;i.direction=r.int32();continue;case 4:if(32!==e)break;i.reason=r.int32();continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({transportId:Us(e.transportId)?globalThis.String(e.transportId):"",timeout:Us(e.timeout)?globalThis.Number(e.timeout):0,direction:Us(e.direction)?Fs(e.direction):0,reason:Us(e.reason)?xs(e.reason):0}),toJSON(e){const t={};return""!==e.transportId&&(t.transportId=e.transportId),0!==e.timeout&&(t.timeout=Math.round(e.timeout)),0!==e.direction&&(t.direction=function(e){switch(e){case Ls.TRANSPORT_DIRECTION_UNSPECIFIED:return"TRANSPORT_DIRECTION_UNSPECIFIED";case Ls.TRANSPORT_DIRECTION_SEND:return"TRANSPORT_DIRECTION_SEND";case Ls.TRANSPORT_DIRECTION_RECEIVE:return"TRANSPORT_DIRECTION_RECEIVE";case Ls.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.direction)),0!==e.reason&&(t.reason=function(e){switch(e){case Ns.TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED";case Ns.TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS";case Ns.TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE";case Ns.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.reason)),t},create:e=>js.fromPartial(null!=e?e:{}),fromPartial(e){var t,r,n,i;const s={transportId:"",timeout:0,direction:0,reason:0};return s.transportId=null!==(t=e.transportId)&&void 0!==t?t:"",s.timeout=null!==(r=e.timeout)&&void 0!==r?r:0,s.direction=null!==(n=e.direction)&&void 0!==n?n:0,s.reason=null!==(i=e.reason)&&void 0!==i?i:0,s}};function Us(e){return null!=e}var Vs;function Bs(e){switch(e){case 0:case"MEDIA_EVENT_TYPE_UNSPECIFIED":return Vs.MEDIA_EVENT_TYPE_UNSPECIFIED;case 1:case"MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT":return Vs.MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT;case 2:case"MEDIA_EVENT_TYPE_PRODUCER_CREATED":return Vs.MEDIA_EVENT_TYPE_PRODUCER_CREATED;case 3:case"MEDIA_EVENT_TYPE_PRODUCER_PAUSED":return Vs.MEDIA_EVENT_TYPE_PRODUCER_PAUSED;case 4:case"MEDIA_EVENT_TYPE_PRODUCER_RESUMED":return Vs.MEDIA_EVENT_TYPE_PRODUCER_RESUMED;case 5:case"MEDIA_EVENT_TYPE_PRODUCER_CLOSED":return Vs.MEDIA_EVENT_TYPE_PRODUCER_CLOSED;case 6:case"MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED":return Vs.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED;case 7:case"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED":return Vs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED;case 8:case"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED":return Vs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED;case 9:case"MEDIA_EVENT_TYPE_CONSUMER_CLOSED":return Vs.MEDIA_EVENT_TYPE_CONSUMER_CLOSED;case 10:case"MEDIA_EVENT_TYPE_CONSUMER_PAUSED":return Vs.MEDIA_EVENT_TYPE_CONSUMER_PAUSED;case 11:case"MEDIA_EVENT_TYPE_CONSUMER_RESUMED":return Vs.MEDIA_EVENT_TYPE_CONSUMER_RESUMED;case 12:case"MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED":return Vs.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED;case 13:case"MEDIA_EVENT_TYPE_PRODUCER_KEY_FRAME_REQUESTED":return Vs.MEDIA_EVENT_TYPE_PRODUCER_KEY_FRAME_REQUESTED;default:return Vs.UNRECOGNIZED}}function Ws(e){switch(e){case Vs.MEDIA_EVENT_TYPE_UNSPECIFIED:return"MEDIA_EVENT_TYPE_UNSPECIFIED";case Vs.MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT:return"MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT";case Vs.MEDIA_EVENT_TYPE_PRODUCER_CREATED:return"MEDIA_EVENT_TYPE_PRODUCER_CREATED";case Vs.MEDIA_EVENT_TYPE_PRODUCER_PAUSED:return"MEDIA_EVENT_TYPE_PRODUCER_PAUSED";case Vs.MEDIA_EVENT_TYPE_PRODUCER_RESUMED:return"MEDIA_EVENT_TYPE_PRODUCER_RESUMED";case Vs.MEDIA_EVENT_TYPE_PRODUCER_CLOSED:return"MEDIA_EVENT_TYPE_PRODUCER_CLOSED";case Vs.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED:return"MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED";case Vs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED:return"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED";case Vs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED:return"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED";case Vs.MEDIA_EVENT_TYPE_CONSUMER_CLOSED:return"MEDIA_EVENT_TYPE_CONSUMER_CLOSED";case Vs.MEDIA_EVENT_TYPE_CONSUMER_PAUSED:return"MEDIA_EVENT_TYPE_CONSUMER_PAUSED";case Vs.MEDIA_EVENT_TYPE_CONSUMER_RESUMED:return"MEDIA_EVENT_TYPE_CONSUMER_RESUMED";case Vs.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED:return"MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED";case Vs.MEDIA_EVENT_TYPE_PRODUCER_KEY_FRAME_REQUESTED:return"MEDIA_EVENT_TYPE_PRODUCER_KEY_FRAME_REQUESTED";case Vs.UNRECOGNIZED:default:return"UNRECOGNIZED"}}!function(e){e[e.MEDIA_EVENT_TYPE_UNSPECIFIED=0]="MEDIA_EVENT_TYPE_UNSPECIFIED",e[e.MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT=1]="MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT",e[e.MEDIA_EVENT_TYPE_PRODUCER_CREATED=2]="MEDIA_EVENT_TYPE_PRODUCER_CREATED",e[e.MEDIA_EVENT_TYPE_PRODUCER_PAUSED=3]="MEDIA_EVENT_TYPE_PRODUCER_PAUSED",e[e.MEDIA_EVENT_TYPE_PRODUCER_RESUMED=4]="MEDIA_EVENT_TYPE_PRODUCER_RESUMED",e[e.MEDIA_EVENT_TYPE_PRODUCER_CLOSED=5]="MEDIA_EVENT_TYPE_PRODUCER_CLOSED",e[e.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED=6]="MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED",e[e.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED=7]="MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED",e[e.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED=8]="MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED",e[e.MEDIA_EVENT_TYPE_CONSUMER_CLOSED=9]="MEDIA_EVENT_TYPE_CONSUMER_CLOSED",e[e.MEDIA_EVENT_TYPE_CONSUMER_PAUSED=10]="MEDIA_EVENT_TYPE_CONSUMER_PAUSED",e[e.MEDIA_EVENT_TYPE_CONSUMER_RESUMED=11]="MEDIA_EVENT_TYPE_CONSUMER_RESUMED",e[e.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED=12]="MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED",e[e.MEDIA_EVENT_TYPE_PRODUCER_KEY_FRAME_REQUESTED=13]="MEDIA_EVENT_TYPE_PRODUCER_KEY_FRAME_REQUESTED",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(Vs||(Vs={}));const Hs={encode:(e,t=new Li)=>(0!==e.eventType&&t.uint32(8).int32(e.eventType),void 0!==e.producer&&us.encode(e.producer,t.uint32(18).fork()).join(),void 0!==e.consumer&&Ds.encode(e.consumer,t.uint32(26).fork()).join(),void 0!==e.producerSpatialLayerRequest&&Os.encode(e.producerSpatialLayerRequest,t.uint32(34).fork()).join(),void 0!==e.transportConnectionTimeout&&js.encode(e.transportConnectionTimeout,t.uint32(42).fork()).join(),void 0!==e.producerKeyFrameRequest&&As.encode(e.producerKeyFrameRequest,t.uint32(50).fork()).join(),t),decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={eventType:0,producer:void 0,consumer:void 0,producerSpatialLayerRequest:void 0,transportConnectionTimeout:void 0,producerKeyFrameRequest:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(8!==e)break;i.eventType=r.int32();continue;case 2:if(18!==e)break;i.producer=us.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.consumer=Ds.decode(r,r.uint32());continue;case 4:if(34!==e)break;i.producerSpatialLayerRequest=Os.decode(r,r.uint32());continue;case 5:if(42!==e)break;i.transportConnectionTimeout=js.decode(r,r.uint32());continue;case 6:if(50!==e)break;i.producerKeyFrameRequest=As.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({eventType:qs(e.eventType)?Bs(e.eventType):0,producer:qs(e.producer)?us.fromJSON(e.producer):void 0,consumer:qs(e.consumer)?Ds.fromJSON(e.consumer):void 0,producerSpatialLayerRequest:qs(e.producerSpatialLayerRequest)?Os.fromJSON(e.producerSpatialLayerRequest):void 0,transportConnectionTimeout:qs(e.transportConnectionTimeout)?js.fromJSON(e.transportConnectionTimeout):void 0,producerKeyFrameRequest:qs(e.producerKeyFrameRequest)?As.fromJSON(e.producerKeyFrameRequest):void 0}),toJSON(e){const t={};return 0!==e.eventType&&(t.eventType=Ws(e.eventType)),void 0!==e.producer&&(t.producer=us.toJSON(e.producer)),void 0!==e.consumer&&(t.consumer=Ds.toJSON(e.consumer)),void 0!==e.producerSpatialLayerRequest&&(t.producerSpatialLayerRequest=Os.toJSON(e.producerSpatialLayerRequest)),void 0!==e.transportConnectionTimeout&&(t.transportConnectionTimeout=js.toJSON(e.transportConnectionTimeout)),void 0!==e.producerKeyFrameRequest&&(t.producerKeyFrameRequest=As.toJSON(e.producerKeyFrameRequest)),t},create:e=>Hs.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={eventType:0,producer:void 0,consumer:void 0,producerSpatialLayerRequest:void 0,transportConnectionTimeout:void 0,producerKeyFrameRequest:void 0};return r.eventType=null!==(t=e.eventType)&&void 0!==t?t:0,r.producer=void 0!==e.producer&&null!==e.producer?us.fromPartial(e.producer):void 0,r.consumer=void 0!==e.consumer&&null!==e.consumer?Ds.fromPartial(e.consumer):void 0,r.producerSpatialLayerRequest=void 0!==e.producerSpatialLayerRequest&&null!==e.producerSpatialLayerRequest?Os.fromPartial(e.producerSpatialLayerRequest):void 0,r.transportConnectionTimeout=void 0!==e.transportConnectionTimeout&&null!==e.transportConnectionTimeout?js.fromPartial(e.transportConnectionTimeout):void 0,r.producerKeyFrameRequest=void 0!==e.producerKeyFrameRequest&&null!==e.producerKeyFrameRequest?As.fromPartial(e.producerKeyFrameRequest):void 0,r}};function qs(e){return null!=e}const zs={encode:(e,t=new Li)=>(0!==e.id&&t.uint32(8).int32(e.id),void 0!==e.channelEvent&&Rs.encode(e.channelEvent,t.uint32(18).fork()).join(),void 0!==e.mediaEvent&&Hs.encode(e.mediaEvent,t.uint32(26).fork()).join(),t),decode(e,t){const r=e instanceof xi?e:new xi(e),n=void 0===t?r.len:r.pos+t,i={id:0,channelEvent:void 0,mediaEvent:void 0};for(;r.pos<n;){const e=r.uint32();switch(e>>>3){case 1:if(8!==e)break;i.id=r.int32();continue;case 2:if(18!==e)break;i.channelEvent=Rs.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.mediaEvent=Hs.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({id:Gs(e.id)?globalThis.Number(e.id):0,channelEvent:Gs(e.channelEvent)?Rs.fromJSON(e.channelEvent):void 0,mediaEvent:Gs(e.mediaEvent)?Hs.fromJSON(e.mediaEvent):void 0}),toJSON(e){const t={};return 0!==e.id&&(t.id=Math.round(e.id)),void 0!==e.channelEvent&&(t.channelEvent=Rs.toJSON(e.channelEvent)),void 0!==e.mediaEvent&&(t.mediaEvent=Hs.toJSON(e.mediaEvent)),t},create:e=>zs.fromPartial(null!=e?e:{}),fromPartial(e){var t;const r={id:0,channelEvent:void 0,mediaEvent:void 0};return r.id=null!==(t=e.id)&&void 0!==t?t:0,r.channelEvent=void 0!==e.channelEvent&&null!==e.channelEvent?Rs.fromPartial(e.channelEvent):void 0,r.mediaEvent=void 0!==e.mediaEvent&&null!==e.mediaEvent?Hs.fromPartial(e.mediaEvent):void 0,r}};function Gs(e){return null!=e}var Ys,$s,Ks,Js,Qs,Zs,Xs,eo;let to=class{constructor(e){Ys.set(this,[]),$s.set(this,!1),Ks.set(this,!1),Js.set(this,void 0),Qs.set(this,void 0),Zs.set(this,new Map),Xs.set(this,void 0),eo.set(this,new Set),c(this,Xs,e("EventsQueue"),"f")}setMediaEventHandler(e){c(this,Js,e,"f"),a(this,Xs,"f").info("Media event handler set",{case:"EventsQueue"})}setChannelEventHandler(e){c(this,Qs,e,"f"),a(this,Xs,"f").info("Channel event handler set",{case:"EventsQueue"})}subscribe(e){c(this,eo,new Set,"f");let t=0;const r=e=>{try{const r=this.processMessageChunk(e);if(!r||!this.isPendingMessageFullyReceived(r))return;const n=this.finalizeMessageBytes(r),i=zs.decode(n);i.id&&(a(this,eo,"f").has(i.id)&&a(this,Xs,"f").warn("Received duplicate message",{case:"EventsQueue",lastReceivedMsgId:t,currentReceivedMsgId:i.id}),i.id>t+1&&a(this,Xs,"f").warn("Received out of order message",{case:"EventsQueue",lastReceivedMsgId:t,currentReceivedMsgId:i.id})),a(this,eo,"f").add(i.id),t=i.id,this.push(i)}catch(e){a(this,Xs,"f").error("Failed to parse channel message",{error:Vt(e),case:"EventsQueue"})}},n=()=>{e.removeListener("message",r),e.removeListener("close",n)};e.on("close",n),e.on("message",r),a(this,Xs,"f").info("Subscribed to data channel",{case:"EventsQueue"})}push(e){a(this,Ys,"f").push(e),this.process()}process(){return o(this,void 0,void 0,(function*(){if(!a(this,$s,"f")&&!a(this,Ks,"f")){for(c(this,Ks,!0,"f");!a(this,$s,"f")&&a(this,Ys,"f").length>0;){const e=a(this,Ys,"f").shift();if(e)try{if(e.channelEvent&&a(this,Qs,"f")){a(this,Xs,"f").debug("Handle channel event",{case:"EventsQueue",id:e.id,type:Ps(e.channelEvent.eventType),event:e.channelEvent}),yield a(this,Qs,"f").call(this,e.channelEvent);continue}if(e.mediaEvent&&a(this,Js,"f")){a(this,Xs,"f").debug("Handle media event",{case:"EventsQueue",id:e.id,type:Ws(e.mediaEvent.eventType),event:e.mediaEvent}),yield a(this,Js,"f").call(this,e.mediaEvent);continue}a(this,Xs,"f").warn("Received unknown message",{message:e,case:"EventsQueue"})}catch(t){a(this,Xs,"f").error("Failed to handle event",{case:"EventsQueue",id:e.id,error:Vt(t)})}}c(this,Ks,!1,"f"),!a(this,$s,"f")&&a(this,Ys,"f").length>0&&queueMicrotask((()=>{this.process()}))}}))}processMessageChunk(e){const t=new Uint8Array(e);if(t.length<12)return void a(this,Xs,"f").warn("Chunk too small",{case:"EventsQueue",bytesLength:t.length});const{msgId:r,index:n,total:i}=this.parseMessageChunkHeader(t),s=t.slice(12);a(this,Zs,"f").has(r)||a(this,Zs,"f").set(r,{msgId:r,total:i,received:[]});const o=a(this,Zs,"f").get(r);if(o)return o.received[n]=s,o.msgId=r,o;a(this,Xs,"f").warn("Chunk buffer entry not found for msgId",{msgId:r,case:"EventsQueue"})}parseMessageChunkHeader(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{msgId:t.getUint32(0),index:t.getUint32(4),total:t.getUint32(8)}}isPendingMessageFullyReceived(e){return e.received.filter(Boolean).length===e.total}finalizeMessageBytes(e){const t=new Uint8Array(e.received.reduce(((e,t)=>e+t.length),0));let r=0;for(const n of e.received)t.set(n,r),r+=n.length;return a(this,Zs,"f").delete(e.msgId),t}pause(){c(this,$s,!0,"f")}size(){return a(this,Ys,"f").length}resume(){c(this,$s,!1,"f"),this.process()}isMessageReceived(e){return a(this,eo,"f").has(e)}};Ys=new WeakMap,$s=new WeakMap,Ks=new WeakMap,Js=new WeakMap,Qs=new WeakMap,Zs=new WeakMap,Xs=new WeakMap,eo=new WeakMap,to=n([ot(),i(0,ct(mi.LoggerFactory)),s("design:paramtypes",[Function])],to);var ro=to;function no(e){return{id:e.id,appId:e.appId,role:e.role,groups:e.groups,producePermissions:e.producePermissions}}let io=class{get(){return this.peer}set(e){this.peer=e}delete(){this.peer=void 0}get canPublish(){var e;return"host"===(null===(e=this.peer)||void 0===e?void 0:e.role)}};io=n([ot()],io);const so=["no media section found for reuseMid","Duplicate a=msid lines detected"];class oo extends Gn{constructor(e,t,r){super(null!=e?e:oo.DEFAULT_MESSAGE,null!=t?t:"already_connected",r)}}var ao,co,uo;oo.DEFAULT_MESSAGE="Peer is already connected";let lo=class{constructor(e,t,r,n,i,s,o,a,d){this.state=e,this.myPeer=t,this.clientEventEmitter=n,this.dataChannelsManager=i,this.signalingApiClient=s,this.datachannelHeartbeater=o,this.signalingHeartbeater=a,this.iceRecoveryService=d,ao.set(this,0),co.set(this,void 0),uo.set(this,void 0),this.peersLoaded=!1,c(this,uo,r("Network"),"f"),c(this,co,new Ft,"f")}get isNetworkActive(){var e,t,r,n;return["connected","new"].includes(null!==(t=null===(e=this.receiveTransport)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"")&&["connected","new"].includes(null!==(n=null===(r=this.sendTransport)||void 0===r?void 0:r.connectionState)&&void 0!==n?n:"")}get observer(){return a(this,co,"f")}removeEventListeners(){const{sendTransport:e,receiveTransport:t,signalingTransport:r}=this;if(e){["connect","produce","connectionstatechange"].forEach((t=>e.removeAllListeners(t)))}if(t){["connect","produce","connectionstatechange"].forEach((e=>t.removeAllListeners(e)))}if(r){["connect","produce","producedata","connectionstatechange"].forEach((e=>r.removeAllListeners(e)))}}reset(){this.datachannelHeartbeater.dispose(),this.signalingHeartbeater.dispose(),this.heartbeatDataProducer=void 0,this.peersLoaded=!1,this.stopRestartIceAttempts(),this.removeEventListeners(),this.closeAllDataChannels(),this.closeSendTransport(),this.closeReceiveTransport(),this.closeConnectionTransport()}closeRemoteProducer(e){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.closeProducer(e)}))}closeSendTransport(){this.sendTransport?(this.closeTransport(this.sendTransport),this.sendTransport=void 0):a(this,uo,"f").debug("closeSendTransport()",{message:"No available send transport"})}closeReceiveTransport(){this.receiveTransport?(this.closeTransport(this.receiveTransport),this.receiveTransport=void 0):a(this,uo,"f").debug("closeReceiveTransport()",{message:"No available receive transport"})}closeConnectionTransport(){this.signalingTransport?(this.closeTransport(this.signalingTransport),this.signalingTransport=void 0):a(this,uo,"f").debug("closeConnectionTransport()",{message:"No available connection transport"})}closeTransport(e){try{e.close(),a(this,uo,"f").debug("closeTransport()",{transportId:e.id,direction:e.direction})}catch(t){a(this,uo,"f").error("closeTransport()",{error:t,transportId:e.id,direction:e.direction})}}createSendTransport(e){return o(this,void 0,void 0,(function*(){this.sendTransport&&(a(this,uo,"f").warn("createSendTransport()",{message:"Send transport already exists, closing previous"}),this.closeSendTransport());const{data:t}=yield this.signalingApiClient.transport.createTransport({localDirection:"send"}),r=e.createSendTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return a(this,uo,"f").debug("createSendTransport()",{transportId:r.id,direction:r.direction,preferRelay:this.preferRelay}),this.sendTransport=r,this.subscribeCommonTransportEvents(r),r}))}createRecvTransport(e){return o(this,void 0,void 0,(function*(){this.receiveTransport&&(a(this,uo,"f").warn("createRecvTransport()",{message:"Receive transport already exists, closing previous"}),this.closeReceiveTransport());const{data:t}=yield this.signalingApiClient.transport.createTransport({localDirection:"receive"}),r=e.createRecvTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return a(this,uo,"f").debug("createReceiveTransport()",{transportId:r.id,direction:r.direction,preferRelay:this.preferRelay}),this.receiveTransport=r,this.subscribeCommonTransportEvents(r),r}))}createSignalingTransport(e){return o(this,void 0,void 0,(function*(){this.signalingTransport&&(a(this,uo,"f").warn("createSignalingTransport()",{message:"Signaling transport already exists, closing previous"}),this.closeConnectionTransport());const{data:t}=yield this.signalingApiClient.transport.createTransport({localDirection:"receive",tcpOnly:!0}),r=e.createSendTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return a(this,uo,"f").debug("createConnectionTransport()",{transportId:r.id,direction:r.direction,tcpOnly:!0}),this.signalingTransport=r,this.subscribeCommonTransportEvents(r),r}))}restartIce(e){return o(this,void 0,void 0,(function*(){return yield this.iceRecoveryService.restartIce(e)}))}createConsumer(e){return o(this,arguments,void 0,(function*({producerId:e,rtpCapabilities:t,producerPeerId:r}){const n=this.receiveTransport;if(!n)throw a(this,uo,"f").error("createConsumer()",{reason:"missing receive transport"}),new Error("Failed to create consumer due to missing receive transport");a(this,uo,"f").debug("createConsumer()",{producerId:e});const i=yield this.signalingApiClient.consumer.createConsumer({producerId:e,transportId:n.id,rtpCapabilities:t,producerPeerId:r,forceCloseExisting:!0}).then((({data:e})=>this.toRemoteConsumerOptions(e))).catch((t=>{throw(Jn(t)?a(this,uo,"f").debug.bind(a(this,uo,"f")):a(this,uo,"f").error.bind(a(this,uo,"f")))("Failed to get consumer options",{producerId:e,producerPeerId:r,error:Vt(t)}),t})),s=yield n.consume(i).catch((t=>{throw t instanceof Error&&so.some((e=>t.message.includes(e)))&&(a(this,uo,"f").error("createConsumer() reached irrecoverable mediasoup state",{producerId:e,producerPeerId:r,error:Vt(t)}),this.signalingApiClient.abortPendingRequests("channel-rejoin"),this.clientEventEmitter.safeEmit($r)),t})),{producerPaused:o}=i;return o&&"audio"!==s.kind&&s.pause(),a(this,uo,"f").debug("Consumer created",{consumerId:s.id,label:s.appData.label,isProducerPaused:o}),{consumer:s,isProducerPaused:o}}))}initializeHeartbeats(){return o(this,void 0,void 0,(function*(){this.signalingHeartbeater.start();const e=this.sendTransport;if(!e)throw a(this,uo,"f").error("createHeartbeatProducer()",{reason:"missing send transport"}),new Error("Failed to create data producer");const t=yield e.produceData({label:"heart-beater",protocol:"heartbeat"});this.heartbeatDataProducer=t,t.once("transportclose",(()=>{var e;null===(e=this.heartbeatDataProducer)||void 0===e||e.close(),this.heartbeatDataProducer=void 0,this.datachannelHeartbeater.dispose()})),this.datachannelHeartbeater.init(e,t)}))}createKeepAliveConsumer(){return o(this,void 0,void 0,(function*(){const e=this.signalingTransport;if(!e)return void a(this,uo,"f").error("createKeepAliveConsumer()",{reason:"missing signaling transport"});const t=yield e.produceData({label:"consumers-scores",protocol:"keepalive"});t.once("open",(()=>{t.send(new Uint8Array(0))})),t.once("transportclose",(()=>{t.close()}))}))}get channelMessagesDataConsumer(){return this.dataChannelsManager.channelMessagesDataConsumer}closeRemoteConsumer(e){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.closeConsumer(e)}))}resumeRemoteConsumer(e){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.resumeConsumer(e)}))}pauseRemoteProducer(e){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.pauseProducer(e)}))}resumeRemoteProducer(e){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.resumeProducer(e)}))}pauseRemoteConsumer(e){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.pauseConsumer(e)}))}updatePeerAppData(e){return o(this,arguments,void 0,(function*({appData:e}){yield this.signalingApiClient.appData.updateSelfPeerAppData({appData:e})}))}setProducerMaxSpatialLayer(e,t){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.setProducerMaxSpatialLayer(e,{maxSpatialLayer:t})}))}requestProducerMaxSpatialLayer(e,t){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.requestProducerMaxSpatialLayer(e,{spatialLayer:t})}))}changePeerProducePermissions(e,t){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.peers.changePeerProducePermissions(e,{producePermissions:null==t?void 0:t.map((e=>e))})}))}addPeerProducePermission(e,t){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.peers.addPeerProducePermissions(e,t)}))}removePeerProducePermission(e,t){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.peers.removePeerProducePermissions(e,t)}))}updateConsumerPreferredLayers(e,t,r){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.updateConsumerPreferredLayers(e,{spatialLayer:t,temporalLayer:r})}))}requestConsumerKeyFrame(e){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.requestConsumerKeyFrame(e)}))}ping(){return o(this,void 0,void 0,(function*(){yield this.signalingApiClient.ping.pingPeer()}))}getTransportsStateInfo(){return o(this,void 0,void 0,(function*(){const[e,t]=yield Promise.all([this.getParsedTransportStats(this.receiveTransport),this.getParsedTransportStats(this.sendTransport)]);return{receive:e,send:t}}))}setPreferRelay(e){this.preferRelay=e,e||c(this,ao,0,"f")}getPreferRelay(){var e;return null!==(e=this.preferRelay)&&void 0!==e&&e}isRelayEnforced(){return this.getPreferRelay()&&a(this,ao,"f")>Date.now()}enforceRelay(e){c(this,ao,Date.now()+e,"f"),this.preferRelay=!0,a(this,uo,"f").info("enforceRelay()",{durationMs:e,relayEnforcedUntil:a(this,ao,"f")})}getChannelPeers(e){return o(this,void 0,void 0,(function*(){var t;const{data:r}=yield this.signalingApiClient.peers.getPeers({role:e});this.peersLoaded=!0;return{peers:(null!==(t=r.items)&&void 0!==t?t:[]).map((e=>this.mapPeerResponse(e)))}}))}createAllDataChannels(){return o(this,void 0,void 0,(function*(){if(!this.receiveTransport)throw new Bt("create_data_channels_failed",new Error("Receive transport is not created"));yield this.dataChannelsManager.createAudioObserver(this.receiveTransport),yield this.dataChannelsManager.createChannelMessagesDataConsumer(this.receiveTransport)}))}closeAllDataChannels(){this.dataChannelsManager.closeAudioObserver(),this.dataChannelsManager.closeChannelMessagesDataConsumer()}waitForReceiveTransportConnected(e){return o(this,arguments,void 0,(function*({onReceiveTransportFailed:e}){if(!this.receiveTransport)throw new Error("receiveTransport is not initialized");if("connected"===(yield this.waitForTransportTerminalState(this.receiveTransport)))return;yield e(),yield this.waitForIceRestartStateTransition(this.receiveTransport);const t=yield this.waitForTransportTerminalState(this.receiveTransport);if("connected"!==t)throw new Error(`receiveTransport connection failed after relay escalation: ${t}`)}))}triggerChannelStateEvent(e){return o(this,void 0,void 0,(function*(){const{data:t}=yield this.signalingApiClient.channel.triggerChannelStateEvent({role:e});if("number"!=typeof t.messageId)throw new Error("Invalid channel state event response");return t.messageId}))}waitForChannelMessagesDataConsumerConnected(){return o(this,void 0,void 0,(function*(){if(!this.dataChannelsManager.channelMessagesDataConsumer)throw new Error("channelMessagesDataConsumer is not initialized");yield this.waitForDataConsumerConnected(this.dataChannelsManager.channelMessagesDataConsumer)}))}waitForIceRestartStateTransition(e){return o(this,arguments,void 0,(function*(e,t=1e4){"failed"===e.connectionState&&(yield new Promise((r=>{const n=setTimeout((()=>{i(),r()}),t),i=()=>{clearTimeout(n),e.off("connectionstatechange",s)},s=()=>{i(),r()};e.on("connectionstatechange",s)})))}))}waitForTransportTerminalState(e){return o(this,arguments,void 0,(function*(e,t=6e4){if("connected"===e.connectionState)return e.connectionState;if("failed"===e.connectionState)return e.connectionState;if("closed"===e.connectionState)throw new Error(`receiveTransport connection failed: ${e.connectionState}`);return yield new Promise(((r,n)=>{const i=setTimeout((()=>{s(),r(e.connectionState)}),t),s=()=>{clearTimeout(i),e.off("connectionstatechange",o)},o=()=>{["connected","failed"].includes(e.connectionState)?(s(),r(e.connectionState)):"closed"===e.connectionState&&(s(),n(new Error(`receiveTransport connection failed: ${e.connectionState}`)))};e.on("connectionstatechange",o)}))}))}waitForDataConsumerConnected(e){return o(this,arguments,void 0,(function*(e,t=6e4){if(!e)throw new Error("Data consumer is not initialized");"open"!==e.readyState&&(yield new Promise(((r,n)=>{const i=setTimeout((()=>{s(),n(new Error("Timed out waiting for data consumer to connect"))}),t),s=()=>{clearTimeout(i),e.off("open",o),e.off("close",a)},o=()=>{s(),r()},a=()=>{s(),n(new Error(`Data consumer closed unexpectedly: ${e.readyState}`))};e.on("open",o),e.on("close",a)})))}))}getParsedTransportStats(e){return o(this,void 0,void 0,(function*(){if(e)try{const t=Array.from((yield e.getStats()).values()),r=t.find((e=>"local-candidate"===e.type)),n=t.find((e=>"remote-candidate"===e.type)),i=t.find((e=>"transport"===e.type));return{dtlsState:null==i?void 0:i.dtlsState,iceState:null==i?void 0:i.iceState,dtlsRole:null==i?void 0:i.dtlsRole,iceRole:null==i?void 0:i.iceRole,selectedCandidatePairChanges:null==i?void 0:i.selectedCandidatePairChanges,tlsVersion:null==i?void 0:i.tlsVersion,localCandidateState:{ip:null==r?void 0:r.ip,address:null==r?void 0:r.address,port:null==r?void 0:r.port,protocol:null==r?void 0:r.protocol,candidateType:null==r?void 0:r.candidateType},remoteCandidateState:{ip:null==n?void 0:n.ip,address:null==n?void 0:n.address,port:null==n?void 0:n.port,protocol:null==n?void 0:n.protocol,candidateType:null==n?void 0:n.candidateType}}}catch(e){return void(e instanceof Error&&"InvalidStateError"===e.name?a(this,uo,"f").debug.bind(a(this,uo,"f")):a(this,uo,"f").error.bind(a(this,uo,"f")))("getParsedTransportStats()",{error:e})}else a(this,uo,"f").debug("getParsedTransportStats()",{message:"Transport is missing"})}))}logTransportDetails(e){return o(this,void 0,void 0,(function*(){var t,r,n,i;let s;try{s=yield e.getStats()}catch(t){return void a(this,uo,"f").error("Failed to log detailed WebRTC transport stats",{error:Vt(t),transportId:e.id,reason:"failed to parse getStats"})}try{const o=[...s],[,c]=null!==(t=o.find((([,e])=>"transport"===(null==e?void 0:e.type))))&&void 0!==t?t:[],[,d]=null!==(r=o.find((([,e])=>"candidate-pair"===e.type&&"succeeded"===e.state&&e.nominated)))&&void 0!==r?r:[],u=s.get(String(null!==(n=null==d?void 0:d.localCandidateId)&&void 0!==n?n:"-")),l=s.get(String(null!==(i=null==d?void 0:d.remoteCandidateId)&&void 0!==i?i:"-")),p={hasNominatedPair:!!d,transportId:e.id,iceRole:null==c?void 0:c.iceRole,iceState:null==c?void 0:c.iceState,dtlsRole:null==c?void 0:c.dtlsRole,dtlsState:null==c?void 0:c.dtlsState,local:{address:null==u?void 0:u.address,candidateType:null==u?void 0:u.candidateType,foundation:null==u?void 0:u.foundation,networkType:null==u?void 0:u.networkType,isRemote:null==u?void 0:u.isRemote,port:null==u?void 0:u.port,protocol:null==u?void 0:u.protocol,relatedAddress:null==u?void 0:u.relatedAddress,relatedPort:null==u?void 0:u.relatedPort,transportId:null==u?void 0:u.transportId,relayProtocol:null==u?void 0:u.relayProtocol,url:null==u?void 0:u.url},remote:{address:null==l?void 0:l.address,candidateType:null==l?void 0:l.candidateType,foundation:null==l?void 0:l.foundation,isRemote:null==l?void 0:l.isRemote,port:null==l?void 0:l.port,protocol:null==l?void 0:l.protocol,transportId:null==l?void 0:l.transportId}};(null==d?void 0:d.totalRoundTripTime)&&(null==d?void 0:d.responsesReceived)&&(p.pairRoundTripTime=Math.round(d.totalRoundTripTime/d.responsesReceived*1e3)),a(this,uo,"f").info("Detailed WebRTC transport stats",p)}catch(t){a(this,uo,"f").error("Failed to log detailed WebRTC transport stats",{error:Vt(t),transportId:e.id,reason:"-"})}}))}stopRestartIceAttempts(){this.iceRecoveryService.cancelAll()}toRemoteConsumerOptions(e){const{producerPaused:t}=e,n=r(e,["producerPaused"]);return Object.assign(Object.assign({},n),{producerPaused:t})}mapPeerResponse(e){var t,r,n,i,s,o,a,c;return{id:e.id,channelIds:null!==(t=e.channelIds)&&void 0!==t?t:[],groups:null!==(r=e.groups)&&void 0!==r?r:[],producePermissions:null!==(n=e.producePermissions)&&void 0!==n?n:[],appId:null!==(s=null!==(i=e.appId)&&void 0!==i?i:this.state.appId)&&void 0!==s?s:"",producers:(null!==(o=e.producers)&&void 0!==o?o:[]).map((e=>this.mapProducer(e))),uid:e.uid,appData:null!==(a=e.appData)&&void 0!==a?a:{},role:null!==(c=e.role)&&void 0!==c?c:"audience",loginDate:e.loginDate?new Date(e.loginDate):new Date}}mapProducer(e){var t;return{id:e.id,kind:e.kind,peerId:e.peerId,label:e.label,paused:null!==(t=e.paused)&&void 0!==t&&t,encodings:[],maxSpatialLayer:0}}connectTransport(e,t){return o(this,void 0,void 0,(function*(){try{yield this.signalingApiClient.transport.connectTransport(e,{dtlsParameters:t})}catch(t){if(t instanceof oo)return void a(this,uo,"f").warn("connectTransport() transport already connected",{transportId:e});throw t}}))}subscribeCommonTransportEvents(e){e.on("connect",((t,r,n)=>o(this,[t,r,n],void 0,(function*({dtlsParameters:t},r,n){try{yield this.connectTransport(e.id,t),r(),a(this,uo,"f").debug(`${e.direction}Transport.connect()`,{transportId:e.id,dtlsRole:t.role}),setTimeout((()=>o(this,void 0,void 0,(function*(){return yield this.logTransportDetails(e)}))),2e3),setTimeout((()=>o(this,void 0,void 0,(function*(){return yield this.checkTransportState(e)}))),15e3)}catch(t){a(this,uo,"f").error(`${e.direction}Transport.on('connect')`,{error:t}),n(t)}})))),e.on("produce",((t,r,n)=>o(this,void 0,void 0,(function*(){try{const{data:n}=yield this.signalingApiClient.transport.produceMediaToTransport(e.id,{kind:t.kind,rtpParameters:t.rtpParameters,appData:t.appData,forceCloseExisting:!0}),i=n.id;r({id:i}),a(this,uo,"f").debug(`${e.direction}Transport.produce()`,{producerId:i,transportId:e.id,kind:t.kind})}catch(r){(Jn(r)?a(this,uo,"f").info.bind(a(this,uo,"f")):a(this,uo,"f").error.bind(a(this,uo,"f")))(`${e.direction}Transport.produce()`,{error:Vt(r),transportId:e.id,kind:t.kind}),n(r)}})))),e.on("producedata",((t,r,n)=>o(this,void 0,void 0,(function*(){try{const{data:n}=yield this.signalingApiClient.transport.produceDataToTransport(e.id,{label:t.label,sctpStreamParameters:t.sctpStreamParameters,appData:t.appData});r({id:n.id}),a(this,uo,"f").debug(`${e.direction}Transport.produceData()`,{producerId:n.id,transportId:e.id,sctpStreamParameters:t.sctpStreamParameters,label:t.label})}catch(r){(Jn(r)?a(this,uo,"f").info.bind(a(this,uo,"f")):a(this,uo,"f").error.bind(a(this,uo,"f")))(`${e.direction}Transport.produceData()`,{error:Vt(r),transportId:e.id,sctpStreamParameters:t.sctpStreamParameters,label:t.label}),n(r)}})))),e.on("connectionstatechange",(t=>{if(this.isStaleTransport(e))a(this,uo,"f").info("Transport.state ignored (stale transport)",{state:t,direction:e.direction,transportId:e.id});else{if(a(this,uo,"f").info(`${e.direction}Transport.state`,{state:t}),["closed","connected"].includes(t))return a(this,co,"f").safeEmit(qn,{state:t,direction:e.direction}),this.iceRecoveryService.handleConnectionStateChange(e,t),void("connected"===t&&(a(this,co,"f").safeEmit(qn,{state:"reconnected",direction:e.direction}),setTimeout((()=>{this.logTransportDetails(e).catch((e=>{a(this,uo,"f").debug("Failed to log transport details",{error:Vt(e)})}))}),1500)));a(this,co,"f").safeEmit(qn,{state:t,direction:e.direction}),["disconnected","failed"].includes(t)&&this.iceRecoveryService.handleConnectionStateChange(e,t)}})),e.on("icegatheringstatechange",(t=>{a(this,uo,"f").info("icegatheringstatechange",{state:t,transportId:e.id,transportDirection:e.direction})}))}checkTransportState(e){return o(this,void 0,void 0,(function*(){if(!this.isStaleTransport(e))try{const t=yield this.getParsedTransportStats(e);if(!t)return;const r="send"===e.direction?"send":"receive";if("connected"!==t.iceState)return this.clientEventEmitter.emit(Jr,{direction:r,reason:"ice"}),void a(this,uo,"f").warn(Hn,{reason:"ice",transportId:e.id,direction:r});"connected"!==t.dtlsState&&(this.clientEventEmitter.emit(Jr,{direction:r,reason:"dtls"}),a(this,uo,"f").warn(Hn,{reason:"dtls",transportId:e.id,direction:r}))}catch(t){a(this,uo,"f").error("checkTransportState()",{error:Vt(t),transportId:e.id,direction:e.direction})}}))}isStaleTransport(e){return e.closed||e!==this.sendTransport&&e!==this.receiveTransport}};ao=new WeakMap,co=new WeakMap,uo=new WeakMap,lo=n([ot(),i(0,ct(mi.CallState)),i(1,ct(mi.MyPeer)),i(2,ct(mi.LoggerFactory)),i(3,ct(mi.ClientEventEmitter)),i(4,ct(mi.DataChannelsManager)),i(5,ct(mi.SignalingApiClient)),i(6,ct(mi.DatachannelHeartbeater)),i(7,ct(mi.SignalingHeartbeater)),i(8,ct(mi.IceRecoveryService)),s("design:paramtypes",[gi,io,Function,Ft,Function,Function,Function,Function,Function])],lo);var po=lo;let ho=class{constructor(){this.peers=new Map}has(e){return this.peers.has(e)}set(e,t){this.peers.set(e,t)}get(e){return this.peers.get(e)}delete(e){return this.peers.delete(e)}all(){return Array.from(this.peers.values())}hosts(){return this.all().filter((e=>"host"===e.role))}audience(){return this.all().filter((e=>"audience"===e.role))}clear(){this.peers.clear()}};ho=n([ot()],ho);var fo=ho;let mo=class{constructor(e,t,r,n,i){this.myPeer=e,this.network=t,this.peerFactory=r,this.clientEventEmitter=n,this.peersStorage=i}has(e){return this.peersStorage.has(e)}set(e,t){e===this.myPeer.id&&this.myPeer.set(t),this.peersStorage.set(e,t)}get(e){return this.peersStorage.get(e)}delete(e){return e===this.myPeer.id&&this.myPeer.delete(),this.peersStorage.delete(e)}remove(e){return o(this,void 0,void 0,(function*(){const t=this.get(e);t&&(yield t.reset(),this.delete(e),this.clientEventEmitter.safeEmit(qr,e))}))}all(){return this.peersStorage.all()}hosts(){return this.peersStorage.hosts()}audience(){return this.peersStorage.audience()}reset(){return o(this,void 0,void 0,(function*(){yield Promise.all(this.peersStorage.all().map((e=>o(this,void 0,void 0,(function*(){return yield e.reset()}))))),this.peersStorage.clear()}))}load(e){return o(this,void 0,void 0,(function*(){const{peers:t}=yield this.network.getChannelPeers(e);t.filter((e=>!this.has(e.id))).forEach((e=>this.add(e,!1)))}))}add(e,t=!0){const r=this.get(e.id);if(r)return r;const n=this.peerFactory(e);return this.set(n.id,n),t&&this.clientEventEmitter.safeEmit(Hr,n),n}isModerator(e){if(void 0===e)return!1;const t=this.get(e);return!!t&&t.isModerator}};function go(e,t){var r,n;if(0===t.length)return e;for(r=0,n=t.length;r<n;r++)e=(e<<5)-e+t.charCodeAt(r),e|=0;return e<0?-2*e:e}function vo(e,t,r,n){var i=go(go(go(e,r),function(e){return Object.prototype.toString.call(e)}(t)),typeof t);if(null===t)return go(i,"null");if(void 0===t)return go(i,"undefined");if("object"==typeof t||"function"==typeof t){if(-1!==n.indexOf(t))return go(i,"[Circular]"+r);n.push(t);var s=function(e,t,r){return Object.keys(t).sort().reduce((function(e,n){return vo(e,t[n],n,r)}),e)}(i,t,n);if(!("valueOf"in t)||"function"!=typeof t.valueOf)return s;try{return go(s,String(t.valueOf()))}catch(e){return go(s,"[valueOf exception]"+(e.stack||e.message))}}return go(i,t.toString())}mo=n([ot(),i(0,ct(mi.MyPeer)),i(1,ct(mi.Network)),i(2,ct(mi.PeerFactory)),i(3,ct(mi.ClientEventEmitter)),i(4,ct(mi.PeersStorage)),s("design:paramtypes",[io,po,Function,Ft,fo])],mo);var yo=function(e){return function(e,t){for(;e.length<t;)e="0"+e;return e}(vo(0,e,"",[]).toString(16),8)};const bo=new Set(["ENOTFOUND","ENETUNREACH","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_CRL","UNABLE_TO_DECRYPT_CERT_SIGNATURE","UNABLE_TO_DECRYPT_CRL_SIGNATURE","UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY","CERT_SIGNATURE_FAILURE","CRL_SIGNATURE_FAILURE","CERT_NOT_YET_VALID","CERT_HAS_EXPIRED","CRL_NOT_YET_VALID","CRL_HAS_EXPIRED","ERROR_IN_CERT_NOT_BEFORE_FIELD","ERROR_IN_CERT_NOT_AFTER_FIELD","ERROR_IN_CRL_LAST_UPDATE_FIELD","ERROR_IN_CRL_NEXT_UPDATE_FIELD","OUT_OF_MEM","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","CERT_CHAIN_TOO_LONG","CERT_REVOKED","INVALID_CA","PATH_LENGTH_EXCEEDED","INVALID_PURPOSE","CERT_UNTRUSTED","CERT_REJECTED","HOSTNAME_MISMATCH"]);function _o(e){return!e.response&&(!!e.code&&(!["ERR_CANCELED","ECONNABORTED"].includes(e.code)&&(e=>!bo.has(e&&e.code))(e)))}const Eo=["get","head","options"],wo=Eo.concat(["put","delete"]);function So(e){return"ECONNABORTED"!==e.code&&(!e.response||429===e.response.status||e.response.status>=500&&e.response.status<=599)}function Co(e){return!!e.config?.method&&(So(e)&&-1!==wo.indexOf(e.config.method))}function To(e){return _o(e)||Co(e)}function Po(e){const t=e?.response?.headers["retry-after"];if(!t)return 0;let r=1e3*(Number(t)||0);return 0===r&&(r=(new Date(t).valueOf()||0)-Date.now()),Math.max(0,r)}const Ro={retries:3,retryCondition:To,retryDelay:function(e=0,t){return Math.max(0,Po(t))},shouldResetTimeout:!1,onRetry:()=>{},onMaxRetryTimesExceeded:()=>{},validateResponse:null};function ko(e,t,r=!1){const n=function(e,t){return{...Ro,...t,...e["axios-retry"]}}(e,t||{});return n.retryCount=n.retryCount||0,n.lastRequestTime&&!r||(n.lastRequestTime=Date.now()),e["axios-retry"]=n,n}const Do=(e,t)=>{const r=e.interceptors.request.use((e=>(ko(e,t,!0),e["axios-retry"]?.validateResponse&&(e.validateStatus=()=>!1),e))),n=e.interceptors.response.use(null,(async r=>{const{config:n}=r;if(!n)return Promise.reject(r);const i=ko(n,t);return r.response&&i.validateResponse?.(r.response)?r.response:await async function(e,t){const{retries:r,retryCondition:n}=e,i=(e.retryCount||0)<r&&n(t);if("object"==typeof i)try{return!1!==await i}catch(e){return!1}return i}(i,r)?async function(e,t,r,n){t.retryCount+=1;const{retryDelay:i,shouldResetTimeout:s,onRetry:o}=t,a=i(t.retryCount,r);if(function(e,t){e.defaults.agent===t.agent&&delete t.agent,e.defaults.httpAgent===t.httpAgent&&delete t.httpAgent,e.defaults.httpsAgent===t.httpsAgent&&delete t.httpsAgent}(e,n),!s&&n.timeout&&t.lastRequestTime){const e=Date.now()-t.lastRequestTime,i=n.timeout-e-a;if(i<=0)return Promise.reject(r);n.timeout=i}return n.transformRequest=[e=>e],await o(t.retryCount,r,n),n.signal?.aborted?Promise.resolve(e(n)):new Promise((t=>{const r=()=>{clearTimeout(i),t(e(n))},i=setTimeout((()=>{t(e(n)),n.signal?.removeEventListener&&n.signal.removeEventListener("abort",r)}),a);n.signal?.addEventListener&&n.signal.addEventListener("abort",r,{once:!0})}))}(e,i,r,n):(await async function(e,t){e.retryCount>=e.retries&&await e.onMaxRetryTimesExceeded(t,e.retryCount)}(i,r),Promise.reject(r))}));return{requestInterceptorId:r,responseInterceptorId:n}};function Io(e,t){return function(){return e.apply(t,arguments)}}Do.isNetworkError=_o,Do.isSafeRequestError=function(e){return!!e.config?.method&&(So(e)&&-1!==Eo.indexOf(e.config.method))},Do.isIdempotentRequestError=Co,Do.isNetworkOrIdempotentRequestError=To,Do.exponentialDelay=function(e=0,t,r=100){const n=2**e*r,i=Math.max(n,Po(t));return i+.2*i*Math.random()},Do.linearDelay=function(e=100){return(t=0,r)=>{const n=t*e;return Math.max(n,Po(r))}},Do.isRetryableError=So;const{toString:Ao}=Object.prototype,{getPrototypeOf:Oo}=Object,{iterator:Mo,toStringTag:No}=Symbol,Lo=(xo=Object.create(null),e=>{const t=Ao.call(e);return xo[t]||(xo[t]=t.slice(8,-1).toLowerCase())});var xo;const Fo=e=>(e=e.toLowerCase(),t=>Lo(t)===e),jo=e=>t=>typeof t===e,{isArray:Uo}=Array,Vo=jo("undefined");const Bo=Fo("ArrayBuffer");const Wo=jo("string"),Ho=jo("function"),qo=jo("number"),zo=e=>null!==e&&"object"==typeof e,Go=e=>{if("object"!==Lo(e))return!1;const t=Oo(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||No in e||Mo in e)},Yo=Fo("Date"),$o=Fo("File"),Ko=Fo("Blob"),Jo=Fo("FileList"),Qo=Fo("URLSearchParams"),[Zo,Xo,ea,ta]=["ReadableStream","Request","Response","Headers"].map(Fo);function ra(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,i;if("object"!=typeof e&&(e=[e]),Uo(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{const i=r?Object.getOwnPropertyNames(e):Object.keys(e),s=i.length;let o;for(n=0;n<s;n++)o=i[n],t.call(null,e[o],o,e)}}function na(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,i=r.length;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}const ia="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,sa=e=>!Vo(e)&&e!==ia;const oa=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Oo(Uint8Array)),aa=Fo("HTMLFormElement"),ca=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),da=Fo("RegExp"),ua=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};ra(r,((r,i)=>{let s;!1!==(s=t(r,i,e))&&(n[i]=s||r)})),Object.defineProperties(e,n)};const la=Fo("AsyncFunction"),pa=(ha="function"==typeof setImmediate,fa=Ho(ia.postMessage),ha?setImmediate:fa?(ma=`axios@${Math.random()}`,ga=[],ia.addEventListener("message",(({source:e,data:t})=>{e===ia&&t===ma&&ga.length&&ga.shift()()}),!1),e=>{ga.push(e),ia.postMessage(ma,"*")}):e=>setTimeout(e));var ha,fa,ma,ga;const va="undefined"!=typeof queueMicrotask?queueMicrotask.bind(ia):"undefined"!=typeof process&&process.nextTick||pa;var ya={isArray:Uo,isArrayBuffer:Bo,isBuffer:function(e){return null!==e&&!Vo(e)&&null!==e.constructor&&!Vo(e.constructor)&&Ho(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Ho(e.append)&&("formdata"===(t=Lo(e))||"object"===t&&Ho(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Bo(e.buffer),t},isString:Wo,isNumber:qo,isBoolean:e=>!0===e||!1===e,isObject:zo,isPlainObject:Go,isReadableStream:Zo,isRequest:Xo,isResponse:ea,isHeaders:ta,isUndefined:Vo,isDate:Yo,isFile:$o,isBlob:Ko,isRegExp:da,isFunction:Ho,isStream:e=>zo(e)&&Ho(e.pipe),isURLSearchParams:Qo,isTypedArray:oa,isFileList:Jo,forEach:ra,merge:function e(){const{caseless:t}=sa(this)&&this||{},r={},n=(n,i)=>{const s=t&&na(r,i)||i;Go(r[s])&&Go(n)?r[s]=e(r[s],n):Go(n)?r[s]=e({},n):Uo(n)?r[s]=n.slice():r[s]=n};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&ra(arguments[e],n);return r},extend:(e,t,r,{allOwnKeys:n}={})=>(ra(t,((t,n)=>{r&&Ho(t)?e[n]=Io(t,r):e[n]=t}),{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let i,s,o;const a={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),s=i.length;s-- >0;)o=i[s],n&&!n(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==r&&Oo(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:Lo,kindOfTest:Fo,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(Uo(e))return e;let t=e.length;if(!qo(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Mo]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:aa,hasOwnProperty:ca,hasOwnProp:ca,reduceDescriptors:ua,freezeMethods:e=>{ua(e,((t,r)=>{if(Ho(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];Ho(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach((e=>{r[e]=!0}))};return Uo(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:na,global:ia,isContextDefined:sa,isSpecCompliantForm:function(e){return!!(e&&Ho(e.append)&&"FormData"===e[No]&&e[Mo])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(zo(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const i=Uo(e)?[]:{};return ra(e,((e,t)=>{const s=r(e,n+1);!Vo(s)&&(i[t]=s)})),t[n]=void 0,i}}return e};return r(e,0)},isAsyncFn:la,isThenable:e=>e&&(zo(e)||Ho(e))&&Ho(e.then)&&Ho(e.catch),setImmediate:pa,asap:va,isIterable:e=>null!=e&&Ho(e[Mo])};function ba(e,t,r,n,i){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),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}ya.inherits(ba,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:ya.toJSONObject(this.config),code:this.code,status:this.status}}});const _a=ba.prototype,Ea={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{Ea[e]={value:e}})),Object.defineProperties(ba,Ea),Object.defineProperty(_a,"isAxiosError",{value:!0}),ba.from=(e,t,r,n,i,s)=>{const o=Object.create(_a);return ya.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),ba.call(o,e.message,t,r,n,i),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function wa(e){return ya.isPlainObject(e)||ya.isArray(e)}function Sa(e){return ya.endsWith(e,"[]")?e.slice(0,-2):e}function Ca(e,t,r){return e?e.concat(t).map((function(e,t){return e=Sa(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const Ta=ya.toFlatObject(ya,{},null,(function(e){return/^is[A-Z]/.test(e)}));function Pa(e,t,r){if(!ya.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=ya.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!ya.isUndefined(t[e])}))).metaTokens,i=r.visitor||d,s=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&ya.isSpecCompliantForm(t);if(!ya.isFunction(i))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(ya.isDate(e))return e.toISOString();if(ya.isBoolean(e))return e.toString();if(!a&&ya.isBlob(e))throw new ba("Blob is not supported. Use a Buffer instead.");return ya.isArrayBuffer(e)||ya.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,r,i){let a=e;if(e&&!i&&"object"==typeof e)if(ya.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(ya.isArray(e)&&function(e){return ya.isArray(e)&&!e.some(wa)}(e)||(ya.isFileList(e)||ya.endsWith(r,"[]"))&&(a=ya.toArray(e)))return r=Sa(r),a.forEach((function(e,n){!ya.isUndefined(e)&&null!==e&&t.append(!0===o?Ca([r],n,s):null===o?r:r+"[]",c(e))})),!1;return!!wa(e)||(t.append(Ca(i,r,s),c(e)),!1)}const u=[],l=Object.assign(Ta,{defaultVisitor:d,convertValue:c,isVisitable:wa});if(!ya.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!ya.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+n.join("."));u.push(r),ya.forEach(r,(function(r,s){!0===(!(ya.isUndefined(r)||null===r)&&i.call(t,r,ya.isString(s)?s.trim():s,n,l))&&e(r,n?n.concat(s):[s])})),u.pop()}}(e),t}function Ra(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function ka(e,t){this._pairs=[],e&&Pa(e,this,t)}const Da=ka.prototype;function Ia(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Aa(e,t,r){if(!t)return e;const n=r&&r.encode||Ia;ya.isFunction(r)&&(r={serialize:r});const i=r&&r.serialize;let s;if(s=i?i(t,r):ya.isURLSearchParams(t)?t.toString():new ka(t,r).toString(n),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}Da.append=function(e,t){this._pairs.push([e,t])},Da.toString=function(e){const t=e?function(t){return e.call(this,t,Ra)}:Ra;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var Oa=class{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){ya.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},Ma={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Na={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:ka,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const La="undefined"!=typeof window&&"undefined"!=typeof document,xa="object"==typeof navigator&&navigator||void 0,Fa=La&&(!xa||["ReactNative","NativeScript","NS"].indexOf(xa.product)<0),ja="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Ua=La&&window.location.href||"http://localhost";var Va={...Object.freeze({__proto__:null,hasBrowserEnv:La,hasStandardBrowserWebWorkerEnv:ja,hasStandardBrowserEnv:Fa,navigator:xa,origin:Ua}),...Na};function Ba(e){function t(e,r,n,i){let s=e[i++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=i>=e.length;if(s=!s&&ya.isArray(n)?n.length:s,a)return ya.hasOwnProp(n,s)?n[s]=[n[s],r]:n[s]=r,!o;n[s]&&ya.isObject(n[s])||(n[s]=[]);return t(e,r,n[s],i)&&ya.isArray(n[s])&&(n[s]=function(e){const t={},r=Object.keys(e);let n;const i=r.length;let s;for(n=0;n<i;n++)s=r[n],t[s]=e[s];return t}(n[s])),!o}if(ya.isFormData(e)&&ya.isFunction(e.entries)){const r={};return ya.forEachEntry(e,((e,n)=>{t(function(e){return ya.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null}const Wa={transitional:Ma,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,i=ya.isObject(e);i&&ya.isHTMLForm(e)&&(e=new FormData(e));if(ya.isFormData(e))return n?JSON.stringify(Ba(e)):e;if(ya.isArrayBuffer(e)||ya.isBuffer(e)||ya.isStream(e)||ya.isFile(e)||ya.isBlob(e)||ya.isReadableStream(e))return e;if(ya.isArrayBufferView(e))return e.buffer;if(ya.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Pa(e,new Va.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return Va.isNode&&ya.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=ya.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Pa(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return i||n?(t.setContentType("application/json",!1),function(e,t,r){if(ya.isString(e))try{return(t||JSON.parse)(e),ya.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Wa.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(ya.isResponse(e)||ya.isReadableStream(e))return e;if(e&&ya.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw ba.from(e,ba.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:Va.classes.FormData,Blob:Va.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ya.forEach(["delete","get","head","post","put","patch"],(e=>{Wa.headers[e]={}}));var Ha=Wa;const qa=ya.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const za=Symbol("internals");function Ga(e){return e&&String(e).trim().toLowerCase()}function Ya(e){return!1===e||null==e?e:ya.isArray(e)?e.map(Ya):String(e)}function $a(e,t,r,n,i){return ya.isFunction(n)?n.call(this,t,r):(i&&(t=r),ya.isString(t)?ya.isString(n)?-1!==t.indexOf(n):ya.isRegExp(n)?n.test(t):void 0:void 0)}class Ka{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function i(e,t,r){const i=Ga(t);if(!i)throw new Error("header name must be a non-empty string");const s=ya.findKey(n,i);(!s||void 0===n[s]||!0===r||void 0===r&&!1!==n[s])&&(n[s||t]=Ya(e))}const s=(e,t)=>ya.forEach(e,((e,r)=>i(e,r,t)));if(ya.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(ya.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let r,n,i;return e&&e.split("\n").forEach((function(e){i=e.indexOf(":"),r=e.substring(0,i).trim().toLowerCase(),n=e.substring(i+1).trim(),!r||t[r]&&qa[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t);else if(ya.isObject(e)&&ya.isIterable(e)){let r,n,i={};for(const t of e){if(!ya.isArray(t))throw TypeError("Object iterator must return a key-value pair");i[n=t[0]]=(r=i[n])?ya.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}s(i,t)}else null!=e&&i(t,e,r);return this}get(e,t){if(e=Ga(e)){const r=ya.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(ya.isFunction(t))return t.call(this,e,r);if(ya.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Ga(e)){const r=ya.findKey(this,e);return!(!r||void 0===this[r]||t&&!$a(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function i(e){if(e=Ga(e)){const i=ya.findKey(r,e);!i||t&&!$a(0,r[i],i,t)||(delete r[i],n=!0)}}return ya.isArray(e)?e.forEach(i):i(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const i=t[r];e&&!$a(0,this[i],i,e,!0)||(delete this[i],n=!0)}return n}normalize(e){const t=this,r={};return ya.forEach(this,((n,i)=>{const s=ya.findKey(r,i);if(s)return t[s]=Ya(n),void delete t[i];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(i):String(i).trim();o!==i&&delete t[i],t[o]=Ya(n),r[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return ya.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&ya.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[za]=this[za]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=Ga(e);t[n]||(!function(e,t){const r=ya.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,i){return this[n].call(this,t,e,r,i)},configurable:!0})}))}(r,e),t[n]=!0)}return ya.isArray(e)?e.forEach(n):n(e),this}}Ka.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),ya.reduceDescriptors(Ka.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),ya.freezeMethods(Ka);var Ja=Ka;function Qa(e,t){const r=this||Ha,n=t||r,i=Ja.from(n.headers);let s=n.data;return ya.forEach(e,(function(e){s=e.call(r,s,i.normalize(),t?t.status:void 0)})),i.normalize(),s}function Za(e){return!(!e||!e.__CANCEL__)}function Xa(e,t,r){ba.call(this,null==e?"canceled":e,ba.ERR_CANCELED,t,r),this.name="CanceledError"}function ec(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new ba("Request failed with status code "+r.status,[ba.ERR_BAD_REQUEST,ba.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}ya.inherits(Xa,ba,{__CANCEL__:!0});const tc=(e,t,r=3)=>{let n=0;const i=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let i,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=n[o];i||(i=c),r[s]=a,n[s]=c;let u=o,l=0;for(;u!==s;)l+=r[u++],u%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-i<t)return;const p=d&&c-d;return p?Math.round(1e3*l/p):void 0}}(50,250);return function(e,t){let r,n,i=0,s=1e3/t;const o=(t,s=Date.now())=>{i=s,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-i;a>=s?o(e,t):(r=e,n||(n=setTimeout((()=>{n=null,o(r)}),s-a)))},()=>r&&o(r)]}((r=>{const s=r.loaded,o=r.lengthComputable?r.total:void 0,a=s-n,c=i(a);n=s;e({loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:r,lengthComputable:null!=o,[t?"download":"upload"]:!0})}),r)},rc=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},nc=e=>(...t)=>ya.asap((()=>e(...t)));var ic=Va.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,Va.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(Va.origin),Va.navigator&&/(msie|trident)/i.test(Va.navigator.userAgent)):()=>!0,sc=Va.hasStandardBrowserEnv?{write(e,t,r,n,i,s){const o=[e+"="+encodeURIComponent(t)];ya.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),ya.isString(n)&&o.push("path="+n),ya.isString(i)&&o.push("domain="+i),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function oc(e,t,r){let n=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(n||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const ac=e=>e instanceof Ja?{...e}:e;function cc(e,t){t=t||{};const r={};function n(e,t,r,n){return ya.isPlainObject(e)&&ya.isPlainObject(t)?ya.merge.call({caseless:n},e,t):ya.isPlainObject(t)?ya.merge({},t):ya.isArray(t)?t.slice():t}function i(e,t,r,i){return ya.isUndefined(t)?ya.isUndefined(e)?void 0:n(void 0,e,0,i):n(e,t,0,i)}function s(e,t){if(!ya.isUndefined(t))return n(void 0,t)}function o(e,t){return ya.isUndefined(t)?ya.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,i,s){return s in t?n(r,i):s in e?n(void 0,r):void 0}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,r)=>i(ac(e),ac(t),0,!0)};return ya.forEach(Object.keys(Object.assign({},e,t)),(function(n){const s=c[n]||i,o=s(e[n],t[n],n);ya.isUndefined(o)&&s!==a||(r[n]=o)})),r}var dc=e=>{const t=cc({},e);let r,{data:n,withXSRFToken:i,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=Ja.from(a),t.url=Aa(oc(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),ya.isFormData(n))if(Va.hasStandardBrowserEnv||Va.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map((e=>e.trim())).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(Va.hasStandardBrowserEnv&&(i&&ya.isFunction(i)&&(i=i(t)),i||!1!==i&&ic(t.url))){const e=s&&o&&sc.read(o);e&&a.set(s,e)}return t};var uc="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){const n=dc(e);let i=n.data;const s=Ja.from(n.headers).normalize();let o,a,c,d,u,{responseType:l,onUploadProgress:p,onDownloadProgress:h}=n;function f(){d&&d(),u&&u(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let m=new XMLHttpRequest;function g(){if(!m)return;const n=Ja.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());ec((function(e){t(e),f()}),(function(e){r(e),f()}),{data:l&&"text"!==l&&"json"!==l?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:n,config:e,request:m}),m=null}m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout,"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(g)},m.onabort=function(){m&&(r(new ba("Request aborted",ba.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ba("Network Error",ba.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const i=n.transitional||Ma;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new ba(t,i.clarifyTimeoutError?ba.ETIMEDOUT:ba.ECONNABORTED,e,m)),m=null},void 0===i&&s.setContentType(null),"setRequestHeader"in m&&ya.forEach(s.toJSON(),(function(e,t){m.setRequestHeader(t,e)})),ya.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),l&&"json"!==l&&(m.responseType=n.responseType),h&&([c,u]=tc(h,!0),m.addEventListener("progress",c)),p&&m.upload&&([a,d]=tc(p),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",d)),(n.cancelToken||n.signal)&&(o=t=>{m&&(r(!t||t.type?new Xa(null,e,m):t),m.abort(),m=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));const v=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);v&&-1===Va.protocols.indexOf(v)?r(new ba("Unsupported protocol "+v+":",ba.ERR_BAD_REQUEST,e)):m.send(i||null)}))};var lc=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const i=function(e){if(!r){r=!0,o();const t=e instanceof Error?e:this.reason;n.abort(t instanceof ba?t:new Xa(t instanceof Error?t.message:t))}};let s=t&&setTimeout((()=>{s=null,i(new ba(`timeout ${t} of ms exceeded`,ba.ETIMEDOUT))}),t);const o=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)})),e=null)};e.forEach((e=>e.addEventListener("abort",i)));const{signal:a}=n;return a.unsubscribe=()=>ya.asap(o),a}};const pc=function*(e,t){let r=e.byteLength;if(!t||r<t)return void(yield e);let n,i=0;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},hc=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},fc=(e,t,r,n)=>{const i=async function*(e,t){for await(const r of hc(e))yield*pc(r,t)}(e,t);let s,o=0,a=e=>{s||(s=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await i.next();if(t)return a(),void e.close();let s=n.byteLength;if(r){let e=o+=s;r(e)}e.enqueue(new Uint8Array(n))}catch(e){throw a(e),e}},cancel:e=>(a(e),i.return())},{highWaterMark:2})},mc="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,gc=mc&&"function"==typeof ReadableStream,vc=mc&&("function"==typeof TextEncoder?(yc=new TextEncoder,e=>yc.encode(e)):async e=>new Uint8Array(await new Response(e).arrayBuffer()));var yc;const bc=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},_c=gc&&bc((()=>{let e=!1;const t=new Request(Va.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),Ec=gc&&bc((()=>ya.isReadableStream(new Response("").body))),wc={stream:Ec&&(e=>e.body)};var Sc;mc&&(Sc=new Response,["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!wc[e]&&(wc[e]=ya.isFunction(Sc[e])?t=>t[e]():(t,r)=>{throw new ba(`Response type '${e}' is not supported`,ba.ERR_NOT_SUPPORT,r)})})));const Cc=async(e,t)=>{const r=ya.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(ya.isBlob(e))return e.size;if(ya.isSpecCompliantForm(e)){const t=new Request(Va.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return ya.isArrayBufferView(e)||ya.isArrayBuffer(e)?e.byteLength:(ya.isURLSearchParams(e)&&(e+=""),ya.isString(e)?(await vc(e)).byteLength:void 0)})(t):r};var Tc=mc&&(async e=>{let{url:t,method:r,data:n,signal:i,cancelToken:s,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:d,headers:u,withCredentials:l="same-origin",fetchOptions:p}=dc(e);d=d?(d+"").toLowerCase():"text";let h,f=lc([i,s&&s.toAbortSignal()],o);const m=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let g;try{if(c&&_c&&"get"!==r&&"head"!==r&&0!==(g=await Cc(u,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if(ya.isFormData(n)&&(e=r.headers.get("content-type"))&&u.setContentType(e),r.body){const[e,t]=rc(g,tc(nc(c)));n=fc(r.body,65536,e,t)}}ya.isString(l)||(l=l?"include":"omit");const i="credentials"in Request.prototype;h=new Request(t,{...p,signal:f,method:r.toUpperCase(),headers:u.normalize().toJSON(),body:n,duplex:"half",credentials:i?l:void 0});let s=await fetch(h,p);const o=Ec&&("stream"===d||"response"===d);if(Ec&&(a||o&&m)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=s[t]}));const t=ya.toFiniteNumber(s.headers.get("content-length")),[r,n]=a&&rc(t,tc(nc(a),!0))||[];s=new Response(fc(s.body,65536,r,(()=>{n&&n(),m&&m()})),e)}d=d||"text";let v=await wc[ya.findKey(wc,d)||"text"](s,e);return!o&&m&&m(),await new Promise(((t,r)=>{ec(t,r,{data:v,headers:Ja.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:h})}))}catch(t){if(m&&m(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new ba("Network Error",ba.ERR_NETWORK,e,h),{cause:t.cause||t});throw ba.from(t,t&&t.code,e,h)}});const Pc={http:null,xhr:uc,fetch:Tc};ya.forEach(Pc,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));const Rc=e=>`- ${e}`,kc=e=>ya.isFunction(e)||null===e||!1===e;var Dc=e=>{e=ya.isArray(e)?e:[e];const{length:t}=e;let r,n;const i={};for(let s=0;s<t;s++){let t;if(r=e[s],n=r,!kc(r)&&(n=Pc[(t=String(r)).toLowerCase()],void 0===n))throw new ba(`Unknown adapter '${t}'`);if(n)break;i[t||"#"+s]=n}if(!n){const e=Object.entries(i).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new ba("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(Rc).join("\n"):" "+Rc(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n};function Ic(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Xa(null,e)}function Ac(e){Ic(e),e.headers=Ja.from(e.headers),e.data=Qa.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Dc(e.adapter||Ha.adapter)(e).then((function(t){return Ic(e),t.data=Qa.call(e,e.transformResponse,t),t.headers=Ja.from(t.headers),t}),(function(t){return Za(t)||(Ic(e),t&&t.response&&(t.response.data=Qa.call(e,e.transformResponse,t.response),t.response.headers=Ja.from(t.response.headers))),Promise.reject(t)}))}const Oc={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Oc[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const Mc={};Oc.transitional=function(e,t,r){function n(e,t){return"[Axios v1.10.0] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,i,s)=>{if(!1===e)throw new ba(n(i," has been removed"+(t?" in "+t:"")),ba.ERR_DEPRECATED);return t&&!Mc[i]&&(Mc[i]=!0,console.warn(n(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,i,s)}},Oc.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};var Nc={assertOptions:function(e,t,r){if("object"!=typeof e)throw new ba("options must be an object",ba.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let i=n.length;for(;i-- >0;){const s=n[i],o=t[s];if(o){const t=e[s],r=void 0===t||o(t,s,e);if(!0!==r)throw new ba("option "+s+" must be "+r,ba.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new ba("Unknown option "+s,ba.ERR_BAD_OPTION)}},validators:Oc};const Lc=Nc.validators;class xc{constructor(e){this.defaults=e||{},this.interceptors={request:new Oa,response:new Oa}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const r=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=cc(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:i}=t;void 0!==r&&Nc.assertOptions(r,{silentJSONParsing:Lc.transitional(Lc.boolean),forcedJSONParsing:Lc.transitional(Lc.boolean),clarifyTimeoutError:Lc.transitional(Lc.boolean)},!1),null!=n&&(ya.isFunction(n)?t.paramsSerializer={serialize:n}:Nc.assertOptions(n,{encode:Lc.function,serialize:Lc.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Nc.assertOptions(t,{baseUrl:Lc.spelling("baseURL"),withXsrfToken:Lc.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=i&&ya.merge(i.common,i[t.method]);i&&ya.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete i[e]})),t.headers=Ja.concat(s,i);const o=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))}));const c=[];let d;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let u,l=0;if(!a){const e=[Ac.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),u=e.length,d=Promise.resolve(t);l<u;)d=d.then(e[l++],e[l++]);return d}u=o.length;let p=t;for(l=0;l<u;){const e=o[l++],t=o[l++];try{p=e(p)}catch(e){t.call(this,e);break}}try{d=Ac.call(this,p)}catch(e){return Promise.reject(e)}for(l=0,u=c.length;l<u;)d=d.then(c[l++],c[l++]);return d}getUri(e){return Aa(oc((e=cc(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}}ya.forEach(["delete","get","head","options"],(function(e){xc.prototype[e]=function(t,r){return this.request(cc(r||{},{method:e,url:t,data:(r||{}).data}))}})),ya.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,i){return this.request(cc(i||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}xc.prototype[e]=t(),xc.prototype[e+"Form"]=t(!0)}));var Fc=xc;class jc{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,i){r.reason||(r.reason=new Xa(e,n,i),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;const t=new jc((function(t){e=t}));return{token:t,cancel:e}}}var Uc=jc;const Vc={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Vc).forEach((([e,t])=>{Vc[t]=e}));var Bc=Vc;const Wc=function e(t){const r=new Fc(t),n=Io(Fc.prototype.request,r);return ya.extend(n,Fc.prototype,r,{allOwnKeys:!0}),ya.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(cc(t,r))},n}(Ha);Wc.Axios=Fc,Wc.CanceledError=Xa,Wc.CancelToken=Uc,Wc.isCancel=Za,Wc.VERSION="1.10.0",Wc.toFormData=Pa,Wc.AxiosError=ba,Wc.Cancel=Wc.CanceledError,Wc.all=function(e){return Promise.all(e)},Wc.spread=function(e){return function(t){return e.apply(null,t)}},Wc.isAxiosError=function(e){return ya.isObject(e)&&!0===e.isAxiosError},Wc.mergeConfig=cc,Wc.AxiosHeaders=Ja,Wc.formToJSON=e=>Ba(ya.isHTMLForm(e)?new FormData(e):e),Wc.getAdapter=Dc,Wc.HttpStatusCode=Bc,Wc.default=Wc;var Hc=Wc;class qc extends Gn{constructor(e,t,r){super(null!=e?e:qc.DEFAULT_MESSAGE,null!=t?t:"already_created",r)}}qc.DEFAULT_MESSAGE="Resource has already been created";class zc extends Gn{constructor(e,t,r){super(null!=e?e:zc.DEFAULT_MESSAGE,null!=t?t:"forbidden",r)}}zc.DEFAULT_MESSAGE="Forbidden";class Gc extends Gn{constructor(e,t,r){super(null!=e?e:Gc.DEFAULT_MESSAGE,null!=t?t:"invalid_request",r)}}Gc.DEFAULT_MESSAGE="Invalid request";class Yc extends Gn{constructor(e,t,r){super(null!=e?e:Yc.DEFAULT_MESSAGE,null!=t?t:"too_many_requests",r)}}Yc.DEFAULT_MESSAGE="Too many requests";class $c extends Gn{constructor(e,t,r){super(null!=e?e:$c.DEFAULT_MESSAGE,null!=t?t:"unauthorized",r)}}$c.DEFAULT_MESSAGE="Unauthorized";const Kc=e=>(t,r,n)=>new e(t,r,n),Jc={check_access_fail:Kc(zc),join_room_fail:Kc(Gc),need_joined_to_channel:Kc(Qn),forbidden:Kc(zc),not_found:Kc(Yn),invalid_request:Kc(Gc),invalid_payload:Kc(Gc),already_created:Kc(qc),too_many_requests:Kc(Yc),something_went_wrong:Kc($n),di_error:Kc(Gc),resources_lock_error:Kc(Gc),already_connected:Kc(oo),timeout:Kc(Kn),unauthorized:Kc($c)},Qc=e=>{if(!(e=>"object"==typeof e&&null!==e&&!Array.isArray(e))(e))return!1;const{error:t,errorCode:r}=e;return!(void 0!==t&&"string"!=typeof t||void 0!==r&&"string"!=typeof r)},Zc=(e,t)=>{var r,n,i,s;const o={};return t&&Object.keys(t).length>0&&(o.response=t),"number"==typeof(null===(r=e.response)||void 0===r?void 0:r.status)&&(o.status=e.response.status),(null===(n=e.response)||void 0===n?void 0:n.statusText)&&(o.statusText=e.response.statusText),e.code&&(o.axiosCode=e.code),(null===(i=e.config)||void 0===i?void 0:i.url)&&(o.url=e.config.url),(null===(s=e.config)||void 0===s?void 0:s.method)&&(o.method=e.config.method),Object.keys(o).length>0?o:void 0};var Xc;!function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"}(Xc||(Xc={}));const ed=["/ping","/ice-parameters"];let td=class extends class extends class{constructor(e={}){var{securityWorker:t,secure:n,format:i}=e,s=r(e,["securityWorker","secure","format"]);this.securityData=null,this.setSecurityData=e=>{this.securityData=e},this.request=e=>o(this,void 0,void 0,(function*(){var{secure:t,path:n,type:i,query:s,format:o,body:a}=e,c=r(e,["secure","path","type","query","format","body"]);const d=("boolean"==typeof t?t:this.secure)&&this.securityWorker&&(yield this.securityWorker(this.securityData))||{},u=this.mergeRequestParams(c,d),l=o||this.format||void 0;return i===Xc.FormData&&a&&null!==a&&"object"==typeof a&&(a=this.createFormData(a)),i===Xc.Text&&a&&null!==a&&"string"!=typeof a&&(a=JSON.stringify(a)),this.instance.request(Object.assign(Object.assign({},u),{headers:Object.assign(Object.assign({},u.headers||{}),i&&i!==Xc.FormData?{"Content-Type":i}:{}),params:s,responseType:l,data:a,url:n}))})),this.instance=Hc.create(Object.assign(Object.assign({},s),{baseURL:s.baseURL||"signaling.livedigital.space/v1"})),this.secure=n,this.format=i,this.securityWorker=t}mergeRequestParams(e,t){const r=e.method||t&&t.method;return Object.assign(Object.assign(Object.assign(Object.assign({},this.instance.defaults),e),t||{}),{headers:Object.assign(Object.assign(Object.assign({},r&&this.instance.defaults.headers[r.toLowerCase()]||{}),e.headers||{}),t&&t.headers||{})})}stringifyFormItem(e){return"object"==typeof e&&null!==e?JSON.stringify(e):`${e}`}createFormData(e){return Object.keys(e||{}).reduce(((t,r)=>{const n=e[r],i=n instanceof Array?n:[n];for(const e of i){const n=e instanceof Blob||e instanceof File;t.append(r,n?e:this.stringifyFormItem(e))}return t}),new FormData)}}{constructor(){super(...arguments),this.peers={getPeers:(e,t={})=>this.request(Object.assign({path:"/peers",method:"GET",query:e,secure:!0,format:"json"},t)),registerPeer:(e,t={})=>this.request(Object.assign({path:"/peers",method:"POST",body:e,secure:!0,type:Xc.Json,format:"json"},t)),disconnectPeer:(e={})=>this.request(Object.assign({path:"/peers",method:"DELETE",secure:!0},e)),changePeerProducePermissions:(e,t,r={})=>this.request(Object.assign({path:`/peers/${e}/produce-permissions`,method:"PUT",body:t,secure:!0,type:Xc.Json},r)),addPeerProducePermissions:(e,t,r={})=>this.request(Object.assign({path:`/peers/${e}/produce-permissions/${t}`,method:"POST",secure:!0},r)),removePeerProducePermissions:(e,t,r={})=>this.request(Object.assign({path:`/peers/${e}/produce-permissions/${t}`,method:"DELETE",secure:!0},r))},this.router={getRtpCapabilities:(e={})=>this.request(Object.assign({path:"/router/rtp-capabilities",method:"GET",secure:!0,format:"json"},e))},this.channel={confirmChannelActivity:(e={})=>this.request(Object.assign({path:"/channel/activity",method:"PATCH",secure:!0},e)),triggerChannelStateEvent:(e,t={})=>this.request(Object.assign({path:"/channel/peers-state-message-id",method:"GET",query:e,secure:!0,format:"json"},t))},this.ping={pingPeer:(e={})=>this.request(Object.assign({path:"/ping",method:"POST",secure:!0},e))},this.appData={updateSelfPeerAppData:(e,t={})=>this.request(Object.assign({path:"/app-data",method:"PUT",body:e,secure:!0,type:Xc.Json},t))},this.producer={getGeneralDataProducer:(e={})=>this.request(Object.assign({path:"/producer/general-data",method:"GET",secure:!0,format:"json"},e)),getAudioObserverProducer:(e={})=>this.request(Object.assign({path:"/producer/audio-observer",method:"GET",secure:!0,format:"json"},e)),getChannelStateSyncDataProducer:(e={})=>this.request(Object.assign({path:"/producer/channel-state-sync-data",method:"GET",secure:!0,format:"json"},e)),closeProducer:(e,t={})=>this.request(Object.assign({path:`/producer/${e}`,method:"DELETE",secure:!0},t)),pauseProducer:(e,t={})=>this.request(Object.assign({path:`/producer/${e}/actions/pause`,method:"POST",secure:!0},t)),resumeProducer:(e,t={})=>this.request(Object.assign({path:`/producer/${e}/actions/resume`,method:"POST",secure:!0},t)),requestProducerMaxSpatialLayer:(e,t,r={})=>this.request(Object.assign({path:`/producer/${e}/max-spatial-layer`,method:"POST",body:t,secure:!0,type:Xc.Json},r)),setProducerMaxSpatialLayer:(e,t,r={})=>this.request(Object.assign({path:`/producer/${e}/max-spatial-layer`,method:"PUT",body:t,secure:!0,type:Xc.Json},r))},this.consumer={createConsumer:(e,t={})=>this.request(Object.assign({path:"/consumer",method:"POST",body:e,secure:!0,type:Xc.Json,format:"json"},t)),closeConsumer:(e,t={})=>this.request(Object.assign({path:`/consumer/${e}`,method:"DELETE",secure:!0},t)),pauseConsumer:(e,t={})=>this.request(Object.assign({path:`/consumer/${e}/actions/pause`,method:"POST",secure:!0},t)),resumeConsumer:(e,t={})=>this.request(Object.assign({path:`/consumer/${e}/actions/resume`,method:"POST",secure:!0},t)),updateConsumerPreferredLayers:(e,t,r={})=>this.request(Object.assign({path:`/consumer/${e}/preferred-layers`,method:"PUT",body:t,secure:!0,type:Xc.Json},r)),requestConsumerKeyFrame:(e,t={})=>this.request(Object.assign({path:`/consumer/${e}/key-frame`,method:"POST",secure:!0},t))},this.dataConsumer={createDataConsumer:(e,t={})=>this.request(Object.assign({path:"/data-consumer",method:"POST",body:e,secure:!0,type:Xc.Json,format:"json"},t))},this.transport={createTransport:(e,t={})=>this.request(Object.assign({path:"/transport",method:"POST",body:e,secure:!0,type:Xc.Json,format:"json"},t)),getTransportIceParameters:(e,t={})=>this.request(Object.assign({path:`/transport/${e}/ice-parameters`,method:"GET",secure:!0,format:"json"},t)),connectTransport:(e,t,r={})=>this.request(Object.assign({path:`/transport/${e}/connect`,method:"PUT",body:t,secure:!0,type:Xc.Json},r)),produceMediaToTransport:(e,t,r={})=>this.request(Object.assign({path:`/transport/${e}/media-producer`,method:"PUT",body:t,secure:!0,type:Xc.Json,format:"json"},r)),produceDataToTransport:(e,t,r={})=>this.request(Object.assign({path:`/transport/${e}/data-producer`,method:"PUT",body:t,secure:!0,type:Xc.Json,format:"json"},r)),closeTransport:(e,t={})=>this.request(Object.assign({path:`/transport/${e}`,method:"DELETE",secure:!0},t))}}}{constructor(e){super({baseURL:String("https://signaling-api.livedigital.space/v1"),securityWorker:e=>{if(!e)return;const t={};return e.token&&(t.Authorization=`Bearer ${e.token}`),e.peerApiVersion&&(t["x-peer-api-version"]=String(e.peerApiVersion)),e.datacenterType&&(t["x-datacenter-type"]=e.datacenterType),e.preferredDC&&(t["x-datacenter-name"]=e.preferredDC),{headers:t}}}),this.config=e,this.errorListeners=new Set,this.abortController=new AbortController,this.instance.interceptors.request.use((e=>(!e.signal&&this.abortController&&(e.signal=this.abortController.signal),e))),Do(this.instance,{retries:3,shouldResetTimeout:!0,retryDelay:e=>Math.min(300*Math.pow(2,e-1),2e3)+300*Math.random(),retryCondition:e=>{var t,r;return"ERR_CANCELED"!==e.code&&(("string"!=typeof(r=null===(t=e.config)||void 0===t?void 0:t.url)||!ed.some((e=>r.includes(e))))&&(Do.isNetworkError(e)||"ECONNABORTED"===e.code&&!e.response))}}),this.instance.interceptors.response.use((e=>e),(e=>{const t=(e=>{var t,r;if(!Hc.isAxiosError(e))return e instanceof Error?e:new $n;const n=e;if(!n.response){const e=Zc(n),r=n.message||$n.DEFAULT_MESSAGE,i=null!==(t=n.code)&&void 0!==t?t:"network_error";return new $n(r,i,e)}const i=Qc(n.response.data)?n.response.data:void 0,s="string"==typeof(null==i?void 0:i.errorCode)?i.errorCode:void 0,o="string"==typeof(null==i?void 0:i.error)?i.error:void 0,a=(o&&o.trim().length>0?o:n.message)||$n.DEFAULT_MESSAGE,c=Zc(n,i);if(s){const e=Jc[s];return e?e(a,s,c):new $n(a,s,c)}const d=null!==(r=n.code)&&void 0!==r?r:"number"==typeof n.response.status?`http_${n.response.status}`:"something_went_wrong";return new $n(a,d,c)})(e);throw this.notifyErrorListeners(t),t})),this.instance.defaults.timeout=7e3;const t=this.config.get("signalingServerUrl");t&&(this.instance.defaults.baseURL=t)}abortPendingRequests(e){this.abortController.abort(e),this.abortController=new AbortController}addErrorListener(e){return this.errorListeners.add(e),()=>{this.errorListeners.delete(e)}}notifyErrorListeners(e){this.errorListeners.forEach((t=>{try{t(e)}catch(e){}}))}};td=n([ot(),i(0,ct(mi.Config)),s("design:paramtypes",[Et])],td);var rd=td;class nd{constructor(e){this.missingPeers=e.missingPeers,this.missingProducers=e.missingProducers,this.consumersWithInconsistentState=e.consumersWithInconsistentState,this.producersWithInconsistentState=e.producersWithInconsistentState,this.peersWithInconsistentAppData=e.peersWithInconsistentAppData}hasInconsistencyCases(){return this.missingPeers.length>0||this.missingProducers.length>0||this.consumersWithInconsistentState.length>0||this.producersWithInconsistentState.length>0||this.peersWithInconsistentAppData.length>0}}class id{constructor(e){this.missingPeers=[],this.missingProducers=[],this.consumersWithInconsistentState=[],this.producersWithInconsistentState=[],this.peersWithInconsistentAppData=[],this.localState=e.localState,this.remoteState=e.remoteState}check(){return this.resetPreviousCheckResults(),this.remoteState.peers.forEach((e=>{const t=this.findLocalPeerById(e.id);if(!t)return void this.missingPeers.push(e.id);t.appDataHash!==e.appDataHash&&this.peersWithInconsistentAppData.push(e.id),e.producers.forEach((e=>{const r=this.findLocalProducerById(t,e.id);if(!r)return void this.missingProducers.push(e.id);if(this.isLocalProducerStateChangedRecently(r))return;if(r.paused!==e.paused)return void this.producersWithInconsistentState.push(e.id);const n=this.findLocalConsumerByProducerId(t,e.id);n&&n.paused!==e.paused&&this.consumersWithInconsistentState.push(n.id),r||this.missingProducers.push(e.id)}))})),new nd({missingPeers:this.missingPeers,missingProducers:this.missingProducers,consumersWithInconsistentState:this.consumersWithInconsistentState,producersWithInconsistentState:this.producersWithInconsistentState,peersWithInconsistentAppData:this.peersWithInconsistentAppData})}getMissingPeers(){return this.missingPeers}getMissingProducers(){return this.missingProducers}getConsumersWithInconsistentState(){return this.consumersWithInconsistentState}getProducersWithInconsistentState(){return this.producersWithInconsistentState}getPeersWithInconsistentAppData(){return this.peersWithInconsistentAppData}findLocalPeerById(e){return this.localState.peers.find((t=>t.id===e))}findLocalConsumerByProducerId(e,t){var r;return null===(r=e.consumers)||void 0===r?void 0:r.find((e=>e.producerId===t))}findLocalProducerById(e,t){return e.producers.find((e=>e.id===t))}resetPreviousCheckResults(){this.missingPeers=[],this.missingProducers=[],this.consumersWithInconsistentState=[],this.producersWithInconsistentState=[],this.peersWithInconsistentAppData=[]}isLocalProducerStateChangedRecently(e){return Date.now()-e.stateChangedAt<5e3}}var sd,od,ad,cd,dd,ud,ld;!function(e){e.MissingPeer="missing-peer",e.MissingProducer="missing-producer",e.IncorrectProducerState="incorrect-producer-state",e.IncorrectConsumerState="incorrect-consumer-state",e.IncorrectAppData="incorrect-app-data"}(sd||(sd={}));let pd=class{constructor(e,t,r,n,i,s,o){var a;this.network=t,this.callState=r,this.peersStorage=n,this.clientEventEmitter=i,this.signalingApiClient=s,this.webRtcIssueDetector=o,od.set(this,void 0),ad.set(this,void 0),cd.set(this,[]),dd.set(this,!1),ud.set(this,{inbound:4.3,outbound:4.3}),ld.set(this,(new Date).getTime()-15e3),c(this,ad,null===(a=this.webRtcIssueDetector)||void 0===a?void 0:a.eventEmitter,"f"),c(this,od,e("ChannelStateSyncEventHandler"),"f"),this.debouncedHandleChannelStateEvent=ii(this.handleChannelStateEvent.bind(this),3e3),this.listenNetworkScoresUpdatedEvents()}handleChannelStateShort(e){return o(this,void 0,void 0,(function*(){try{yield this.debouncedHandleChannelStateEvent(e)}catch(e){a(this,od,"f").error("handleChannelStateSyncEvent()",{error:Vt(e)})}}))}handleChannelStateEvent(e){return o(this,void 0,void 0,(function*(){if(a(this,dd,"f"))a(this,od,"f").warn("Channel state event is already being handled, skipping new event",{case:"handleChannelStateEvent"});else{c(this,dd,!0,"f");try{yield this.collectProbableInconsistencyCases(e);const t=this.getConfirmedInconsistencyResult();if(!(null==t?void 0:t.hasInconsistencyCases()))return;if(this.isRestoreStateRequestToEarly())return void a(this,od,"f").info("Inconsistency detected, but restore skipped",Object.assign({},t));this.handleConfirmedInconsistencyResult(t)}finally{c(this,dd,!1,"f")}}}))}getLastInconsistencyCheckResult(){return a(this,cd,"f")[a(this,cd,"f").length-1]}handleConfirmedInconsistencyResult(e){e.missingPeers.forEach((e=>{this.clientEventEmitter.safeEmit(en,{peerId:e,peersLoaded:this.network.peersLoaded,sdkInstances:Array.from(window._sdkMarks||[]).length,type:sd.MissingPeer})})),e.missingProducers.forEach((e=>{this.clientEventEmitter.safeEmit(en,{producerId:e,type:sd.MissingProducer})})),e.producersWithInconsistentState.forEach((e=>{this.clientEventEmitter.safeEmit(en,{producerId:e,type:sd.IncorrectProducerState})})),e.peersWithInconsistentAppData.forEach((e=>{this.clientEventEmitter.safeEmit(en,{peerId:e,type:sd.IncorrectAppData})}))}getConfirmedInconsistencyResult(){const e=this.getLastInconsistencyCheckResult();if(!e)return;return new nd({missingPeers:this.getConfirmedMissingPeers(e.missingPeers),missingProducers:this.getConfirmedMissingProducers(e.missingProducers),consumersWithInconsistentState:this.getConfirmedConsumersWithInconsistencState(e.consumersWithInconsistentState),producersWithInconsistentState:this.getConfirmedProducersWithInconsistencState(e.producersWithInconsistentState),peersWithInconsistentAppData:this.getConfirmedPeersWithInconsistentAppData(e.missingPeers)})}collectProbableInconsistencyCases(e){return o(this,void 0,void 0,(function*(){const t=new id({remoteState:e,localState:this.getLocalState()}).check();if(this.rotateLastProbableInconsistencyCheckResults(t),!t.hasInconsistencyCases())return;if(this.isBadNetworkScore())return void this.resetLastProbableInconsistencyCheckResults();(yield this.getIsConnectionActive())&&this.callState.isJoined&&this.network.isNetworkActive||this.resetLastProbableInconsistencyCheckResults()}))}resetLastProbableInconsistencyCheckResults(){c(this,cd,[],"f")}rotateLastProbableInconsistencyCheckResults(e){4===a(this,cd,"f").length&&a(this,cd,"f").shift(),a(this,cd,"f").push(e)}isReachedMaxCheckRetries(e,t,r=4){let n=0;return a(this,cd,"f").forEach((r=>{r[e].includes(t)&&(n+=1)})),n>=r}getConfirmedMissingPeers(e){return e.filter((e=>this.isReachedMaxCheckRetries("missingPeers",e)))}getConfirmedMissingProducers(e){return e.filter((e=>this.isReachedMaxCheckRetries("missingProducers",e)))}getConfirmedConsumersWithInconsistencState(e){return e.filter((e=>this.isReachedMaxCheckRetries("consumersWithInconsistentState",e,1)))}getConfirmedProducersWithInconsistencState(e){return e.filter((e=>this.isReachedMaxCheckRetries("producersWithInconsistentState",e)))}getConfirmedPeersWithInconsistentAppData(e){return e.filter((e=>this.isReachedMaxCheckRetries("peersWithInconsistentAppData",e)))}getLocalState(){return{peers:this.peersStorage.hosts().map((e=>({id:e.id,appDataHash:yo(e.appData),producers:e.getProducers().map((e=>({id:e.id,paused:e.paused,stateChangedAt:e.getStateChangedAt()}))),consumers:e.getConsumersState()})))}}getIsConnectionActive(){return o(this,void 0,void 0,(function*(){try{return!!this.network.isNetworkActive&&(yield this.signalingApiClient.ping.pingPeer(),!0)}catch(e){return!1}}))}listenNetworkScoresUpdatedEvents(){a(this,ad,"f")&&a(this,ad,"f").on(Wt.NetworkScoresUpdated,(e=>{e.inbound&&(a(this,ud,"f").inbound=e.inbound),e.outbound&&(a(this,ud,"f").outbound=e.outbound)}))}isBadNetworkScore(){const{inbound:e,outbound:t}=a(this,ud,"f");return e<=2.6||t<=2.6}compareCheckedAndRestoredResults(e,t){return new nd({missingPeers:e.missingPeers.filter((e=>!t.missingPeers.includes(e))),missingProducers:e.missingProducers.filter((e=>!t.missingProducers.includes(e))),consumersWithInconsistentState:e.consumersWithInconsistentState.filter((e=>!t.fixedConsumersState.includes(e))),producersWithInconsistentState:e.producersWithInconsistentState.filter((e=>!t.fixedProducersState.includes(e))),peersWithInconsistentAppData:e.peersWithInconsistentAppData.filter((e=>!t.restoredAppDataPeers.includes(e)))})}isRestoreStateRequestToEarly(){return(new Date).getTime()-a(this,ld,"f")<=15e3}};od=new WeakMap,ad=new WeakMap,cd=new WeakMap,dd=new WeakMap,ud=new WeakMap,ld=new WeakMap,pd=n([ot(),i(0,ct(mi.LoggerFactory)),i(1,ct(mi.Network)),i(2,ct(mi.CallState)),i(3,ct(mi.PeersStorage)),i(4,ct(mi.ClientEventEmitter)),i(5,ct(mi.SignalingApiClient)),i(6,ct(mi.WebRTCIssueDetector)),s("design:paramtypes",[Function,po,gi,fo,Ft,rd,Tr])],pd);var hd=pd,fd={},md={exports:{}},gd=1e3,vd=6e4,yd=60*vd,bd=24*yd,_d=function(e,t){t=t||{};var r=typeof e;if("string"===r&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return 6048e5*r;case"days":case"day":case"d":return r*bd;case"hours":case"hour":case"hrs":case"hr":case"h":return r*yd;case"minutes":case"minute":case"mins":case"min":case"m":return r*vd;case"seconds":case"second":case"secs":case"sec":case"s":return 1e3*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(e);if("number"===r&&isFinite(e))return t.long?function(e){var t=Math.abs(e);if(t>=bd)return Ed(e,t,bd,"day");if(t>=yd)return Ed(e,t,yd,"hour");if(t>=vd)return Ed(e,t,vd,"minute");if(t>=1e3)return Ed(e,t,1e3,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=bd)return Math.round(e/bd)+"d";if(t>=yd)return Math.round(e/yd)+"h";if(t>=vd)return Math.round(e/vd)+"m";if(t>=gd)return Math.round(e/gd)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function Ed(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}var wd=function(e){function t(e){let n,i,s,o=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,i)=>{if("%%"===n)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];n=s.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e,t){let r=0,n=0,i=-1,s=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(i=n,s=r,n++):(r++,n++);else{if(-1===i)return!1;n=i+1,s++,r=s}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(n(e,r))return!1;for(const r of t.names)if(n(e,r))return!0;return!1},t.humanize=_d,t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=wd(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(md,md.exports);var Sd={};Object.defineProperty(Sd,"__esModule",{value:!0});var Cd={},Td={};Object.defineProperty(Td,"__esModule",{value:!0}),Td.Logger=void 0;const Pd=md.exports,Rd="mediasoup-client";Td.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Pd.default)(`${Rd}:${e}`),this._warn=(0,Pd.default)(`${Rd}:WARN:${e}`),this._error=(0,Pd.default)(`${Rd}:ERROR:${e}`)):(this._debug=(0,Pd.default)(Rd),this._warn=(0,Pd.default)(`${Rd}:WARN`),this._error=(0,Pd.default)(`${Rd}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};var kd={};Object.defineProperty(kd,"__esModule",{value:!0}),kd.EnhancedEventEmitter=void 0;const Dd=wt.exports,Id=new Td.Logger("EnhancedEventEmitter");class Ad extends Dd.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}close(){super.removeAllListeners()}emit(e,...t){return super.emit(e,...t)}safeEmit(e,...t){try{return super.emit(e,...t)}catch(t){Id.error("safeEmit() | event listener threw an error [eventName:%s]:%o",e,t);try{super.emit("listenererror",e,t)}catch(e){}return Boolean(super.listenerCount(e))}}on(e,t){return super.on(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.on(e,t),this}prependListener(e,t){return super.prependListener(e,t),this}once(e,t){return super.once(e,t),this}prependOnceListener(e,t){return super.prependOnceListener(e,t),this}removeListener(e,t){return super.off(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}rawListeners(e){return super.rawListeners(e)}}kd.EnhancedEventEmitter=Ad;var Od={};Object.defineProperty(Od,"__esModule",{value:!0}),Od.InvalidStateError=Od.UnsupportedError=void 0;class Md extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Md):this.stack=new Error(e).stack}}Od.UnsupportedError=Md;class Nd extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Nd):this.stack=new Error(e).stack}}Od.InvalidStateError=Nd;var Ld={};Object.defineProperty(Ld,"__esModule",{value:!0}),Ld.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))},Ld.generateRandomNumber=function(){return Math.round(1e7*Math.random())},Ld.deepFreeze=function e(t){const r=Reflect.ownKeys(t);for(const n of r){const r=t[n];(r&&"object"==typeof r||"function"==typeof r)&&e(r)}return Object.freeze(t)};var xd={},Fd={},jd={},Ud={exports:{}};var Vd=function(e){function t(e){let n,i,s,o=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,i)=>{if("%%"===n)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];n=s.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e,t){let r=0,n=0,i=-1,s=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(i=n,s=r,n++):(r++,n++);else{if(-1===i)return!1;n=i+1,s++,r=s}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(n(e,r))return!1;for(const r of t.names)if(n(e,r))return!0;return!1},t.humanize=_d,t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=Vd(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Ud,Ud.exports),Object.defineProperty(jd,"__esModule",{value:!0}),jd.Logger=void 0;const Bd=Ud.exports,Wd="h264-profile-level-id";jd.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Bd.default)(`${Wd}:${e}`),this._warn=(0,Bd.default)(`${Wd}:WARN:${e}`),this._error=(0,Bd.default)(`${Wd}:ERROR:${e}`)):(this._debug=(0,Bd.default)(Wd),this._warn=(0,Bd.default)(`${Wd}:WARN`),this._error=(0,Bd.default)(`${Wd}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}},Object.defineProperty(Fd,"__esModule",{value:!0}),Fd.ProfileLevelId=Fd.Level=Fd.Profile=void 0,Fd.parseProfileLevelId=Zd,Fd.profileLevelIdToString=Xd,Fd.profileToString=function(e){switch(e){case qd.ConstrainedBaseline:return"ConstrainedBaseline";case qd.Baseline:return"Baseline";case qd.Main:return"Main";case qd.ConstrainedHigh:return"ConstrainedHigh";case qd.High:return"High";case qd.PredictiveHigh444:return"PredictiveHigh444";default:return void Hd.warn(`profileToString() | unrecognized profile ${e}`)}},Fd.levelToString=function(e){switch(e){case zd.L1_b:return"1b";case zd.L1:return"1";case zd.L1_1:return"1.1";case zd.L1_2:return"1.2";case zd.L1_3:return"1.3";case zd.L2:return"2";case zd.L2_1:return"2.1";case zd.L2_2:return"2.2";case zd.L3:return"3";case zd.L3_1:return"3.1";case zd.L3_2:return"3.2";case zd.L4:return"4";case zd.L4_1:return"4.1";case zd.L4_2:return"4.2";case zd.L5:return"5";case zd.L5_1:return"5.1";case zd.L5_2:return"5.2";default:return void Hd.warn(`levelToString() | unrecognized level ${e}`)}},Fd.parseSdpProfileLevelId=eu,Fd.isSameProfile=function(e={},t={}){const r=eu(e),n=eu(t);return Boolean(r&&n&&r.profile===n.profile)},Fd.isSameProfileAndLevel=function(e={},t={}){const r=eu(e),n=eu(t);return Boolean(r&&n&&r.profile===n.profile&&r.level==n.level)},Fd.generateProfileLevelIdStringForAnswer=function(e={},t={}){if(!e["profile-level-id"]&&!t["profile-level-id"])return void Hd.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");const r=eu(e),n=eu(t);if(!r)throw new TypeError("invalid local_profile_level_id");if(!n)throw new TypeError("invalid remote_profile_level_id");if(r.profile!==n.profile)throw new TypeError("H264 Profile mismatch");const i=ru(e)&&ru(t),s=r.level,o=n.level,a=function(e,t){return function(e,t){if(e===zd.L1_b)return t!==zd.L1&&t!==zd.L1_b;if(t===zd.L1_b)return e!==zd.L1;return e<t}(e,t)?e:t}(s,o),c=i?s:a;return Hd.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${r.profile}, level:${c}]`),Xd(new Gd(r.profile,c))},Fd.supportedLevel=function(e,t){for(let r=Qd.length-1;r>=0;--r){const n=Qd[r];if(256*n.max_macroblock_frame_size<=e&&n.max_macroblocks_per_second<=t*n.max_macroblock_frame_size)return Hd.debug(`supportedLevel() | result [max_frame_pixel_count:${e}, max_fps:${t}, level:${n.level}]`),n.level}return void Hd.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${e}, max_fps:${t}]`)};const Hd=new jd.Logger;var qd,zd;!function(e){e[e.ConstrainedBaseline=1]="ConstrainedBaseline",e[e.Baseline=2]="Baseline",e[e.Main=3]="Main",e[e.ConstrainedHigh=4]="ConstrainedHigh",e[e.High=5]="High",e[e.PredictiveHigh444=6]="PredictiveHigh444"}(qd||(Fd.Profile=qd={})),function(e){e[e.L1_b=0]="L1_b",e[e.L1=10]="L1",e[e.L1_1=11]="L1_1",e[e.L1_2=12]="L1_2",e[e.L1_3=13]="L1_3",e[e.L2=20]="L2",e[e.L2_1=21]="L2_1",e[e.L2_2=22]="L2_2",e[e.L3=30]="L3",e[e.L3_1=31]="L3_1",e[e.L3_2=32]="L3_2",e[e.L4=40]="L4",e[e.L4_1=41]="L4_1",e[e.L4_2=42]="L4_2",e[e.L5=50]="L5",e[e.L5_1=51]="L5_1",e[e.L5_2=52]="L5_2"}(zd||(Fd.Level=zd={}));class Gd{profile;level;constructor(e,t){this.profile=e,this.level=t}}Fd.ProfileLevelId=Gd;const Yd=new Gd(qd.ConstrainedBaseline,zd.L3_1);class $d{mask;masked_value;constructor(e){this.mask=~tu("x",e),this.masked_value=tu("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}}class Kd{profile_idc;profile_iop;profile;constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}}const Jd=[new Kd(66,new $d("x1xx0000"),qd.ConstrainedBaseline),new Kd(77,new $d("1xxx0000"),qd.ConstrainedBaseline),new Kd(88,new $d("11xx0000"),qd.ConstrainedBaseline),new Kd(66,new $d("x0xx0000"),qd.Baseline),new Kd(88,new $d("10xx0000"),qd.Baseline),new Kd(77,new $d("0x0x0000"),qd.Main),new Kd(100,new $d("00000000"),qd.High),new Kd(100,new $d("00001100"),qd.ConstrainedHigh),new Kd(244,new $d("00000000"),qd.PredictiveHigh444)],Qd=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:zd.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:zd.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:zd.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:zd.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:zd.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:zd.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:zd.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:zd.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:zd.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:zd.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:zd.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:zd.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:zd.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:zd.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:zd.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:zd.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:zd.L5_2}];function Zd(e){if("string"!=typeof e||6!==e.length)return;const t=parseInt(e,16);if(0===t)return;const r=255&t,n=t>>8&255,i=t>>16&255;let s;switch(r){case zd.L1_1:s=0!=(16&n)?zd.L1_b:zd.L1_1;break;case zd.L1:case zd.L1_2:case zd.L1_3:case zd.L2:case zd.L2_1:case zd.L2_2:case zd.L3:case zd.L3_1:case zd.L3_2:case zd.L4:case zd.L4_1:case zd.L4_2:case zd.L5:case zd.L5_1:case zd.L5_2:s=r;break;default:return void Hd.warn(`parseProfileLevelId() | unrecognized level_idc [str:${e}, level_idc:${r}]`)}for(const t of Jd)if(i===t.profile_idc&&t.profile_iop.isMatch(n))return Hd.debug(`parseProfileLevelId() | result [str:${e}, profile:${t.profile}, level:${s}]`),new Gd(t.profile,s);Hd.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${e}, profile_idc:${i}, profile_iop:${n}]`)}function Xd(e){if(e.level==zd.L1_b)switch(e.profile){case qd.ConstrainedBaseline:return"42f00b";case qd.Baseline:return"42100b";case qd.Main:return"4d100b";default:return void Hd.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${e.profile}`)}let t;switch(e.profile){case qd.ConstrainedBaseline:t="42e0";break;case qd.Baseline:t="4200";break;case qd.Main:t="4d00";break;case qd.ConstrainedHigh:t="640c";break;case qd.High:t="6400";break;case qd.PredictiveHigh444:t="f400";break;default:return void Hd.warn(`profileLevelIdToString() | unrecognized profile ${e.profile}`)}let r=e.level.toString(16);return 1===r.length&&(r=`0${r}`),`${t}${r}`}function eu(e={}){const t=e["profile-level-id"];return t?Zd(t):Yd}function tu(e,t){return Number(t[0]===e)<<7|Number(t[1]===e)<<6|Number(t[2]===e)<<5|Number(t[3]===e)<<4|Number(t[4]===e)<<3|Number(t[5]===e)<<2|Number(t[6]===e)<<1|Number(t[7]===e)<<0}function ru(e={}){const t=e["level-asymmetry-allowed"];return!0===t||1===t||"1"===t}Object.defineProperty(xd,"__esModule",{value:!0}),xd.validateAndNormalizeRtpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(e.codecs&&!Array.isArray(e.codecs))throw new TypeError("caps.codecs is not an array");e.codecs||(e.codecs=[]);for(const t of e.codecs)ou(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)cu(t)},xd.validateAndNormalizeRtpParameters=su,xd.validateAndNormalizeSctpStreamParameters=function(e){if("object"!=typeof e)throw new TypeError("params is not an object");if("number"!=typeof e.streamId)throw new TypeError("missing params.streamId");let t=!1;"boolean"==typeof e.ordered?t=!0:e.ordered=!0;if(e.maxPacketLifeTime&&"number"!=typeof e.maxPacketLifeTime)throw new TypeError("invalid params.maxPacketLifeTime");if(e.maxRetransmits&&"number"!=typeof e.maxRetransmits)throw new TypeError("invalid params.maxRetransmits");if(e.maxPacketLifeTime&&e.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(t&&e.ordered&&(e.maxPacketLifeTime||e.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");t||!e.maxPacketLifeTime&&!e.maxRetransmits||(e.ordered=!1);if(e.label&&"string"!=typeof e.label)throw new TypeError("invalid params.label");if(e.protocol&&"string"!=typeof e.protocol)throw new TypeError("invalid params.protocol")},xd.validateSctpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(!e.numStreams||"object"!=typeof e.numStreams)throw new TypeError("missing caps.numStreams");!function(e){if("object"!=typeof e)throw new TypeError("numStreams is not an object");if("number"!=typeof e.OS)throw new TypeError("missing numStreams.OS");if("number"!=typeof e.MIS)throw new TypeError("missing numStreams.MIS")}(e.numStreams)},xd.getExtendedRtpCapabilities=function(e,t,r){const n={codecs:[],headerExtensions:[]};if(r)for(const r of e.codecs??[]){if(hu(r))continue;const e=(t.codecs??[]).find((e=>fu(e,r,{strict:!0,modify:!0})));if(!e)continue;const i={kind:r.kind,mimeType:r.mimeType,clockRate:r.clockRate,channels:r.channels,localPayloadType:r.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:e.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:r.parameters??{},remoteParameters:e.parameters??{},rtcpFeedback:gu(r,e)};n.codecs.push(i)}else for(const r of t.codecs??[]){if(hu(r))continue;const t=(e.codecs??[]).find((e=>fu(e,r,{strict:!0,modify:!0})));if(!t)continue;const i={kind:t.kind,mimeType:t.mimeType,clockRate:t.clockRate,channels:t.channels,localPayloadType:t.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:r.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:t.parameters??{},remoteParameters:r.parameters??{},rtcpFeedback:gu(t,r)};n.codecs.push(i)}for(const r of n.codecs){const n=e.codecs.find((e=>hu(e)&&e.parameters?.apt===r.localPayloadType)),i=t.codecs.find((e=>hu(e)&&e.parameters?.apt===r.remotePayloadType));n&&i&&(r.localRtxPayloadType=n.preferredPayloadType,r.remoteRtxPayloadType=i.preferredPayloadType)}for(const r of t.headerExtensions){const t=e.headerExtensions.find((e=>mu(e,r)));if(!t)continue;const i={kind:r.kind,uri:r.uri,sendId:t.preferredId,recvId:r.preferredId,encrypt:t.preferredEncrypt??!1,direction:"sendrecv"};switch(r.direction){case"sendrecv":i.direction="sendrecv";break;case"recvonly":i.direction="sendonly";break;case"sendonly":i.direction="recvonly";break;case"inactive":i.direction="inactive"}n.headerExtensions.push(i)}return n},xd.getRecvRtpCapabilities=function(e){return pu({direction:"recvonly",extendedRtpCapabilities:e})},xd.getSendRtpCapabilities=function(e){return pu({direction:"sendonly",extendedRtpCapabilities:e})},xd.getSendingRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const n of t.codecs){if(n.kind!==e)continue;const t={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.localParameters,rtcpFeedback:n.rtcpFeedback};if(r.codecs.push(t),n.localRtxPayloadType){const e={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const n of t.headerExtensions){if(n.kind&&n.kind!==e||"sendrecv"!==n.direction&&"sendonly"!==n.direction)continue;const t={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};r.headerExtensions.push(t)}return r},xd.getSendingRemoteRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const n of t.codecs){if(n.kind!==e)continue;const t={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.remoteParameters,rtcpFeedback:n.rtcpFeedback};if(r.codecs.push(t),n.localRtxPayloadType){const e={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const n of t.headerExtensions){if(n.kind&&n.kind!==e||"sendrecv"!==n.direction&&"sendonly"!==n.direction)continue;const t={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};r.headerExtensions.push(t)}if(r.headerExtensions.some((e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.uri)))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"goog-remb"!==e.type));else if(r.headerExtensions.some((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.uri)))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"transport-cc"!==e.type));else for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"transport-cc"!==e.type&&"goog-remb"!==e.type));return r},xd.reduceCodecs=function(e,t){const r=[];if(t){for(let n=0;n<e.length;++n)if(fu(e[n],t,{strict:!0})){r.push(e[n]),hu(e[n+1])&&r.push(e[n+1]);break}if(0===r.length)throw new TypeError("no matching codec found")}else r.push(e[0]),hu(e[1])&&r.push(e[1]);return r},xd.generateProbatorRtpParameters=function(e){su(e=iu.clone(e));const t={mid:"probator",codecs:[],headerExtensions:[],encodings:[{ssrc:1234}],rtcp:{cname:"probator"}};return t.codecs.push(e.codecs[0]),t.codecs[0].payloadType=127,t.headerExtensions=e.headerExtensions,t},xd.canSend=function(e,t){return(t.codecs??[]).some((t=>t.kind===e))},xd.canReceive=function(e,t){if(su(e),0===e.codecs.length)return!1;const r=e.codecs[0];return(t.codecs??[]).some((e=>e.preferredPayloadType===r.payloadType))};const nu=Fd,iu=Ld;function su(e){if("object"!=typeof e)throw new TypeError("params is not an object");if(e.mid&&"string"!=typeof e.mid)throw new TypeError("params.mid is not a string");if(!Array.isArray(e.codecs))throw new TypeError("missing params.codecs");for(const t of e.codecs)du(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("params.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)uu(t);if(e.encodings&&!Array.isArray(e.encodings))throw new TypeError("params.encodings is not an array");e.encodings||(e.encodings=[]);for(const t of e.encodings)lu(t);if(e.rtcp&&"object"!=typeof e.rtcp)throw new TypeError("params.rtcp is not an object");e.rtcp||(e.rtcp={}),function(e){if("object"!=typeof e)throw new TypeError("rtcp is not an object");if(e.cname&&"string"!=typeof e.cname)throw new TypeError("invalid rtcp.cname");e.reducedSize&&"boolean"==typeof e.reducedSize||(e.reducedSize=!0)}(e.rtcp)}function ou(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const r=t.exec(e.mimeType);if(!r)throw new TypeError("invalid codec.mimeType");if(e.kind=r[1].toLowerCase(),"number"!=typeof e.preferredPayloadType)throw new TypeError("missing codec.preferredPayloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===e.kind?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError(`invalid codec parameter [key:${t}s, value:${r}]`);if("apt"===t&&"number"!=typeof r)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)au(t)}function au(e){if("object"!=typeof e)throw new TypeError("fb is not an object");if(!e.type||"string"!=typeof e.type)throw new TypeError("missing fb.type");e.parameter&&"string"==typeof e.parameter||(e.parameter="")}function cu(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if("audio"!==e.kind&&"video"!==e.kind)throw new TypeError("invalid ext.kind");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.preferredId)throw new TypeError("missing ext.preferredId");if(e.preferredEncrypt&&"boolean"!=typeof e.preferredEncrypt)throw new TypeError("invalid ext.preferredEncrypt");if(e.preferredEncrypt||(e.preferredEncrypt=!1),e.direction&&"string"!=typeof e.direction)throw new TypeError("invalid ext.direction");e.direction||(e.direction="sendrecv")}function du(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const r=t.exec(e.mimeType);if(!r)throw new TypeError("invalid codec.mimeType");if("number"!=typeof e.payloadType)throw new TypeError("missing codec.payloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===r[1].toLowerCase()?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError(`invalid codec parameter [key:${t}s, value:${r}]`);if("apt"===t&&"number"!=typeof r)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)au(t)}function uu(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.id)throw new TypeError("missing ext.id");if(e.encrypt&&"boolean"!=typeof e.encrypt)throw new TypeError("invalid ext.encrypt");e.encrypt||(e.encrypt=!1),e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError("invalid header extension parameter")}}function lu(e){if("object"!=typeof e)throw new TypeError("encoding is not an object");if(e.ssrc&&"number"!=typeof e.ssrc)throw new TypeError("invalid encoding.ssrc");if(e.rid&&"string"!=typeof e.rid)throw new TypeError("invalid encoding.rid");if(e.rtx&&"object"!=typeof e.rtx)throw new TypeError("invalid encoding.rtx");if(e.rtx&&"number"!=typeof e.rtx.ssrc)throw new TypeError("missing encoding.rtx.ssrc");if(e.dtx&&"boolean"==typeof e.dtx||(e.dtx=!1),e.scalabilityMode&&"string"!=typeof e.scalabilityMode)throw new TypeError("invalid encoding.scalabilityMode")}function pu({direction:e,extendedRtpCapabilities:t}){const r={codecs:[],headerExtensions:[]};for(const e of t.codecs){const t={kind:e.kind,mimeType:e.mimeType,preferredPayloadType:e.remotePayloadType,clockRate:e.clockRate,channels:e.channels,parameters:e.localParameters,rtcpFeedback:e.rtcpFeedback};if(r.codecs.push(t),!e.remoteRtxPayloadType)continue;const n={kind:e.kind,mimeType:`${e.kind}/rtx`,preferredPayloadType:e.remoteRtxPayloadType,clockRate:e.clockRate,parameters:{apt:e.remotePayloadType},rtcpFeedback:[]};r.codecs.push(n)}for(const n of t.headerExtensions){if("sendrecv"!==n.direction&&n.direction!==e)continue;const t={kind:n.kind,uri:n.uri,preferredId:n.recvId,preferredEncrypt:n.encrypt??!1,direction:n.direction};r.headerExtensions.push(t)}return r}function hu(e){return!!e&&/.+\/rtx$/i.test(e.mimeType)}function fu(e,t,{strict:r=!1,modify:n=!1}={}){const i=e.mimeType.toLowerCase();if(i!==t.mimeType.toLowerCase())return!1;if(e.clockRate!==t.clockRate)return!1;if(e.channels!==t.channels)return!1;switch(i){case"video/h264":if(r){if((e.parameters["packetization-mode"]??0)!==(t.parameters["packetization-mode"]??0))return!1;if(!nu.isSameProfile(e.parameters,t.parameters))return!1;let r;try{r=nu.generateProfileLevelIdStringForAnswer(e.parameters,t.parameters)}catch(e){return!1}n&&(r?(e.parameters["profile-level-id"]=r,t.parameters["profile-level-id"]=r):(delete e.parameters["profile-level-id"],delete t.parameters["profile-level-id"]))}break;case"video/vp9":if(r){if((e.parameters["profile-id"]??0)!==(t.parameters["profile-id"]??0))return!1}}return!0}function mu(e,t){return(!e.kind||!t.kind||e.kind===t.kind)&&e.uri===t.uri}function gu(e,t){const r=[];for(const n of e.rtcpFeedback??[]){const e=(t.rtcpFeedback??[]).find((e=>e.type===n.type&&(e.parameter===n.parameter||!e.parameter&&!n.parameter)));e&&r.push(e)}return r}var vu={},yu={},bu={},_u={};Object.defineProperty(_u,"__esModule",{value:!0}),_u.Logger=void 0;const Eu=md.exports,wu="awaitqueue";_u.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=Eu(`awaitqueue:${e}`),this._warn=Eu(`awaitqueue:WARN:${e}`),this._error=Eu(`awaitqueue:ERROR:${e}`)):(this._debug=Eu(wu),this._warn=Eu("awaitqueue:WARN"),this._error=Eu("awaitqueue:ERROR")),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};var Su={};Object.defineProperty(Su,"__esModule",{value:!0}),Su.AwaitQueueRemovedTaskError=Su.AwaitQueueStoppedError=void 0;class Cu extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Cu)}}Su.AwaitQueueStoppedError=Cu;class Tu extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Tu)}}Su.AwaitQueueRemovedTaskError=Tu,Object.defineProperty(bu,"__esModule",{value:!0}),bu.AwaitQueue=void 0;const Pu=Su,Ru=new _u.Logger("AwaitQueue");bu.AwaitQueue=class{pendingTasks=new Map;nextTaskId=0;constructor(){Ru.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t,r){if(t=t??e.name,Ru.debug(`push() [name:${t}, options:%o]`,r),"function"!=typeof e)throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch(e){}return new Promise(((n,i)=>{if(t&&r?.removeOngoingTasksWithSameName)for(const e of this.pendingTasks.values())e.name===t&&e.reject(new Pu.AwaitQueueRemovedTaskError,{canExecuteNextTask:!1});const s={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:e=>{if(s.completed)return;s.completed=!0,this.pendingTasks.delete(s.id),Ru.debug(`resolving task [name:${s.name}]`),n(e);const[t]=this.pendingTasks.values();t&&!t.executedAt&&this.execute(t)},reject:(e,{canExecuteNextTask:t})=>{if(!s.completed&&(s.completed=!0,this.pendingTasks.delete(s.id),Ru.debug(`rejecting task [name:${s.name}]: %s`,String(e)),i(e),t)){const[e]=this.pendingTasks.values();e&&!e.executedAt&&this.execute(e)}}};this.pendingTasks.set(s.id,s),1===this.pendingTasks.size&&this.execute(s)}))}stop(){Ru.debug("stop()");for(const e of this.pendingTasks.values())Ru.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Pu.AwaitQueueStoppedError,{canExecuteNextTask:!1})}remove(e){Ru.debug(`remove() [taskIdx:${e}]`);const t=Array.from(this.pendingTasks.values())[e];t?t.reject(new Pu.AwaitQueueRemovedTaskError,{canExecuteNextTask:!0}):Ru.debug(`stop() | no task with given idx [taskIdx:${e}]`)}dump(){const e=Date.now();let t=0;return Array.from(this.pendingTasks.values()).map((r=>({idx:t++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:e-r.enqueuedAt,executionTime:r.executedAt?e-r.executedAt:0})))}async execute(e){if(Ru.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const t=await e.task();e.resolve(t)}catch(t){e.reject(t,{canExecuteNextTask:!0})}}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AwaitQueueRemovedTaskError=e.AwaitQueueStoppedError=e.AwaitQueue=void 0;var t=bu;Object.defineProperty(e,"AwaitQueue",{enumerable:!0,get:function(){return t.AwaitQueue}});var r=Su;Object.defineProperty(e,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return r.AwaitQueueStoppedError}}),Object.defineProperty(e,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return r.AwaitQueueRemovedTaskError}})}(yu);var ku={};Object.defineProperty(ku,"__esModule",{value:!0}),ku.Producer=void 0;const Du=kd,Iu=Od,Au=new Td.Logger("Producer");class Ou extends Du.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new Du.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:r,track:n,rtpParameters:i,stopTracks:s,disableTrackOnPause:o,zeroRtpOnPause:a,appData:c}){super(),Au.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=r,this._track=n,this._kind=n.kind,this._rtpParameters=i,this._paused=!!o&&!n.enabled,this._maxSpatialLayer=void 0,this._stopTracks=s,this._disableTrackOnPause=o,this._zeroRtpOnPause=a,this._appData=c??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get rtpSender(){return this._rtpSender}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Au.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Au.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Iu.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){Au.debug("pause()"),this._closed?Au.error("pause() | Producer closed"):(this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&new Promise(((e,t)=>{this.safeEmit("@pause",e,t)})).catch((()=>{})),this._observer.safeEmit("pause"))}resume(){Au.debug("resume()"),this._closed?Au.error("resume() | Producer closed"):(this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&new Promise(((e,t)=>{this.safeEmit("@resume",e,t)})).catch((()=>{})),this._observer.safeEmit("resume"))}async replaceTrack({track:e}){if(Au.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch(e){}throw new Iu.InvalidStateError("closed")}if("ended"===e?.readyState)throw new Iu.InvalidStateError("track ended");e!==this._track?(await new Promise(((t,r)=>{this.safeEmit("@replacetrack",e,t,r)})),this.destroyTrack(),this._track=e,this._track&&this._disableTrackOnPause&&(this._paused?this._paused&&(this._track.enabled=!1):this._track.enabled=!0),this.handleTrack()):Au.debug("replaceTrack() | same track, ignored")}async setMaxSpatialLayer(e){if(this._closed)throw new Iu.InvalidStateError("closed");if("video"!==this._kind)throw new Iu.UnsupportedError("not a video Producer");if("number"!=typeof e)throw new TypeError("invalid spatialLayer");e!==this._maxSpatialLayer&&(await new Promise(((t,r)=>{this.safeEmit("@setmaxspatiallayer",e,t,r)})).catch((()=>{})),this._maxSpatialLayer=e)}async setRtpEncodingParameters(e){if(this._closed)throw new Iu.InvalidStateError("closed");if("object"!=typeof e)throw new TypeError("invalid params");await new Promise(((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)}))}onTrackEnded(){Au.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track&&this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){if(this._track)try{this._track.removeEventListener("ended",this.onTrackEnded),this._stopTracks&&this._track.stop()}catch(e){}}}ku.Producer=Ou;var Mu={};Object.defineProperty(Mu,"__esModule",{value:!0}),Mu.Consumer=void 0;const Nu=kd,Lu=Od,xu=new Td.Logger("Consumer");class Fu extends Nu.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new Nu.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:r,rtpReceiver:n,track:i,rtpParameters:s,appData:o}){super(),xu.debug("constructor()"),this._id=e,this._localId=t,this._producerId=r,this._rtpReceiver=n,this._track=i,this._rtpParameters=s,this._paused=!i.enabled,this._appData=o??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get producerId(){return this._producerId}get closed(){return this._closed}get kind(){return this._track.kind}get rtpReceiver(){return this._rtpReceiver}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(xu.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(xu.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Lu.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){xu.debug("pause()"),this._closed?xu.error("pause() | Consumer closed"):this._paused?xu.debug("pause() | Consumer is already paused"):(this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause"))}resume(){xu.debug("resume()"),this._closed?xu.error("resume() | Consumer closed"):this._paused?(this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")):xu.debug("resume() | Consumer is already resumed")}onTrackEnded(){xu.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){try{this._track.removeEventListener("ended",this.onTrackEnded),this._track.stop()}catch(e){}}}Mu.Consumer=Fu;var ju={};Object.defineProperty(ju,"__esModule",{value:!0}),ju.DataProducer=void 0;const Uu=kd,Vu=Od,Bu=new Td.Logger("DataProducer");class Wu extends Uu.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new Uu.EnhancedEventEmitter;constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:n}){super(),Bu.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=r,this._appData=n??{},this.handleDataChannel()}get id(){return this._id}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get bufferedAmount(){return this._dataChannel.bufferedAmount}get bufferedAmountLowThreshold(){return this._dataChannel.bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._dataChannel.bufferedAmountLowThreshold=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Bu.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Bu.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(Bu.debug("send()"),this._closed)throw new Vu.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(Bu.debug('DataChannel "open" event'),this.safeEmit("open"))})),this._dataChannel.addEventListener("error",(e=>{if(this._closed)return;const t=e.error??new Error("unknown DataChannel error");"sctp-failure"===e.error?.errorDetail?Bu.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):Bu.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(Bu.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))})),this._dataChannel.addEventListener("message",(()=>{this._closed||Bu.warn('DataChannel "message" event in a DataProducer, message discarded')})),this._dataChannel.addEventListener("bufferedamountlow",(()=>{this._closed||this.safeEmit("bufferedamountlow")}))}}ju.DataProducer=Wu;var Hu={};Object.defineProperty(Hu,"__esModule",{value:!0}),Hu.DataConsumer=void 0;const qu=kd,zu=new Td.Logger("DataConsumer");class Gu extends qu.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new qu.EnhancedEventEmitter;constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:n,appData:i}){super(),zu.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=r,this._sctpStreamParameters=n,this._appData=i??{},this.handleDataChannel()}get id(){return this._id}get dataProducerId(){return this._dataProducerId}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get binaryType(){return this._dataChannel.binaryType}set binaryType(e){this._dataChannel.binaryType=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(zu.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(zu.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(zu.debug('DataChannel "open" event'),this.safeEmit("open"))})),this._dataChannel.addEventListener("error",(e=>{if(this._closed)return;const t=e.error??new Error("unknown DataChannel error");"sctp-failure"===e.error?.errorDetail?zu.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):zu.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(zu.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))})),this._dataChannel.addEventListener("message",(e=>{this._closed||this.safeEmit("message",e.data)}))}}Hu.DataConsumer=Gu,Object.defineProperty(vu,"__esModule",{value:!0}),vu.Transport=void 0;const Yu=yu,$u=kd,Ku=Od,Ju=Ld,Qu=xd,Zu=ku,Xu=Mu,el=ju,tl=Hu,rl=new Td.Logger("Transport");class nl{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class il extends $u.EnhancedEventEmitter{_id;_closed=!1;_direction;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_canProduceByKind;_maxSctpMessageSize;_handler;_iceGatheringState="new";_connectionState="new";_appData;_producers=new Map;_consumers=new Map;_dataProducers=new Map;_dataConsumers=new Map;_probatorConsumerCreated=!1;_awaitQueue=new Yu.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new $u.EnhancedEventEmitter;constructor({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d,handlerFactory:u,getSendExtendedRtpCapabilities:l,recvRtpCapabilities:p,canProduceByKind:h}){super(),rl.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._getSendExtendedRtpCapabilities=l,this._recvRtpCapabilities=p,this._canProduceByKind=h,this._maxSctpMessageSize=s?s.maxMessageSize:null;const f=Ju.clone(c)??{};delete f.iceServers,delete f.iceTransportPolicy,delete f.bundlePolicy,delete f.rtcpMuxPolicy,this._handler=u.factory({direction:e,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:f,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities}),this._appData=d??{},this.handleHandler()}get id(){return this._id}get closed(){return this._closed}get direction(){return this._direction}get handler(){return this._handler}get iceGatheringState(){return this._iceGatheringState}get connectionState(){return this._connectionState}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){if(!this._closed){rl.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(const e of this._producers.values())e.transportClosed();this._producers.clear();for(const e of this._consumers.values())e.transportClosed();this._consumers.clear();for(const e of this._dataProducers.values())e.transportClosed();this._dataProducers.clear();for(const e of this._dataConsumers.values())e.transportClosed();this._dataConsumers.clear(),this._observer.safeEmit("close"),super.close(),this._observer.close()}}async getStats(){if(this._closed)throw new Ku.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(rl.debug("restartIce()"),this._closed)throw new Ku.InvalidStateError("closed");if(!e)throw new TypeError("missing iceParameters");return this._awaitQueue.push((async()=>await this._handler.restartIce(e)),"transport.restartIce()")}async updateIceServers({iceServers:e}={}){if(rl.debug("updateIceServers()"),this._closed)throw new Ku.InvalidStateError("closed");if(!Array.isArray(e))throw new TypeError("missing iceServers");return this._awaitQueue.push((async()=>this._handler.updateIceServers(e)),"transport.updateIceServers()")}async produce({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s,stopTracks:o=!0,disableTrackOnPause:a=!0,zeroRtpOnPause:c=!1,onRtpSender:d,appData:u={}}={}){if(rl.debug("produce() [track:%o]",e),this._closed)throw new Ku.InvalidStateError("closed");if(!e)throw new TypeError("missing track");if("send"!==this._direction)throw new Ku.UnsupportedError("not a sending Transport");if(!this._canProduceByKind[e.kind])throw new Ku.UnsupportedError(`cannot produce ${e.kind}`);if("ended"===e.readyState)throw new Ku.InvalidStateError("track ended");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("produce"))throw new TypeError('no "produce" listener set into this transport');if(u&&"object"!=typeof u)throw new TypeError("if given, appData must be an object");return this._awaitQueue.push((async()=>{let l;if(r&&!Array.isArray(r))throw TypeError("encodings must be an array");0===r?.length?l=void 0:r&&(l=r.map((e=>{const t={active:!0};return!1===e.active&&(t.active=!1),"boolean"==typeof e.dtx&&(t.dtx=e.dtx),"string"==typeof e.scalabilityMode&&(t.scalabilityMode=e.scalabilityMode),"number"==typeof e.scaleResolutionDownBy&&(t.scaleResolutionDownBy=e.scaleResolutionDownBy),"number"==typeof e.maxBitrate&&(t.maxBitrate=e.maxBitrate),"number"==typeof e.maxFramerate&&(t.maxFramerate=e.maxFramerate),"boolean"==typeof e.adaptivePtime&&(t.adaptivePtime=e.adaptivePtime),"string"==typeof e.priority&&(t.priority=e.priority),"string"==typeof e.networkPriority&&(t.networkPriority=e.networkPriority),t})));const{localId:p,rtpParameters:h,rtpSender:f}=await this._handler.send({track:e,streamId:t,encodings:l,codecOptions:n,headerExtensionOptions:i,codec:s,onRtpSender:d});try{Qu.validateAndNormalizeRtpParameters(h);const{id:t}=await new Promise(((t,r)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:h,appData:u},t,r)})),r=new Zu.Producer({id:t,localId:p,rtpSender:f,track:e,rtpParameters:h,stopTracks:o,disableTrackOnPause:a,zeroRtpOnPause:c,appData:u});return this._producers.set(r.id,r),this.handleProducer(r),this._observer.safeEmit("newproducer",r),r}catch(e){throw this._handler.stopSending(p).catch((()=>{})),e}}),"transport.produce()").catch((t=>{if(o)try{e.stop()}catch(e){}throw t}))}async consume({id:e,producerId:t,kind:r,rtpParameters:n,streamId:i,onRtpReceiver:s,appData:o={}}){if(rl.debug("consume()"),this._closed)throw new Ku.InvalidStateError("closed");if("recv"!==this._direction)throw new Ku.UnsupportedError("not a receiving Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing producerId");if("audio"!==r&&"video"!==r)throw new TypeError(`invalid kind '${r}'`);if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(o&&"object"!=typeof o)throw new TypeError("if given, appData must be an object");const a=Ju.clone(n);if(!Qu.canReceive(a,this._recvRtpCapabilities))throw new Ku.UnsupportedError("cannot consume this Producer");const c=new nl({id:e,producerId:t,kind:r,rtpParameters:a,streamId:i,onRtpReceiver:s,appData:o});return this._pendingConsumerTasks.push(c),queueMicrotask((()=>{this._closed||!1===this._consumerCreationInProgress&&this.createPendingConsumers()})),c.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:r,label:n="",protocol:i="",appData:s={}}={}){if(rl.debug("produceData()"),this._closed)throw new Ku.InvalidStateError("closed");if("send"!==this._direction)throw new Ku.UnsupportedError("not a sending Transport");if(!this._maxSctpMessageSize)throw new Ku.UnsupportedError("SCTP not enabled by remote Transport");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("producedata"))throw new TypeError('no "producedata" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");return(t||r)&&(e=!1),this._awaitQueue.push((async()=>{const{dataChannel:o,sctpStreamParameters:a}=await this._handler.sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i});Qu.validateAndNormalizeSctpStreamParameters(a);const{id:c}=await new Promise(((e,t)=>{this.safeEmit("producedata",{sctpStreamParameters:a,label:n,protocol:i,appData:s},e,t)})),d=new el.DataProducer({id:c,dataChannel:o,sctpStreamParameters:a,appData:s});return this._dataProducers.set(d.id,d),this.handleDataProducer(d),this._observer.safeEmit("newdataproducer",d),d}),"transport.produceData()")}async consumeData({id:e,dataProducerId:t,sctpStreamParameters:r,label:n="",protocol:i="",appData:s={}}){if(rl.debug("consumeData()"),this._closed)throw new Ku.InvalidStateError("closed");if("recv"!==this._direction)throw new Ku.UnsupportedError("not a receiving Transport");if(!this._maxSctpMessageSize)throw new Ku.UnsupportedError("SCTP not enabled by remote Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing dataProducerId");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");const o=Ju.clone(r);return Qu.validateAndNormalizeSctpStreamParameters(o),this._awaitQueue.push((async()=>{const{dataChannel:r}=await this._handler.receiveDataChannel({sctpStreamParameters:o,label:n,protocol:i}),a=new tl.DataConsumer({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:o,appData:s});return this._dataConsumers.set(a.id,a),this.handleDataConsumer(a),this._observer.safeEmit("newdataconsumer",a),a}),"transport.consumeData()")}createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingConsumerTasks.length)return void rl.debug("createPendingConsumers() | there is no Consumer to be created");const e=[...this._pendingConsumerTasks];let t;this._pendingConsumerTasks=[];const r=[];for(const t of e){const{id:e,kind:n,rtpParameters:i,streamId:s,onRtpReceiver:o}=t.consumerOptions;r.push({trackId:e,kind:n,rtpParameters:i,streamId:s,onRtpReceiver:o})}try{const n=await this._handler.receive(r);for(let r=0;r<n.length;++r){const i=e[r],s=n[r],{id:o,producerId:a,kind:c,rtpParameters:d,appData:u}=i.consumerOptions,{localId:l,rtpReceiver:p,track:h}=s,f=new Xu.Consumer({id:o,localId:l,producerId:a,rtpReceiver:p,track:h,rtpParameters:d,appData:u});this._consumers.set(f.id,f),this.handleConsumer(f),this._probatorConsumerCreated||t||"video"!==c||(t=f),this._observer.safeEmit("newconsumer",f),i.resolve(f)}}catch(t){for(const r of e)r.reject(t)}if(t)try{const e=Qu.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:e}]),rl.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(e){rl.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",e)}}),"transport.createPendingConsumers()").then((()=>{this._consumerCreationInProgress=!1,this._pendingConsumerTasks.length>0&&this.createPendingConsumers()})).catch((()=>{}))}pausePendingConsumers(){this._consumerPauseInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingPauseConsumers.size)return void rl.debug("pausePendingConsumers() | there is no Consumer to be paused");const e=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{const t=e.map((e=>e.localId));await this._handler.pauseReceiving(t)}catch(e){rl.error("pausePendingConsumers() | failed to pause Consumers:",e)}}),"transport.pausePendingConsumers()").then((()=>{this._consumerPauseInProgress=!1,this._pendingPauseConsumers.size>0&&this.pausePendingConsumers()})).catch((()=>{}))}resumePendingConsumers(){this._consumerResumeInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingResumeConsumers.size)return void rl.debug("resumePendingConsumers() | there is no Consumer to be resumed");const e=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{const t=e.map((e=>e.localId));await this._handler.resumeReceiving(t)}catch(e){rl.error("resumePendingConsumers() | failed to resume Consumers:",e)}}),"transport.resumePendingConsumers()").then((()=>{this._consumerResumeInProgress=!1,this._pendingResumeConsumers.size>0&&this.resumePendingConsumers()})).catch((()=>{}))}closePendingConsumers(){this._consumerCloseInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingCloseConsumers.size)return void rl.debug("closePendingConsumers() | there is no Consumer to be closed");const e=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(e.map((e=>e.localId)))}catch(e){rl.error("closePendingConsumers() | failed to close Consumers:",e)}}),"transport.closePendingConsumers()").then((()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()})).catch((()=>{}))}handleHandler(){const e=this._handler;e.on("@connect",(({dtlsParameters:e},t,r)=>{this._closed?r(new Ku.InvalidStateError("closed")):this.safeEmit("connect",{dtlsParameters:e},t,r)})),e.on("@icegatheringstatechange",(e=>{e!==this._iceGatheringState&&(rl.debug("ICE gathering state changed to %s",e),this._iceGatheringState=e,this._closed||this.safeEmit("icegatheringstatechange",e))})),e.on("@icecandidateerror",(e=>{rl.warn(`ICE candidate error [url:${e.url}, localAddress:${e.address}, localPort:${e.port}]: ${e.errorCode} "${e.errorText}"`),this.safeEmit("icecandidateerror",e)})),e.on("@connectionstatechange",(e=>{e!==this._connectionState&&(rl.debug("connection state changed to %s",e),this._connectionState=e,this._closed||this.safeEmit("connectionstatechange",e))}))}handleProducer(e){e.on("@close",(()=>{this._producers.delete(e.id),this._closed||this._awaitQueue.push((async()=>await this._handler.stopSending(e.localId)),"producer @close event").catch((e=>rl.warn("producer.close() failed:%o",e)))})),e.on("@pause",((t,r)=>{this._awaitQueue.push((async()=>await this._handler.pauseSending(e.localId)),"producer @pause event").then(t).catch(r)})),e.on("@resume",((t,r)=>{this._awaitQueue.push((async()=>await this._handler.resumeSending(e.localId)),"producer @resume event").then(t).catch(r)})),e.on("@replacetrack",((t,r,n)=>{this._awaitQueue.push((async()=>await this._handler.replaceTrack(e.localId,t)),"producer @replacetrack event").then(r).catch(n)})),e.on("@setmaxspatiallayer",((t,r,n)=>{this._awaitQueue.push((async()=>await this._handler.setMaxSpatialLayer(e.localId,t)),"producer @setmaxspatiallayer event").then(r).catch(n)})),e.on("@setrtpencodingparameters",((t,r,n)=>{this._awaitQueue.push((async()=>await this._handler.setRtpEncodingParameters(e.localId,t)),"producer @setrtpencodingparameters event").then(r).catch(n)})),e.on("@getstats",((t,r)=>{if(this._closed)return r(new Ku.InvalidStateError("closed"));this._handler.getSenderStats(e.localId).then(t).catch(r)}))}handleConsumer(e){e.on("@close",(()=>{this._consumers.delete(e.id),this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.delete(e.id),this._closed||(this._pendingCloseConsumers.set(e.id,e),!1===this._consumerCloseInProgress&&this.closePendingConsumers())})),e.on("@pause",(()=>{this._pendingResumeConsumers.has(e.id)&&this._pendingResumeConsumers.delete(e.id),this._pendingPauseConsumers.set(e.id,e),queueMicrotask((()=>{this._closed||!1===this._consumerPauseInProgress&&this.pausePendingConsumers()}))})),e.on("@resume",(()=>{this._pendingPauseConsumers.has(e.id)&&this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.set(e.id,e),queueMicrotask((()=>{this._closed||!1===this._consumerResumeInProgress&&this.resumePendingConsumers()}))})),e.on("@getstats",((t,r)=>{if(this._closed)return r(new Ku.InvalidStateError("closed"));this._handler.getReceiverStats(e.localId).then(t).catch(r)}))}handleDataProducer(e){e.on("@close",(()=>{this._dataProducers.delete(e.id)}))}handleDataConsumer(e){e.on("@close",(()=>{this._dataConsumers.delete(e.id)}))}}vu.Transport=il;var sl={},ol={},al={},cl={exports:{}},dl=cl.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:/^(\w*) (\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:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s 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:"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"},{push:"msid",reg:/^msid:([\w-]+)(?: ([\w-]+))?/,names:["id","appdata"],format:"msid:%s %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",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{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":"",t+=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"},{push:"invalid",names:["value"]}]};Object.keys(dl).forEach((function(e){dl[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,n){var i=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:i&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:i?r[e.name]:r;!function(e,r,n,i){if(i&&!n)r[i]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(r[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},n=cl.exports,i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(i).forEach((function(e){var t=e[0],i=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(i))return r(c,o,i)}})),t.media=s,t};var s=function(e,r){var n=r.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&r.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 r=[],n=e.split(" ").map(t),i=0;i<n.length;i+=3)r.push({component:n[i],ip:n[i+1],port:n[i+2]});return r},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 r,n=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),n=!0),{scid:r,paused:n}}))}))}}(al);var ul=cl.exports,ll=/%[sdv%]/g,pl=function(e){var t=1,r=arguments,n=r.length;return e.replace(ll,(function(e){if(t>=n)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}}))},hl=function(e,t,r){var n=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var i=0;i<t.names.length;i+=1){var s=t.names[i];t.name?n.push(r[t.name][s]):n.push(r[t.names[i]])}else n.push(r[t.name]);return pl.apply(null,n)},fl=["v","o","s","i","u","e","p","c","b","t","r","z","a"],ml=["i","c","b","a"],gl=al,vl=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 r=t.outerOrder||fl,n=t.innerOrder||ml,i=[];return r.forEach((function(t){ul[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(hl(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(hl(t,r,e))}))}))})),e.media.forEach((function(e){i.push(hl("m",ul.m[0],e)),n.forEach((function(t){ul[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(hl(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(hl(t,r,e))}))}))}))})),i.join("\r\n")+"\r\n"},yl=cl.exports;ol.grammar=yl,ol.write=vl,ol.parse=gl.parse,ol.parseParams=gl.parseParams,ol.parseFmtpConfig=gl.parseFmtpConfig,ol.parsePayloads=gl.parsePayloads,ol.parseRemoteCandidates=gl.parseRemoteCandidates,ol.parseImageAttributes=gl.parseImageAttributes,ol.parseSimulcastStreamList=gl.parseSimulcastStreamList;var bl={};Object.defineProperty(bl,"__esModule",{value:!0}),bl.parse=function(e){const t=_l.exec(e??"");return t?{spatialLayers:Number(t[1]),temporalLayers:Number(t[2])}:{spatialLayers:1,temporalLayers:1}};const _l=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");var El={},wl={};Object.defineProperty(wl,"__esModule",{value:!0}),wl.OfferMediaSection=wl.AnswerMediaSection=wl.MediaSection=void 0;const Sl=ol,Cl=Ld;class Tl{_mediaObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r}){if(this._mediaObject={type:"",port:0,protocol:"",payloads:"",rtp:[],fmtp:[]},e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(const e of t){const t={foundation:e.foundation,component:1,ip:e.address??e.ip,port:e.port,priority:e.priority,transport:e.protocol,type:e.type};e.tcpType&&(t.tcptype=e.tcpType),this._mediaObject.candidates.push(t)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}r&&this.setDtlsRole(r.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return 0===this._mediaObject.port}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause()}close(){this.disable(),this._mediaObject.port=0,delete this._mediaObject.candidates,delete this._mediaObject.endOfCandidates,delete this._mediaObject.iceUfrag,delete this._mediaObject.icePwd,delete this._mediaObject.iceOptions,this._mediaObject.rtp=[],this._mediaObject.fmtp=[],delete this._mediaObject.rtcp,delete this._mediaObject.rtcpFb,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}}wl.MediaSection=Tl;wl.AnswerMediaSection=class extends Tl{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,offerMediaObject:s,offerRtpParameters:o,answerRtpParameters:a,codecOptions:c}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(s.mid),this._mediaObject.type=s.type,this._mediaObject.protocol=s.protocol,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),s.type){case"audio":case"video":this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(const e of a.codecs){const t={payload:e.payloadType,codec:Pl(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r=Cl.clone(e.parameters)??{};let n=Cl.clone(e.rtcpFeedback)??[];if(c){const{opusStereo:t,opusFec:i,opusDtx:s,opusMaxPlaybackRate:a,opusMaxAverageBitrate:d,opusPtime:u,opusNack:l,videoGoogleStartBitrate:p,videoGoogleMaxBitrate:h,videoGoogleMinBitrate:f}=c,m=o.codecs.find((t=>t.payloadType===e.payloadType));switch(e.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":void 0!==t&&(m.parameters["sprop-stereo"]=t?1:0,r.stereo=t?1:0),void 0!==i&&(m.parameters.useinbandfec=i?1:0,r.useinbandfec=i?1:0),void 0!==s&&(m.parameters.usedtx=s?1:0,r.usedtx=s?1:0),void 0!==a&&(r.maxplaybackrate=a),void 0!==d&&(r.maxaveragebitrate=d),void 0!==u&&(m.parameters.ptime=u,r.ptime=u),l||(m.rtcpFeedback=m.rtcpFeedback.filter((e=>"nack"!==e.type||e.parameter)),n=n.filter((e=>"nack"!==e.type||e.parameter)));break;case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":case"video/av1":void 0!==p&&(r["x-google-start-bitrate"]=p),void 0!==h&&(r["x-google-max-bitrate"]=h),void 0!==f&&(r["x-google-min-bitrate"]=f)}}const i={payload:e.payloadType,config:""};for(const e of Object.keys(r))i.config&&(i.config+=";"),i.config+=`${e}=${r[e]}`;i.config&&this._mediaObject.fmtp.push(i);for(const t of n)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=a.codecs.map((e=>e.payloadType)).join(" "),this._mediaObject.ext=[];for(const e of a.headerExtensions){(s.ext??[]).some((t=>t.uri===e.uri))&&this._mediaObject.ext.push({uri:e.uri,value:e.id})}if("extmap-allow-mixed"===s.extmapAllowMixed&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),s.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:s.simulcast.list1},this._mediaObject.rids=[];for(const e of s.rids??[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}else if(s.simulcast_03){this._mediaObject.simulcast_03={value:s.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(const e of s.rids??[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";break;case"application":"number"==typeof s.sctpPort?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize):s.sctpmap&&(this._mediaObject.payloads=String(n.port),this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:n.port,maxMessageSize:n.maxMessageSize})}}setDtlsRole(e){switch(e){case"client":this._mediaObject.setup="active";break;case"server":this._mediaObject.setup="passive";break;case"auto":this._mediaObject.setup="actpass"}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(e){if(!this._mediaObject.simulcast?.list1)return;const t={};for(const r of e)r.rid&&(t[r.rid]=r);const r=this._mediaObject.simulcast.list1,n=Sl.parseSimulcastStreamList(r);for(const e of n)for(const r of e)r.paused=!t[r.scid]?.active;this._mediaObject.simulcast.list1=n.map((e=>e.map((e=>`${e.paused?"~":""}${e.scid}`)).join(","))).join(";")}};function Pl(e){const t=new RegExp("^(audio|video)/(.+)","i").exec(e.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}wl.OfferMediaSection=class extends Tl{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,mid:s,kind:o,offerRtpParameters:a,streamId:c,trackId:d}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(s),this._mediaObject.type=o,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.protocol=n?"UDP/DTLS/SCTP":"UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",o){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=[{id:c,appdata:d}];for(const e of a.codecs){const t={payload:e.payloadType,codec:Pl(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r={payload:e.payloadType,config:""};for(const t of Object.keys(e.parameters??{}))r.config&&(r.config+=";"),r.config+=`${t}=${e.parameters[t]}`;r.config&&this._mediaObject.fmtp.push(r);for(const t of e.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=a.codecs.map((e=>e.payloadType)).join(" "),this._mediaObject.ext=[];for(const e of a.headerExtensions)this._mediaObject.ext.push({uri:e.uri,value:e.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";const e=a.encodings[0],t=e.ssrc,r=e.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],t&&a.rtcp.cname&&this._mediaObject.ssrcs.push({id:t,attribute:"cname",value:a.rtcp.cname}),r&&(a.rtcp.cname&&this._mediaObject.ssrcs.push({id:r,attribute:"cname",value:a.rtcp.cname}),t&&this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${t} ${r}`}));break}case"application":this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}},Object.defineProperty(El,"__esModule",{value:!0}),El.RemoteSdp=void 0;const Rl=ol,kl=wl,Dl=fd,Il=["av1","h264"],Al=new Td.Logger("RemoteSdp");El.RemoteSdp=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i}){if(this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=r,this._sctpParameters=n,this._plainRtpParameters=i,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:`mediasoup-client-v${Dl.version}`},name:"-",timing:{start:0,stop:0},media:[]},this._sdpObject.iceOptions="ice2",e?.iceLite&&(this._sdpObject.icelite="ice-lite"),r){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};const e=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:r.fingerprints[e-1].algorithm,hash:r.fingerprints[e-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){Al.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(const t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){Al.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(const t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){Al.debug("setSessionExtmapAllowMixed()"),this._sdpObject.extmapAllowMixed="extmap-allow-mixed"}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){const t=this._mediaSections[e];if(t.closed)return{idx:e,reuseMid:t.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:e,reuseMid:t,offerRtpParameters:r,answerRtpParameters:n,codecOptions:i}){const s=new kl.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e,offerRtpParameters:r,answerRtpParameters:n,codecOptions:i}),o=s.getObject();o.rtp.find((e=>Il.includes(e.codec.toLowerCase())))||(o.ext=o.ext?.filter((e=>"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"!==e.uri))),t?this.replaceMediaSection(s,t):this._midToIndex.has(s.mid)?this.replaceMediaSection(s):this.addMediaSection(s)}receive({mid:e,kind:t,offerRtpParameters:r,streamId:n,trackId:i}){this.setSessionExtmapAllowMixed();const s=new kl.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,mid:e,kind:t,offerRtpParameters:r,streamId:n,trackId:i}),o=this._mediaSections.find((e=>e.closed&&e.getObject().type===t));o?this.replaceMediaSection(s,o.mid):this.addMediaSection(s)}pauseMediaSection(e){this.findMediaSection(e).pause()}resumeSendingMediaSection(e){this.findMediaSection(e).resume()}resumeReceivingMediaSection(e){this.findMediaSection(e).resume()}disableMediaSection(e){this.findMediaSection(e).disable()}closeMediaSection(e){const t=this.findMediaSection(e);return e===this._firstMid?(Al.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",e),this.disableMediaSection(e),!1):(t.close(),this.regenerateBundleMids(),!0)}muxMediaSectionSimulcast(e,t){const r=this.findMediaSection(e);r.muxSimulcastStreams(t),this.replaceMediaSection(r)}sendSctpAssociation({offerMediaObject:e}){const t=new kl.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this.addMediaSection(t)}receiveSctpAssociation(){const e=new kl.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application"});this.addMediaSection(e)}getSdp(){return this._sdpObject.origin.sessionVersion++,Rl.write(this._sdpObject)}addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this.regenerateBundleMids()}replaceMediaSection(e,t){if("string"==typeof t){const r=this._midToIndex.get(t);if(void 0===r)throw new Error(`no media section found for reuseMid '${t}'`);const n=this._mediaSections[r];this._mediaSections[r]=e,this._midToIndex.delete(n.mid),this._midToIndex.set(e.mid,r),this._sdpObject.media[r]=e.getObject(),this.regenerateBundleMids()}else{const t=this._midToIndex.get(e.mid);if(void 0===t)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[t]=e,this._sdpObject.media[t]=e.getObject()}}findMediaSection(e){const t=this._midToIndex.get(e);if(void 0===t)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter((e=>!e.closed)).map((e=>e.mid)).join(" "))}};var Ol={};Object.defineProperty(Ol,"__esModule",{value:!0}),Ol.extractRtpCapabilities=function({sdpObject:e}){const t=new Map,r=new Map;for(const n of e.media){const e=n.type;switch(e){case"audio":case"video":break;default:continue}for(const r of n.rtp){const n={kind:e,mimeType:`${e}/${r.codec}`,preferredPayloadType:r.payload,clockRate:r.rate,channels:r.encoding,parameters:{},rtcpFeedback:[]};t.set(n.preferredPayloadType,n)}for(const e of n.fmtp??[]){const r=Ml.parseParams(e.config),n=t.get(e.payload);n&&(r?.hasOwnProperty("profile-level-id")&&(r["profile-level-id"]=String(r["profile-level-id"])),n.parameters=r)}for(const r of n.rtcpFb??[]){const n={type:r.type,parameter:r.subtype};if(n.parameter||delete n.parameter,"*"!==r.payload){const e=t.get(Number(r.payload));if(!e)continue;e.rtcpFeedback.push(n)}else for(const r of t.values())r.kind!==e||/.+\/rtx$/i.test(r.mimeType)||r.rtcpFeedback.push(n)}for(const t of n.ext??[]){if(t["encrypt-uri"])continue;const n={kind:e,uri:t.uri,preferredId:t.value};r.set(n.preferredId,n)}}return{codecs:Array.from(t.values()),headerExtensions:Array.from(r.values())}},Ol.extractDtlsParameters=function({sdpObject:e}){let t,r=e.setup,n=e.fingerprint;if(!r||!n){const t=(e.media??[]).find((e=>0!==e.port));t&&(r=r??t.setup,n=n??t.fingerprint)}if(!r)throw new Error("no a=setup found at SDP session or media level");if(!n)throw new Error("no a=fingerprint found at SDP session or media level");switch(r){case"active":t="client";break;case"passive":t="server";break;case"actpass":t="auto"}return{role:t,fingerprints:[{algorithm:n.type,value:n.hash}]}},Ol.getCname=function({offerMediaObject:e}){const t=(e.ssrcs??[]).find((e=>"cname"===e.attribute));if(!t)return"";return t.value},Ol.applyCodecParameters=function({offerRtpParameters:e,answerMediaObject:t}){for(const r of e.codecs){const e=r.mimeType.toLowerCase();if("audio/opus"!==e)continue;const n=(t.rtp??[]).find((e=>e.payload===r.payloadType));if(!n)continue;t.fmtp=t.fmtp??[];let i=t.fmtp.find((e=>e.payload===r.payloadType));i||(i={payload:r.payloadType,config:""},t.fmtp.push(i));const s=Ml.parseParams(i.config);switch(e){case"audio/opus":{const e=r.parameters?.["sprop-stereo"];void 0!==e&&(s.stereo=Number(e)?1:0);break}}i.config="";for(const e of Object.keys(s))i.config&&(i.config+=";"),i.config+=`${e}=${s[e]}`}},Ol.addHeaderExtension=function({offerMediaObject:e,headerExtensionUri:t,headerExtensionId:r}){e.ext||(e.ext=[]);e.ext.push({uri:t,value:r})};const Ml=ol;var Nl={};Object.defineProperty(Nl,"__esModule",{value:!0}),Nl.getRtpEncodings=function({offerMediaObject:e,codecs:t}){const r=new Set;for(const t of e.ssrcs??[]){const e=t.id;e&&r.add(e)}if(0===r.size)throw new Error("no a=ssrc lines found");const n=new Map;for(const t of e.ssrcGroups??[]){if("FID"!==t.semantics)continue;const e=t.ssrcs.split(/\s+/),i=Number(e[0]),s=Number(e[1]);r.has(i)&&(r.delete(i),r.delete(s),n.set(i,s))}for(const e of r)n.set(e,void 0);const i=[];for(const[e,r]of n){const n={ssrc:e};r&&t.length>1&&(n.rtx={ssrc:r}),i.push(n)}return i},Nl.addLegacySimulcast=function({offerMediaObject:e,numStreams:t}){if(t<=1)throw new TypeError("numStreams must be greater than 1");const r=(e.ssrcs??[]).find((e=>"msid"===e.attribute));if(!r)throw new Error("a=ssrc line with msid information not found");const[n,i]=r.value.split(" "),s=Number(r.id);let o;(e.ssrcGroups??[]).some((e=>{if("FID"!==e.semantics)return!1;const t=e.ssrcs.split(/\s+/);return Number(t[0])===s&&(o=Number(t[1]),!0)}));const a=(e.ssrcs??[]).find((e=>"cname"===e.attribute));if(!a)throw new Error("a=ssrc line with cname information not found");const c=a.value,d=[],u=[];for(let e=0;e<t;++e)d.push(s+e),o&&u.push(o+e);e.ssrcGroups=[],e.ssrcs=[],e.ssrcGroups.push({semantics:"SIM",ssrcs:d.join(" ")});for(const t of d)e.ssrcs.push({id:t,attribute:"cname",value:c}),e.ssrcs.push({id:t,attribute:"msid",value:`${n} ${i}`});for(let t=0;t<u.length;++t){const r=d[t],s=u[t];e.ssrcs.push({id:s,attribute:"cname",value:c}),e.ssrcs.push({id:s,attribute:"msid",value:`${n} ${i}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${r} ${s}`})}};var Ll={};Object.defineProperty(Ll,"__esModule",{value:!0}),Ll.addNackSupportForOpus=function(e){for(const t of e.codecs??[])"audio/opus"!==t.mimeType.toLowerCase()&&"audio/multiopus"!==t.mimeType.toLowerCase()||t.rtcpFeedback?.some((e=>"nack"===e.type&&!e.parameter))||(t.rtcpFeedback||(t.rtcpFeedback=[]),t.rtcpFeedback.push({type:"nack"}))},Ll.addHeaderExtensionSupport=function(e,t){let r;const n=e.headerExtensions?.find((e=>e.uri===t.uri));if(n){if(n.kind===t.kind)return;r=n.preferredId}e.headerExtensions||(e.headerExtensions=[]);if(void 0===r){r=1;const t=new Set(e.headerExtensions.map((e=>e.preferredId)));for(;t.has(r);)++r}const i={kind:t.kind,uri:t.uri,preferredId:r,preferredEncrypt:!1,direction:t.direction};e.headerExtensions.push(i)},Ll.getMsidStreamIdAndTrackId=function(e){if(!e||"string"!=typeof e)return{msidStreamId:void 0,msidTrackId:void 0};const[t,r]=e.trim().split(/\s+/);if(!t)return{msidStreamId:void 0,msidTrackId:void 0};return{msidStreamId:t,msidTrackId:r}},Object.defineProperty(sl,"__esModule",{value:!0}),sl.Chrome111=void 0;const xl=ol,Fl=kd,jl=xd,Ul=Od,Vl=bl,Bl=El,Wl=Ol,Hl=Nl,ql=Ll,zl=new Td.Logger("Chrome111"),Gl={OS:65535,MIS:65535};class Yl extends Fl.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:"Chrome111",factory:e=>new Yl(e),getNativeRtpCapabilities:async({direction:e})=>{zl.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e,sendEncodings:[{scalabilityMode:"L3T3"}]});const r=await t.createOffer();try{t.close()}catch(e){}t=void 0;const n=xl.parse(r.sdp);return Yl.getLocalRtpCapabilities(n)}catch(e){try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(zl.debug("getNativeSctpCapabilities()"),{numStreams:Gl})}}static getLocalRtpCapabilities(e,t=[]){const r=Wl.extractRtpCapabilities({sdpObject:e});jl.validateAndNormalizeRtpCapabilities(r),ql.addNackSupportForOpus(r);for(const e of t)ql.addHeaderExtensionSupport(r,e);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),zl.debug("constructor()"),this._direction=e,this._remoteSdp=new Bl.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(zl.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Chrome111"}close(){if(zl.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch(e){}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),zl.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),zl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});zl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};zl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};zl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();zl.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s,onRtpSender:o}){if(this.assertNotClosed(),this.assertSendDirection(),zl.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1){let e=1;for(const t of r){const r=t.scalabilityMode?(0,Vl.parse)(t.scalabilityMode).temporalLayers:3;r>e&&(e=r)}r.forEach(((t,r)=>{t.rid=`r${r}`,t.scalabilityMode=`L1T${e}`}))}const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});o&&o(c.sender);let d=await this._pc.createOffer(),u=xl.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const l=[];l.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});const p=Yl.getLocalRtpCapabilities(u,l),h=this._getSendExtendedRtpCapabilities(p),f=jl.getSendingRtpParameters(e.kind,h);f.codecs=jl.reduceCodecs(f.codecs,s);const m=jl.getSendingRemoteRtpParameters(e.kind,h);if(m.codecs=jl.reduceCodecs(m.codecs,s),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u}),i?.absCaptureTime){const e=u.media[a.idx];Wl.addHeaderExtension({offerMediaObject:e,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"===e.uri)).id}),d={type:"offer",sdp:xl.write(u)}}zl.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const g=c.mid;f.mid=g,u=xl.parse(this._pc.localDescription.sdp);const v=u.media[a.idx];if(f.rtcp.cname=Wl.getCname({offerMediaObject:v}),f.msid=`${t??this._sendStream.id} ${e.id}`,r)if(1===r.length){const e=Hl.getRtpEncodings({offerMediaObject:v,codecs:f.codecs});Object.assign(e[0],r[0]),f.encodings=e}else f.encodings=r;else f.encodings=Hl.getRtpEncodings({offerMediaObject:v,codecs:f.codecs});this._remoteSdp.send({offerMediaObject:v,reuseMid:a.reuseMid,offerRtpParameters:f,answerRtpParameters:m,codecOptions:n});const y={type:"answer",sdp:this._remoteSdp.getSdp()};return zl.debug("send() | calling pc.setRemoteDescription() [answer:%o]",y),await this._pc.setRemoteDescription(y),this._mapMidTransceiver.set(g,c),{localId:g,rtpParameters:f,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),zl.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();zl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};zl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),zl.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();zl.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};zl.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),zl.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();zl.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};zl.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?zl.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):zl.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),zl.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();zl.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};zl.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),zl.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();zl.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};zl.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};zl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Gl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=xl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),zl.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};zl.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;zl.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=ql.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};zl.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=xl.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));Wl.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:xl.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),zl.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){zl.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};zl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();zl.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){zl.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};zl.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();zl.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){zl.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};zl.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();zl.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};zl.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};zl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=xl.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}zl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=xl.parse(this._pc.localDescription.sdp));const r=Wl.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}};assertNotClosed(){if(this._closed)throw new Ul.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}sl.Chrome111=Yl;var $l={};Object.defineProperty($l,"__esModule",{value:!0}),$l.Chrome74=void 0;const Kl=ol,Jl=kd,Ql=xd,Zl=Od,Xl=bl,ep=El,tp=Ol,rp=Nl,np=Ll,ip=new Td.Logger("Chrome74"),sp={OS:1024,MIS:1024};class op extends Jl.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:"Chrome74",factory:e=>new op(e),getNativeRtpCapabilities:async({direction:e})=>{ip.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});const r=await t.createOffer();try{t.close()}catch(e){}t=void 0;const n=Kl.parse(r.sdp);return op.getLocalRtpCapabilities(n)}catch(e){try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(ip.debug("getNativeSctpCapabilities()"),{numStreams:sp})}}static getLocalRtpCapabilities(e,t=[]){const r=tp.extractRtpCapabilities({sdpObject:e});Ql.validateAndNormalizeRtpCapabilities(r),np.addNackSupportForOpus(r);for(const e of t)np.addHeaderExtensionSupport(r,e);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),ip.debug("constructor()"),this._direction=e,this._remoteSdp=new ep.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(ip.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Chrome74"}close(){if(ip.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch(e){}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),ip.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),ip.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});ip.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};ip.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};ip.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();ip.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s}){this.assertNotClosed(),this.assertSendDirection(),ip.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach(((e,t)=>{e.rid=`r${t}`}));const o=this._remoteSdp.getNextMediaSectionIdx(),a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});let c=await this._pc.createOffer(),d=Kl.parse(c.sdp);d.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const u=[];u.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});const l=op.getLocalRtpCapabilities(d,u),p=this._getSendExtendedRtpCapabilities(l),h=Ql.getSendingRtpParameters(e.kind,p);h.codecs=Ql.reduceCodecs(h.codecs,s);const f=Ql.getSendingRemoteRtpParameters(e.kind,p);f.codecs=Ql.reduceCodecs(f.codecs,s),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:d});let m=!1;const g=(0,Xl.parse)((r??[{}])[0].scalabilityMode);let v;1===r?.length&&g.spatialLayers>1&&"video/vp9"===h.codecs[0].mimeType.toLowerCase()&&(ip.debug("send() | enabling legacy simulcast for VP9 SVC"),m=!0,d=Kl.parse(c.sdp),v=d.media[o.idx],rp.addLegacySimulcast({offerMediaObject:v,numStreams:g.spatialLayers}),c={type:"offer",sdp:Kl.write(d)}),ip.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),i?.absCaptureTime&&(v=d.media[o.idx],tp.addHeaderExtension({offerMediaObject:v,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:f.headerExtensions.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"===e.uri)).id}),c={type:"offer",sdp:Kl.write(d)}),await this._pc.setLocalDescription(c);const y=a.mid;if(h.mid=y,d=Kl.parse(this._pc.localDescription.sdp),v=d.media[o.idx],h.rtcp.cname=tp.getCname({offerMediaObject:v}),h.msid=`${t??this._sendStream.id} ${e.id}`,r)if(1===r.length){let e=rp.getRtpEncodings({offerMediaObject:v,codecs:h.codecs});Object.assign(e[0],r[0]),m&&(e=[e[0]]),h.encodings=e}else h.encodings=r;else h.encodings=rp.getRtpEncodings({offerMediaObject:v,codecs:h.codecs});if(h.encodings.length>1&&("video/vp8"===h.codecs[0].mimeType.toLowerCase()||"video/h264"===h.codecs[0].mimeType.toLowerCase()))for(const e of h.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${g.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:v,reuseMid:o.reuseMid,offerRtpParameters:h,answerRtpParameters:f,codecOptions:n});const b={type:"answer",sdp:this._remoteSdp.getSdp()};return ip.debug("send() | calling pc.setRemoteDescription() [answer:%o]",b),await this._pc.setRemoteDescription(b),this._mapMidTransceiver.set(y,a),{localId:y,rtpParameters:h,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),ip.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();ip.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};ip.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),ip.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();ip.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};ip.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),ip.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();ip.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};ip.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?ip.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):ip.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),ip.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();ip.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};ip.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),ip.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();ip.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};ip.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};ip.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%sp.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Kl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),ip.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};ip.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;ip.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=np.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};ip.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer();const s=Kl.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));tp.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Kl.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),ip.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){ip.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};ip.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ip.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){ip.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};ip.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ip.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){ip.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};ip.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ip.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};ip.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};ip.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Kl.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}ip.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Kl.parse(this._pc.localDescription.sdp));const r=tp.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}};assertNotClosed(){if(this._closed)throw new Zl.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}$l.Chrome74=op;var ap={};Object.defineProperty(ap,"__esModule",{value:!0}),ap.Firefox120=void 0;const cp=ol,dp=kd,up=Od,lp=xd,pp=bl,hp=El,fp=Ol,mp=Nl,gp=Ll,vp=new Td.Logger("Firefox120"),yp={OS:16,MIS:2048};class bp extends dp.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:"Firefox120",factory:e=>new bp(e),getNativeRtpCapabilities:async({direction:e})=>{vp.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});const r=document.createElement("canvas");r.getContext("2d");const n=r.captureStream().getVideoTracks()[0];try{t.addTransceiver("audio",{direction:e}),t.addTransceiver(n,{direction:e,sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});const i=await t.createOffer();try{r.remove()}catch(e){}try{n.stop()}catch(e){}try{t.close()}catch(e){}t=void 0;const s=cp.parse(i.sdp);return bp.getLocalRtpCapabilities(s)}catch(e){try{r.remove()}catch(e){}try{n.stop()}catch(e){}try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(vp.debug("getNativeSctpCapabilities()"),{numStreams:yp})}}static getLocalRtpCapabilities(e){const t=fp.extractRtpCapabilities({sdpObject:e});return lp.validateAndNormalizeRtpCapabilities(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),vp.debug("constructor()"),this._direction=e,this._remoteSdp=new hp.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(vp.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Firefox120"}close(){if(vp.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch(e){}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){throw this.assertNotClosed(),new up.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),vp.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});vp.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};vp.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};vp.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();vp.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,codec:i,onRtpSender:s}){this.assertNotClosed(),this.assertSendDirection(),vp.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach(((e,t)=>{e.rid=`r${t}`}));const o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});s&&s(o.sender);const a=await this._pc.createOffer();let c=cp.parse(a.sdp);c.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const d=bp.getLocalRtpCapabilities(c),u=this._getSendExtendedRtpCapabilities(d),l=lp.getSendingRtpParameters(e.kind,u);l.codecs=lp.reduceCodecs(l.codecs,i);const p=lp.getSendingRemoteRtpParameters(e.kind,u);p.codecs=lp.reduceCodecs(p.codecs,i),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:c});const h=(0,pp.parse)((r??[{}])[0].scalabilityMode);vp.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const f=o.mid;l.mid=f,c=cp.parse(this._pc.localDescription.sdp);const m=c.media[c.media.length-1];if(l.rtcp.cname=fp.getCname({offerMediaObject:m}),l.msid=`${t??this._sendStream.id} ${e.id}`,r)if(1===r.length){const e=mp.getRtpEncodings({offerMediaObject:m,codecs:l.codecs});Object.assign(e[0],r[0]),l.encodings=e}else l.encodings=r;else l.encodings=mp.getRtpEncodings({offerMediaObject:m,codecs:l.codecs});if(l.encodings.length>1&&("video/vp8"===l.codecs[0].mimeType.toLowerCase()||"video/h264"===l.codecs[0].mimeType.toLowerCase()))for(const e of l.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${h.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:m,offerRtpParameters:l,answerRtpParameters:p,codecOptions:n});const g={type:"answer",sdp:this._remoteSdp.getSdp()};return vp.debug("send() | calling pc.setRemoteDescription() [answer:%o]",g),await this._pc.setRemoteDescription(g),this._mapMidTransceiver.set(f,o),{localId:f,rtpParameters:l,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),vp.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);const r=await this._pc.createOffer();vp.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};vp.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),vp.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();vp.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};vp.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),vp.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();vp.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};vp.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?vp.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):vp.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),vp.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();vp.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};vp.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),vp.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();vp.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};vp.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};vp.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%yp.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=cp.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),vp.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};vp.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;vp.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=gp.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};vp.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=cp.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,o=r.get(e),a=s.media.find((e=>String(e.mid)===o));fp.applyCodecParameters({offerRtpParameters:n,answerMediaObject:a}),i={type:"answer",sdp:cp.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),vp.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){vp.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};vp.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();vp.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){vp.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};vp.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();vp.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){vp.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};vp.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();vp.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};vp.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};vp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=cp.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}vp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=cp.parse(this._pc.localDescription.sdp));const r=fp.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}};assertNotClosed(){if(this._closed)throw new up.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}ap.Firefox120=bp;var _p={};Object.defineProperty(_p,"__esModule",{value:!0}),_p.Safari12=void 0;const Ep=ol,wp=kd,Sp=xd,Cp=Od,Tp=bl,Pp=El,Rp=Ol,kp=Nl,Dp=Ll,Ip=new Td.Logger("Safari12"),Ap={OS:65535,MIS:65535};class Op extends wp.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:"Safari12",factory:e=>new Op(e),getNativeRtpCapabilities:async({direction:e})=>{Ip.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});const r=await t.createOffer();try{t.close()}catch(e){}t=void 0;const n=Ep.parse(r.sdp);return Op.getLocalRtpCapabilities(n)}catch(e){try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(Ip.debug("getNativeSctpCapabilities()"),{numStreams:Ap})}}static getLocalRtpCapabilities(e,t=[]){const r=Rp.extractRtpCapabilities({sdpObject:e});Sp.validateAndNormalizeRtpCapabilities(r),Dp.addNackSupportForOpus(r);for(const e of t)Dp.addHeaderExtensionSupport(r,e);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Ip.debug("constructor()"),this._direction=e,this._remoteSdp=new Pp.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",(()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)})),this._pc.addEventListener("icecandidateerror",(e=>{this.emit("@icecandidateerror",e)})),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(Ip.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Safari12"}close(){if(Ip.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch(e){}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),Ip.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Ip.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Ip.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Ip.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Ip.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Ip.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s,onRtpSender:o}){this.assertNotClosed(),this.assertSendDirection(),Ip.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});o&&o(c.sender);let d=await this._pc.createOffer(),u=Ep.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const l=[];l.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});const p=Op.getLocalRtpCapabilities(u,l),h=this._getSendExtendedRtpCapabilities(p),f=Sp.getSendingRtpParameters(e.kind,h);f.codecs=Sp.reduceCodecs(f.codecs,s);const m=Sp.getSendingRemoteRtpParameters(e.kind,h);let g;m.codecs=Sp.reduceCodecs(m.codecs,s),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});const v=(0,Tp.parse)((r??[{}])[0].scalabilityMode);r&&r.length>1&&(Ip.debug("send() | enabling legacy simulcast"),u=Ep.parse(d.sdp),g=u.media[a.idx],kp.addLegacySimulcast({offerMediaObject:g,numStreams:r.length}),d={type:"offer",sdp:Ep.write(u)}),i?.absCaptureTime&&(g=u.media[a.idx],Rp.addHeaderExtension({offerMediaObject:g,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"===e.uri)).id}),d={type:"offer",sdp:Ep.write(u)}),Ip.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const y=c.mid;if(f.mid=y,u=Ep.parse(this._pc.localDescription.sdp),g=u.media[a.idx],f.rtcp.cname=Rp.getCname({offerMediaObject:g}),f.msid=`${t??this._sendStream.id} ${e.id}`,f.encodings=kp.getRtpEncodings({offerMediaObject:g,codecs:f.codecs}),r)for(let e=0;e<f.encodings.length;++e)r[e]&&Object.assign(f.encodings[e],r[e]);if(f.encodings.length>1&&("video/vp8"===f.codecs[0].mimeType.toLowerCase()||"video/h264"===f.codecs[0].mimeType.toLowerCase()))for(const e of f.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${v.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:g,reuseMid:a.reuseMid,offerRtpParameters:f,answerRtpParameters:m,codecOptions:n});const b={type:"answer",sdp:this._remoteSdp.getSdp()};return Ip.debug("send() | calling pc.setRemoteDescription() [answer:%o]",b),await this._pc.setRemoteDescription(b),this._mapMidTransceiver.set(y,c),{localId:y,rtpParameters:f,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Ip.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Ip.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Ip.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Ip.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Ip.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Ip.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Ip.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();Ip.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Ip.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Ip.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Ip.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Ip.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Ip.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Ip.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Ip.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Ip.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Ip.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};Ip.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Ap.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Ep.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Ip.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Ip.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;Ip.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=Dp.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Ip.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=Ep.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));Rp.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Ep.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Ip.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Ip.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Ip.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Ip.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Ip.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Ip.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Ip.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Ip.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Ip.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Ip.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Ip.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Ip.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Ep.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Ip.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Ep.parse(this._pc.localDescription.sdp));const r=Rp.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}};assertNotClosed(){if(this._closed)throw new Cp.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}_p.Safari12=Op;var Mp={};Object.defineProperty(Mp,"__esModule",{value:!0}),Mp.ReactNative106=void 0;const Np=ol,Lp=kd,xp=xd,Fp=Od,jp=bl,Up=El,Vp=Ol,Bp=Nl,Wp=Ll,Hp=new Td.Logger("ReactNative106"),qp={OS:65535,MIS:65535};class zp extends Lp.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:"ReactNative106",factory:e=>new zp(e),getNativeRtpCapabilities:async({direction:e})=>{Hp.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});const r=await t.createOffer();try{t.close()}catch(e){}t=void 0;const n=Np.parse(r.sdp);return zp.getLocalRtpCapabilities(n)}catch(e){try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(Hp.debug("getNativeSctpCapabilities()"),{numStreams:qp})}}static getLocalRtpCapabilities(e,t=[]){const r=Vp.extractRtpCapabilities({sdpObject:e});xp.validateAndNormalizeRtpCapabilities(r),Wp.addNackSupportForOpus(r);for(const e of t)Wp.addHeaderExtensionSupport(r,e);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Hp.debug("constructor()"),this._direction=e,this._remoteSdp=new Up.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(Hp.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"ReactNative106"}close(){if(Hp.debug("close()"),!this._closed){this._closed=!0,this._sendStream.release(!1);try{this._pc.close()}catch(e){}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),Hp.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Hp.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Hp.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Hp.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Hp.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Hp.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s,onRtpSender:o}){this.assertNotClosed(),this.assertSendDirection(),Hp.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach(((e,t)=>{e.rid=`r${t}`}));const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});o&&o(c.sender);let d=await this._pc.createOffer(),u=Np.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const l=[];l.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});const p=zp.getLocalRtpCapabilities(u,l),h=this._getSendExtendedRtpCapabilities(p),f=xp.getSendingRtpParameters(e.kind,h);f.codecs=xp.reduceCodecs(f.codecs,s);const m=xp.getSendingRemoteRtpParameters(e.kind,h);m.codecs=xp.reduceCodecs(m.codecs,s),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let g=!1;const v=(0,jp.parse)((r??[{}])[0].scalabilityMode);let y;1===r?.length&&v.spatialLayers>1&&"video/vp9"===f.codecs[0].mimeType.toLowerCase()&&(Hp.debug("send() | enabling legacy simulcast for VP9 SVC"),g=!0,u=Np.parse(d.sdp),y=u.media[a.idx],Bp.addLegacySimulcast({offerMediaObject:y,numStreams:v.spatialLayers}),d={type:"offer",sdp:Np.write(u)}),i?.absCaptureTime&&(y=u.media[a.idx],Vp.addHeaderExtension({offerMediaObject:y,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"===e.uri)).id}),d={type:"offer",sdp:Np.write(u)}),Hp.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);let b=c.mid??void 0;if(b||Hp.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),f.mid=b,u=Np.parse(this._pc.localDescription.sdp),y=u.media[a.idx],f.rtcp.cname=Vp.getCname({offerMediaObject:y}),f.msid=`${t??this._sendStream.id} ${e.id}`,r)if(1===r.length){let e=Bp.getRtpEncodings({offerMediaObject:y,codecs:f.codecs});Object.assign(e[0],r[0]),g&&(e=[e[0]]),f.encodings=e}else f.encodings=r;else f.encodings=Bp.getRtpEncodings({offerMediaObject:y,codecs:f.codecs});if(f.encodings.length>1&&("video/vp8"===f.codecs[0].mimeType.toLowerCase()||"video/h264"===f.codecs[0].mimeType.toLowerCase()))for(const e of f.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${v.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:y,reuseMid:a.reuseMid,offerRtpParameters:f,answerRtpParameters:m,codecOptions:n});const _={type:"answer",sdp:this._remoteSdp.getSdp()};return Hp.debug("send() | calling pc.setRemoteDescription() [answer:%o]",_),await this._pc.setRemoteDescription(_),b||(b=c.mid,f.mid=b),this._mapMidTransceiver.set(b,c),{localId:b,rtpParameters:f,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Hp.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Hp.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Hp.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Hp.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Hp.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Hp.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Hp.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();Hp.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Hp.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Hp.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Hp.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Hp.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Hp.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Hp.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Hp.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Hp.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Hp.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};Hp.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%qp.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Np.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Hp.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Hp.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;Hp.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=Wp.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Hp.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=Np.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));Vp.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Np.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Hp.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Hp.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hp.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hp.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Hp.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hp.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hp.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Hp.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hp.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hp.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Hp.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Hp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Np.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Hp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Np.parse(this._pc.localDescription.sdp));const r=Vp.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)})),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}};assertNotClosed(){if(this._closed)throw new Fp.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Mp.ReactNative106=zp,Object.defineProperty(Cd,"__esModule",{value:!0}),Cd.Device=void 0,Cd.detectDevice=nh,Cd.detectDeviceAsync=ih;const Gp=kd,Yp=Od,$p=Ld,Kp=xd,Jp=vu,Qp=sl,Zp=$l,Xp=ap,eh=_p,th=Mp,rh=new Td.Logger("Device");function nh(e,t){return rh.debug("detectDevice()"),e||"object"!=typeof navigator||(e=navigator.userAgent),t||"object"!=typeof navigator||(t=navigator.userAgentData),oh(e,t)}async function ih(e,t){return rh.debug("detectDeviceAsync()"),e||"object"!=typeof navigator||(e=navigator.userAgent),t||"object"!=typeof navigator||(t=navigator.userAgentData),oh(e,t)}class sh{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new Gp.EnhancedEventEmitter;static async factory({handlerName:e,handlerFactory:t}={}){if(rh.debug("factory()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!e&&!t&&!(e=await ih()))throw new Yp.UnsupportedError("device not supported");return new sh({handlerName:e,handlerFactory:t})}constructor({handlerName:e,handlerFactory:t}={}){if(rh.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)rh.debug("constructor() | handler given: %s",e);else{if(!(e=nh()))throw new Yp.UnsupportedError("device not supported");rh.debug("constructor() | detected handler: %s",e)}switch(e){case"Chrome111":this._handlerFactory=Qp.Chrome111.createFactory();break;case"Chrome74":this._handlerFactory=Zp.Chrome74.createFactory();break;case"Firefox120":this._handlerFactory=Xp.Firefox120.createFactory();break;case"Safari12":this._handlerFactory=eh.Safari12.createFactory();break;case"ReactNative106":this._handlerFactory=th.ReactNative106.createFactory();break;default:throw new TypeError(`unknown handlerName "${e}"`)}}this._handlerName=this._handlerFactory.name}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){return this.recvRtpCapabilities}get recvRtpCapabilities(){if(!this._loaded)throw new Yp.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sendRtpCapabilities(){if(!this._loaded)throw new Yp.InvalidStateError("not loaded");return this._sendRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new Yp.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e,preferLocalCodecsOrder:t=!1}){if(rh.debug("load() [routerRtpCapabilities:%o]",e),this._loaded)throw new Yp.InvalidStateError("already loaded");const r=$p.clone(e);Kp.validateAndNormalizeRtpCapabilities(r);const{getNativeRtpCapabilities:n,getNativeSctpCapabilities:i}=this._handlerFactory,s=$p.clone(await n({direction:"recvonly"}));rh.debug("load() | got native receiving RTP capabilities:%o",s),Kp.validateAndNormalizeRtpCapabilities(s);const o=$p.clone(await n({direction:"sendonly"}));rh.debug("load() | got native sending RTP capabilities:%o",o),Kp.validateAndNormalizeRtpCapabilities(o),this._getSendExtendedRtpCapabilities=e=>$p.clone(Kp.getExtendedRtpCapabilities(e,r,t));const a=Kp.getExtendedRtpCapabilities(s,r,!1);this._recvRtpCapabilities=Kp.getRecvRtpCapabilities(a),rh.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),Kp.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities);const c=Kp.getExtendedRtpCapabilities(o,r,t);this._sendRtpCapabilities=Kp.getSendRtpCapabilities(c),rh.debug("load() | got sending RTP capabilities:%o",this._sendRtpCapabilities),Kp.validateAndNormalizeRtpCapabilities(this._sendRtpCapabilities),this._canProduceByKind.audio=Kp.canSend("audio",this._sendRtpCapabilities),this._canProduceByKind.video=Kp.canSend("video",this._sendRtpCapabilities),this._sctpCapabilities=await i(),Kp.validateSctpCapabilities(this._sctpCapabilities),rh.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),rh.debug("load() succeeded"),this._loaded=!0}canProduce(e){if(!this._loaded)throw new Yp.InvalidStateError("not loaded");if("audio"!==e&&"video"!==e)throw new TypeError(`invalid kind "${e}"`);return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,appData:c}){return rh.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,appData:c})}createRecvTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,appData:c}){return rh.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,appData:c})}createTransport({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d}){if(!this._loaded)throw new Yp.InvalidStateError("not loaded");if("string"!=typeof t)throw new TypeError("missing id");if("object"!=typeof r)throw new TypeError("missing iceParameters");if(!Array.isArray(n))throw new TypeError("missing iceCandidates");if("object"!=typeof i)throw new TypeError("missing dtlsParameters");if(s&&"object"!=typeof s)throw new TypeError("wrong sctpParameters");if(d&&"object"!=typeof d)throw new TypeError("if given, appData must be an object");const u=new Jp.Transport({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d,handlerFactory:this._handlerFactory,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities,recvRtpCapabilities:this._recvRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",u),u}}function oh(e,t){rh.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',e,t);const r=function(e,t){if(rh.debug("getChromiumMajorVersion()"),ah(e,t))return void rh.debug("getChromiumMajorVersion() | this is iOS => undefined");if(ch())return void rh.debug("getChromiumMajorVersion() | this is React-Native => undefined");if(t){const e=(Array.isArray(t.brands)?t.brands:[]).find((e=>"Chromium"===e.brand));if(e){const t=Number(e.version);return rh.debug(`getChromiumMajorVersion() | Chromium major version based on NavigatorUAData => ${t}`),t}}const r=e?.match(/\b(?:Chrome|Chromium)\/(\w+)/i);if(r?.[1]){const e=Number(r[1]);return rh.debug(`getChromiumMajorVersion() | Chromium major version based on User-Agent => ${e}`),e}return void rh.debug("getChromiumMajorVersion() | this is not Chromium => undefined")}(e,t);if(r)return r>=111?(rh.debug("detectDeviceImpl() | using Chrome111 handler"),"Chrome111"):r>=74?(rh.debug("detectDeviceImpl() | using Chrome74 handler"),"Chrome74"):void rh.warn("detectDeviceImpl() | unsupported Chromium based browser/version");const n=function(e){if(rh.debug("getFirefoxMajorVersion()"),ah(e))return void rh.debug("getFirefoxMajorVersion() | this is iOS => undefined");if(ch())return void rh.debug("getFirefoxMajorVersion() | this is React-Native => undefined");const t=e?.match(/\bFirefox\/(\w+)/i);if(t?.[1]){const e=Number(t[1]);return rh.debug(`getFirefoxMajorVersion() | Firefox major version based on User-Agent => ${e}`),e}return void rh.debug("getFirefoxMajorVersion() | this is not Firefox => undefined")}(e);if(n)return n>=120?(rh.debug("detectDeviceImpl() | using Firefox120 handler"),"Firefox120"):void rh.warn("detectDeviceImpl() | unsupported Firefox browser/version");const i=function(e){if(rh.debug("getMacOSWebKitMajorVersion()"),ah(e))return void rh.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");if(ch())return void rh.debug("getMacOSWebKitMajorVersion() | this is React-Native => undefined");if(!e||!/\bSafari\b/i.test(e)||/\bChrome\b/i.test(e)||/\bChromium\b/i.test(e)||/\bFirefox\b/i.test(e))return void rh.debug("getMacOSWebKitMajorVersion() | this is not Safari => undefined");const t=e.match(/AppleWebKit\/(\w+)/i);if(t?.[1]){const e=Number(t[1]);return rh.debug(`getMacOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${e}`),e}return void rh.debug("getMacOSWebKitMajorVersion() | this is not WebKit => undefined")}(e);if(i)return i>=605?(rh.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12"):void rh.warn("detectDeviceImpl() | unsupported desktop Safari browser/version");const s=function(e){if(rh.debug("getIOSWebKitMajorVersion()"),!ah(e))return void rh.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");if(ch())return void rh.debug("getIOSWebKitMajorVersion() | this is React-Native => undefined");const t=e?.match(/AppleWebKit\/(\w+)/i);if(t?.[1]){const e=Number(t[1]);return rh.debug(`getIOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${e}`),e}return void rh.debug("getIOSWebKitMajorVersion() | this is not WebKit => undefined")}(e);return s?s>=605?(rh.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12"):void rh.warn("detectDeviceImpl() | unsupported iOS Safari based browser/version"):ch()?"undefined"!=typeof RTCPeerConnection&&"undefined"!=typeof RTCRtpTransceiver?(rh.debug("detectDeviceImpl() | using ReactNative106 handler"),"ReactNative106"):void rh.warn("detectDeviceImpl() | unsupported react-native-webrtc version without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?"):void rh.warn('detectDeviceImpl() | device not supported [userAgent:"%s", userAgentData:%o]',e,t)}function ah(e,t){return rh.debug("isIOS()"),"iOS"===t?.platform?(rh.debug("isIOS() | this is iOS based on NavigatorUAData.platform => true"),!0):t?.platform?(rh.debug("isIOS() | this is not iOS based on NavigatorUAData.platform => false"),!1):e&&/iPad|iPhone|iPod/.test(e)?(rh.debug("isIOS() | this is iOS based on User-Agent => true"),!0):"object"==typeof navigator&&"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1?(rh.debug("isIOS() | this is iPadOS 13+ based on User-Agent => true"),!0):(rh.debug("isIOS() | this is not iOS => false"),!1)}function ch(){return rh.debug("isReactNative()"),"object"==typeof navigator&&"ReactNative"===navigator.product?(rh.debug("isReactNative() | this is React-Native based on navigator.product"),!0):(rh.debug("isReactNative() | this is not React-Native => false"),!1)}Cd.Device=sh;for(var dh,uh={},lh={},ph={},hh=256,fh=[];hh--;)fh[hh]=(hh+256).toString(16).substring(1);ph.v4=function(){var e,t=0,r="";if(!dh||hh+16>256){for(dh=Array(t=256);t--;)dh[t]=256*Math.random()|0;t=hh=0}for(;t<16;t++)e=dh[hh+t],r+=6==t?fh[15&e|64]:8==t?fh[63&e|128]:fh[e],1&t&&t>1&&t<11&&(r+="-");return hh++,r};var mh={};Object.defineProperty(mh,"__esModule",{value:!0}),mh.FakeEventTarget=void 0;mh.FakeEventTarget=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:"function"==typeof t?t:t.handleEvent,once:"object"==typeof r&&!0===r.once}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter((e=>e.callback!==("function"==typeof t?t:t.handleEvent))))}dispatchEvent(e){if(!e||"string"!=typeof e.type)throw new Error("invalid event object");const t=this.listeners[e.type];if(!t)return!0;for(const r of[...t]){try{r.callback.call(this,e)}catch(e){setTimeout((()=>{throw e}),0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}};var gh={};Object.defineProperty(gh,"__esModule",{value:!0}),gh.FakeEvent=void 0;gh.FakeEvent=class{NONE=0;CAPTURING_PHASE=1;AT_TARGET=2;BUBBLING_PHASE=3;type;bubbles;cancelable;defaultPrevented=!1;composed=!1;currentTarget=null;eventPhase=u.NONE;isTrusted=!0;target=null;timeStamp=0;cancelBubble=!1;returnValue=!0;srcElement=null;constructor(e,t={}){this.type=e,this.bubbles=t.bubbles??!1,this.cancelable=t.cancelable??!1}preventDefault(){this.cancelable&&(this.defaultPrevented=!0)}stopPropagation(){}stopImmediatePropagation(){}composedPath(){return[]}initEvent(e,t,r){}};var vh={};Object.defineProperty(vh,"__esModule",{value:!0}),vh.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))},Object.defineProperty(lh,"__esModule",{value:!0}),lh.FakeMediaStreamTrack=void 0;const yh=ph,bh=mh,_h=gh,Eh=vh;class wh extends bh.FakeEventTarget{#E;#w;#S;#C;#T;#P;#R;#k;#D;#I;#A;#O=null;#M=null;#N=null;#L=null;#x=null;constructor({kind:e,id:t,label:r,contentHint:n,enabled:i,muted:s,readyState:o,capabilities:a,constraints:c,settings:d,data:u}){super(),this.#E=t??(0,yh.v4)(),this.#w=e,this.#S=r??"",this.#R=n??"",this.#T=i??!0,this.#P=s??!1,this.#C=o??"live",this.#k=a??{},this.#D=c??{},this.#I=d??{},this.#A=u??{}}get id(){return this.#E}get kind(){return this.#w}get label(){return this.#S}get contentHint(){return this.#R}set contentHint(e){this.#R=e}get enabled(){return this.#T}set enabled(e){const t=this.#T!==e;this.#T=e,t&&this.dispatchEvent(new _h.FakeEvent("enabledchange"))}get muted(){return this.#P}get readyState(){return this.#C}get data(){return this.#A}set data(e){this.#A=e}get onmute(){return this.#O}set onmute(e){this.#O&&this.removeEventListener("mute",this.#O),this.#O=e,e&&this.addEventListener("mute",e)}get onunmute(){return this.#M}set onunmute(e){this.#M&&this.removeEventListener("unmute",this.#M),this.#M=e,e&&this.addEventListener("unmute",e)}get onended(){return this.#N}set onended(e){this.#N&&this.removeEventListener("ended",this.#N),this.#N=e,e&&this.addEventListener("ended",e)}get onenabledchange(){return this.#L}set onenabledchange(e){this.#L&&this.removeEventListener("enabledchange",this.#L),this.#L=e,e&&this.addEventListener("enabledchange",e)}get onstopped(){return this.#x}set onstopped(e){this.#x&&this.removeEventListener("stopped",this.#x),this.#x=e,e&&this.addEventListener("stopped",e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}stop(){"ended"!==this.#C&&(this.#C="ended",this.dispatchEvent(new _h.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new wh({id:e??(0,yh.v4)(),kind:this.#w,label:this.#S,contentHint:this.#R,enabled:this.#T,muted:this.#P,readyState:this.#C,capabilities:(0,Eh.clone)(this.#k),constraints:(0,Eh.clone)(this.#D),settings:(0,Eh.clone)(this.#I),data:t??(0,Eh.clone)(this.#A)})}getCapabilities(){return this.#k}getConstraints(){return this.#D}async applyConstraints(e={}){return this.#D=e,Promise.resolve()}getSettings(){return this.#I}remoteStop(){"ended"!==this.#C&&(this.#C="ended",this.dispatchEvent(new _h.FakeEvent("stopped")),this.dispatchEvent(new _h.FakeEvent("ended")))}remoteMute(){this.#P||(this.#P=!0,this.dispatchEvent(new _h.FakeEvent("mute")))}remoteUnmute(){this.#P&&(this.#P=!1,this.dispatchEvent(new _h.FakeEvent("unmute")))}}lh.FakeMediaStreamTrack=wh;var Sh={};Object.defineProperty(Sh,"__esModule",{value:!0}),Sh.FakeEventTarget=void 0;Sh.FakeEventTarget=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:"function"==typeof t?t:t.handleEvent,once:"object"==typeof r&&!0===r.once}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter((e=>e.callback!==("function"==typeof t?t:t.handleEvent))))}dispatchEvent(e){if(!e||"string"!=typeof e.type)throw new Error("invalid event object");const t=this.listeners[e.type];if(!t)return!0;for(const r of[...t]){try{r.callback.call(this,e)}catch(e){setTimeout((()=>{throw e}),0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}},Object.defineProperty(uh,"__esModule",{value:!0}),uh.FakeHandler=void 0;const Ch=lh,Th=kd,Ph=Ld,Rh=xd,kh=Od,Dh=Sh,Ih=new Td.Logger("FakeHandler");class Ah extends Th.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${Ph.generateRandomNumber()}`;_defaultSendStreamId=`${Ph.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:"FakeHandler",factory:t=>new Ah(t,e),getNativeRtpCapabilities:async({direction:t})=>(Ih.debug("getNativeRtpCapabilities() [direction:%o]",t),Ah.getLocalRtpCapabilities(e)),getNativeSctpCapabilities:async()=>(Ih.debug("getNativeSctpCapabilities()"),e.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(e){const t=e.generateNativeRtpCapabilities();return Rh.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),Ih.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return"FakeHandler"}close(){Ih.debug("close()"),this._closed||(this._closed=!0,super.close())}setIceGatheringState(e){this.emit("@icegatheringstatechange",e)}setConnectionState(e){this.emit("@connectionstatechange",e)}async updateIceServers(e){this.assertNotClosed(),Ih.debug("updateIceServers()")}async restartIce(e){this.assertNotClosed(),Ih.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:e,streamId:t,encodings:r,codecOptions:n,codec:i}){this.assertNotClosed(),Ih.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});const s=Ah.getLocalRtpCapabilities(this._fakeParameters),o=this._getSendExtendedRtpCapabilities(s),a=Rh.getSendingRtpParameters(e.kind,o);a.codecs=Rh.reduceCodecs(a.codecs,i);const c=a.codecs.some((e=>/.+\/rtx$/i.test(e.mimeType)));a.mid=`mid-${Ph.generateRandomNumber()}`,a.msid=`${t??"-"} ${e.id}`,r||(r=[{}]);for(const e of r)e.ssrc=Ph.generateRandomNumber(),c&&(e.rtx={ssrc:Ph.generateRandomNumber()});a.encodings=r,a.rtcp={cname:this._cname,reducedSize:!0,mux:!0},a.msid=`${t??this._defaultSendStreamId} ${e.id}`;const d=this._nextLocalId++;return this._tracks.set(d,e),{localId:String(d),rtpParameters:a}}async stopSending(e){if(Ih.debug("stopSending() [localId:%s]",e),!this._closed){if(!this._tracks.has(Number(e)))throw new Error("local track not found");this._tracks.delete(Number(e))}}async pauseSending(e){this.assertNotClosed()}async resumeSending(e){this.assertNotClosed()}async replaceTrack(e,t){this.assertNotClosed(),t?Ih.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Ih.debug("replaceTrack() [localId:%s, no track]",e),this._tracks.delete(Number(e)),this._tracks.set(Number(e),t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),Ih.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),Ih.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t)}async getSenderStats(e){return this.assertNotClosed(),new Map}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),Ih.debug("sendDataChannel()");return{dataChannel:new Oh({id:this._nextSctpStreamId++,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}),sctpStreamParameters:{streamId:this._nextSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r}}}async receive(e){this.assertNotClosed();const t=[];for(const r of e){const{trackId:e,kind:n}=r;this._transportReady||await this.setupTransport({localDtlsRole:"client"}),Ih.debug("receive() [trackId:%s, kind:%s]",e,n);const i=this._nextLocalId++,s=new Ch.FakeMediaStreamTrack({kind:n});this._tracks.set(i,s),t.push({localId:String(i),track:s})}return t}async stopReceiving(e){if(!this._closed)for(const t of e)Ih.debug("stopReceiving() [localId:%s]",t),this._tracks.delete(Number(t))}async pauseReceiving(e){this.assertNotClosed()}async resumeReceiving(e){this.assertNotClosed()}async getReceiverStats(e){return this.assertNotClosed(),new Map}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"client"}),Ih.debug("receiveDataChannel()");return{dataChannel:new Oh({id:e.streamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:t,protocol:r})}}async setupTransport({localDtlsRole:e,localSdpObject:t}){const r=Ph.clone(this._fakeParameters.generateLocalDtlsParameters());e&&(r.role=e),this.emit("@connectionstatechange","connecting"),await new Promise(((e,t)=>this.emit("@connect",{dtlsParameters:r},e,t))),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new kh.InvalidStateError("method called in a closed handler")}}uh.FakeHandler=Ah;class Oh extends Dh.FakeEventTarget{_id;_negotiated=!0;_ordered;_maxPacketLifeTime;_maxRetransmits;_label;_protocol;_readyState="connecting";_bufferedAmount=0;_bufferedAmountLowThreshold=0;_binaryType="arraybuffer";_onopen=null;_onclosing=null;_onclose=null;_onmessage=null;_onbufferedamountlow=null;_onerror=null;constructor({id:e,ordered:t=!0,maxPacketLifeTime:r=null,maxRetransmits:n=null,label:i="",protocol:s=""}){super(),Ih.debug(`constructor() [id:${e}, ordered:${t}, maxPacketLifeTime:${r}, maxRetransmits:${n}, label:${i}, protocol:${s}`),this._id=e,this._ordered=t,this._maxPacketLifeTime=r,this._maxRetransmits=n,this._label=i,this._protocol=s}get id(){return this._id}get negotiated(){return this._negotiated}get ordered(){return this._ordered}get maxPacketLifeTime(){return this._maxPacketLifeTime}get maxRetransmits(){return this._maxRetransmits}get label(){return this._label}get protocol(){return this._protocol}get readyState(){return this._readyState}get bufferedAmount(){return this._bufferedAmount}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._bufferedAmountLowThreshold=e}get binaryType(){return this._binaryType}set binaryType(e){this._binaryType=e}get onopen(){return this._onopen}set onopen(e){this._onopen&&this.removeEventListener("open",this._onopen),this._onopen=e,e&&this.addEventListener("open",e)}get onclosing(){return this._onclosing}set onclosing(e){this._onclosing&&this.removeEventListener("closing",this._onclosing),this._onclosing=e,e&&this.addEventListener("closing",e)}get onclose(){return this._onclose}set onclose(e){this._onclose&&this.removeEventListener("close",this._onclose),this._onclose=e,e&&this.addEventListener("close",e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage&&this.removeEventListener("message",this._onmessage),this._onmessage=e,e&&this.addEventListener("message",e)}get onbufferedamountlow(){return this._onbufferedamountlow}set onbufferedamountlow(e){this._onbufferedamountlow&&this.removeEventListener("bufferedamountlow",this._onbufferedamountlow),this._onbufferedamountlow=e,e&&this.addEventListener("bufferedamountlow",e)}get onerror(){return this._onerror}set onerror(e){this._onerror&&this.removeEventListener("error",this._onerror),this._onerror=e,e&&this.addEventListener("error",e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}close(){["closing","closed"].includes(this._readyState)||(this._readyState="closed")}send(e){if("open"!==this._readyState)throw new kh.InvalidStateError("not open")}}var Mh={};Object.defineProperty(Mh,"__esModule",{value:!0}),Mh.generateRouterRtpCapabilities=function(){return Nh.deepFreeze({codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}},{mimeType:"video/H264",kind:"video",preferredPayloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:105,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"profile-id":0,"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:106,clockRate:9e4,rtcpFeedback:[],parameters:{apt:105}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",preferredId:2,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",preferredId:3,preferredEncrypt:!1,direction:"recvonly"},{kind:"audio",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:11,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:12,preferredEncrypt:!1,direction:"sendrecv"}]})},Mh.generateNativeRtpCapabilities=function(){return{codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:111,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{minptime:10,useinbandfec:1}},{mimeType:"audio/ISAC",kind:"audio",preferredPayloadType:103,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/CN",kind:"audio",preferredPayloadType:106,clockRate:32e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/foo",kind:"audio",preferredPayloadType:107,clockRate:9e4,channels:4,rtcpFeedback:[{type:"foo-qwe-qwe"}],parameters:{foo:"lalala"}},{mimeType:"video/BAZCODEC",kind:"video",preferredPayloadType:100,clockRate:9e4,rtcpFeedback:[{type:"foo"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[],parameters:{apt:100}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:96,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:97,clockRate:9e4,rtcpFeedback:[],parameters:{apt:96}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:98,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{"profile-id":0}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:99,clockRate:9e4,rtcpFeedback:[],parameters:{apt:98}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:2},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:3},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:4},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay",preferredId:6},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type",preferredId:7},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing",preferredId:8},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10}]}},Mh.generateNativeSctpCapabilities=function(){return Nh.deepFreeze({numStreams:{OS:2048,MIS:2048}})},Mh.generateLocalDtlsParameters=function(){return Nh.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"82:5A:68:3D:36:C3:0A:DE:AF:E7:32:43:D2:88:83:57:AC:2D:65:E5:80:C4:B6:FB:AF:1A:A0:21:9F:6D:0C:AD"}],role:"auto"})},Mh.generateTransportRemoteParameters=function(){return{id:Lh(),iceParameters:Nh.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:Nh.deepFreeze([{foundation:"udpcandidate",address:"9.9.9.9",ip:"9.9.9.9",port:40533,priority:1078862079,protocol:"udp",type:"host",tcpType:"passive"},{foundation:"udpcandidate",address:"9.9.9.9",ip:"9:9:9:9:9:9",port:41333,priority:1078862089,protocol:"udp",type:"host",tcpType:"passive"}]),dtlsParameters:Nh.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"A9:F4:E0:D2:74:D3:0F:D9:CA:A5:2F:9F:7F:47:FA:F0:C4:72:DD:73:49:D0:3B:14:90:20:51:30:1B:90:8E:71"},{algorithm:"sha-384",value:"03:D9:0B:87:13:98:F6:6D:BC:FC:92:2E:39:D4:E1:97:32:61:30:56:84:70:81:6E:D1:82:97:EA:D9:C1:21:0F:6B:C5:E7:7F:E1:97:0C:17:97:6E:CF:B3:EF:2E:74:B0"},{algorithm:"sha-512",value:"84:27:A4:28:A4:73:AF:43:02:2A:44:68:FF:2F:29:5C:3B:11:9A:60:F4:A8:F0:F5:AC:A0:E3:49:3E:B1:34:53:A9:85:CE:51:9B:ED:87:5E:B8:F4:8E:3D:FA:20:51:B8:96:EE:DA:56:DC:2F:5C:62:79:15:23:E0:21:82:2B:2C"}],role:"auto"}),sctpParameters:Nh.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}},Mh.generateProducerRemoteParameters=function(){return Nh.deepFreeze({id:Lh()})},Mh.generateConsumerRemoteParameters=function({id:e,codecMimeType:t}={}){switch(t){case"audio/opus":return{id:e??Lh(),producerId:Lh(),kind:"audio",rtpParameters:Nh.deepFreeze({codecs:[{mimeType:"audio/opus",payloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}}],encodings:[{ssrc:46687003}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",id:10}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"audio/ISAC":return{id:e??Lh(),producerId:Lh(),kind:"audio",rtpParameters:Nh.deepFreeze({codecs:[{mimeType:"audio/ISAC",payloadType:111,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}}],encodings:[{ssrc:46687004}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/VP8":return{id:e??Lh(),producerId:Lh(),kind:"video",rtpParameters:Nh.deepFreeze({codecs:[{mimeType:"video/VP8",payloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",payloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}}],encodings:[{ssrc:99991111,rtx:{ssrc:99991112}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/H264":return{id:e??Lh(),producerId:Lh(),kind:"video",rtpParameters:Nh.deepFreeze({codecs:[{mimeType:"video/H264",payloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",payloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}}],encodings:[{ssrc:99991113,rtx:{ssrc:99991114}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};default:throw new TypeError(`unknown codecMimeType '${t}'`)}},Mh.generateDataProducerRemoteParameters=function(){return Nh.deepFreeze({id:Lh()})},Mh.generateDataConsumerRemoteParameters=function({id:e}={}){return{id:e??Lh(),dataProducerId:Lh(),sctpStreamParameters:Nh.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}};const Nh=Ld;function Lh(){return String(Nh.generateRandomNumber())}!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.debug=e.testFakeParameters=e.FakeHandler=e.enhancedEvents=e.ortc=e.parseScalabilityMode=e.detectDeviceAsync=e.detectDevice=e.Device=e.version=e.types=void 0;const t=md.exports;e.debug=t.default,e.types=Sd,e.version="3.18.8";var r=Cd;Object.defineProperty(e,"Device",{enumerable:!0,get:function(){return r.Device}}),Object.defineProperty(e,"detectDevice",{enumerable:!0,get:function(){return r.detectDevice}}),Object.defineProperty(e,"detectDeviceAsync",{enumerable:!0,get:function(){return r.detectDeviceAsync}});var n=bl;Object.defineProperty(e,"parseScalabilityMode",{enumerable:!0,get:function(){return n.parse}}),e.ortc=xd,e.enhancedEvents=kd;var i=uh;Object.defineProperty(e,"FakeHandler",{enumerable:!0,get:function(){return i.FakeHandler}}),e.testFakeParameters=Mh}(fd);const xh=[{scaleResolutionDownBy:4,maxBitrate:15e4,maxFramerate:12},{scaleResolutionDownBy:2,maxBitrate:35e4,maxFramerate:18},{scaleResolutionDownBy:1,maxBitrate:9e5,maxFramerate:24}],Fh=[{maxBitrate:1e6,dtx:!0}],jh=[{maxBitrate:4e4,dtx:!0}],Uh={width:1280,height:720},Vh=0,Bh=2,Wh=0;function Hh(e,t){e.onload=function(){this.onerror=this.onload=null,t(null,e)},e.onerror=function(){this.onerror=this.onload=null,t(new Error("Failed to load "+this.src),e)}}function qh(e,t){e.onreadystatechange=function(){"complete"!=this.readyState&&"loaded"!=this.readyState||(this.onreadystatechange=null,t(null,e))}}const zh=new pi,Gh=e=>o(void 0,void 0,void 0,(function*(){return yield new Promise(((t,r)=>{!function(e,t,r){var n=document.head||document.getElementsByTagName("head")[0],i=document.createElement("script");"function"==typeof t&&(r=t,t={}),t=t||{},r=r||function(){},i.type=t.type||"text/javascript",i.charset=t.charset||"utf8",i.async=!("async"in t)||!!t.async,i.src=e,t.attrs&&function(e,t){for(var r in t)e.setAttribute(r,t[r])}(i,t.attrs),t.text&&(i.text=""+t.text),("onload"in i?Hh:qh)(i,r),i.onload||Hh(i,r),n.appendChild(i)}(e,((e,n)=>{e?r(e):t(n)}))}))})),Yh=(e,...t)=>o(void 0,[e,...t],void 0,(function*(e,t=3,r=500){let n=0;for(;n<t;)try{return void(yield Gh(e))}catch(e){if(n+=1,!(n<t))throw e;yield zh.sleepMs(r)}}));var $h;let Kh=class{constructor(){$h.set(this,new Map)}add(e,t,r){const n=this.getKey(e,t);if(a(this,$h,"f").has(n))throw new Error("Attempt to rewrite cached track processor");a(this,$h,"f").set(n,r)}get(e,t){return a(this,$h,"f").get(this.getKey(e,t))}has(e,t){return a(this,$h,"f").has(this.getKey(e,t))}getKey(e,t){return`${e}:${t}`}reset(){for(const e of a(this,$h,"f").values())try{e.stopProcessing(),e.release()}catch(e){}a(this,$h,"f").clear()}};var Jh,Qh;$h=new WeakMap,Kh=n([ot()],Kh);let Zh=class{constructor(e,t,r,n){this.config=e,this.processorsCache=t,this.audioTrackProcessorFactory=r,Jh.set(this,new Map),Qh.set(this,void 0),c(this,Qh,n("IntegrationsService"),"f")}init(){const e=this.config.get("denoiser");if("asdk"===e){a(this,Qh,"f").info("Start integration of ASDK",{denoiser:e});const t=this.integrateASDK();t.catch((e=>{a(this,Qh,"f").warn("ASDK integration failed, will fallback to RNNoise on demand",{error:String(e)})}));const r={integrated:!1,initPromise:t};a(this,Jh,"f").set("asdk",r)}else{a(this,Qh,"f").info("Start integration of RNNoise",{denoiser:e});const t=this.integrateRNNoise();t.catch((e=>{a(this,Qh,"f").warn("RNNoise integration failed",{error:String(e)})}));const r={integrated:!1,initPromise:t};a(this,Jh,"f").set("rnnoise",r)}}integrateASDK(){return o(this,void 0,void 0,(function*(){const e=this.config.get("asdk"),t=this.config.get("staticFilesPath");if(!window.atsvb){const i=`https://effectssdk.ai/sdk/audio/dev/${e.version}/atsvb-web.js`;let s=i;if(e.localDir){const r=`${e.localDir}/${e.version}/atsvb-web.js`;s=new URL(r,t).href}yield(r=s,n=i,o(void 0,void 0,void 0,(function*(){try{yield Yh(r)}catch(e){if(!n)throw e;yield Yh(n)}})))}var r,n;if(!window.atsvb)throw a(this,Qh,"f").info("Audio Effects SDK is not loaded, skipping initialization",{case:"initAudioSDK"}),new Error("windows.atsvb is still missing");const i=this.audioTrackProcessorFactory({trackLabel:exports.TrackLabel.Microphone});yield i.init(),this.processorsCache.add("asdk",exports.TrackLabel.Microphone,i);const s=a(this,Jh,"f").get("asdk");if(!s)throw Error("IntegrationContext is missing for ASDK");s.integrated=!0}))}get audio(){return"asdk"===this.config.get("denoiser")?this.getASDKState():this.getRNNoiseState()}getASDKState(){var e,t;const r=a(this,Jh,"f").get("asdk");return{type:"asdk",enabled:Boolean(r),isInitialized:null!==(e=null==r?void 0:r.integrated)&&void 0!==e&&e,waitForInitialization:null!==(t=null==r?void 0:r.initPromise)&&void 0!==t?t:Promise.resolve()}}getRNNoiseState(){var e,t;const r=a(this,Jh,"f").get("rnnoise");return{type:"rnnoise",enabled:Boolean(r),isInitialized:null!==(e=null==r?void 0:r.integrated)&&void 0!==e&&e,waitForInitialization:null!==(t=null==r?void 0:r.initPromise)&&void 0!==t?t:Promise.resolve()}}integrateRNNoise(){return o(this,void 0,void 0,(function*(){const e=yield function(e){return o(this,void 0,void 0,(function*(){if(!window.WebAssembly)throw new Error("Webassembly not supported");const t=yield fetch(`${e}/rnnoise-processor.wasm`);return yield WebAssembly.instantiate(yield t.arrayBuffer())}))}(this.config.get("staticFilesPath")),t=this.audioTrackProcessorFactory({trackLabel:exports.TrackLabel.Microphone,noiseSuppressor:e});this.processorsCache.add("rnnoise",exports.TrackLabel.Microphone,t);const r=a(this,Jh,"f").get("rnnoise");if(!r)throw Error("IntegrationContext is missing for RNNoise");r.integrated=!0}))}reset(){a(this,Jh,"f").clear()}};function Xh(e,t){return(r,n,i)=>{const s=i.value,a=null!=t?t:n;return i.value=function(...t){return o(this,void 0,void 0,(function*(){return yield function(e,t,r){return o(this,void 0,void 0,(function*(){let n;const i=new Promise(((e,i)=>{n=setTimeout((()=>{i(new Kn(`Operation "${t}" timed out after ${r}ms`,"operation_timeout",{operation:t,timeoutMs:r}))}),r)}));return yield Promise.race([e,i]).finally((()=>{clearTimeout(n)}))}))}(s.apply(this,t),a,e)}))},i}}var ef,tf,rf,nf,sf,of,af,cf,df,uf,lf,pf,hf,ff,mf,gf,vf,yf,bf;Jh=new WeakMap,Qh=new WeakMap,Zh=n([ot(),i(0,ct(mi.Config)),i(1,ct(mi.ProcessorsCache)),i(2,ct(mi.AudioTrackProcessorFactory)),i(3,ct(mi.LoggerFactory)),s("design:paramtypes",[Et,Kh,Function,Function])],Zh);class _f{constructor(e){var t,r;ef.set(this,void 0),tf.set(this,void 0),rf.set(this,void 0),nf.set(this,void 0),sf.set(this,void 0),of.set(this,void 0),af.set(this,0),c(this,ef,e.logger,"f"),c(this,tf,e.getMetrics,"f"),c(this,rf,null!==(t=e.pollIntervalMs)&&void 0!==t?t:15e3,"f"),c(this,nf,null!==(r=e.minLogIntervalMs)&&void 0!==r?r:6e4,"f")}start(){void 0===a(this,sf,"f")&&c(this,sf,setInterval((()=>this.tick()),a(this,rf,"f")),"f")}stop(){void 0!==a(this,sf,"f")&&(clearInterval(a(this,sf,"f")),c(this,sf,void 0,"f"))}tick(){const e=a(this,tf,"f").call(this);if(!e)return;const t={fps:Math.round(e.fps),segmentationInferenceTime:Math.round(e.segmentationInferenceTime),fullFrameDrawTime:Math.round(e.fullFrameDrawTime)},r=`fps=${t.fps}|seg=${t.segmentationInferenceTime}|draw=${t.fullFrameDrawTime}`;if(r===a(this,of,"f"))return;void 0!==a(this,of,"f")&&Date.now()-a(this,af,"f")<a(this,nf,"f")||(a(this,ef,"f").info("effects_metrics",{metrics:t}),c(this,of,r,"f"),c(this,af,Date.now(),"f"))}}ef=new WeakMap,tf=new WeakMap,rf=new WeakMap,nf=new WeakMap,sf=new WeakMap,of=new WeakMap,af=new WeakMap,function(e){e.INFO="info",e.WARNING="warning",e.ERROR="error"}(yf||(yf={})),function(e){e.TSVB="tsvb",e.COMPONENTS_SYSTEM="components_system",e.SRTEAM_PROCESSOR="stream_processor",e.ML_INFERENCE="ml_inference",e.PRESET_INIT="preset_init",e.RENDERER="renderer",e.RECORDER="recorder",e.EFFECT_VIRTUAL_BACKGROUND="effect_virtual_background",e.EFFECT_COLOR_CORRECTION="effect_color_correction",e.EFFECT_COLOR_FILTER="effect_color_filter",e.EFFECT_SMART_ZOOM="effect_smart_zoom",e.EFFECT_LOW_LIGHT="effect_low_light"}(bf||(bf={}));class Ef{constructor(e){cf.set(this,void 0),df.set(this,void 0),uf.set(this,{lowLighter:!1,colorCorrector:!1,faceDetector:!1,segmentation:!1}),lf.set(this,null),pf.set(this,void 0),hf.set(this,!1),ff.set(this,!1),mf.set(this,void 0),gf.set(this,void 0),vf.set(this,void 0);const{loggerFactory:t}=e;if(c(this,df,t("EffectsSDKTrackProcessor"),"f"),c(this,mf,e.onModelsLoaded,"f"),!e.customerId)throw new Error("Customer ID must be provided");c(this,cf,new window.tsvb(e.customerId),"f"),a(this,cf,"f").onError(this.tsvbErrorHandler.bind(this)),a(this,cf,"f").onReady=this.onReady.bind(this);const r=e.config.get("staticFilesPath"),{localDir:n,version:i}=e.config.get("effectsSDKParams"),s=n&&i?`${r}/esdk/${null!=i?i:"3.8.0"}`:`https://effectssdk.ai/sdk/web/${null!=i?i:"3.8.0"}`,o={preset:"balanced",provider:"webgpu",sdk_url:e.sdk_url,api_url:e.api_url,test_inference:!0,wasmPaths:{"ort-wasm.wasm":`${s}/ort-wasm.wasm`,"ort-wasm-simd.wasm":`${s}/ort-wasm-simd.wasm`,"ort-wasm-simd.jsep.wasm":`${s}/ort-wasm-simd.jsep.wasm`}};a(this,cf,"f").config(o)}init(){return o(this,void 0,void 0,(function*(){yield a(this,cf,"f").preload(),yield a(this,cf,"f").cache(),c(this,hf,!0,"f")}))}awaitReady(){return o(this,void 0,void 0,(function*(){yield new Promise((e=>{const t=setInterval((()=>{this.isModelsLoaded&&(clearInterval(t),e())}),100)}))}))}setOnRuntimeError(e){c(this,gf,e,"f")}tsvbErrorHandler(e){var t,n;const{emitter:i,type:s}=e,o=r(e,["emitter","type"]),c=null!=i?i:"N/A emitter";s===yf.ERROR&&(a(this,df,"f").error(c,Object.assign({error:Vt(e)},o)),null===(t=a(this,gf,"f"))||void 0===t||t.call(this,e)),s===yf.WARNING&&a(this,df,"f").warn(c,Object.assign({},o)),s===yf.INFO&&a(this,df,"f").debug(c,Object.assign({},o)),i===bf.ML_INFERENCE&&(o.message.toLocaleLowerCase().includes("init lowlighter")&&(a(this,uf,"f").lowLighter=!0),o.message.toLocaleLowerCase().includes("init colorcorrector")&&(a(this,uf,"f").colorCorrector=!0),o.message.toLocaleLowerCase().includes("init facedetector")&&(a(this,uf,"f").faceDetector=!0),o.message.toLocaleLowerCase().includes("init segmentation")&&(a(this,uf,"f").segmentation=!0),this.isModelsLoaded&&(null===(n=a(this,mf,"f"))||void 0===n||n.call(this)))}get isModelsLoaded(){return a(this,uf,"f").colorCorrector&&a(this,uf,"f").faceDetector&&a(this,uf,"f").lowLighter&&a(this,uf,"f").segmentation}get modelsLoadProgress(){return Object.values(a(this,uf,"f")).filter(Boolean).length/Object.keys(a(this,uf,"f")).length}get isReady(){return a(this,ff,"f")&&a(this,hf,"f")}setOnLoadModels(e){c(this,mf,e,"f"),this.isModelsLoaded&&a(this,mf,"f").call(this)}onReady(){c(this,ff,!0,"f"),a(this,df,"f").debug("onReady()",{description:"ESDK is ready"}),this.updateEffects(a(this,pf,"f")),c(this,vf,new _f({logger:a(this,df,"f"),getMetrics:()=>a(this,cf,"f").getMetrics()}),"f"),a(this,vf,"f").start()}processTrack(e){var t,r,n;if(a(this,lf,"f")===e||"ended"===e.readyState)return null!==(r=null===(t=a(this,cf,"f").getStream())||void 0===t?void 0:t.getVideoTracks()[0])&&void 0!==r?r:e;this.stopProcessing();try{a(this,cf,"f").useStream(new MediaStream([e]));const t=null===(n=a(this,cf,"f").getStream())||void 0===n?void 0:n.getVideoTracks()[0];return t?(c(this,lf,e,"f"),t):e}catch(t){throw a(this,df,"f").error("processTrack()",{error:t,track:e}),new Bt("esdk_process_track_failed",t)}}stopProcessing(){var e;null===(e=a(this,vf,"f"))||void 0===e||e.stop(),c(this,vf,void 0,"f");try{a(this,cf,"f").clear(),a(this,cf,"f").stop()}catch(e){a(this,df,"f").error("stopProcessing()",{error:e})}finally{c(this,lf,null,"f"),c(this,ff,!1,"f")}}updateEffects(e){var t,r,n,i,s,o,d,u,l,p,h,f,m,g,v,y,b,_,E,w,S,C;if(c(this,pf,e,"f"),!a(this,ff,"f"))return void a(this,df,"f").warn("updateEffects()",{description:"Esdk pipeline not ready"});if(!a(this,pf,"f")||0===Object.keys(a(this,pf,"f")).length)return void a(this,cf,"f").stop();let T=0;if((null===(t=a(this,pf,"f"))||void 0===t?void 0:t.blur)&&!(null===(r=a(this,pf,"f"))||void 0===r?void 0:r.backgroundColor)?(a(this,cf,"f").setBlur(a(this,pf,"f").blur),T+=1):a(this,cf,"f").clearBlur(),void 0!==(null===(n=a(this,pf,"f"))||void 0===n?void 0:n.background)?(a(this,cf,"f").setBackground(a(this,pf,"f").background),T+=1):void 0!==(null===(i=a(this,pf,"f"))||void 0===i?void 0:i.backgroundColor)?(a(this,cf,"f").setBackgroundColor(null===(s=a(this,pf,"f"))||void 0===s?void 0:s.backgroundColor),a(this,cf,"f").setBackground("color"),T+=1):a(this,cf,"f").clearBackground(),(null===(o=a(this,pf,"f"))||void 0===o?void 0:o.beautification)?(a(this,cf,"f").enableBeautification(),a(this,cf,"f").setBeautificationLevel(a(this,pf,"f").beautification),T+=1):a(this,cf,"f").disableBeautification(),(null===(d=a(this,pf,"f"))||void 0===d?void 0:d.lowLightEffect)?(a(this,cf,"f").enableLowLightEffect(),a(this,cf,"f").setLowLightEffectPower(a(this,pf,"f").lowLightEffect),T+=1):a(this,cf,"f").disableLowLightEffect(),(null===(u=a(this,pf,"f"))||void 0===u?void 0:u.colorCorrector)?(a(this,cf,"f").enableColorCorrector(),a(this,cf,"f").setColorCorrectorPower(a(this,pf,"f").colorCorrector),T+=1):a(this,cf,"f").disableColorCorrector(),(null===(l=a(this,pf,"f"))||void 0===l?void 0:l.smartZoom)?(a(this,cf,"f").enableSmartZoom(),a(this,cf,"f").setFaceArea(a(this,pf,"f").smartZoom),T+=1):a(this,cf,"f").disableSmartZoom(),(null===(p=a(this,pf,"f"))||void 0===p?void 0:p.layout)?(a(this,cf,"f").setLayout(a(this,pf,"f").layout),T+=1):a(this,cf,"f").setLayout("center"),(null===(h=a(this,pf,"f"))||void 0===h?void 0:h.colorFilter)&&(null===(f=a(this,pf,"f"))||void 0===f?void 0:f.colorFilter.power)&&(null===(m=a(this,pf,"f"))||void 0===m?void 0:m.colorFilter.url)?(a(this,cf,"f").setColorFilterConfig({lut:a(this,pf,"f").colorFilter.url,power:a(this,pf,"f").colorFilter.power}),a(this,cf,"f").enableColorFilter(),T+=1):a(this,cf,"f").disableColorFilter(),null===(g=a(this,pf,"f"))||void 0===g?void 0:g.lowerThird){const e=a(this,cf,"f").createComponent({component:a(this,pf,"f").lowerThird.type,options:null!==(v=a(this,pf,"f").lowerThird.options)&&void 0!==v?v:{}});null===(_=null===(b=null===(y=a(this,cf,"f").components)||void 0===y?void 0:y.lowerThird)||void 0===b?void 0:b.hideLowerThird)||void 0===_||_.call(b),a(this,cf,"f").addComponent(e,"lowerThird"),a(this,cf,"f").components.lowerThird.showLowerThird(),T+=1}else null===(S=null===(w=null===(E=a(this,cf,"f").components)||void 0===E?void 0:E.lowerThird)||void 0===w?void 0:w.hideLowerThird)||void 0===S||S.call(w);(null===(C=a(this,pf,"f"))||void 0===C?void 0:C.sharpness)?(a(this,cf,"f").setSharpnessEffectConfig(a(this,pf,"f").sharpness),T+=1):a(this,cf,"f").disableSharpnessEffect(),T>2?a(this,cf,"f").enableFrameSkipping():a(this,cf,"f").disableFrameSkipping(),a(this,cf,"f").run()}}cf=new WeakMap,df=new WeakMap,uf=new WeakMap,lf=new WeakMap,pf=new WeakMap,hf=new WeakMap,ff=new WeakMap,mf=new WeakMap,gf=new WeakMap,vf=new WeakMap,n([Xh(15e3,"EffectsSDKTrackProcessor.init"),s("design:type",Function),s("design:paramtypes",[]),s("design:returntype",Promise)],Ef.prototype,"init",null),n([Xh(15e3),s("design:type",Function),s("design:paramtypes",[]),s("design:returntype",Promise)],Ef.prototype,"awaitReady",null);const wf=new Set(["width","height","aspectRatio","frameRate","facingMode","resizeMode","displaySurface","logicalSurface","cursor"]),Sf=e=>e instanceof DOMException&&"OverconstrainedError"===e.name&&"constraint"in e&&"string"==typeof e.constraint,Cf=(e,t)=>{const r=e.getSettings()[t];return void 0===r?"unknown":String(r)};class Tf extends Bt{constructor(e,t,{errorCode:r,actual:n}){const{constraint:i}=e,s=((e,t)=>wf.has(t)||void 0!==e.video&&!1!==e.video?"video":"audio")(t,i),o=((e,t,r)=>{const n="audio"===t?e.audio:e.video;if(!n||!0===n)return"unknown";const i=n[r];return void 0===i?"unknown":"object"==typeof i?JSON.stringify(i):String(i)})(t,s,i),a=n?`Requested: ${o}, Actual: ${n}`:`Requested: ${o}`;super(r,Object.assign(Object.assign(Object.assign(Object.assign({},Vt(e)),{constraint:i,requested:o}),n?{actual:n}:{}),{message:a})),this.constraint=i,this.requested=o,this.actual=n}}const Pf=e=>"rtx"!==e.mimeType;var Rf,kf,Df;class If{constructor({track:e}){Rf.set(this,1e4),kf.set(this,0),Df.set(this,void 0),this.startCleanupTimer(),e.addEventListener("ended",(()=>{clearInterval(a(this,Df,"f")),c(this,Df,void 0,"f")}),{once:!0})}touchLastReceivedStatsTimestamp(){c(this,kf,Date.now(),"f")}startCleanupTimer(){c(this,Df,setInterval((()=>{a(this,kf,"f")>0&&Date.now()-a(this,kf,"f")>=a(this,Rf,"f")&&this.cleanupStats()}),a(this,Rf,"f")),"f")}}var Af,Of,Mf,Nf,Lf,xf,Ff,jf,Uf,Vf,Bf,Wf,Hf,qf,zf,Gf,Yf,$f,Kf,Jf,Qf,Zf,Xf;Rf=new WeakMap,kf=new WeakMap,Df=new WeakMap;class em extends If{constructor({track:e,statsHandler:t,widStatsAdapter:r,scoresCalculator:n,isStaticContent:i}){super({track:e}),Af.set(this,void 0),Of.set(this,void 0),Mf.set(this,void 0),Nf.set(this,void 0),Lf.set(this,void 0),xf.set(this,void 0),Ff.set(this,void 0),this.handleWebRTCStats(e,t),c(this,xf,r,"f"),c(this,Lf,n,"f"),c(this,Ff,i,"f")}get videoWebRTCStats(){var e,t,r,n,i;return null!==(r=null===(t=null===(e=a(this,Af,"f"))||void 0===e?void 0:e.find((e=>e.outbound.active)))||void 0===t?void 0:t.outbound)&&void 0!==r?r:null===(i=null===(n=a(this,Af,"f"))||void 0===n?void 0:n[0])||void 0===i?void 0:i.outbound}get audioWebRTCStats(){var e;return null===(e=a(this,Of,"f"))||void 0===e?void 0:e.outbound}get scores(){return{Qv:a(this,Mf,"f"),Qa:a(this,Nf,"f")}}handleWebRTCStats(e,t){e.addEventListener("ended",(()=>{t.removeOutboundVideoHandler(e.id),t.removeOutboundAudioHandler(e.id)}),{once:!0}),"video"!==e.kind?t.addOutboundAudioHandler(e.id,this.setAudioWebRTCStats.bind(this)):t.addOutboundVideoHandler(e.id,this.setVideoWebRTCStats.bind(this))}setVideoWebRTCStats(e){this.touchLastReceivedStatsTimestamp();const t=e.filter((e=>e.outbound.active)),r=[];t.forEach((e=>{var t;const n=null===(t=a(this,Af,"f"))||void 0===t?void 0:t.find((t=>t.outbound.ssrc===e.outbound.ssrc)),i=a(this,xf,"f").adaptOutboundVideoStats({stats:e.outbound,remoteInboundStats:e.remoteInbound,prevStats:n,isStaticContent:a(this,Ff,"f")});r.push(a(this,Lf,"f").calculateVideoMOS(i))})),c(this,Mf,r.length>0?Math.min(...r):void 0,"f"),c(this,Af,e,"f")}setAudioWebRTCStats(e){var t,r;this.touchLastReceivedStatsTimestamp();const n=a(this,Of,"f")?{outbound:a(this,Of,"f").outbound,remoteInbound:a(this,Of,"f").remoteInbound}:void 0,i=a(this,xf,"f").adaptOutboundAudioStats({stats:e.outbound,remoteInboundStats:e.remoteInbound,fec:null===(t=Ar("qosOutboundFec"))||void 0===t||t,dtx:null===(r=Ar("qosOutboundDtx"))||void 0===r||r,prevStats:n});c(this,Nf,a(this,Lf,"f").calculateAudioMOS(i),"f"),c(this,Of,e,"f")}cleanupStats(){c(this,Af,void 0,"f"),c(this,Of,void 0,"f"),c(this,Mf,void 0,"f"),c(this,Nf,void 0,"f")}}Af=new WeakMap,Of=new WeakMap,Mf=new WeakMap,Nf=new WeakMap,Lf=new WeakMap,xf=new WeakMap,Ff=new WeakMap;class tm{constructor(e){jf.set(this,void 0),Uf.set(this,void 0),this.encoderConfig={},this.label=exports.TrackLabel.Unknown,Vf.set(this,void 0),Bf.set(this,void 0),Wf.set(this,void 0),Hf.set(this,void 0),qf.set(this,void 0),zf.set(this,void 0),Gf.set(this,void 0),Yf.set(this,void 0),$f.set(this,!0),Kf.set(this,void 0),Jf.set(this,void 0),Qf.set(this,void 0),Zf.set(this,void 0),Xf.set(this,void 0);const{mediaStreamTrack:t,internalEventEmitter:r,constraints:n,mediaStreamTrackManager:i,media:s,myPeer:o,network:a,producerCloseManager:d,mutex:u,loggerFactory:l,loggerNamespace:p,statsHandler:h,widStatsAdapter:f,scoresCalculator:m}=e;c(this,jf,t,"f"),c(this,qf,r,"f"),c(this,zf,n,"f"),c(this,Gf,i,"f"),c(this,Yf,new Ft,"f"),this.logger=l(p),c(this,Kf,u,"f"),c(this,Bf,s,"f"),c(this,Vf,o,"f"),c(this,Wf,a,"f"),c(this,Hf,d,"f"),c(this,Qf,h,"f"),c(this,Zf,f,"f"),c(this,Xf,m,"f"),c(this,Jf,new em({track:t,statsHandler:h,widStatsAdapter:f,scoresCalculator:m}),"f")}get videoWebRTCStats(){return a(this,Jf,"f").videoWebRTCStats}get audioWebRTCStats(){return a(this,Jf,"f").audioWebRTCStats}get connectionScores(){return a(this,Jf,"f").scores}get logCtx(){return{label:this.getLabel(),id:this.id,kind:this.kind,producerId:this.producerId,paused:this.isPaused,published:this.isPublished}}get observer(){return a(this,Yf,"f")}get mediaStreamTrack(){return a(this,jf,"f")}get originalTrack(){return a(this,Uf,"f")}get id(){return this.mediaStreamTrack.id}get kind(){return this.mediaStreamTrack.kind}get producerId(){var e;return null===(e=this.producer)||void 0===e?void 0:e.id}get isPublished(){return!!this.producer&&!this.producer.closed}get isPaused(){var e,t;return null!==(t=null===(e=this.producer)||void 0===e?void 0:e.paused)&&void 0!==t&&t}get internalEventEmitter(){return a(this,qf,"f")}get network(){return a(this,Wf,"f")}getLabel(){return this.label}setLabel(e){if("string"!=typeof(t=e)||!Object.values(exports.TrackLabel).includes(t))throw this.logger.error("setLabel()",{message:"Invalid track label",label:e}),new Bt("invalid_track_label",new Error(`Invalid track label: ${e}`));var t;this.label=e}setEncoderConfig(e){this.encoderConfig=e}getEncoderConfig(){return this.encoderConfig}setProducer(e){this.producer=e}setStopTrackOnPause(e){this.isPublished||c(this,$f,e,"f")}getProducer(){return this.producer}setOriginalTrack(){c(this,Uf,this.mediaStreamTrack,"f")}closeProducer(){return o(this,arguments,void 0,(function*(e=!0){const t=yield a(this,Kf,"f").lock(zn.CloseProducer);if(!this.producer)return void t();const{producerId:r}=this;r&&(yield a(this,Hf,"f").close(this.getLabel(),r)),this.producer.close(),this.producer=void 0,e&&this.stopMediaStreamTrack(),t()}))}setPriority(e){return o(this,void 0,void 0,(function*(){this.producer?(yield this.producer.setRtpEncodingParameters({priority:e}),this.logger.debug("setPriority()",{label:this.getLabel(),priority:e})):this.logger.debug("setPriority()",{priority:e,reason:"Not published yet"})}))}stopMediaStreamTrack(){this.mediaStreamTrack.stop(),this.mediaStreamTrack.dispatchEvent(new Event("ended")),this.stopOriginalTrack()}stopOriginalTrack(){a(this,Uf,"f")&&(a(this,Uf,"f").stop(),c(this,Uf,void 0,"f"))}buildProduceEncodings(){return[]}produce(e){return o(this,arguments,void 0,(function*({codecOptions:e,preferredCodec:t,transformParams:r,keyFrameRequestDelay:n}){var i,s,o,c;if(!a(this,Vf,"f").canPublish)throw this.logger.error("produce()",{message:"Not enough access to produce"}),new Bt("not_enough_access",new Error("Not enough access to produce"));if(!a(this,Wf,"f").sendTransport)throw this.logger.error("produce()",{message:"Send transport not initialized"}),new Bt("send_transport_not_initialized",new Error("Send transport not initialized"));if(this.producer)throw new Bt("track_already_produced",new Error("Track already produced"));const d=this.getLabel();if([exports.TrackLabel.CameraPreview,exports.TrackLabel.MicrophonePreview].includes(d))throw this.logger.error("produce()",{message:"Cannot produce a preview track",label:d,track:this.logCtx}),new Bt("track_publish_failed",new Error("Cannot produce preview track"));try{yield a(this,Hf,"f").ensureNoPending(this.getLabel()),yield a(this,Wf,"f").ping();const{rtpCapabilities:{codecs:d}}=a(this,Bf,"f").mediasoupDevice,u=null==d?void 0:d.find((e=>e.mimeType.toLowerCase()===`${this.kind}/${t}`)),l=0,p=this.buildProduceEncodings(),h=this.prepareProducerEncodings({codec:u,encodings:p,maxSpatialLayer:p.length-1}),f={trackTransformParams:r,peerId:String(a(this,Vf,"f").id),label:this.getLabel(),maxSpatialLayer:l,encodings:h,codecOptions:e,preferredCodec:t,codec:u,keyFrameRequestDelay:n},m=yield a(this,Wf,"f").sendTransport.produce({track:this.mediaStreamTrack,encodings:h.length?h:void 0,codecOptions:e,codec:u,stopTracks:!1,disableTrackOnPause:!0,zeroRtpOnPause:!0,appData:f});return this.setProducer(m),(null===(s=null===(i=this.producer)||void 0===i?void 0:i.track)||void 0===s?void 0:s.id)!==a(this,jf,"f").id&&(this.logger.info("Producer initialized with old track, updating",{oldTrackId:null===(c=null===(o=this.producer)||void 0===o?void 0:o.track)||void 0===c?void 0:c.id,newTrackId:a(this,jf,"f").id}),yield this.replaceTrack(a(this,jf,"f"))),this.logger.debug("produce()",{track:this.logCtx,encodings:p,codecOptions:e}),m}catch(e){throw(Jn(e)?this.logger.debug.bind(this.logger):this.logger.error.bind(this.logger))("produce()",{error:Vt(e),track:this.logCtx}),new Bt("track_publish_failed",e)}}))}setNetworkProducerMaxSpatialLayer(e,t){return o(this,void 0,void 0,(function*(){yield a(this,Wf,"f").setProducerMaxSpatialLayer(e,t)}))}publish(){return o(this,void 0,void 0,(function*(){yield this.produce({}),this.internalEventEmitter.emit(gn,this)}))}unpublish(){return o(this,arguments,void 0,(function*(e=!0){if(this.producer)try{e&&this.stopMediaStreamTrack(),this.internalEventEmitter.emit(vn,this),this.producer&&(yield this.closeProducer()),this.logger.debug("unpublish()",{track:this.logCtx})}catch(e){this.logger.error("unpublish()",{error:e})}}))}pauseRemoteProducer(e){return o(this,void 0,void 0,(function*(){yield a(this,Wf,"f").pauseRemoteProducer(e)}))}resumeRemoteProducer(e){return o(this,void 0,void 0,(function*(){yield a(this,Wf,"f").resumeRemoteProducer(e)}))}mute(e){return o(this,void 0,void 0,(function*(){const t=yield a(this,Kf,"f").lock(zn.Mute);if(!this.producer)return this.logger.debug("pause()",{message:"Track is not published",track:this.logCtx}),void t();try{if(this.producer.pause(),this.logger.debug("pause()",{track:this.logCtx}),a(this,$f,"f"))return null==e||e(),a(this,jf,"f").stop(),this.stopOriginalTrack(),this.internalEventEmitter.emit(_n,this),void(yield this.pauseRemoteProducer(this.producer.id));yield this.pauseRemoteProducer(this.producer.id),this.internalEventEmitter.emit(yn,this)}catch(e){throw(Jn(e)?this.logger.debug.bind(this.logger):this.logger.error.bind(this.logger))("pause()",{error:Vt(e),track:this.logCtx}),yield a(this,Bf,"f").deleteTrack(this),this.internalEventEmitter.emit(wn,this),new Bt("track_pause_failed",e)}finally{t()}}))}resume(){return o(this,void 0,void 0,(function*(){const e=yield a(this,Kf,"f").lock(zn.Resume);if(!this.producer)return this.logger.debug("resume()",{message:"Track is not published",track:this.logCtx}),void e();try{if(this.logger.debug("resume()",{track:this.logCtx}),a(this,$f,"f"))return yield this.reopenMediaStreamTrack(),yield this.resumeProducer(),void this.internalEventEmitter.emit(En,this);yield this.resumeProducer(),this.internalEventEmitter.emit(bn,this)}catch(e){if(Sf(e)){const t=new Tf(e,a(this,zf,"f"),{errorCode:"track_resume_overconstrained",actual:Cf(a(this,jf,"f"),e.constraint)});throw this.logger.error("resume()",{error:Vt(t),track:this.logCtx}),t}throw(Jn(e)?this.logger.debug.bind(this.logger):this.logger.error.bind(this.logger))("resume()",{error:Vt(e),track:this.logCtx}),new Bt("track_resume_failed",e)}finally{e()}}))}getInfo(){return o(this,void 0,void 0,(function*(){const{width:e,height:t,frameRate:r,aspectRatio:n}=a(this,jf,"f").getSettings();return{trackId:a(this,jf,"f").id,readyState:a(this,jf,"f").readyState,kind:this.kind,label:this.label,width:e,height:t,frameRate:r,aspectRatio:n,paused:this.isPaused,trackOutboundStats:yield this.getStats()}}))}getStats(){return o(this,void 0,void 0,(function*(){var e,t,r,n,i;try{return{producerId:null===(e=this.producer)||void 0===e?void 0:e.id,codec:null===(t=this.producer)||void 0===t?void 0:t.rtpParameters.codecs.find((e=>Pf(e))),dtlsState:null===(i=null===(n=null===(r=this.producer)||void 0===r?void 0:r.rtpSender)||void 0===n?void 0:n.transport)||void 0===i?void 0:i.state,rtcStats:yield this.getOutboundRTPStreamStats()}}catch(e){return void this.logger.debug("getStats()",{error:e})}}))}replaceTrack(e){return o(this,void 0,void 0,(function*(){var t;try{c(this,jf,e,"f"),this.internalEventEmitter.emit(En,this),this.observer.safeEmit("track-changed",{track:e}),yield null===(t=this.producer)||void 0===t?void 0:t.replaceTrack({track:e}),c(this,Jf,new em({track:e,statsHandler:a(this,Qf,"f"),widStatsAdapter:a(this,Zf,"f"),scoresCalculator:a(this,Xf,"f")}),"f")}catch(e){(e instanceof Error&&"InvalidStateError"===e.name?this.logger.debug.bind(this.logger):this.logger.error.bind(this.logger))("replaceTrack()",{error:e})}}))}resumeProducer(){return o(this,void 0,void 0,(function*(){this.producer?(yield this.resumeRemoteProducer(this.producer.id),this.producer.resume()):this.logger.debug("resumeProducer()",{message:"Track not produced yet",track:this.logCtx})}))}reopenMediaStreamTrack(){return o(this,void 0,void 0,(function*(){var e;const t=yield a(this,Gf,"f").createMediaStreamTrack({label:this.label,constraints:a(this,zf,"f")});c(this,jf,t,"f"),yield null===(e=this.producer)||void 0===e?void 0:e.replaceTrack({track:t})}))}prepareProducerEncodings(e){const{encodings:t,codec:r,maxSpatialLayer:n}=e;return t.length?t.length>1&&r&&di(r.mimeType)?[t[n]||t[0]]:t:[]}getOutboundRTPStreamStats(){return o(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>{const r=(...n)=>o(this,[...n],void 0,(function*(n=0){if(!this.producer)throw new Error("Producer is missed");try{const i=yield this.producer.getStats(),s=Array.from(i.values()).find((e=>"outbound-rtp"===e.type));if(!s&&n<5)return void setTimeout((()=>o(this,void 0,void 0,(function*(){return yield r(n+1)}))),150);n>=5&&!s&&t(new Error("OutboundRTPStreamStat not exist")),e(s)}catch(e){t(new Error("Can not get RTCStatsReport")),this.logger.debug("getOutboundRTPStreamStats()",{error:e})}}));r().catch((e=>{this.logger.debug("Error executing getRTCStatsReport",{case:"DefaultBaseTrack",error:Vt(e)})}))}))}))}}var rm,nm,im,sm;jf=new WeakMap,Uf=new WeakMap,Vf=new WeakMap,Bf=new WeakMap,Wf=new WeakMap,Hf=new WeakMap,qf=new WeakMap,zf=new WeakMap,Gf=new WeakMap,Yf=new WeakMap,$f=new WeakMap,Kf=new WeakMap,Jf=new WeakMap,Qf=new WeakMap,Zf=new WeakMap,Xf=new WeakMap;class om extends tm{constructor(e){super(e),this.transformParams={},rm.set(this,void 0),nm.set(this,void 0),im.set(this,void 0),sm.set(this,!1),c(this,nm,e,"f"),c(this,im,e.clientEventEmitter,"f")}get logCtx(){return{label:this.getLabel(),id:this.id,kind:this.kind,producerId:this.producerId,paused:this.isPaused,published:this.isPublished,isEffectsProcessing:this.isEffectsProcessing}}get isEffectsProcessing(){return Boolean(a(this,rm,"f"))}getEncoderConfig(){return this.encoderConfig}getCodecOptions(){var e;return{videoGoogleStartBitrate:null!==(e=this.getEncoderConfig().videoGoogleStartBitrate)&&void 0!==e?e:1e3}}getPreferredCodec(){const{preferredCodec:e}=this.getEncoderConfig();return e||(this.getLabel()===exports.TrackLabel.ScreenVideo?"vp8":"h264")}getEncodings(){var e;return null!==(e=this.getEncoderConfig().encodings)&&void 0!==e?e:xh}buildProduceEncodings(){return this.getEncodings()}setTransformParams(e){this.transformParams=e}setMaxSpatialLayer(e){return o(this,void 0,void 0,(function*(){const t=this.getProducer();t?(yield t.setMaxSpatialLayer(e),this.logger.debug("setMaxSpatialLayer()",{label:this.getLabel(),spatialLayer:e})):this.logger.debug("setMaxSpatialLayer()",{message:"Not produced yet"})}))}getMaxSpatialLayer(){const e=this.getProducer();if(e)return e.maxSpatialLayer;this.logger.debug("getMaxSpatialLayer()",{message:"Not produced yet"})}getEncodedVideoStats(){}enableEffects(){return o(this,void 0,void 0,(function*(){if(!a(this,sm,"f")){c(this,sm,!0,"f");try{if(a(this,rm,"f"))return void this.logger.debug("enableEffects()",{description:"Track is already processed"});if("ended"===this.mediaStreamTrack.readyState)return void this.logger.debug("Track already ended",{case:"enableEffects"});if(!a(this,nm,"f").media.effectsSDKInitialized)return void this.logger.debug("Effects SDK not initialized",{case:"enableEffects"});const e=Date.now();yield this.performEnableEffects();const t=Date.now();this.logger.info("enableEffects() time",{time:(t-e)/1e3}),this.logger.info("enableEffects()",{track:this.logCtx}),a(this,im,"f").emit(ln)}catch(e){this.logger.warn("enableEffects()",{track:this.logCtx,error:Vt(e)}),a(this,im,"f").emit(hn,{cause:"Failed to enable video effects",operation:"enable",error:e}),this.disableEffects().catch((e=>{this.logger.warn("Failed to this.disableEffects() in catch{}",{track:this.logCtx,error:Vt(e)})}))}finally{c(this,sm,!1,"f")}}}))}disableEffects(){return o(this,arguments,void 0,(function*(e=!0){if(a(this,rm,"f"))try{yield this.performDisableEffects(e),this.logger.info("disableEffects()",{track:this.logCtx}),a(this,im,"f").emit(pn)}catch(e){this.logger.warn("disableEffects()",{track:this.logCtx,error:e}),a(this,im,"f").emit(hn,{cause:"Failed to disable video effects",operation:"disable",error:e})}else this.logger.debug("disableEffects()",{description:"Track is not processed"})}))}publish(){return o(this,arguments,void 0,(function*(e={}){var t;const r=yield this.produce({preferredCodec:this.getPreferredCodec(),transformParams:this.transformParams,codecOptions:this.getCodecOptions(),keyFrameRequestDelay:null!==(t=e.keyFrameRequestDelay)&&void 0!==t?t:0});yield this.setupVideoProducer(r),this.internalEventEmitter.emit(gn,this)}))}setupVideoProducer(e){return o(this,void 0,void 0,(function*(){const t=this.buildProduceEncodings(),r=e.rtpSender,n=()=>/Safari/i.test(navigator.userAgent);if(t.length&&r&&n()){const e=r.getParameters();t.forEach((({maxBitrate:t,scaleResolutionDownBy:r},n)=>{e.encodings[n]&&(e.encodings[n].maxBitrate=t,e.encodings[n].scaleResolutionDownBy=r)})),yield r.setParameters(e)}if(t.length&&r&&di(this.getPreferredCodec())&&!n()){const e=t.length>1?[t[0]||t[0]]:t;yield r.setParameters(Object.assign(Object.assign({},r.getParameters()),{encodings:e}))}else yield e.setMaxSpatialLayer(0);yield this.setNetworkProducerMaxSpatialLayer(e.id,0)}))}adjustEncodingPresetToCurrentMaxSpatialLayer(e){return o(this,void 0,void 0,(function*(){var t;if(!di(this.getPreferredCodec()))return;const{rtpSender:r}=null!==(t=this.getProducer())&&void 0!==t?t:{};if(!r)return void this.logger.debug("No rtpSender found in producer to change encodings",{maxSpatialLayer:e,trackId:this.id,producerId:this.producerId});const{encodings:n=[]}=this.getEncoderConfig(),i=n[e];if(!i)return void this.logger.warn("Skipping RTPSender params update. No target encoding found",{initialEncodings:n});this.logger.debug("Adjusting encoding parameters to max spatial layer",{targetEncoding:i,maxSpatialLayer:e});const s=r.getParameters();yield r.setParameters(Object.assign(Object.assign({},s),{encodings:[Object.assign(Object.assign({},s.encodings[0]),i)]}))}))}applyEffects(e){return o(this,void 0,void 0,(function*(){var t;try{!this.isEffectsProcessing&&Object.keys(e).length>0&&(yield this.enableEffects()),null===(t=a(this,rm,"f"))||void 0===t||t.updateEffects(e)}catch(e){a(this,im,"f").emit(hn,{cause:"Failed to apply video effects",operation:"apply",error:e})}}))}resetEffects(){var e;null===(e=a(this,rm,"f"))||void 0===e||e.updateEffects({})}setOnLoadModels(e){var t;null===(t=a(this,rm,"f"))||void 0===t||t.setOnLoadModels(e)}get modelsLoadProgress(){var e,t;return null!==(t=null===(e=a(this,rm,"f"))||void 0===e?void 0:e.modelsLoadProgress)&&void 0!==t?t:0}pause(){return o(this,void 0,void 0,(function*(){yield this.mute((()=>{var e;a(this,rm,"f")&&(null===(e=a(this,rm,"f"))||void 0===e||e.stopProcessing(),c(this,rm,void 0,"f"))}))}))}performEnableEffects(){return o(this,void 0,void 0,(function*(){const{media:e}=a(this,nm,"f");c(this,rm,yield e.createEffectsSDKTrackProcessor(this.getLabel()),"f"),a(this,rm,"f").setOnRuntimeError((e=>{a(this,im,"f").emit(hn,{cause:`Video effects runtime error: ${e.message}`,operation:"runtime",error:e})})),this.setOriginalTrack();const t=a(this,rm,"f").processTrack(this.mediaStreamTrack);yield this.replaceTrack(t)}))}performDisableEffects(e){return o(this,void 0,void 0,(function*(){var t;null===(t=a(this,rm,"f"))||void 0===t||t.stopProcessing(),c(this,rm,void 0,"f"),e&&this.originalTrack&&(yield this.replaceTrack(this.originalTrack))}))}}var am,cm;rm=new WeakMap,nm=new WeakMap,im=new WeakMap,sm=new WeakMap,n([Xh(1e4,"DefaultVideoTrack.enableEffects"),s("design:type",Function),s("design:paramtypes",[]),s("design:returntype",Promise)],om.prototype,"performEnableEffects",null),n([Xh(1e4,"DefaultVideoTrack.disableEffects"),s("design:type",Function),s("design:paramtypes",[Boolean]),s("design:returntype",Promise)],om.prototype,"performDisableEffects",null);let dm=cm=class{constructor(e){am.set(this,void 0),c(this,am,e("MediaStreamTrackManager"),"f")}createMediaStreamTrack(e){return o(this,arguments,void 0,(function*({label:e,constraints:t}){if(cm.isDisplayMedia(e)){const[e]=yield this.createDisplayMediaTracks(t);return e}const[r]=yield this.createUserMediaTracks(t);return r}))}static isDisplayMedia(e){return[exports.TrackLabel.ScreenVideo,exports.TrackLabel.ScreenAudio].includes(e)}createUserMediaTracks(e){return o(this,void 0,void 0,(function*(){try{const t=yield navigator.mediaDevices.getUserMedia(e);return a(this,am,"f").debug("createUserMediaTracks() stream created",{streamId:t.id}),t.getTracks()}catch(t){if(Sf(t)){throw new Tf(t,e,{errorCode:"create_track_overconstrained"})}throw t}}))}createDisplayMediaTracks(e){return o(this,void 0,void 0,(function*(){try{const t=yield navigator.mediaDevices.getDisplayMedia(e);return a(this,am,"f").debug("getDisplayMediaTracks() stream created",{streamId:t.id}),t.getTracks()}catch(t){if(Sf(t)){throw new Tf(t,e,{errorCode:"create_screen_track_overconstrained"})}throw t}}))}};am=new WeakMap,dm=cm=n([ot(),i(0,ct(mi.LoggerFactory)),s("design:paramtypes",[Function])],dm);var um,lm,pm,hm,fm,mm,gm,vm=dm;let ym=class{constructor(e,t,r,n,i,s,o,a,d,u){this.config=e,this.loggerFactory=t,this.audioTrackFactory=r,this.clientEventEmitter=n,this.integrationsService=i,this.processorsCache=s,this.videoTrackFactory=o,this.encodedVideoTrackFactory=a,this.mediaStreamTrackManager=d,this.signalingApiClient=u,this.isDeviceLoaded=!1,this.tracks=new Map,um.set(this,void 0),lm.set(this,null),pm.set(this,!1),hm.set(this,new Map),fm.set(this,!1),mm.set(this,!1),gm.set(this,void 0);const l=this.config.get("effectsSDKParams");c(this,gm,this.config.get("denoiser"),"f"),c(this,um,this.loggerFactory("Media"),"f"),c(this,lm,null!=l?l:null,"f")}get mediasoupDevice(){var e;return null!==(e=this.device)&&void 0!==e||(this.device=this.createDevice()),this.device}get effectsSDKInitialized(){return a(this,pm,"f")}get effectsSDKParams(){return a(this,lm,"f")}getTrackByLabel(e){return Array.from(this.tracks.values()).find((t=>t.getLabel()===e))}loadDevice(e){return o(this,void 0,void 0,(function*(){this.isDeviceLoaded||(yield this.mediasoupDevice.load({routerRtpCapabilities:e}),this.isDeviceLoaded=!0)}))}getTrackCodec(e){const{rtpCapabilities:t,rtpCapabilities:{codecs:r}}=this.mediasoupDevice;if(r)return r.find((t=>t.mimeType.toLowerCase()===`${e.kind}/${e.getPreferredCodec()}`));a(this,um,"f").error("getTrackCodec()",{label:e.getLabel,rtpCapabilities:t})}createTracks({constraints:e,mediaStreamTracks:t},r=!1){return t.map((t=>{const n={mediaStreamTrack:t,constraints:e};let i;return i="audio"===t.kind?this.audioTrackFactory(Object.assign(Object.assign({},n),{loggerNamespace:"AudioTrack"})):r?this.encodedVideoTrackFactory(Object.assign(Object.assign({},n),{loggerNamespace:"EncodedVideoTrack"})):this.videoTrackFactory(Object.assign(Object.assign({},n),{loggerNamespace:"VideoTrack"})),a(this,um,"f").debug("createTrack() track created",{trackId:i.id,kind:i.kind}),i}))}createUserMediaTracks(e){return o(this,void 0,void 0,(function*(){const t=yield this.mediaStreamTrackManager.createUserMediaTracks(e);return this.createTracks({constraints:e,mediaStreamTracks:t})}))}createDisplayMediaTracks(e){return o(this,arguments,void 0,(function*(e,t=!1){const r=yield this.mediaStreamTrackManager.createDisplayMediaTracks(e);return this.createTracks({constraints:e,mediaStreamTracks:r},t)}))}createCustomMediaTrack(e,t,r=!1){return this.createTracks({constraints:t,mediaStreamTracks:[e]},r)[0]}deleteTrack(e){return o(this,void 0,void 0,(function*(){if(!this.tracks.has(e.id))return;const t={trackId:e.id,label:e.getLabel(),producerId:e.producerId};try{"disableNoiseSuppression"in e&&(yield e.disableNoiseSuppression()),"disableEffects"in e&&(yield e.disableEffects(!1))}catch(e){a(this,um,"f").debug("deleteTrack() disable effects error",Object.assign({error:e},t))}try{this.tracks.delete(e.id),e.stopMediaStreamTrack(),yield e.closeProducer()}catch(e){(e instanceof Yn?a(this,um,"f").debug.bind(a(this,um,"f")):a(this,um,"f").error.bind(a(this,um,"f")))("deleteTrack()",{error:e})}finally{a(this,um,"f").debug("deleteTrack()",t)}}))}getAllTracks(){return Array.from(this.tracks.values())}publishedTracks(){return this.getAllTracks().filter((e=>e.isPublished))}clearTracks(){try{this.getAllTracks().forEach((e=>e.stopMediaStreamTrack()))}catch(e){a(this,um,"f").debug("clearTracks() error",{error:e})}finally{this.tracks.clear()}}unpublishTracks(){return o(this,void 0,void 0,(function*(){try{yield Promise.all(this.publishedTracks().map((e=>o(this,void 0,void 0,(function*(){return yield e.unpublish(!1)})))))}catch(e){(Jn(e)?a(this,um,"f").debug.bind(a(this,um,"f")):a(this,um,"f").warn.bind(a(this,um,"f")))("unpublishTracks()",{error:e})}}))}setTrack(e){this.tracks.set(e.id,e)}initEffectsSDK(){return o(this,void 0,void 0,(function*(){if(a(this,pm,"f"))return!0;if(!a(this,lm,"f"))throw a(this,um,"f").error("Effects SDK config params not provided",{case:"initEffectsSDK"}),new Bt("effects_sdk_config_missing",new Error("Effects SDK config not provided"));const e=(e,t)=>o(this,void 0,void 0,(function*(){if(!window.tsvb)return a(this,um,"f").info("Effects SDK not loaded, skipping initialization",{case:"initEffectsSDK"}),void e(!1);a(this,um,"f").debug("Effects SDK initializing",{case:"initEffectsSDK"});try{a(this,hm,"f").set(exports.TrackLabel.Camera,yield this.createEffectsSDKTrackProcessor(exports.TrackLabel.Camera)),a(this,hm,"f").set(exports.TrackLabel.CameraPreview,yield this.createEffectsSDKTrackProcessor(exports.TrackLabel.CameraPreview)),c(this,pm,!0,"f"),a(this,um,"f").info("Effects SDK initialized",{case:"initEffectsSDK"}),e(!0)}catch(e){a(this,um,"f").error("Failed to initialize Effects SDK",{error:e,case:"initEffectsSDK"}),t(e)}}));return yield new Promise(((t,r)=>{if(!window.tsvb)return a(this,um,"f").debug("Effects SDK tsvb-web.js is not ready, waiting",{case:"initEffectsSDK"}),void window.addEventListener("load",(()=>o(this,void 0,void 0,(function*(){return yield e(t,r)}))));e(t,r).catch((e=>{a(this,um,"f").error("Failed to execute init() in initEffectsSDK",{error:Vt(e)})}))}))}))}initDenoiser(e,t){return o(this,void 0,void 0,(function*(){if(!a(this,fm,"f"))try{c(this,fm,!0,"f"),this.clientEventEmitter.emit(sn,!0);try{yield this.integrationsService.audio.waitForInitialization}catch(e){"asdk"===a(this,gm,"f")&&(c(this,mm,!0,"f"),c(this,gm,"rnnoise","f"),this.config.set("denoiser",a(this,gm,"f")),a(this,um,"f").debug("Set config to rnnoise denoiser",{case:"Denoiser",error:Vt(e),type:this.config.get("denoiser")}),this.clientEventEmitter.emit(dn),this.integrationsService.init(),yield this.integrationsService.audio.waitForInitialization)}a(this,um,"f").debug("Denoiser initialized, activating",{case:"Denoiser",type:this.integrationsService.audio.type,trackLabel:e.getLabel()});const r=e,n=this.processorsCache.get(a(this,gm,"f"),exports.TrackLabel.Microphone);if(!n)return void a(this,um,"f").error("No cached trackProcessor found",{case:"Denoiser",trackLabel:e.getLabel(),type:this.integrationsService.audio.type});"asdk"===n.type&&n.setOnError(((r,n)=>{this.clientEventEmitter.emit(sn,!0),this.fallbackToRNoise(e,{reason:r,options:t,error:n}).catch((t=>{a(this,um,"f").error("Failed to fallback to RNNoise through onError",{case:"Denoiser",type:a(this,gm,"f"),error:Vt(t),label:e.getLabel()})})).then((()=>{this.clientEventEmitter.emit(sn,!1)})).catch((()=>{}))})),r.setTrackProcessor(n),a(this,um,"f").debug("Denoiser trackProcessor set, check if activation is needed",{case:"Denoiser",type:a(this,gm,"f"),shouldEnableDenoiser:null==t?void 0:t.noiseSuppression,trackLabel:e.getLabel()}),(null==t?void 0:t.noiseSuppression)&&(yield e.enableNoiseSuppression())}catch(r){if(a(this,um,"f").warn("Failed to start noise suppression, featured original track",{case:"Denoiser",type:a(this,gm,"f"),error:Vt(r),label:e.getLabel()}),"asdk"===a(this,gm,"f"))try{a(this,um,"f").warn("Fallback to RNNoise",{error:Vt(r)}),yield this.fallbackToRNoise(e,{options:t,reason:"ASDK init error",error:r})}catch(t){a(this,um,"f").error("Failed to fallback to RNNoise through catch",{case:"Denoiser",type:a(this,gm,"f"),error:Vt(t),label:e.getLabel()})}}finally{this.clientEventEmitter.emit(sn,!1),c(this,fm,!1,"f")}}))}fallbackToRNoise(e,t){return o(this,void 0,void 0,(function*(){var r;if(a(this,mm,"f"))return;if(c(this,mm,!0,"f"),"rnnoise"===a(this,gm,"f"))return;this.clientEventEmitter.emit(dn),a(this,um,"f").warn("Fallback to RNNoise",{reason:null==t?void 0:t.reason,error:Vt(null==t?void 0:t.error),case:"Denoiser"});const n=e;yield n.disableNoiseSuppression(),n.unsetTrackProcessor(),c(this,gm,"rnnoise","f"),this.config.set("denoiser",a(this,gm,"f")),a(this,um,"f").debug("Set config to rnnoise denoiser",{case:"Denoiser",type:this.config.get("denoiser")}),this.integrationsService.init(),yield this.integrationsService.audio.waitForInitialization;const i=this.processorsCache.get(a(this,gm,"f"),exports.TrackLabel.Microphone);i?(n.setTrackProcessor(i),(null===(r=null==t?void 0:t.options)||void 0===r?void 0:r.noiseSuppression)&&(yield n.enableNoiseSuppression())):a(this,um,"f").error("No cached trackProcessor found",{case:"Denoiser",trackLabel:e.getLabel(),type:this.integrationsService.audio.type})}))}createEffectsSDKTrackProcessor(e){return o(this,void 0,void 0,(function*(){var t,r,n;if(e){const t=a(this,hm,"f").get(e);if(t)return t}if(!a(this,lm,"f"))throw a(this,um,"f").error("Effects SDK config params not provided",{case:"initEffectsSDK"}),new Bt("effects_sdk_config_missing",new Error("Effects SDK config not provided"));const i=new Ef({loggerFactory:this.loggerFactory,customerId:null===(t=this.config.get("effectsSDKParams"))||void 0===t?void 0:t.customerId,sdk_url:null===(r=this.config.get("effectsSDKParams"))||void 0===r?void 0:r.sdk_url,api_url:null===(n=this.config.get("effectsSDKParams"))||void 0===n?void 0:n.api_url,config:this.config});return yield i.init(),a(this,um,"f").info("Track effects processor initialized",{trackLabel:e}),i}))}handleProducerSetMaxSpatialLayer(e){return o(this,arguments,void 0,(function*({producerId:e,spatialLayer:t}){const r=this.getAllTracks().find((t=>{var r;return(null===(r=t.getProducer())||void 0===r?void 0:r.id)===e}));if(!r)return void a(this,um,"f").warn("producerRequestMaxSpatialLayer()",{message:"Producer not found"});if(!(r instanceof om))return void a(this,um,"f").warn("producerRequestMaxSpatialLayer()",{message:"Wrong producer kind"});const n=null!=t?t:Vh,i=r.getMaxSpatialLayer();i!==n?(r.getEncodings().length>1&&(yield r.setMaxSpatialLayer(n)),yield this.signalingApiClient.producer.setProducerMaxSpatialLayer(e,{maxSpatialLayer:n}),yield r.adjustEncodingPresetToCurrentMaxSpatialLayer(n)):a(this,um,"f").debug("producerRequestMaxSpatialLayer()",{message:"Skip set max spatial layer",requestedSpatialLayer:n,currentMaxSpatialLayer:i})}))}static getVideoTrackTransformParams(e){var t,r;const n=e.getSettings();return{width:null!==(t=n.width)&&void 0!==t?t:Uh.width,height:null!==(r=n.height)&&void 0!==r?r:Uh.height}}static getScreenVideoTrackParams(e){var t,r;return{videoTrackOptions:null!==(t=null==e?void 0:e.video)&&void 0!==t?t:{frameRate:{max:20},width:{max:Uh.width},height:{max:Uh.height}},encoderConfig:null!==(r=null==e?void 0:e.videoEncoderConfig)&&void 0!==r?r:{encodings:Fh}}}static getCameraVideoTrackParams(e){var t,r;return{videoTrackOptions:null!==(t=null==e?void 0:e.video)&&void 0!==t?t:{frameRate:{max:24},width:{max:Uh.width},height:{max:Uh.height}},encoderConfig:null!==(r=null==e?void 0:e.encoderConfig)&&void 0!==r?r:{encodings:xh}}}createDevice(){const e=(e=>{const t=null!=e?e:null===navigator||void 0===navigator?void 0:navigator.userAgent;if(!t)return;const r=ti.getParser(t);return r.satisfies({"yandex browser":">=25"})&&"iOS"===r.getOSName()?void 0:r.satisfies({"yandex browser":">=23.7"})?"Chrome111":r.satisfies({"yandex browser":">=22"})?"Chrome74":r.satisfies({"Samsung Internet for Android":">=17"})?"Chrome111":void 0})();return a(this,um,"f").debug("Creating a media device",{handlerName:null!=e?e:"not specified"}),new fd.Device({handlerName:e})}};um=new WeakMap,lm=new WeakMap,pm=new WeakMap,hm=new WeakMap,fm=new WeakMap,mm=new WeakMap,gm=new WeakMap,ym=n([ot(),i(0,ct(mi.Config)),i(1,ct(mi.LoggerFactory)),i(2,ct(mi.AudioTrackFactory)),i(3,ct(mi.ClientEventEmitter)),i(4,ct(mi.IntegrationsService)),i(5,ct(mi.ProcessorsCache)),i(6,ct(mi.VideoTrackFactory)),i(7,ct(mi.EncodedVideoTrackFactory)),i(8,ct(mi.MediaStreamTrackManager)),i(9,ct(mi.SignalingApiClient)),s("design:paramtypes",[Et,Function,Function,Ft,Zh,Kh,Function,Function,vm,rd])],ym);var bm=ym;const _m={[cs.PRODUCER_KIND_VIDEO]:"video",[cs.PRODUCER_KIND_AUDIO]:"audio"},Em={[ps.PEER_ROLE_HOST]:"host",[ps.PEER_ROLE_AUDIENCE]:"audience"},wm={[Xi.PRODUCER_LABEL_CAMERA]:exports.TrackLabel.Camera,[Xi.PRODUCER_LABEL_MICROPHONE]:exports.TrackLabel.Microphone,[Xi.PRODUCER_LABEL_SCREEN_VIDEO]:exports.TrackLabel.ScreenVideo,[Xi.PRODUCER_LABEL_SCREEN_AUDIO]:exports.TrackLabel.ScreenAudio,[Xi.PRODUCER_LABEL_CUSTOM_VIDEO]:exports.TrackLabel.CustomVideo,[Xi.PRODUCER_LABEL_CUSTOM_AUDIO]:exports.TrackLabel.CustomAudio,[Xi.PRODUCER_LABEL_UNKNOWN]:exports.TrackLabel.Unknown,[Xi.PRODUCER_LABEL_UNSPECIFIED]:exports.TrackLabel.Unknown},Sm={[Zi.PEER_GROUP_MODERATOR]:"moderator",[Zi.PEER_GROUP_USER]:"user"},Cm=e=>{const t=_m[e];if(!t)throw new Error(`Unknown producer kind: ${e}`);return t},Tm=e=>{const t=Sm[e];if(!t)throw new Error(`Unknown peer group: ${e}`);return t},Pm=e=>{const t=wm[e];if(!t)throw new Error(`Unknown producer label: ${e}`);return t},Rm=e=>{const t=Em[e];if(!t)throw new Error(`Unknown peer role: ${e}`);return t},km=e=>({id:e.id,channelIds:e.channelIds,groups:e.groups.map(Tm),producePermissions:e.producePermissions.map(Pm),appId:e.appId,producers:e.producers.map(Dm),uid:e.uid,appData:e.appData,role:Rm(e.role),loginDate:e.loginDate}),Dm=e=>{var t;return{id:e.id,kind:Cm(e.kind),label:Pm(e.label),peerId:e.peerId,paused:e.paused,encodings:e.encodings,maxSpatialLayer:null!==(t=e.maxSpatialLayer)&&void 0!==t?t:0}},Im=e=>{switch(e){case"moderator":return Zi.PEER_GROUP_MODERATOR;case"user":return Zi.PEER_GROUP_USER;default:return Zi.PEER_GROUP_UNSPECIFIED}};var Am;let Om=class{constructor(e,t,r,n,i,s,o){this.network=e,this.media=t,this.myPeer=r,this.eventsQueue=n,this.clientEventEmitter=i,this.peers=s,Am.set(this,void 0),c(this,Am,o("ChannelStateSyncEventHandler"),"f"),this.debouncedTriggerChannelStateEvent=ii(this.triggerChannelStateEvent.bind(this),3e3),this.watchNetworkState()}handleChannelStateEvent(e){return o(this,void 0,void 0,(function*(){this.network.peersLoaded?yield this.restoreState(e):this.loadChannelState(e),this.clientEventEmitter.emit(on)}))}watchNetworkState(){this.clientEventEmitter.on(rn,(()=>{this.debouncedTriggerChannelStateEvent()}))}triggerChannelStateEvent(){return o(this,void 0,void 0,(function*(){const e=()=>o(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>o(this,void 0,void 0,(function*(){const r=yield this.network.triggerChannelStateEvent("host"),n=setTimeout((()=>{this.eventsQueue.isMessageReceived(r)?(a(this,Am,"f").info("Channel state event received",{case:"ChannelStateSynchronizer.triggerChannelStateEvent"}),e()):t(new Error("Channel state event not received"))}),5e3),i=()=>{clearTimeout(n),this.clientEventEmitter.off(tn,i),e()};this.clientEventEmitter.on(tn,i)}))))}));try{yield fi(e,{maxRetries:5,actionName:"triggerChannelStateEventWithRetry",logger:a(this,Am,"f")})}catch(e){(Jn(e)?a(this,Am,"f").debug.bind(a(this,Am,"f")):a(this,Am,"f").warn.bind(a(this,Am,"f")))("Failed to trigger channel state event",{case:"ChannelStateSynchronizer.triggerChannelStateEvent",error:Vt(e)})}}))}loadChannelState(e){a(this,Am,"f").info("Loading channel state",{case:"loadChannelState"});try{const t=this.peers.hosts().map((e=>e.shortData)),r=e.peers.filter((e=>e.role===ps.PEER_ROLE_HOST));this.setMissingPeers(t,r),this.restoreLocalPeersState(r),this.network.peersLoaded=!0}catch(e){a(this,Am,"f").error("Failed to load channel state",{case:"loadState",error:Vt(e)})}}restoreState(e){return o(this,void 0,void 0,(function*(){const{peers:t}=e,r={missingPeers:[],removedPeers:[],missingProducers:[],removedProducers:[],fixedProducersState:[],fixedConsumersState:[],restoredAppDataPeers:[]};try{if(!this.network.isNetworkActive)return a(this,Am,"f").info("Connection inactive, skipping restore local state",{case:"restoreLocalState"}),r;a(this,Am,"f").info("Restoring local state",{case:"restoreLocalState"});const e=this.peers.hosts().map((e=>e.shortData)),n=t.filter((e=>e.role===ps.PEER_ROLE_HOST)),{removedProducers:i,fixedProducersState:s}=yield this.restoreRemoteProducersState(n);r.fixedProducersState.push(...s),r.removedProducers.push(...i),r.removedPeers.push(...this.removeUnnecessaryPeers(e,n)),r.missingPeers.push(...this.setMissingPeers(e,n));const o=this.restoreLocalPeersState(n);return r.missingProducers.push(...o.missingProducers),r.removedProducers.push(...o.removedProducers),r.restoredAppDataPeers.push(...o.restoredAppDataPeers),r.fixedProducersState.push(...o.fixedProducersState),r.fixedConsumersState.push(...o.fixedConsumersState),r}catch(e){return a(this,Am,"f").info("Failed to restore local state",{case:"restoreLocalState",error:Vt(e)}),r}}))}restoreRemoteProducersState(e){return o(this,void 0,void 0,(function*(){const t={removedProducers:[],fixedProducersState:[]},r=this.myPeer.get(),n=e.find((e=>e.id===this.myPeer.id));if(!r||!n)return t;const i=new Map;this.media.getAllTracks().forEach((e=>{e.producerId&&i.set(e.producerId,e)}));const s=new Set(i.keys()),c=n.producers.filter((e=>!s.has(e.id)));yield Promise.all(c.map((e=>o(this,void 0,void 0,(function*(){yield this.network.closeRemoteProducer(e.id),r.producers.delete(e.id),t.removedProducers.push(e.id),a(this,Am,"f").info("Unnecessary local producer closed",{case:"restoreLocalState",removedProducerId:e.id,removedProducerPeerId:e.peerId})})))));const d=[];for(const e of n.producers){const t=i.get(e.id);t&&(t.isPaused!==e.paused&&d.push({cp:e,localTrack:t}))}return yield Promise.all(d.map((e=>o(this,[e],void 0,(function*({cp:e,localTrack:r}){r.isPaused?yield this.network.pauseRemoteProducer(e.id):yield this.network.resumeRemoteProducer(e.id),t.fixedProducersState.push(e.id),e.paused=r.isPaused,a(this,Am,"f").info("Remote producer state repaired",{case:"restoreLocalState",removedProducerId:e.id,removedProducerPeerId:e.peerId,paused:r.isPaused})}))))),t}))}removeUnnecessaryPeers(e,t){const r=[];return e.filter((e=>!t.find((t=>t.id===e.id)))).forEach((e=>{this.peers.remove(e.id).catch((e=>{a(this,Am,"f").error("Failed to remove peer",{error:Vt(e)})})),r.push(e.id),a(this,Am,"f").info("Unnecessary peer removed",{case:"restoreLocalState",removedPeerId:e.id})})),r}setMissingPeers(e,t){const r=[];return t.forEach((t=>{if(e.find((e=>e.id===t.id)))return;const n=this.peers.add(km(t));r.push(n.id),a(this,Am,"f").info("Missing peer added to storage",{case:"restoreLocalState",peerId:t.id})})),r}restoreLocalPeersState(e){const t=new Map(e.map((e=>[e.id,e]))),r=this.peers.hosts(),n={removedProducers:[],missingProducers:[],restoredAppDataPeers:[],fixedConsumersState:[],fixedProducersState:[]};return r.forEach((e=>{const r=t.get(e.id);if(!r)return void a(this,Am,"f").info("Found new local peer, skip restoring state",{case:"restoreLocalState",newPeerId:e.id});n.removedProducers.push(...this.removeUnnecessaryProducers(e,r));this.restoreAppData(e,r)&&n.restoredAppDataPeers.push(e.id);const{fixedProducersState:i,fixedConsumersState:s,missingProducers:o}=this.restoreTracksState(e,r);n.fixedProducersState.push(...i),n.fixedConsumersState.push(...s),n.missingProducers.push(...o)})),a(this,Am,"f").info("Peers state restored",{case:"restoreLocalState"}),n}removeUnnecessaryProducers(e,t){const r=[];return e.getProducers().filter((e=>!t.producers.find((t=>t.id===e.id)))).forEach((t=>{e.observer.safeEmit(xn,t),r.push(t.id),a(this,Am,"f").info("Unnecessary producer removed",{case:"restoreLocalState",removedProducerId:t.id,removedProducerPeerId:t.peerId})})),r}restoreTracksState(e,t){const r={missingProducers:[],fixedProducersState:[],fixedConsumersState:[]};return t.producers.forEach((t=>{var n;const i=e.producers.get(t.id);if(!i)return e.observer.safeEmit(Ln,Dm(t)),r.missingProducers.push(t.id),void a(this,Am,"f").info("Missing producer added to storage",{case:"restoreLocalState",producerId:t.id,producerPeerId:t.peerId});const{paused:s}=t;if(i.paused!==s){i.setPaused(s);const n=i.paused?Tn:Pn;e.observer.safeEmit(n,{producerId:i.id,kind:i.kind,label:i.label,paused:i.paused}),r.fixedProducersState.push(t.id),a(this,Am,"f").info("Producer state fixed",{case:"restoreLocalState",producerId:t.id,producerPeerId:t.peerId})}const o=e.tracks.get(i.label);if((null==o?void 0:o.consumerId)&&(null===(n=o.consumer)||void 0===n?void 0:n.paused)!==t.paused){const{consumerId:n}=o,s=i.paused?Vn:Bn;e.observer.safeEmit(s,n),r.fixedConsumersState.push(n),a(this,Am,"f").info("Consumer state fixed",{case:"restoreLocalState",consumerId:n,consumerProducerId:t.id,consumerProducerPeerId:t.peerId})}})),r}restoreAppData(e,t){return!ni(e.appData,t.appData)&&(e.observer.emit(Br,t.appData),a(this,Am,"f").info("Application data restored",{case:"restoreLocalState",peerId:e.id,appData:t.appData}),!0)}};Am=new WeakMap,Om=n([ot(),i(0,ct(mi.Network)),i(1,ct(mi.Media)),i(2,ct(mi.MyPeer)),i(3,ct(mi.EventsQueue)),i(4,ct(mi.ClientEventEmitter)),i(5,ct(mi.Peers)),i(6,ct(mi.LoggerFactory)),s("design:paramtypes",[po,bm,io,ro,Ft,mo,Function])],Om);var Mm,Nm=Om;let Lm=class{constructor(e,t,r,n,i){this.peers=e,this.clientEventEmitter=t,this.channelStateSyncEventHandler=n,this.channelStateSynchronizer=i,Mm.set(this,void 0),c(this,Mm,r("ChannelEvents"),"f")}handleChannelEvent(e){return o(this,void 0,void 0,(function*(){switch(e.eventType){case Cs.CHANNEL_EVENT_TYPE_CHANNEL_STATE:yield this.handleChannelState(e);break;case Cs.CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT:this.handleChannelStateShort(e);break;case Cs.CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT:this.handleChannelManagementEvent(e);break;case Cs.CHANNEL_EVENT_TYPE_PEER_JOINED:this.handlePeerJoined(e);break;case Cs.CHANNEL_EVENT_TYPE_PEER_LEFT:this.handlePeerLeft(e);break;case Cs.CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED:this.handlePeerAppDataChanged(e);break;case Cs.CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED:this.handlePeerGroupsChanged(e);break;case Cs.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED:this.handleChannelActivityConfirmationAcquired();break;case Cs.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED:this.handleChannelActivityConfirmationExpired();break;case Cs.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED:this.handleChannelActivityConfirmationRequired(e);break;case Cs.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED:this.handleChannelProducePermissionsChanged(e);break;case Cs.CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED:this.handlePeerProducePermissionsChanged(e);break;case Cs.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED:this.handleChannelProducePermissionsDeleted(e);break;default:throw new Error(`Unsupported event type: ${e.eventType}`)}}))}handleChannelManagementEvent(e){if(!e.channelManagementEvent)throw new Error("Missing channelManagementEvent in CHANNEL_MANAGEMENT_EVENT");const t=e.channelManagementEvent.event;if(t.eventName===nn)return this.clientEventEmitter.safeEmit(nn),void a(this,Mm,"f").debug("New forced disconnect event",{event:t});this.clientEventEmitter.safeEmit(Wr,t),a(this,Mm,"f").debug("New channel event",{event:t})}handlePeerJoined(e){if(!e.peer)throw new Error("Missing peer in PEER_APP_DATA_CHANGED event");const t=this.peers.add(km(e.peer));a(this,Mm,"f").debug("Peer joined to the channel",{peer:no(t)})}handlePeerLeft(e){if(!e.peer)throw new Error("Missing peer in PEER_LEFT event");this.peers.remove(e.peer.id).catch((e=>{a(this,Mm,"f").debug("Failed to remove peer",{error:Vt(e)})})),a(this,Mm,"f").debug("Peer left the channel",{peerId:e.peer.id})}handleChannelState(e){return o(this,void 0,void 0,(function*(){if(!e.channelState)throw new Error("Missing channelState in CHANNEL_STATE event");try{yield this.channelStateSynchronizer.handleChannelStateEvent(e.channelState)}catch(e){a(this,Mm,"f").error("Failed to restore channel state",{case:"restoreLocalState",error:Vt(e)})}}))}handleChannelStateShort(e){if(!e.channelStateShort)throw new Error("Missing channelStateShort in CHANNEL_STATE_SHORT event");this.channelStateSyncEventHandler.handleChannelStateShort(e.channelStateShort).catch((e=>{a(this,Mm,"f").error("Failed to handle channel state short event",{error:Vt(e)})}))}handlePeerAppDataChanged(e){if(!e.peer)throw new Error("Missing peer in PEER_APP_DATA_CHANGED event");const t=this.peers.get(e.peer.id);t&&t.observer.emit(Br,e.peer.appData)}handlePeerGroupsChanged(e){if(!e.peer)throw new Error("Missing peer in PEER_GROUP_CHANGED event");const t=this.peers.get(e.peer.id);null==t||t.handleGroupsChange(e.peer.groups.map(Tm))}handleChannelActivityConfirmationExpired(){this.clientEventEmitter.safeEmit(Yr),a(this,Mm,"f").info("Notify the channel that it has disconnected due to the activity confirmation expiring",{})}handleChannelActivityConfirmationAcquired(){this.clientEventEmitter.safeEmit(Gr),a(this,Mm,"f").info("Notify the channel that the activity has been acquired.",{})}handleChannelActivityConfirmationRequired(e){if(!e.channelActivityConfirmationTime)throw new Error("Missing channelActivityConfirmationTime in CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED event");const t=e.channelActivityConfirmationTime;this.clientEventEmitter.safeEmit(zr,t),a(this,Mm,"f").info("Notify the channel that activity confirmation is required",{event:e.channelActivityConfirmationTime})}handleChannelProducePermissionsChanged(e){if(!e.channelProducePermissions)throw new Error("Missing channelProducePermissions in CHANNEL_PRODUCE_PERMISSIONS_CHANGED event");const{groups:t}=e.channelProducePermissions,r=this.peers.all().filter((e=>e.groups.some((e=>t.includes(Im(e)))))),n=e.channelProducePermissions.producePermissions.map(Pm),i=e.channelProducePermissions.changedProducePermissions.map(Pm);r.forEach((e=>{const t=Array.from(new Set([...e.producePermissions,...i])).filter((e=>!i.includes(e)||n.includes(e)));e.handleProducePermissionsChange(t)})),a(this,Mm,"f").info("Peers changed produce permissions",{groups:t,producePermissions:n})}handlePeerProducePermissionsChanged(e){if(!e.peer)throw new Error("Missing peer in PEER_PRODUCE_PERMISSIONS_CHANGED event");const t=this.peers.get(e.peer.id);if(!t)return;const r=e.peer.producePermissions.map(Pm);t.handleProducePermissionsChange(r)}handleChannelProducePermissionsDeleted(e){if(!e.channelProducePermissions)throw new Error("Missing channelProducePermissions in CHANNEL_PRODUCE_PERMISSIONS_DELETED event");const{groups:t}=e.channelProducePermissions,r=this.peers.all().filter((e=>e.groups.some((e=>t.includes(Im(e)))))),n=e.channelProducePermissions.producePermissions.map(Pm);r.forEach((e=>{const t=e.producePermissions.filter((e=>!n.includes(e)));e.handleProducePermissionsChange(t)})),a(this,Mm,"f").info("Peers deleted produce permissions",{groups:t,producePermissions:n})}};Mm=new WeakMap,Lm=n([ot(),i(0,ct(mi.Peers)),i(1,ct(mi.ClientEventEmitter)),i(2,ct(mi.LoggerFactory)),i(3,ct(mi.ChannelStateSyncEventHandler)),i(4,ct(mi.ChannelStateSynchronizer)),s("design:paramtypes",[mo,Ft,Function,hd,Nm])],Lm);var xm=Lm,Fm={},jm=u&&u.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(Fm,"__esModule",{value:!0});var Um=Fm.AwaitQueue=class{constructor({ClosedErrorClass:e=Error,StoppedErrorClass:t=Error,RemovedTaskErrorClass:r=Error}={ClosedErrorClass:Error,StoppedErrorClass:Error,RemovedTaskErrorClass:Error}){this.closed=!1,this.pendingTasks=[],this.ClosedErrorClass=Error,this.StoppedErrorClass=Error,this.RemovedTaskErrorClass=Error,this.ClosedErrorClass=e,this.StoppedErrorClass=t,this.RemovedTaskErrorClass=r}get size(){return this.pendingTasks.length}close(){if(!this.closed){this.closed=!0;for(const e of this.pendingTasks)e.stopped=!0,e.reject(new this.ClosedErrorClass("AwaitQueue closed"));this.pendingTasks.length=0}}push(e,t){return jm(this,void 0,void 0,(function*(){if(this.closed)throw new this.ClosedErrorClass("AwaitQueue closed");if("function"!=typeof e)throw new TypeError("given task is not a function");if(!e.name&&t)try{Object.defineProperty(e,"name",{value:t})}catch(e){}return new Promise(((r,n)=>{const i={task:e,name:t,resolve:r,reject:n,stopped:!1,enqueuedAt:new Date,executedAt:void 0};this.pendingTasks.push(i),1===this.pendingTasks.length&&this.next()}))}))}removeTask(e){if(0===e)throw new TypeError("cannot remove task with index 0");const t=this.pendingTasks[e];t&&(this.pendingTasks.splice(e,1),t.reject(new this.RemovedTaskErrorClass("task removed from the queue")))}stop(){if(!this.closed){for(const e of this.pendingTasks)e.stopped=!0,e.reject(new this.StoppedErrorClass("AwaitQueue stopped"));this.pendingTasks.length=0}}dump(){const e=new Date;let t=0;return this.pendingTasks.map((r=>({idx:t++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt.getTime()-r.enqueuedAt.getTime():e.getTime()-r.enqueuedAt.getTime(),executingTime:r.executedAt?e.getTime()-r.executedAt.getTime():0})))}next(){return jm(this,void 0,void 0,(function*(){const e=this.pendingTasks[0];e&&(yield this.executeTask(e),this.pendingTasks.shift(),this.next())}))}executeTask(e){return jm(this,void 0,void 0,(function*(){if(!e.stopped){e.executedAt=new Date;try{const t=yield e.task();if(e.stopped)return;e.resolve(t)}catch(t){if(e.stopped)return;e.reject(t)}}}))}};var Vm,Bm,Wm,Hm,qm,zm,Gm,Ym,$m,Km,Jm,Qm,Zm,Xm,eg,tg,rg,ng,ig,sg,og,ag,cg,dg,ug,lg,pg,hg,fg,mg,gg,vg,yg,bg,_g,Eg,wg,Sg,Cg,Tg,Pg,Rg,kg,Dg,Ig,Ag,Og,Mg,Ng,Lg,xg,Fg,jg,Ug,Vg;class Bg{constructor(){Vm.set(this,0),Bm.set(this,0),Wm.set(this,0),Hm.set(this,0),qm.set(this,0),zm.set(this,0),Gm.set(this,performance.now())}frameSent(e,t){c(this,Bm,a(this,Bm,"f")+1,"f"),c(this,Vm,a(this,Vm,"f")+e,"f"),t&&c(this,Wm,a(this,Wm,"f")+1,"f")}frameDropped(){c(this,Hm,a(this,Hm,"f")+1,"f")}frameShed(){c(this,qm,a(this,qm,"f")+1,"f")}snapshot(e,t){const r=performance.now(),n=Math.max(r-a(this,Gm,"f"),1),i=Math.max(0,a(this,zm,"f")+a(this,Vm,"f")-e),s=e=>Math.round(1e3*e/n),o={fps:s(a(this,Bm,"f")),kbps:Math.round(8*a(this,Vm,"f")/n),wireKbps:Math.round(8*i/n),keyFrames:a(this,Wm,"f"),droppedFps:s(a(this,Hm,"f")),sheddedFps:s(a(this,qm,"f")),gated:e>t,bufferedAmount:e};return c(this,zm,e,"f"),c(this,Gm,r,"f"),c(this,Vm,0,"f"),c(this,Bm,0,"f"),c(this,Wm,0,"f"),c(this,Hm,0,"f"),c(this,qm,0,"f"),o}}Vm=new WeakMap,Bm=new WeakMap,Wm=new WeakMap,Hm=new WeakMap,qm=new WeakMap,zm=new WeakMap,Gm=new WeakMap;class Wg{constructor(e){Ym.set(this,void 0),$m.set(this,!1),c(this,Ym,e,"f")}get chainBroken(){return a(this,$m,"f")}decide(e,t){return e>a(this,Ym,"f")?(c(this,$m,!0,"f"),{send:!1,needKeyFrame:!1}):a(this,$m,"f")&&!t?{send:!1,needKeyFrame:!0}:{send:!0,needKeyFrame:!1}}onKeyFrameSent(){c(this,$m,!1,"f")}}Ym=new WeakMap,$m=new WeakMap;class Hg{constructor(e,t,r){Km.add(this),Jm.set(this,void 0),Qm.set(this,void 0),Zm.set(this,void 0),Xm.set(this,void 0),eg.set(this,0),tg.set(this,0),c(this,Jm,e,"f"),c(this,Qm,t,"f"),c(this,Zm,r,"f")}get isConfigured(){var e;return"configured"===(null===(e=a(this,Xm,"f"))||void 0===e?void 0:e.state)}get width(){return a(this,eg,"f")}get height(){return a(this,tg,"f")}encode(e,t){var r;const n=a(this,Km,"m",rg).call(this,e.codedWidth,e.codedHeight);return null===(r=a(this,Xm,"f"))||void 0===r||r.encode(e,{keyFrame:t||n}),n}close(){if(a(this,Xm,"f")&&"closed"!==a(this,Xm,"f").state)try{a(this,Xm,"f").close()}catch(e){}c(this,Xm,void 0,"f"),c(this,eg,0,"f"),c(this,tg,0,"f")}}Jm=new WeakMap,Qm=new WeakMap,Zm=new WeakMap,Xm=new WeakMap,eg=new WeakMap,tg=new WeakMap,Km=new WeakSet,rg=function(e,t){return(!a(this,Xm,"f")||a(this,eg,"f")!==e||a(this,tg,"f")!==t)&&(a(this,Xm,"f")&&"closed"!==a(this,Xm,"f").state&&a(this,Xm,"f").close(),c(this,Xm,new VideoEncoder({output:e=>{a(this,Qm,"f").call(this,e)},error:e=>{a(this,Zm,"f").call(this,e)}}),"f"),a(this,Xm,"f").configure({codec:"vp8",width:e,height:t,framerate:a(this,Jm,"f").framerate,latencyMode:"realtime",bitrate:a(this,Jm,"f").bitrate,bitrateMode:"variable"}),c(this,eg,e,"f"),c(this,tg,t,"f"),!0)};class qg{constructor(e){var t,r,n,i,s,o;ng.add(this),ig.set(this,void 0),sg.set(this,void 0),og.set(this,void 0),ag.set(this,void 0),cg.set(this,new Bg),dg.set(this,void 0),ug.set(this,void 0),lg.set(this,void 0),pg.set(this,!1),hg.set(this,!1),fg.set(this,0),mg.set(this,void 0),gg.set(this,void 0),vg.set(this,void 0),yg.set(this,0),bg.set(this,0),_g.set(this,void 0),c(this,ig,e.track,"f"),c(this,sg,e.dataProducer,"f"),c(this,ag,e.logger,"f"),c(this,og,{bitrate:null!==(r=null===(t=e.config)||void 0===t?void 0:t.bitrate)&&void 0!==r?r:25e5,framerate:null!==(i=null===(n=e.config)||void 0===n?void 0:n.framerate)&&void 0!==i?i:15,readyBufferedAmount:null!==(o=null===(s=e.config)||void 0===s?void 0:s.readyBufferedAmount)&&void 0!==o?o:65536},"f"),c(this,dg,new Wg(a(this,og,"f").readyBufferedAmount),"f"),c(this,ug,new Hg({bitrate:a(this,og,"f").bitrate,framerate:a(this,og,"f").framerate},(e=>{a(this,ng,"m",Ig).call(this,e)}),(e=>{var t;null===(t=a(this,ag,"f"))||void 0===t||t.call(this,"encoder error",e)})),"f"),c(this,mg,Math.floor(1e6/a(this,og,"f").framerate),"f")}start(){a(this,pg,"f")||(c(this,pg,!0,"f"),c(this,_g,setInterval((()=>{a(this,ng,"m",kg).call(this)}),500),"f"),a(this,ng,"m",Eg).call(this))}requestKeyFrame(){c(this,hg,!0,"f"),performance.now()-a(this,yg,"f")>200&&a(this,ng,"m",Rg).call(this,!0)}stop(){var e,t;c(this,pg,!1,"f"),a(this,_g,"f")&&(clearInterval(a(this,_g,"f")),c(this,_g,void 0,"f")),null===(e=a(this,lg,"f"))||void 0===e||e.cancel().catch((()=>{})),c(this,lg,void 0,"f"),a(this,ug,"f").close(),null===(t=a(this,vg,"f"))||void 0===t||t.close(),c(this,vg,void 0,"f")}getStatsSnapshot(){return a(this,cg,"f").snapshot(a(this,sg,"f").bufferedAmount,a(this,og,"f").readyBufferedAmount)}}ig=new WeakMap,sg=new WeakMap,og=new WeakMap,ag=new WeakMap,cg=new WeakMap,dg=new WeakMap,ug=new WeakMap,lg=new WeakMap,pg=new WeakMap,hg=new WeakMap,fg=new WeakMap,mg=new WeakMap,gg=new WeakMap,vg=new WeakMap,yg=new WeakMap,bg=new WeakMap,_g=new WeakMap,ng=new WeakSet,Eg=function(){return o(this,void 0,void 0,(function*(){var e;null===(e=a(this,ag,"f"))||void 0===e||e.call(this,"encoded video sender started",{framerate:a(this,og,"f").framerate});const t=new MediaStreamTrackProcessor({track:a(this,ig,"f")});c(this,lg,t.readable.getReader(),"f"),yield a(this,ng,"m",wg).call(this)}))},wg=function(){return o(this,void 0,void 0,(function*(){const e=a(this,lg,"f");if(e)for(;a(this,pg,"f");){const t=yield a(this,ng,"m",Sg).call(this,e);if(!t||t.done||!t.value)break;a(this,ng,"m",Tg).call(this,t.value)}}))},Sg=function(e){return o(this,void 0,void 0,(function*(){var t;try{return yield e.read()}catch(e){return null===(t=a(this,ag,"f"))||void 0===t||t.call(this,"reader error",e),null}}))},Cg=function(e){const t=a(this,gg,"f");return void 0!==t&&e.timestamp-t<a(this,mg,"f")?(a(this,cg,"f").frameDropped(),!0):(c(this,gg,e.timestamp,"f"),!1)},Tg=function(e){var t;try{if(a(this,ng,"m",Cg).call(this,e))return;const t=a(this,hg,"f");c(this,hg,!1,"f"),a(this,ug,"f").encode(e,t),a(this,ng,"m",Pg).call(this,e),c(this,yg,performance.now(),"f"),c(this,bg,a(this,yg,"f"),"f")}catch(e){null===(t=a(this,ag,"f"))||void 0===t||t.call(this,"encode error",e)}finally{e.close()}},Pg=function(e){var t;null===(t=a(this,vg,"f"))||void 0===t||t.close(),c(this,vg,e.clone(),"f")},Rg=function(e){var t,r;const n=a(this,vg,"f");if(!a(this,ug,"f").isConfigured||!n)return;if(n.codedWidth!==a(this,ug,"f").width||n.codedHeight!==a(this,ug,"f").height)return;const i=performance.now(),s=Math.max(a(this,mg,"f"),Math.round(1e3*(i-a(this,bg,"f")))),o=(null!==(t=a(this,gg,"f"))&&void 0!==t?t:n.timestamp)+s,d=a(this,ng,"m",Dg).call(this,n,o);if(d)try{e&&c(this,hg,!1,"f"),c(this,gg,o,"f"),c(this,bg,i,"f"),a(this,ug,"f").encode(d,e)}catch(e){null===(r=a(this,ag,"f"))||void 0===r||r.call(this,"synth frame encode failed",e)}finally{d.close()}},kg=function(){a(this,pg,"f")&&(performance.now()-a(this,yg,"f")<=200||a(this,ng,"m",Rg).call(this,a(this,dg,"f").chainBroken))},Dg=function(e,t){var r;try{return new VideoFrame(e,{timestamp:t})}catch(e){return null===(r=a(this,ag,"f"))||void 0===r||r.call(this,"key frame synth failed",e),null}},Ig=function(e){var t;const r="key"===e.type,n=a(this,dg,"f").decide(a(this,sg,"f").bufferedAmount,r);if(!n.send)return a(this,cg,"f").frameShed(),void(n.needKeyFrame&&c(this,hg,!0,"f"));r&&a(this,dg,"f").onKeyFrameSent();const i=new Uint8Array(e.byteLength);e.copyTo(i);const s=function(e,t=65536){const r=t-14;if(r<=0)throw new RangeError("maxMessageBytes is too small for the frame header");const n=e.data.length,i=Math.max(1,Math.ceil(n/r));if(i>65535)throw new RangeError(`frame too large: ${i} fragments exceeds 65535`);const s=[];for(let t=0;t<i;t++){const o=t*r,a=Math.min(o+r,n),c=new Uint8Array(a-o+14),d=new DataView(c.buffer);d.setUint8(0,1),d.setUint8(1,e.keyFrame?1:0),d.setUint32(2,e.frameId>>>0),d.setUint32(6,e.rtpTimestamp90k>>>0),d.setUint16(10,t),d.setUint16(12,i),c.set(e.data.subarray(o,a),14),s.push(c)}return s}({frameId:a(this,fg,"f"),rtpTimestamp90k:Math.round(.09*e.timestamp)>>>0,keyFrame:r,data:i});c(this,fg,a(this,fg,"f")+1>>>0,"f"),a(this,cg,"f").frameSent(e.byteLength,r);for(const e of s)try{a(this,sg,"f").send(e)}catch(e){null===(t=a(this,ag,"f"))||void 0===t||t.call(this,"dataProducer send error",e);break}};class zg extends om{constructor(){super(...arguments),Ag.add(this),Og.set(this,void 0),Mg.set(this,void 0),Ng.set(this,void 0),Lg.set(this,!1),xg.set(this,!1)}get producerId(){return a(this,Ng,"f")}get isPublished(){var e;return a(this,Lg,"f")&&Boolean(a(this,Mg,"f"))&&!(null===(e=a(this,Mg,"f"))||void 0===e?void 0:e.closed)}get isPaused(){return a(this,xg,"f")}publish(){return o(this,void 0,void 0,(function*(){if(a(this,Lg,"f"))return;const e=this.network.sendTransport;if(!e)throw new Error("Send transport is not ready");const t=yield e.produceData({label:"encoded-video",ordered:!1,appData:{label:this.getLabel()}});c(this,Mg,t,"f"),c(this,Ng,t.id,"f"),t.once("transportclose",(()=>{a(this,Ag,"m",Fg).call(this)})),a(this,Ag,"m",Ug).call(this,t),c(this,Lg,!0,"f"),c(this,xg,!1,"f"),this.logger.info("publish() encoded",{producerId:a(this,Ng,"f"),label:this.getLabel()}),this.internalEventEmitter.emit(gn,this)}))}stopMediaStreamTrack(){a(this,Ag,"m",jg).call(this),super.stopMediaStreamTrack()}unpublish(){return o(this,arguments,void 0,(function*(e=!0){var t,r;if(!a(this,Lg,"f"))return;const n=a(this,Ng,"f");if(null===(t=a(this,Og,"f"))||void 0===t||t.stop(),c(this,Og,void 0,"f"),c(this,Lg,!1,"f"),c(this,xg,!1,"f"),this.internalEventEmitter.emit(vn,this),n)try{yield this.network.closeRemoteProducer(n)}catch(e){this.logger.warn("unpublish() encoded: closeRemoteProducer failed",{error:e})}try{null===(r=a(this,Mg,"f"))||void 0===r||r.close()}catch(e){this.logger.warn("unpublish() encoded: dataProducer close failed",{error:e})}c(this,Mg,void 0,"f"),c(this,Ng,void 0,"f"),e&&this.stopMediaStreamTrack()}))}pause(){return o(this,void 0,void 0,(function*(){var e;a(this,Lg,"f")&&!a(this,xg,"f")&&(null===(e=a(this,Og,"f"))||void 0===e||e.stop(),c(this,Og,void 0,"f"),a(this,Ng,"f")&&(yield this.network.pauseRemoteProducer(a(this,Ng,"f"))),c(this,xg,!0,"f"),this.internalEventEmitter.emit(yn,this))}))}resume(){return o(this,void 0,void 0,(function*(){a(this,xg,"f")&&a(this,Mg,"f")&&(a(this,Ag,"m",Ug).call(this,a(this,Mg,"f")),a(this,Ng,"f")&&(yield this.network.resumeRemoteProducer(a(this,Ng,"f"))),c(this,xg,!1,"f"),this.internalEventEmitter.emit(bn,this))}))}requestKeyFrame(){var e;null===(e=a(this,Og,"f"))||void 0===e||e.requestKeyFrame()}getEncodedVideoStats(){var e;return null===(e=a(this,Og,"f"))||void 0===e?void 0:e.getStatsSnapshot()}getMaxSpatialLayer(){}setMaxSpatialLayer(){return o(this,void 0,void 0,(function*(){}))}enableEffects(){return o(this,void 0,void 0,(function*(){this.logger.debug("enableEffects() ignored for encoded screen share",{})}))}}var Gg,Yg;Og=new WeakMap,Mg=new WeakMap,Ng=new WeakMap,Lg=new WeakMap,xg=new WeakMap,Ag=new WeakSet,Fg=function(){this.logger.info("encoded track: send transport closed",{producerId:a(this,Ng,"f")}),a(this,Ag,"m",jg).call(this),this.internalEventEmitter.emit(vn,this)},jg=function(){var e,t;null===(e=a(this,Og,"f"))||void 0===e||e.stop(),c(this,Og,void 0,"f");try{null===(t=a(this,Mg,"f"))||void 0===t||t.close()}catch(e){}c(this,Mg,void 0,"f"),c(this,Ng,void 0,"f"),c(this,Lg,!1,"f"),c(this,xg,!1,"f")},Ug=function(e){c(this,Og,new qg({track:this.mediaStreamTrack,dataProducer:e,config:a(this,Ag,"m",Vg).call(this),logger:(e,t)=>{this.logger.debug(e,null!=t?t:{})}}),"f"),a(this,Og,"f").start()},Vg=function(){var e,t,r;const n=(null!==(e=this.getEncoderConfig().encodings)&&void 0!==e?e:[]).reduce(((e,t)=>{var r,n;return e?(null!==(r=t.maxBitrate)&&void 0!==r?r:0)>(null!==(n=e.maxBitrate)&&void 0!==n?n:0)?t:e:t}),void 0);return{bitrate:null!==(t=null==n?void 0:n.maxBitrate)&&void 0!==t?t:25e5,framerate:null!==(r=null==n?void 0:n.maxFramerate)&&void 0!==r?r:15}};let $g=class{constructor(e,t,r,n,i){this.media=e,this.internalEventEmitter=t,this.peersStorage=r,this.clientEventEmitter=n,Gg.set(this,new Um),Yg.set(this,void 0),c(this,Yg,i("MediaEvents"),"f")}handleMediaEvent(e){var t;switch(e.eventType){case Vs.MEDIA_EVENT_TYPE_PRODUCER_CREATED:this.handleProducerCreated(e);break;case Vs.MEDIA_EVENT_TYPE_PRODUCER_CLOSED:this.handleProducerClosed(e);break;case Vs.MEDIA_EVENT_TYPE_PRODUCER_PAUSED:this.handleProducerPaused(e);break;case Vs.MEDIA_EVENT_TYPE_PRODUCER_RESUMED:this.handleProducerResumed(e);break;case Vs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED:this.handleProducerMaxSpatialLayerChanged(e);break;case Vs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED:this.handleProducerRequestMaxSpatialLayer(e).catch((e=>{a(this,Yg,"f").error("Failed to handle producer max spatial layer requested event",{error:Vt(e)})}));break;case Vs.MEDIA_EVENT_TYPE_PRODUCER_KEY_FRAME_REQUESTED:this.handleProducerKeyFrameRequested(e);break;case Vs.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED:this.handleProducerForciblyClosed(e).catch((e=>{a(this,Yg,"f").error("Failed to handle producer forcibly closed event",{error:Vt(e)})}));break;case Vs.MEDIA_EVENT_TYPE_CONSUMER_CLOSED:a(this,Yg,"f").debug("Close consumer event received, skip",{consumerId:null===(t=e.consumer)||void 0===t?void 0:t.id});break;case Vs.MEDIA_EVENT_TYPE_CONSUMER_RESUMED:this.handleConsumerResumed(e);break;case Vs.MEDIA_EVENT_TYPE_CONSUMER_PAUSED:this.handleConsumerPaused(e);break;case Vs.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED:this.handleConsumerPreferredLayersChanged(e);break;case Vs.MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT:this.handleTransportConnectionTimeout(e);break;default:throw new Error(`Unsupported event type: ${e.eventType}`)}}handleProducerKeyFrameRequested(e){var t;const r=null===(t=e.producerKeyFrameRequest)||void 0===t?void 0:t.producerId;if(!r)return;const n=this.media.getTrackByLabel(exports.TrackLabel.ScreenVideo);n instanceof zg&&n.producerId===r&&n.requestKeyFrame()}handleProducerCreated(e){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_CREATED");const t=this.peersStorage.get(e.producer.peerId);null==t||t.observer.safeEmit(Ln,Dm(e.producer))}handleProducerClosed(e){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_CLOSED");const t=this.peersStorage.get(e.producer.peerId);null==t||t.observer.safeEmit(xn,Dm(e.producer))}handleProducerPaused(e){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_PAUSED");const t=this.peersStorage.get(e.producer.peerId),r=null==t?void 0:t.producers.get(e.producer.id);t?r?(r.setPaused(!0),t.observer.safeEmit(Tn,{producerId:r.id,kind:r.kind,label:r.label,paused:r.paused})):t.observer.safeEmit(Ln,Object.assign(Object.assign({},Dm(e.producer)),{paused:!0})):a(this,Yg,"f").debug("Peer not found for producer paused event",{peerId:e.producer.peerId})}handleProducerResumed(e){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_RESUMED");const t=this.peersStorage.get(e.producer.peerId),r=null==t?void 0:t.producers.get(e.producer.id);t?r?(r.setPaused(!1),t.observer.safeEmit(Pn,{producerId:r.id,kind:r.kind,label:r.label,paused:r.paused})):t.observer.safeEmit(Ln,Object.assign(Object.assign({},Dm(e.producer)),{paused:!1})):a(this,Yg,"f").debug("Peer not found for producer resumed event",{peerId:e.producer.peerId})}handleProducerMaxSpatialLayerChanged(e){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED");if(void 0===e.producer.maxSpatialLayer)return;const t=this.peersStorage.get(e.producer.peerId);null==t||t.observer.safeEmit(Fn,{peerId:e.producer.peerId,producerId:e.producer.id,spatialLayer:e.producer.maxSpatialLayer})}handleProducerRequestMaxSpatialLayer(e){return o(this,void 0,void 0,(function*(){if(!e.producerSpatialLayerRequest)throw new Error("Missing producerSpatialLayerRequest in MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED");const{producerId:t,spatialLayer:r}=e.producerSpatialLayerRequest;yield a(this,Gg,"f").push((()=>o(this,void 0,void 0,(function*(){yield this.media.handleProducerSetMaxSpatialLayer({producerId:t,spatialLayer:r})}))),jn)}))}handleProducerForciblyClosed(e){return o(this,void 0,void 0,(function*(){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED");const t=Pm(e.producer.label),r=this.media.getTrackByLabel(t);if(!r)return;r.stopMediaStreamTrack(),this.internalEventEmitter.safeEmit(_n,r);const n={label:t};this.clientEventEmitter.emit(Qr,n),yield this.media.deleteTrack(r)}))}handleConsumerResumed(e){if(!e.consumer)throw new Error("Missing consumer in MEDIA_EVENT_TYPE_CONSUMER_RESUMED");const t=this.peersStorage.get(e.consumer.producerPeerId);null==t||t.observer.safeEmit(Bn,e.consumer.id)}handleConsumerPaused(e){if(!e.consumer)throw new Error("Missing consumer in MEDIA_EVENT_TYPE_CONSUMER_PAUSED");const t=this.peersStorage.get(e.consumer.producerPeerId);null==t||t.observer.safeEmit(Vn,e.consumer.id)}handleConsumerPreferredLayersChanged(e){var t;if(!e.consumer)throw new Error("Missing consumer in MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED");if(void 0===e.consumer.spatialLayer)return;const r=e.consumer.producerPeerId||e.consumer.peerId,n=this.peersStorage.get(r);null==n||n.observer.safeEmit(Wn,{consumerId:e.consumer.id,spatialLayer:e.consumer.spatialLayer,temporalLayer:null!==(t=e.consumer.temporalLayer)&&void 0!==t?t:Wh})}handleTransportConnectionTimeout(e){if(!e.transportConnectionTimeout)throw new Error("Missing transportConnectionTimeout in MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT");a(this,Yg,"f").info("Transport connection timed out",{transportId:e.transportConnectionTimeout.transportId,direction:e.transportConnectionTimeout.direction,timeout:e.transportConnectionTimeout.timeout,reason:e.transportConnectionTimeout.reason})}};Gg=new WeakMap,Yg=new WeakMap,$g=n([ot(),i(0,ct(mi.Media)),i(1,ct(mi.InternalEventEmitter)),i(2,ct(mi.PeersStorage)),i(3,ct(mi.ClientEventEmitter)),i(4,ct(mi.LoggerFactory)),s("design:paramtypes",[bm,Ft,fo,Ft,Function])],$g);var Kg,Jg=$g;let Qg=class{constructor(){Kg.set(this,new Map)}set(e,t){a(this,Kg,"f").set(e,{label:e,producerId:t})}get(e){return a(this,Kg,"f").get(e)}has(e){return a(this,Kg,"f").has(e)}delete(e){a(this,Kg,"f").delete(e)}entries(){return Array.from(a(this,Kg,"f").values())}};Kg=new WeakMap,Qg=n([ot()],Qg);var Zg,Xg=Qg;let ev=class{constructor(e,t,r){this.network=e,this.storage=t,Zg.set(this,void 0),c(this,Zg,r("ProducerCloseManager"),"f")}close(e,t){return o(this,void 0,void 0,(function*(){try{const r=yield this.sendCloseRequest(t);if(this.storage.delete(e),!r)return;a(this,Zg,"f").info("Remote producer closed",{label:e,producerId:t})}catch(r){this.storage.set(e,t);(Jn(r)?a(this,Zg,"f").debug.bind(a(this,Zg,"f")):a(this,Zg,"f").warn.bind(a(this,Zg,"f")))("Failed to close remote producer, queued for retry",{label:e,producerId:t,error:Vt(r)})}}))}ensureNoPending(e){return o(this,void 0,void 0,(function*(){const t=this.storage.get(e);t&&(yield this.flushEntry(t))}))}flushPending(){return o(this,void 0,void 0,(function*(){const e=this.storage.entries();for(const t of e)try{yield this.flushEntry(t)}catch(e){}}))}flushEntry(e){return o(this,void 0,void 0,(function*(){try{yield fi((()=>o(this,void 0,void 0,(function*(){yield this.sendCloseRequest(e.producerId)}))),{maxRetries:5,minBackoffDelayMs:200,maxBackoffDelayMs:1e3,actionName:"closeRemoteProducer",logger:a(this,Zg,"f")}),this.storage.delete(e.label),a(this,Zg,"f").info("Pending remote producer closed",{label:e.label,producerId:e.producerId})}catch(t){throw a(this,Zg,"f").debug("Failed to close pending remote producer",{label:e.label,producerId:e.producerId,error:Vt(t)}),t}}))}sendCloseRequest(e){return o(this,void 0,void 0,(function*(){try{return yield this.network.closeRemoteProducer(e),!0}catch(t){if(t instanceof Yn)return a(this,Zg,"f").debug("Remote producer maybe already closed",{producerId:e}),!1;throw t}}))}};Zg=new WeakMap,ev=n([ot(),i(0,ct(mi.Network)),i(1,ct(mi.PendingClosureProducerStorage)),i(2,ct(mi.LoggerFactory)),s("design:paramtypes",[Function,Xg,Function])],ev);var tv,rv,nv,iv,sv,ov,av,cv=ev;const dv=["send","recv"];let uv=av=class{constructor(e,t){this.network=e,this.loggerFactory=t,tv.set(this,!1),rv.set(this,new Map),nv.set(this,new Set),iv.set(this,new Map),sv.set(this,void 0),ov.set(this,void 0),this.handleTransportState=({state:e,direction:t})=>{if(!a(this,tv,"f"))return;if(a(this,nv,"f").has(t))return;if(a(this,iv,"f").has(t))return;if(!["disconnected","failed"].includes(e))return;const r=this.recordDisconnectAndGetCount(t);r&&(r<=3||(a(this,ov,"f").info("transport instability detected. Escalating to relay",{direction:t,disconnectCount:r}),this.triggerRelayEscalation(t).catch((e=>{a(this,ov,"f").warn("Failed to escalate to relay",{direction:t,error:Vt(e)})}))))},c(this,ov,this.loggerFactory("NetworkTransportPolicyManager"),"f")}setRelayEscalationHandler(e){c(this,sv,e,"f")}startMonitoring(){a(this,tv,"f")||(this.refreshDirectionRelayState(),a(this,rv,"f").clear(),c(this,tv,!0,"f"),this.network.observer.on(qn,this.handleTransportState))}stopMonitoring(){a(this,tv,"f")&&(this.network.observer.off(qn,this.handleTransportState),c(this,tv,!1,"f"),a(this,rv,"f").clear())}changeIceTransportPolicy(e){return o(this,void 0,void 0,(function*(){yield Promise.all(a(this,iv,"f").values()),yield Promise.all(dv.map((t=>o(this,void 0,void 0,(function*(){return yield this.applyRelayPolicy(t,e)}))))),a(this,rv,"f").clear(),"all"!==e?this.stopMonitoring():a(this,nv,"f").clear()}))}triggerRelayEscalation(e){return o(this,void 0,void 0,(function*(){if(a(this,sv,"f"))return a(this,rv,"f").clear(),void(yield a(this,sv,"f").call(this));yield this.escalateDirectionToRelay(e)}))}recordDisconnectAndGetCount(e){var t;const r=Date.now(),n=null!==(t=a(this,rv,"f").get(e))&&void 0!==t?t:[],i=n[n.length-1];if(av.isDuplicateDisconnect(i,r))return;const s=av.getDisconnectsInWindow(n,r);return s.push(r),a(this,rv,"f").set(e,s),s.length}applyRelayPolicy(e,t){return o(this,void 0,void 0,(function*(){const r=this.getTransportByDirection(e);if(!r)return;const n=av.getPeerConnection(r);n&&(n.setConfiguration(Object.assign(Object.assign({},n.getConfiguration()),{iceTransportPolicy:t})),yield this.network.restartIce(r),"relay"===t?a(this,nv,"f").add(e):a(this,nv,"f").delete(e))}))}escalateDirectionToRelay(e){return o(this,void 0,void 0,(function*(){if(a(this,nv,"f").has(e))return;const t=a(this,iv,"f").get(e);if(t)return void(yield t);const r=(()=>o(this,void 0,void 0,(function*(){yield this.applyRelayPolicy(e,"relay"),a(this,rv,"f").delete(e)})))();a(this,iv,"f").set(e,r);try{yield r}finally{a(this,iv,"f").delete(e)}}))}refreshDirectionRelayState(){dv.forEach((e=>{const t=this.getTransportByDirection(e),r=av.getPeerConnection(t);"relay"!==(null==r?void 0:r.getConfiguration().iceTransportPolicy)?a(this,nv,"f").delete(e):a(this,nv,"f").add(e)}))}getTransportByDirection(e){return"send"===e?this.network.sendTransport:this.network.receiveTransport}static getPeerConnection(e){var t;return null===(t=null==e?void 0:e.handler)||void 0===t?void 0:t._pc}static getDisconnectsInWindow(e,t){const r=t-3e4;return e.filter((e=>e>=r))}static isDuplicateDisconnect(e,t){return"number"==typeof e&&t-e<400}};tv=new WeakMap,rv=new WeakMap,nv=new WeakMap,iv=new WeakMap,sv=new WeakMap,ov=new WeakMap,uv=av=n([ot(),i(0,ct(mi.Network)),i(1,ct(mi.LoggerFactory)),s("design:paramtypes",[po,Function])],uv);var lv=uv;const pv=new Error("request for lock canceled");var hv=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class fv{constructor(e,t=pv){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise(((r,n)=>{const i={resolve:r,reject:n,weight:e,priority:t},s=mv(this._queue,(e=>t<=e.priority));-1===s&&e<=this._value?this._dispatchItem(i):this._queue.splice(s+1,0,i)}))}runExclusive(e){return hv(this,arguments,void 0,(function*(e,t=1,r=0){const[n,i]=yield this.acquire(t,r);try{return yield e(n)}finally{i()}}))}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise((r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),function(e,t){const r=mv(e,(e=>t.priority<=e.priority));e.splice(r+1,0,t)}(this._weightedWaiters[e-1],{resolve:r,priority:t})}))}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach((e=>e.reject(this._cancelError))),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(0===this._queue.length)for(let e=this._value;e>0;e--){const t=this._weightedWaiters[e-1];t&&(t.forEach((e=>e.resolve())),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let t=this._value;t>0;t--){const r=this._weightedWaiters[t-1];if(!r)continue;const n=r.findIndex((t=>t.priority<=e));(-1===n?r:r.splice(0,n)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(0===this._queue.length||this._queue[0].priority<t)&&e<=this._value}}function mv(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1}var gv,vv=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class yv{constructor(e){this._semaphore=new fv(1,e)}acquire(){return vv(this,arguments,void 0,(function*(e=0){const[,t]=yield this._semaphore.acquire(1,e);return t}))}runExclusive(e,t=0){return this._semaphore.runExclusive((()=>e()),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}let bv=class{constructor(){gv.set(this,new Map)}lock(e){return o(this,void 0,void 0,(function*(){let t=a(this,gv,"f").get(e);return t||(t=new yv,a(this,gv,"f").set(e,t)),t.isLocked()&&(yield t.waitForUnlock()),yield t.acquire()}))}isLocked(e){const t=a(this,gv,"f").get(e);return!!t&&t.isLocked()}waitForUnlock(e){return o(this,void 0,void 0,(function*(){const t=a(this,gv,"f").get(e);(null==t?void 0:t.isLocked())?yield t.waitForUnlock():yield Promise.resolve()}))}};gv=new WeakMap,bv=n([ot()],bv);var _v,Ev=bv;class wv extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="MediaDeviceAccessError",this.code=e}}let Sv=class{constructor(e,t){this.clientEventEmitter=e,this.isEnableVideoDevicesLock=!1,this.isEnableAudioDevicesLock=!1,this.isDevicesDetected=!1,this.availableVideoDevices=[],this.availableAudioDevices=[],this.availableAudioOutputDevices=[],_v.set(this,void 0),c(this,_v,t("System"),"f"),this.deviceChangeHandler=this.deviceChangeHandler.bind(this),this.listenDevices()}setIsEnableVideoDevicesLock(e){this.isEnableVideoDevicesLock=e}setIsEnableAudioDevicesLock(e){this.isEnableAudioDevicesLock=e}setAvailableVideoDevices(e){this.availableVideoDevices=e}setAvailableAudioDevices(e){this.availableAudioDevices=e}setAvailableAudioOutputDevices(e){this.availableAudioOutputDevices=e}requestMediaDevicesAccess(){return o(this,arguments,void 0,(function*(e={video:!0,audio:!0}){try{return(yield navigator.mediaDevices.getUserMedia(e)).getTracks()}catch(t){a(this,_v,"f").error("getUserMedia()",{error:t,constraints:e});const r=t instanceof Error?t.name:void 0;if("NotAllowedError"===r)throw new wv(exports.DeviceErrors.NotAllowedError);if("NotReadableError"===r)throw new wv(exports.DeviceErrors.DeviceIsBusy);if("NotFoundError"===r)throw new wv(exports.DeviceErrors.NotFoundError);throw new wv(exports.DeviceErrors.RequestDevicesUnknownError)}}))}hasAvailableMediaDevicesList(){return o(this,void 0,void 0,(function*(){const e=yield navigator.mediaDevices.enumerateDevices();if(0===e.length)return!0;return e.every((e=>e.deviceId&&e.label))}))}refreshAvailableMediaDevicesList(){return o(this,void 0,void 0,(function*(){const e=yield navigator.mediaDevices.enumerateDevices(),t=[],r=[],n=[];e.forEach((e=>{""!==e.deviceId&&("videoinput"===e.kind&&t.push(e),"audioinput"===e.kind&&r.push(e),"audiooutput"===e.kind&&n.push(e))})),this.setAvailableVideoDevices(t),this.setAvailableAudioDevices(r),this.setAvailableAudioOutputDevices(n);const i=({label:e,kind:t})=>({label:e,kind:t});return a(this,_v,"f").info("Devices list updated",{videoDevices:t.map(i),audioDevices:r.map(i),audioOutputDevices:n.map(i)}),e}))}detectDevices(e){return o(this,void 0,void 0,(function*(){if(this.isDevicesDetected&&!e)return this.getAvailableMediaDevices();this.resetDeviceAvailability();(yield this.hasAvailableMediaDevicesList())||(yield this.tryToAccessDevices()),this.isDevicesDetected=!0,yield this.refreshAvailableMediaDevicesList();const t=this.getAvailableMediaDevices();return a(this,_v,"f").debug("detectDevices()",{availability:t.availability,audio:t.audio,video:t.video,audioOutput:t.audioOutput}),t}))}deviceChangeHandler(){return o(this,void 0,void 0,(function*(){if(!this.isDevicesDetected)return;yield this.refreshAvailableMediaDevicesList();const e=this.getAvailableMediaDevices();this.clientEventEmitter.safeEmit(Kr,e)}))}resetDeviceAvailability(){this.audioDeviceAvailability=void 0,this.videoDeviceAvailability=void 0,this.audioOutputDeviceAvailability=void 0}getAvailableMediaDevices(){return{audio:this.availableAudioDevices,video:this.availableVideoDevices,audioOutput:this.availableAudioOutputDevices,availability:{audio:this.getDeviceAvailability("audio"),video:this.getDeviceAvailability("video"),audioOutput:this.getDeviceAvailability("audioOutput")}}}getDeviceAvailability(e){var t;const r={audio:this.availableAudioDevices,video:this.availableVideoDevices,audioOutput:this.availableAudioOutputDevices},n={audio:this.audioDeviceAvailability,video:this.videoDeviceAvailability,audioOutput:this.audioOutputDeviceAvailability};return r[e].length>0?{available:!0}:null!==(t=n[e])&&void 0!==t?t:{available:!1,reason:"not_found"}}listenDevices(){navigator.mediaDevices.addEventListener("devicechange",this.deviceChangeHandler)}requestMediaDeviceAccessAvailability(e){return o(this,void 0,void 0,(function*(){try{return(yield this.requestMediaDevicesAccess({[e]:!0})).forEach((e=>e.stop())),{available:!0}}catch(e){if(e instanceof wv){if(e.code===exports.DeviceErrors.NotAllowedError)return{available:!1,reason:"not_allowed"};if(e.code===exports.DeviceErrors.NotFoundError)return{available:!1,reason:"not_found"};if(e.code===exports.DeviceErrors.DeviceIsBusy)return{available:!1,reason:"device_is_busy"}}throw e}}))}tryToAccessDevices(){return o(this,void 0,void 0,(function*(){try{(yield this.requestMediaDevicesAccess()).forEach((e=>e.stop()))}catch(e){if(!(e instanceof wv))throw e;if(e.code===exports.DeviceErrors.DeviceIsBusy)return;if(e.code===exports.DeviceErrors.RequestDevicesUnknownError)throw e;this.audioDeviceAvailability=yield this.requestMediaDeviceAccessAvailability("audio"),this.videoDeviceAvailability=yield this.requestMediaDeviceAccessAvailability("video")}}))}};_v=new WeakMap,Sv=n([ot(),i(0,ct(mi.ClientEventEmitter)),i(1,ct(mi.LoggerFactory)),s("design:paramtypes",[Ft,Function])],Sv);var Cv,Tv=Sv;class Pv{constructor({transport:e,statsHandler:t}){Cv.set(this,void 0),this.handleWebRTCStats(e,t)}get connectionStats(){return a(this,Cv,"f")}handleWebRTCStats(e,t){t.addConnectionHandler(e.id,this.setConnectionStats.bind(this)),e.observer.once("close",(()=>{t.removeConnectionHandler(e.id)}))}setConnectionStats(e){c(this,Cv,e,"f")}}Cv=new WeakMap;function Rv(e,t){return t.find((t=>t.ssrc===e))}function kv(e,t,r){return Math.max(t,Math.min(e,r))}function Dv(e,t=2){return Number(e.toFixed(t))}function Iv(e){return kv(Dv(e),1,5)}function Av(e,t){if(0===e.length)throw new Error("Cannot compute percentile of empty array");if(1===e.length)return e[0];const r=t*(e.length-1),n=Math.floor(r),i=Math.ceil(r),s=r-n;return Dv(e[n]+s*(e[i]-e[n]))}var Ov,Mv,Nv,Lv,xv;let Fv=class{constructor(){Ov.set(this,new Map),Mv.set(this,new Map),Nv.set(this,new Map),Lv.set(this,new Map),xv.set(this,new Map)}handle(e){e.forEach((({id:e,stats:t})=>{var r;null===(r=a(this,Ov,"f").get(e))||void 0===r||r(t.connection),t.video.inbound.forEach((e=>{var r;return null===(r=a(this,Mv,"f").get(e.trackIdentifier))||void 0===r?void 0:r({inbound:e,connection:t.connection})})),t.audio.inbound.forEach((e=>{var r;return null===(r=a(this,Nv,"f").get(e.trackIdentifier))||void 0===r?void 0:r({inbound:e,connection:t.connection})}));const n=new Map;t.video.outbound.forEach((e=>{const r=Rv(e.ssrc,t.remote.video.inbound);if(!r)return;const i={outbound:e,remoteInbound:r,connection:t.connection},s=n.get(e.mid);s?s.push(i):n.set(e.mid,[i])})),n.forEach((e=>{var t,r;const n=null===(t=e.find((e=>e.outbound.track.trackIdentifier)))||void 0===t?void 0:t.outbound.track.trackIdentifier;n&&(null===(r=a(this,Lv,"f").get(n))||void 0===r||r(e))})),t.audio.outbound.forEach((e=>{var r;const n=Rv(e.ssrc,t.remote.audio.inbound);n&&(null===(r=a(this,xv,"f").get(e.track.trackIdentifier))||void 0===r||r({outbound:e,remoteInbound:n,connection:t.connection}))}))}))}addConnectionHandler(e,t){a(this,Ov,"f").set(e,t)}addInboundVideoHandler(e,t){a(this,Mv,"f").set(e,t)}addInboundAudioHandler(e,t){a(this,Nv,"f").set(e,t)}addOutboundVideoHandler(e,t){a(this,Lv,"f").set(e,t)}addOutboundAudioHandler(e,t){a(this,xv,"f").set(e,t)}removeConnectionHandler(e){a(this,Ov,"f").delete(e)}removeInboundVideoHandler(e){a(this,Mv,"f").delete(e)}removeInboundAudioHandler(e){a(this,Nv,"f").delete(e)}removeOutboundVideoHandler(e){a(this,Lv,"f").delete(e)}removeOutboundAudioHandler(e){a(this,xv,"f").delete(e)}clear(){a(this,Ov,"f").clear(),a(this,Mv,"f").clear(),a(this,Nv,"f").clear(),a(this,Lv,"f").clear(),a(this,xv,"f").clear()}};Ov=new WeakMap,Mv=new WeakMap,Nv=new WeakMap,Lv=new WeakMap,xv=new WeakMap,Fv=n([ot()],Fv);var jv,Uv,Vv,Bv,Wv,Hv,qv,zv,Gv=Fv;let Yv=class{constructor(e,t){var r;jv.set(this,!1),Uv.set(this,void 0),Vv.set(this,void 0),Bv.set(this,void 0),Wv.set(this,void 0),Hv.set(this,void 0),qv.set(this,void 0),zv.set(this,.5),c(this,Uv,e("IntegrationsService"),"f"),c(this,qv,t,"f"),c(this,zv,null!==(r=Ar("qosQPercentile"))&&void 0!==r?r:a(this,zv,"f"),"f")}init({sendTransportConnectionManager:e,receiveTransportConnectionManager:t,media:r,peers:n}){c(this,Vv,e,"f"),c(this,Bv,t,"f"),c(this,Wv,r,"f"),c(this,Hv,n,"f"),c(this,jv,!0,"f")}getStats(){try{return this.doGetStats()}catch(e){return a(this,Uv,"f").error("Failed to get stats",{error:Vt(e)}),{}}}clear(){c(this,Vv,void 0,"f"),c(this,Bv,void 0,"f"),c(this,Wv,void 0,"f"),c(this,Hv,void 0,"f")}doGetStats(){var e,t,r,n;if(!a(this,jv,"f"))throw new Error("TransportsStatsProvider is not initialized");const i={};if(null===(t=null===(e=a(this,Vv,"f"))||void 0===e?void 0:e.connectionStats)||void 0===t?void 0:t.id){const e=this.calculateOutboundTracksResultQValues();i.outbound=Object.assign(Object.assign({},a(this,Vv,"f").connectionStats),{bitrate:this.calculateOutboundTracksBitrate(),Qav:e.Qav,Qa:e.Qa,Qv:e.Qv})}if(null===(n=null===(r=a(this,Bv,"f"))||void 0===r?void 0:r.connectionStats)||void 0===n?void 0:n.id){const e=this.calculateInboundTracksResultQValues();i.inbound=Object.assign(Object.assign({},a(this,Bv,"f").connectionStats),{bitrate:this.calculateInboundTracksBitrate(),Qav:e.Qav,Qa:e.Qa,Qv:e.Qv})}return i}calculateInboundTracksBitrate(){if(void 0===a(this,Hv,"f"))throw new Error("Peers is undefined");return a(this,Hv,"f").hosts().reduce(((e,t)=>{if(t.isMe)return e;return e+Array.from(t.tracks.values()).reduce(((e,t)=>{var r,n;const i="video"===t.kind?null===(r=t.videoWebRTCStats)||void 0===r?void 0:r.bitrate:null===(n=t.audioWebRTCStats)||void 0===n?void 0:n.bitrate;return e+(null!=i?i:0)}),0)}),0)}calculateInboundTracksResultQValues(){if(void 0===a(this,Hv,"f"))throw new Error("Peers prop is not defined");const e=[],t=[],r=[];for(const n of a(this,Hv,"f").hosts()){if(n.isMe)continue;const{Qa:i,Qv:s}=this.getWorstQValues(Array.from(n.tracks.values()));void 0!==i&&t.push(i),void 0!==s&&r.push(s);const o=void 0===i||void 0===s?null!=i?i:s:a(this,qv,"f").calculateAVCompositeMOS(i,s);void 0!==o&&e.push(o)}const n=(e,t)=>e-t;return e.sort(n),t.sort(n),r.sort(n),{Qav:e.length>0?Av(e,a(this,zv,"f")):void 0,Qa:t.length>0?Av(t,a(this,zv,"f")):void 0,Qv:r.length>0?Av(r,a(this,zv,"f")):void 0}}calculateOutboundTracksResultQValues(){var e;if(void 0===a(this,Wv,"f"))throw new Error("Media prop is not defined");const t=a(this,Wv,"f").getAllTracks().filter((e=>e.isPublished)),{Qa:r,Qv:n}=this.getWorstQValues(t);let i;return void 0!==r&&void 0!==n&&(i=a(this,qv,"f").calculateAVCompositeMOS(r,n)),{Qav:null!==(e=null!=i?i:r)&&void 0!==e?e:n,Qa:r,Qv:n}}calculateOutboundTracksBitrate(){if(void 0===a(this,Wv,"f"))throw new Error("Media is undefined");return a(this,Wv,"f").getAllTracks().reduce(((e,t)=>{var r,n;if(!t.isPublished)return e;const i="video"===t.kind?null===(r=t.videoWebRTCStats)||void 0===r?void 0:r.bitrate:null===(n=t.audioWebRTCStats)||void 0===n?void 0:n.bitrate;return e+(null!=i?i:0)}),0)}getWorstQValues(e){let t,r;for(const n of e){const{Qa:e,Qv:i}=n.connectionScores;void 0!==e&&(void 0===t||e<t)&&(t=e),void 0!==i&&(void 0===r||i<r)&&(r=i)}return{Qa:t,Qv:r}}};jv=new WeakMap,Uv=new WeakMap,Vv=new WeakMap,Bv=new WeakMap,Wv=new WeakMap,Hv=new WeakMap,qv=new WeakMap,zv=new WeakMap,Yv=n([ot(),i(0,ct(mi.LoggerFactory)),i(1,ct(mi.ScoresCalculator)),s("design:paramtypes",[Function,Function])],Yv);var $v=Yv;const Kv={vp8:40,vp9:40,h264:25},Jv={mobile:[.1558,1.0348,-.0181,-.4048],pc:[.1526,.8788,.0086,-.2242],tv:[.1496,1.0267,-.0248,-.3477]},Qv={video:{codecFactors:{vp9:1.2,vp8:1,h264:1}},defaults:{audio:{ssrc:-1,packetLoss:0,bufferDelay:50,roundTripTime:50,fec:!0,bitrate:0,dtx:!1},video:{ssrc:-1,packetLoss:0,bufferDelay:0,roundTripTime:50,codec:"vp8",width:640,height:480,expectedWidth:640,expectedHeight:480,frameRate:20,expectedFrameRate:20,bitrate:0}}};var Zv,Xv,ey;exports.ScoresCalculator=class{constructor(e){this.config=this.mergeConfig(e)}calculateAudioMOS(e){const t=this.normalizeAudioStats(e),r=20+t.bufferDelay+t.roundTripTime/2,n=t.packetLoss;let i=0;i=t.dtx?8:t.bitrate>0?kv(55-4.6*Math.log(t.bitrate),0,30):6;const s=kv(100-(i+(100-i)*n/(n+(t.fec?20:10)))-(.03*r+(r>150?.1*(r-150):0)),0,100);return Iv(1+.035*s+s*(s-60)*(100-s)*7/1e6)}calculateVideoMOS(e){var t,r,n,i,s,o;const a=this.normalizeVideoStats(e),c=a.expectedWidth*a.expectedHeight;if(!a.frameRate||!c||void 0===a.bitrate)return 1;const d=a.codec&&null!==(n=null===(r=null===(t=this.config.video)||void 0===t?void 0:t.codecFactors)||void 0===r?void 0:r[a.codec.toLowerCase()])&&void 0!==n?n:1,u=a.bufferDelay+a.roundTripTime/2,l=d*a.bitrate/c/a.frameRate,p=kv(.56*Math.log(l)+5.36,1,5),h=!0===a.decreaseOutboundPenalty&&"none"===a.qualityLimitationReason,f=null!==(o=Kv[null!==(s=null===(i=a.codec)||void 0===i?void 0:i.toLowerCase())&&void 0!==s?s:""])&&void 0!==o?o:40,m=void 0!==a.averageQP&&a.averageQP<f;return Iv((h||!0===a.isStaticContent||m?Math.max(p,4):p)-(a.expectedFrameRate>0?1.9*Math.log(a.expectedFrameRate/a.frameRate):0)-.002*u)}calculateAVCompositeMOS(e,t,r){const[n,i,s,o]=Jv[null!=r?r:"pc"];return Iv(n*e+i*t+s*e*t+o)}mergeConfig(e){var t;return e?{video:{codecFactors:Object.assign(Object.assign({},Qv.video.codecFactors),null===(t=e.video)||void 0===t?void 0:t.codecFactors)}}:Qv}normalizeAudioStats(e){return Object.assign(Object.assign({},Qv.defaults.audio),e)}normalizeVideoStats(e){const t=Object.assign(Object.assign({},Qv.defaults.video),e);return void 0!==e.width&&void 0===e.expectedWidth&&(t.expectedWidth=e.width),void 0!==e.height&&void 0===e.expectedHeight&&(t.expectedHeight=e.height),void 0!==e.frameRate&&void 0===e.expectedFrameRate&&(t.expectedFrameRate=e.frameRate),t}},exports.ScoresCalculator=n([ot(),s("design:paramtypes",[Object])],exports.ScoresCalculator);let ty=class{constructor(e,t,r,n,i,s,o,a,d,u,l,p,h,f,m,g,v,y,b,_,E,w,S,C,T){var P;this.state=e,this.myPeer=t,this.integrationsService=n,this.processorsCache=i,this.mediaEventHandler=s,this.channelEventsHandler=o,this.peerTrackFactory=a,this.peers=d,this.peersStorage=u,this.system=l,this.media=p,this.network=h,this.networkTransportPolicyManager=f,this.producerCloseManager=m,this.signalingApiClient=g,this.eventsQueue=v,this.clientEventEmitter=y,this.internalEventEmitter=b,this.statsHandler=_,this.transportsStatsProvider=E,this.localMutex=w,this.scoresCalculatorInstance=S,this.clientMetaProvider=C,this.webRtcIssueDetector=T,Zv.set(this,void 0),this.rejoinRequested=!1,this.isReleasing=!1,Xv.set(this,!1),ey.set(this,!1),this.mark=Rr(),this.handleSignalingError=e=>{this.isReleasing||!this.isChannelJoined||this.state.isChannelJoining||e instanceof Qn&&this.triggerRejoinEventIfAppropriate(e.errorCode)},c(this,Zv,r("Engine"),"f"),this.watchNetworkState(),this.watchDocumentUnload(),this.watchInternalEvents(),this.signalingApiClient.addErrorListener(this.handleSignalingError),P=this.mark,window._sdkMarks||(window._sdkMarks=new Set),window._sdkMarks.add(P)}get isChannelJoined(){return this.state.isJoined}get scoresCalculator(){return this.scoresCalculatorInstance}initialize(){return o(this,void 0,void 0,(function*(){var e,t;try{const{data:r}=yield this.signalingApiClient.router.getRtpCapabilities(),{rtpCapabilities:n}=r;this.integrationsService.init(),yield this.media.loadDevice(n),a(this,Zv,"f").info("Supported capabilities",{codecs:ci(this.media.mediasoupDevice)}),yield this.initTransports(),this.network.channelMessagesDataConsumer&&(this.eventsQueue.setChannelEventHandler(this.channelEventsHandler.handleChannelEvent.bind(this.channelEventsHandler)),this.eventsQueue.setMediaEventHandler(this.mediaEventHandler.handleMediaEvent.bind(this.mediaEventHandler)),this.eventsQueue.subscribe(this.network.channelMessagesDataConsumer)),a(this,Zv,"f").debug("initialize()",{sendTransportId:null===(e=this.network.sendTransport)||void 0===e?void 0:e.id,recvTransportId:null===(t=this.network.receiveTransport)||void 0===t?void 0:t.id})}catch(e){a(this,Zv,"f").error("initialize()",{error:e});const t=e instanceof Error&&"UnsupportedError"===e.name&&"device not supported"===e.message,r=e instanceof Error&&"RTCPeerConnection is not defined"===e.message;if(t||r)throw new Zn("Device not supported",Zn.UNSUPPORTED_DEVICE_CODE);if(e instanceof Gn)throw e;throw new Bt("initialize_engine_error",e)}}))}release(e){return o(this,void 0,void 0,(function*(){var t;if(this.isReleasing)return;const r=this.myPeer.get(),n={case:"release",applicationId:this.state.appId,channelId:this.state.channelId,peerId:null!==(t=null==r?void 0:r.id)&&void 0!==t?t:this.myPeerId,peerRole:null==r?void 0:r.role,isJoined:this.state.isJoined,isChannelJoining:this.state.isChannelJoining,rejoinRequested:this.rejoinRequested};this.isReleasing=!0;const i=yield this.localMutex.lock(zn.Release);try{this.signalingApiClient.abortPendingRequests("release"),e||this.media.clearTracks(),yield Promise.all([si((()=>o(this,void 0,void 0,(function*(){return yield this.peers.reset()})))),si((()=>o(this,void 0,void 0,(function*(){return yield this.media.unpublishTracks()})))),si((()=>o(this,void 0,void 0,(function*(){return yield this.signalingApiClient.peers.disconnectPeer()}))))]),this.cleanup(),a(this,Zv,"f").debug("release()",n)}catch(e){a(this,Zv,"f").error("Failed to release",Object.assign(Object.assign({},n),{error:Vt(e)}))}finally{this.isReleasing=!1,i()}}))}getPeers(){return this.peers.all()}get myPeerId(){return this.myPeer.id}confirmActivity(){return o(this,void 0,void 0,(function*(){try{yield this.signalingApiClient.channel.confirmChannelActivity()}catch(e){throw new Bt("confirm_activity_failed",e)}}))}join(e){return o(this,arguments,void 0,(function*({token:e,appData:t,isP2pCall:r,preferredDC:n}){if(this.isChannelJoined)throw new Bt("method_not_available_when_joined");const i=yield this.localMutex.lock(zn.Join);try{a(this,Zv,"f").debug("join()",{appData:t,isP2pCall:r}),this.state.isChannelJoining=!0,this.signalingApiClient.abortPendingRequests("join"),this.signalingApiClient.setSecurityData({token:e,peerApiVersion:8,datacenterType:r?"p2p":"common",preferredDC:n});const{data:s,headers:o}=yield this.signalingApiClient.peers.registerPeer({appData:t}),{appId:c,channelId:d,peerId:u}=s,l=String(o["x-datacenter-name"]),p=String(o["x-node-id"]);this.myPeer.id=u,this.state.appId=c,this.state.channelId=d,this.clientMetaProvider.setPeerId(u),this.clientMetaProvider.setChannelId(d),this.clientMetaProvider.setAppId(c),this.clientMetaProvider.setDatacenterName(l),this.clientMetaProvider.setNodeId(p),yield this.initialize(),this.state.isJoined=!0,a(this,Zv,"f").info("Successfully joined channel",{channelId:d,datacenterName:l})}catch(e){throw this.signalingApiClient.abortPendingRequests("join"),yield this.release(),a(this,Zv,"f").error("join()",{error:e}),new Bt("join_failed",e)}finally{this.state.isChannelJoining=!1,this.rejoinRequested=!1,i()}}))}requestChannelStateSync(){return o(this,void 0,void 0,(function*(){yield this.network.waitForReceiveTransportConnected({onReceiveTransportFailed:()=>o(this,void 0,void 0,(function*(){this.network.reset(),this.network.enforceRelay(12e4),yield this.initTransports()}))}),yield this.network.waitForChannelMessagesDataConsumerConnected(),this.state.isJoined=!0,this.networkTransportPolicyManager.setRelayEscalationHandler((()=>{this.network.enforceRelay(12e4),this.triggerRejoinEventIfAppropriate("relay_escalation")})),this.networkTransportPolicyManager.startMonitoring();fi((()=>o(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>o(this,void 0,void 0,(function*(){if(!this.isChannelJoined||this.rejoinRequested||this.state.isChannelJoining)return e();const r=yield this.network.triggerChannelStateEvent("host"),n=setTimeout((()=>{this.eventsQueue.isMessageReceived(r)?(a(this,Zv,"f").info("Channel state event received",{case:"Engine.requestChannelStateSync"}),e()):t(new Bt("channel_state_event_not_received",new Error("Channel state event not received")))}),5e3),i=()=>{clearTimeout(n),this.clientEventEmitter.off(tn,i),e()};this.clientEventEmitter.on(tn,i)}))))}))),{minBackoffDelayMs:0,maxBackoffDelayMs:0,maxRetries:10,actionName:"triggerChannelStateEventWithRetry",logger:a(this,Zv,"f")}).catch((e=>{(Jn(e)?a(this,Zv,"f").debug.bind(a(this,Zv,"f")):a(this,Zv,"f").error.bind(a(this,Zv,"f")))("Failed to request channel state event",{case:"Engine.requestChannelStateSync",error:Vt(e)})}))}))}updateAppData(e){return o(this,void 0,void 0,(function*(){const t=this.myPeer.get();if(!t)throw new Bt("need_joined_to_channel",new Error("Need join to channel first"));try{Xn(e)}catch(e){throw a(this,Zv,"f").error("updateAppData() validation failed",{error:e}),new Bt("invalid_app_data",e)}try{yield this.network.updatePeerAppData({peerId:t.id,appData:e})}catch(e){throw(Jn(e)?a(this,Zv,"f").debug.bind(a(this,Zv,"f")):a(this,Zv,"f").error.bind(a(this,Zv,"f")))("updateAppData()",{error:Vt(e)}),new Bt("update_app_data_failed",e)}}))}createCameraVideoTrack(e){return o(this,void 0,void 0,(function*(){const t=bm.getCameraVideoTrackParams(e);try{const[r]=yield this.media.createUserMediaTracks({audio:!1,video:t.videoTrackOptions});return r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof om&&(r.setLabel((null==e?void 0:e.isPreview)?exports.TrackLabel.CameraPreview:exports.TrackLabel.Camera),r.setEncoderConfig(t.encoderConfig),r.setTransformParams(bm.getVideoTrackTransformParams(r.mediaStreamTrack))),this.media.setTrack(r),a(this,Zv,"f").debug("createCameraVideoTrack()",{trackParams:t}),r}catch(e){throw a(this,Zv,"f").error("createCameraVideoTrack()",{error:e,trackParams:t}),new Bt("create_camera_track_failed",e)}}))}createMicrophoneAudioTrack(e){return o(this,void 0,void 0,(function*(){try{const[t]=yield this.media.createUserMediaTracks({video:!1,audio:null==e?void 0:e.audio}),r=(null==e?void 0:e.isPreview)?exports.TrackLabel.MicrophonePreview:exports.TrackLabel.Microphone;return t.setLabel(r),t.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),(null==e?void 0:e.encoderConfig)&&t.setEncoderConfig(e.encoderConfig),"audio"!==t.kind||t.getLabel()!==exports.TrackLabel.Microphone||a(this,ey,"f")||this.media.initDenoiser(t,e).catch((t=>{this.clientEventEmitter.emit(un,{cause:"Failed to initialize denoiser",error:t}),a(this,Zv,"f").error("Failed to execute initDenoiser",{case:"Denoiser",options:e,error:Vt(t)})})),this.media.setTrack(t),a(this,Zv,"f").debug("createMicrophoneAudioTrack()",{options:e,trackLabel:t.getLabel()}),t}catch(t){throw a(this,Zv,"f").error("createMicrophoneAudioTrack()",{error:t,options:e}),new Bt("create_microphone_track_failed",t)}}))}createScreenMediaTracks(e){return o(this,void 0,void 0,(function*(){const t=bm.getScreenVideoTrackParams(e),r=Boolean(null==e?void 0:e.encoded)&&(yield li());a(this,Zv,"f").debug("createScreenMediaTracks()",{useEncoded:r});try{const n=yield this.media.createDisplayMediaTracks({audio:null==e?void 0:e.audio,video:null==e?void 0:e.video},r);return n.forEach((r=>{if(r.mediaStreamTrack.addEventListener("ended",(()=>{r.unpublish().catch((e=>{a(this,Zv,"f").error("Failed to unpublish screen track",{error:Vt(e)})}))}),{once:!0}),r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof om){r.setLabel(exports.TrackLabel.ScreenVideo),r.setEncoderConfig(t.encoderConfig);const e=bm.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(e),this.media.setTrack(r),void a(this,Zv,"f").debug("createScreenMediaTrack()",{trackParams:t,transformParams:e,label:r.logCtx})}r.setLabel(exports.TrackLabel.ScreenAudio),(null==e?void 0:e.audioEncoderConfig)&&r.setEncoderConfig(e.audioEncoderConfig),this.media.setTrack(r),a(this,Zv,"f").debug("createScreenMediaTrack()",{trackParams:null==e?void 0:e.audio,encoderConfig:null==e?void 0:e.audioEncoderConfig})})),n}catch(e){throw a(this,Zv,"f").error("createScreenMediaTrack()",{error:e,trackParams:t}),new Bt("create_screen_tracks_failed",e)}}))}createCustomAudioTrack(e){if(!e.audioTrack)throw new Bt("missing_audio_track",new Error("options.audioTrack is required"));try{const t=this.media.createCustomMediaTrack(e.audioTrack,{audio:e.audio});return t.mediaStreamTrack.addEventListener("ended",(()=>{t.unpublish().catch((e=>{a(this,Zv,"f").error("Failed to unpublish custom audio track",{track:t,error:Vt(e)})}))}),{once:!0}),t.setStopTrackOnPause(Boolean(e.stopTrackOnPause)),t.setLabel(exports.TrackLabel.CustomAudio),e.audioEncoderConfig&&t.setEncoderConfig(e.audioEncoderConfig),this.media.setTrack(t),a(this,Zv,"f").debug("createCustomAudioTrack()",{trackParams:e.audio,encoderConfig:e.audioEncoderConfig}),t}catch(t){throw a(this,Zv,"f").error("createCustomAudioTrack()",{error:t,trackParams:e.audioTrack}),new Bt("create_custom_audio_track_failed",t)}}createCustomVideoTrack(e){return o(this,void 0,void 0,(function*(){const t=bm.getScreenVideoTrackParams(e);if(!e.videoTrack)throw new Bt("missing_video_track",new Error("options.videoTrack is required"));const r=Boolean(e.encoded)&&(yield li());a(this,Zv,"f").debug("createCustomVideoTrack()",{useEncoded:r});try{const n=this.media.createCustomMediaTrack(e.videoTrack,{video:e.video},r);n.mediaStreamTrack.addEventListener("ended",(()=>{n.unpublish().catch((e=>{a(this,Zv,"f").error("Failed to unpublish custom video track",{track:n,error:Vt(e)})}))}),{once:!0}),n.mediaStreamTrack.contentHint="customVideo",n.setLabel(exports.TrackLabel.CustomVideo),n.setEncoderConfig(t.encoderConfig);const i=bm.getVideoTrackTransformParams(n.mediaStreamTrack);return n.setTransformParams(i),this.media.setTrack(n),a(this,Zv,"f").debug("createCustomVideoTrack()",{trackParams:t,transformParams:i,label:n.logCtx}),n}catch(e){throw a(this,Zv,"f").error("createCustomVideoTrack()",{error:e,trackParams:t}),new Bt("create_custom_video_track_failed",e)}}))}deleteTrack(e){return o(this,void 0,void 0,(function*(){try{yield this.media.deleteTrack(e)}catch(e){throw new Bt("delete_track_failed",e)}}))}transportsStats(){return this.transportsStatsProvider.getStats()}setSignalingServerUrl(e){if(this.isChannelJoined||this.rejoinRequested||this.state.isChannelJoining)throw new Bt("method_not_available_when_joined",new Error("Method not available when joined channel"));this.signalingApiClient.instance.defaults.baseURL=e}cleanup(){var e;this.signalingApiClient.abortPendingRequests("cleanup"),this.rejoinRequested=!1,c(this,Xv,!1,"f"),this.networkTransportPolicyManager.stopMonitoring(),this.state.reset(),this.network.reset(),this.peersStorage.clear(),this.transportsStatsProvider.clear(),this.statsHandler.clear(),this.integrationsService.reset(),null===(e=this.webRtcIssueDetector)||void 0===e||e.stopWatchingNewPeerConnections(),this.processorsCache.reset(),this.clientMetaProvider.clear()}watchInternalEvents(){this.internalEventEmitter.on(gn,(e=>o(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.internalEventEmitter.on(vn,(e=>o(this,void 0,void 0,(function*(){var t,r;const n=null===(t=this.myPeer.get())||void 0===t?void 0:t.tracks.get(e.getLabel());null===(r=null==n?void 0:n.close())||void 0===r||r.catch((e=>{a(this,Zv,"f").debug("Failed to close peerTrack",{error:Vt(e)})})),yield this.media.deleteTrack(e)})))),this.internalEventEmitter.on(yn,(e=>{var t,r;const n=null===(t=this.myPeer.get())||void 0===t?void 0:t.tracks.get(e.getLabel());null===(r=null==n?void 0:n.pause())||void 0===r||r.catch((e=>{a(this,Zv,"f").debug("Failed to pause peerTrack",{error:Vt(e)})}))})),this.internalEventEmitter.on(bn,(e=>{var t,r;const n=null===(t=this.myPeer.get())||void 0===t?void 0:t.tracks.get(e.getLabel());null===(r=null==n?void 0:n.resume())||void 0===r||r.catch((e=>{a(this,Zv,"f").debug("Failed to resume peerTrack",{error:Vt(e)})}))})),this.internalEventEmitter.on(_n,(e=>{var t,r;const n=null===(t=this.myPeer.get())||void 0===t?void 0:t.tracks.get(e.getLabel());null===(r=null==n?void 0:n.close())||void 0===r||r.catch((e=>{a(this,Zv,"f").debug("Failed to close peerTrack",{error:Vt(e)})}))})),this.internalEventEmitter.on(En,(e=>o(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.internalEventEmitter.on(wn,(e=>{this.clientEventEmitter.safeEmit(Zr,{label:e.getLabel()})}))}createSelfPeerTrack(e){return o(this,void 0,void 0,(function*(){var t;if(!this.myPeer.id)return;const r=this.peers.get(this.myPeer.id);if(!r)return;yield null===(t=r.tracks.get(e.getLabel()))||void 0===t?void 0:t.close();const n=this.peerTrackFactory({label:e.getLabel(),mediaStreamTrack:e.mediaStreamTrack,muted:!1,paused:e.isPaused,onClose:()=>{},peerEventEmitter:r.observer});r.tracks.set(n.label,n)}))}triggerRejoinEventIfAppropriate(e){!this.isChannelJoined||this.isReleasing||this.state.isChannelJoining||this.rejoinRequested||(a(this,Zv,"f").info("Triggering channel rejoin required event",{reason:e}),this.signalingApiClient.abortPendingRequests("channel-rejoin"),this.rejoinRequested=!0,this.clientEventEmitter.emit($r))}watchNetworkState(){this.network.observer.on(qn,(({state:e,direction:t})=>{if(!this.isReleasing&&(["disconnected","failed"].includes(e)&&this.isChannelJoined&&!a(this,Xv,"f")&&(c(this,Xv,!0,"f"),a(this,Zv,"f").info("connection lost",{channel:"webrtc-transport",direction:t}),this.clientEventEmitter.safeEmit(tn)),"reconnected"===e&&this.isChannelJoined&&a(this,Zv,"f").info("connection restored",{channel:"webrtc-transport",direction:t}),"reconnected"===e&&this.isChannelJoined&&a(this,Xv,"f"))){if(![this.network.receiveTransport,this.network.sendTransport].every((e=>"connected"===(null==e?void 0:e.connectionState)||"new"===(null==e?void 0:e.connectionState))))return;c(this,Xv,!1,"f"),this.clientEventEmitter.safeEmit(rn),this.producerCloseManager.flushPending().catch((e=>{a(this,Zv,"f").warn("Failed to flush pending remote producers",{error:Vt(e)})}))}}))}watchDocumentUnload(){try{window.addEventListener("unload",(()=>{var e,t;null===(e=this.network.sendTransport)||void 0===e||e.close(),null===(t=this.network.receiveTransport)||void 0===t||t.close()}))}catch(e){a(this,Zv,"f").error("Failed to add watchDocumentUnload listener",{channelId:this.state.channelId,error:Vt(e)})}}initTransports(){return o(this,void 0,void 0,(function*(){const[e,t]=yield this.createSendRecvTransports();this.registerNewTransports(e,t),yield this.network.initializeHeartbeats();const{isChromiumBased:r}=(e=>{var t;const r=null!=e?e:"undefined"!=typeof navigator?navigator.userAgent:void 0;if(!r)return{isMobile:!1,isChromiumBased:!1};const n=ti.getParser(r),i=n.getPlatformType(!0),s="mobile"===i||"tablet"===i,o=n.getEngineName().toLowerCase(),a=null!==(t=n.satisfies({chrome:">=0",chromium:">=0","chromium webview":">=0",edge:">=0",opera:">=0","opera coast":">=0","samsung internet for android":">=0","yandex browser":">=0",electron:">=0"}))&&void 0!==t&&t;return{isMobile:s,isChromiumBased:"blink"===o||a&&"webkit"!==o}})();r||(yield this.network.createSignalingTransport(this.media.mediasoupDevice),yield this.network.createKeepAliveConsumer()),yield this.network.createAllDataChannels()}))}registerNewTransports(e,t){var r,n;null===(r=this.webRtcIssueDetector)||void 0===r||r.handleNewPeerConnection(e.handler._pc,e.id),null===(n=this.webRtcIssueDetector)||void 0===n||n.handleNewPeerConnection(t.handler._pc,t.id),this.transportsStatsProvider.clear(),this.transportsStatsProvider.init({media:this.media,peers:this.peers,receiveTransportConnectionManager:new Pv({transport:t,statsHandler:this.statsHandler}),sendTransportConnectionManager:new Pv({transport:e,statsHandler:this.statsHandler})}),this.network.channelMessagesDataConsumer&&this.eventsQueue.subscribe(this.network.channelMessagesDataConsumer)}createSendRecvTransports(){return o(this,void 0,void 0,(function*(){const[e,t]=yield Promise.allSettled([this.network.createSendTransport(this.media.mediasoupDevice),this.network.createRecvTransport(this.media.mediasoupDevice)]);if(("rejected"===e.status||"rejected"===t.status)&&(this.network.closeSendTransport(),this.network.closeReceiveTransport()),"rejected"===e.status)throw new Bt("create_send_transport_failed",e.reason);if("rejected"===t.status)throw new Bt("create_recv_transport_failed",t.reason);return[e.value,t.value]}))}};Zv=new WeakMap,Xv=new WeakMap,ey=new WeakMap,ty=n([ot(),i(0,ct(mi.CallState)),i(1,ct(mi.MyPeer)),i(2,ct(mi.LoggerFactory)),i(3,ct(mi.IntegrationsService)),i(4,ct(mi.ProcessorsCache)),i(5,ct(mi.MediaEventHandler)),i(6,ct(mi.ChannelEventHandler)),i(7,ct(mi.PeerTrackFactory)),i(8,ct(mi.Peers)),i(9,ct(mi.PeersStorage)),i(10,ct(mi.System)),i(11,ct(mi.Media)),i(12,ct(mi.Network)),i(13,ct(mi.NetworkTransportPolicyManager)),i(14,ct(mi.ProducerCloseManager)),i(15,ct(mi.SignalingApiClient)),i(16,ct(mi.EventsQueue)),i(17,ct(mi.ClientEventEmitter)),i(18,ct(mi.InternalEventEmitter)),i(19,ct(mi.StatsHandler)),i(20,ct(mi.TransportsStatsProvider)),i(21,ct(mi.LocalMutex)),i(22,ct(mi.ScoresCalculator)),i(23,ct(mi.ClientMetaProvider)),i(24,ct(mi.WebRTCIssueDetector)),s("design:paramtypes",[gi,io,Function,Zh,Kh,Jg,xm,Function,Object,fo,Tv,bm,po,lv,cv,rd,ro,Ft,Ft,Gv,$v,Ev,exports.ScoresCalculator,Vr,Tr])],ty);var ry=ty,ny="undefined"!=typeof Symbol&&Symbol,iy=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var n=Object.getOwnPropertySymbols(e);if(1!==n.length||n[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var i=Object.getOwnPropertyDescriptor(e,t);if(42!==i.value||!0!==i.enumerable)return!1}return!0},sy="Function.prototype.bind called on incompatible ",oy=Array.prototype.slice,ay=Object.prototype.toString,cy=function(e){var t=this;if("function"!=typeof t||"[object Function]"!==ay.call(t))throw new TypeError(sy+t);for(var r,n=oy.call(arguments,1),i=function(){if(this instanceof r){var i=t.apply(this,n.concat(oy.call(arguments)));return Object(i)===i?i:this}return t.apply(e,n.concat(oy.call(arguments)))},s=Math.max(0,t.length-n.length),o=[],a=0;a<s;a++)o.push("$"+a);if(r=Function("binder","return function ("+o.join(",")+"){ return binder.apply(this,arguments); }")(i),t.prototype){var c=function(){};c.prototype=t.prototype,r.prototype=new c,c.prototype=null}return r},dy=Function.prototype.bind||cy,uy="Function.prototype.bind called on incompatible ",ly=Array.prototype.slice,py=Object.prototype.toString,hy=function(e){var t=this;if("function"!=typeof t||"[object Function]"!==py.call(t))throw new TypeError(uy+t);for(var r,n=ly.call(arguments,1),i=function(){if(this instanceof r){var i=t.apply(this,n.concat(ly.call(arguments)));return Object(i)===i?i:this}return t.apply(e,n.concat(ly.call(arguments)))},s=Math.max(0,t.length-n.length),o=[],a=0;a<s;a++)o.push("$"+a);if(r=Function("binder","return function ("+o.join(",")+"){ return binder.apply(this,arguments); }")(i),t.prototype){var c=function(){};c.prototype=t.prototype,r.prototype=new c,c.prototype=null}return r},fy=(Function.prototype.bind||hy).call(Function.call,Object.prototype.hasOwnProperty),my=SyntaxError,gy=Function,vy=TypeError,yy=function(e){try{return gy('"use strict"; return ('+e+").constructor;")()}catch(e){}},by=Object.getOwnPropertyDescriptor;if(by)try{by({},"")}catch(Ht){by=null}var _y=function(){throw new vy},Ey=by?function(){try{return _y}catch(e){try{return by(arguments,"callee").get}catch(e){return _y}}}():_y,wy="function"==typeof ny&&"function"==typeof Symbol&&"symbol"==typeof ny("foo")&&"symbol"==typeof Symbol("bar")&&iy(),Sy=Object.getPrototypeOf||function(e){return e.__proto__},Cy={},Ty="undefined"==typeof Uint8Array?undefined:Sy(Uint8Array),Py={"%AggregateError%":"undefined"==typeof AggregateError?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":wy?Sy([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":Cy,"%AsyncGenerator%":Cy,"%AsyncGeneratorFunction%":Cy,"%AsyncIteratorPrototype%":Cy,"%Atomics%":"undefined"==typeof Atomics?undefined:Atomics,"%BigInt%":"undefined"==typeof BigInt?undefined:BigInt,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?undefined:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?undefined:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?undefined:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?undefined:FinalizationRegistry,"%Function%":gy,"%GeneratorFunction%":Cy,"%Int8Array%":"undefined"==typeof Int8Array?undefined:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":wy?Sy(Sy([][Symbol.iterator]())):undefined,"%JSON%":"object"==typeof JSON?JSON:undefined,"%Map%":"undefined"==typeof Map?undefined:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&wy?Sy((new Map)[Symbol.iterator]()):undefined,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?undefined:Promise,"%Proxy%":"undefined"==typeof Proxy?undefined:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?undefined:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?undefined:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&wy?Sy((new Set)[Symbol.iterator]()):undefined,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":wy?Sy(""[Symbol.iterator]()):undefined,"%Symbol%":wy?Symbol:undefined,"%SyntaxError%":my,"%ThrowTypeError%":Ey,"%TypedArray%":Ty,"%TypeError%":vy,"%Uint8Array%":"undefined"==typeof Uint8Array?undefined:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?undefined:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?undefined:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?undefined:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?undefined:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?undefined:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?undefined:WeakSet},Ry=function e(t){var r;if("%AsyncFunction%"===t)r=yy("async function () {}");else if("%GeneratorFunction%"===t)r=yy("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=yy("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&(r=Sy(i.prototype))}return Py[t]=r,r},ky={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},Dy=dy,Iy=fy,Ay=Dy.call(Function.call,Array.prototype.concat),Oy=Dy.call(Function.apply,Array.prototype.splice),My=Dy.call(Function.call,String.prototype.replace),Ny=Dy.call(Function.call,String.prototype.slice),Ly=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,xy=/\\(\\)?/g,Fy=function(e){var t=Ny(e,0,1),r=Ny(e,-1);if("%"===t&&"%"!==r)throw new my("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new my("invalid intrinsic syntax, expected opening `%`");var n=[];return My(e,Ly,(function(e,t,r,i){n[n.length]=r?My(i,xy,"$1"):t||e})),n},jy=function(e,t){var r,n=e;if(Iy(ky,n)&&(n="%"+(r=ky[n])[0]+"%"),Iy(Py,n)){var i=Py[n];if(i===Cy&&(i=Ry(n)),void 0===i&&!t)throw new vy("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:i}}throw new my("intrinsic "+e+" does not exist!")},Uy=function(e,t){if("string"!=typeof e||0===e.length)throw new vy("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new vy('"allowMissing" argument must be a boolean');var r=Fy(e),n=r.length>0?r[0]:"",i=jy("%"+n+"%",t),s=i.name,o=i.value,a=!1,c=i.alias;c&&(n=c[0],Oy(r,Ay([0,1],c)));for(var d=1,u=!0;d<r.length;d+=1){var l=r[d],p=Ny(l,0,1),h=Ny(l,-1);if(('"'===p||"'"===p||"`"===p||'"'===h||"'"===h||"`"===h)&&p!==h)throw new my("property names with quotes must have matching quotes");if("constructor"!==l&&u||(a=!0),Iy(Py,s="%"+(n+="."+l)+"%"))o=Py[s];else if(null!=o){if(!(l in o)){if(!t)throw new vy("base intrinsic for "+e+" exists, but the property is not available.");return}if(by&&d+1>=r.length){var f=by(o,l);o=(u=!!f)&&"get"in f&&!("originalValue"in f.get)?f.get:o[l]}else u=Iy(o,l),o=o[l];u&&!a&&(Py[s]=o)}}return o},Vy={exports:{}};!function(e){var t=dy,r=Uy,n=r("%Function.prototype.apply%"),i=r("%Function.prototype.call%"),s=r("%Reflect.apply%",!0)||t.call(i,n),o=r("%Object.getOwnPropertyDescriptor%",!0),a=r("%Object.defineProperty%",!0),c=r("%Math.max%");if(a)try{a({},"a",{value:1})}catch(e){a=null}e.exports=function(e){var r=s(t,i,arguments);if(o&&a){var n=o(r,"length");n.configurable&&a(r,"length",{value:1+c(0,e.length-(arguments.length-1))})}return r};var d=function(){return s(t,n,arguments)};a?a(e.exports,"apply",{value:d}):e.exports.apply=d}(Vy);var By=Uy,Wy=Vy.exports,Hy=Wy(By("String.prototype.indexOf")),qy=p(Object.freeze({__proto__:null,default:{}})),zy="function"==typeof Map&&Map.prototype,Gy=Object.getOwnPropertyDescriptor&&zy?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Yy=zy&&Gy&&"function"==typeof Gy.get?Gy.get:null,$y=zy&&Map.prototype.forEach,Ky="function"==typeof Set&&Set.prototype,Jy=Object.getOwnPropertyDescriptor&&Ky?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,Qy=Ky&&Jy&&"function"==typeof Jy.get?Jy.get:null,Zy=Ky&&Set.prototype.forEach,Xy="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,eb="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,tb="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,rb=Boolean.prototype.valueOf,nb=Object.prototype.toString,ib=Function.prototype.toString,sb=String.prototype.match,ob="function"==typeof BigInt?BigInt.prototype.valueOf:null,ab=Object.getOwnPropertySymbols,cb="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,db="function"==typeof Symbol&&"object"==typeof Symbol.iterator,ub=Object.prototype.propertyIsEnumerable,lb=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null),pb=qy.custom,hb=pb&&yb(pb)?pb:null,fb="function"==typeof Symbol&&void 0!==Symbol.toStringTag?Symbol.toStringTag:null;function mb(e,t,r){var n="double"===(r.quoteStyle||t)?'"':"'";return n+e+n}function gb(e){return String(e).replace(/"/g,"&quot;")}function vb(e){return!("[object Array]"!==Eb(e)||fb&&"object"==typeof e&&fb in e)}function yb(e){if(db)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!cb)return!1;try{return cb.call(e),!0}catch(e){}return!1}var bb=Object.prototype.hasOwnProperty||function(e){return e in this};function _b(e,t){return bb.call(e,t)}function Eb(e){return nb.call(e)}function wb(e,t){if(e.indexOf)return e.indexOf(t);for(var r=0,n=e.length;r<n;r++)if(e[r]===t)return r;return-1}function Sb(e,t){if(e.length>t.maxStringLength){var r=e.length-t.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return Sb(e.slice(0,t.maxStringLength),t)+n}return mb(e.replace(/(['\\])/g,"\\$1").replace(/[\x00-\x1f]/g,Cb),"single",t)}function Cb(e){var t=e.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return r?"\\"+r:"\\x"+(t<16?"0":"")+t.toString(16).toUpperCase()}function Tb(e){return"Object("+e+")"}function Pb(e){return e+" { ? }"}function Rb(e,t,r,n){return e+" ("+t+") {"+(n?kb(r,n):r.join(", "))+"}"}function kb(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+e.join(","+r)+"\n"+t.prev}function Db(e,t){var r=vb(e),n=[];if(r){n.length=e.length;for(var i=0;i<e.length;i++)n[i]=_b(e,i)?t(e[i],e):""}var s,o="function"==typeof ab?ab(e):[];if(db){s={};for(var a=0;a<o.length;a++)s["$"+o[a]]=o[a]}for(var c in e)_b(e,c)&&(r&&String(Number(c))===c&&c<e.length||db&&s["$"+c]instanceof Symbol||(/[^\w$]/.test(c)?n.push(t(c,e)+": "+t(e[c],e)):n.push(c+": "+t(e[c],e))));if("function"==typeof ab)for(var d=0;d<o.length;d++)ub.call(e,o[d])&&n.push("["+t(o[d])+"]: "+t(e[o[d]],e));return n}var Ib=Uy,Ab=function(e,t){var r=By(e,!!t);return"function"==typeof r&&Hy(e,".prototype.")>-1?Wy(r):r},Ob=function e(t,r,n,i){var s=r||{};if(_b(s,"quoteStyle")&&"single"!==s.quoteStyle&&"double"!==s.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(_b(s,"maxStringLength")&&("number"==typeof s.maxStringLength?s.maxStringLength<0&&s.maxStringLength!==1/0:null!==s.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var o=!_b(s,"customInspect")||s.customInspect;if("boolean"!=typeof o&&"symbol"!==o)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(_b(s,"indent")&&null!==s.indent&&"\t"!==s.indent&&!(parseInt(s.indent,10)===s.indent&&s.indent>0))throw new TypeError('options "indent" must be "\\t", an integer > 0, or `null`');if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return Sb(t,s);if("number"==typeof t)return 0===t?1/0/t>0?"0":"-0":String(t);if("bigint"==typeof t)return String(t)+"n";var a=void 0===s.depth?5:s.depth;if(void 0===n&&(n=0),n>=a&&a>0&&"object"==typeof t)return vb(t)?"[Array]":"[Object]";var c=function(e,t){var r;if("\t"===e.indent)r="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;r=Array(e.indent+1).join(" ")}return{base:r,prev:Array(t+1).join(r)}}(s,n);if(void 0===i)i=[];else if(wb(i,t)>=0)return"[Circular]";function d(t,r,o){if(r&&(i=i.slice()).push(r),o){var a={depth:s.depth};return _b(s,"quoteStyle")&&(a.quoteStyle=s.quoteStyle),e(t,a,n+1,i)}return e(t,s,n+1,i)}if("function"==typeof t){var u=function(e){if(e.name)return e.name;var t=sb.call(ib.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),l=Db(t,d);return"[Function"+(u?": "+u:" (anonymous)")+"]"+(l.length>0?" { "+l.join(", ")+" }":"")}if(yb(t)){var p=db?String(t).replace(/^(Symbol\(.*\))_[^)]*$/,"$1"):cb.call(t);return"object"!=typeof t||db?p:Tb(p)}if(function(e){if(!e||"object"!=typeof e)return!1;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return!0;return"string"==typeof e.nodeName&&"function"==typeof e.getAttribute}(t)){for(var h="<"+String(t.nodeName).toLowerCase(),f=t.attributes||[],m=0;m<f.length;m++)h+=" "+f[m].name+"="+mb(gb(f[m].value),"double",s);return h+=">",t.childNodes&&t.childNodes.length&&(h+="..."),h+="</"+String(t.nodeName).toLowerCase()+">"}if(vb(t)){if(0===t.length)return"[]";var g=Db(t,d);return c&&!function(e){for(var t=0;t<e.length;t++)if(wb(e[t],"\n")>=0)return!1;return!0}(g)?"["+kb(g,c)+"]":"[ "+g.join(", ")+" ]"}if(function(e){return!("[object Error]"!==Eb(e)||fb&&"object"==typeof e&&fb in e)}(t)){var v=Db(t,d);return 0===v.length?"["+String(t)+"]":"{ ["+String(t)+"] "+v.join(", ")+" }"}if("object"==typeof t&&o){if(hb&&"function"==typeof t[hb])return t[hb]();if("symbol"!==o&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Yy||!e||"object"!=typeof e)return!1;try{Yy.call(e);try{Qy.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var y=[];return $y.call(t,(function(e,r){y.push(d(r,t,!0)+" => "+d(e,t))})),Rb("Map",Yy.call(t),y,c)}if(function(e){if(!Qy||!e||"object"!=typeof e)return!1;try{Qy.call(e);try{Yy.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var b=[];return Zy.call(t,(function(e){b.push(d(e,t))})),Rb("Set",Qy.call(t),b,c)}if(function(e){if(!Xy||!e||"object"!=typeof e)return!1;try{Xy.call(e,Xy);try{eb.call(e,eb)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Pb("WeakMap");if(function(e){if(!eb||!e||"object"!=typeof e)return!1;try{eb.call(e,eb);try{Xy.call(e,Xy)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Pb("WeakSet");if(function(e){if(!tb||!e||"object"!=typeof e)return!1;try{return tb.call(e),!0}catch(e){}return!1}(t))return Pb("WeakRef");if(function(e){return!("[object Number]"!==Eb(e)||fb&&"object"==typeof e&&fb in e)}(t))return Tb(d(Number(t)));if(function(e){if(!e||"object"!=typeof e||!ob)return!1;try{return ob.call(e),!0}catch(e){}return!1}(t))return Tb(d(ob.call(t)));if(function(e){return!("[object Boolean]"!==Eb(e)||fb&&"object"==typeof e&&fb in e)}(t))return Tb(rb.call(t));if(function(e){return!("[object String]"!==Eb(e)||fb&&"object"==typeof e&&fb in e)}(t))return Tb(d(String(t)));if(!function(e){return!("[object Date]"!==Eb(e)||fb&&"object"==typeof e&&fb in e)}(t)&&!function(e){return!("[object RegExp]"!==Eb(e)||fb&&"object"==typeof e&&fb in e)}(t)){var _=Db(t,d),E=lb?lb(t)===Object.prototype:t instanceof Object||t.constructor===Object,w=t instanceof Object?"":"null prototype",S=!E&&fb&&Object(t)===t&&fb in t?Eb(t).slice(8,-1):w?"Object":"",C=(E||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(S||w?"["+[].concat(S||[],w||[]).join(": ")+"] ":"");return 0===_.length?C+"{}":c?C+"{"+kb(_,c)+"}":C+"{ "+_.join(", ")+" }"}return String(t)},Mb=Ib("%TypeError%"),Nb=Ib("%WeakMap%",!0),Lb=Ib("%Map%",!0),xb=Ab("WeakMap.prototype.get",!0),Fb=Ab("WeakMap.prototype.set",!0),jb=Ab("WeakMap.prototype.has",!0),Ub=Ab("Map.prototype.get",!0),Vb=Ab("Map.prototype.set",!0),Bb=Ab("Map.prototype.has",!0),Wb=function(e,t){for(var r,n=e;null!==(r=n.next);n=r)if(r.key===t)return n.next=r.next,r.next=e.next,e.next=r,r},Hb=String.prototype.replace,qb=/%20/g,zb="RFC3986",Gb={default:zb,formatters:{RFC1738:function(e){return Hb.call(e,qb,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:zb},Yb=Gb,$b=Object.prototype.hasOwnProperty,Kb=Array.isArray,Jb=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),Qb=function(e,t){for(var r=t&&t.plainObjects?Object.create(null):{},n=0;n<e.length;++n)void 0!==e[n]&&(r[n]=e[n]);return r},Zb={arrayToObject:Qb,assign:function(e,t){return Object.keys(t).reduce((function(e,r){return e[r]=t[r],e}),e)},combine:function(e,t){return[].concat(e,t)},compact:function(e){for(var t=[{obj:{o:e},prop:"o"}],r=[],n=0;n<t.length;++n)for(var i=t[n],s=i.obj[i.prop],o=Object.keys(s),a=0;a<o.length;++a){var c=o[a],d=s[c];"object"==typeof d&&null!==d&&-1===r.indexOf(d)&&(t.push({obj:s,prop:c}),r.push(d))}return function(e){for(;e.length>1;){var t=e.pop(),r=t.obj[t.prop];if(Kb(r)){for(var n=[],i=0;i<r.length;++i)void 0!==r[i]&&n.push(r[i]);t.obj[t.prop]=n}}}(t),e},decode:function(e,t,r){var n=e.replace(/\+/g," ");if("iso-8859-1"===r)return n.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(n)}catch(e){return n}},encode:function(e,t,r,n,i){if(0===e.length)return e;var s=e;if("symbol"==typeof e?s=Symbol.prototype.toString.call(e):"string"!=typeof e&&(s=String(e)),"iso-8859-1"===r)return escape(s).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));for(var o="",a=0;a<s.length;++a){var c=s.charCodeAt(a);45===c||46===c||95===c||126===c||c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||i===Yb.RFC1738&&(40===c||41===c)?o+=s.charAt(a):c<128?o+=Jb[c]:c<2048?o+=Jb[192|c>>6]+Jb[128|63&c]:c<55296||c>=57344?o+=Jb[224|c>>12]+Jb[128|c>>6&63]+Jb[128|63&c]:(a+=1,c=65536+((1023&c)<<10|1023&s.charCodeAt(a)),o+=Jb[240|c>>18]+Jb[128|c>>12&63]+Jb[128|c>>6&63]+Jb[128|63&c])}return o},isBuffer:function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(Kb(e)){for(var r=[],n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)},merge:function e(t,r,n){if(!r)return t;if("object"!=typeof r){if(Kb(t))t.push(r);else{if(!t||"object"!=typeof t)return[t,r];(n&&(n.plainObjects||n.allowPrototypes)||!$b.call(Object.prototype,r))&&(t[r]=!0)}return t}if(!t||"object"!=typeof t)return[t].concat(r);var i=t;return Kb(t)&&!Kb(r)&&(i=Qb(t,n)),Kb(t)&&Kb(r)?(r.forEach((function(r,i){if($b.call(t,i)){var s=t[i];s&&"object"==typeof s&&r&&"object"==typeof r?t[i]=e(s,r,n):t.push(r)}else t[i]=r})),t):Object.keys(r).reduce((function(t,i){var s=r[i];return $b.call(t,i)?t[i]=e(t[i],s,n):t[i]=s,t}),i)}},Xb=function(){var e,t,r,n={assert:function(e){if(!n.has(e))throw new Mb("Side channel does not contain "+Ob(e))},get:function(n){if(Nb&&n&&("object"==typeof n||"function"==typeof n)){if(e)return xb(e,n)}else if(Lb){if(t)return Ub(t,n)}else if(r)return function(e,t){var r=Wb(e,t);return r&&r.value}(r,n)},has:function(n){if(Nb&&n&&("object"==typeof n||"function"==typeof n)){if(e)return jb(e,n)}else if(Lb){if(t)return Bb(t,n)}else if(r)return function(e,t){return!!Wb(e,t)}(r,n);return!1},set:function(n,i){Nb&&n&&("object"==typeof n||"function"==typeof n)?(e||(e=new Nb),Fb(e,n,i)):Lb?(t||(t=new Lb),Vb(t,n,i)):(r||(r={key:{},next:null}),function(e,t,r){var n=Wb(e,t);n?n.value=r:e.next={key:t,next:e.next,value:r}}(r,n,i))}};return n},e_=Zb,t_=Gb,r_=Object.prototype.hasOwnProperty,n_={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},i_=Array.isArray,s_=String.prototype.split,o_=Array.prototype.push,a_=function(e,t){o_.apply(e,i_(t)?t:[t])},c_=Date.prototype.toISOString,d_=t_.default,u_={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:e_.encode,encodeValuesOnly:!1,format:d_,formatter:t_.formatters[d_],indices:!1,serializeDate:function(e){return c_.call(e)},skipNulls:!1,strictNullHandling:!1},l_={},p_=function e(t,r,n,i,s,o,a,c,d,u,l,p,h,f,m,g){for(var v=t,y=g,b=0,_=!1;void 0!==(y=y.get(l_))&&!_;){var E=y.get(t);if(b+=1,void 0!==E){if(E===b)throw new RangeError("Cyclic object value");_=!0}void 0===y.get(l_)&&(b=0)}if("function"==typeof c?v=c(r,v):v instanceof Date?v=l(v):"comma"===n&&i_(v)&&(v=e_.maybeMap(v,(function(e){return e instanceof Date?l(e):e}))),null===v){if(s)return a&&!f?a(r,u_.encoder,m,"key",p):r;v=""}if(function(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e||"symbol"==typeof e||"bigint"==typeof e}(v)||e_.isBuffer(v)){if(a){var w=f?r:a(r,u_.encoder,m,"key",p);if("comma"===n&&f){for(var S=s_.call(String(v),","),C="",T=0;T<S.length;++T)C+=(0===T?"":",")+h(a(S[T],u_.encoder,m,"value",p));return[h(w)+(i&&i_(v)&&1===S.length?"[]":"")+"="+C]}return[h(w)+"="+h(a(v,u_.encoder,m,"value",p))]}return[h(r)+"="+h(String(v))]}var P,R=[];if(void 0===v)return R;if("comma"===n&&i_(v))P=[{value:v.length>0?v.join(",")||null:void 0}];else if(i_(c))P=c;else{var k=Object.keys(v);P=d?k.sort(d):k}for(var D=i&&i_(v)&&1===v.length?r+"[]":r,I=0;I<P.length;++I){var A=P[I],O="object"==typeof A&&void 0!==A.value?A.value:v[A];if(!o||null!==O){var M=i_(v)?"function"==typeof n?n(D,A):D:D+(u?"."+A:"["+A+"]");g.set(t,b);var N=Xb();N.set(l_,g),a_(R,e(O,M,n,i,s,o,a,c,d,u,l,p,h,f,m,N))}}return R},h_=Zb,f_=Object.prototype.hasOwnProperty,m_=Array.isArray,g_={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:h_.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},v_=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},y_=function(e,t){return e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1?e.split(","):e},b_=function(e,t,r,n){if(e){var i=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,s=/(\[[^[\]]*])/g,o=r.depth>0&&/(\[[^[\]]*])/.exec(i),a=o?i.slice(0,o.index):i,c=[];if(a){if(!r.plainObjects&&f_.call(Object.prototype,a)&&!r.allowPrototypes)return;c.push(a)}for(var d=0;r.depth>0&&null!==(o=s.exec(i))&&d<r.depth;){if(d+=1,!r.plainObjects&&f_.call(Object.prototype,o[1].slice(1,-1))&&!r.allowPrototypes)return;c.push(o[1])}return o&&c.push("["+i.slice(o.index)+"]"),function(e,t,r,n){for(var i=n?t:y_(t,r),s=e.length-1;s>=0;--s){var o,a=e[s];if("[]"===a&&r.parseArrays)o=[].concat(i);else{o=r.plainObjects?Object.create(null):{};var c="["===a.charAt(0)&&"]"===a.charAt(a.length-1)?a.slice(1,-1):a,d=parseInt(c,10);r.parseArrays||""!==c?!isNaN(d)&&a!==c&&String(d)===c&&d>=0&&r.parseArrays&&d<=r.arrayLimit?(o=[])[d]=i:"__proto__"!==c&&(o[c]=i):o={0:i}}i=o}return i}(c,t,r,n)}},__=function(e,t){var r,n=e,i=function(e){if(!e)return u_;if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||u_.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var r=t_.default;if(void 0!==e.format){if(!r_.call(t_.formatters,e.format))throw new TypeError("Unknown format option provided.");r=e.format}var n=t_.formatters[r],i=u_.filter;return("function"==typeof e.filter||i_(e.filter))&&(i=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:u_.addQueryPrefix,allowDots:void 0===e.allowDots?u_.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:u_.charsetSentinel,delimiter:void 0===e.delimiter?u_.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:u_.encode,encoder:"function"==typeof e.encoder?e.encoder:u_.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:u_.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:u_.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:u_.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:u_.strictNullHandling}}(t);"function"==typeof i.filter?n=(0,i.filter)("",n):i_(i.filter)&&(r=i.filter);var s,o=[];if("object"!=typeof n||null===n)return"";s=t&&t.arrayFormat in n_?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var a=n_[s];if(t&&"commaRoundTrip"in t&&"boolean"!=typeof t.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var c="comma"===a&&t&&t.commaRoundTrip;r||(r=Object.keys(n)),i.sort&&r.sort(i.sort);for(var d=Xb(),u=0;u<r.length;++u){var l=r[u];i.skipNulls&&null===n[l]||a_(o,p_(n[l],l,a,c,i.strictNullHandling,i.skipNulls,i.encode?i.encoder:null,i.filter,i.sort,i.allowDots,i.serializeDate,i.format,i.formatter,i.encodeValuesOnly,i.charset,d))}var p=o.join(i.delimiter),h=!0===i.addQueryPrefix?"?":"";return i.charsetSentinel&&("iso-8859-1"===i.charset?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),p.length>0?h+p:""},E_=function(e,t){var r=function(e){if(!e)return g_;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?g_.charset:e.charset;return{allowDots:void 0===e.allowDots?g_.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:g_.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:g_.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:g_.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:g_.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:g_.comma,decoder:"function"==typeof e.decoder?e.decoder:g_.decoder,delimiter:"string"==typeof e.delimiter||h_.isRegExp(e.delimiter)?e.delimiter:g_.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:g_.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:g_.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:g_.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:g_.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:g_.strictNullHandling}}(t);if(""===e||null==e)return r.plainObjects?Object.create(null):{};for(var n="string"==typeof e?function(e,t){var r,n={},i=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,s=t.parameterLimit===1/0?void 0:t.parameterLimit,o=i.split(t.delimiter,s),a=-1,c=t.charset;if(t.charsetSentinel)for(r=0;r<o.length;++r)0===o[r].indexOf("utf8=")&&("utf8=%E2%9C%93"===o[r]?c="utf-8":"utf8=%26%2310003%3B"===o[r]&&(c="iso-8859-1"),a=r,r=o.length);for(r=0;r<o.length;++r)if(r!==a){var d,u,l=o[r],p=l.indexOf("]="),h=-1===p?l.indexOf("="):p+1;-1===h?(d=t.decoder(l,g_.decoder,c,"key"),u=t.strictNullHandling?null:""):(d=t.decoder(l.slice(0,h),g_.decoder,c,"key"),u=h_.maybeMap(y_(l.slice(h+1),t),(function(e){return t.decoder(e,g_.decoder,c,"value")}))),u&&t.interpretNumericEntities&&"iso-8859-1"===c&&(u=v_(u)),l.indexOf("[]=")>-1&&(u=m_(u)?[u]:u),f_.call(n,d)?n[d]=h_.combine(n[d],u):n[d]=u}return n}(e,r):e,i=r.plainObjects?Object.create(null):{},s=Object.keys(n),o=0;o<s.length;++o){var a=s[o],c=b_(a,n[a],r,"string"==typeof e);i=h_.merge(i,c,r)}return!0===r.allowSparse?i:h_.compact(i)},w_={formats:Gb,parse:E_,stringify:__};class S_{constructor(e){this.api=e,Do(this.api,{retries:2,shouldResetTimeout:!0,retryDelay:e=>1500*e,retryCondition:e=>{var t,r;return/^\/?log\//.test(null!==(r=null===(t=e.config)||void 0===t?void 0:t.url)&&void 0!==r?r:"")||!1}})}batch(e){return o(this,void 0,void 0,(function*(){try{if("undefined"!=typeof CompressionStream){const t=yield function(e){return o(this,void 0,void 0,(function*(){const t=new Blob([e]).stream().pipeThrough(new CompressionStream("gzip"));return yield new Response(t).arrayBuffer()}))}(JSON.stringify(e));return void(yield this.api.post("/log/batch",t,{headers:{"Content-Encoding":"gzip","Content-Type":"application/json"}}))}yield this.api.post("/log/batch",e)}catch(e){console.info("Failed to send logs batch",e)}}))}}class C_{constructor(e){this.api=e,Do(this.api,{retries:2,shouldResetTimeout:!0,retryDelay:e=>1500*e,retryCondition:e=>{var t,r;return/^\/?log\//.test(null!==(r=null===(t=e.config)||void 0===t?void 0:t.url)&&void 0!==r?r:"")||!1}})}sendNetworkMetrics(e){return o(this,void 0,void 0,(function*(){yield this.api.post("/analytics/network-metrics",e)}))}sendWIDMetrics(e){return o(this,void 0,void 0,(function*(){yield this.api.post("/analytics/wid-metrics",Object.assign({},e))}))}}let T_=class{constructor(e){this.api=Hc.create({baseURL:e,timeout:1e4,withCredentials:!0,paramsSerializer:e=>w_.stringify(e),headers:{"x-cl-id":Mr()}}),this.api.defaults.headers.common["Cache-Control"]="no-cache",this.api.defaults.headers.common.Pragma="no-cache",this.api.defaults.headers.common.Expires="0",this.logApi=new S_(this.api),this.metricsApi=new C_(this.api)}get log(){return this.logApi}get metrics(){return this.metricsApi}};T_=n([ot(),s("design:paramtypes",[String])],T_);var P_,R_,k_=T_;class D_ extends Gn{constructor(e,t,r){super(null!=e?e:D_.DEFAULT_MESSAGE,null!=t?t:"invalid_payload",r)}}D_.DEFAULT_MESSAGE="Invalid payload",function(e){e.DominantSpeaker="dominant-speaker",e.PeersVolumes="peers-volumes",e.Silence="silence"}(P_||(P_={}));let I_=class{constructor(e,t){this.peersStorage=e,R_.set(this,void 0),c(this,R_,t("ChannelAudioObserverMissingProducerRestorer"),"f")}handlePeerVolume(e){const{peerId:t,producerId:r}=e,n=this.peersStorage.get(t);if(!n)return;if(n.producers.has(r))return;const i={id:r,kind:"audio",peerId:t,label:exports.TrackLabel.Microphone,paused:!1,encodings:jh,maxSpatialLayer:0};n.observer.safeEmit(Ln,i),a(this,R_,"f").warn("Recovered missing audio producer from audio observer volume",{peerId:t,producerId:r})}};R_=new WeakMap,I_=n([ot(),i(0,ct(mi.PeersStorage)),i(1,ct(mi.LoggerFactory)),s("design:paramtypes",[fo,Function])],I_);var A_,O_,M_,N_,L_,x_=I_;let F_=L_=class{constructor(e,t,r,n){this.peersStorage=e,this.clientEventEmitter=t,this.channelAudioObserverMissingProducerRestorer=r,A_.set(this,void 0),O_.set(this,void 0),M_.set(this,void 0),N_.set(this,void 0),c(this,A_,n("ChannelAudioObserverEventHandler"),"f"),this.watchPeersLeave()}handle(e){try{const t=JSON.parse(e);switch(L_.validateEventPayload(t),t.event){case P_.DominantSpeaker:this.handleDominantSpeaker(t);break;case P_.PeersVolumes:this.handlePeerVolumes(t);break;case P_.Silence:this.handleSilence()}}catch(t){a(this,A_,"f").warn("Failed to handle audio observer event",{error:Vt(t),eventData:e})}}handleDominantSpeaker(e){const{peerId:t}=e.data,r=this.peersStorage.get(t);c(this,M_,r,"f"),c(this,N_,r,"f"),this.setActiveSpeaker(r)}handlePeerVolumes(e){e.volumes.forEach((e=>{var t;const{peerId:r,trackLabel:n,value:i}=e,s=this.peersStorage.get(r);if(!s)return;i>0&&!a(this,M_,"f")&&s.id===(null===(t=a(this,N_,"f"))||void 0===t?void 0:t.id)&&(c(this,M_,s,"f"),this.setActiveSpeaker(s));const o=null==s?void 0:s.tracks.get(n);o&&o.setVolume(i)}))}handleSilence(){this.peersStorage.all().flatMap((e=>Array.from(e.tracks.values()))).forEach((e=>e.setVolume(0))),c(this,M_,void 0,"f"),this.setActiveSpeaker(void 0)}watchPeersLeave(){this.clientEventEmitter.on(qr,(e=>{var t;e===(null===(t=a(this,M_,"f"))||void 0===t?void 0:t.id)&&this.setActiveSpeaker(void 0)}))}setActiveSpeaker(e){a(this,O_,"f")!==(null==e?void 0:e.id)&&(c(this,O_,null==e?void 0:e.id,"f"),this.clientEventEmitter.safeEmit(Xr,{peer:e}))}static validateEventPayload(e){switch(e.event){case P_.Silence:break;case P_.DominantSpeaker:{e.data||L_.throwInvalidPayload();const{peerId:t,producerId:r,trackLabel:n}=e.data;"string"==typeof t&&"string"==typeof r&&n===exports.TrackLabel.Microphone||L_.throwInvalidPayload();break}case P_.PeersVolumes:Array.isArray(e.volumes)||L_.throwInvalidPayload(),e.volumes.forEach((e=>{const{peerId:t,producerId:r,value:n,trackLabel:i}=e;"string"==typeof t&&"string"==typeof r&&"number"==typeof n&&i===exports.TrackLabel.Microphone||L_.throwInvalidPayload()}));break;default:L_.throwInvalidPayload()}}static throwInvalidPayload(){throw new D_("invalid_channel_audio_observer_payload")}};A_=new WeakMap,O_=new WeakMap,M_=new WeakMap,N_=new WeakMap,F_=L_=n([ot(),i(0,ct(mi.PeersStorage)),i(1,ct(mi.ClientEventEmitter)),i(2,ct(mi.ChannelAudioObserverMissingProducerRestorer)),i(3,ct(mi.LoggerFactory)),s("design:paramtypes",[fo,Ft,x_,Function])],F_);var j_=F_,U_={},V_={},B_={},W_={exports:{}};
30
30
  /**
31
31
  * @license
32
32
  * Lodash <https://lodash.com/>
@@ -35,5 +35,5 @@ and limitations under the License.
35
35
  * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
36
36
  * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
37
37
  */
38
- !function(e,t){(function(){var r,n="Expected a function",i="__lodash_hash_undefined__",s="__lodash_placeholder__",o=16,a=32,c=64,d=128,l=256,p=1/0,h=9007199254740991,f=NaN,m=4294967295,g=[["ary",d],["bind",1],["bindKey",2],["curry",8],["curryRight",o],["flip",512],["partial",a],["partialRight",c],["rearg",l]],v="[object Arguments]",y="[object Array]",b="[object Boolean]",_="[object Date]",E="[object Error]",w="[object Function]",S="[object GeneratorFunction]",C="[object Map]",P="[object Number]",T="[object Object]",R="[object Promise]",k="[object RegExp]",D="[object Set]",I="[object String]",A="[object Symbol]",O="[object WeakMap]",M="[object ArrayBuffer]",N="[object DataView]",L="[object Float32Array]",x="[object Float64Array]",F="[object Int8Array]",j="[object Int16Array]",U="[object Int32Array]",V="[object Uint8Array]",B="[object Uint8ClampedArray]",W="[object Uint16Array]",H="[object Uint32Array]",q=/\b__p \+= '';/g,z=/\b(__p \+=) '' \+/g,G=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Y=/&(?:amp|lt|gt|quot|#39);/g,$=/[&<>"']/g,J=RegExp(Y.source),Q=RegExp($.source),K=/<%-([\s\S]+?)%>/g,Z=/<%([\s\S]+?)%>/g,X=/<%=([\s\S]+?)%>/g,ee=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,te=/^\w*$/,re=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ne=/[\\^$.*+?()[\]{}|]/g,ie=RegExp(ne.source),se=/^\s+/,oe=/\s/,ae=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,ce=/\{\n\/\* \[wrapped with (.+)\] \*/,de=/,? & /,ue=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,le=/[()=,{}\[\]\/\s]/,pe=/\\(\\)?/g,he=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,fe=/\w*$/,me=/^[-+]0x[0-9a-f]+$/i,ge=/^0b[01]+$/i,ve=/^\[object .+?Constructor\]$/,ye=/^0o[0-7]+$/i,be=/^(?:0|[1-9]\d*)$/,_e=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Ee=/($^)/,we=/['\n\r\u2028\u2029\\]/g,Se="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",Ce="\\u2700-\\u27bf",Pe="a-z\\xdf-\\xf6\\xf8-\\xff",Te="A-Z\\xc0-\\xd6\\xd8-\\xde",Re="\\ufe0e\\ufe0f",ke="\\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",De="['’]",Ie="[\\ud800-\\udfff]",Ae="["+ke+"]",Oe="["+Se+"]",Me="\\d+",Ne="[\\u2700-\\u27bf]",Le="["+Pe+"]",xe="[^\\ud800-\\udfff"+ke+Me+Ce+Pe+Te+"]",Fe="\\ud83c[\\udffb-\\udfff]",je="[^\\ud800-\\udfff]",Ue="(?:\\ud83c[\\udde6-\\uddff]){2}",Ve="[\\ud800-\\udbff][\\udc00-\\udfff]",Be="["+Te+"]",We="(?:"+Le+"|"+xe+")",He="(?:"+Be+"|"+xe+")",qe="(?:['’](?:d|ll|m|re|s|t|ve))?",ze="(?:['’](?:D|LL|M|RE|S|T|VE))?",Ge="(?:"+Oe+"|"+Fe+")"+"?",Ye="[\\ufe0e\\ufe0f]?",$e=Ye+Ge+("(?:\\u200d(?:"+[je,Ue,Ve].join("|")+")"+Ye+Ge+")*"),Je="(?:"+[Ne,Ue,Ve].join("|")+")"+$e,Qe="(?:"+[je+Oe+"?",Oe,Ue,Ve,Ie].join("|")+")",Ke=RegExp(De,"g"),Ze=RegExp(Oe,"g"),Xe=RegExp(Fe+"(?="+Fe+")|"+Qe+$e,"g"),et=RegExp([Be+"?"+Le+"+"+qe+"(?="+[Ae,Be,"$"].join("|")+")",He+"+"+ze+"(?="+[Ae,Be+We,"$"].join("|")+")",Be+"?"+We+"+"+qe,Be+"+"+ze,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Me,Je].join("|"),"g"),tt=RegExp("[\\u200d\\ud800-\\udfff"+Se+Re+"]"),rt=/[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"],it=-1,st={};st[L]=st[x]=st[F]=st[j]=st[U]=st[V]=st[B]=st[W]=st[H]=!0,st[v]=st[y]=st[M]=st[b]=st[N]=st[_]=st[E]=st[w]=st[C]=st[P]=st[T]=st[k]=st[D]=st[I]=st[O]=!1;var ot={};ot[v]=ot[y]=ot[M]=ot[N]=ot[b]=ot[_]=ot[L]=ot[x]=ot[F]=ot[j]=ot[U]=ot[C]=ot[P]=ot[T]=ot[k]=ot[D]=ot[I]=ot[A]=ot[V]=ot[B]=ot[W]=ot[H]=!0,ot[E]=ot[w]=ot[O]=!1;var at={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},ct=parseFloat,dt=parseInt,ut="object"==typeof u&&u&&u.Object===Object&&u,lt="object"==typeof self&&self&&self.Object===Object&&self,pt=ut||lt||Function("return this")(),ht=t&&!t.nodeType&&t,ft=ht&&e&&!e.nodeType&&e,mt=ft&&ft.exports===ht,gt=mt&&ut.process,vt=function(){try{var e=ft&&ft.require&&ft.require("util").types;return e||gt&&gt.binding&&gt.binding("util")}catch(e){}}(),yt=vt&&vt.isArrayBuffer,bt=vt&&vt.isDate,_t=vt&&vt.isMap,Et=vt&&vt.isRegExp,wt=vt&&vt.isSet,St=vt&&vt.isTypedArray;function Ct(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}function Pt(e,t,r,n){for(var i=-1,s=null==e?0:e.length;++i<s;){var o=e[i];t(n,o,r(o),e)}return n}function Tt(e,t){for(var r=-1,n=null==e?0:e.length;++r<n&&!1!==t(e[r],r,e););return e}function Rt(e,t){for(var r=null==e?0:e.length;r--&&!1!==t(e[r],r,e););return e}function kt(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(!t(e[r],r,e))return!1;return!0}function Dt(e,t){for(var r=-1,n=null==e?0:e.length,i=0,s=[];++r<n;){var o=e[r];t(o,r,e)&&(s[i++]=o)}return s}function It(e,t){return!!(null==e?0:e.length)&&Vt(e,t,0)>-1}function At(e,t,r){for(var n=-1,i=null==e?0:e.length;++n<i;)if(r(t,e[n]))return!0;return!1}function Ot(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i}function Mt(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}function Nt(e,t,r,n){var i=-1,s=null==e?0:e.length;for(n&&s&&(r=e[++i]);++i<s;)r=t(r,e[i],i,e);return r}function Lt(e,t,r,n){var i=null==e?0:e.length;for(n&&i&&(r=e[--i]);i--;)r=t(r,e[i],i,e);return r}function xt(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}var Ft=qt("length");function jt(e,t,r){var n;return r(e,(function(e,r,i){if(t(e,r,i))return n=r,!1})),n}function Ut(e,t,r,n){for(var i=e.length,s=r+(n?1:-1);n?s--:++s<i;)if(t(e[s],s,e))return s;return-1}function Vt(e,t,r){return t==t?function(e,t,r){var n=r-1,i=e.length;for(;++n<i;)if(e[n]===t)return n;return-1}(e,t,r):Ut(e,Wt,r)}function Bt(e,t,r,n){for(var i=r-1,s=e.length;++i<s;)if(n(e[i],t))return i;return-1}function Wt(e){return e!=e}function Ht(e,t){var r=null==e?0:e.length;return r?Yt(e,t)/r:f}function qt(e){return function(t){return null==t?r:t[e]}}function zt(e){return function(t){return null==e?r:e[t]}}function Gt(e,t,r,n,i){return i(e,(function(e,i,s){r=n?(n=!1,e):t(r,e,i,s)})),r}function Yt(e,t){for(var n,i=-1,s=e.length;++i<s;){var o=t(e[i]);o!==r&&(n=n===r?o:n+o)}return n}function $t(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}function Jt(e){return e?e.slice(0,hr(e)+1).replace(se,""):e}function Qt(e){return function(t){return e(t)}}function Kt(e,t){return Ot(t,(function(t){return e[t]}))}function Zt(e,t){return e.has(t)}function Xt(e,t){for(var r=-1,n=e.length;++r<n&&Vt(t,e[r],0)>-1;);return r}function er(e,t){for(var r=e.length;r--&&Vt(t,e[r],0)>-1;);return r}function tr(e,t){for(var r=e.length,n=0;r--;)e[r]===t&&++n;return n}var rr=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"}),nr=zt({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"});function ir(e){return"\\"+at[e]}function sr(e){return tt.test(e)}function or(e){var t=-1,r=Array(e.size);return e.forEach((function(e,n){r[++t]=[n,e]})),r}function ar(e,t){return function(r){return e(t(r))}}function cr(e,t){for(var r=-1,n=e.length,i=0,o=[];++r<n;){var a=e[r];a!==t&&a!==s||(e[r]=s,o[i++]=r)}return o}function dr(e){var t=-1,r=Array(e.size);return e.forEach((function(e){r[++t]=e})),r}function ur(e){var t=-1,r=Array(e.size);return e.forEach((function(e){r[++t]=[e,e]})),r}function lr(e){return sr(e)?function(e){var t=Xe.lastIndex=0;for(;Xe.test(e);)++t;return t}(e):Ft(e)}function pr(e){return sr(e)?function(e){return e.match(Xe)||[]}(e):function(e){return e.split("")}(e)}function hr(e){for(var t=e.length;t--&&oe.test(e.charAt(t)););return t}var fr=zt({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"});var mr=function e(t){var u,oe=(t=null==t?pt:mr.defaults(pt.Object(),t,mr.pick(pt,nt))).Array,Se=t.Date,Ce=t.Error,Pe=t.Function,Te=t.Math,Re=t.Object,ke=t.RegExp,De=t.String,Ie=t.TypeError,Ae=oe.prototype,Oe=Pe.prototype,Me=Re.prototype,Ne=t["__core-js_shared__"],Le=Oe.toString,xe=Me.hasOwnProperty,Fe=0,je=(u=/[^.]+$/.exec(Ne&&Ne.keys&&Ne.keys.IE_PROTO||""))?"Symbol(src)_1."+u:"",Ue=Me.toString,Ve=Le.call(Re),Be=pt._,We=ke("^"+Le.call(xe).replace(ne,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),He=mt?t.Buffer:r,qe=t.Symbol,ze=t.Uint8Array,Ge=He?He.allocUnsafe:r,Ye=ar(Re.getPrototypeOf,Re),$e=Re.create,Je=Me.propertyIsEnumerable,Qe=Ae.splice,Xe=qe?qe.isConcatSpreadable:r,tt=qe?qe.iterator:r,at=qe?qe.toStringTag:r,ut=function(){try{var e=hs(Re,"defineProperty");return e({},"",{}),e}catch(e){}}(),lt=t.clearTimeout!==pt.clearTimeout&&t.clearTimeout,ht=Se&&Se.now!==pt.Date.now&&Se.now,ft=t.setTimeout!==pt.setTimeout&&t.setTimeout,gt=Te.ceil,vt=Te.floor,Ft=Re.getOwnPropertySymbols,zt=He?He.isBuffer:r,gr=t.isFinite,vr=Ae.join,yr=ar(Re.keys,Re),br=Te.max,_r=Te.min,Er=Se.now,wr=t.parseInt,Sr=Te.random,Cr=Ae.reverse,Pr=hs(t,"DataView"),Tr=hs(t,"Map"),Rr=hs(t,"Promise"),kr=hs(t,"Set"),Dr=hs(t,"WeakMap"),Ir=hs(Re,"create"),Ar=Dr&&new Dr,Or={},Mr=Vs(Pr),Nr=Vs(Tr),Lr=Vs(Rr),xr=Vs(kr),Fr=Vs(Dr),jr=qe?qe.prototype:r,Ur=jr?jr.valueOf:r,Vr=jr?jr.toString:r;function Br(e){if(ia(e)&&!Yo(e)&&!(e instanceof zr)){if(e instanceof qr)return e;if(xe.call(e,"__wrapped__"))return Bs(e)}return new qr(e)}var Wr=function(){function e(){}return function(t){if(!na(t))return{};if($e)return $e(t);e.prototype=t;var n=new e;return e.prototype=r,n}}();function Hr(){}function qr(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=r}function zr(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=m,this.__views__=[]}function Gr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Yr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function $r(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Jr(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new $r;++t<r;)this.add(e[t])}function Qr(e){var t=this.__data__=new Yr(e);this.size=t.size}function Kr(e,t){var r=Yo(e),n=!r&&Go(e),i=!r&&!n&&Ko(e),s=!r&&!n&&!i&&pa(e),o=r||n||i||s,a=o?$t(e.length,De):[],c=a.length;for(var d in e)!t&&!xe.call(e,d)||o&&("length"==d||i&&("offset"==d||"parent"==d)||s&&("buffer"==d||"byteLength"==d||"byteOffset"==d)||_s(d,c))||a.push(d);return a}function Zr(e){var t=e.length;return t?e[Qn(0,t-1)]:r}function Xr(e,t){return Fs(Ai(e),dn(t,0,e.length))}function en(e){return Fs(Ai(e))}function tn(e,t,n){(n!==r&&!Ho(e[t],n)||n===r&&!(t in e))&&an(e,t,n)}function rn(e,t,n){var i=e[t];xe.call(e,t)&&Ho(i,n)&&(n!==r||t in e)||an(e,t,n)}function nn(e,t){for(var r=e.length;r--;)if(Ho(e[r][0],t))return r;return-1}function sn(e,t,r,n){return fn(e,(function(e,i,s){t(n,e,r(e),s)})),n}function on(e,t){return e&&Oi(t,Na(t),e)}function an(e,t,r){"__proto__"==t&&ut?ut(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}function cn(e,t){for(var n=-1,i=t.length,s=oe(i),o=null==e;++n<i;)s[n]=o?r:Da(e,t[n]);return s}function dn(e,t,n){return e==e&&(n!==r&&(e=e<=n?e:n),t!==r&&(e=e>=t?e:t)),e}function un(e,t,n,i,s,o){var a,c=1&t,d=2&t,u=4&t;if(n&&(a=s?n(e,i,s,o):n(e)),a!==r)return a;if(!na(e))return e;var l=Yo(e);if(l){if(a=function(e){var t=e.length,r=new e.constructor(t);t&&"string"==typeof e[0]&&xe.call(e,"index")&&(r.index=e.index,r.input=e.input);return r}(e),!c)return Ai(e,a)}else{var p=gs(e),h=p==w||p==S;if(Ko(e))return Pi(e,c);if(p==T||p==v||h&&!s){if(a=d||h?{}:ys(e),!c)return d?function(e,t){return Oi(e,ms(e),t)}(e,function(e,t){return e&&Oi(t,La(t),e)}(a,e)):function(e,t){return Oi(e,fs(e),t)}(e,on(a,e))}else{if(!ot[p])return s?e:{};a=function(e,t,r){var n=e.constructor;switch(t){case M:return Ti(e);case b:case _:return new n(+e);case N:return function(e,t){var r=t?Ti(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}(e,r);case L:case x:case F:case j:case U:case V:case B:case W:case H:return Ri(e,r);case C:case D:return new n;case P:case I:return new n(e);case k:return function(e){var t=new e.constructor(e.source,fe.exec(e));return t.lastIndex=e.lastIndex,t}(e);case A:return function(e){return Ur?Re(Ur.call(e)):{}}(e)}}(e,p,c)}}o||(o=new Qr);var f=o.get(e);if(f)return f;o.set(e,a),da(e)?e.forEach((function(r){a.add(un(r,t,n,r,e,o))})):sa(e)&&e.forEach((function(r,i){a.set(i,un(r,t,n,i,e,o))}));var m=l?r:(u?d?os:ss:d?La:Na)(e);return Tt(m||e,(function(r,i){m&&(r=e[i=r]),rn(a,i,un(r,t,n,i,e,o))})),a}function ln(e,t,n){var i=n.length;if(null==e)return!i;for(e=Re(e);i--;){var s=n[i],o=t[s],a=e[s];if(a===r&&!(s in e)||!o(a))return!1}return!0}function pn(e,t,i){if("function"!=typeof e)throw new Ie(n);return Ms((function(){e.apply(r,i)}),t)}function hn(e,t,r,n){var i=-1,s=It,o=!0,a=e.length,c=[],d=t.length;if(!a)return c;r&&(t=Ot(t,Qt(r))),n?(s=At,o=!1):t.length>=200&&(s=Zt,o=!1,t=new Jr(t));e:for(;++i<a;){var u=e[i],l=null==r?u:r(u);if(u=n||0!==u?u:0,o&&l==l){for(var p=d;p--;)if(t[p]===l)continue e;c.push(u)}else s(t,l,n)||c.push(u)}return c}Br.templateSettings={escape:K,evaluate:Z,interpolate:X,variable:"",imports:{_:Br}},Br.prototype=Hr.prototype,Br.prototype.constructor=Br,qr.prototype=Wr(Hr.prototype),qr.prototype.constructor=qr,zr.prototype=Wr(Hr.prototype),zr.prototype.constructor=zr,Gr.prototype.clear=function(){this.__data__=Ir?Ir(null):{},this.size=0},Gr.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},Gr.prototype.get=function(e){var t=this.__data__;if(Ir){var n=t[e];return n===i?r:n}return xe.call(t,e)?t[e]:r},Gr.prototype.has=function(e){var t=this.__data__;return Ir?t[e]!==r:xe.call(t,e)},Gr.prototype.set=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=Ir&&t===r?i:t,this},Yr.prototype.clear=function(){this.__data__=[],this.size=0},Yr.prototype.delete=function(e){var t=this.__data__,r=nn(t,e);return!(r<0)&&(r==t.length-1?t.pop():Qe.call(t,r,1),--this.size,!0)},Yr.prototype.get=function(e){var t=this.__data__,n=nn(t,e);return n<0?r:t[n][1]},Yr.prototype.has=function(e){return nn(this.__data__,e)>-1},Yr.prototype.set=function(e,t){var r=this.__data__,n=nn(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this},$r.prototype.clear=function(){this.size=0,this.__data__={hash:new Gr,map:new(Tr||Yr),string:new Gr}},$r.prototype.delete=function(e){var t=ls(this,e).delete(e);return this.size-=t?1:0,t},$r.prototype.get=function(e){return ls(this,e).get(e)},$r.prototype.has=function(e){return ls(this,e).has(e)},$r.prototype.set=function(e,t){var r=ls(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this},Jr.prototype.add=Jr.prototype.push=function(e){return this.__data__.set(e,i),this},Jr.prototype.has=function(e){return this.__data__.has(e)},Qr.prototype.clear=function(){this.__data__=new Yr,this.size=0},Qr.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},Qr.prototype.get=function(e){return this.__data__.get(e)},Qr.prototype.has=function(e){return this.__data__.has(e)},Qr.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Yr){var n=r.__data__;if(!Tr||n.length<199)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new $r(n)}return r.set(e,t),this.size=r.size,this};var fn=Li(wn),mn=Li(Sn,!0);function gn(e,t){var r=!0;return fn(e,(function(e,n,i){return r=!!t(e,n,i)})),r}function vn(e,t,n){for(var i=-1,s=e.length;++i<s;){var o=e[i],a=t(o);if(null!=a&&(c===r?a==a&&!la(a):n(a,c)))var c=a,d=o}return d}function yn(e,t){var r=[];return fn(e,(function(e,n,i){t(e,n,i)&&r.push(e)})),r}function bn(e,t,r,n,i){var s=-1,o=e.length;for(r||(r=bs),i||(i=[]);++s<o;){var a=e[s];t>0&&r(a)?t>1?bn(a,t-1,r,n,i):Mt(i,a):n||(i[i.length]=a)}return i}var _n=xi(),En=xi(!0);function wn(e,t){return e&&_n(e,t,Na)}function Sn(e,t){return e&&En(e,t,Na)}function Cn(e,t){return Dt(t,(function(t){return ea(e[t])}))}function Pn(e,t){for(var n=0,i=(t=Ei(t,e)).length;null!=e&&n<i;)e=e[Us(t[n++])];return n&&n==i?e:r}function Tn(e,t,r){var n=t(e);return Yo(e)?n:Mt(n,r(e))}function Rn(e){return null==e?e===r?"[object Undefined]":"[object Null]":at&&at in Re(e)?function(e){var t=xe.call(e,at),n=e[at];try{e[at]=r;var i=!0}catch(e){}var s=Ue.call(e);i&&(t?e[at]=n:delete e[at]);return s}(e):function(e){return Ue.call(e)}(e)}function kn(e,t){return e>t}function Dn(e,t){return null!=e&&xe.call(e,t)}function In(e,t){return null!=e&&t in Re(e)}function An(e,t,n){for(var i=n?At:It,s=e[0].length,o=e.length,a=o,c=oe(o),d=1/0,u=[];a--;){var l=e[a];a&&t&&(l=Ot(l,Qt(t))),d=_r(l.length,d),c[a]=!n&&(t||s>=120&&l.length>=120)?new Jr(a&&l):r}l=e[0];var p=-1,h=c[0];e:for(;++p<s&&u.length<d;){var f=l[p],m=t?t(f):f;if(f=n||0!==f?f:0,!(h?Zt(h,m):i(u,m,n))){for(a=o;--a;){var g=c[a];if(!(g?Zt(g,m):i(e[a],m,n)))continue e}h&&h.push(m),u.push(f)}}return u}function On(e,t,n){var i=null==(e=Ds(e,t=Ei(t,e)))?e:e[Us(Zs(t))];return null==i?r:Ct(i,e,n)}function Mn(e){return ia(e)&&Rn(e)==v}function Nn(e,t,n,i,s){return e===t||(null==e||null==t||!ia(e)&&!ia(t)?e!=e&&t!=t:function(e,t,n,i,s,o){var a=Yo(e),c=Yo(t),d=a?y:gs(e),u=c?y:gs(t),l=(d=d==v?T:d)==T,p=(u=u==v?T:u)==T,h=d==u;if(h&&Ko(e)){if(!Ko(t))return!1;a=!0,l=!1}if(h&&!l)return o||(o=new Qr),a||pa(e)?ns(e,t,n,i,s,o):function(e,t,r,n,i,s,o){switch(r){case N:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case M:return!(e.byteLength!=t.byteLength||!s(new ze(e),new ze(t)));case b:case _:case P:return Ho(+e,+t);case E:return e.name==t.name&&e.message==t.message;case k:case I:return e==t+"";case C:var a=or;case D:var c=1&n;if(a||(a=dr),e.size!=t.size&&!c)return!1;var d=o.get(e);if(d)return d==t;n|=2,o.set(e,t);var u=ns(a(e),a(t),n,i,s,o);return o.delete(e),u;case A:if(Ur)return Ur.call(e)==Ur.call(t)}return!1}(e,t,d,n,i,s,o);if(!(1&n)){var f=l&&xe.call(e,"__wrapped__"),m=p&&xe.call(t,"__wrapped__");if(f||m){var g=f?e.value():e,w=m?t.value():t;return o||(o=new Qr),s(g,w,n,i,o)}}if(!h)return!1;return o||(o=new Qr),function(e,t,n,i,s,o){var a=1&n,c=ss(e),d=c.length,u=ss(t).length;if(d!=u&&!a)return!1;var l=d;for(;l--;){var p=c[l];if(!(a?p in t:xe.call(t,p)))return!1}var h=o.get(e),f=o.get(t);if(h&&f)return h==t&&f==e;var m=!0;o.set(e,t),o.set(t,e);var g=a;for(;++l<d;){var v=e[p=c[l]],y=t[p];if(i)var b=a?i(y,v,p,t,e,o):i(v,y,p,e,t,o);if(!(b===r?v===y||s(v,y,n,i,o):b)){m=!1;break}g||(g="constructor"==p)}if(m&&!g){var _=e.constructor,E=t.constructor;_==E||!("constructor"in e)||!("constructor"in t)||"function"==typeof _&&_ instanceof _&&"function"==typeof E&&E instanceof E||(m=!1)}return o.delete(e),o.delete(t),m}(e,t,n,i,s,o)}(e,t,n,i,Nn,s))}function Ln(e,t,n,i){var s=n.length,o=s,a=!i;if(null==e)return!o;for(e=Re(e);s--;){var c=n[s];if(a&&c[2]?c[1]!==e[c[0]]:!(c[0]in e))return!1}for(;++s<o;){var d=(c=n[s])[0],u=e[d],l=c[1];if(a&&c[2]){if(u===r&&!(d in e))return!1}else{var p=new Qr;if(i)var h=i(u,l,d,e,t,p);if(!(h===r?Nn(l,u,3,i,p):h))return!1}}return!0}function xn(e){return!(!na(e)||(t=e,je&&je in t))&&(ea(e)?We:ve).test(Vs(e));var t}function Fn(e){return"function"==typeof e?e:null==e?oc:"object"==typeof e?Yo(e)?Hn(e[0],e[1]):Wn(e):mc(e)}function jn(e){if(!Ps(e))return yr(e);var t=[];for(var r in Re(e))xe.call(e,r)&&"constructor"!=r&&t.push(r);return t}function Un(e){if(!na(e))return function(e){var t=[];if(null!=e)for(var r in Re(e))t.push(r);return t}(e);var t=Ps(e),r=[];for(var n in e)("constructor"!=n||!t&&xe.call(e,n))&&r.push(n);return r}function Vn(e,t){return e<t}function Bn(e,t){var r=-1,n=Jo(e)?oe(e.length):[];return fn(e,(function(e,i,s){n[++r]=t(e,i,s)})),n}function Wn(e){var t=ps(e);return 1==t.length&&t[0][2]?Rs(t[0][0],t[0][1]):function(r){return r===e||Ln(r,e,t)}}function Hn(e,t){return ws(e)&&Ts(t)?Rs(Us(e),t):function(n){var i=Da(n,e);return i===r&&i===t?Ia(n,e):Nn(t,i,3)}}function qn(e,t,n,i,s){e!==t&&_n(t,(function(o,a){if(s||(s=new Qr),na(o))!function(e,t,n,i,s,o,a){var c=As(e,n),d=As(t,n),u=a.get(d);if(u)return void tn(e,n,u);var l=o?o(c,d,n+"",e,t,a):r,p=l===r;if(p){var h=Yo(d),f=!h&&Ko(d),m=!h&&!f&&pa(d);l=d,h||f||m?Yo(c)?l=c:Qo(c)?l=Ai(c):f?(p=!1,l=Pi(d,!0)):m?(p=!1,l=Ri(d,!0)):l=[]:aa(d)||Go(d)?(l=c,Go(c)?l=_a(c):na(c)&&!ea(c)||(l=ys(d))):p=!1}p&&(a.set(d,l),s(l,d,i,o,a),a.delete(d));tn(e,n,l)}(e,t,a,n,qn,i,s);else{var c=i?i(As(e,a),o,a+"",e,t,s):r;c===r&&(c=o),tn(e,a,c)}}),La)}function zn(e,t){var n=e.length;if(n)return _s(t+=t<0?n:0,n)?e[t]:r}function Gn(e,t,r){t=t.length?Ot(t,(function(e){return Yo(e)?function(t){return Pn(t,1===e.length?e[0]:e)}:e})):[oc];var n=-1;t=Ot(t,Qt(us()));var i=Bn(e,(function(e,r,i){var s=Ot(t,(function(t){return t(e)}));return{criteria:s,index:++n,value:e}}));return function(e,t){var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e}(i,(function(e,t){return function(e,t,r){var n=-1,i=e.criteria,s=t.criteria,o=i.length,a=r.length;for(;++n<o;){var c=ki(i[n],s[n]);if(c)return n>=a?c:c*("desc"==r[n]?-1:1)}return e.index-t.index}(e,t,r)}))}function Yn(e,t,r){for(var n=-1,i=t.length,s={};++n<i;){var o=t[n],a=Pn(e,o);r(a,o)&&ti(s,Ei(o,e),a)}return s}function $n(e,t,r,n){var i=n?Bt:Vt,s=-1,o=t.length,a=e;for(e===t&&(t=Ai(t)),r&&(a=Ot(e,Qt(r)));++s<o;)for(var c=0,d=t[s],u=r?r(d):d;(c=i(a,u,c,n))>-1;)a!==e&&Qe.call(a,c,1),Qe.call(e,c,1);return e}function Jn(e,t){for(var r=e?t.length:0,n=r-1;r--;){var i=t[r];if(r==n||i!==s){var s=i;_s(i)?Qe.call(e,i,1):hi(e,i)}}return e}function Qn(e,t){return e+vt(Sr()*(t-e+1))}function Kn(e,t){var r="";if(!e||t<1||t>h)return r;do{t%2&&(r+=e),(t=vt(t/2))&&(e+=e)}while(t);return r}function Zn(e,t){return Ns(ks(e,t,oc),e+"")}function Xn(e){return Zr(Ha(e))}function ei(e,t){var r=Ha(e);return Fs(r,dn(t,0,r.length))}function ti(e,t,n,i){if(!na(e))return e;for(var s=-1,o=(t=Ei(t,e)).length,a=o-1,c=e;null!=c&&++s<o;){var d=Us(t[s]),u=n;if("__proto__"===d||"constructor"===d||"prototype"===d)return e;if(s!=a){var l=c[d];(u=i?i(l,d,c):r)===r&&(u=na(l)?l:_s(t[s+1])?[]:{})}rn(c,d,u),c=c[d]}return e}var ri=Ar?function(e,t){return Ar.set(e,t),e}:oc,ni=ut?function(e,t){return ut(e,"toString",{configurable:!0,enumerable:!1,value:nc(t),writable:!0})}:oc;function ii(e){return Fs(Ha(e))}function si(e,t,r){var n=-1,i=e.length;t<0&&(t=-t>i?0:i+t),(r=r>i?i:r)<0&&(r+=i),i=t>r?0:r-t>>>0,t>>>=0;for(var s=oe(i);++n<i;)s[n]=e[n+t];return s}function oi(e,t){var r;return fn(e,(function(e,n,i){return!(r=t(e,n,i))})),!!r}function ai(e,t,r){var n=0,i=null==e?n:e.length;if("number"==typeof t&&t==t&&i<=2147483647){for(;n<i;){var s=n+i>>>1,o=e[s];null!==o&&!la(o)&&(r?o<=t:o<t)?n=s+1:i=s}return i}return ci(e,t,oc,r)}function ci(e,t,n,i){var s=0,o=null==e?0:e.length;if(0===o)return 0;for(var a=(t=n(t))!=t,c=null===t,d=la(t),u=t===r;s<o;){var l=vt((s+o)/2),p=n(e[l]),h=p!==r,f=null===p,m=p==p,g=la(p);if(a)var v=i||m;else v=u?m&&(i||h):c?m&&h&&(i||!f):d?m&&h&&!f&&(i||!g):!f&&!g&&(i?p<=t:p<t);v?s=l+1:o=l}return _r(o,4294967294)}function di(e,t){for(var r=-1,n=e.length,i=0,s=[];++r<n;){var o=e[r],a=t?t(o):o;if(!r||!Ho(a,c)){var c=a;s[i++]=0===o?0:o}}return s}function ui(e){return"number"==typeof e?e:la(e)?f:+e}function li(e){if("string"==typeof e)return e;if(Yo(e))return Ot(e,li)+"";if(la(e))return Vr?Vr.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function pi(e,t,r){var n=-1,i=It,s=e.length,o=!0,a=[],c=a;if(r)o=!1,i=At;else if(s>=200){var d=t?null:Ki(e);if(d)return dr(d);o=!1,i=Zt,c=new Jr}else c=t?[]:a;e:for(;++n<s;){var u=e[n],l=t?t(u):u;if(u=r||0!==u?u:0,o&&l==l){for(var p=c.length;p--;)if(c[p]===l)continue e;t&&c.push(l),a.push(u)}else i(c,l,r)||(c!==a&&c.push(l),a.push(u))}return a}function hi(e,t){return null==(e=Ds(e,t=Ei(t,e)))||delete e[Us(Zs(t))]}function fi(e,t,r,n){return ti(e,t,r(Pn(e,t)),n)}function mi(e,t,r,n){for(var i=e.length,s=n?i:-1;(n?s--:++s<i)&&t(e[s],s,e););return r?si(e,n?0:s,n?s+1:i):si(e,n?s+1:0,n?i:s)}function gi(e,t){var r=e;return r instanceof zr&&(r=r.value()),Nt(t,(function(e,t){return t.func.apply(t.thisArg,Mt([e],t.args))}),r)}function vi(e,t,r){var n=e.length;if(n<2)return n?pi(e[0]):[];for(var i=-1,s=oe(n);++i<n;)for(var o=e[i],a=-1;++a<n;)a!=i&&(s[i]=hn(s[i]||o,e[a],t,r));return pi(bn(s,1),t,r)}function yi(e,t,n){for(var i=-1,s=e.length,o=t.length,a={};++i<s;){var c=i<o?t[i]:r;n(a,e[i],c)}return a}function bi(e){return Qo(e)?e:[]}function _i(e){return"function"==typeof e?e:oc}function Ei(e,t){return Yo(e)?e:ws(e,t)?[e]:js(Ea(e))}var wi=Zn;function Si(e,t,n){var i=e.length;return n=n===r?i:n,!t&&n>=i?e:si(e,t,n)}var Ci=lt||function(e){return pt.clearTimeout(e)};function Pi(e,t){if(t)return e.slice();var r=e.length,n=Ge?Ge(r):new e.constructor(r);return e.copy(n),n}function Ti(e){var t=new e.constructor(e.byteLength);return new ze(t).set(new ze(e)),t}function Ri(e,t){var r=t?Ti(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}function ki(e,t){if(e!==t){var n=e!==r,i=null===e,s=e==e,o=la(e),a=t!==r,c=null===t,d=t==t,u=la(t);if(!c&&!u&&!o&&e>t||o&&a&&d&&!c&&!u||i&&a&&d||!n&&d||!s)return 1;if(!i&&!o&&!u&&e<t||u&&n&&s&&!i&&!o||c&&n&&s||!a&&s||!d)return-1}return 0}function Di(e,t,r,n){for(var i=-1,s=e.length,o=r.length,a=-1,c=t.length,d=br(s-o,0),u=oe(c+d),l=!n;++a<c;)u[a]=t[a];for(;++i<o;)(l||i<s)&&(u[r[i]]=e[i]);for(;d--;)u[a++]=e[i++];return u}function Ii(e,t,r,n){for(var i=-1,s=e.length,o=-1,a=r.length,c=-1,d=t.length,u=br(s-a,0),l=oe(u+d),p=!n;++i<u;)l[i]=e[i];for(var h=i;++c<d;)l[h+c]=t[c];for(;++o<a;)(p||i<s)&&(l[h+r[o]]=e[i++]);return l}function Ai(e,t){var r=-1,n=e.length;for(t||(t=oe(n));++r<n;)t[r]=e[r];return t}function Oi(e,t,n,i){var s=!n;n||(n={});for(var o=-1,a=t.length;++o<a;){var c=t[o],d=i?i(n[c],e[c],c,n,e):r;d===r&&(d=e[c]),s?an(n,c,d):rn(n,c,d)}return n}function Mi(e,t){return function(r,n){var i=Yo(r)?Pt:sn,s=t?t():{};return i(r,e,us(n,2),s)}}function Ni(e){return Zn((function(t,n){var i=-1,s=n.length,o=s>1?n[s-1]:r,a=s>2?n[2]:r;for(o=e.length>3&&"function"==typeof o?(s--,o):r,a&&Es(n[0],n[1],a)&&(o=s<3?r:o,s=1),t=Re(t);++i<s;){var c=n[i];c&&e(t,c,i,o)}return t}))}function Li(e,t){return function(r,n){if(null==r)return r;if(!Jo(r))return e(r,n);for(var i=r.length,s=t?i:-1,o=Re(r);(t?s--:++s<i)&&!1!==n(o[s],s,o););return r}}function xi(e){return function(t,r,n){for(var i=-1,s=Re(t),o=n(t),a=o.length;a--;){var c=o[e?a:++i];if(!1===r(s[c],c,s))break}return t}}function Fi(e){return function(t){var n=sr(t=Ea(t))?pr(t):r,i=n?n[0]:t.charAt(0),s=n?Si(n,1).join(""):t.slice(1);return i[e]()+s}}function ji(e){return function(t){return Nt(ec(Ga(t).replace(Ke,"")),e,"")}}function Ui(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 r=Wr(e.prototype),n=e.apply(r,t);return na(n)?n:r}}function Vi(e){return function(t,n,i){var s=Re(t);if(!Jo(t)){var o=us(n,3);t=Na(t),n=function(e){return o(s[e],e,s)}}var a=e(t,n,i);return a>-1?s[o?t[a]:a]:r}}function Bi(e){return is((function(t){var i=t.length,s=i,o=qr.prototype.thru;for(e&&t.reverse();s--;){var a=t[s];if("function"!=typeof a)throw new Ie(n);if(o&&!c&&"wrapper"==cs(a))var c=new qr([],!0)}for(s=c?s:i;++s<i;){var d=cs(a=t[s]),u="wrapper"==d?as(a):r;c=u&&Ss(u[0])&&424==u[1]&&!u[4].length&&1==u[9]?c[cs(u[0])].apply(c,u[3]):1==a.length&&Ss(a)?c[d]():c.thru(a)}return function(){var e=arguments,r=e[0];if(c&&1==e.length&&Yo(r))return c.plant(r).value();for(var n=0,s=i?t[n].apply(this,e):r;++n<i;)s=t[n].call(this,s);return s}}))}function Wi(e,t,n,i,s,o,a,c,u,l){var p=t&d,h=1&t,f=2&t,m=24&t,g=512&t,v=f?r:Ui(e);return function r(){for(var d=arguments.length,y=oe(d),b=d;b--;)y[b]=arguments[b];if(m)var _=ds(r),E=tr(y,_);if(i&&(y=Di(y,i,s,m)),o&&(y=Ii(y,o,a,m)),d-=E,m&&d<l){var w=cr(y,_);return Ji(e,t,Wi,r.placeholder,n,y,w,c,u,l-d)}var S=h?n:this,C=f?S[e]:e;return d=y.length,c?y=Is(y,c):g&&d>1&&y.reverse(),p&&u<d&&(y.length=u),this&&this!==pt&&this instanceof r&&(C=v||Ui(C)),C.apply(S,y)}}function Hi(e,t){return function(r,n){return function(e,t,r,n){return wn(e,(function(e,i,s){t(n,r(e),i,s)})),n}(r,e,t(n),{})}}function qi(e,t){return function(n,i){var s;if(n===r&&i===r)return t;if(n!==r&&(s=n),i!==r){if(s===r)return i;"string"==typeof n||"string"==typeof i?(n=li(n),i=li(i)):(n=ui(n),i=ui(i)),s=e(n,i)}return s}}function zi(e){return is((function(t){return t=Ot(t,Qt(us())),Zn((function(r){var n=this;return e(t,(function(e){return Ct(e,n,r)}))}))}))}function Gi(e,t){var n=(t=t===r?" ":li(t)).length;if(n<2)return n?Kn(t,e):t;var i=Kn(t,gt(e/lr(t)));return sr(t)?Si(pr(i),0,e).join(""):i.slice(0,e)}function Yi(e){return function(t,n,i){return i&&"number"!=typeof i&&Es(t,n,i)&&(n=i=r),t=ga(t),n===r?(n=t,t=0):n=ga(n),function(e,t,r,n){for(var i=-1,s=br(gt((t-e)/(r||1)),0),o=oe(s);s--;)o[n?s:++i]=e,e+=r;return o}(t,n,i=i===r?t<n?1:-1:ga(i),e)}}function $i(e){return function(t,r){return"string"==typeof t&&"string"==typeof r||(t=ba(t),r=ba(r)),e(t,r)}}function Ji(e,t,n,i,s,o,d,u,l,p){var h=8&t;t|=h?a:c,4&(t&=~(h?c:a))||(t&=-4);var f=[e,t,s,h?o:r,h?d:r,h?r:o,h?r:d,u,l,p],m=n.apply(r,f);return Ss(e)&&Os(m,f),m.placeholder=i,Ls(m,e,t)}function Qi(e){var t=Te[e];return function(e,r){if(e=ba(e),(r=null==r?0:_r(va(r),292))&&gr(e)){var n=(Ea(e)+"e").split("e");return+((n=(Ea(t(n[0]+"e"+(+n[1]+r)))+"e").split("e"))[0]+"e"+(+n[1]-r))}return t(e)}}var Ki=kr&&1/dr(new kr([,-0]))[1]==p?function(e){return new kr(e)}:lc;function Zi(e){return function(t){var r=gs(t);return r==C?or(t):r==D?ur(t):function(e,t){return Ot(t,(function(t){return[t,e[t]]}))}(t,e(t))}}function Xi(e,t,i,u,p,h,f,m){var g=2&t;if(!g&&"function"!=typeof e)throw new Ie(n);var v=u?u.length:0;if(v||(t&=-97,u=p=r),f=f===r?f:br(va(f),0),m=m===r?m:va(m),v-=p?p.length:0,t&c){var y=u,b=p;u=p=r}var _=g?r:as(e),E=[e,t,i,u,p,y,b,h,f,m];if(_&&function(e,t){var r=e[1],n=t[1],i=r|n,o=i<131,a=n==d&&8==r||n==d&&r==l&&e[7].length<=t[8]||384==n&&t[7].length<=t[8]&&8==r;if(!o&&!a)return e;1&n&&(e[2]=t[2],i|=1&r?0:4);var c=t[3];if(c){var u=e[3];e[3]=u?Di(u,c,t[4]):c,e[4]=u?cr(e[3],s):t[4]}(c=t[5])&&(u=e[5],e[5]=u?Ii(u,c,t[6]):c,e[6]=u?cr(e[5],s):t[6]);(c=t[7])&&(e[7]=c);n&d&&(e[8]=null==e[8]?t[8]:_r(e[8],t[8]));null==e[9]&&(e[9]=t[9]);e[0]=t[0],e[1]=i}(E,_),e=E[0],t=E[1],i=E[2],u=E[3],p=E[4],!(m=E[9]=E[9]===r?g?0:e.length:br(E[9]-v,0))&&24&t&&(t&=-25),t&&1!=t)w=8==t||t==o?function(e,t,n){var i=Ui(e);return function s(){for(var o=arguments.length,a=oe(o),c=o,d=ds(s);c--;)a[c]=arguments[c];var u=o<3&&a[0]!==d&&a[o-1]!==d?[]:cr(a,d);return(o-=u.length)<n?Ji(e,t,Wi,s.placeholder,r,a,u,r,r,n-o):Ct(this&&this!==pt&&this instanceof s?i:e,this,a)}}(e,t,m):t!=a&&33!=t||p.length?Wi.apply(r,E):function(e,t,r,n){var i=1&t,s=Ui(e);return function t(){for(var o=-1,a=arguments.length,c=-1,d=n.length,u=oe(d+a),l=this&&this!==pt&&this instanceof t?s:e;++c<d;)u[c]=n[c];for(;a--;)u[c++]=arguments[++o];return Ct(l,i?r:this,u)}}(e,t,i,u);else var w=function(e,t,r){var n=1&t,i=Ui(e);return function t(){return(this&&this!==pt&&this instanceof t?i:e).apply(n?r:this,arguments)}}(e,t,i);return Ls((_?ri:Os)(w,E),e,t)}function es(e,t,n,i){return e===r||Ho(e,Me[n])&&!xe.call(i,n)?t:e}function ts(e,t,n,i,s,o){return na(e)&&na(t)&&(o.set(t,e),qn(e,t,r,ts,o),o.delete(t)),e}function rs(e){return aa(e)?r:e}function ns(e,t,n,i,s,o){var a=1&n,c=e.length,d=t.length;if(c!=d&&!(a&&d>c))return!1;var u=o.get(e),l=o.get(t);if(u&&l)return u==t&&l==e;var p=-1,h=!0,f=2&n?new Jr:r;for(o.set(e,t),o.set(t,e);++p<c;){var m=e[p],g=t[p];if(i)var v=a?i(g,m,p,t,e,o):i(m,g,p,e,t,o);if(v!==r){if(v)continue;h=!1;break}if(f){if(!xt(t,(function(e,t){if(!Zt(f,t)&&(m===e||s(m,e,n,i,o)))return f.push(t)}))){h=!1;break}}else if(m!==g&&!s(m,g,n,i,o)){h=!1;break}}return o.delete(e),o.delete(t),h}function is(e){return Ns(ks(e,r,Ys),e+"")}function ss(e){return Tn(e,Na,fs)}function os(e){return Tn(e,La,ms)}var as=Ar?function(e){return Ar.get(e)}:lc;function cs(e){for(var t=e.name+"",r=Or[t],n=xe.call(Or,t)?r.length:0;n--;){var i=r[n],s=i.func;if(null==s||s==e)return i.name}return t}function ds(e){return(xe.call(Br,"placeholder")?Br:e).placeholder}function us(){var e=Br.iteratee||ac;return e=e===ac?Fn:e,arguments.length?e(arguments[0],arguments[1]):e}function ls(e,t){var r,n,i=e.__data__;return("string"==(n=typeof(r=t))||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==r:null===r)?i["string"==typeof t?"string":"hash"]:i.map}function ps(e){for(var t=Na(e),r=t.length;r--;){var n=t[r],i=e[n];t[r]=[n,i,Ts(i)]}return t}function hs(e,t){var n=function(e,t){return null==e?r:e[t]}(e,t);return xn(n)?n:r}var fs=Ft?function(e){return null==e?[]:(e=Re(e),Dt(Ft(e),(function(t){return Je.call(e,t)})))}:yc,ms=Ft?function(e){for(var t=[];e;)Mt(t,fs(e)),e=Ye(e);return t}:yc,gs=Rn;function vs(e,t,r){for(var n=-1,i=(t=Ei(t,e)).length,s=!1;++n<i;){var o=Us(t[n]);if(!(s=null!=e&&r(e,o)))break;e=e[o]}return s||++n!=i?s:!!(i=null==e?0:e.length)&&ra(i)&&_s(o,i)&&(Yo(e)||Go(e))}function ys(e){return"function"!=typeof e.constructor||Ps(e)?{}:Wr(Ye(e))}function bs(e){return Yo(e)||Go(e)||!!(Xe&&e&&e[Xe])}function _s(e,t){var r=typeof e;return!!(t=null==t?h:t)&&("number"==r||"symbol"!=r&&be.test(e))&&e>-1&&e%1==0&&e<t}function Es(e,t,r){if(!na(r))return!1;var n=typeof t;return!!("number"==n?Jo(r)&&_s(t,r.length):"string"==n&&t in r)&&Ho(r[t],e)}function ws(e,t){if(Yo(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!la(e))||(te.test(e)||!ee.test(e)||null!=t&&e in Re(t))}function Ss(e){var t=cs(e),r=Br[t];if("function"!=typeof r||!(t in zr.prototype))return!1;if(e===r)return!0;var n=as(r);return!!n&&e===n[0]}(Pr&&gs(new Pr(new ArrayBuffer(1)))!=N||Tr&&gs(new Tr)!=C||Rr&&gs(Rr.resolve())!=R||kr&&gs(new kr)!=D||Dr&&gs(new Dr)!=O)&&(gs=function(e){var t=Rn(e),n=t==T?e.constructor:r,i=n?Vs(n):"";if(i)switch(i){case Mr:return N;case Nr:return C;case Lr:return R;case xr:return D;case Fr:return O}return t});var Cs=Ne?ea:bc;function Ps(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Me)}function Ts(e){return e==e&&!na(e)}function Rs(e,t){return function(n){return null!=n&&(n[e]===t&&(t!==r||e in Re(n)))}}function ks(e,t,n){return t=br(t===r?e.length-1:t,0),function(){for(var r=arguments,i=-1,s=br(r.length-t,0),o=oe(s);++i<s;)o[i]=r[t+i];i=-1;for(var a=oe(t+1);++i<t;)a[i]=r[i];return a[t]=n(o),Ct(e,this,a)}}function Ds(e,t){return t.length<2?e:Pn(e,si(t,0,-1))}function Is(e,t){for(var n=e.length,i=_r(t.length,n),s=Ai(e);i--;){var o=t[i];e[i]=_s(o,n)?s[o]:r}return e}function As(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}var Os=xs(ri),Ms=ft||function(e,t){return pt.setTimeout(e,t)},Ns=xs(ni);function Ls(e,t,r){var n=t+"";return Ns(e,function(e,t){var r=t.length;if(!r)return e;var n=r-1;return t[n]=(r>1?"& ":"")+t[n],t=t.join(r>2?", ":" "),e.replace(ae,"{\n/* [wrapped with "+t+"] */\n")}(n,function(e,t){return Tt(g,(function(r){var n="_."+r[0];t&r[1]&&!It(e,n)&&e.push(n)})),e.sort()}(function(e){var t=e.match(ce);return t?t[1].split(de):[]}(n),r)))}function xs(e){var t=0,n=0;return function(){var i=Er(),s=16-(i-n);if(n=i,s>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(r,arguments)}}function Fs(e,t){var n=-1,i=e.length,s=i-1;for(t=t===r?i:t;++n<t;){var o=Qn(n,s),a=e[o];e[o]=e[n],e[n]=a}return e.length=t,e}var js=function(e){var t=Fo(e,(function(e){return 500===r.size&&r.clear(),e})),r=t.cache;return t}((function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(re,(function(e,r,n,i){t.push(n?i.replace(pe,"$1"):r||e)})),t}));function Us(e){if("string"==typeof e||la(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function Vs(e){if(null!=e){try{return Le.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Bs(e){if(e instanceof zr)return e.clone();var t=new qr(e.__wrapped__,e.__chain__);return t.__actions__=Ai(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}var Ws=Zn((function(e,t){return Qo(e)?hn(e,bn(t,1,Qo,!0)):[]})),Hs=Zn((function(e,t){var n=Zs(t);return Qo(n)&&(n=r),Qo(e)?hn(e,bn(t,1,Qo,!0),us(n,2)):[]})),qs=Zn((function(e,t){var n=Zs(t);return Qo(n)&&(n=r),Qo(e)?hn(e,bn(t,1,Qo,!0),r,n):[]}));function zs(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var i=null==r?0:va(r);return i<0&&(i=br(n+i,0)),Ut(e,us(t,3),i)}function Gs(e,t,n){var i=null==e?0:e.length;if(!i)return-1;var s=i-1;return n!==r&&(s=va(n),s=n<0?br(i+s,0):_r(s,i-1)),Ut(e,us(t,3),s,!0)}function Ys(e){return(null==e?0:e.length)?bn(e,1):[]}function $s(e){return e&&e.length?e[0]:r}var Js=Zn((function(e){var t=Ot(e,bi);return t.length&&t[0]===e[0]?An(t):[]})),Qs=Zn((function(e){var t=Zs(e),n=Ot(e,bi);return t===Zs(n)?t=r:n.pop(),n.length&&n[0]===e[0]?An(n,us(t,2)):[]})),Ks=Zn((function(e){var t=Zs(e),n=Ot(e,bi);return(t="function"==typeof t?t:r)&&n.pop(),n.length&&n[0]===e[0]?An(n,r,t):[]}));function Zs(e){var t=null==e?0:e.length;return t?e[t-1]:r}var Xs=Zn(eo);function eo(e,t){return e&&e.length&&t&&t.length?$n(e,t):e}var to=is((function(e,t){var r=null==e?0:e.length,n=cn(e,t);return Jn(e,Ot(t,(function(e){return _s(e,r)?+e:e})).sort(ki)),n}));function ro(e){return null==e?e:Cr.call(e)}var no=Zn((function(e){return pi(bn(e,1,Qo,!0))})),io=Zn((function(e){var t=Zs(e);return Qo(t)&&(t=r),pi(bn(e,1,Qo,!0),us(t,2))})),so=Zn((function(e){var t=Zs(e);return t="function"==typeof t?t:r,pi(bn(e,1,Qo,!0),r,t)}));function oo(e){if(!e||!e.length)return[];var t=0;return e=Dt(e,(function(e){if(Qo(e))return t=br(e.length,t),!0})),$t(t,(function(t){return Ot(e,qt(t))}))}function ao(e,t){if(!e||!e.length)return[];var n=oo(e);return null==t?n:Ot(n,(function(e){return Ct(t,r,e)}))}var co=Zn((function(e,t){return Qo(e)?hn(e,t):[]})),uo=Zn((function(e){return vi(Dt(e,Qo))})),lo=Zn((function(e){var t=Zs(e);return Qo(t)&&(t=r),vi(Dt(e,Qo),us(t,2))})),po=Zn((function(e){var t=Zs(e);return t="function"==typeof t?t:r,vi(Dt(e,Qo),r,t)})),ho=Zn(oo);var fo=Zn((function(e){var t=e.length,n=t>1?e[t-1]:r;return n="function"==typeof n?(e.pop(),n):r,ao(e,n)}));function mo(e){var t=Br(e);return t.__chain__=!0,t}function go(e,t){return t(e)}var vo=is((function(e){var t=e.length,n=t?e[0]:0,i=this.__wrapped__,s=function(t){return cn(t,e)};return!(t>1||this.__actions__.length)&&i instanceof zr&&_s(n)?((i=i.slice(n,+n+(t?1:0))).__actions__.push({func:go,args:[s],thisArg:r}),new qr(i,this.__chain__).thru((function(e){return t&&!e.length&&e.push(r),e}))):this.thru(s)}));var yo=Mi((function(e,t,r){xe.call(e,r)?++e[r]:an(e,r,1)}));var bo=Vi(zs),_o=Vi(Gs);function Eo(e,t){return(Yo(e)?Tt:fn)(e,us(t,3))}function wo(e,t){return(Yo(e)?Rt:mn)(e,us(t,3))}var So=Mi((function(e,t,r){xe.call(e,r)?e[r].push(t):an(e,r,[t])}));var Co=Zn((function(e,t,r){var n=-1,i="function"==typeof t,s=Jo(e)?oe(e.length):[];return fn(e,(function(e){s[++n]=i?Ct(t,e,r):On(e,t,r)})),s})),Po=Mi((function(e,t,r){an(e,r,t)}));function To(e,t){return(Yo(e)?Ot:Bn)(e,us(t,3))}var Ro=Mi((function(e,t,r){e[r?0:1].push(t)}),(function(){return[[],[]]}));var ko=Zn((function(e,t){if(null==e)return[];var r=t.length;return r>1&&Es(e,t[0],t[1])?t=[]:r>2&&Es(t[0],t[1],t[2])&&(t=[t[0]]),Gn(e,bn(t,1),[])})),Do=ht||function(){return pt.Date.now()};function Io(e,t,n){return t=n?r:t,t=e&&null==t?e.length:t,Xi(e,d,r,r,r,r,t)}function Ao(e,t){var i;if("function"!=typeof t)throw new Ie(n);return e=va(e),function(){return--e>0&&(i=t.apply(this,arguments)),e<=1&&(t=r),i}}var Oo=Zn((function(e,t,r){var n=1;if(r.length){var i=cr(r,ds(Oo));n|=a}return Xi(e,n,t,r,i)})),Mo=Zn((function(e,t,r){var n=3;if(r.length){var i=cr(r,ds(Mo));n|=a}return Xi(t,n,e,r,i)}));function No(e,t,i){var s,o,a,c,d,u,l=0,p=!1,h=!1,f=!0;if("function"!=typeof e)throw new Ie(n);function m(t){var n=s,i=o;return s=o=r,l=t,c=e.apply(i,n)}function g(e){return l=e,d=Ms(y,t),p?m(e):c}function v(e){var n=e-u;return u===r||n>=t||n<0||h&&e-l>=a}function y(){var e=Do();if(v(e))return b(e);d=Ms(y,function(e){var r=t-(e-u);return h?_r(r,a-(e-l)):r}(e))}function b(e){return d=r,f&&s?m(e):(s=o=r,c)}function _(){var e=Do(),n=v(e);if(s=arguments,o=this,u=e,n){if(d===r)return g(u);if(h)return Ci(d),d=Ms(y,t),m(u)}return d===r&&(d=Ms(y,t)),c}return t=ba(t)||0,na(i)&&(p=!!i.leading,a=(h="maxWait"in i)?br(ba(i.maxWait)||0,t):a,f="trailing"in i?!!i.trailing:f),_.cancel=function(){d!==r&&Ci(d),l=0,s=u=o=d=r},_.flush=function(){return d===r?c:b(Do())},_}var Lo=Zn((function(e,t){return pn(e,1,t)})),xo=Zn((function(e,t,r){return pn(e,ba(t)||0,r)}));function Fo(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new Ie(n);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],s=r.cache;if(s.has(i))return s.get(i);var o=e.apply(this,n);return r.cache=s.set(i,o)||s,o};return r.cache=new(Fo.Cache||$r),r}function jo(e){if("function"!=typeof e)throw new Ie(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)}}Fo.Cache=$r;var Uo=wi((function(e,t){var r=(t=1==t.length&&Yo(t[0])?Ot(t[0],Qt(us())):Ot(bn(t,1),Qt(us()))).length;return Zn((function(n){for(var i=-1,s=_r(n.length,r);++i<s;)n[i]=t[i].call(this,n[i]);return Ct(e,this,n)}))})),Vo=Zn((function(e,t){var n=cr(t,ds(Vo));return Xi(e,a,r,t,n)})),Bo=Zn((function(e,t){var n=cr(t,ds(Bo));return Xi(e,c,r,t,n)})),Wo=is((function(e,t){return Xi(e,l,r,r,r,t)}));function Ho(e,t){return e===t||e!=e&&t!=t}var qo=$i(kn),zo=$i((function(e,t){return e>=t})),Go=Mn(function(){return arguments}())?Mn:function(e){return ia(e)&&xe.call(e,"callee")&&!Je.call(e,"callee")},Yo=oe.isArray,$o=yt?Qt(yt):function(e){return ia(e)&&Rn(e)==M};function Jo(e){return null!=e&&ra(e.length)&&!ea(e)}function Qo(e){return ia(e)&&Jo(e)}var Ko=zt||bc,Zo=bt?Qt(bt):function(e){return ia(e)&&Rn(e)==_};function Xo(e){if(!ia(e))return!1;var t=Rn(e);return t==E||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!aa(e)}function ea(e){if(!na(e))return!1;var t=Rn(e);return t==w||t==S||"[object AsyncFunction]"==t||"[object Proxy]"==t}function ta(e){return"number"==typeof e&&e==va(e)}function ra(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=h}function na(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function ia(e){return null!=e&&"object"==typeof e}var sa=_t?Qt(_t):function(e){return ia(e)&&gs(e)==C};function oa(e){return"number"==typeof e||ia(e)&&Rn(e)==P}function aa(e){if(!ia(e)||Rn(e)!=T)return!1;var t=Ye(e);if(null===t)return!0;var r=xe.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Le.call(r)==Ve}var ca=Et?Qt(Et):function(e){return ia(e)&&Rn(e)==k};var da=wt?Qt(wt):function(e){return ia(e)&&gs(e)==D};function ua(e){return"string"==typeof e||!Yo(e)&&ia(e)&&Rn(e)==I}function la(e){return"symbol"==typeof e||ia(e)&&Rn(e)==A}var pa=St?Qt(St):function(e){return ia(e)&&ra(e.length)&&!!st[Rn(e)]};var ha=$i(Vn),fa=$i((function(e,t){return e<=t}));function ma(e){if(!e)return[];if(Jo(e))return ua(e)?pr(e):Ai(e);if(tt&&e[tt])return function(e){for(var t,r=[];!(t=e.next()).done;)r.push(t.value);return r}(e[tt]());var t=gs(e);return(t==C?or:t==D?dr:Ha)(e)}function ga(e){return e?(e=ba(e))===p||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}function va(e){var t=ga(e),r=t%1;return t==t?r?t-r:t:0}function ya(e){return e?dn(va(e),0,m):0}function ba(e){if("number"==typeof e)return e;if(la(e))return f;if(na(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=na(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=Jt(e);var r=ge.test(e);return r||ye.test(e)?dt(e.slice(2),r?2:8):me.test(e)?f:+e}function _a(e){return Oi(e,La(e))}function Ea(e){return null==e?"":li(e)}var wa=Ni((function(e,t){if(Ps(t)||Jo(t))Oi(t,Na(t),e);else for(var r in t)xe.call(t,r)&&rn(e,r,t[r])})),Sa=Ni((function(e,t){Oi(t,La(t),e)})),Ca=Ni((function(e,t,r,n){Oi(t,La(t),e,n)})),Pa=Ni((function(e,t,r,n){Oi(t,Na(t),e,n)})),Ta=is(cn);var Ra=Zn((function(e,t){e=Re(e);var n=-1,i=t.length,s=i>2?t[2]:r;for(s&&Es(t[0],t[1],s)&&(i=1);++n<i;)for(var o=t[n],a=La(o),c=-1,d=a.length;++c<d;){var u=a[c],l=e[u];(l===r||Ho(l,Me[u])&&!xe.call(e,u))&&(e[u]=o[u])}return e})),ka=Zn((function(e){return e.push(r,ts),Ct(Fa,r,e)}));function Da(e,t,n){var i=null==e?r:Pn(e,t);return i===r?n:i}function Ia(e,t){return null!=e&&vs(e,t,In)}var Aa=Hi((function(e,t,r){null!=t&&"function"!=typeof t.toString&&(t=Ue.call(t)),e[t]=r}),nc(oc)),Oa=Hi((function(e,t,r){null!=t&&"function"!=typeof t.toString&&(t=Ue.call(t)),xe.call(e,t)?e[t].push(r):e[t]=[r]}),us),Ma=Zn(On);function Na(e){return Jo(e)?Kr(e):jn(e)}function La(e){return Jo(e)?Kr(e,!0):Un(e)}var xa=Ni((function(e,t,r){qn(e,t,r)})),Fa=Ni((function(e,t,r,n){qn(e,t,r,n)})),ja=is((function(e,t){var r={};if(null==e)return r;var n=!1;t=Ot(t,(function(t){return t=Ei(t,e),n||(n=t.length>1),t})),Oi(e,os(e),r),n&&(r=un(r,7,rs));for(var i=t.length;i--;)hi(r,t[i]);return r}));var Ua=is((function(e,t){return null==e?{}:function(e,t){return Yn(e,t,(function(t,r){return Ia(e,r)}))}(e,t)}));function Va(e,t){if(null==e)return{};var r=Ot(os(e),(function(e){return[e]}));return t=us(t),Yn(e,r,(function(e,r){return t(e,r[0])}))}var Ba=Zi(Na),Wa=Zi(La);function Ha(e){return null==e?[]:Kt(e,Na(e))}var qa=ji((function(e,t,r){return t=t.toLowerCase(),e+(r?za(t):t)}));function za(e){return Xa(Ea(e).toLowerCase())}function Ga(e){return(e=Ea(e))&&e.replace(_e,rr).replace(Ze,"")}var Ya=ji((function(e,t,r){return e+(r?"-":"")+t.toLowerCase()})),$a=ji((function(e,t,r){return e+(r?" ":"")+t.toLowerCase()})),Ja=Fi("toLowerCase");var Qa=ji((function(e,t,r){return e+(r?"_":"")+t.toLowerCase()}));var Ka=ji((function(e,t,r){return e+(r?" ":"")+Xa(t)}));var Za=ji((function(e,t,r){return e+(r?" ":"")+t.toUpperCase()})),Xa=Fi("toUpperCase");function ec(e,t,n){return e=Ea(e),(t=n?r:t)===r?function(e){return rt.test(e)}(e)?function(e){return e.match(et)||[]}(e):function(e){return e.match(ue)||[]}(e):e.match(t)||[]}var tc=Zn((function(e,t){try{return Ct(e,r,t)}catch(e){return Xo(e)?e:new Ce(e)}})),rc=is((function(e,t){return Tt(t,(function(t){t=Us(t),an(e,t,Oo(e[t],e))})),e}));function nc(e){return function(){return e}}var ic=Bi(),sc=Bi(!0);function oc(e){return e}function ac(e){return Fn("function"==typeof e?e:un(e,1))}var cc=Zn((function(e,t){return function(r){return On(r,e,t)}})),dc=Zn((function(e,t){return function(r){return On(e,r,t)}}));function uc(e,t,r){var n=Na(t),i=Cn(t,n);null!=r||na(t)&&(i.length||!n.length)||(r=t,t=e,e=this,i=Cn(t,Na(t)));var s=!(na(r)&&"chain"in r&&!r.chain),o=ea(e);return Tt(i,(function(r){var n=t[r];e[r]=n,o&&(e.prototype[r]=function(){var t=this.__chain__;if(s||t){var r=e(this.__wrapped__),i=r.__actions__=Ai(this.__actions__);return i.push({func:n,args:arguments,thisArg:e}),r.__chain__=t,r}return n.apply(e,Mt([this.value()],arguments))})})),e}function lc(){}var pc=zi(Ot),hc=zi(kt),fc=zi(xt);function mc(e){return ws(e)?qt(Us(e)):function(e){return function(t){return Pn(t,e)}}(e)}var gc=Yi(),vc=Yi(!0);function yc(){return[]}function bc(){return!1}var _c=qi((function(e,t){return e+t}),0),Ec=Qi("ceil"),wc=qi((function(e,t){return e/t}),1),Sc=Qi("floor");var Cc,Pc=qi((function(e,t){return e*t}),1),Tc=Qi("round"),Rc=qi((function(e,t){return e-t}),0);return Br.after=function(e,t){if("function"!=typeof t)throw new Ie(n);return e=va(e),function(){if(--e<1)return t.apply(this,arguments)}},Br.ary=Io,Br.assign=wa,Br.assignIn=Sa,Br.assignInWith=Ca,Br.assignWith=Pa,Br.at=Ta,Br.before=Ao,Br.bind=Oo,Br.bindAll=rc,Br.bindKey=Mo,Br.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return Yo(e)?e:[e]},Br.chain=mo,Br.chunk=function(e,t,n){t=(n?Es(e,t,n):t===r)?1:br(va(t),0);var i=null==e?0:e.length;if(!i||t<1)return[];for(var s=0,o=0,a=oe(gt(i/t));s<i;)a[o++]=si(e,s,s+=t);return a},Br.compact=function(e){for(var t=-1,r=null==e?0:e.length,n=0,i=[];++t<r;){var s=e[t];s&&(i[n++]=s)}return i},Br.concat=function(){var e=arguments.length;if(!e)return[];for(var t=oe(e-1),r=arguments[0],n=e;n--;)t[n-1]=arguments[n];return Mt(Yo(r)?Ai(r):[r],bn(t,1))},Br.cond=function(e){var t=null==e?0:e.length,r=us();return e=t?Ot(e,(function(e){if("function"!=typeof e[1])throw new Ie(n);return[r(e[0]),e[1]]})):[],Zn((function(r){for(var n=-1;++n<t;){var i=e[n];if(Ct(i[0],this,r))return Ct(i[1],this,r)}}))},Br.conforms=function(e){return function(e){var t=Na(e);return function(r){return ln(r,e,t)}}(un(e,1))},Br.constant=nc,Br.countBy=yo,Br.create=function(e,t){var r=Wr(e);return null==t?r:on(r,t)},Br.curry=function e(t,n,i){var s=Xi(t,8,r,r,r,r,r,n=i?r:n);return s.placeholder=e.placeholder,s},Br.curryRight=function e(t,n,i){var s=Xi(t,o,r,r,r,r,r,n=i?r:n);return s.placeholder=e.placeholder,s},Br.debounce=No,Br.defaults=Ra,Br.defaultsDeep=ka,Br.defer=Lo,Br.delay=xo,Br.difference=Ws,Br.differenceBy=Hs,Br.differenceWith=qs,Br.drop=function(e,t,n){var i=null==e?0:e.length;return i?si(e,(t=n||t===r?1:va(t))<0?0:t,i):[]},Br.dropRight=function(e,t,n){var i=null==e?0:e.length;return i?si(e,0,(t=i-(t=n||t===r?1:va(t)))<0?0:t):[]},Br.dropRightWhile=function(e,t){return e&&e.length?mi(e,us(t,3),!0,!0):[]},Br.dropWhile=function(e,t){return e&&e.length?mi(e,us(t,3),!0):[]},Br.fill=function(e,t,n,i){var s=null==e?0:e.length;return s?(n&&"number"!=typeof n&&Es(e,t,n)&&(n=0,i=s),function(e,t,n,i){var s=e.length;for((n=va(n))<0&&(n=-n>s?0:s+n),(i=i===r||i>s?s:va(i))<0&&(i+=s),i=n>i?0:ya(i);n<i;)e[n++]=t;return e}(e,t,n,i)):[]},Br.filter=function(e,t){return(Yo(e)?Dt:yn)(e,us(t,3))},Br.flatMap=function(e,t){return bn(To(e,t),1)},Br.flatMapDeep=function(e,t){return bn(To(e,t),p)},Br.flatMapDepth=function(e,t,n){return n=n===r?1:va(n),bn(To(e,t),n)},Br.flatten=Ys,Br.flattenDeep=function(e){return(null==e?0:e.length)?bn(e,p):[]},Br.flattenDepth=function(e,t){return(null==e?0:e.length)?bn(e,t=t===r?1:va(t)):[]},Br.flip=function(e){return Xi(e,512)},Br.flow=ic,Br.flowRight=sc,Br.fromPairs=function(e){for(var t=-1,r=null==e?0:e.length,n={};++t<r;){var i=e[t];n[i[0]]=i[1]}return n},Br.functions=function(e){return null==e?[]:Cn(e,Na(e))},Br.functionsIn=function(e){return null==e?[]:Cn(e,La(e))},Br.groupBy=So,Br.initial=function(e){return(null==e?0:e.length)?si(e,0,-1):[]},Br.intersection=Js,Br.intersectionBy=Qs,Br.intersectionWith=Ks,Br.invert=Aa,Br.invertBy=Oa,Br.invokeMap=Co,Br.iteratee=ac,Br.keyBy=Po,Br.keys=Na,Br.keysIn=La,Br.map=To,Br.mapKeys=function(e,t){var r={};return t=us(t,3),wn(e,(function(e,n,i){an(r,t(e,n,i),e)})),r},Br.mapValues=function(e,t){var r={};return t=us(t,3),wn(e,(function(e,n,i){an(r,n,t(e,n,i))})),r},Br.matches=function(e){return Wn(un(e,1))},Br.matchesProperty=function(e,t){return Hn(e,un(t,1))},Br.memoize=Fo,Br.merge=xa,Br.mergeWith=Fa,Br.method=cc,Br.methodOf=dc,Br.mixin=uc,Br.negate=jo,Br.nthArg=function(e){return e=va(e),Zn((function(t){return zn(t,e)}))},Br.omit=ja,Br.omitBy=function(e,t){return Va(e,jo(us(t)))},Br.once=function(e){return Ao(2,e)},Br.orderBy=function(e,t,n,i){return null==e?[]:(Yo(t)||(t=null==t?[]:[t]),Yo(n=i?r:n)||(n=null==n?[]:[n]),Gn(e,t,n))},Br.over=pc,Br.overArgs=Uo,Br.overEvery=hc,Br.overSome=fc,Br.partial=Vo,Br.partialRight=Bo,Br.partition=Ro,Br.pick=Ua,Br.pickBy=Va,Br.property=mc,Br.propertyOf=function(e){return function(t){return null==e?r:Pn(e,t)}},Br.pull=Xs,Br.pullAll=eo,Br.pullAllBy=function(e,t,r){return e&&e.length&&t&&t.length?$n(e,t,us(r,2)):e},Br.pullAllWith=function(e,t,n){return e&&e.length&&t&&t.length?$n(e,t,r,n):e},Br.pullAt=to,Br.range=gc,Br.rangeRight=vc,Br.rearg=Wo,Br.reject=function(e,t){return(Yo(e)?Dt:yn)(e,jo(us(t,3)))},Br.remove=function(e,t){var r=[];if(!e||!e.length)return r;var n=-1,i=[],s=e.length;for(t=us(t,3);++n<s;){var o=e[n];t(o,n,e)&&(r.push(o),i.push(n))}return Jn(e,i),r},Br.rest=function(e,t){if("function"!=typeof e)throw new Ie(n);return Zn(e,t=t===r?t:va(t))},Br.reverse=ro,Br.sampleSize=function(e,t,n){return t=(n?Es(e,t,n):t===r)?1:va(t),(Yo(e)?Xr:ei)(e,t)},Br.set=function(e,t,r){return null==e?e:ti(e,t,r)},Br.setWith=function(e,t,n,i){return i="function"==typeof i?i:r,null==e?e:ti(e,t,n,i)},Br.shuffle=function(e){return(Yo(e)?en:ii)(e)},Br.slice=function(e,t,n){var i=null==e?0:e.length;return i?(n&&"number"!=typeof n&&Es(e,t,n)?(t=0,n=i):(t=null==t?0:va(t),n=n===r?i:va(n)),si(e,t,n)):[]},Br.sortBy=ko,Br.sortedUniq=function(e){return e&&e.length?di(e):[]},Br.sortedUniqBy=function(e,t){return e&&e.length?di(e,us(t,2)):[]},Br.split=function(e,t,n){return n&&"number"!=typeof n&&Es(e,t,n)&&(t=n=r),(n=n===r?m:n>>>0)?(e=Ea(e))&&("string"==typeof t||null!=t&&!ca(t))&&!(t=li(t))&&sr(e)?Si(pr(e),0,n):e.split(t,n):[]},Br.spread=function(e,t){if("function"!=typeof e)throw new Ie(n);return t=null==t?0:br(va(t),0),Zn((function(r){var n=r[t],i=Si(r,0,t);return n&&Mt(i,n),Ct(e,this,i)}))},Br.tail=function(e){var t=null==e?0:e.length;return t?si(e,1,t):[]},Br.take=function(e,t,n){return e&&e.length?si(e,0,(t=n||t===r?1:va(t))<0?0:t):[]},Br.takeRight=function(e,t,n){var i=null==e?0:e.length;return i?si(e,(t=i-(t=n||t===r?1:va(t)))<0?0:t,i):[]},Br.takeRightWhile=function(e,t){return e&&e.length?mi(e,us(t,3),!1,!0):[]},Br.takeWhile=function(e,t){return e&&e.length?mi(e,us(t,3)):[]},Br.tap=function(e,t){return t(e),e},Br.throttle=function(e,t,r){var i=!0,s=!0;if("function"!=typeof e)throw new Ie(n);return na(r)&&(i="leading"in r?!!r.leading:i,s="trailing"in r?!!r.trailing:s),No(e,t,{leading:i,maxWait:t,trailing:s})},Br.thru=go,Br.toArray=ma,Br.toPairs=Ba,Br.toPairsIn=Wa,Br.toPath=function(e){return Yo(e)?Ot(e,Us):la(e)?[e]:Ai(js(Ea(e)))},Br.toPlainObject=_a,Br.transform=function(e,t,r){var n=Yo(e),i=n||Ko(e)||pa(e);if(t=us(t,4),null==r){var s=e&&e.constructor;r=i?n?new s:[]:na(e)&&ea(s)?Wr(Ye(e)):{}}return(i?Tt:wn)(e,(function(e,n,i){return t(r,e,n,i)})),r},Br.unary=function(e){return Io(e,1)},Br.union=no,Br.unionBy=io,Br.unionWith=so,Br.uniq=function(e){return e&&e.length?pi(e):[]},Br.uniqBy=function(e,t){return e&&e.length?pi(e,us(t,2)):[]},Br.uniqWith=function(e,t){return t="function"==typeof t?t:r,e&&e.length?pi(e,r,t):[]},Br.unset=function(e,t){return null==e||hi(e,t)},Br.unzip=oo,Br.unzipWith=ao,Br.update=function(e,t,r){return null==e?e:fi(e,t,_i(r))},Br.updateWith=function(e,t,n,i){return i="function"==typeof i?i:r,null==e?e:fi(e,t,_i(n),i)},Br.values=Ha,Br.valuesIn=function(e){return null==e?[]:Kt(e,La(e))},Br.without=co,Br.words=ec,Br.wrap=function(e,t){return Vo(_i(t),e)},Br.xor=uo,Br.xorBy=lo,Br.xorWith=po,Br.zip=ho,Br.zipObject=function(e,t){return yi(e||[],t||[],rn)},Br.zipObjectDeep=function(e,t){return yi(e||[],t||[],ti)},Br.zipWith=fo,Br.entries=Ba,Br.entriesIn=Wa,Br.extend=Sa,Br.extendWith=Ca,uc(Br,Br),Br.add=_c,Br.attempt=tc,Br.camelCase=qa,Br.capitalize=za,Br.ceil=Ec,Br.clamp=function(e,t,n){return n===r&&(n=t,t=r),n!==r&&(n=(n=ba(n))==n?n:0),t!==r&&(t=(t=ba(t))==t?t:0),dn(ba(e),t,n)},Br.clone=function(e){return un(e,4)},Br.cloneDeep=function(e){return un(e,5)},Br.cloneDeepWith=function(e,t){return un(e,5,t="function"==typeof t?t:r)},Br.cloneWith=function(e,t){return un(e,4,t="function"==typeof t?t:r)},Br.conformsTo=function(e,t){return null==t||ln(e,t,Na(t))},Br.deburr=Ga,Br.defaultTo=function(e,t){return null==e||e!=e?t:e},Br.divide=wc,Br.endsWith=function(e,t,n){e=Ea(e),t=li(t);var i=e.length,s=n=n===r?i:dn(va(n),0,i);return(n-=t.length)>=0&&e.slice(n,s)==t},Br.eq=Ho,Br.escape=function(e){return(e=Ea(e))&&Q.test(e)?e.replace($,nr):e},Br.escapeRegExp=function(e){return(e=Ea(e))&&ie.test(e)?e.replace(ne,"\\$&"):e},Br.every=function(e,t,n){var i=Yo(e)?kt:gn;return n&&Es(e,t,n)&&(t=r),i(e,us(t,3))},Br.find=bo,Br.findIndex=zs,Br.findKey=function(e,t){return jt(e,us(t,3),wn)},Br.findLast=_o,Br.findLastIndex=Gs,Br.findLastKey=function(e,t){return jt(e,us(t,3),Sn)},Br.floor=Sc,Br.forEach=Eo,Br.forEachRight=wo,Br.forIn=function(e,t){return null==e?e:_n(e,us(t,3),La)},Br.forInRight=function(e,t){return null==e?e:En(e,us(t,3),La)},Br.forOwn=function(e,t){return e&&wn(e,us(t,3))},Br.forOwnRight=function(e,t){return e&&Sn(e,us(t,3))},Br.get=Da,Br.gt=qo,Br.gte=zo,Br.has=function(e,t){return null!=e&&vs(e,t,Dn)},Br.hasIn=Ia,Br.head=$s,Br.identity=oc,Br.includes=function(e,t,r,n){e=Jo(e)?e:Ha(e),r=r&&!n?va(r):0;var i=e.length;return r<0&&(r=br(i+r,0)),ua(e)?r<=i&&e.indexOf(t,r)>-1:!!i&&Vt(e,t,r)>-1},Br.indexOf=function(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var i=null==r?0:va(r);return i<0&&(i=br(n+i,0)),Vt(e,t,i)},Br.inRange=function(e,t,n){return t=ga(t),n===r?(n=t,t=0):n=ga(n),function(e,t,r){return e>=_r(t,r)&&e<br(t,r)}(e=ba(e),t,n)},Br.invoke=Ma,Br.isArguments=Go,Br.isArray=Yo,Br.isArrayBuffer=$o,Br.isArrayLike=Jo,Br.isArrayLikeObject=Qo,Br.isBoolean=function(e){return!0===e||!1===e||ia(e)&&Rn(e)==b},Br.isBuffer=Ko,Br.isDate=Zo,Br.isElement=function(e){return ia(e)&&1===e.nodeType&&!aa(e)},Br.isEmpty=function(e){if(null==e)return!0;if(Jo(e)&&(Yo(e)||"string"==typeof e||"function"==typeof e.splice||Ko(e)||pa(e)||Go(e)))return!e.length;var t=gs(e);if(t==C||t==D)return!e.size;if(Ps(e))return!jn(e).length;for(var r in e)if(xe.call(e,r))return!1;return!0},Br.isEqual=function(e,t){return Nn(e,t)},Br.isEqualWith=function(e,t,n){var i=(n="function"==typeof n?n:r)?n(e,t):r;return i===r?Nn(e,t,r,n):!!i},Br.isError=Xo,Br.isFinite=function(e){return"number"==typeof e&&gr(e)},Br.isFunction=ea,Br.isInteger=ta,Br.isLength=ra,Br.isMap=sa,Br.isMatch=function(e,t){return e===t||Ln(e,t,ps(t))},Br.isMatchWith=function(e,t,n){return n="function"==typeof n?n:r,Ln(e,t,ps(t),n)},Br.isNaN=function(e){return oa(e)&&e!=+e},Br.isNative=function(e){if(Cs(e))throw new Ce("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");return xn(e)},Br.isNil=function(e){return null==e},Br.isNull=function(e){return null===e},Br.isNumber=oa,Br.isObject=na,Br.isObjectLike=ia,Br.isPlainObject=aa,Br.isRegExp=ca,Br.isSafeInteger=function(e){return ta(e)&&e>=-9007199254740991&&e<=h},Br.isSet=da,Br.isString=ua,Br.isSymbol=la,Br.isTypedArray=pa,Br.isUndefined=function(e){return e===r},Br.isWeakMap=function(e){return ia(e)&&gs(e)==O},Br.isWeakSet=function(e){return ia(e)&&"[object WeakSet]"==Rn(e)},Br.join=function(e,t){return null==e?"":vr.call(e,t)},Br.kebabCase=Ya,Br.last=Zs,Br.lastIndexOf=function(e,t,n){var i=null==e?0:e.length;if(!i)return-1;var s=i;return n!==r&&(s=(s=va(n))<0?br(i+s,0):_r(s,i-1)),t==t?function(e,t,r){for(var n=r+1;n--;)if(e[n]===t)return n;return n}(e,t,s):Ut(e,Wt,s,!0)},Br.lowerCase=$a,Br.lowerFirst=Ja,Br.lt=ha,Br.lte=fa,Br.max=function(e){return e&&e.length?vn(e,oc,kn):r},Br.maxBy=function(e,t){return e&&e.length?vn(e,us(t,2),kn):r},Br.mean=function(e){return Ht(e,oc)},Br.meanBy=function(e,t){return Ht(e,us(t,2))},Br.min=function(e){return e&&e.length?vn(e,oc,Vn):r},Br.minBy=function(e,t){return e&&e.length?vn(e,us(t,2),Vn):r},Br.stubArray=yc,Br.stubFalse=bc,Br.stubObject=function(){return{}},Br.stubString=function(){return""},Br.stubTrue=function(){return!0},Br.multiply=Pc,Br.nth=function(e,t){return e&&e.length?zn(e,va(t)):r},Br.noConflict=function(){return pt._===this&&(pt._=Be),this},Br.noop=lc,Br.now=Do,Br.pad=function(e,t,r){e=Ea(e);var n=(t=va(t))?lr(e):0;if(!t||n>=t)return e;var i=(t-n)/2;return Gi(vt(i),r)+e+Gi(gt(i),r)},Br.padEnd=function(e,t,r){e=Ea(e);var n=(t=va(t))?lr(e):0;return t&&n<t?e+Gi(t-n,r):e},Br.padStart=function(e,t,r){e=Ea(e);var n=(t=va(t))?lr(e):0;return t&&n<t?Gi(t-n,r)+e:e},Br.parseInt=function(e,t,r){return r||null==t?t=0:t&&(t=+t),wr(Ea(e).replace(se,""),t||0)},Br.random=function(e,t,n){if(n&&"boolean"!=typeof n&&Es(e,t,n)&&(t=n=r),n===r&&("boolean"==typeof t?(n=t,t=r):"boolean"==typeof e&&(n=e,e=r)),e===r&&t===r?(e=0,t=1):(e=ga(e),t===r?(t=e,e=0):t=ga(t)),e>t){var i=e;e=t,t=i}if(n||e%1||t%1){var s=Sr();return _r(e+s*(t-e+ct("1e-"+((s+"").length-1))),t)}return Qn(e,t)},Br.reduce=function(e,t,r){var n=Yo(e)?Nt:Gt,i=arguments.length<3;return n(e,us(t,4),r,i,fn)},Br.reduceRight=function(e,t,r){var n=Yo(e)?Lt:Gt,i=arguments.length<3;return n(e,us(t,4),r,i,mn)},Br.repeat=function(e,t,n){return t=(n?Es(e,t,n):t===r)?1:va(t),Kn(Ea(e),t)},Br.replace=function(){var e=arguments,t=Ea(e[0]);return e.length<3?t:t.replace(e[1],e[2])},Br.result=function(e,t,n){var i=-1,s=(t=Ei(t,e)).length;for(s||(s=1,e=r);++i<s;){var o=null==e?r:e[Us(t[i])];o===r&&(i=s,o=n),e=ea(o)?o.call(e):o}return e},Br.round=Tc,Br.runInContext=e,Br.sample=function(e){return(Yo(e)?Zr:Xn)(e)},Br.size=function(e){if(null==e)return 0;if(Jo(e))return ua(e)?lr(e):e.length;var t=gs(e);return t==C||t==D?e.size:jn(e).length},Br.snakeCase=Qa,Br.some=function(e,t,n){var i=Yo(e)?xt:oi;return n&&Es(e,t,n)&&(t=r),i(e,us(t,3))},Br.sortedIndex=function(e,t){return ai(e,t)},Br.sortedIndexBy=function(e,t,r){return ci(e,t,us(r,2))},Br.sortedIndexOf=function(e,t){var r=null==e?0:e.length;if(r){var n=ai(e,t);if(n<r&&Ho(e[n],t))return n}return-1},Br.sortedLastIndex=function(e,t){return ai(e,t,!0)},Br.sortedLastIndexBy=function(e,t,r){return ci(e,t,us(r,2),!0)},Br.sortedLastIndexOf=function(e,t){if(null==e?0:e.length){var r=ai(e,t,!0)-1;if(Ho(e[r],t))return r}return-1},Br.startCase=Ka,Br.startsWith=function(e,t,r){return e=Ea(e),r=null==r?0:dn(va(r),0,e.length),t=li(t),e.slice(r,r+t.length)==t},Br.subtract=Rc,Br.sum=function(e){return e&&e.length?Yt(e,oc):0},Br.sumBy=function(e,t){return e&&e.length?Yt(e,us(t,2)):0},Br.template=function(e,t,n){var i=Br.templateSettings;n&&Es(e,t,n)&&(t=r),e=Ea(e),t=Ca({},t,i,es);var s,o,a=Ca({},t.imports,i.imports,es),c=Na(a),d=Kt(a,c),u=0,l=t.interpolate||Ee,p="__p += '",h=ke((t.escape||Ee).source+"|"+l.source+"|"+(l===X?he:Ee).source+"|"+(t.evaluate||Ee).source+"|$","g"),f="//# sourceURL="+(xe.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++it+"]")+"\n";e.replace(h,(function(t,r,n,i,a,c){return n||(n=i),p+=e.slice(u,c).replace(we,ir),r&&(s=!0,p+="' +\n__e("+r+") +\n'"),a&&(o=!0,p+="';\n"+a+";\n__p += '"),n&&(p+="' +\n((__t = ("+n+")) == null ? '' : __t) +\n'"),u=c+t.length,t})),p+="';\n";var m=xe.call(t,"variable")&&t.variable;if(m){if(le.test(m))throw new Ce("Invalid `variable` option passed into `_.template`")}else p="with (obj) {\n"+p+"\n}\n";p=(o?p.replace(q,""):p).replace(z,"$1").replace(G,"$1;"),p="function("+(m||"obj")+") {\n"+(m?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(s?", __e = _.escape":"")+(o?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+p+"return __p\n}";var g=tc((function(){return Pe(c,f+"return "+p).apply(r,d)}));if(g.source=p,Xo(g))throw g;return g},Br.times=function(e,t){if((e=va(e))<1||e>h)return[];var r=m,n=_r(e,m);t=us(t),e-=m;for(var i=$t(n,t);++r<e;)t(r);return i},Br.toFinite=ga,Br.toInteger=va,Br.toLength=ya,Br.toLower=function(e){return Ea(e).toLowerCase()},Br.toNumber=ba,Br.toSafeInteger=function(e){return e?dn(va(e),-9007199254740991,h):0===e?e:0},Br.toString=Ea,Br.toUpper=function(e){return Ea(e).toUpperCase()},Br.trim=function(e,t,n){if((e=Ea(e))&&(n||t===r))return Jt(e);if(!e||!(t=li(t)))return e;var i=pr(e),s=pr(t);return Si(i,Xt(i,s),er(i,s)+1).join("")},Br.trimEnd=function(e,t,n){if((e=Ea(e))&&(n||t===r))return e.slice(0,hr(e)+1);if(!e||!(t=li(t)))return e;var i=pr(e);return Si(i,0,er(i,pr(t))+1).join("")},Br.trimStart=function(e,t,n){if((e=Ea(e))&&(n||t===r))return e.replace(se,"");if(!e||!(t=li(t)))return e;var i=pr(e);return Si(i,Xt(i,pr(t))).join("")},Br.truncate=function(e,t){var n=30,i="...";if(na(t)){var s="separator"in t?t.separator:s;n="length"in t?va(t.length):n,i="omission"in t?li(t.omission):i}var o=(e=Ea(e)).length;if(sr(e)){var a=pr(e);o=a.length}if(n>=o)return e;var c=n-lr(i);if(c<1)return i;var d=a?Si(a,0,c).join(""):e.slice(0,c);if(s===r)return d+i;if(a&&(c+=d.length-c),ca(s)){if(e.slice(c).search(s)){var u,l=d;for(s.global||(s=ke(s.source,Ea(fe.exec(s))+"g")),s.lastIndex=0;u=s.exec(l);)var p=u.index;d=d.slice(0,p===r?c:p)}}else if(e.indexOf(li(s),c)!=c){var h=d.lastIndexOf(s);h>-1&&(d=d.slice(0,h))}return d+i},Br.unescape=function(e){return(e=Ea(e))&&J.test(e)?e.replace(Y,fr):e},Br.uniqueId=function(e){var t=++Fe;return Ea(e)+t},Br.upperCase=Za,Br.upperFirst=Xa,Br.each=Eo,Br.eachRight=wo,Br.first=$s,uc(Br,(Cc={},wn(Br,(function(e,t){xe.call(Br.prototype,t)||(Cc[t]=e)})),Cc),{chain:!1}),Br.VERSION="4.17.21",Tt(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(e){Br[e].placeholder=Br})),Tt(["drop","take"],(function(e,t){zr.prototype[e]=function(n){n=n===r?1:br(va(n),0);var i=this.__filtered__&&!t?new zr(this):this.clone();return i.__filtered__?i.__takeCount__=_r(n,i.__takeCount__):i.__views__.push({size:_r(n,m),type:e+(i.__dir__<0?"Right":"")}),i},zr.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),Tt(["filter","map","takeWhile"],(function(e,t){var r=t+1,n=1==r||3==r;zr.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:us(e,3),type:r}),t.__filtered__=t.__filtered__||n,t}})),Tt(["head","last"],(function(e,t){var r="take"+(t?"Right":"");zr.prototype[e]=function(){return this[r](1).value()[0]}})),Tt(["initial","tail"],(function(e,t){var r="drop"+(t?"":"Right");zr.prototype[e]=function(){return this.__filtered__?new zr(this):this[r](1)}})),zr.prototype.compact=function(){return this.filter(oc)},zr.prototype.find=function(e){return this.filter(e).head()},zr.prototype.findLast=function(e){return this.reverse().find(e)},zr.prototype.invokeMap=Zn((function(e,t){return"function"==typeof e?new zr(this):this.map((function(r){return On(r,e,t)}))})),zr.prototype.reject=function(e){return this.filter(jo(us(e)))},zr.prototype.slice=function(e,t){e=va(e);var n=this;return n.__filtered__&&(e>0||t<0)?new zr(n):(e<0?n=n.takeRight(-e):e&&(n=n.drop(e)),t!==r&&(n=(t=va(t))<0?n.dropRight(-t):n.take(t-e)),n)},zr.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},zr.prototype.toArray=function(){return this.take(m)},wn(zr.prototype,(function(e,t){var n=/^(?:filter|find|map|reject)|While$/.test(t),i=/^(?:head|last)$/.test(t),s=Br[i?"take"+("last"==t?"Right":""):t],o=i||/^find/.test(t);s&&(Br.prototype[t]=function(){var t=this.__wrapped__,a=i?[1]:arguments,c=t instanceof zr,d=a[0],u=c||Yo(t),l=function(e){var t=s.apply(Br,Mt([e],a));return i&&p?t[0]:t};u&&n&&"function"==typeof d&&1!=d.length&&(c=u=!1);var p=this.__chain__,h=!!this.__actions__.length,f=o&&!p,m=c&&!h;if(!o&&u){t=m?t:new zr(this);var g=e.apply(t,a);return g.__actions__.push({func:go,args:[l],thisArg:r}),new qr(g,p)}return f&&m?e.apply(this,a):(g=this.thru(l),f?i?g.value()[0]:g.value():g)})})),Tt(["pop","push","shift","sort","splice","unshift"],(function(e){var t=Ae[e],r=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",n=/^(?:pop|shift)$/.test(e);Br.prototype[e]=function(){var e=arguments;if(n&&!this.__chain__){var i=this.value();return t.apply(Yo(i)?i:[],e)}return this[r]((function(r){return t.apply(Yo(r)?r:[],e)}))}})),wn(zr.prototype,(function(e,t){var r=Br[t];if(r){var n=r.name+"";xe.call(Or,n)||(Or[n]=[]),Or[n].push({name:t,func:r})}})),Or[Wi(r,2).name]=[{name:"wrapper",func:r}],zr.prototype.clone=function(){var e=new zr(this.__wrapped__);return e.__actions__=Ai(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=Ai(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=Ai(this.__views__),e},zr.prototype.reverse=function(){if(this.__filtered__){var e=new zr(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},zr.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,r=Yo(e),n=t<0,i=r?e.length:0,s=function(e,t,r){var n=-1,i=r.length;for(;++n<i;){var s=r[n],o=s.size;switch(s.type){case"drop":e+=o;break;case"dropRight":t-=o;break;case"take":t=_r(t,e+o);break;case"takeRight":e=br(e,t-o)}}return{start:e,end:t}}(0,i,this.__views__),o=s.start,a=s.end,c=a-o,d=n?a:o-1,u=this.__iteratees__,l=u.length,p=0,h=_r(c,this.__takeCount__);if(!r||!n&&i==c&&h==c)return gi(e,this.__actions__);var f=[];e:for(;c--&&p<h;){for(var m=-1,g=e[d+=t];++m<l;){var v=u[m],y=v.iteratee,b=v.type,_=y(g);if(2==b)g=_;else if(!_){if(1==b)continue e;break e}}f[p++]=g}return f},Br.prototype.at=vo,Br.prototype.chain=function(){return mo(this)},Br.prototype.commit=function(){return new qr(this.value(),this.__chain__)},Br.prototype.next=function(){this.__values__===r&&(this.__values__=ma(this.value()));var e=this.__index__>=this.__values__.length;return{done:e,value:e?r:this.__values__[this.__index__++]}},Br.prototype.plant=function(e){for(var t,n=this;n instanceof Hr;){var i=Bs(n);i.__index__=0,i.__values__=r,t?s.__wrapped__=i:t=i;var s=i;n=n.__wrapped__}return s.__wrapped__=e,t},Br.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof zr){var t=e;return this.__actions__.length&&(t=new zr(this)),(t=t.reverse()).__actions__.push({func:go,args:[ro],thisArg:r}),new qr(t,this.__chain__)}return this.thru(ro)},Br.prototype.toJSON=Br.prototype.valueOf=Br.prototype.value=function(){return gi(this.__wrapped__,this.__actions__)},Br.prototype.first=Br.prototype.head,tt&&(Br.prototype[tt]=function(){return this}),Br}();ft?((ft.exports=mr)._=mr,ht._=mr):pt._=mr}).call(u)}(Nb,Nb.exports);var Lb,xb=u&&u.__extends||(Lb=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},function(e,t){function r(){this.constructor=e}Lb(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(Mb,"__esModule",{value:!0});var Fb=t.default,jb=Nb.exports,Ub=["MaxBatchSize","MaxDelay","MinDelay"],Vb=function(e){function t(t){var r=e.call(this)||this;return r.fifo=[],r.firstBatch=!0,function(e){if(Ub.forEach((function(t){if(!e.hasOwnProperty(t))throw new Error("Missing required MessageBatcher option: "+t)})),isNaN(e.MaxBatchSize))throw new Error("MessageBatcher MaxBatchSize option must be a number");if(!isFinite(e.MaxBatchSize))throw new Error("MessageBatcher MaxBatchSize option must be a finite number");if(e.MaxBatchSize<1)throw new Error("MessageBatcher MaxBatchSize option cannot be less than 1");if(isNaN(e.MaxDelay))throw new Error("MessageBatcher MaxDelay option must be a number");if(!isFinite(e.MaxDelay))throw new Error("MessageBatcher MaxDelay option must be a finite number");if(e.MaxDelay<0)throw new Error("MessageBatcher MaxDelay option cannot be less than 0");if(isNaN(e.MinDelay))throw new Error("MessageBatcher MinDelay option must be a number");if(!isFinite(e.MinDelay))throw new Error("MessageBatcher MinDelay option must be a finite number");if(e.MinDelay<0)throw new Error("MessageBatcher MinDelay option cannot be less than 0");if(e.MinDelay>e.MaxDelay)throw new Error("MessageBatcher MinDelay option cannot be greater than MaxDelay")}(t),r.options=t,r.releaseBatchDebouncedMax=jb.debounce(r.releaseBatch.bind(r),r.options.MaxDelay,{maxWait:r.options.MaxDelay}),r.releaseBatchDebouncedMin=jb.debounce(r.releaseBatch.bind(r),r.options.MinDelay,{maxWait:r.options.MinDelay}),r}return xb(t,e),t.prototype.Queue=function(e){var t=this;(e=[].concat(e)).forEach((function(e){t.fifo.push(e),t.debounce(t.fifo,t.options.MaxBatchSize)}),this)},t.prototype.debounce=function(e,t){e.length>0&&(e.length>=t?this.firstBatch?(this.firstBatch=!1,this.releaseBatchDebouncedMax.flush()):(this.releaseBatchDebouncedMax.cancel(),this.releaseBatchDebouncedMin(e,t)):(this.releaseBatchDebouncedMin.cancel(),this.releaseBatchDebouncedMax(e,t)))},t.prototype.releaseBatch=function(e,t){var r=this.drainFIFO(e,t);r&&r.length&&(this.emit("batch",r),this.debounce(e,t))},t.prototype.drainFIFO=function(e,t){return e.length>0?e.splice(0,t):e},t}(Fb.EventEmitter);Mb.MessageBatcher=Vb,function(e){Object.defineProperty(e,"__esModule",{value:!0}),function(t){for(var r in t)e.hasOwnProperty(r)||(e[r]=t[r])}(Mb)}(Ob),function(e){Object.defineProperty(e,"__esModule",{value:!0}),function(t){for(var r in t)e.hasOwnProperty(r)||(e[r]=t[r])}(Ob)}(Ab);var Bb={exports:{}},Wb=1e3,Hb=60*Wb,qb=60*Hb,zb=24*qb,Gb=7*zb,Yb=365.25*zb,$b=function(e,t){t=t||{};var r=typeof e;if("string"===r&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*Yb;case"weeks":case"week":case"w":return r*Gb;case"days":case"day":case"d":return r*zb;case"hours":case"hour":case"hrs":case"hr":case"h":return r*qb;case"minutes":case"minute":case"mins":case"min":case"m":return r*Hb;case"seconds":case"second":case"secs":case"sec":case"s":return r*Wb;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(e);if("number"===r&&isFinite(e))return t.long?function(e){var t=Math.abs(e);if(t>=zb)return Jb(e,t,zb,"day");if(t>=qb)return Jb(e,t,qb,"hour");if(t>=Hb)return Jb(e,t,Hb,"minute");if(t>=Wb)return Jb(e,t,Wb,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=zb)return Math.round(e/zb)+"d";if(t>=qb)return Math.round(e/qb)+"h";if(t>=Hb)return Math.round(e/Hb)+"m";if(t>=Wb)return Math.round(e/Wb)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function Jb(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}var Qb=function(e){function t(e){let n,i,s,o=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,i)=>{if("%%"===n)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];n=s.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r<i;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=$b,t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=Qb(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Bb,Bb.exports);var Kb,Zb,Xb,e_,t_,r_,n_,i_,s_=Bb.exports;class o_{constructor(e){Kb.add(this),Zb.set(this,void 0),Xb.set(this,void 0),e_.set(this,void 0),t_.set(this,void 0);const{logLevel:t,namespace:r,onLogMessage:n}=e;c(this,Zb,r,"f"),c(this,Xb,t,"f"),this.onLogMessage=n,c(this,e_,e.logToRemoteBatcher,"f"),c(this,t_,e.sendAnalytics,"f"),this._debug=s_("LiveDigital").extend("debug").extend(a(this,Zb,"f")),this._info=s_("LiveDigital").extend("info").extend(a(this,Zb,"f")),this._warn=s_("LiveDigital").extend("warn").extend(a(this,Zb,"f")),this._error=s_("LiveDigital").extend("error").extend(a(this,Zb,"f")),this._debug.log=console.info.bind(console),this._info.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}debug(e,t){this._debug(e,t),a(this,Xb,"f")<pt||(a(this,t_,"f")&&a(this,e_,"f").Queue(a(this,Kb,"m",n_).call(this,{level:"debug",message:e,meta:a(this,Kb,"m",i_).call(this,t)})),a(this,Kb,"m",r_).call(this,"debug",e,t))}info(e,t){this._info(e,t),a(this,Xb,"f")<lt||(a(this,t_,"f")&&a(this,e_,"f").Queue(a(this,Kb,"m",n_).call(this,{level:"info",message:e,meta:a(this,Kb,"m",i_).call(this,t)})),a(this,Kb,"m",r_).call(this,"info",e,t))}warn(e,t){this._warn(e,t),a(this,Xb,"f")<ut||(a(this,t_,"f")&&a(this,e_,"f").Queue(a(this,Kb,"m",n_).call(this,{level:"warn",message:e,meta:a(this,Kb,"m",i_).call(this,t)})),a(this,Kb,"m",r_).call(this,"warn",e,t))}error(e,t){this._error(e,t),a(this,Xb,"f")<dt||(a(this,t_,"f")&&a(this,e_,"f").Queue(a(this,Kb,"m",n_).call(this,{level:"error",message:e,meta:a(this,Kb,"m",i_).call(this,t)})),a(this,Kb,"m",r_).call(this,"error",e,t))}}var a_,c_,d_;Zb=new WeakMap,Xb=new WeakMap,e_=new WeakMap,t_=new WeakMap,Kb=new WeakSet,r_=function(e,t,...r){"function"==typeof this.onLogMessage&&this.onLogMessage(t,...a(this,Kb,"m",n_).call(this,r),e)},n_=function(e){const t=new WeakMap;return function e(r,n=[]){if(!ri(r))return r;const i=t.get(r);if(i)return`[Circular *${i.join(".")}]`;t.set(r,n);const s=Array.isArray(r)?[]:{};return Object.entries(r).forEach((([t,r])=>{s[t]=e(r,[...n,t])})),t.delete(r),s}(e)},i_=function(e){const t=null!=e?e:{},{error:r}=t;return Object.assign(Object.assign(Object.assign(Object.assign({},t),{clientTimestamp:(new Date).toISOString(),from_sdk:!0,sdkVersion:ft}),r&&"object"==typeof r?{error:Vt(r)}:{}),{namespace:a(this,Zb,"f")})};let u_=class{constructor(e,t,r,n,i){this.state=e,this.myPeer=r,this.signalingApiClient=n,this.channelAudioObserverEventHandler=i,a_.set(this,void 0),c_.set(this,void 0),d_.set(this,void 0),c(this,a_,t("DataChannels"),"f")}get channelMessagesDataConsumer(){return a(this,d_,"f")}createAudioObserver(e){return o(this,void 0,void 0,(function*(){var t;const r={channelId:this.state.channelId,appId:this.state.appId,peerId:null===(t=this.myPeer)||void 0===t?void 0:t.id};try{const{producerId:t}=yield this.getAudioObserverProducer();c(this,c_,yield this.createDataConsumer({producerId:t,appId:this.state.appId,channelId:this.state.channelId,transport:e}),"f")}catch(e){if(e instanceof Bt)throw e;return void a(this,a_,"f").error("Failed to create audio observer",Object.assign(Object.assign({},r),{error:Vt(e)}))}const n=this.channelAudioObserverEventHandler.handle.bind(this.channelAudioObserverEventHandler),i=()=>{var e,t;null===(e=a(this,c_,"f"))||void 0===e||e.removeListener("message",n),null===(t=a(this,c_,"f"))||void 0===t||t.removeListener("close",i)};a(this,c_,"f").on("close",i),a(this,c_,"f").on("message",n),a(this,a_,"f").debug("Successfully create audio observer",r)}))}createChannelMessagesDataConsumer(e){return o(this,void 0,void 0,(function*(){var t;const r={channelId:this.state.channelId,appId:this.state.appId,peerId:null===(t=this.myPeer)||void 0===t?void 0:t.id};try{const{id:t}=yield this.createDataProducer(e.id,"channel-messages-data-producer");c(this,d_,yield this.createDataConsumer({producerId:t,appId:this.state.appId,channelId:this.state.channelId,ordered:!0,transport:e}),"f"),a(this,a_,"f").debug("Successfully created channel messages data consumer",Object.assign(Object.assign({},r),{producerId:t}))}catch(e){throw a(this,a_,"f").error("Failed to create channel messages data consumer",Object.assign(Object.assign({},r),{error:e})),e}}))}closeAudioObserver(){var e;null===(e=a(this,c_,"f"))||void 0===e||e.close()}closeChannelMessagesDataConsumer(){var e;null===(e=a(this,d_,"f"))||void 0===e||e.close()}createDataProducer(e,t){return o(this,void 0,void 0,(function*(){const{data:r}=yield this.signalingApiClient.transport.produceDataToTransport(e,{label:t});return r}))}createDataConsumer(e){return o(this,arguments,void 0,(function*({producerId:e,appId:t,channelId:r,ordered:n,transport:i}){if(!i)throw a(this,a_,"f").error("createDataConsumer()",{reason:"missing receive transport"}),new Bt("create_data_consumer_failed",new Error("Missing receive transport"));a(this,a_,"f").debug("createDataConsumer()",{producerId:e});const s=(yield this.signalingApiClient.dataConsumer.createDataConsumer({ordered:n,dataProducerId:e,transportId:i.id,appData:{peerId:this.myPeer.id,producerId:e,appId:t,channelId:r}})).data;try{const e=yield i.consumeData(s);return a(this,a_,"f").debug("Data consumer created",{consumerId:e.id}),e}catch(e){throw new Bt("transport_consume_data_failed",e)}}))}getAudioObserverProducer(){return o(this,void 0,void 0,(function*(){const{data:e}=yield this.signalingApiClient.producer.getAudioObserverProducer();return e}))}};a_=new WeakMap,c_=new WeakMap,d_=new WeakMap,u_=n([ot(),i(0,ct(fi.CallState)),i(1,ct(fi.LoggerFactory)),i(2,ct(fi.MyPeer)),i(3,ct(fi.SignalingApiClient)),i(4,ct(fi.ChannelAudioObserverEventHandler)),s("design:paramtypes",[mi,Function,ro,ed,Ib])],u_);var l_,p_,h_,f_,m_,g_,v_=u_;let y_=class{constructor(e){l_.set(this,void 0),p_.set(this,void 0),h_.set(this,void 0),f_.set(this,[]),m_.set(this,void 0),g_.set(this,new Uint8Array(0)),c(this,m_,e("DatachannelHeartbeater"),"f")}init(e,t){c(this,h_,e,"f"),c(this,p_,t,"f"),this.subscribeToDataProducerEvents(t),this.startHeartbeatInterval()}dispose(){this.stopHeartbeatInterval(),this.cleanupDataProducerEvents(),c(this,p_,void 0,"f"),c(this,h_,void 0,"f")}startHeartbeatInterval(){a(this,l_,"f")||(c(this,l_,setInterval((()=>{this.sendHeartbeat()}),5e3),"f"),a(this,m_,"f").debug("Datachannel heartbeat interval started"))}stopHeartbeatInterval(){a(this,l_,"f")&&(clearInterval(a(this,l_,"f")),c(this,l_,void 0,"f"),a(this,m_,"f").debug("Datachannel heartbeat interval stopped"))}canSendHeartbeat(){return!(!a(this,p_,"f")||!a(this,h_,"f"))&&(!a(this,p_,"f").closed&&"connected"===a(this,h_,"f").connectionState&&"open"===a(this,p_,"f").readyState)}subscribeToDataProducerEvents(e){this.cleanupDataProducerEvents();const t=t=>{a(this,m_,"f").debug(`Heartbeat data producer ${t}`,{readyState:e.readyState,closed:e.closed})},r=()=>t("open"),n=()=>t("close"),i=()=>t("transport closed");e.on("open",r),e.on("close",n),e.on("transportclose",i),c(this,f_,[()=>e.off("open",r),()=>e.off("close",n),()=>e.off("transportclose",i)],"f")}cleanupDataProducerEvents(){a(this,f_,"f").forEach((e=>e())),c(this,f_,[],"f")}sendHeartbeat(){if(a(this,p_,"f")&&this.canSendHeartbeat())try{a(this,p_,"f").send(a(this,g_,"f"))}catch(e){a(this,m_,"f").debug("Failed to send datachannel heartbeat",{error:Vt(e)})}}};l_=new WeakMap,p_=new WeakMap,h_=new WeakMap,f_=new WeakMap,m_=new WeakMap,g_=new WeakMap,y_=n([ot(),i(0,ct(fi.LoggerFactory)),s("design:paramtypes",[Function])],y_);var b_,__,E_=y_;let w_=class{constructor(e,t){this.signalingApiClient=t,b_.set(this,void 0),__.set(this,void 0),c(this,__,e("SignalingHeartbeater"),"f")}start(){a(this,b_,"f")||(c(this,b_,setInterval((()=>o(this,void 0,void 0,(function*(){yield this.sendHeartbeat()}))),15e3),"f"),a(this,__,"f").debug("Signaling heartbeat interval started"))}dispose(){a(this,b_,"f")&&(clearInterval(a(this,b_,"f")),c(this,b_,void 0,"f"),a(this,__,"f").debug("Signaling heartbeat interval stopped"))}sendHeartbeat(){return o(this,void 0,void 0,(function*(){try{yield this.signalingApiClient.ping.pingPeer()}catch(e){a(this,__,"f").debug("Failed to send signaling heartbeat",{error:Vt(e)})}}))}};b_=new WeakMap,__=new WeakMap,w_=n([ot(),i(0,ct(fi.LoggerFactory)),i(1,ct(fi.SignalingApiClient)),s("design:paramtypes",[Function,ed])],w_);var S_=w_;let C_=class{constructor(e){this.peerTrackFactory=e,this.tracksByConsumerId=new Map}register(e,t){this.tracksByConsumerId.set(e,t)}get(e){return this.tracksByConsumerId.get(e)}delete(e){return this.tracksByConsumerId.delete(e)}reset(){this.tracksByConsumerId.clear()}create(e){const{consumer:t,label:r,muted:n=!1,mediaStreamTrack:i,paused:s,peerEventEmitter:o}=e,a=this.peerTrackFactory({consumer:t,label:r,mediaStreamTrack:i,paused:s,peerEventEmitter:o,muted:n,onClose:()=>{void 0!==a.consumerId&&this.delete(a.consumerId)}});return void 0!==a.consumerId&&this.register(a.consumerId,a),a}};var P_,T_,R_;C_=n([ot(),i(0,ct(fi.PeerTrackFactory)),s("design:paramtypes",[Function])],C_);const k_=["frozen-video-track","network-media-sync-failure","encoder-cpu-throttling","decoder-cpu-throttling","missing-video-stream-data","missing-audio-stream-data"];let D_=class{constructor(e,t,r,n,i,s){this.analyticsApiClient=e,this.peers=t,this.myPeer=r,this.transportsStatsProvider=i,this.clientMetaProvider=s,P_.set(this,void 0),T_.set(this,void 0),R_.set(this,void 0),c(this,R_,n("IntegrationsService"),"f"),c(this,T_,new Ab.MessageBatcher({MaxBatchSize:50,MaxDelay:6e4,MinDelay:3e4}),"f"),a(this,T_,"f").on("batch",(e=>{this.analyticsApiClient.metrics.sendWIDMetrics({reasons:e,clientMeta:this.getClientMeta()}).catch((e=>{a(this,R_,"f").debug("Failed to sendWIDMetrics",{error:Vt(e)})}))})),c(this,P_,new Ab.MessageBatcher({MaxBatchSize:20,MaxDelay:6e4,MinDelay:2e4}),"f"),a(this,P_,"f").on("batch",(e=>{this.analyticsApiClient.metrics.sendNetworkMetrics({metrics:this.getWorstPerDirectionMetric(e),clientMeta:this.getClientMeta()}).catch((e=>{a(this,R_,"f").debug("Failed to sendNetworkMetrics",{error:Vt(e)})}))}))}handleIssues(e){e.forEach((e=>a(this,R_,"f").info("WebRTCIssue",e)));const t=e.filter((e=>k_.includes(e.reason)));0!==t.length&&t.forEach((e=>a(this,T_,"f").Queue(e.reason)))}handleNetworkScores(e){var t,r,n,i,s,o,c,d,u,l,p,h;const{inbound:f,outbound:m,statsSamples:{inboundStatsSample:g,outboundStatsSample:v}}=e,y=this.getNodeActiveStreamsStat(),b=this.transportsStatsProvider.getStats();if(void 0!==f&&g){const e={jitter:Math.round(g.avgJitter),packetLoss:g.packetsLoss,rtt:g.rtt,mos:Math.round(10*f)/10,streams:y.inboundActiveStreams,direction:"inbound",node:null!==(t=this.clientMetaProvider.meta.datacenterName)&&void 0!==t?t:"unknown node",bitrate:null!==(n=null===(r=null==b?void 0:b.inbound)||void 0===r?void 0:r.bitrate)&&void 0!==n?n:0,timestamp:(new Date).toISOString(),Qa:null===(i=null==b?void 0:b.inbound)||void 0===i?void 0:i.Qa,Qv:null===(s=null==b?void 0:b.inbound)||void 0===s?void 0:s.Qv,Qav:null===(o=null==b?void 0:b.inbound)||void 0===o?void 0:o.Qav};a(this,R_,"f").debug("Queueing inbound network score metric",e),a(this,P_,"f").Queue(e)}if(void 0!==m&&v){const e={jitter:Math.round(v.avgJitter),packetLoss:v.packetsLoss,rtt:v.rtt,mos:Math.round(10*m)/10,streams:y.outboundActiveStreams,direction:"outbound",node:null!==(c=this.clientMetaProvider.meta.datacenterName)&&void 0!==c?c:"unknown node",bitrate:null!==(u=null===(d=null==b?void 0:b.outbound)||void 0===d?void 0:d.bitrate)&&void 0!==u?u:0,timestamp:(new Date).toISOString(),Qa:null===(l=null==b?void 0:b.outbound)||void 0===l?void 0:l.Qa,Qv:null===(p=null==b?void 0:b.outbound)||void 0===p?void 0:p.Qv,Qav:null===(h=null==b?void 0:b.outbound)||void 0===h?void 0:h.Qav};a(this,R_,"f").debug("Queueing outbound network score metric",e),a(this,P_,"f").Queue(e)}}getNodeActiveStreamsStat(){var e;const t=this.peers.hosts().filter((e=>{var t;return e.id!==(null===(t=this.myPeer)||void 0===t?void 0:t.id)})).reduce(((e,t)=>e+t.getActiveTracksCount()),0),r=this.myPeer.get();return{inboundActiveStreams:t,outboundActiveStreams:null!==(e=null==r?void 0:r.getActivePublishersCount())&&void 0!==e?e:0}}getClientMeta(){return Object.assign(Object.assign({},this.clientMetaProvider.meta),{clientUniqueId:this.clientMetaProvider.meta.clUId})}getWorstPerDirectionMetric(e){return["inbound","outbound"].map((t=>this.pickWorstMetric(e.filter((e=>e.direction===t))))).filter((e=>void 0!==e))}pickWorstMetric(e){if(!e.length)return;const t=e.filter((e=>"number"==typeof e.Qav));return t.length?t.reduce(((e,t)=>t.Qav<e.Qav?t:e)):e.reduce(((e,t)=>t.jitter>e.jitter?t:e))}};P_=new WeakMap,T_=new WeakMap,R_=new WeakMap,D_=n([ot(),i(0,ct(fi.AnalyticsApiClient)),i(1,ct(fi.Peers)),i(2,ct(fi.MyPeer)),i(3,ct(fi.LoggerFactory)),i(4,ct(fi.TransportsStatsProvider)),i(5,ct(fi.ClientMetaProvider)),s("design:paramtypes",[_b,Object,ro,Function,Vg,Vr])],D_);var I_=D_;let A_=class{constructor(e,t,r){this.widHandler=e,this.clientEventEmitter=t,this.config=r}handle(e){var t;this.widHandler.handleNetworkScores(e),null===(t=this.config.get("onNetworkScoresUpdated"))||void 0===t||t(e),this.clientEventEmitter.safeEmit(fn,e)}};A_=n([ot(),i(0,ct(fi.WIDHandler)),i(1,ct(fi.ClientEventEmitter)),i(2,ct(fi.Config)),s("design:paramtypes",[Function,Function,Function])],A_);var O_=A_;let M_=class{constructor(e){this.handles=new Map,this.logger=e("TransportStateMonitor")}schedule(e){var t;const{transport:r,options:n,restartIce:i}=e;if(this.handles.has(r.id))return void this.logger.debug("restartIce attempt skipped",{transportId:r.id,direction:r.direction});const s=null!==(t=n.intervalMs)&&void 0!==t?t:1500,a=(e=>{const{callback:t,intervalMs:r,immediate:n=!1}=e;let i,s=!0;const a=()=>o(void 0,void 0,void 0,(function*(){if(s){try{yield t()}catch(e){}s&&(i=setTimeout(a,r))}}));return n?a():i=setTimeout(a,r),{stop:()=>{s=!1,void 0!==i&&(clearTimeout(i),i=void 0)}}})({callback:()=>o(this,void 0,void 0,(function*(){try{yield i(r)}catch(e){this.logger.debug("restartIce attempt failed",{intervalMs:s,error:e instanceof Error?e.message:e,transportId:r.id,direction:r.direction})}})),intervalMs:s,immediate:n.immediate});this.handles.set(r.id,a)}cancel(e){const t=this.handles.get(e);t&&(t.stop(),this.handles.delete(e))}cancelAll(){this.handles.forEach((e=>e.stop())),this.handles.clear()}};M_=n([ot(),i(0,ct(fi.LoggerFactory)),s("design:paramtypes",[Function])],M_);var N_=M_;let L_=class{constructor(e,t,r){this.signalingApiClient=e,this.transportStateMonitor=r,this.logger=t("IceRecoveryService")}getIceParameters(e){return o(this,void 0,void 0,(function*(){const{data:{iceParameters:t}}=yield this.signalingApiClient.transport.getTransportIceParameters(e.id);return t}))}restartIce(e){return o(this,void 0,void 0,(function*(){try{const t=yield this.getIceParameters(e);yield e.restartIce({iceParameters:t}),this.logger.info("restartIce completed",{iceParameters:t})}catch(e){if(e instanceof Yn||e instanceof Kn)return void this.logger.debug("Cannot update ice due to connection not found on server",{error:Vt(e)});(Qn(e)?this.logger.debug.bind(this.logger):this.logger.error.bind(this.logger))("restartIce() error",{error:Vt(e)})}}))}handleConnectionStateChange(e,t){["closed","connected"].includes(t)?this.transportStateMonitor.cancel(e.id):["disconnected","failed"].includes(t)&&this.transportStateMonitor.schedule({transport:e,restartIce:this.restartIce.bind(this),options:{immediate:"failed"===t,intervalMs:1500}})}cancelAll(){this.transportStateMonitor.cancelAll()}};L_=n([ot(),i(0,ct(fi.SignalingApiClient)),i(1,ct(fi.LoggerFactory)),i(2,ct(fi.TransportStateMonitor)),s("design:paramtypes",[Function,Function,Function])],L_);var x_,F_,j_,U_,V_,B_,W_,H_,q_,z_=L_;!function(e){e.INFO="info",e.WARNING="warning",e.ERROR="error"}(W_||(W_={})),function(e){e[e.PERFORMANCE_STOP=1001]="PERFORMANCE_STOP",e[e.REDUCE_LATENCY=1002]="REDUCE_LATENCY",e[e.MODEL_LOAD_FAILED=1010]="MODEL_LOAD_FAILED",e[e.PROCESSOR_INIT_ISSUE=1020]="PROCESSOR_INIT_ISSUE",e[e.AUTH_ISSUE=1030]="AUTH_ISSUE",e[e.SUPPORT_ISSUE=1040]="SUPPORT_ISSUE",e[e.PROCESSING_PROGRESS=1060]="PROCESSING_PROGRESS"}(H_||(H_={})),function(e){e.ATSVB="atsvb",e.STREAM_PROCESSOR="stream_processor",e.ML_INFERENCE="ml_inference",e.MODEL="model",e.WORKLET="worklet",e.WORKER="worker",e.MODEL_LOADER="model_loader"}(q_||(q_={}));const G_=()=>{};class Y_{constructor(e){x_.set(this,void 0),F_.set(this,void 0),j_.set(this,null),U_.set(this,new Map),V_.set(this,void 0),this.type="asdk",B_.set(this,void 0);const{loggerFactory:t}=e;c(this,F_,t("ASDKTrackProcessor"),"f"),c(this,B_,"function"==typeof e.onError?e.onError:G_,"f"),c(this,x_,new window.atsvb(e.asdkCustomerId),"f");const r=e.config.get("staticFilesPath"),{localDir:n,version:i,sdk_url:s,api_url:o}=e.config.get("asdk");let d=`https://effectssdk.ai/sdk/audio/dev/${null!=i?i:"2.5.1"}`;if(n){d=new URL(`${n}/${null!=i?i:"2.5.1"}`,r).href}const u={preset:"balanced",sample_rate:48e3,api_url:o,wasmPaths:{"ort-wasm.wasm":`${d}/ort-wasm.wasm`,"ort-wasm-simd.wasm":`${d}/ort-wasm-simd.wasm`}},l=!s&&n,p=l?`${d}/`:s;l&&a(this,F_,"f").warn("Using static ASDK path due to missing config",Object.assign(Object.assign({case:"Denoiser",type:"asdk"},e.config.get("asdk")),{sdkUrl:u.sdk_url})),p&&(u.sdk_url=p),a(this,x_,"f").config(u),a(this,x_,"f").onError(this.onError.bind(this))}setOnError(e){c(this,B_,e,"f")}init(){return o(this,void 0,void 0,(function*(){yield a(this,x_,"f").preload()}))}release(){a(this,x_,"f").stop(),a(this,x_,"f").clear()}get isProcessing(){return!!a(this,V_,"f")}processTrack(e){return o(this,void 0,void 0,(function*(){var t;if(a(this,j_,"f")===e||"ended"===e.readyState)return(null===(t=a(this,x_,"f").getStream())||void 0===t?void 0:t.getAudioTracks()[0])||e;this.stopProcessing();try{const t=new Promise(((t,r)=>{a(this,x_,"f").onReady=()=>{try{const r=a(this,x_,"f").getStream(),n=null==r?void 0:r.getAudioTracks()[0];if(!n)return void t(e);c(this,j_,e,"f"),c(this,V_,n,"f"),t(n),a(this,x_,"f").run()}catch(e){r(e)}finally{a(this,x_,"f").onReady=void 0}}}));a(this,x_,"f").useStream(new MediaStream([e]));const r=yield t;return a(this,F_,"f").info("processTrack()",{case:"Denoiser",type:this.type,track:e.id}),r}catch(t){throw a(this,F_,"f").error("processTrack()",{error:Vt(t),type:this.type,case:"Denoiser",track:e}),a(this,B_,"f").call(this,"ASDK processTrack() error",t),c(this,B_,G_,"f"),new Bt("asdk_process_track_failed",t)}}))}stopProcessing(){try{a(this,x_,"f").stop()}catch(e){a(this,F_,"f").error("stopProcessing()",{type:this.type,case:"Denoiser",error:Vt(e)})}finally{c(this,j_,null,"f")}}getUpdatedDebounceCounter(e){var t;let r=null!==(t=a(this,U_,"f").get(e))&&void 0!==t?t:0;return r+=1,a(this,U_,"f").set(e,r),setTimeout((()=>{var t;const r=null!==(t=a(this,U_,"f").get(e))&&void 0!==t?t:0;r<=0?a(this,U_,"f").set(e,0):a(this,U_,"f").set(e,r-1)}),1e4),r}onError(e){const{message:t,type:n,cause:i}=e,s=r(e,["message","type","cause"]);if(n===W_.ERROR)if(a(this,F_,"f").error(t,Object.assign(Object.assign({error:Vt(i),cause:i},s),{type:this.type,case:"Denoiser"})),s.code===H_.REDUCE_LATENCY||s.code===H_.PERFORMANCE_STOP){this.getUpdatedDebounceCounter(s.code)>3&&(a(this,U_,"f").set(s.code,0),a(this,B_,"f").call(this,`ASDK performance issue(${s.code}): ${t}`,i),c(this,B_,G_,"f"))}else a(this,B_,"f").call(this,`ASDK runtime error: ${t}`,i),c(this,B_,G_,"f");n===W_.WARNING&&a(this,F_,"f").warn(t,Object.assign(Object.assign({},s),{type:this.type,case:"Denoiser"})),n===W_.INFO&&a(this,F_,"f").debug(t,Object.assign(Object.assign({},s),{type:this.type,case:"Denoiser"}))}}x_=new WeakMap,F_=new WeakMap,j_=new WeakMap,U_=new WeakMap,V_=new WeakMap,B_=new WeakMap,n([Kh(1e4),s("design:type",Function),s("design:paramtypes",[]),s("design:returntype",Promise)],Y_.prototype,"init",null);class $_ extends AudioWorkletNode{constructor(e){super(e.context,"rnnoise",{channelCountMode:"explicit",channelCount:1,channelInterpretation:"speakers",numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{module:e.noiseSuppressor.module}}),this.port.onmessage=({data:e})=>{const t=Object.assign(new Event("status"),e);this.dispatchEvent(t)}}update(e){this.port.postMessage(e)}static register(e){return o(this,void 0,void 0,(function*(){const t=rw.get(fi.Config);yield e.audioWorklet.addModule(`${t.get("staticFilesPath")}/noiseSuppressionWorklet.js`)}))}}var J_,Q_,K_,Z_,X_,eE;class tE{constructor(e){J_.set(this,void 0),Q_.set(this,void 0),K_.set(this,void 0),Z_.set(this,void 0),X_.set(this,void 0),eE.set(this,!0),c(this,J_,e.noiseSuppressor.instance.exports,"f"),c(this,Q_,e.context,"f"),c(this,K_,new Float32Array(a(this,J_,"f").memory.buffer),"f"),c(this,Z_,a(this,J_,"f").newState(),"f"),c(this,X_,a(this,Q_,"f").createScriptProcessor(),"f"),this.setOnAudioProcess()}get noiseSuppressionScriptProcessorNode(){return a(this,X_,"f")}update(e){e||(c(this,eE,!1,"f"),a(this,J_,"f").deleteState(a(this,Z_,"f")));const t=Object.assign(new Event("status"),{vadProb:a(this,J_,"f").getVadProb(a(this,Z_,"f"))});a(this,X_,"f").dispatchEvent(t)}setOnAudioProcess(){a(this,X_,"f").addEventListener("audioprocess",(({inputBuffer:e,outputBuffer:t})=>{if(!a(this,eE,"f"))return;a(this,K_,"f").set(e.getChannelData(0),a(this,J_,"f").getInput(a(this,Z_,"f"))/4);const r=t.getChannelData(0),n=a(this,J_,"f").pipe(a(this,Z_,"f"),r.length)/4;n&&r.set(a(this,K_,"f").subarray(n,n+r.length))}))}}var rE,nE,iE,sE,oE,aE,cE,dE,uE,lE,pE,hE,fE,mE,gE,vE,yE,bE,_E,EE,wE,SE,CE,PE,TE,RE,kE,DE,IE,AE,OE,ME,NE,LE,xE,FE,jE,UE,VE,BE,WE,HE,qE,zE,GE;J_=new WeakMap,Q_=new WeakMap,K_=new WeakMap,Z_=new WeakMap,X_=new WeakMap,eE=new WeakMap;class YE{constructor({context:e,noiseSuppressor:t}){rE.set(this,void 0),nE.set(this,void 0),iE.set(this,void 0),c(this,rE,e,"f"),c(this,nE,t,"f")}createNoiseSuppressionNode(){return o(this,void 0,void 0,(function*(){return/apple/i.test(navigator.vendor)?this.createScriptProcessorNode():yield this.createAudioWorkletNode()}))}stop(){var e;null===(e=a(this,iE,"f"))||void 0===e||e.update(!1)}createAudioWorkletNode(){return o(this,void 0,void 0,(function*(){return yield $_.register(a(this,rE,"f")),c(this,iE,new $_({context:a(this,rE,"f"),noiseSuppressor:a(this,nE,"f")}),"f"),a(this,iE,"f")}))}createScriptProcessorNode(){return c(this,iE,new tE({context:a(this,rE,"f"),noiseSuppressor:a(this,nE,"f")}),"f"),a(this,iE,"f").noiseSuppressionScriptProcessorNode}}rE=new WeakMap,nE=new WeakMap,iE=new WeakMap;class $E{constructor(e){sE.set(this,void 0),oE.set(this,void 0),aE.set(this,void 0),cE.set(this,void 0),this.type="rnnoise",c(this,sE,e.noiseSuppressor,"f"),c(this,aE,e.loggerFactory("TrackProcessor"),"f")}get isProcessing(){return!!a(this,cE,"f")}release(){this.stopProcessing()}processTrack(e){return o(this,void 0,void 0,(function*(){const t=(e=>{const t=window.AudioContext||window.webkitAudioContext||!1;return t?new t(e):null})();if(!t)throw new Error("AudioContext is not available");const r=new MediaStreamAudioDestinationNode(t,{channelCountMode:"explicit",channelCount:1,channelInterpretation:"speakers"});yield $_.register(t);const n=t.createMediaStreamSource(new MediaStream([e])),i=new YE({context:t,noiseSuppressor:a(this,sE,"f")}),s=yield i.createNoiseSuppressionNode();s.connect(r),n.connect(s);const[o]=r.stream.getTracks();return c(this,oE,{audioContext:t,streamDestination:r,noiseSuppressionNode:s,noiseSuppressionProvider:i},"f"),c(this,cE,o,"f"),a(this,aE,"f").info("processTrack()",{case:"Denoiser",type:this.type,track:e.id}),o}))}stopProcessing(){var e;if(this.isProcessing)if(a(this,oE,"f"))try{a(this,oE,"f").noiseSuppressionProvider.stop(),a(this,oE,"f").noiseSuppressionNode.disconnect(),a(this,oE,"f").streamDestination.disconnect(),a(this,oE,"f").audioContext.close().catch((e=>{a(this,aE,"f").error("stopProcessing()",{success:!1,error:Vt(e),case:"Denoiser",type:this.type})})),null===(e=a(this,cE,"f"))||void 0===e||e.stop(),c(this,cE,void 0,"f"),a(this,aE,"f").info("stopProcessing()",{success:!0,case:"Denoiser",type:this.type})}catch(e){a(this,aE,"f").error("stopProcessing()",{success:!1,error:Vt(e),case:"Denoiser",type:this.type})}else a(this,aE,"f").debug("stopProcessing()",{success:!1,description:"Processing context is not available",case:"Denoiser",type:this.type});else a(this,aE,"f").debug("stopProcessing()",{description:"Track is not processed",case:"Denoiser",type:this.type})}}sE=new WeakMap,oE=new WeakMap,aE=new WeakMap,cE=new WeakMap;class JE extends Xf{constructor(e){super(e),dE.set(this,!1),uE.set(this,void 0),lE.set(this,void 0),pE.set(this,void 0),c(this,pE,e.clientEventEmitter,"f")}get isDenoiserRequireActivation(){var e;return!(null===(e=a(this,uE,"f"))||void 0===e?void 0:e.isProcessing)&&a(this,dE,"f")}setTrackProcessor(e){if(!e)throw new Bt("track_processor_missing",new Error("trackProcessor must be passed as parameter"));this.logger.debug("Setting trackProcessor to AudioTrack",{case:"Denoiser",type:e.type}),c(this,uE,e,"f")}unsetTrackProcessor(){c(this,uE,void 0,"f")}get isEffectsProcessing(){var e;return Boolean(null===(e=a(this,uE,"f"))||void 0===e?void 0:e.isProcessing)}getEncoderConfig(){return this.encoderConfig}getEncodings(){var e;return ui(this.getPreferredCodec())?[]:null!==(e=this.getEncoderConfig().encodings)&&void 0!==e?e:xh}buildProduceEncodings(){return this.getEncodings()}getCodecOptions(){var e,t;return ui(this.getPreferredCodec())?{}:{opusFec:null===(e=this.getEncoderConfig().enableFec)||void 0===e||e,opusDtx:null===(t=this.getEncoderConfig().enableDtx)||void 0===t||t}}getPreferredCodec(){const{preferredCodec:e}=this.getEncoderConfig();return e||"opus"}enableNoiseSuppression(){return o(this,void 0,void 0,(function*(){var e,t;if(c(this,dE,!0,"f"),!a(this,uE,"f"))return this.logger.warn("enableNoiseSuppression()",{description:"Track suppressor is not defined"}),void a(this,pE,"f").emit(un,{cause:"Track suppressor is not defined"});try{yield this.performEnableNoiseSuppression(a(this,uE,"f")),this.logger.debug("Denoiser activated",{case:"Denoiser",type:(null===(e=a(this,uE,"f"))||void 0===e?void 0:e.type)||"none"}),a(this,pE,"f").emit(an,{type:null===(t=a(this,uE,"f"))||void 0===t?void 0:t.type})}catch(e){throw this.logger.warn("enableNoiseSuppression()",{description:"Can not enable noise suppression",track:this.logCtx,error:Vt(e)}),a(this,pE,"f").emit(un,{cause:"Failed to enable noise suppression",error:e}),new Bt("noise_suppression_enable_failed",e)}}))}disableNoiseSuppression(){return o(this,void 0,void 0,(function*(){var e,t,r;if(c(this,dE,!1,"f"),null===(e=a(this,uE,"f"))||void 0===e?void 0:e.isProcessing)if(a(this,lE,"f"))try{yield this.performDisableNoiseSuppression(),this.logger.debug("Denoiser deactivated",{case:"Denoiser",type:(null===(t=a(this,uE,"f"))||void 0===t?void 0:t.type)||"none"}),a(this,pE,"f").emit(cn,{type:null===(r=a(this,uE,"f"))||void 0===r?void 0:r.type})}catch(e){throw this.logger.warn("disableNoiseSuppression()",{description:"Can not disable noise suppression",track:this.logCtx,error:Vt(e)}),a(this,pE,"f").emit(un,{cause:"Failed to disable noise suppression",error:e}),new Bt("noise_suppression_disable_failed",e)}else this.logger.debug("disableNoiseSuppression()",{description:"Original track missing"});else this.logger.debug("stopProcessing()",{description:"Track is not processed"})}))}publish(){return o(this,void 0,void 0,(function*(){yield this.produce({preferredCodec:this.getPreferredCodec(),codecOptions:this.getCodecOptions()}),yield this.setPriority("high"),this.internalEventEmitter.emit(gn,this)}))}pause(){return o(this,void 0,void 0,(function*(){yield this.mute()}))}performEnableNoiseSuppression(e){return o(this,void 0,void 0,(function*(){const t=yield e.processTrack(this.mediaStreamTrack);c(this,lE,this.mediaStreamTrack,"f"),yield this.replaceTrack(t)}))}performDisableNoiseSuppression(){return o(this,void 0,void 0,(function*(){var e;a(this,lE,"f")&&(yield this.replaceTrack(a(this,lE,"f"))),null===(e=a(this,uE,"f"))||void 0===e||e.stopProcessing()}))}}dE=new WeakMap,uE=new WeakMap,lE=new WeakMap,pE=new WeakMap,n([Kh(1e4,"DefaultAudioTrack.enableNoiseSuppression"),s("design:type",Function),s("design:paramtypes",[Object]),s("design:returntype",Promise)],JE.prototype,"performEnableNoiseSuppression",null),n([Kh(1e4,"DefaultAudioTrack.disableNoiseSuppression"),s("design:type",Function),s("design:paramtypes",[]),s("design:returntype",Promise)],JE.prototype,"performDisableNoiseSuppression",null);class QE extends kf{constructor({track:e,statsHandler:t,widStatsAdapter:r,scoresCalculator:n,getExpectedVideoParams:i,isStaticContent:s}){super({track:e}),hE.set(this,void 0),fE.set(this,void 0),mE.set(this,void 0),gE.set(this,void 0),vE.set(this,void 0),yE.set(this,void 0),bE.set(this,void 0),_E.set(this,void 0),this.handleWebRTCStats(e,t),c(this,yE,r,"f"),c(this,vE,n,"f"),c(this,bE,i,"f"),c(this,_E,s,"f")}get videoWebRTCStats(){var e;return null===(e=a(this,hE,"f"))||void 0===e?void 0:e.inbound}get audioWebRTCStats(){var e;return null===(e=a(this,fE,"f"))||void 0===e?void 0:e.inbound}get scores(){return{Qv:a(this,mE,"f"),Qa:a(this,gE,"f")}}handleWebRTCStats(e,t){e.addEventListener("ended",(()=>{t.removeInboundVideoHandler(e.id),t.removeInboundAudioHandler(e.id)}),{once:!0}),"video"!==e.kind?t.addInboundAudioHandler(e.id,this.setAudioWebRTCStats.bind(this)):t.addInboundVideoHandler(e.id,this.setVideoWebRTCStats.bind(this))}setVideoWebRTCStats(e){var t,r;this.touchLastReceivedStatsTimestamp();const n=null===(t=a(this,bE,"f"))||void 0===t?void 0:t.call(this),i=a(this,yE,"f").adaptInboundVideoStats({stats:e.inbound,connectionStats:e.connection,prevStats:null===(r=a(this,hE,"f"))||void 0===r?void 0:r.inbound,expectedWidth:null==n?void 0:n.width,expectedHeight:null==n?void 0:n.height,expectedFrameRate:null==n?void 0:n.maxFramerate,isStaticContent:a(this,_E,"f")});c(this,mE,a(this,vE,"f").calculateVideoMOS(i),"f"),c(this,hE,e,"f")}setAudioWebRTCStats(e){var t,r,n;this.touchLastReceivedStatsTimestamp();const{inbound:i}=e,s=a(this,yE,"f").adaptInboundAudioStats({stats:i,connectionStats:e.connection,fec:null===(t=Ar("qosInboundFec"))||void 0===t||t,dtx:null===(r=Ar("qosInboundDtx"))||void 0===r||r,prevStats:null===(n=a(this,fE,"f"))||void 0===n?void 0:n.inbound});c(this,gE,a(this,vE,"f").calculateAudioMOS(s),"f"),c(this,fE,e,"f")}cleanupStats(){c(this,hE,void 0,"f"),c(this,fE,void 0,"f"),c(this,mE,void 0,"f"),c(this,gE,void 0,"f")}}hE=new WeakMap,fE=new WeakMap,mE=new WeakMap,gE=new WeakMap,vE=new WeakMap,yE=new WeakMap,bE=new WeakMap,_E=new WeakMap;class KE{constructor(e){this.label=exports.TrackLabel.Unknown,EE.set(this,void 0),wE.set(this,void 0),SE.set(this,void 0),CE.set(this,void 0),PE.set(this,void 0),TE.set(this,void 0),RE.set(this,void 0),kE.set(this,void 0),DE.set(this,void 0),IE.set(this,!1),AE.set(this,void 0),OE.set(this,!1),ME.set(this,new Um),NE.set(this,!1),LE.set(this,0),xE.set(this,void 0),this.observer=new Ft,c(this,RE,e.mediaStreamTrack,"f"),this.label=e.label,c(this,kE,e.consumer,"f"),c(this,CE,e.peerConsumerFactory,"f"),c(this,PE,e.loggerFactory("PeerTrack"),"f"),c(this,TE,e.peerEventEmitter,"f"),c(this,NE,e.muted,"f"),c(this,DE,e.paused,"f"),c(this,EE,e.network,"f"),c(this,wE,e.media,"f"),c(this,SE,e.onClose,"f"),c(this,xE,new QE({track:e.mediaStreamTrack,statsHandler:e.statsHandler,widStatsAdapter:e.widStatsAdapter,scoresCalculator:e.scoresCalculator,getExpectedVideoParams:()=>{var e;return null===(e=a(this,kE,"f"))||void 0===e?void 0:e.currentSpatialLayerParams}}),"f")}get consumer(){return a(this,kE,"f")}get videoWebRTCStats(){return a(this,xE,"f").videoWebRTCStats}get audioWebRTCStats(){return a(this,xE,"f").audioWebRTCStats}get connectionScores(){return a(this,xE,"f").scores}get logCtx(){var e,t;return{id:a(this,RE,"f").id,label:this.label,consumerId:null===(e=a(this,kE,"f"))||void 0===e?void 0:e.id,producerId:null===(t=a(this,kE,"f"))||void 0===t?void 0:t.producerId,muted:a(this,NE,"f"),paused:a(this,DE,"f"),closed:a(this,OE,"f")}}get volume(){return a(this,LE,"f")}get isRemote(){return!!a(this,kE,"f")}get mediaStreamTrack(){return a(this,RE,"f")}get kind(){return this.mediaStreamTrack.kind}get isPaused(){return a(this,DE,"f")}get isMuted(){return a(this,NE,"f")}get consumerId(){var e;return null===(e=a(this,kE,"f"))||void 0===e?void 0:e.id}get currentSpatialLayer(){var e,t;return null!==(t=null===(e=a(this,kE,"f"))||void 0===e?void 0:e.currentSpatialLayer)&&void 0!==t?t:jh}close(){return o(this,arguments,void 0,(function*({closeRemote:e=!0}={}){a(this,OE,"f")||(a(this,kE,"f")&&(yield this.closeConsumer({closeRemote:e}),this.clearCheckStateTimeout()),a(this,TE,"f").safeEmit(kn,this),c(this,OE,!0,"f"),a(this,SE,"f").call(this))}))}mute(){return o(this,void 0,void 0,(function*(){yield a(this,ME,"f").push((()=>o(this,void 0,void 0,(function*(){a(this,PE,"f").debug("mute()",{track:this.logCtx}),yield this.pauseConsumer(),c(this,NE,!0,"f")}))))}))}unmute(){return o(this,void 0,void 0,(function*(){yield a(this,ME,"f").push((()=>o(this,void 0,void 0,(function*(){a(this,PE,"f").debug("unmute()",{track:this.logCtx}),yield this.resumeConsumer(),c(this,NE,!1,"f")}))))}))}pause(){return o(this,arguments,void 0,(function*(e=!0){yield a(this,ME,"f").push((()=>o(this,void 0,void 0,(function*(){if(!a(this,kE,"f")||this.isMuted)return c(this,DE,!0,"f"),a(this,TE,"f").safeEmit(Dn,this),void a(this,PE,"f").debug("pause()",{track:this.logCtx});yield this.pauseConsumer(e),c(this,DE,!0,"f"),a(this,TE,"f").safeEmit(Dn,this)}))))}))}resume(){return o(this,arguments,void 0,(function*(e=!0){yield a(this,ME,"f").push((()=>o(this,void 0,void 0,(function*(){if(!a(this,kE,"f")||this.isMuted)return c(this,DE,!1,"f"),a(this,TE,"f").safeEmit(In,this),void a(this,PE,"f").debug("resume()",{track:this.logCtx});yield this.resumeConsumer(e),c(this,DE,!1,"f"),a(this,TE,"f").safeEmit(In,this)}))))}))}resumeConsumer(){return o(this,arguments,void 0,(function*(e=!0){if(a(this,kE,"f"))try{a(this,kE,"f").resume(),e&&(yield a(this,EE,"f").resumeRemoteConsumer(a(this,kE,"f").id)),this.checkConsumerState().catch((e=>{a(this,PE,"f").warn("Failed to checkConsumerState()",{track:this.logCtx,error:Vt(e)})})),a(this,PE,"f").debug("resumeConsumer()",{track:this.logCtx})}catch(e){(Qn(e)?a(this,PE,"f").debug.bind(a(this,PE,"f")):a(this,PE,"f").warn.bind(a(this,PE,"f")))("resumeConsumer()",{error:Vt(e),track:this.logCtx})}}))}pauseConsumer(){return o(this,arguments,void 0,(function*(e=!0){if(a(this,kE,"f"))try{if(this.clearCheckStateTimeout(),e&&(yield a(this,EE,"f").pauseRemoteConsumer(a(this,kE,"f").id)),"audio"===this.kind)return void a(this,PE,"f").debug("pauseConsumer() - skipping for audio",{track:this.logCtx});a(this,kE,"f").pause(),c(this,IE,!1,"f"),a(this,PE,"f").debug("pauseConsumer()",{track:this.logCtx})}catch(e){(Qn(e)?a(this,PE,"f").debug.bind(a(this,PE,"f")):a(this,PE,"f").warn.bind(a(this,PE,"f")))("pauseConsumer()",{error:Vt(e),track:this.logCtx})}}))}requestVideoPreferredLayers(e){return o(this,arguments,void 0,(function*({spatialLayer:e,temporalLayer:t}){if(a(this,kE,"f"))try{if(a(this,kE,"f").isAudio)return void a(this,PE,"f").debug("Only video consumers support layers",{case:"requestVideoPreferredLayers"});if(e===a(this,kE,"f").currentSpatialLayer)return;if(e>a(this,kE,"f").spatialLayers)return void a(this,PE,"f").debug("Invalid spatial layer",{spatialLayer:e,consumerSpatialLayers:a(this,kE,"f").spatialLayers,case:"requestVideoPreferredLayers"});if(e>a(this,kE,"f").currentMaxSpatialLayer)return void(yield this.requestMaxSpatialLayer(a(this,kE,"f").id,e));yield a(this,EE,"f").updateConsumerPreferredLayers(a(this,kE,"f").id,e,t),a(this,PE,"f").debug("requestVideoPreferredLayers()",{track:this.logCtx,consumer:a(this,kE,"f"),spatialLayer:e,temporalLayer:t})}catch(e){throw(Qn(e)?a(this,PE,"f").debug.bind(a(this,PE,"f")):a(this,PE,"f").error.bind(a(this,PE,"f")))("Failed to request preferred layers",{case:"requestVideoPreferredLayers",track:{id:this.mediaStreamTrack.id,kind:this.mediaStreamTrack.kind,label:this.mediaStreamTrack.label},consumerId:a(this,kE,"f").id,spatialLayers:a(this,kE,"f").spatialLayers,temporalLayers:a(this,kE,"f").temporalLayers,error:Vt(e)}),new Bt("peer_track_request_preferred_layers_failed",e)}}))}requestKeyFrame(){return o(this,void 0,void 0,(function*(){if(this.consumerId){a(this,PE,"f").debug("requestKeyFrame()",{track:this.logCtx});try{yield a(this,EE,"f").requestConsumerKeyFrame(this.consumerId)}catch(e){throw(Qn(e)?a(this,PE,"f").debug.bind(a(this,PE,"f")):a(this,PE,"f").error.bind(a(this,PE,"f")))("requestKeyFrame()",{error:Vt(e),track:this.logCtx,consumerId:this.consumerId}),new Bt("peer_track_request_key_frame_failed",e)}}}))}getVideoAvailableLayers(){if(a(this,kE,"f")){if(!a(this,kE,"f").isAudio)return a(this,kE,"f").availableSpatialLayers;a(this,PE,"f").debug("Only video consumers support layers",{case:"getVideoAvailableLayers"})}}getInfo(){return o(this,void 0,void 0,(function*(){var e;const{width:t,height:r,frameRate:n,aspectRatio:i}=a(this,RE,"f").getSettings();return{trackId:a(this,RE,"f").id,readyState:a(this,RE,"f").readyState,isRemote:this.isRemote,kind:this.kind,label:this.label,width:t,height:r,frameRate:n,aspectRatio:i,paused:a(this,DE,"f"),trackInboundStats:yield null===(e=a(this,kE,"f"))||void 0===e?void 0:e.getStats(),trackOutboundStats:yield this.getOutboundStats()}}))}getOutboundStats(){return o(this,void 0,void 0,(function*(){if(this.isRemote)return;const e=a(this,wE,"f").getAllTracks().find((e=>e.getLabel()===this.label));return e?yield e.getStats():void 0}))}requestMaxSpatialLayer(e,t){return o(this,void 0,void 0,(function*(){try{if(!a(this,kE,"f"))return;if(a(this,kE,"f").isAudio||0===a(this,kE,"f").spatialLayers||a(this,kE,"f").currentMaxSpatialLayer===t||t<a(this,kE,"f").currentMaxSpatialLayer)return void a(this,PE,"f").warn("Can`t request this spatial layer",{case:"requestMaxSpatialLayer",consumerId:e,spatialLayer:t});a(this,kE,"f").setRequestedSpatialLayer(t),yield a(this,EE,"f").requestProducerMaxSpatialLayer(a(this,kE,"f").producerId,t),a(this,PE,"f").debug("requestMaxSpatialLayer()",{consumerId:e,spatialLayer:t})}catch(r){(Qn(r)?a(this,PE,"f").debug.bind(a(this,PE,"f")):a(this,PE,"f").warn.bind(a(this,PE,"f")))("Failed to request max spatial layer",{case:"requestMaxSpatialLayer",consumerId:e,spatialLayer:t,error:Vt(r)})}}))}checkConsumerState(){return o(this,void 0,void 0,(function*(){try{if(a(this,OE,"f")||"audio"===this.kind)return;a(this,PE,"f").debug("checkConsumerState()",{track:this.logCtx});if((yield this.isInboundRTPStreamActive())||a(this,OE,"f"))return;yield this.requestKeyFrame();if((yield this.isInboundRTPStreamActive())||a(this,OE,"f"))return;if(a(this,IE,"f"))return a(this,TE,"f").emit(An,this),void a(this,PE,"f").debug("trackFail()",{track:this.logCtx});yield this.restartConsumer()}catch(e){a(this,PE,"f").warn("checkConsumerState()",{track:this,error:e})}}))}setVolume(e){a(this,LE,"f")!==e&&(c(this,LE,e,"f"),this.observer.safeEmit(mn,{value:e}))}closeConsumer(){return o(this,arguments,void 0,(function*({closeRemote:e=!0}={}){a(this,kE,"f")&&(e&&(yield a(this,EE,"f").closeRemoteConsumer(a(this,kE,"f").id)),a(this,kE,"f").close())}))}restartConsumer(){return o(this,void 0,void 0,(function*(){try{if(!a(this,kE,"f")||a(this,OE,"f"))return;a(this,PE,"f").debug("restartConsumer()",{track:this.logCtx}),a(this,TE,"f").emit(kn,this),c(this,DE,!0,"f"),yield this.closeConsumer();const{consumer:e}=yield a(this,EE,"f").createConsumer({producerId:a(this,kE,"f").producerId,rtpCapabilities:a(this,wE,"f").mediasoupDevice.rtpCapabilities,producerPeerId:a(this,kE,"f").appData.producerData.peerId});c(this,IE,!0,"f"),c(this,kE,a(this,CE,"f").call(this,{consumer:e}),"f"),c(this,RE,e.track,"f"),yield this.resume(),a(this,TE,"f").emit(Rn,this)}catch(e){c(this,IE,!0,"f"),a(this,PE,"f").warn("restartConsumer()",{track:this,error:e})}}))}isInboundRTPStreamActive(){return o(this,void 0,void 0,(function*(){if(!a(this,kE,"f")||a(this,OE,"f"))return!1;const{framesDecoded:e}=yield a(this,kE,"f").getInboundRTPStreamStats();return yield new Promise((t=>{c(this,AE,setTimeout((()=>o(this,void 0,void 0,(function*(){try{if(!a(this,kE,"f"))return void t(!1);const{framesDecoded:r}=yield a(this,kE,"f").getInboundRTPStreamStats();if(e===r&&!this.isPaused)return void t(!1);t(!0)}catch(e){a(this,PE,"f").debug("isInboundRTPStreamActive()",{error:e,track:this.logCtx}),t(!1)}}))),4500),"f")}))}))}clearCheckStateTimeout(){a(this,AE,"f")||clearTimeout(a(this,AE,"f"))}}EE=new WeakMap,wE=new WeakMap,SE=new WeakMap,CE=new WeakMap,PE=new WeakMap,TE=new WeakMap,RE=new WeakMap,kE=new WeakMap,DE=new WeakMap,IE=new WeakMap,AE=new WeakMap,OE=new WeakMap,ME=new WeakMap,NE=new WeakMap,LE=new WeakMap,xE=new WeakMap;class ZE{constructor(e){this.encodings=[],FE.set(this,void 0);const{id:t,kind:r,peerId:n,label:i,paused:s}=e;this.id=t,this.kind=r,this.peerId=n,this.label=i,this.paused=s,this.encodings=e.encodings,this.trackTransformParams=e.trackTransformParams,this.maxSpatialLayer=e.maxSpatialLayer,c(this,FE,Date.now(),"f")}setPaused(e){this.paused=e,c(this,FE,Date.now(),"f")}getStateChangedAt(){return a(this,FE,"f")}}FE=new WeakMap;class XE{constructor({id:e,channelIds:t,groups:r,producePermissions:n,appId:i,loginDate:s,producers:o=[],appData:a,uid:d,role:u,loggerFactory:l,myPeer:p,callState:h,peers:f,remotePeerTracks:m,media:g,network:v,peerConsumerFactory:y}){this.producers=new Map,this.tracks=new Map,jE.set(this,void 0),UE.set(this,void 0),VE.set(this,void 0),BE.set(this,void 0),WE.set(this,void 0),HE.set(this,void 0),qE.set(this,void 0),zE.set(this,void 0),this._observer=new Ft,this.id=e,this.channelIds=t,this.groups=r,this.producePermissions=n,this.appId=i,this.loginDate=s,this.applicationData=null!=a?a:{},this.uid=d,this.role=u,c(this,WE,p,"f"),c(this,HE,h,"f"),c(this,jE,f,"f"),c(this,UE,m,"f"),c(this,qE,y,"f"),c(this,VE,v,"f"),c(this,BE,g,"f"),c(this,zE,l("Peer"),"f"),o.forEach(this.handleNewProducer.bind(this)),this.handlePeerEvents()}get appData(){return this.applicationData}get observer(){return this._observer}get isMe(){return this.id===a(this,WE,"f").id}get isModerator(){return this.groups.includes("moderator")}get isUser(){return this.groups.includes("user")}get publishedMedia(){return Array.from(this.producers.values()).map((e=>({producerId:e.id,kind:e.kind,label:e.label,paused:e.paused})))}get shortData(){return{id:this.id,producers:Array.from(this.producers.values()).map((e=>({id:e.id,paused:e.paused}))),appData:this.appData}}hasPermission(e){return this.producePermissions.includes(e)}hasGroup(e){return this.groups.includes(e)}subscribe(e){return o(this,arguments,void 0,(function*({producerId:e,muted:t=!1}){try{const r=this.producers.get(e);if(!r)return void a(this,zE,"f").debug("subscribe()",{error:"Peer does not have a producer",peer:to(this),producerId:e});if(this.getAllConsumers().find((t=>t.producerId===e)))return void a(this,zE,"f").debug("subscribe()",{error:"Already subscribed to producer",peer:to(this),producerId:e});const{consumer:n,isProducerPaused:i}=yield a(this,VE,"f").createConsumer({producerId:r.id,rtpCapabilities:a(this,BE,"f").mediasoupDevice.rtpCapabilities,producerPeerId:this.id});if(!this.producePermissions.includes(r.label)&&Object.values(exports.TrackLabel).includes(r.label))return void a(this,zE,"f").debug("subscribe()",{error:"Producer is not allowed anymore",peer:to(this),producerId:e});const s=a(this,UE,"f").create({mediaStreamTrack:n.track,label:r.label,consumer:a(this,qE,"f").call(this,{consumer:n}),muted:t,paused:i,peerEventEmitter:this.observer});t||(yield s.unmute()),this.tracks.set(s.label,s),a(this,zE,"f").debug(`Subscribed for ${r.kind}`,{peer:to(this)})}catch(t){throw(Qn(t)?a(this,zE,"f").debug.bind(a(this,zE,"f")):a(this,zE,"f").error.bind(a(this,zE,"f")))("subscribe()",{producerId:e,error:t,peer:to(this)}),new Bt("peer_subscribe_failed",t)}}))}unsubscribe(e){return o(this,void 0,void 0,(function*(){try{const t=this.getConsumerByProducerId(e);if(!t)return;const r=this.getTrackByConsumerId(t.id);if(!r)return;yield r.close(),this.tracks.delete(r.label),a(this,zE,"f").debug(`Unsubscribed consumer ${t.kind}`,{peer:to(this)})}catch(t){throw(Qn(t)?a(this,zE,"f").debug.bind(a(this,zE,"f")):a(this,zE,"f").error.bind(a(this,zE,"f")))("unsubscribe()",{producerId:e,error:t}),new Bt("peer_unsubscribe_failed",t)}}))}setProducePermissions(e){return o(this,void 0,void 0,(function*(){this.throwIfIamNotModerator();try{yield a(this,VE,"f").changePeerProducePermissions(this.id,e)}catch(e){throw new Bt("peer_set_produce_permissions_failed",e)}a(this,zE,"f").debug("Produce permissions changed",{peerId:this.id,producePermissions:e})}))}addProducePermission(e){return o(this,void 0,void 0,(function*(){this.throwIfIamNotModerator();try{yield a(this,VE,"f").addPeerProducePermission(this.id,e)}catch(e){throw new Bt("peer_add_produce_permission_failed",e)}a(this,zE,"f").debug("Add produce permission requested",{peerId:this.id,label:e})}))}removeProducePermission(e){return o(this,void 0,void 0,(function*(){this.throwIfIamNotModerator();try{yield a(this,VE,"f").removePeerProducePermission(this.id,e)}catch(e){throw new Bt("peer_remove_produce_permission_failed",e)}a(this,zE,"f").debug("Remove produce permission requested",{peerId:this.id,label:e})}))}getInfo(){return o(this,void 0,void 0,(function*(){try{return{id:this.id,appData:this.appData,role:this.role,channelIds:this.channelIds,appId:this.appId,uid:this.uid,loginDate:this.loginDate,tracks:yield Promise.all(Array.from(this.tracks.values()).map((e=>o(this,void 0,void 0,(function*(){return yield e.getInfo()})))))}}catch(e){throw a(this,zE,"f").error("getInfo()",{peer:to(this),error:e}),new Bt("peer_get_info_failed",e)}}))}getProducers(){return Array.from(this.producers.values())}getConsumersState(){return this.getAllConsumers().map((e=>({id:e.id,paused:e.paused,producerId:e.producerId})))}handleNewProducer(e){if(this.producers.get(e.id))return;const t=new ZE(e);this.producers.set(t.id,t),a(this,zE,"f").debug("Peer published media:",{peer:to(this),producer:t});const r={producerId:t.id,kind:t.kind,label:t.label,paused:t.paused};this.observer.safeEmit(Sn,r)}handlePeerEvents(){this.observer.on(Ln,this.handleNewProducer.bind(this)),this.observer.on(xn,(e=>o(this,void 0,void 0,(function*(){this.producers.delete(e.id),a(this,zE,"f").debug("Peer unpublished media:",{peer:to(this),producer:e}),this.observer.safeEmit(Cn,{producerId:e.id,kind:e.kind,label:e.label,paused:e.paused});const t=this.tracks.get(e.label);if(t)try{yield t.close({closeRemote:!1})}catch(e){(Qn(e)?a(this,zE,"f").debug.bind(a(this,zE,"f")):a(this,zE,"f").warn.bind(a(this,zE,"f")))("Failed to close peer track due to producer closed",{label:t.label,peerId:this.id,error:Vt(e)})}})))),this.observer.on(Un,(e=>o(this,void 0,void 0,(function*(){const t=this.getTrackByConsumerId(e);if(t)try{yield t.close({closeRemote:!1}),this.tracks.delete(t.label),a(this,zE,"f").debug("Peer video track was ended:",{peer:to(this),trackLabel:t.label})}catch(e){(e instanceof Yn?a(this,zE,"f").debug.bind(a(this,zE,"f")):a(this,zE,"f").warn.bind(a(this,zE,"f")))("Failed to close peer track due to consumer closed",{label:t.label,peerId:this.id,error:Vt(e)})}})))),this.observer.on(Vn,(e=>o(this,void 0,void 0,(function*(){const t=this.getTrackByConsumerId(e);t&&(yield t.pause(!1))})))),this.observer.on(Bn,(e=>o(this,void 0,void 0,(function*(){const t=this.getTrackByConsumerId(e);t&&(yield t.resume(!1))})))),this.observer.on(Wn,(e=>{const t=this.getConsumerById(e.consumerId);(null==t?void 0:t.isVideo)&&(t.applyLayersUpdate({spatialLayer:e.spatialLayer,temporalLayer:e.temporalLayer}),e.spatialLayer===t.requestedSpatialLayer&&t.setRequestedSpatialLayer(void 0),a(this,zE,"f").debug("consumerChangePreferredLayers()",Object.assign({},e)))})),this.observer.on(Fn,(e=>o(this,void 0,void 0,(function*(){const{producerId:t,spatialLayer:r}=e,n=this.getConsumerByProducerId(t);n?(n.setCurrentMaxSpatialLayer(r),a(this,zE,"f").debug("producerSetMaxSpatialLayer()",{producerId:t,consumerId:n.id,spatialLayer:r}),n.requestedSpatialLayer===r?(yield a(this,VE,"f").updateConsumerPreferredLayers(n.id,r),a(this,zE,"f").debug("requestVideoPreferredLayers()",{producerId:t,consumerId:n.id,spatialLayer:r})):a(this,zE,"f").debug("producerSetMaxSpatialLayer()",{message:"No need to request new preferred layer",currentMaxSpatialLayer:r,requestedMaxSpatialLayer:n.requestedSpatialLayer})):a(this,zE,"f").debug("producerSetMaxSpatialLayer()",{message:"Consumer for producer not created, ignore MaxSpatialLayer change"})})))),this.observer.on(Br,(e=>{try{Xn(e),this.setAppData(e),this.observer.emit(On,e),a(this,zE,"f").debug("updatePeerAppData",{peer:to(this),appData:e})}catch(t){a(this,zE,"f").error("updatePeerAppData",{peer:to(this),appData:e,error:t})}}))}reset(){return o(this,void 0,void 0,(function*(){this.producers.clear();try{yield Promise.all(Array.from(this.tracks.values()).map((e=>o(this,void 0,void 0,(function*(){return yield e.close({closeRemote:!1})})))))}catch(e){a(this,zE,"f").debug("Failed to reset peer tracks",{peer:to(this),error:Vt(e)})}this.tracks.clear();[Ln,xn,Un,Vn,Bn,Wn,Fn,Br].forEach((e=>this.observer.removeAllListeners(e)))}))}getActiveTracksCount(){return Array.from(this.tracks.values()).map((e=>e.consumer)).filter((e=>!(null==e?void 0:e.paused))).length}getActivePublishersCount(){return Array.from(this.producers.values()).filter((e=>!e.paused)).length}handleProducePermissionsChange(e){this.producePermissions=e,Object.values(exports.TrackLabel).filter((e=>!this.producePermissions.includes(e))).forEach((e=>{const t=this.tracks.get(e);t&&(this.tracks.delete(t.label),t.close({closeRemote:!1}).catch((e=>{a(this,zE,"f").error("Failed to close track",{case:"Peer",error:Vt(e)})})))})),this.observer.safeEmit(Mn,{labels:this.producePermissions})}handleGroupsChange(e){this.groups=e,this.observer.safeEmit(Nn,{groups:e})}getAllConsumers(){return Array.from(this.tracks.values()).map((e=>e.consumer)).filter((e=>!!e))}getConsumerByProducerId(e){return this.getAllConsumers().find((t=>t.producerId===e))}getConsumerById(e){return this.getAllConsumers().find((t=>t.id===e))}getTrackByConsumerId(e){return Array.from(this.tracks.values()).find((t=>t.consumerId===e))}setAppData(e){this.applicationData=e}throwIfIamNotModerator(){if(!a(this,jE,"f").isModerator(a(this,WE,"f").id))throw new Bt("not_enough_access",new Error("Not enough access"))}}jE=new WeakMap,UE=new WeakMap,VE=new WeakMap,BE=new WeakMap,WE=new WeakMap,HE=new WeakMap,qE=new WeakMap,zE=new WeakMap;class ew{constructor(e){this.spatialLayers=jh,this.temporalLayers=Vh,this.currentSpatialLayer=jh,this.currentTemporalLayer=Vh,this.availableSpatialLayers=[],GE.set(this,void 0);const{consumer:t,loggerFactory:r}=e;this.id=t.id,this.kind=t.kind,this.producerId=t.producerId,this.appData=t.appData,this.consumer=t,c(this,GE,r("PeerConsumer"),"f"),this.currentMaxSpatialLayer=this.appData.producerData.maxSpatialLayer,this.parseScalabilityMode(),this.initAvailableSpatialLayers(),this.setCurrentSpatialLayerParams()}get paused(){return this.consumer.paused}pause(){this.consumer.pause()}resume(){this.consumer.resume()}close(){this.consumer.close()}get isVideo(){return"video"===this.kind}get isAudio(){return"audio"===this.kind}parseScalabilityMode(){if(this.consumer.rtpParameters.encodings){const{scalabilityMode:e}=this.consumer.rtpParameters.encodings[0],{spatialLayers:t,temporalLayers:r}=pd.parseScalabilityMode(e);this.spatialLayers=t,this.temporalLayers=r,a(this,GE,"f").debug("parseScalabilityMode()",{scalabilityMode:e,spatialLayers:t,temporalLayers:r})}}initAvailableSpatialLayers(){const{encodings:e,trackTransformParams:t}=this.appData.producerData;if(!Array.isArray(e))return;if(this.availableSpatialLayers=e.map((e=>this.tryPrepareSpatialLayerParams(e))),!t||this.availableSpatialLayers.length>1||this.spatialLayers<Uh)return void a(this,GE,"f").debug("Using available spatial layers",{case:"initAvailableSpatialLayers"});a(this,GE,"f").debug("Pre-generating encodings with spatial layer params",{case:"initAvailableSpatialLayers"});const r=[],n=e[e.length-1];for(let e=this.spatialLayers-1;e>=0;e-=1)r.push(this.tryPrepareSpatialLayerParams(Object.assign(Object.assign({},n),{scaleResolutionDownBy:Math.pow(2,e)})));this.availableSpatialLayers=r}setCurrentSpatialLayerParams(){const{encodings:e}=this.appData.producerData;(null==e?void 0:e[this.currentSpatialLayer])&&(this.currentSpatialLayerParams=this.tryPrepareSpatialLayerParams(e[this.currentSpatialLayer]),a(this,GE,"f").debug("setCurrentSpatialLayerParams()",{currentSpatialLayerParams:this.currentSpatialLayerParams}))}tryPrepareSpatialLayerParams(e){var t;const{trackTransformParams:r}=this.appData.producerData;if(!r)return e;const{width:n,height:i}=r,s=null!==(t=e.scaleResolutionDownBy)&&void 0!==t?t:1;return n&&i?Object.assign({width:n/s,height:i/s},e):e}setCurrentSpatialLayer(e){if(!this.isVideo)throw new Error("setCurrentSpatialLayer applies to video consumers only");this.currentSpatialLayer=e,a(this,GE,"f").debug("setCurrentSpatialLayer()",{currentSpatialLayer:e}),this.setCurrentSpatialLayerParams()}setCurrentTemporalLayer(e){if(!this.isVideo)throw new Error("setCurrentTemporalLayer applies to video consumers only");this.currentTemporalLayer=e,a(this,GE,"f").debug("setCurrentTemporalLayer()",{currentTemporalLayer:e})}applyLayersUpdate(e){if(!this.isVideo)throw new Error("applyLayersUpdate applies to video consumers only");const{spatialLayer:t,temporalLayer:r}=e;void 0!==t&&this.setCurrentSpatialLayer(t),void 0!==r&&this.setCurrentTemporalLayer(r)}setRequestedSpatialLayer(e){this.requestedSpatialLayer=e}setCurrentMaxSpatialLayer(e){this.currentMaxSpatialLayer=e}getStats(){return o(this,void 0,void 0,(function*(){var e,t;try{return{consumerId:this.consumer.id,codec:this.consumer.rtpParameters.codecs.find((e=>Cf(e))),dtlsState:null===(t=null===(e=this.consumer.rtpReceiver)||void 0===e?void 0:e.transport)||void 0===t?void 0:t.state,availableSpatialLayers:this.availableSpatialLayers,currentSpatialLayerParams:this.currentSpatialLayerParams,requestedSpatialLayer:this.requestedSpatialLayer,rtcStats:yield this.getInboundRTPStreamStats()}}catch(e){return void a(this,GE,"f").debug("getStats()",{error:e})}}))}getInboundRTPStreamStats(){return o(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>{const r=(...n)=>o(this,[...n],void 0,(function*(n=0){try{const i=yield this.consumer.getStats(),s=Array.from(i.values()).find((e=>"inbound-rtp"===e.type));if(!s&&n<5)return void setTimeout((()=>{r(n+1).catch((e=>{a(this,GE,"f").debug("Error getting RTCStatsReport",{attempt:n,error:Vt(e)})}))}),150);n>=5&&!s&&t(new Error("InboundRTPStreamStat not exist")),e(s)}catch(e){t(new Error("Can not get RTCStatsReport")),a(this,GE,"f").debug("getInboundRTPStreamStats()",{error:e})}}));r().catch((e=>{a(this,GE,"f").debug("Error executing getRTCStatsReport",{case:"PeerConsumer",error:Vt(e)})}))}))}))}}GE=new WeakMap;let tw=class{adaptInboundAudioStats(e){const{stats:t,connectionStats:r,fec:n,dtx:i,prevStats:s}=e,o=this.calculateDeltaPacketLoss({packetsLost:t.packetsLost,packetsReceivedOrSent:t.packetsReceived},s?{packetsLost:s.packetsLost,packetsReceivedOrSent:s.packetsReceived}:void 0),a=this.calculateJitterBufferDelay(t.jitterBufferDelay,t.jitterBufferEmittedCount);return{ssrc:t.ssrc,dtx:i,fec:n,packetLoss:o,bufferDelay:a,bitrate:t.bitrate,roundTripTime:1e3*r.currentRoundTripTime}}adaptInboundVideoStats(e){var t,r,n;const{stats:i,connectionStats:s,prevStats:o}=e,a=this.calculateDeltaPacketLoss({packetsLost:i.packetsLost,packetsReceivedOrSent:i.packetsReceived},o?{packetsLost:o.packetsLost,packetsReceivedOrSent:o.packetsReceived}:void 0),c=this.calculateJitterBufferDelay(i.jitterBufferDelay,i.jitterBufferEmittedCount),d=i,u=o,l=this.calculateDeltaAverageQP(d.qpSum,d.framesDecoded,null==u?void 0:u.qpSum,null==u?void 0:u.framesDecoded);return{ssrc:i.ssrc,packetLoss:a,bufferDelay:c,bitrate:i.bitrate,roundTripTime:1e3*s.currentRoundTripTime,width:i.frameWidth,height:i.frameHeight,expectedWidth:null!==(t=e.expectedWidth)&&void 0!==t?t:i.frameWidth,expectedHeight:null!==(r=e.expectedHeight)&&void 0!==r?r:i.frameHeight,frameRate:i.framesPerSecond,expectedFrameRate:null!==(n=e.expectedFrameRate)&&void 0!==n?n:i.framesPerSecond,isStaticContent:e.isStaticContent,averageQP:l}}adaptOutboundAudioStats(e){const{stats:t,remoteInboundStats:r,fec:n,dtx:i,prevStats:s}=e,o=r?this.calculateDeltaPacketLoss({packetsLost:r.packetsLost,packetsReceivedOrSent:t.packetsSent},s?{packetsLost:s.remoteInbound.packetsLost,packetsReceivedOrSent:s.outbound.packetsSent}:void 0):0,a=(null==r?void 0:r.roundTripTime)?1e3*r.roundTripTime:50,c=(null==r?void 0:r.jitter)?1e3*r.jitter:0;return{ssrc:t.ssrc,fec:n,dtx:i,packetLoss:o,bufferDelay:c,roundTripTime:a,bitrate:t.bitrate}}adaptOutboundVideoStats(e){var t,r,n,i,s,o,a;const{stats:c,remoteInboundStats:d,prevStats:u}=e,l=d?this.calculateDeltaPacketLoss({packetsLost:d.packetsLost,packetsReceivedOrSent:c.packetsSent},u?{packetsLost:u.remoteInbound.packetsLost,packetsReceivedOrSent:u.outbound.packetsSent}:void 0):0,p=(null==d?void 0:d.roundTripTime)?1e3*d.roundTripTime:50,h=(null==d?void 0:d.jitter)?1e3*d.jitter:0,f=this.calculateDeltaAverageQP(c.qpSum,c.framesEncoded,null==u?void 0:u.outbound.qpSum,null==u?void 0:u.outbound.framesEncoded);return{ssrc:c.ssrc,packetLoss:l,bufferDelay:h,bitrate:c.bitrate,roundTripTime:p,width:c.frameWidth,height:c.frameHeight,expectedWidth:null!==(t=c.frameWidth)&&void 0!==t?t:null===(r=c.track)||void 0===r?void 0:r.width,expectedHeight:null!==(n=c.frameHeight)&&void 0!==n?n:null===(i=c.track)||void 0===i?void 0:i.height,frameRate:c.framesPerSecond,expectedFrameRate:null!==(s=c.framesPerSecond)&&void 0!==s?s:null===(o=c.track)||void 0===o?void 0:o.framesPerSecond,decreaseOutboundPenalty:null===(a=Ar("qosDecreaseOutboundPenalty"))||void 0===a||a,isStaticContent:e.isStaticContent,averageQP:f,qualityLimitationReason:c.qualityLimitationReason}}calculateDeltaPacketLoss(e,t){var r,n;const i=_g(e.packetsLost-(null!==(r=null==t?void 0:t.packetsLost)&&void 0!==r?r:0),0,e.packetsLost),s=_g(e.packetsReceivedOrSent-(null!==(n=null==t?void 0:t.packetsReceivedOrSent)&&void 0!==n?n:0),0,e.packetsReceivedOrSent);return s||i?i/(i+s)*100:0}calculateDeltaAverageQP(e,t,r,n){if(void 0===e||void 0===t)return;const i=t-(null!=n?n:0);return i<=0?void 0:(e-(null!=r?r:0))/i}calculateJitterBufferDelay(e,t){return 0===t?0:e/t*1e3}};tw=n([ot()],tw);const rw=new tt({autoBindInjectable:!0});var nw,iw,sw;rw.bind(fi.ClientMetaProvider).to(Vr).inSingletonScope(),rw.bind(fi.LocalMutex).to(hg).inSingletonScope(),rw.bind(fi.SignalingApiClient).toDynamicValue((e=>new ed(e.container.get(fi.Config)))).inSingletonScope(),rw.bind(fi.CallState).to(mi).inSingletonScope(),rw.bind(fi.MyPeer).to(ro).inSingletonScope(),rw.bind(fi.LoggerFactory).toFactory((e=>{const t=e.container.get(fi.Config),r=t.get("logLevel"),n=t.get("sendAnalytics"),i=t.get("onLogMessage"),s=e.container.get(fi.ClientMetaProvider),o=e.container.get(fi.AnalyticsApiClient),a=new Ab.MessageBatcher({MaxBatchSize:50,MaxDelay:2e3,MinDelay:500});return a.on("batch",(e=>{o.log.batch({logs:e,clientMeta:s.meta})})),e=>new o_({logLevel:r,namespace:e,onLogMessage:i,sendAnalytics:n,logToRemoteBatcher:a})})),rw.bind(fi.System).to(vg).inSingletonScope(),rw.bind(fi.ProcessorsCache).to(Yh).inSingletonScope(),rw.bind(fi.IntegrationsService).to(Qh).inSingletonScope(),rw.bind(fi.MediaStreamTrackManager).to(mm).inSingletonScope(),rw.bind(fi.Media).to(vm).inSingletonScope(),rw.bind(fi.Network).to(uo).inSingletonScope(),rw.bind(fi.NetworkTransportPolicyManager).to(ng).inSingletonScope(),rw.bind(fi.TransportStateMonitor).to(N_).inSingletonScope(),rw.bind(fi.IceRecoveryService).to(z_).inSingletonScope(),rw.bind(fi.PendingClosureProducerStorage).to(zm).inSingletonScope(),rw.bind(fi.ProducerCloseManager).to(eg).inSingletonScope(),rw.bind(fi.RemotePeerTracks).to(C_).inSingletonScope(),rw.bind(fi.Peers).to(ho).inSingletonScope(),rw.bind(fi.MediaEventHandler).to(Wm).inSingletonScope(),rw.bind(fi.ChannelEventHandler).to(Nm).inSingletonScope(),rw.bind(fi.ChannelAudioObserverEventHandler).to(Ib).inSingletonScope(),rw.bind(fi.ChannelAudioObserverMissingProducerRestorer).to(kb).inSingletonScope(),rw.bind(fi.EventsQueue).to(eo).inSingletonScope(),rw.bind(fi.ChannelStateSynchronizer).to(Om).inSingletonScope(),rw.bind(fi.ChannelStateSyncEventHandler).to(ld).inSingletonScope(),rw.bind(fi.StatsHandler).to(jg).inSingletonScope(),rw.bind(fi.WIDHandler).to(I_).inSingletonScope(),rw.bind(fi.NetworkScoresUpdatedEventHandler).to(O_).inSingletonScope(),rw.bind(fi.WIDIgnoreSsrcList).toConstantValue([1234]),rw.bind(fi.CompositeStatsParser).toDynamicValue((e=>{const t=e.container.get(fi.LoggerFactory)("WID"),r=e.container.get(fi.WIDIgnoreSsrcList);return new Sr({statsParser:new Cr({ignoreSSRCList:r,logger:t})})})).inSingletonScope(),rw.bind(fi.PeriodicStatsReporter).toDynamicValue((e=>{const t=e.container.get(fi.Config),r=e.container.get(fi.CompositeStatsParser);return new sr({compositeStatsParser:r,getStatsInterval:t.get("getStatsInterval")})})).inSingletonScope(),rw.bind(fi.WebRTCIssueDetector).toDynamicValue((e=>{const t=e.container.get(fi.Config),r=e.container.get(fi.WIDHandler);if(t.get("disableWid"))return;const n=e.container.get(fi.StatsHandler),i=e.container.get(fi.NetworkScoresUpdatedEventHandler),s=e.container.get(fi.WIDIgnoreSsrcList),o=e.container.get(fi.LoggerFactory)("WID"),a=e.container.get(fi.CompositeStatsParser),c=e.container.get(fi.PeriodicStatsReporter);return new Pr({onIssues:e=>{var n;r.handleIssues(e),null===(n=t.get("onIssues"))||void 0===n||n(e)},issueEmitter:new ir,networkScoresCalculator:new ar,detectors:[new hr,new ur,new pr,new lr,new dr,new fr,new yr({minMosQuality:zt.GOOD,avgFreezeDurationThresholdMs:2e3,frozenDurationThresholdPct:50}),new br({minMosQuality:zt.GOOD,volatilityThreshold:10,affectedStreamsPercentThreshold:60})],statsReporter:c,onNetworkScoresUpdated:e=>{i.handle(e)},onStats:n.handle.bind(n),ignoreSSRCList:s,compositeStatsParser:a,logger:o,autoAddPeerConnections:!1})})).inSingletonScope(),rw.bind(fi.WIDStatsAdapter).to(tw).inSingletonScope(),rw.bind(fi.ScoresCalculator).toDynamicValue((()=>new exports.ScoresCalculator)).inSingletonScope(),rw.bind(fi.Engine).to($g).inSingletonScope(),rw.bind(fi.PeerTrackFactory).toFactory((function(e){const t=e.container.get(fi.LoggerFactory),r=e.container.get(fi.CallState),n=e.container.get(fi.StatsHandler);return i=>{const s={callState:r,loggerFactory:t,media:e.container.get(fi.Media),network:e.container.get(fi.Network),peerConsumerFactory:e.container.get(fi.PeerConsumerFactory),widStatsAdapter:e.container.get(fi.WIDStatsAdapter),scoresCalculator:e.container.get(fi.ScoresCalculator)},{peerEventEmitter:o}=i,a=new KE(Object.assign(Object.assign(Object.assign({},i),s),{statsHandler:n}));return o.safeEmit(Rn,a),a}})),rw.bind(fi.PeerFactory).toFactory((function(e){const t=e.container.get(fi.LoggerFactory),r=e.container.get(fi.CallState);return n=>{const i={callState:r,loggerFactory:t,media:e.container.get(fi.Media),myPeer:e.container.get(fi.MyPeer),network:e.container.get(fi.Network),peers:e.container.get(fi.Peers),remotePeerTracks:e.container.get(fi.RemotePeerTracks),peerConsumerFactory:e.container.get(fi.PeerConsumerFactory)};return new XE(Object.assign(Object.assign({},i),n))}})),rw.bind(fi.PeerConsumerFactory).toFactory((function(e){const t=e.container.get(fi.LoggerFactory);return e=>{const r={loggerFactory:t};return new ew(Object.assign(Object.assign({},r),e))}})),rw.bind(fi.AudioTrackFactory).toFactory((function(e){const t=e.container.get(fi.LoggerFactory),r=e.container.get(fi.StatsHandler);return n=>{const i={internalEventEmitter:e.container.get(fi.InternalEventEmitter),loggerFactory:t,media:e.container.get(fi.Media),mediaStreamTrackManager:e.container.get(fi.MediaStreamTrackManager),myPeer:e.container.get(fi.MyPeer),network:e.container.get(fi.Network),producerCloseManager:e.container.get(fi.ProducerCloseManager),mutex:e.container.get(fi.LocalMutex),processorFactory:e.container.get(fi.AudioTrackProcessorFactory),clientEventEmitter:e.container.get(fi.ClientEventEmitter),statsHandler:r,widStatsAdapter:e.container.get(fi.WIDStatsAdapter),scoresCalculator:e.container.get(fi.ScoresCalculator)};return new JE(Object.assign(Object.assign({},i),n))}})),rw.bind(fi.VideoTrackFactory).toFactory((function(e){const t=e.container.get(fi.LoggerFactory),r=e.container.get(fi.StatsHandler);return n=>{const i={internalEventEmitter:e.container.get(fi.InternalEventEmitter),loggerFactory:t,media:e.container.get(fi.Media),mediaStreamTrackManager:e.container.get(fi.MediaStreamTrackManager),myPeer:e.container.get(fi.MyPeer),network:e.container.get(fi.Network),producerCloseManager:e.container.get(fi.ProducerCloseManager),mutex:e.container.get(fi.LocalMutex),clientEventEmitter:e.container.get(fi.ClientEventEmitter),statsHandler:r,widStatsAdapter:e.container.get(fi.WIDStatsAdapter),scoresCalculator:e.container.get(fi.ScoresCalculator)};return new im(Object.assign(Object.assign({},i),n))}})),rw.bind(fi.AudioTrackProcessorFactory).toFactory((function(e){const t=e.container.get(fi.LoggerFactory),r=e.container.get(fi.Config),n=e.container.get(fi.ProcessorsCache),i=r.get("asdk");return e=>{const s=r.get("denoiser");let o=n.get(s,e.trackLabel);if(o)return o;if("rnnoise"===s&&e.noiseSuppressor&&(o=new $E({noiseSuppressor:e.noiseSuppressor,loggerFactory:t})),"asdk"===s&&(null==i?void 0:i.customerId)&&(o=new Y_({asdkCustomerId:i.customerId,loggerFactory:t,config:r})),!o)throw new TypeError("Incorrect parameters passed to AudioTrackProcessorFactory");return o}})),rw.bind(fi.DataChannelsManager).to(v_).inSingletonScope(),rw.bind(fi.DatachannelHeartbeater).to(E_).inSingletonScope(),rw.bind(fi.SignalingHeartbeater).to(S_).inSingletonScope(),rw.bind(fi.AnalyticsApiClient).toDynamicValue((e=>{const t=e.container.get(fi.Config);return new _b(t.get("analyticsApiUrl"))})).inSingletonScope(),rw.bind(fi.PeersStorage).to(po).inSingletonScope(),rw.bind(fi.TransportsStatsProvider).to(Vg).inSingletonScope();class ow{constructor(e){nw.set(this,void 0),iw.set(this,void 0),sw.set(this,void 0),this.canUseNoiseSuppression=!0;const{clientEventEmitter:t,internalEventEmitter:r}=e;rw.bind(fi.Config).toDynamicValue((()=>new Et(e))).inSingletonScope(),rw.bind(fi.InternalEventEmitter).toDynamicValue((()=>null!=r?r:new Ft)).inSingletonScope(),rw.bind(fi.ClientEventEmitter).toDynamicValue((()=>null!=t?t:new Ft)).inSingletonScope(),rw.get(fi.IntegrationsService),this.clientEventEmitter=rw.get(fi.ClientEventEmitter),c(this,nw,rw.get(fi.Engine),"f"),c(this,iw,rw.get(fi.NetworkTransportPolicyManager),"f"),c(this,sw,rw.get(fi.ClientMetaProvider),"f")}get meta(){return a(this,sw,"f").meta}get observer(){return this.clientEventEmitter}get id(){return a(this,nw,"f").myPeerId}get peers(){return a(this,nw,"f").getPeers()}get availableVideoDevices(){return a(this,nw,"f").system.availableVideoDevices}get availableAudioDevices(){return a(this,nw,"f").system.availableAudioDevices}get effectsSDKInitialized(){return a(this,nw,"f").media.effectsSDKInitialized}get scoresCalculator(){return a(this,nw,"f").scoresCalculator}detectDevices(e){return o(this,void 0,void 0,(function*(){try{return yield a(this,nw,"f").system.detectDevices(e)}catch(e){throw new Bt("detect_devices_failed",e)}}))}initEffectsSDK(){return o(this,void 0,void 0,(function*(){try{return yield a(this,nw,"f").media.initEffectsSDK()}catch(e){throw new Bt("init_effects_sdk_failed",e)}}))}join(e){return o(this,void 0,void 0,(function*(){yield a(this,nw,"f").join(e)}))}leave(e){return o(this,void 0,void 0,(function*(){yield a(this,nw,"f").release(e)}))}confirmActivity(){return o(this,void 0,void 0,(function*(){yield a(this,nw,"f").confirmActivity()}))}createCameraVideoTrack(e){return o(this,void 0,void 0,(function*(){return yield a(this,nw,"f").createCameraVideoTrack(e)}))}createMicrophoneAudioTrack(e){return o(this,void 0,void 0,(function*(){return yield a(this,nw,"f").createMicrophoneAudioTrack(e)}))}createScreenMediaTracks(e){return o(this,void 0,void 0,(function*(){return yield a(this,nw,"f").createScreenMediaTracks(e)}))}createCustomAudioTrack(e){return a(this,nw,"f").createCustomAudioTrack(e)}createCustomVideoTrack(e){return a(this,nw,"f").createCustomVideoTrack(e)}deleteTrack(e){return o(this,void 0,void 0,(function*(){yield a(this,nw,"f").deleteTrack(e)}))}requestChannelStateSync(){return o(this,void 0,void 0,(function*(){yield a(this,nw,"f").requestChannelStateSync()}))}updateAppData(e){return o(this,void 0,void 0,(function*(){yield a(this,nw,"f").updateAppData(e)}))}getTransportsInfo(){return o(this,void 0,void 0,(function*(){try{return yield a(this,nw,"f").network.getTransportsStateInfo()}catch(e){throw new Bt("get_transports_info_failed",e)}}))}setPreferRelay(e){a(this,nw,"f").network.setPreferRelay(e)}getPreferRelay(){return a(this,nw,"f").network.getPreferRelay()}isRelayEnforced(){return a(this,nw,"f").network.isRelayEnforced()}changeIceTransportPolicy(e){return o(this,void 0,void 0,(function*(){try{yield a(this,iw,"f").changeIceTransportPolicy(e)}catch(e){throw new Bt("change_ice_transport_policy_failed",e)}}))}restartIce(){return o(this,void 0,void 0,(function*(){try{const e=[a(this,nw,"f").network.sendTransport,a(this,nw,"f").network.receiveTransport,a(this,nw,"f").network.signalingTransport].filter((e=>!!e));yield Promise.all(e.map((e=>o(this,void 0,void 0,(function*(){return yield a(this,nw,"f").network.restartIce(e)})))))}catch(e){throw new Bt("restart_ice_failed",e)}}))}transportsStats(){return a(this,nw,"f").transportsStats()}setSignalingServerUrl(e){a(this,nw,"f").setSignalingServerUrl(e)}setMeta(e){a(this,sw,"f").setExternalMeta(e)}}nw=new WeakMap,iw=new WeakMap,sw=new WeakMap,exports.Client=ow,exports.EnhancedEventEmitter=Ft,exports.Peer=XE,exports.PeerProducer=ZE,exports.default=ow;
38
+ !function(e,t){(function(){var r,n="Expected a function",i="__lodash_hash_undefined__",s="__lodash_placeholder__",o=16,a=32,c=64,d=128,l=256,p=1/0,h=9007199254740991,f=NaN,m=4294967295,g=[["ary",d],["bind",1],["bindKey",2],["curry",8],["curryRight",o],["flip",512],["partial",a],["partialRight",c],["rearg",l]],v="[object Arguments]",y="[object Array]",b="[object Boolean]",_="[object Date]",E="[object Error]",w="[object Function]",S="[object GeneratorFunction]",C="[object Map]",T="[object Number]",P="[object Object]",R="[object Promise]",k="[object RegExp]",D="[object Set]",I="[object String]",A="[object Symbol]",O="[object WeakMap]",M="[object ArrayBuffer]",N="[object DataView]",L="[object Float32Array]",x="[object Float64Array]",F="[object Int8Array]",j="[object Int16Array]",U="[object Int32Array]",V="[object Uint8Array]",B="[object Uint8ClampedArray]",W="[object Uint16Array]",H="[object Uint32Array]",q=/\b__p \+= '';/g,z=/\b(__p \+=) '' \+/g,G=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Y=/&(?:amp|lt|gt|quot|#39);/g,$=/[&<>"']/g,K=RegExp(Y.source),J=RegExp($.source),Q=/<%-([\s\S]+?)%>/g,Z=/<%([\s\S]+?)%>/g,X=/<%=([\s\S]+?)%>/g,ee=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,te=/^\w*$/,re=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ne=/[\\^$.*+?()[\]{}|]/g,ie=RegExp(ne.source),se=/^\s+/,oe=/\s/,ae=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,ce=/\{\n\/\* \[wrapped with (.+)\] \*/,de=/,? & /,ue=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,le=/[()=,{}\[\]\/\s]/,pe=/\\(\\)?/g,he=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,fe=/\w*$/,me=/^[-+]0x[0-9a-f]+$/i,ge=/^0b[01]+$/i,ve=/^\[object .+?Constructor\]$/,ye=/^0o[0-7]+$/i,be=/^(?:0|[1-9]\d*)$/,_e=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Ee=/($^)/,we=/['\n\r\u2028\u2029\\]/g,Se="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",Ce="\\u2700-\\u27bf",Te="a-z\\xdf-\\xf6\\xf8-\\xff",Pe="A-Z\\xc0-\\xd6\\xd8-\\xde",Re="\\ufe0e\\ufe0f",ke="\\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",De="['’]",Ie="[\\ud800-\\udfff]",Ae="["+ke+"]",Oe="["+Se+"]",Me="\\d+",Ne="[\\u2700-\\u27bf]",Le="["+Te+"]",xe="[^\\ud800-\\udfff"+ke+Me+Ce+Te+Pe+"]",Fe="\\ud83c[\\udffb-\\udfff]",je="[^\\ud800-\\udfff]",Ue="(?:\\ud83c[\\udde6-\\uddff]){2}",Ve="[\\ud800-\\udbff][\\udc00-\\udfff]",Be="["+Pe+"]",We="(?:"+Le+"|"+xe+")",He="(?:"+Be+"|"+xe+")",qe="(?:['’](?:d|ll|m|re|s|t|ve))?",ze="(?:['’](?:D|LL|M|RE|S|T|VE))?",Ge="(?:"+Oe+"|"+Fe+")"+"?",Ye="[\\ufe0e\\ufe0f]?",$e=Ye+Ge+("(?:\\u200d(?:"+[je,Ue,Ve].join("|")+")"+Ye+Ge+")*"),Ke="(?:"+[Ne,Ue,Ve].join("|")+")"+$e,Je="(?:"+[je+Oe+"?",Oe,Ue,Ve,Ie].join("|")+")",Qe=RegExp(De,"g"),Ze=RegExp(Oe,"g"),Xe=RegExp(Fe+"(?="+Fe+")|"+Je+$e,"g"),et=RegExp([Be+"?"+Le+"+"+qe+"(?="+[Ae,Be,"$"].join("|")+")",He+"+"+ze+"(?="+[Ae,Be+We,"$"].join("|")+")",Be+"?"+We+"+"+qe,Be+"+"+ze,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Me,Ke].join("|"),"g"),tt=RegExp("[\\u200d\\ud800-\\udfff"+Se+Re+"]"),rt=/[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"],it=-1,st={};st[L]=st[x]=st[F]=st[j]=st[U]=st[V]=st[B]=st[W]=st[H]=!0,st[v]=st[y]=st[M]=st[b]=st[N]=st[_]=st[E]=st[w]=st[C]=st[T]=st[P]=st[k]=st[D]=st[I]=st[O]=!1;var ot={};ot[v]=ot[y]=ot[M]=ot[N]=ot[b]=ot[_]=ot[L]=ot[x]=ot[F]=ot[j]=ot[U]=ot[C]=ot[T]=ot[P]=ot[k]=ot[D]=ot[I]=ot[A]=ot[V]=ot[B]=ot[W]=ot[H]=!0,ot[E]=ot[w]=ot[O]=!1;var at={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},ct=parseFloat,dt=parseInt,ut="object"==typeof u&&u&&u.Object===Object&&u,lt="object"==typeof self&&self&&self.Object===Object&&self,pt=ut||lt||Function("return this")(),ht=t&&!t.nodeType&&t,ft=ht&&e&&!e.nodeType&&e,mt=ft&&ft.exports===ht,gt=mt&&ut.process,vt=function(){try{var e=ft&&ft.require&&ft.require("util").types;return e||gt&&gt.binding&&gt.binding("util")}catch(e){}}(),yt=vt&&vt.isArrayBuffer,bt=vt&&vt.isDate,_t=vt&&vt.isMap,Et=vt&&vt.isRegExp,wt=vt&&vt.isSet,St=vt&&vt.isTypedArray;function Ct(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}function Tt(e,t,r,n){for(var i=-1,s=null==e?0:e.length;++i<s;){var o=e[i];t(n,o,r(o),e)}return n}function Pt(e,t){for(var r=-1,n=null==e?0:e.length;++r<n&&!1!==t(e[r],r,e););return e}function Rt(e,t){for(var r=null==e?0:e.length;r--&&!1!==t(e[r],r,e););return e}function kt(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(!t(e[r],r,e))return!1;return!0}function Dt(e,t){for(var r=-1,n=null==e?0:e.length,i=0,s=[];++r<n;){var o=e[r];t(o,r,e)&&(s[i++]=o)}return s}function It(e,t){return!!(null==e?0:e.length)&&Vt(e,t,0)>-1}function At(e,t,r){for(var n=-1,i=null==e?0:e.length;++n<i;)if(r(t,e[n]))return!0;return!1}function Ot(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i}function Mt(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}function Nt(e,t,r,n){var i=-1,s=null==e?0:e.length;for(n&&s&&(r=e[++i]);++i<s;)r=t(r,e[i],i,e);return r}function Lt(e,t,r,n){var i=null==e?0:e.length;for(n&&i&&(r=e[--i]);i--;)r=t(r,e[i],i,e);return r}function xt(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}var Ft=qt("length");function jt(e,t,r){var n;return r(e,(function(e,r,i){if(t(e,r,i))return n=r,!1})),n}function Ut(e,t,r,n){for(var i=e.length,s=r+(n?1:-1);n?s--:++s<i;)if(t(e[s],s,e))return s;return-1}function Vt(e,t,r){return t==t?function(e,t,r){var n=r-1,i=e.length;for(;++n<i;)if(e[n]===t)return n;return-1}(e,t,r):Ut(e,Wt,r)}function Bt(e,t,r,n){for(var i=r-1,s=e.length;++i<s;)if(n(e[i],t))return i;return-1}function Wt(e){return e!=e}function Ht(e,t){var r=null==e?0:e.length;return r?Yt(e,t)/r:f}function qt(e){return function(t){return null==t?r:t[e]}}function zt(e){return function(t){return null==e?r:e[t]}}function Gt(e,t,r,n,i){return i(e,(function(e,i,s){r=n?(n=!1,e):t(r,e,i,s)})),r}function Yt(e,t){for(var n,i=-1,s=e.length;++i<s;){var o=t(e[i]);o!==r&&(n=n===r?o:n+o)}return n}function $t(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}function Kt(e){return e?e.slice(0,hr(e)+1).replace(se,""):e}function Jt(e){return function(t){return e(t)}}function Qt(e,t){return Ot(t,(function(t){return e[t]}))}function Zt(e,t){return e.has(t)}function Xt(e,t){for(var r=-1,n=e.length;++r<n&&Vt(t,e[r],0)>-1;);return r}function er(e,t){for(var r=e.length;r--&&Vt(t,e[r],0)>-1;);return r}function tr(e,t){for(var r=e.length,n=0;r--;)e[r]===t&&++n;return n}var rr=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"}),nr=zt({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"});function ir(e){return"\\"+at[e]}function sr(e){return tt.test(e)}function or(e){var t=-1,r=Array(e.size);return e.forEach((function(e,n){r[++t]=[n,e]})),r}function ar(e,t){return function(r){return e(t(r))}}function cr(e,t){for(var r=-1,n=e.length,i=0,o=[];++r<n;){var a=e[r];a!==t&&a!==s||(e[r]=s,o[i++]=r)}return o}function dr(e){var t=-1,r=Array(e.size);return e.forEach((function(e){r[++t]=e})),r}function ur(e){var t=-1,r=Array(e.size);return e.forEach((function(e){r[++t]=[e,e]})),r}function lr(e){return sr(e)?function(e){var t=Xe.lastIndex=0;for(;Xe.test(e);)++t;return t}(e):Ft(e)}function pr(e){return sr(e)?function(e){return e.match(Xe)||[]}(e):function(e){return e.split("")}(e)}function hr(e){for(var t=e.length;t--&&oe.test(e.charAt(t)););return t}var fr=zt({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"});var mr=function e(t){var u,oe=(t=null==t?pt:mr.defaults(pt.Object(),t,mr.pick(pt,nt))).Array,Se=t.Date,Ce=t.Error,Te=t.Function,Pe=t.Math,Re=t.Object,ke=t.RegExp,De=t.String,Ie=t.TypeError,Ae=oe.prototype,Oe=Te.prototype,Me=Re.prototype,Ne=t["__core-js_shared__"],Le=Oe.toString,xe=Me.hasOwnProperty,Fe=0,je=(u=/[^.]+$/.exec(Ne&&Ne.keys&&Ne.keys.IE_PROTO||""))?"Symbol(src)_1."+u:"",Ue=Me.toString,Ve=Le.call(Re),Be=pt._,We=ke("^"+Le.call(xe).replace(ne,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),He=mt?t.Buffer:r,qe=t.Symbol,ze=t.Uint8Array,Ge=He?He.allocUnsafe:r,Ye=ar(Re.getPrototypeOf,Re),$e=Re.create,Ke=Me.propertyIsEnumerable,Je=Ae.splice,Xe=qe?qe.isConcatSpreadable:r,tt=qe?qe.iterator:r,at=qe?qe.toStringTag:r,ut=function(){try{var e=hs(Re,"defineProperty");return e({},"",{}),e}catch(e){}}(),lt=t.clearTimeout!==pt.clearTimeout&&t.clearTimeout,ht=Se&&Se.now!==pt.Date.now&&Se.now,ft=t.setTimeout!==pt.setTimeout&&t.setTimeout,gt=Pe.ceil,vt=Pe.floor,Ft=Re.getOwnPropertySymbols,zt=He?He.isBuffer:r,gr=t.isFinite,vr=Ae.join,yr=ar(Re.keys,Re),br=Pe.max,_r=Pe.min,Er=Se.now,wr=t.parseInt,Sr=Pe.random,Cr=Ae.reverse,Tr=hs(t,"DataView"),Pr=hs(t,"Map"),Rr=hs(t,"Promise"),kr=hs(t,"Set"),Dr=hs(t,"WeakMap"),Ir=hs(Re,"create"),Ar=Dr&&new Dr,Or={},Mr=Vs(Tr),Nr=Vs(Pr),Lr=Vs(Rr),xr=Vs(kr),Fr=Vs(Dr),jr=qe?qe.prototype:r,Ur=jr?jr.valueOf:r,Vr=jr?jr.toString:r;function Br(e){if(ia(e)&&!Yo(e)&&!(e instanceof zr)){if(e instanceof qr)return e;if(xe.call(e,"__wrapped__"))return Bs(e)}return new qr(e)}var Wr=function(){function e(){}return function(t){if(!na(t))return{};if($e)return $e(t);e.prototype=t;var n=new e;return e.prototype=r,n}}();function Hr(){}function qr(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=r}function zr(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=m,this.__views__=[]}function Gr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Yr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function $r(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}function Kr(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new $r;++t<r;)this.add(e[t])}function Jr(e){var t=this.__data__=new Yr(e);this.size=t.size}function Qr(e,t){var r=Yo(e),n=!r&&Go(e),i=!r&&!n&&Qo(e),s=!r&&!n&&!i&&pa(e),o=r||n||i||s,a=o?$t(e.length,De):[],c=a.length;for(var d in e)!t&&!xe.call(e,d)||o&&("length"==d||i&&("offset"==d||"parent"==d)||s&&("buffer"==d||"byteLength"==d||"byteOffset"==d)||_s(d,c))||a.push(d);return a}function Zr(e){var t=e.length;return t?e[Jn(0,t-1)]:r}function Xr(e,t){return Fs(Ai(e),dn(t,0,e.length))}function en(e){return Fs(Ai(e))}function tn(e,t,n){(n!==r&&!Ho(e[t],n)||n===r&&!(t in e))&&an(e,t,n)}function rn(e,t,n){var i=e[t];xe.call(e,t)&&Ho(i,n)&&(n!==r||t in e)||an(e,t,n)}function nn(e,t){for(var r=e.length;r--;)if(Ho(e[r][0],t))return r;return-1}function sn(e,t,r,n){return fn(e,(function(e,i,s){t(n,e,r(e),s)})),n}function on(e,t){return e&&Oi(t,Na(t),e)}function an(e,t,r){"__proto__"==t&&ut?ut(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}function cn(e,t){for(var n=-1,i=t.length,s=oe(i),o=null==e;++n<i;)s[n]=o?r:Da(e,t[n]);return s}function dn(e,t,n){return e==e&&(n!==r&&(e=e<=n?e:n),t!==r&&(e=e>=t?e:t)),e}function un(e,t,n,i,s,o){var a,c=1&t,d=2&t,u=4&t;if(n&&(a=s?n(e,i,s,o):n(e)),a!==r)return a;if(!na(e))return e;var l=Yo(e);if(l){if(a=function(e){var t=e.length,r=new e.constructor(t);t&&"string"==typeof e[0]&&xe.call(e,"index")&&(r.index=e.index,r.input=e.input);return r}(e),!c)return Ai(e,a)}else{var p=gs(e),h=p==w||p==S;if(Qo(e))return Ti(e,c);if(p==P||p==v||h&&!s){if(a=d||h?{}:ys(e),!c)return d?function(e,t){return Oi(e,ms(e),t)}(e,function(e,t){return e&&Oi(t,La(t),e)}(a,e)):function(e,t){return Oi(e,fs(e),t)}(e,on(a,e))}else{if(!ot[p])return s?e:{};a=function(e,t,r){var n=e.constructor;switch(t){case M:return Pi(e);case b:case _:return new n(+e);case N:return function(e,t){var r=t?Pi(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}(e,r);case L:case x:case F:case j:case U:case V:case B:case W:case H:return Ri(e,r);case C:case D:return new n;case T:case I:return new n(e);case k:return function(e){var t=new e.constructor(e.source,fe.exec(e));return t.lastIndex=e.lastIndex,t}(e);case A:return function(e){return Ur?Re(Ur.call(e)):{}}(e)}}(e,p,c)}}o||(o=new Jr);var f=o.get(e);if(f)return f;o.set(e,a),da(e)?e.forEach((function(r){a.add(un(r,t,n,r,e,o))})):sa(e)&&e.forEach((function(r,i){a.set(i,un(r,t,n,i,e,o))}));var m=l?r:(u?d?os:ss:d?La:Na)(e);return Pt(m||e,(function(r,i){m&&(r=e[i=r]),rn(a,i,un(r,t,n,i,e,o))})),a}function ln(e,t,n){var i=n.length;if(null==e)return!i;for(e=Re(e);i--;){var s=n[i],o=t[s],a=e[s];if(a===r&&!(s in e)||!o(a))return!1}return!0}function pn(e,t,i){if("function"!=typeof e)throw new Ie(n);return Ms((function(){e.apply(r,i)}),t)}function hn(e,t,r,n){var i=-1,s=It,o=!0,a=e.length,c=[],d=t.length;if(!a)return c;r&&(t=Ot(t,Jt(r))),n?(s=At,o=!1):t.length>=200&&(s=Zt,o=!1,t=new Kr(t));e:for(;++i<a;){var u=e[i],l=null==r?u:r(u);if(u=n||0!==u?u:0,o&&l==l){for(var p=d;p--;)if(t[p]===l)continue e;c.push(u)}else s(t,l,n)||c.push(u)}return c}Br.templateSettings={escape:Q,evaluate:Z,interpolate:X,variable:"",imports:{_:Br}},Br.prototype=Hr.prototype,Br.prototype.constructor=Br,qr.prototype=Wr(Hr.prototype),qr.prototype.constructor=qr,zr.prototype=Wr(Hr.prototype),zr.prototype.constructor=zr,Gr.prototype.clear=function(){this.__data__=Ir?Ir(null):{},this.size=0},Gr.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},Gr.prototype.get=function(e){var t=this.__data__;if(Ir){var n=t[e];return n===i?r:n}return xe.call(t,e)?t[e]:r},Gr.prototype.has=function(e){var t=this.__data__;return Ir?t[e]!==r:xe.call(t,e)},Gr.prototype.set=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=Ir&&t===r?i:t,this},Yr.prototype.clear=function(){this.__data__=[],this.size=0},Yr.prototype.delete=function(e){var t=this.__data__,r=nn(t,e);return!(r<0)&&(r==t.length-1?t.pop():Je.call(t,r,1),--this.size,!0)},Yr.prototype.get=function(e){var t=this.__data__,n=nn(t,e);return n<0?r:t[n][1]},Yr.prototype.has=function(e){return nn(this.__data__,e)>-1},Yr.prototype.set=function(e,t){var r=this.__data__,n=nn(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this},$r.prototype.clear=function(){this.size=0,this.__data__={hash:new Gr,map:new(Pr||Yr),string:new Gr}},$r.prototype.delete=function(e){var t=ls(this,e).delete(e);return this.size-=t?1:0,t},$r.prototype.get=function(e){return ls(this,e).get(e)},$r.prototype.has=function(e){return ls(this,e).has(e)},$r.prototype.set=function(e,t){var r=ls(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this},Kr.prototype.add=Kr.prototype.push=function(e){return this.__data__.set(e,i),this},Kr.prototype.has=function(e){return this.__data__.has(e)},Jr.prototype.clear=function(){this.__data__=new Yr,this.size=0},Jr.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},Jr.prototype.get=function(e){return this.__data__.get(e)},Jr.prototype.has=function(e){return this.__data__.has(e)},Jr.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Yr){var n=r.__data__;if(!Pr||n.length<199)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new $r(n)}return r.set(e,t),this.size=r.size,this};var fn=Li(wn),mn=Li(Sn,!0);function gn(e,t){var r=!0;return fn(e,(function(e,n,i){return r=!!t(e,n,i)})),r}function vn(e,t,n){for(var i=-1,s=e.length;++i<s;){var o=e[i],a=t(o);if(null!=a&&(c===r?a==a&&!la(a):n(a,c)))var c=a,d=o}return d}function yn(e,t){var r=[];return fn(e,(function(e,n,i){t(e,n,i)&&r.push(e)})),r}function bn(e,t,r,n,i){var s=-1,o=e.length;for(r||(r=bs),i||(i=[]);++s<o;){var a=e[s];t>0&&r(a)?t>1?bn(a,t-1,r,n,i):Mt(i,a):n||(i[i.length]=a)}return i}var _n=xi(),En=xi(!0);function wn(e,t){return e&&_n(e,t,Na)}function Sn(e,t){return e&&En(e,t,Na)}function Cn(e,t){return Dt(t,(function(t){return ea(e[t])}))}function Tn(e,t){for(var n=0,i=(t=Ei(t,e)).length;null!=e&&n<i;)e=e[Us(t[n++])];return n&&n==i?e:r}function Pn(e,t,r){var n=t(e);return Yo(e)?n:Mt(n,r(e))}function Rn(e){return null==e?e===r?"[object Undefined]":"[object Null]":at&&at in Re(e)?function(e){var t=xe.call(e,at),n=e[at];try{e[at]=r;var i=!0}catch(e){}var s=Ue.call(e);i&&(t?e[at]=n:delete e[at]);return s}(e):function(e){return Ue.call(e)}(e)}function kn(e,t){return e>t}function Dn(e,t){return null!=e&&xe.call(e,t)}function In(e,t){return null!=e&&t in Re(e)}function An(e,t,n){for(var i=n?At:It,s=e[0].length,o=e.length,a=o,c=oe(o),d=1/0,u=[];a--;){var l=e[a];a&&t&&(l=Ot(l,Jt(t))),d=_r(l.length,d),c[a]=!n&&(t||s>=120&&l.length>=120)?new Kr(a&&l):r}l=e[0];var p=-1,h=c[0];e:for(;++p<s&&u.length<d;){var f=l[p],m=t?t(f):f;if(f=n||0!==f?f:0,!(h?Zt(h,m):i(u,m,n))){for(a=o;--a;){var g=c[a];if(!(g?Zt(g,m):i(e[a],m,n)))continue e}h&&h.push(m),u.push(f)}}return u}function On(e,t,n){var i=null==(e=Ds(e,t=Ei(t,e)))?e:e[Us(Zs(t))];return null==i?r:Ct(i,e,n)}function Mn(e){return ia(e)&&Rn(e)==v}function Nn(e,t,n,i,s){return e===t||(null==e||null==t||!ia(e)&&!ia(t)?e!=e&&t!=t:function(e,t,n,i,s,o){var a=Yo(e),c=Yo(t),d=a?y:gs(e),u=c?y:gs(t),l=(d=d==v?P:d)==P,p=(u=u==v?P:u)==P,h=d==u;if(h&&Qo(e)){if(!Qo(t))return!1;a=!0,l=!1}if(h&&!l)return o||(o=new Jr),a||pa(e)?ns(e,t,n,i,s,o):function(e,t,r,n,i,s,o){switch(r){case N:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case M:return!(e.byteLength!=t.byteLength||!s(new ze(e),new ze(t)));case b:case _:case T:return Ho(+e,+t);case E:return e.name==t.name&&e.message==t.message;case k:case I:return e==t+"";case C:var a=or;case D:var c=1&n;if(a||(a=dr),e.size!=t.size&&!c)return!1;var d=o.get(e);if(d)return d==t;n|=2,o.set(e,t);var u=ns(a(e),a(t),n,i,s,o);return o.delete(e),u;case A:if(Ur)return Ur.call(e)==Ur.call(t)}return!1}(e,t,d,n,i,s,o);if(!(1&n)){var f=l&&xe.call(e,"__wrapped__"),m=p&&xe.call(t,"__wrapped__");if(f||m){var g=f?e.value():e,w=m?t.value():t;return o||(o=new Jr),s(g,w,n,i,o)}}if(!h)return!1;return o||(o=new Jr),function(e,t,n,i,s,o){var a=1&n,c=ss(e),d=c.length,u=ss(t).length;if(d!=u&&!a)return!1;var l=d;for(;l--;){var p=c[l];if(!(a?p in t:xe.call(t,p)))return!1}var h=o.get(e),f=o.get(t);if(h&&f)return h==t&&f==e;var m=!0;o.set(e,t),o.set(t,e);var g=a;for(;++l<d;){var v=e[p=c[l]],y=t[p];if(i)var b=a?i(y,v,p,t,e,o):i(v,y,p,e,t,o);if(!(b===r?v===y||s(v,y,n,i,o):b)){m=!1;break}g||(g="constructor"==p)}if(m&&!g){var _=e.constructor,E=t.constructor;_==E||!("constructor"in e)||!("constructor"in t)||"function"==typeof _&&_ instanceof _&&"function"==typeof E&&E instanceof E||(m=!1)}return o.delete(e),o.delete(t),m}(e,t,n,i,s,o)}(e,t,n,i,Nn,s))}function Ln(e,t,n,i){var s=n.length,o=s,a=!i;if(null==e)return!o;for(e=Re(e);s--;){var c=n[s];if(a&&c[2]?c[1]!==e[c[0]]:!(c[0]in e))return!1}for(;++s<o;){var d=(c=n[s])[0],u=e[d],l=c[1];if(a&&c[2]){if(u===r&&!(d in e))return!1}else{var p=new Jr;if(i)var h=i(u,l,d,e,t,p);if(!(h===r?Nn(l,u,3,i,p):h))return!1}}return!0}function xn(e){return!(!na(e)||(t=e,je&&je in t))&&(ea(e)?We:ve).test(Vs(e));var t}function Fn(e){return"function"==typeof e?e:null==e?oc:"object"==typeof e?Yo(e)?Hn(e[0],e[1]):Wn(e):mc(e)}function jn(e){if(!Ts(e))return yr(e);var t=[];for(var r in Re(e))xe.call(e,r)&&"constructor"!=r&&t.push(r);return t}function Un(e){if(!na(e))return function(e){var t=[];if(null!=e)for(var r in Re(e))t.push(r);return t}(e);var t=Ts(e),r=[];for(var n in e)("constructor"!=n||!t&&xe.call(e,n))&&r.push(n);return r}function Vn(e,t){return e<t}function Bn(e,t){var r=-1,n=Ko(e)?oe(e.length):[];return fn(e,(function(e,i,s){n[++r]=t(e,i,s)})),n}function Wn(e){var t=ps(e);return 1==t.length&&t[0][2]?Rs(t[0][0],t[0][1]):function(r){return r===e||Ln(r,e,t)}}function Hn(e,t){return ws(e)&&Ps(t)?Rs(Us(e),t):function(n){var i=Da(n,e);return i===r&&i===t?Ia(n,e):Nn(t,i,3)}}function qn(e,t,n,i,s){e!==t&&_n(t,(function(o,a){if(s||(s=new Jr),na(o))!function(e,t,n,i,s,o,a){var c=As(e,n),d=As(t,n),u=a.get(d);if(u)return void tn(e,n,u);var l=o?o(c,d,n+"",e,t,a):r,p=l===r;if(p){var h=Yo(d),f=!h&&Qo(d),m=!h&&!f&&pa(d);l=d,h||f||m?Yo(c)?l=c:Jo(c)?l=Ai(c):f?(p=!1,l=Ti(d,!0)):m?(p=!1,l=Ri(d,!0)):l=[]:aa(d)||Go(d)?(l=c,Go(c)?l=_a(c):na(c)&&!ea(c)||(l=ys(d))):p=!1}p&&(a.set(d,l),s(l,d,i,o,a),a.delete(d));tn(e,n,l)}(e,t,a,n,qn,i,s);else{var c=i?i(As(e,a),o,a+"",e,t,s):r;c===r&&(c=o),tn(e,a,c)}}),La)}function zn(e,t){var n=e.length;if(n)return _s(t+=t<0?n:0,n)?e[t]:r}function Gn(e,t,r){t=t.length?Ot(t,(function(e){return Yo(e)?function(t){return Tn(t,1===e.length?e[0]:e)}:e})):[oc];var n=-1;t=Ot(t,Jt(us()));var i=Bn(e,(function(e,r,i){var s=Ot(t,(function(t){return t(e)}));return{criteria:s,index:++n,value:e}}));return function(e,t){var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e}(i,(function(e,t){return function(e,t,r){var n=-1,i=e.criteria,s=t.criteria,o=i.length,a=r.length;for(;++n<o;){var c=ki(i[n],s[n]);if(c)return n>=a?c:c*("desc"==r[n]?-1:1)}return e.index-t.index}(e,t,r)}))}function Yn(e,t,r){for(var n=-1,i=t.length,s={};++n<i;){var o=t[n],a=Tn(e,o);r(a,o)&&ti(s,Ei(o,e),a)}return s}function $n(e,t,r,n){var i=n?Bt:Vt,s=-1,o=t.length,a=e;for(e===t&&(t=Ai(t)),r&&(a=Ot(e,Jt(r)));++s<o;)for(var c=0,d=t[s],u=r?r(d):d;(c=i(a,u,c,n))>-1;)a!==e&&Je.call(a,c,1),Je.call(e,c,1);return e}function Kn(e,t){for(var r=e?t.length:0,n=r-1;r--;){var i=t[r];if(r==n||i!==s){var s=i;_s(i)?Je.call(e,i,1):hi(e,i)}}return e}function Jn(e,t){return e+vt(Sr()*(t-e+1))}function Qn(e,t){var r="";if(!e||t<1||t>h)return r;do{t%2&&(r+=e),(t=vt(t/2))&&(e+=e)}while(t);return r}function Zn(e,t){return Ns(ks(e,t,oc),e+"")}function Xn(e){return Zr(Ha(e))}function ei(e,t){var r=Ha(e);return Fs(r,dn(t,0,r.length))}function ti(e,t,n,i){if(!na(e))return e;for(var s=-1,o=(t=Ei(t,e)).length,a=o-1,c=e;null!=c&&++s<o;){var d=Us(t[s]),u=n;if("__proto__"===d||"constructor"===d||"prototype"===d)return e;if(s!=a){var l=c[d];(u=i?i(l,d,c):r)===r&&(u=na(l)?l:_s(t[s+1])?[]:{})}rn(c,d,u),c=c[d]}return e}var ri=Ar?function(e,t){return Ar.set(e,t),e}:oc,ni=ut?function(e,t){return ut(e,"toString",{configurable:!0,enumerable:!1,value:nc(t),writable:!0})}:oc;function ii(e){return Fs(Ha(e))}function si(e,t,r){var n=-1,i=e.length;t<0&&(t=-t>i?0:i+t),(r=r>i?i:r)<0&&(r+=i),i=t>r?0:r-t>>>0,t>>>=0;for(var s=oe(i);++n<i;)s[n]=e[n+t];return s}function oi(e,t){var r;return fn(e,(function(e,n,i){return!(r=t(e,n,i))})),!!r}function ai(e,t,r){var n=0,i=null==e?n:e.length;if("number"==typeof t&&t==t&&i<=2147483647){for(;n<i;){var s=n+i>>>1,o=e[s];null!==o&&!la(o)&&(r?o<=t:o<t)?n=s+1:i=s}return i}return ci(e,t,oc,r)}function ci(e,t,n,i){var s=0,o=null==e?0:e.length;if(0===o)return 0;for(var a=(t=n(t))!=t,c=null===t,d=la(t),u=t===r;s<o;){var l=vt((s+o)/2),p=n(e[l]),h=p!==r,f=null===p,m=p==p,g=la(p);if(a)var v=i||m;else v=u?m&&(i||h):c?m&&h&&(i||!f):d?m&&h&&!f&&(i||!g):!f&&!g&&(i?p<=t:p<t);v?s=l+1:o=l}return _r(o,4294967294)}function di(e,t){for(var r=-1,n=e.length,i=0,s=[];++r<n;){var o=e[r],a=t?t(o):o;if(!r||!Ho(a,c)){var c=a;s[i++]=0===o?0:o}}return s}function ui(e){return"number"==typeof e?e:la(e)?f:+e}function li(e){if("string"==typeof e)return e;if(Yo(e))return Ot(e,li)+"";if(la(e))return Vr?Vr.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function pi(e,t,r){var n=-1,i=It,s=e.length,o=!0,a=[],c=a;if(r)o=!1,i=At;else if(s>=200){var d=t?null:Qi(e);if(d)return dr(d);o=!1,i=Zt,c=new Kr}else c=t?[]:a;e:for(;++n<s;){var u=e[n],l=t?t(u):u;if(u=r||0!==u?u:0,o&&l==l){for(var p=c.length;p--;)if(c[p]===l)continue e;t&&c.push(l),a.push(u)}else i(c,l,r)||(c!==a&&c.push(l),a.push(u))}return a}function hi(e,t){return null==(e=Ds(e,t=Ei(t,e)))||delete e[Us(Zs(t))]}function fi(e,t,r,n){return ti(e,t,r(Tn(e,t)),n)}function mi(e,t,r,n){for(var i=e.length,s=n?i:-1;(n?s--:++s<i)&&t(e[s],s,e););return r?si(e,n?0:s,n?s+1:i):si(e,n?s+1:0,n?i:s)}function gi(e,t){var r=e;return r instanceof zr&&(r=r.value()),Nt(t,(function(e,t){return t.func.apply(t.thisArg,Mt([e],t.args))}),r)}function vi(e,t,r){var n=e.length;if(n<2)return n?pi(e[0]):[];for(var i=-1,s=oe(n);++i<n;)for(var o=e[i],a=-1;++a<n;)a!=i&&(s[i]=hn(s[i]||o,e[a],t,r));return pi(bn(s,1),t,r)}function yi(e,t,n){for(var i=-1,s=e.length,o=t.length,a={};++i<s;){var c=i<o?t[i]:r;n(a,e[i],c)}return a}function bi(e){return Jo(e)?e:[]}function _i(e){return"function"==typeof e?e:oc}function Ei(e,t){return Yo(e)?e:ws(e,t)?[e]:js(Ea(e))}var wi=Zn;function Si(e,t,n){var i=e.length;return n=n===r?i:n,!t&&n>=i?e:si(e,t,n)}var Ci=lt||function(e){return pt.clearTimeout(e)};function Ti(e,t){if(t)return e.slice();var r=e.length,n=Ge?Ge(r):new e.constructor(r);return e.copy(n),n}function Pi(e){var t=new e.constructor(e.byteLength);return new ze(t).set(new ze(e)),t}function Ri(e,t){var r=t?Pi(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}function ki(e,t){if(e!==t){var n=e!==r,i=null===e,s=e==e,o=la(e),a=t!==r,c=null===t,d=t==t,u=la(t);if(!c&&!u&&!o&&e>t||o&&a&&d&&!c&&!u||i&&a&&d||!n&&d||!s)return 1;if(!i&&!o&&!u&&e<t||u&&n&&s&&!i&&!o||c&&n&&s||!a&&s||!d)return-1}return 0}function Di(e,t,r,n){for(var i=-1,s=e.length,o=r.length,a=-1,c=t.length,d=br(s-o,0),u=oe(c+d),l=!n;++a<c;)u[a]=t[a];for(;++i<o;)(l||i<s)&&(u[r[i]]=e[i]);for(;d--;)u[a++]=e[i++];return u}function Ii(e,t,r,n){for(var i=-1,s=e.length,o=-1,a=r.length,c=-1,d=t.length,u=br(s-a,0),l=oe(u+d),p=!n;++i<u;)l[i]=e[i];for(var h=i;++c<d;)l[h+c]=t[c];for(;++o<a;)(p||i<s)&&(l[h+r[o]]=e[i++]);return l}function Ai(e,t){var r=-1,n=e.length;for(t||(t=oe(n));++r<n;)t[r]=e[r];return t}function Oi(e,t,n,i){var s=!n;n||(n={});for(var o=-1,a=t.length;++o<a;){var c=t[o],d=i?i(n[c],e[c],c,n,e):r;d===r&&(d=e[c]),s?an(n,c,d):rn(n,c,d)}return n}function Mi(e,t){return function(r,n){var i=Yo(r)?Tt:sn,s=t?t():{};return i(r,e,us(n,2),s)}}function Ni(e){return Zn((function(t,n){var i=-1,s=n.length,o=s>1?n[s-1]:r,a=s>2?n[2]:r;for(o=e.length>3&&"function"==typeof o?(s--,o):r,a&&Es(n[0],n[1],a)&&(o=s<3?r:o,s=1),t=Re(t);++i<s;){var c=n[i];c&&e(t,c,i,o)}return t}))}function Li(e,t){return function(r,n){if(null==r)return r;if(!Ko(r))return e(r,n);for(var i=r.length,s=t?i:-1,o=Re(r);(t?s--:++s<i)&&!1!==n(o[s],s,o););return r}}function xi(e){return function(t,r,n){for(var i=-1,s=Re(t),o=n(t),a=o.length;a--;){var c=o[e?a:++i];if(!1===r(s[c],c,s))break}return t}}function Fi(e){return function(t){var n=sr(t=Ea(t))?pr(t):r,i=n?n[0]:t.charAt(0),s=n?Si(n,1).join(""):t.slice(1);return i[e]()+s}}function ji(e){return function(t){return Nt(ec(Ga(t).replace(Qe,"")),e,"")}}function Ui(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 r=Wr(e.prototype),n=e.apply(r,t);return na(n)?n:r}}function Vi(e){return function(t,n,i){var s=Re(t);if(!Ko(t)){var o=us(n,3);t=Na(t),n=function(e){return o(s[e],e,s)}}var a=e(t,n,i);return a>-1?s[o?t[a]:a]:r}}function Bi(e){return is((function(t){var i=t.length,s=i,o=qr.prototype.thru;for(e&&t.reverse();s--;){var a=t[s];if("function"!=typeof a)throw new Ie(n);if(o&&!c&&"wrapper"==cs(a))var c=new qr([],!0)}for(s=c?s:i;++s<i;){var d=cs(a=t[s]),u="wrapper"==d?as(a):r;c=u&&Ss(u[0])&&424==u[1]&&!u[4].length&&1==u[9]?c[cs(u[0])].apply(c,u[3]):1==a.length&&Ss(a)?c[d]():c.thru(a)}return function(){var e=arguments,r=e[0];if(c&&1==e.length&&Yo(r))return c.plant(r).value();for(var n=0,s=i?t[n].apply(this,e):r;++n<i;)s=t[n].call(this,s);return s}}))}function Wi(e,t,n,i,s,o,a,c,u,l){var p=t&d,h=1&t,f=2&t,m=24&t,g=512&t,v=f?r:Ui(e);return function r(){for(var d=arguments.length,y=oe(d),b=d;b--;)y[b]=arguments[b];if(m)var _=ds(r),E=tr(y,_);if(i&&(y=Di(y,i,s,m)),o&&(y=Ii(y,o,a,m)),d-=E,m&&d<l){var w=cr(y,_);return Ki(e,t,Wi,r.placeholder,n,y,w,c,u,l-d)}var S=h?n:this,C=f?S[e]:e;return d=y.length,c?y=Is(y,c):g&&d>1&&y.reverse(),p&&u<d&&(y.length=u),this&&this!==pt&&this instanceof r&&(C=v||Ui(C)),C.apply(S,y)}}function Hi(e,t){return function(r,n){return function(e,t,r,n){return wn(e,(function(e,i,s){t(n,r(e),i,s)})),n}(r,e,t(n),{})}}function qi(e,t){return function(n,i){var s;if(n===r&&i===r)return t;if(n!==r&&(s=n),i!==r){if(s===r)return i;"string"==typeof n||"string"==typeof i?(n=li(n),i=li(i)):(n=ui(n),i=ui(i)),s=e(n,i)}return s}}function zi(e){return is((function(t){return t=Ot(t,Jt(us())),Zn((function(r){var n=this;return e(t,(function(e){return Ct(e,n,r)}))}))}))}function Gi(e,t){var n=(t=t===r?" ":li(t)).length;if(n<2)return n?Qn(t,e):t;var i=Qn(t,gt(e/lr(t)));return sr(t)?Si(pr(i),0,e).join(""):i.slice(0,e)}function Yi(e){return function(t,n,i){return i&&"number"!=typeof i&&Es(t,n,i)&&(n=i=r),t=ga(t),n===r?(n=t,t=0):n=ga(n),function(e,t,r,n){for(var i=-1,s=br(gt((t-e)/(r||1)),0),o=oe(s);s--;)o[n?s:++i]=e,e+=r;return o}(t,n,i=i===r?t<n?1:-1:ga(i),e)}}function $i(e){return function(t,r){return"string"==typeof t&&"string"==typeof r||(t=ba(t),r=ba(r)),e(t,r)}}function Ki(e,t,n,i,s,o,d,u,l,p){var h=8&t;t|=h?a:c,4&(t&=~(h?c:a))||(t&=-4);var f=[e,t,s,h?o:r,h?d:r,h?r:o,h?r:d,u,l,p],m=n.apply(r,f);return Ss(e)&&Os(m,f),m.placeholder=i,Ls(m,e,t)}function Ji(e){var t=Pe[e];return function(e,r){if(e=ba(e),(r=null==r?0:_r(va(r),292))&&gr(e)){var n=(Ea(e)+"e").split("e");return+((n=(Ea(t(n[0]+"e"+(+n[1]+r)))+"e").split("e"))[0]+"e"+(+n[1]-r))}return t(e)}}var Qi=kr&&1/dr(new kr([,-0]))[1]==p?function(e){return new kr(e)}:lc;function Zi(e){return function(t){var r=gs(t);return r==C?or(t):r==D?ur(t):function(e,t){return Ot(t,(function(t){return[t,e[t]]}))}(t,e(t))}}function Xi(e,t,i,u,p,h,f,m){var g=2&t;if(!g&&"function"!=typeof e)throw new Ie(n);var v=u?u.length:0;if(v||(t&=-97,u=p=r),f=f===r?f:br(va(f),0),m=m===r?m:va(m),v-=p?p.length:0,t&c){var y=u,b=p;u=p=r}var _=g?r:as(e),E=[e,t,i,u,p,y,b,h,f,m];if(_&&function(e,t){var r=e[1],n=t[1],i=r|n,o=i<131,a=n==d&&8==r||n==d&&r==l&&e[7].length<=t[8]||384==n&&t[7].length<=t[8]&&8==r;if(!o&&!a)return e;1&n&&(e[2]=t[2],i|=1&r?0:4);var c=t[3];if(c){var u=e[3];e[3]=u?Di(u,c,t[4]):c,e[4]=u?cr(e[3],s):t[4]}(c=t[5])&&(u=e[5],e[5]=u?Ii(u,c,t[6]):c,e[6]=u?cr(e[5],s):t[6]);(c=t[7])&&(e[7]=c);n&d&&(e[8]=null==e[8]?t[8]:_r(e[8],t[8]));null==e[9]&&(e[9]=t[9]);e[0]=t[0],e[1]=i}(E,_),e=E[0],t=E[1],i=E[2],u=E[3],p=E[4],!(m=E[9]=E[9]===r?g?0:e.length:br(E[9]-v,0))&&24&t&&(t&=-25),t&&1!=t)w=8==t||t==o?function(e,t,n){var i=Ui(e);return function s(){for(var o=arguments.length,a=oe(o),c=o,d=ds(s);c--;)a[c]=arguments[c];var u=o<3&&a[0]!==d&&a[o-1]!==d?[]:cr(a,d);return(o-=u.length)<n?Ki(e,t,Wi,s.placeholder,r,a,u,r,r,n-o):Ct(this&&this!==pt&&this instanceof s?i:e,this,a)}}(e,t,m):t!=a&&33!=t||p.length?Wi.apply(r,E):function(e,t,r,n){var i=1&t,s=Ui(e);return function t(){for(var o=-1,a=arguments.length,c=-1,d=n.length,u=oe(d+a),l=this&&this!==pt&&this instanceof t?s:e;++c<d;)u[c]=n[c];for(;a--;)u[c++]=arguments[++o];return Ct(l,i?r:this,u)}}(e,t,i,u);else var w=function(e,t,r){var n=1&t,i=Ui(e);return function t(){return(this&&this!==pt&&this instanceof t?i:e).apply(n?r:this,arguments)}}(e,t,i);return Ls((_?ri:Os)(w,E),e,t)}function es(e,t,n,i){return e===r||Ho(e,Me[n])&&!xe.call(i,n)?t:e}function ts(e,t,n,i,s,o){return na(e)&&na(t)&&(o.set(t,e),qn(e,t,r,ts,o),o.delete(t)),e}function rs(e){return aa(e)?r:e}function ns(e,t,n,i,s,o){var a=1&n,c=e.length,d=t.length;if(c!=d&&!(a&&d>c))return!1;var u=o.get(e),l=o.get(t);if(u&&l)return u==t&&l==e;var p=-1,h=!0,f=2&n?new Kr:r;for(o.set(e,t),o.set(t,e);++p<c;){var m=e[p],g=t[p];if(i)var v=a?i(g,m,p,t,e,o):i(m,g,p,e,t,o);if(v!==r){if(v)continue;h=!1;break}if(f){if(!xt(t,(function(e,t){if(!Zt(f,t)&&(m===e||s(m,e,n,i,o)))return f.push(t)}))){h=!1;break}}else if(m!==g&&!s(m,g,n,i,o)){h=!1;break}}return o.delete(e),o.delete(t),h}function is(e){return Ns(ks(e,r,Ys),e+"")}function ss(e){return Pn(e,Na,fs)}function os(e){return Pn(e,La,ms)}var as=Ar?function(e){return Ar.get(e)}:lc;function cs(e){for(var t=e.name+"",r=Or[t],n=xe.call(Or,t)?r.length:0;n--;){var i=r[n],s=i.func;if(null==s||s==e)return i.name}return t}function ds(e){return(xe.call(Br,"placeholder")?Br:e).placeholder}function us(){var e=Br.iteratee||ac;return e=e===ac?Fn:e,arguments.length?e(arguments[0],arguments[1]):e}function ls(e,t){var r,n,i=e.__data__;return("string"==(n=typeof(r=t))||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==r:null===r)?i["string"==typeof t?"string":"hash"]:i.map}function ps(e){for(var t=Na(e),r=t.length;r--;){var n=t[r],i=e[n];t[r]=[n,i,Ps(i)]}return t}function hs(e,t){var n=function(e,t){return null==e?r:e[t]}(e,t);return xn(n)?n:r}var fs=Ft?function(e){return null==e?[]:(e=Re(e),Dt(Ft(e),(function(t){return Ke.call(e,t)})))}:yc,ms=Ft?function(e){for(var t=[];e;)Mt(t,fs(e)),e=Ye(e);return t}:yc,gs=Rn;function vs(e,t,r){for(var n=-1,i=(t=Ei(t,e)).length,s=!1;++n<i;){var o=Us(t[n]);if(!(s=null!=e&&r(e,o)))break;e=e[o]}return s||++n!=i?s:!!(i=null==e?0:e.length)&&ra(i)&&_s(o,i)&&(Yo(e)||Go(e))}function ys(e){return"function"!=typeof e.constructor||Ts(e)?{}:Wr(Ye(e))}function bs(e){return Yo(e)||Go(e)||!!(Xe&&e&&e[Xe])}function _s(e,t){var r=typeof e;return!!(t=null==t?h:t)&&("number"==r||"symbol"!=r&&be.test(e))&&e>-1&&e%1==0&&e<t}function Es(e,t,r){if(!na(r))return!1;var n=typeof t;return!!("number"==n?Ko(r)&&_s(t,r.length):"string"==n&&t in r)&&Ho(r[t],e)}function ws(e,t){if(Yo(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!la(e))||(te.test(e)||!ee.test(e)||null!=t&&e in Re(t))}function Ss(e){var t=cs(e),r=Br[t];if("function"!=typeof r||!(t in zr.prototype))return!1;if(e===r)return!0;var n=as(r);return!!n&&e===n[0]}(Tr&&gs(new Tr(new ArrayBuffer(1)))!=N||Pr&&gs(new Pr)!=C||Rr&&gs(Rr.resolve())!=R||kr&&gs(new kr)!=D||Dr&&gs(new Dr)!=O)&&(gs=function(e){var t=Rn(e),n=t==P?e.constructor:r,i=n?Vs(n):"";if(i)switch(i){case Mr:return N;case Nr:return C;case Lr:return R;case xr:return D;case Fr:return O}return t});var Cs=Ne?ea:bc;function Ts(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Me)}function Ps(e){return e==e&&!na(e)}function Rs(e,t){return function(n){return null!=n&&(n[e]===t&&(t!==r||e in Re(n)))}}function ks(e,t,n){return t=br(t===r?e.length-1:t,0),function(){for(var r=arguments,i=-1,s=br(r.length-t,0),o=oe(s);++i<s;)o[i]=r[t+i];i=-1;for(var a=oe(t+1);++i<t;)a[i]=r[i];return a[t]=n(o),Ct(e,this,a)}}function Ds(e,t){return t.length<2?e:Tn(e,si(t,0,-1))}function Is(e,t){for(var n=e.length,i=_r(t.length,n),s=Ai(e);i--;){var o=t[i];e[i]=_s(o,n)?s[o]:r}return e}function As(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}var Os=xs(ri),Ms=ft||function(e,t){return pt.setTimeout(e,t)},Ns=xs(ni);function Ls(e,t,r){var n=t+"";return Ns(e,function(e,t){var r=t.length;if(!r)return e;var n=r-1;return t[n]=(r>1?"& ":"")+t[n],t=t.join(r>2?", ":" "),e.replace(ae,"{\n/* [wrapped with "+t+"] */\n")}(n,function(e,t){return Pt(g,(function(r){var n="_."+r[0];t&r[1]&&!It(e,n)&&e.push(n)})),e.sort()}(function(e){var t=e.match(ce);return t?t[1].split(de):[]}(n),r)))}function xs(e){var t=0,n=0;return function(){var i=Er(),s=16-(i-n);if(n=i,s>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(r,arguments)}}function Fs(e,t){var n=-1,i=e.length,s=i-1;for(t=t===r?i:t;++n<t;){var o=Jn(n,s),a=e[o];e[o]=e[n],e[n]=a}return e.length=t,e}var js=function(e){var t=Fo(e,(function(e){return 500===r.size&&r.clear(),e})),r=t.cache;return t}((function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(re,(function(e,r,n,i){t.push(n?i.replace(pe,"$1"):r||e)})),t}));function Us(e){if("string"==typeof e||la(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function Vs(e){if(null!=e){try{return Le.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Bs(e){if(e instanceof zr)return e.clone();var t=new qr(e.__wrapped__,e.__chain__);return t.__actions__=Ai(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}var Ws=Zn((function(e,t){return Jo(e)?hn(e,bn(t,1,Jo,!0)):[]})),Hs=Zn((function(e,t){var n=Zs(t);return Jo(n)&&(n=r),Jo(e)?hn(e,bn(t,1,Jo,!0),us(n,2)):[]})),qs=Zn((function(e,t){var n=Zs(t);return Jo(n)&&(n=r),Jo(e)?hn(e,bn(t,1,Jo,!0),r,n):[]}));function zs(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var i=null==r?0:va(r);return i<0&&(i=br(n+i,0)),Ut(e,us(t,3),i)}function Gs(e,t,n){var i=null==e?0:e.length;if(!i)return-1;var s=i-1;return n!==r&&(s=va(n),s=n<0?br(i+s,0):_r(s,i-1)),Ut(e,us(t,3),s,!0)}function Ys(e){return(null==e?0:e.length)?bn(e,1):[]}function $s(e){return e&&e.length?e[0]:r}var Ks=Zn((function(e){var t=Ot(e,bi);return t.length&&t[0]===e[0]?An(t):[]})),Js=Zn((function(e){var t=Zs(e),n=Ot(e,bi);return t===Zs(n)?t=r:n.pop(),n.length&&n[0]===e[0]?An(n,us(t,2)):[]})),Qs=Zn((function(e){var t=Zs(e),n=Ot(e,bi);return(t="function"==typeof t?t:r)&&n.pop(),n.length&&n[0]===e[0]?An(n,r,t):[]}));function Zs(e){var t=null==e?0:e.length;return t?e[t-1]:r}var Xs=Zn(eo);function eo(e,t){return e&&e.length&&t&&t.length?$n(e,t):e}var to=is((function(e,t){var r=null==e?0:e.length,n=cn(e,t);return Kn(e,Ot(t,(function(e){return _s(e,r)?+e:e})).sort(ki)),n}));function ro(e){return null==e?e:Cr.call(e)}var no=Zn((function(e){return pi(bn(e,1,Jo,!0))})),io=Zn((function(e){var t=Zs(e);return Jo(t)&&(t=r),pi(bn(e,1,Jo,!0),us(t,2))})),so=Zn((function(e){var t=Zs(e);return t="function"==typeof t?t:r,pi(bn(e,1,Jo,!0),r,t)}));function oo(e){if(!e||!e.length)return[];var t=0;return e=Dt(e,(function(e){if(Jo(e))return t=br(e.length,t),!0})),$t(t,(function(t){return Ot(e,qt(t))}))}function ao(e,t){if(!e||!e.length)return[];var n=oo(e);return null==t?n:Ot(n,(function(e){return Ct(t,r,e)}))}var co=Zn((function(e,t){return Jo(e)?hn(e,t):[]})),uo=Zn((function(e){return vi(Dt(e,Jo))})),lo=Zn((function(e){var t=Zs(e);return Jo(t)&&(t=r),vi(Dt(e,Jo),us(t,2))})),po=Zn((function(e){var t=Zs(e);return t="function"==typeof t?t:r,vi(Dt(e,Jo),r,t)})),ho=Zn(oo);var fo=Zn((function(e){var t=e.length,n=t>1?e[t-1]:r;return n="function"==typeof n?(e.pop(),n):r,ao(e,n)}));function mo(e){var t=Br(e);return t.__chain__=!0,t}function go(e,t){return t(e)}var vo=is((function(e){var t=e.length,n=t?e[0]:0,i=this.__wrapped__,s=function(t){return cn(t,e)};return!(t>1||this.__actions__.length)&&i instanceof zr&&_s(n)?((i=i.slice(n,+n+(t?1:0))).__actions__.push({func:go,args:[s],thisArg:r}),new qr(i,this.__chain__).thru((function(e){return t&&!e.length&&e.push(r),e}))):this.thru(s)}));var yo=Mi((function(e,t,r){xe.call(e,r)?++e[r]:an(e,r,1)}));var bo=Vi(zs),_o=Vi(Gs);function Eo(e,t){return(Yo(e)?Pt:fn)(e,us(t,3))}function wo(e,t){return(Yo(e)?Rt:mn)(e,us(t,3))}var So=Mi((function(e,t,r){xe.call(e,r)?e[r].push(t):an(e,r,[t])}));var Co=Zn((function(e,t,r){var n=-1,i="function"==typeof t,s=Ko(e)?oe(e.length):[];return fn(e,(function(e){s[++n]=i?Ct(t,e,r):On(e,t,r)})),s})),To=Mi((function(e,t,r){an(e,r,t)}));function Po(e,t){return(Yo(e)?Ot:Bn)(e,us(t,3))}var Ro=Mi((function(e,t,r){e[r?0:1].push(t)}),(function(){return[[],[]]}));var ko=Zn((function(e,t){if(null==e)return[];var r=t.length;return r>1&&Es(e,t[0],t[1])?t=[]:r>2&&Es(t[0],t[1],t[2])&&(t=[t[0]]),Gn(e,bn(t,1),[])})),Do=ht||function(){return pt.Date.now()};function Io(e,t,n){return t=n?r:t,t=e&&null==t?e.length:t,Xi(e,d,r,r,r,r,t)}function Ao(e,t){var i;if("function"!=typeof t)throw new Ie(n);return e=va(e),function(){return--e>0&&(i=t.apply(this,arguments)),e<=1&&(t=r),i}}var Oo=Zn((function(e,t,r){var n=1;if(r.length){var i=cr(r,ds(Oo));n|=a}return Xi(e,n,t,r,i)})),Mo=Zn((function(e,t,r){var n=3;if(r.length){var i=cr(r,ds(Mo));n|=a}return Xi(t,n,e,r,i)}));function No(e,t,i){var s,o,a,c,d,u,l=0,p=!1,h=!1,f=!0;if("function"!=typeof e)throw new Ie(n);function m(t){var n=s,i=o;return s=o=r,l=t,c=e.apply(i,n)}function g(e){return l=e,d=Ms(y,t),p?m(e):c}function v(e){var n=e-u;return u===r||n>=t||n<0||h&&e-l>=a}function y(){var e=Do();if(v(e))return b(e);d=Ms(y,function(e){var r=t-(e-u);return h?_r(r,a-(e-l)):r}(e))}function b(e){return d=r,f&&s?m(e):(s=o=r,c)}function _(){var e=Do(),n=v(e);if(s=arguments,o=this,u=e,n){if(d===r)return g(u);if(h)return Ci(d),d=Ms(y,t),m(u)}return d===r&&(d=Ms(y,t)),c}return t=ba(t)||0,na(i)&&(p=!!i.leading,a=(h="maxWait"in i)?br(ba(i.maxWait)||0,t):a,f="trailing"in i?!!i.trailing:f),_.cancel=function(){d!==r&&Ci(d),l=0,s=u=o=d=r},_.flush=function(){return d===r?c:b(Do())},_}var Lo=Zn((function(e,t){return pn(e,1,t)})),xo=Zn((function(e,t,r){return pn(e,ba(t)||0,r)}));function Fo(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new Ie(n);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],s=r.cache;if(s.has(i))return s.get(i);var o=e.apply(this,n);return r.cache=s.set(i,o)||s,o};return r.cache=new(Fo.Cache||$r),r}function jo(e){if("function"!=typeof e)throw new Ie(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)}}Fo.Cache=$r;var Uo=wi((function(e,t){var r=(t=1==t.length&&Yo(t[0])?Ot(t[0],Jt(us())):Ot(bn(t,1),Jt(us()))).length;return Zn((function(n){for(var i=-1,s=_r(n.length,r);++i<s;)n[i]=t[i].call(this,n[i]);return Ct(e,this,n)}))})),Vo=Zn((function(e,t){var n=cr(t,ds(Vo));return Xi(e,a,r,t,n)})),Bo=Zn((function(e,t){var n=cr(t,ds(Bo));return Xi(e,c,r,t,n)})),Wo=is((function(e,t){return Xi(e,l,r,r,r,t)}));function Ho(e,t){return e===t||e!=e&&t!=t}var qo=$i(kn),zo=$i((function(e,t){return e>=t})),Go=Mn(function(){return arguments}())?Mn:function(e){return ia(e)&&xe.call(e,"callee")&&!Ke.call(e,"callee")},Yo=oe.isArray,$o=yt?Jt(yt):function(e){return ia(e)&&Rn(e)==M};function Ko(e){return null!=e&&ra(e.length)&&!ea(e)}function Jo(e){return ia(e)&&Ko(e)}var Qo=zt||bc,Zo=bt?Jt(bt):function(e){return ia(e)&&Rn(e)==_};function Xo(e){if(!ia(e))return!1;var t=Rn(e);return t==E||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!aa(e)}function ea(e){if(!na(e))return!1;var t=Rn(e);return t==w||t==S||"[object AsyncFunction]"==t||"[object Proxy]"==t}function ta(e){return"number"==typeof e&&e==va(e)}function ra(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=h}function na(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function ia(e){return null!=e&&"object"==typeof e}var sa=_t?Jt(_t):function(e){return ia(e)&&gs(e)==C};function oa(e){return"number"==typeof e||ia(e)&&Rn(e)==T}function aa(e){if(!ia(e)||Rn(e)!=P)return!1;var t=Ye(e);if(null===t)return!0;var r=xe.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Le.call(r)==Ve}var ca=Et?Jt(Et):function(e){return ia(e)&&Rn(e)==k};var da=wt?Jt(wt):function(e){return ia(e)&&gs(e)==D};function ua(e){return"string"==typeof e||!Yo(e)&&ia(e)&&Rn(e)==I}function la(e){return"symbol"==typeof e||ia(e)&&Rn(e)==A}var pa=St?Jt(St):function(e){return ia(e)&&ra(e.length)&&!!st[Rn(e)]};var ha=$i(Vn),fa=$i((function(e,t){return e<=t}));function ma(e){if(!e)return[];if(Ko(e))return ua(e)?pr(e):Ai(e);if(tt&&e[tt])return function(e){for(var t,r=[];!(t=e.next()).done;)r.push(t.value);return r}(e[tt]());var t=gs(e);return(t==C?or:t==D?dr:Ha)(e)}function ga(e){return e?(e=ba(e))===p||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}function va(e){var t=ga(e),r=t%1;return t==t?r?t-r:t:0}function ya(e){return e?dn(va(e),0,m):0}function ba(e){if("number"==typeof e)return e;if(la(e))return f;if(na(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=na(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=Kt(e);var r=ge.test(e);return r||ye.test(e)?dt(e.slice(2),r?2:8):me.test(e)?f:+e}function _a(e){return Oi(e,La(e))}function Ea(e){return null==e?"":li(e)}var wa=Ni((function(e,t){if(Ts(t)||Ko(t))Oi(t,Na(t),e);else for(var r in t)xe.call(t,r)&&rn(e,r,t[r])})),Sa=Ni((function(e,t){Oi(t,La(t),e)})),Ca=Ni((function(e,t,r,n){Oi(t,La(t),e,n)})),Ta=Ni((function(e,t,r,n){Oi(t,Na(t),e,n)})),Pa=is(cn);var Ra=Zn((function(e,t){e=Re(e);var n=-1,i=t.length,s=i>2?t[2]:r;for(s&&Es(t[0],t[1],s)&&(i=1);++n<i;)for(var o=t[n],a=La(o),c=-1,d=a.length;++c<d;){var u=a[c],l=e[u];(l===r||Ho(l,Me[u])&&!xe.call(e,u))&&(e[u]=o[u])}return e})),ka=Zn((function(e){return e.push(r,ts),Ct(Fa,r,e)}));function Da(e,t,n){var i=null==e?r:Tn(e,t);return i===r?n:i}function Ia(e,t){return null!=e&&vs(e,t,In)}var Aa=Hi((function(e,t,r){null!=t&&"function"!=typeof t.toString&&(t=Ue.call(t)),e[t]=r}),nc(oc)),Oa=Hi((function(e,t,r){null!=t&&"function"!=typeof t.toString&&(t=Ue.call(t)),xe.call(e,t)?e[t].push(r):e[t]=[r]}),us),Ma=Zn(On);function Na(e){return Ko(e)?Qr(e):jn(e)}function La(e){return Ko(e)?Qr(e,!0):Un(e)}var xa=Ni((function(e,t,r){qn(e,t,r)})),Fa=Ni((function(e,t,r,n){qn(e,t,r,n)})),ja=is((function(e,t){var r={};if(null==e)return r;var n=!1;t=Ot(t,(function(t){return t=Ei(t,e),n||(n=t.length>1),t})),Oi(e,os(e),r),n&&(r=un(r,7,rs));for(var i=t.length;i--;)hi(r,t[i]);return r}));var Ua=is((function(e,t){return null==e?{}:function(e,t){return Yn(e,t,(function(t,r){return Ia(e,r)}))}(e,t)}));function Va(e,t){if(null==e)return{};var r=Ot(os(e),(function(e){return[e]}));return t=us(t),Yn(e,r,(function(e,r){return t(e,r[0])}))}var Ba=Zi(Na),Wa=Zi(La);function Ha(e){return null==e?[]:Qt(e,Na(e))}var qa=ji((function(e,t,r){return t=t.toLowerCase(),e+(r?za(t):t)}));function za(e){return Xa(Ea(e).toLowerCase())}function Ga(e){return(e=Ea(e))&&e.replace(_e,rr).replace(Ze,"")}var Ya=ji((function(e,t,r){return e+(r?"-":"")+t.toLowerCase()})),$a=ji((function(e,t,r){return e+(r?" ":"")+t.toLowerCase()})),Ka=Fi("toLowerCase");var Ja=ji((function(e,t,r){return e+(r?"_":"")+t.toLowerCase()}));var Qa=ji((function(e,t,r){return e+(r?" ":"")+Xa(t)}));var Za=ji((function(e,t,r){return e+(r?" ":"")+t.toUpperCase()})),Xa=Fi("toUpperCase");function ec(e,t,n){return e=Ea(e),(t=n?r:t)===r?function(e){return rt.test(e)}(e)?function(e){return e.match(et)||[]}(e):function(e){return e.match(ue)||[]}(e):e.match(t)||[]}var tc=Zn((function(e,t){try{return Ct(e,r,t)}catch(e){return Xo(e)?e:new Ce(e)}})),rc=is((function(e,t){return Pt(t,(function(t){t=Us(t),an(e,t,Oo(e[t],e))})),e}));function nc(e){return function(){return e}}var ic=Bi(),sc=Bi(!0);function oc(e){return e}function ac(e){return Fn("function"==typeof e?e:un(e,1))}var cc=Zn((function(e,t){return function(r){return On(r,e,t)}})),dc=Zn((function(e,t){return function(r){return On(e,r,t)}}));function uc(e,t,r){var n=Na(t),i=Cn(t,n);null!=r||na(t)&&(i.length||!n.length)||(r=t,t=e,e=this,i=Cn(t,Na(t)));var s=!(na(r)&&"chain"in r&&!r.chain),o=ea(e);return Pt(i,(function(r){var n=t[r];e[r]=n,o&&(e.prototype[r]=function(){var t=this.__chain__;if(s||t){var r=e(this.__wrapped__),i=r.__actions__=Ai(this.__actions__);return i.push({func:n,args:arguments,thisArg:e}),r.__chain__=t,r}return n.apply(e,Mt([this.value()],arguments))})})),e}function lc(){}var pc=zi(Ot),hc=zi(kt),fc=zi(xt);function mc(e){return ws(e)?qt(Us(e)):function(e){return function(t){return Tn(t,e)}}(e)}var gc=Yi(),vc=Yi(!0);function yc(){return[]}function bc(){return!1}var _c=qi((function(e,t){return e+t}),0),Ec=Ji("ceil"),wc=qi((function(e,t){return e/t}),1),Sc=Ji("floor");var Cc,Tc=qi((function(e,t){return e*t}),1),Pc=Ji("round"),Rc=qi((function(e,t){return e-t}),0);return Br.after=function(e,t){if("function"!=typeof t)throw new Ie(n);return e=va(e),function(){if(--e<1)return t.apply(this,arguments)}},Br.ary=Io,Br.assign=wa,Br.assignIn=Sa,Br.assignInWith=Ca,Br.assignWith=Ta,Br.at=Pa,Br.before=Ao,Br.bind=Oo,Br.bindAll=rc,Br.bindKey=Mo,Br.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return Yo(e)?e:[e]},Br.chain=mo,Br.chunk=function(e,t,n){t=(n?Es(e,t,n):t===r)?1:br(va(t),0);var i=null==e?0:e.length;if(!i||t<1)return[];for(var s=0,o=0,a=oe(gt(i/t));s<i;)a[o++]=si(e,s,s+=t);return a},Br.compact=function(e){for(var t=-1,r=null==e?0:e.length,n=0,i=[];++t<r;){var s=e[t];s&&(i[n++]=s)}return i},Br.concat=function(){var e=arguments.length;if(!e)return[];for(var t=oe(e-1),r=arguments[0],n=e;n--;)t[n-1]=arguments[n];return Mt(Yo(r)?Ai(r):[r],bn(t,1))},Br.cond=function(e){var t=null==e?0:e.length,r=us();return e=t?Ot(e,(function(e){if("function"!=typeof e[1])throw new Ie(n);return[r(e[0]),e[1]]})):[],Zn((function(r){for(var n=-1;++n<t;){var i=e[n];if(Ct(i[0],this,r))return Ct(i[1],this,r)}}))},Br.conforms=function(e){return function(e){var t=Na(e);return function(r){return ln(r,e,t)}}(un(e,1))},Br.constant=nc,Br.countBy=yo,Br.create=function(e,t){var r=Wr(e);return null==t?r:on(r,t)},Br.curry=function e(t,n,i){var s=Xi(t,8,r,r,r,r,r,n=i?r:n);return s.placeholder=e.placeholder,s},Br.curryRight=function e(t,n,i){var s=Xi(t,o,r,r,r,r,r,n=i?r:n);return s.placeholder=e.placeholder,s},Br.debounce=No,Br.defaults=Ra,Br.defaultsDeep=ka,Br.defer=Lo,Br.delay=xo,Br.difference=Ws,Br.differenceBy=Hs,Br.differenceWith=qs,Br.drop=function(e,t,n){var i=null==e?0:e.length;return i?si(e,(t=n||t===r?1:va(t))<0?0:t,i):[]},Br.dropRight=function(e,t,n){var i=null==e?0:e.length;return i?si(e,0,(t=i-(t=n||t===r?1:va(t)))<0?0:t):[]},Br.dropRightWhile=function(e,t){return e&&e.length?mi(e,us(t,3),!0,!0):[]},Br.dropWhile=function(e,t){return e&&e.length?mi(e,us(t,3),!0):[]},Br.fill=function(e,t,n,i){var s=null==e?0:e.length;return s?(n&&"number"!=typeof n&&Es(e,t,n)&&(n=0,i=s),function(e,t,n,i){var s=e.length;for((n=va(n))<0&&(n=-n>s?0:s+n),(i=i===r||i>s?s:va(i))<0&&(i+=s),i=n>i?0:ya(i);n<i;)e[n++]=t;return e}(e,t,n,i)):[]},Br.filter=function(e,t){return(Yo(e)?Dt:yn)(e,us(t,3))},Br.flatMap=function(e,t){return bn(Po(e,t),1)},Br.flatMapDeep=function(e,t){return bn(Po(e,t),p)},Br.flatMapDepth=function(e,t,n){return n=n===r?1:va(n),bn(Po(e,t),n)},Br.flatten=Ys,Br.flattenDeep=function(e){return(null==e?0:e.length)?bn(e,p):[]},Br.flattenDepth=function(e,t){return(null==e?0:e.length)?bn(e,t=t===r?1:va(t)):[]},Br.flip=function(e){return Xi(e,512)},Br.flow=ic,Br.flowRight=sc,Br.fromPairs=function(e){for(var t=-1,r=null==e?0:e.length,n={};++t<r;){var i=e[t];n[i[0]]=i[1]}return n},Br.functions=function(e){return null==e?[]:Cn(e,Na(e))},Br.functionsIn=function(e){return null==e?[]:Cn(e,La(e))},Br.groupBy=So,Br.initial=function(e){return(null==e?0:e.length)?si(e,0,-1):[]},Br.intersection=Ks,Br.intersectionBy=Js,Br.intersectionWith=Qs,Br.invert=Aa,Br.invertBy=Oa,Br.invokeMap=Co,Br.iteratee=ac,Br.keyBy=To,Br.keys=Na,Br.keysIn=La,Br.map=Po,Br.mapKeys=function(e,t){var r={};return t=us(t,3),wn(e,(function(e,n,i){an(r,t(e,n,i),e)})),r},Br.mapValues=function(e,t){var r={};return t=us(t,3),wn(e,(function(e,n,i){an(r,n,t(e,n,i))})),r},Br.matches=function(e){return Wn(un(e,1))},Br.matchesProperty=function(e,t){return Hn(e,un(t,1))},Br.memoize=Fo,Br.merge=xa,Br.mergeWith=Fa,Br.method=cc,Br.methodOf=dc,Br.mixin=uc,Br.negate=jo,Br.nthArg=function(e){return e=va(e),Zn((function(t){return zn(t,e)}))},Br.omit=ja,Br.omitBy=function(e,t){return Va(e,jo(us(t)))},Br.once=function(e){return Ao(2,e)},Br.orderBy=function(e,t,n,i){return null==e?[]:(Yo(t)||(t=null==t?[]:[t]),Yo(n=i?r:n)||(n=null==n?[]:[n]),Gn(e,t,n))},Br.over=pc,Br.overArgs=Uo,Br.overEvery=hc,Br.overSome=fc,Br.partial=Vo,Br.partialRight=Bo,Br.partition=Ro,Br.pick=Ua,Br.pickBy=Va,Br.property=mc,Br.propertyOf=function(e){return function(t){return null==e?r:Tn(e,t)}},Br.pull=Xs,Br.pullAll=eo,Br.pullAllBy=function(e,t,r){return e&&e.length&&t&&t.length?$n(e,t,us(r,2)):e},Br.pullAllWith=function(e,t,n){return e&&e.length&&t&&t.length?$n(e,t,r,n):e},Br.pullAt=to,Br.range=gc,Br.rangeRight=vc,Br.rearg=Wo,Br.reject=function(e,t){return(Yo(e)?Dt:yn)(e,jo(us(t,3)))},Br.remove=function(e,t){var r=[];if(!e||!e.length)return r;var n=-1,i=[],s=e.length;for(t=us(t,3);++n<s;){var o=e[n];t(o,n,e)&&(r.push(o),i.push(n))}return Kn(e,i),r},Br.rest=function(e,t){if("function"!=typeof e)throw new Ie(n);return Zn(e,t=t===r?t:va(t))},Br.reverse=ro,Br.sampleSize=function(e,t,n){return t=(n?Es(e,t,n):t===r)?1:va(t),(Yo(e)?Xr:ei)(e,t)},Br.set=function(e,t,r){return null==e?e:ti(e,t,r)},Br.setWith=function(e,t,n,i){return i="function"==typeof i?i:r,null==e?e:ti(e,t,n,i)},Br.shuffle=function(e){return(Yo(e)?en:ii)(e)},Br.slice=function(e,t,n){var i=null==e?0:e.length;return i?(n&&"number"!=typeof n&&Es(e,t,n)?(t=0,n=i):(t=null==t?0:va(t),n=n===r?i:va(n)),si(e,t,n)):[]},Br.sortBy=ko,Br.sortedUniq=function(e){return e&&e.length?di(e):[]},Br.sortedUniqBy=function(e,t){return e&&e.length?di(e,us(t,2)):[]},Br.split=function(e,t,n){return n&&"number"!=typeof n&&Es(e,t,n)&&(t=n=r),(n=n===r?m:n>>>0)?(e=Ea(e))&&("string"==typeof t||null!=t&&!ca(t))&&!(t=li(t))&&sr(e)?Si(pr(e),0,n):e.split(t,n):[]},Br.spread=function(e,t){if("function"!=typeof e)throw new Ie(n);return t=null==t?0:br(va(t),0),Zn((function(r){var n=r[t],i=Si(r,0,t);return n&&Mt(i,n),Ct(e,this,i)}))},Br.tail=function(e){var t=null==e?0:e.length;return t?si(e,1,t):[]},Br.take=function(e,t,n){return e&&e.length?si(e,0,(t=n||t===r?1:va(t))<0?0:t):[]},Br.takeRight=function(e,t,n){var i=null==e?0:e.length;return i?si(e,(t=i-(t=n||t===r?1:va(t)))<0?0:t,i):[]},Br.takeRightWhile=function(e,t){return e&&e.length?mi(e,us(t,3),!1,!0):[]},Br.takeWhile=function(e,t){return e&&e.length?mi(e,us(t,3)):[]},Br.tap=function(e,t){return t(e),e},Br.throttle=function(e,t,r){var i=!0,s=!0;if("function"!=typeof e)throw new Ie(n);return na(r)&&(i="leading"in r?!!r.leading:i,s="trailing"in r?!!r.trailing:s),No(e,t,{leading:i,maxWait:t,trailing:s})},Br.thru=go,Br.toArray=ma,Br.toPairs=Ba,Br.toPairsIn=Wa,Br.toPath=function(e){return Yo(e)?Ot(e,Us):la(e)?[e]:Ai(js(Ea(e)))},Br.toPlainObject=_a,Br.transform=function(e,t,r){var n=Yo(e),i=n||Qo(e)||pa(e);if(t=us(t,4),null==r){var s=e&&e.constructor;r=i?n?new s:[]:na(e)&&ea(s)?Wr(Ye(e)):{}}return(i?Pt:wn)(e,(function(e,n,i){return t(r,e,n,i)})),r},Br.unary=function(e){return Io(e,1)},Br.union=no,Br.unionBy=io,Br.unionWith=so,Br.uniq=function(e){return e&&e.length?pi(e):[]},Br.uniqBy=function(e,t){return e&&e.length?pi(e,us(t,2)):[]},Br.uniqWith=function(e,t){return t="function"==typeof t?t:r,e&&e.length?pi(e,r,t):[]},Br.unset=function(e,t){return null==e||hi(e,t)},Br.unzip=oo,Br.unzipWith=ao,Br.update=function(e,t,r){return null==e?e:fi(e,t,_i(r))},Br.updateWith=function(e,t,n,i){return i="function"==typeof i?i:r,null==e?e:fi(e,t,_i(n),i)},Br.values=Ha,Br.valuesIn=function(e){return null==e?[]:Qt(e,La(e))},Br.without=co,Br.words=ec,Br.wrap=function(e,t){return Vo(_i(t),e)},Br.xor=uo,Br.xorBy=lo,Br.xorWith=po,Br.zip=ho,Br.zipObject=function(e,t){return yi(e||[],t||[],rn)},Br.zipObjectDeep=function(e,t){return yi(e||[],t||[],ti)},Br.zipWith=fo,Br.entries=Ba,Br.entriesIn=Wa,Br.extend=Sa,Br.extendWith=Ca,uc(Br,Br),Br.add=_c,Br.attempt=tc,Br.camelCase=qa,Br.capitalize=za,Br.ceil=Ec,Br.clamp=function(e,t,n){return n===r&&(n=t,t=r),n!==r&&(n=(n=ba(n))==n?n:0),t!==r&&(t=(t=ba(t))==t?t:0),dn(ba(e),t,n)},Br.clone=function(e){return un(e,4)},Br.cloneDeep=function(e){return un(e,5)},Br.cloneDeepWith=function(e,t){return un(e,5,t="function"==typeof t?t:r)},Br.cloneWith=function(e,t){return un(e,4,t="function"==typeof t?t:r)},Br.conformsTo=function(e,t){return null==t||ln(e,t,Na(t))},Br.deburr=Ga,Br.defaultTo=function(e,t){return null==e||e!=e?t:e},Br.divide=wc,Br.endsWith=function(e,t,n){e=Ea(e),t=li(t);var i=e.length,s=n=n===r?i:dn(va(n),0,i);return(n-=t.length)>=0&&e.slice(n,s)==t},Br.eq=Ho,Br.escape=function(e){return(e=Ea(e))&&J.test(e)?e.replace($,nr):e},Br.escapeRegExp=function(e){return(e=Ea(e))&&ie.test(e)?e.replace(ne,"\\$&"):e},Br.every=function(e,t,n){var i=Yo(e)?kt:gn;return n&&Es(e,t,n)&&(t=r),i(e,us(t,3))},Br.find=bo,Br.findIndex=zs,Br.findKey=function(e,t){return jt(e,us(t,3),wn)},Br.findLast=_o,Br.findLastIndex=Gs,Br.findLastKey=function(e,t){return jt(e,us(t,3),Sn)},Br.floor=Sc,Br.forEach=Eo,Br.forEachRight=wo,Br.forIn=function(e,t){return null==e?e:_n(e,us(t,3),La)},Br.forInRight=function(e,t){return null==e?e:En(e,us(t,3),La)},Br.forOwn=function(e,t){return e&&wn(e,us(t,3))},Br.forOwnRight=function(e,t){return e&&Sn(e,us(t,3))},Br.get=Da,Br.gt=qo,Br.gte=zo,Br.has=function(e,t){return null!=e&&vs(e,t,Dn)},Br.hasIn=Ia,Br.head=$s,Br.identity=oc,Br.includes=function(e,t,r,n){e=Ko(e)?e:Ha(e),r=r&&!n?va(r):0;var i=e.length;return r<0&&(r=br(i+r,0)),ua(e)?r<=i&&e.indexOf(t,r)>-1:!!i&&Vt(e,t,r)>-1},Br.indexOf=function(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var i=null==r?0:va(r);return i<0&&(i=br(n+i,0)),Vt(e,t,i)},Br.inRange=function(e,t,n){return t=ga(t),n===r?(n=t,t=0):n=ga(n),function(e,t,r){return e>=_r(t,r)&&e<br(t,r)}(e=ba(e),t,n)},Br.invoke=Ma,Br.isArguments=Go,Br.isArray=Yo,Br.isArrayBuffer=$o,Br.isArrayLike=Ko,Br.isArrayLikeObject=Jo,Br.isBoolean=function(e){return!0===e||!1===e||ia(e)&&Rn(e)==b},Br.isBuffer=Qo,Br.isDate=Zo,Br.isElement=function(e){return ia(e)&&1===e.nodeType&&!aa(e)},Br.isEmpty=function(e){if(null==e)return!0;if(Ko(e)&&(Yo(e)||"string"==typeof e||"function"==typeof e.splice||Qo(e)||pa(e)||Go(e)))return!e.length;var t=gs(e);if(t==C||t==D)return!e.size;if(Ts(e))return!jn(e).length;for(var r in e)if(xe.call(e,r))return!1;return!0},Br.isEqual=function(e,t){return Nn(e,t)},Br.isEqualWith=function(e,t,n){var i=(n="function"==typeof n?n:r)?n(e,t):r;return i===r?Nn(e,t,r,n):!!i},Br.isError=Xo,Br.isFinite=function(e){return"number"==typeof e&&gr(e)},Br.isFunction=ea,Br.isInteger=ta,Br.isLength=ra,Br.isMap=sa,Br.isMatch=function(e,t){return e===t||Ln(e,t,ps(t))},Br.isMatchWith=function(e,t,n){return n="function"==typeof n?n:r,Ln(e,t,ps(t),n)},Br.isNaN=function(e){return oa(e)&&e!=+e},Br.isNative=function(e){if(Cs(e))throw new Ce("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");return xn(e)},Br.isNil=function(e){return null==e},Br.isNull=function(e){return null===e},Br.isNumber=oa,Br.isObject=na,Br.isObjectLike=ia,Br.isPlainObject=aa,Br.isRegExp=ca,Br.isSafeInteger=function(e){return ta(e)&&e>=-9007199254740991&&e<=h},Br.isSet=da,Br.isString=ua,Br.isSymbol=la,Br.isTypedArray=pa,Br.isUndefined=function(e){return e===r},Br.isWeakMap=function(e){return ia(e)&&gs(e)==O},Br.isWeakSet=function(e){return ia(e)&&"[object WeakSet]"==Rn(e)},Br.join=function(e,t){return null==e?"":vr.call(e,t)},Br.kebabCase=Ya,Br.last=Zs,Br.lastIndexOf=function(e,t,n){var i=null==e?0:e.length;if(!i)return-1;var s=i;return n!==r&&(s=(s=va(n))<0?br(i+s,0):_r(s,i-1)),t==t?function(e,t,r){for(var n=r+1;n--;)if(e[n]===t)return n;return n}(e,t,s):Ut(e,Wt,s,!0)},Br.lowerCase=$a,Br.lowerFirst=Ka,Br.lt=ha,Br.lte=fa,Br.max=function(e){return e&&e.length?vn(e,oc,kn):r},Br.maxBy=function(e,t){return e&&e.length?vn(e,us(t,2),kn):r},Br.mean=function(e){return Ht(e,oc)},Br.meanBy=function(e,t){return Ht(e,us(t,2))},Br.min=function(e){return e&&e.length?vn(e,oc,Vn):r},Br.minBy=function(e,t){return e&&e.length?vn(e,us(t,2),Vn):r},Br.stubArray=yc,Br.stubFalse=bc,Br.stubObject=function(){return{}},Br.stubString=function(){return""},Br.stubTrue=function(){return!0},Br.multiply=Tc,Br.nth=function(e,t){return e&&e.length?zn(e,va(t)):r},Br.noConflict=function(){return pt._===this&&(pt._=Be),this},Br.noop=lc,Br.now=Do,Br.pad=function(e,t,r){e=Ea(e);var n=(t=va(t))?lr(e):0;if(!t||n>=t)return e;var i=(t-n)/2;return Gi(vt(i),r)+e+Gi(gt(i),r)},Br.padEnd=function(e,t,r){e=Ea(e);var n=(t=va(t))?lr(e):0;return t&&n<t?e+Gi(t-n,r):e},Br.padStart=function(e,t,r){e=Ea(e);var n=(t=va(t))?lr(e):0;return t&&n<t?Gi(t-n,r)+e:e},Br.parseInt=function(e,t,r){return r||null==t?t=0:t&&(t=+t),wr(Ea(e).replace(se,""),t||0)},Br.random=function(e,t,n){if(n&&"boolean"!=typeof n&&Es(e,t,n)&&(t=n=r),n===r&&("boolean"==typeof t?(n=t,t=r):"boolean"==typeof e&&(n=e,e=r)),e===r&&t===r?(e=0,t=1):(e=ga(e),t===r?(t=e,e=0):t=ga(t)),e>t){var i=e;e=t,t=i}if(n||e%1||t%1){var s=Sr();return _r(e+s*(t-e+ct("1e-"+((s+"").length-1))),t)}return Jn(e,t)},Br.reduce=function(e,t,r){var n=Yo(e)?Nt:Gt,i=arguments.length<3;return n(e,us(t,4),r,i,fn)},Br.reduceRight=function(e,t,r){var n=Yo(e)?Lt:Gt,i=arguments.length<3;return n(e,us(t,4),r,i,mn)},Br.repeat=function(e,t,n){return t=(n?Es(e,t,n):t===r)?1:va(t),Qn(Ea(e),t)},Br.replace=function(){var e=arguments,t=Ea(e[0]);return e.length<3?t:t.replace(e[1],e[2])},Br.result=function(e,t,n){var i=-1,s=(t=Ei(t,e)).length;for(s||(s=1,e=r);++i<s;){var o=null==e?r:e[Us(t[i])];o===r&&(i=s,o=n),e=ea(o)?o.call(e):o}return e},Br.round=Pc,Br.runInContext=e,Br.sample=function(e){return(Yo(e)?Zr:Xn)(e)},Br.size=function(e){if(null==e)return 0;if(Ko(e))return ua(e)?lr(e):e.length;var t=gs(e);return t==C||t==D?e.size:jn(e).length},Br.snakeCase=Ja,Br.some=function(e,t,n){var i=Yo(e)?xt:oi;return n&&Es(e,t,n)&&(t=r),i(e,us(t,3))},Br.sortedIndex=function(e,t){return ai(e,t)},Br.sortedIndexBy=function(e,t,r){return ci(e,t,us(r,2))},Br.sortedIndexOf=function(e,t){var r=null==e?0:e.length;if(r){var n=ai(e,t);if(n<r&&Ho(e[n],t))return n}return-1},Br.sortedLastIndex=function(e,t){return ai(e,t,!0)},Br.sortedLastIndexBy=function(e,t,r){return ci(e,t,us(r,2),!0)},Br.sortedLastIndexOf=function(e,t){if(null==e?0:e.length){var r=ai(e,t,!0)-1;if(Ho(e[r],t))return r}return-1},Br.startCase=Qa,Br.startsWith=function(e,t,r){return e=Ea(e),r=null==r?0:dn(va(r),0,e.length),t=li(t),e.slice(r,r+t.length)==t},Br.subtract=Rc,Br.sum=function(e){return e&&e.length?Yt(e,oc):0},Br.sumBy=function(e,t){return e&&e.length?Yt(e,us(t,2)):0},Br.template=function(e,t,n){var i=Br.templateSettings;n&&Es(e,t,n)&&(t=r),e=Ea(e),t=Ca({},t,i,es);var s,o,a=Ca({},t.imports,i.imports,es),c=Na(a),d=Qt(a,c),u=0,l=t.interpolate||Ee,p="__p += '",h=ke((t.escape||Ee).source+"|"+l.source+"|"+(l===X?he:Ee).source+"|"+(t.evaluate||Ee).source+"|$","g"),f="//# sourceURL="+(xe.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++it+"]")+"\n";e.replace(h,(function(t,r,n,i,a,c){return n||(n=i),p+=e.slice(u,c).replace(we,ir),r&&(s=!0,p+="' +\n__e("+r+") +\n'"),a&&(o=!0,p+="';\n"+a+";\n__p += '"),n&&(p+="' +\n((__t = ("+n+")) == null ? '' : __t) +\n'"),u=c+t.length,t})),p+="';\n";var m=xe.call(t,"variable")&&t.variable;if(m){if(le.test(m))throw new Ce("Invalid `variable` option passed into `_.template`")}else p="with (obj) {\n"+p+"\n}\n";p=(o?p.replace(q,""):p).replace(z,"$1").replace(G,"$1;"),p="function("+(m||"obj")+") {\n"+(m?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(s?", __e = _.escape":"")+(o?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+p+"return __p\n}";var g=tc((function(){return Te(c,f+"return "+p).apply(r,d)}));if(g.source=p,Xo(g))throw g;return g},Br.times=function(e,t){if((e=va(e))<1||e>h)return[];var r=m,n=_r(e,m);t=us(t),e-=m;for(var i=$t(n,t);++r<e;)t(r);return i},Br.toFinite=ga,Br.toInteger=va,Br.toLength=ya,Br.toLower=function(e){return Ea(e).toLowerCase()},Br.toNumber=ba,Br.toSafeInteger=function(e){return e?dn(va(e),-9007199254740991,h):0===e?e:0},Br.toString=Ea,Br.toUpper=function(e){return Ea(e).toUpperCase()},Br.trim=function(e,t,n){if((e=Ea(e))&&(n||t===r))return Kt(e);if(!e||!(t=li(t)))return e;var i=pr(e),s=pr(t);return Si(i,Xt(i,s),er(i,s)+1).join("")},Br.trimEnd=function(e,t,n){if((e=Ea(e))&&(n||t===r))return e.slice(0,hr(e)+1);if(!e||!(t=li(t)))return e;var i=pr(e);return Si(i,0,er(i,pr(t))+1).join("")},Br.trimStart=function(e,t,n){if((e=Ea(e))&&(n||t===r))return e.replace(se,"");if(!e||!(t=li(t)))return e;var i=pr(e);return Si(i,Xt(i,pr(t))).join("")},Br.truncate=function(e,t){var n=30,i="...";if(na(t)){var s="separator"in t?t.separator:s;n="length"in t?va(t.length):n,i="omission"in t?li(t.omission):i}var o=(e=Ea(e)).length;if(sr(e)){var a=pr(e);o=a.length}if(n>=o)return e;var c=n-lr(i);if(c<1)return i;var d=a?Si(a,0,c).join(""):e.slice(0,c);if(s===r)return d+i;if(a&&(c+=d.length-c),ca(s)){if(e.slice(c).search(s)){var u,l=d;for(s.global||(s=ke(s.source,Ea(fe.exec(s))+"g")),s.lastIndex=0;u=s.exec(l);)var p=u.index;d=d.slice(0,p===r?c:p)}}else if(e.indexOf(li(s),c)!=c){var h=d.lastIndexOf(s);h>-1&&(d=d.slice(0,h))}return d+i},Br.unescape=function(e){return(e=Ea(e))&&K.test(e)?e.replace(Y,fr):e},Br.uniqueId=function(e){var t=++Fe;return Ea(e)+t},Br.upperCase=Za,Br.upperFirst=Xa,Br.each=Eo,Br.eachRight=wo,Br.first=$s,uc(Br,(Cc={},wn(Br,(function(e,t){xe.call(Br.prototype,t)||(Cc[t]=e)})),Cc),{chain:!1}),Br.VERSION="4.17.21",Pt(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(e){Br[e].placeholder=Br})),Pt(["drop","take"],(function(e,t){zr.prototype[e]=function(n){n=n===r?1:br(va(n),0);var i=this.__filtered__&&!t?new zr(this):this.clone();return i.__filtered__?i.__takeCount__=_r(n,i.__takeCount__):i.__views__.push({size:_r(n,m),type:e+(i.__dir__<0?"Right":"")}),i},zr.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),Pt(["filter","map","takeWhile"],(function(e,t){var r=t+1,n=1==r||3==r;zr.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:us(e,3),type:r}),t.__filtered__=t.__filtered__||n,t}})),Pt(["head","last"],(function(e,t){var r="take"+(t?"Right":"");zr.prototype[e]=function(){return this[r](1).value()[0]}})),Pt(["initial","tail"],(function(e,t){var r="drop"+(t?"":"Right");zr.prototype[e]=function(){return this.__filtered__?new zr(this):this[r](1)}})),zr.prototype.compact=function(){return this.filter(oc)},zr.prototype.find=function(e){return this.filter(e).head()},zr.prototype.findLast=function(e){return this.reverse().find(e)},zr.prototype.invokeMap=Zn((function(e,t){return"function"==typeof e?new zr(this):this.map((function(r){return On(r,e,t)}))})),zr.prototype.reject=function(e){return this.filter(jo(us(e)))},zr.prototype.slice=function(e,t){e=va(e);var n=this;return n.__filtered__&&(e>0||t<0)?new zr(n):(e<0?n=n.takeRight(-e):e&&(n=n.drop(e)),t!==r&&(n=(t=va(t))<0?n.dropRight(-t):n.take(t-e)),n)},zr.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},zr.prototype.toArray=function(){return this.take(m)},wn(zr.prototype,(function(e,t){var n=/^(?:filter|find|map|reject)|While$/.test(t),i=/^(?:head|last)$/.test(t),s=Br[i?"take"+("last"==t?"Right":""):t],o=i||/^find/.test(t);s&&(Br.prototype[t]=function(){var t=this.__wrapped__,a=i?[1]:arguments,c=t instanceof zr,d=a[0],u=c||Yo(t),l=function(e){var t=s.apply(Br,Mt([e],a));return i&&p?t[0]:t};u&&n&&"function"==typeof d&&1!=d.length&&(c=u=!1);var p=this.__chain__,h=!!this.__actions__.length,f=o&&!p,m=c&&!h;if(!o&&u){t=m?t:new zr(this);var g=e.apply(t,a);return g.__actions__.push({func:go,args:[l],thisArg:r}),new qr(g,p)}return f&&m?e.apply(this,a):(g=this.thru(l),f?i?g.value()[0]:g.value():g)})})),Pt(["pop","push","shift","sort","splice","unshift"],(function(e){var t=Ae[e],r=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",n=/^(?:pop|shift)$/.test(e);Br.prototype[e]=function(){var e=arguments;if(n&&!this.__chain__){var i=this.value();return t.apply(Yo(i)?i:[],e)}return this[r]((function(r){return t.apply(Yo(r)?r:[],e)}))}})),wn(zr.prototype,(function(e,t){var r=Br[t];if(r){var n=r.name+"";xe.call(Or,n)||(Or[n]=[]),Or[n].push({name:t,func:r})}})),Or[Wi(r,2).name]=[{name:"wrapper",func:r}],zr.prototype.clone=function(){var e=new zr(this.__wrapped__);return e.__actions__=Ai(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=Ai(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=Ai(this.__views__),e},zr.prototype.reverse=function(){if(this.__filtered__){var e=new zr(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},zr.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,r=Yo(e),n=t<0,i=r?e.length:0,s=function(e,t,r){var n=-1,i=r.length;for(;++n<i;){var s=r[n],o=s.size;switch(s.type){case"drop":e+=o;break;case"dropRight":t-=o;break;case"take":t=_r(t,e+o);break;case"takeRight":e=br(e,t-o)}}return{start:e,end:t}}(0,i,this.__views__),o=s.start,a=s.end,c=a-o,d=n?a:o-1,u=this.__iteratees__,l=u.length,p=0,h=_r(c,this.__takeCount__);if(!r||!n&&i==c&&h==c)return gi(e,this.__actions__);var f=[];e:for(;c--&&p<h;){for(var m=-1,g=e[d+=t];++m<l;){var v=u[m],y=v.iteratee,b=v.type,_=y(g);if(2==b)g=_;else if(!_){if(1==b)continue e;break e}}f[p++]=g}return f},Br.prototype.at=vo,Br.prototype.chain=function(){return mo(this)},Br.prototype.commit=function(){return new qr(this.value(),this.__chain__)},Br.prototype.next=function(){this.__values__===r&&(this.__values__=ma(this.value()));var e=this.__index__>=this.__values__.length;return{done:e,value:e?r:this.__values__[this.__index__++]}},Br.prototype.plant=function(e){for(var t,n=this;n instanceof Hr;){var i=Bs(n);i.__index__=0,i.__values__=r,t?s.__wrapped__=i:t=i;var s=i;n=n.__wrapped__}return s.__wrapped__=e,t},Br.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof zr){var t=e;return this.__actions__.length&&(t=new zr(this)),(t=t.reverse()).__actions__.push({func:go,args:[ro],thisArg:r}),new qr(t,this.__chain__)}return this.thru(ro)},Br.prototype.toJSON=Br.prototype.valueOf=Br.prototype.value=function(){return gi(this.__wrapped__,this.__actions__)},Br.prototype.first=Br.prototype.head,tt&&(Br.prototype[tt]=function(){return this}),Br}();ft?((ft.exports=mr)._=mr,ht._=mr):pt._=mr}).call(u)}(W_,W_.exports);var H_,q_=u&&u.__extends||(H_=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},function(e,t){function r(){this.constructor=e}H_(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(B_,"__esModule",{value:!0});var z_=t.default,G_=W_.exports,Y_=["MaxBatchSize","MaxDelay","MinDelay"],$_=function(e){function t(t){var r=e.call(this)||this;return r.fifo=[],r.firstBatch=!0,function(e){if(Y_.forEach((function(t){if(!e.hasOwnProperty(t))throw new Error("Missing required MessageBatcher option: "+t)})),isNaN(e.MaxBatchSize))throw new Error("MessageBatcher MaxBatchSize option must be a number");if(!isFinite(e.MaxBatchSize))throw new Error("MessageBatcher MaxBatchSize option must be a finite number");if(e.MaxBatchSize<1)throw new Error("MessageBatcher MaxBatchSize option cannot be less than 1");if(isNaN(e.MaxDelay))throw new Error("MessageBatcher MaxDelay option must be a number");if(!isFinite(e.MaxDelay))throw new Error("MessageBatcher MaxDelay option must be a finite number");if(e.MaxDelay<0)throw new Error("MessageBatcher MaxDelay option cannot be less than 0");if(isNaN(e.MinDelay))throw new Error("MessageBatcher MinDelay option must be a number");if(!isFinite(e.MinDelay))throw new Error("MessageBatcher MinDelay option must be a finite number");if(e.MinDelay<0)throw new Error("MessageBatcher MinDelay option cannot be less than 0");if(e.MinDelay>e.MaxDelay)throw new Error("MessageBatcher MinDelay option cannot be greater than MaxDelay")}(t),r.options=t,r.releaseBatchDebouncedMax=G_.debounce(r.releaseBatch.bind(r),r.options.MaxDelay,{maxWait:r.options.MaxDelay}),r.releaseBatchDebouncedMin=G_.debounce(r.releaseBatch.bind(r),r.options.MinDelay,{maxWait:r.options.MinDelay}),r}return q_(t,e),t.prototype.Queue=function(e){var t=this;(e=[].concat(e)).forEach((function(e){t.fifo.push(e),t.debounce(t.fifo,t.options.MaxBatchSize)}),this)},t.prototype.debounce=function(e,t){e.length>0&&(e.length>=t?this.firstBatch?(this.firstBatch=!1,this.releaseBatchDebouncedMax.flush()):(this.releaseBatchDebouncedMax.cancel(),this.releaseBatchDebouncedMin(e,t)):(this.releaseBatchDebouncedMin.cancel(),this.releaseBatchDebouncedMax(e,t)))},t.prototype.releaseBatch=function(e,t){var r=this.drainFIFO(e,t);r&&r.length&&(this.emit("batch",r),this.debounce(e,t))},t.prototype.drainFIFO=function(e,t){return e.length>0?e.splice(0,t):e},t}(z_.EventEmitter);B_.MessageBatcher=$_,function(e){Object.defineProperty(e,"__esModule",{value:!0}),function(t){for(var r in t)e.hasOwnProperty(r)||(e[r]=t[r])}(B_)}(V_),function(e){Object.defineProperty(e,"__esModule",{value:!0}),function(t){for(var r in t)e.hasOwnProperty(r)||(e[r]=t[r])}(V_)}(U_);var K_={exports:{}},J_=1e3,Q_=60*J_,Z_=60*Q_,X_=24*Z_,eE=7*X_,tE=365.25*X_,rE=function(e,t){t=t||{};var r=typeof e;if("string"===r&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*tE;case"weeks":case"week":case"w":return r*eE;case"days":case"day":case"d":return r*X_;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Z_;case"minutes":case"minute":case"mins":case"min":case"m":return r*Q_;case"seconds":case"second":case"secs":case"sec":case"s":return r*J_;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(e);if("number"===r&&isFinite(e))return t.long?function(e){var t=Math.abs(e);if(t>=X_)return nE(e,t,X_,"day");if(t>=Z_)return nE(e,t,Z_,"hour");if(t>=Q_)return nE(e,t,Q_,"minute");if(t>=J_)return nE(e,t,J_,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=X_)return Math.round(e/X_)+"d";if(t>=Z_)return Math.round(e/Z_)+"h";if(t>=Q_)return Math.round(e/Q_)+"m";if(t>=J_)return Math.round(e/J_)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function nE(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}var iE=function(e){function t(e){let n,i,s,o=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,i)=>{if("%%"===n)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];n=s.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r<i;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=rE,t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=iE(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(K_,K_.exports);var sE,oE,aE,cE,dE,uE,lE,pE,hE=K_.exports;class fE{constructor(e){sE.add(this),oE.set(this,void 0),aE.set(this,void 0),cE.set(this,void 0),dE.set(this,void 0);const{logLevel:t,namespace:r,onLogMessage:n}=e;c(this,oE,r,"f"),c(this,aE,t,"f"),this.onLogMessage=n,c(this,cE,e.logToRemoteBatcher,"f"),c(this,dE,e.sendAnalytics,"f"),this._debug=hE("LiveDigital").extend("debug").extend(a(this,oE,"f")),this._info=hE("LiveDigital").extend("info").extend(a(this,oE,"f")),this._warn=hE("LiveDigital").extend("warn").extend(a(this,oE,"f")),this._error=hE("LiveDigital").extend("error").extend(a(this,oE,"f")),this._debug.log=console.info.bind(console),this._info.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}debug(e,t){this._debug(e,t),a(this,aE,"f")<pt||(a(this,dE,"f")&&a(this,cE,"f").Queue(a(this,sE,"m",lE).call(this,{level:"debug",message:e,meta:a(this,sE,"m",pE).call(this,t)})),a(this,sE,"m",uE).call(this,"debug",e,t))}info(e,t){this._info(e,t),a(this,aE,"f")<lt||(a(this,dE,"f")&&a(this,cE,"f").Queue(a(this,sE,"m",lE).call(this,{level:"info",message:e,meta:a(this,sE,"m",pE).call(this,t)})),a(this,sE,"m",uE).call(this,"info",e,t))}warn(e,t){this._warn(e,t),a(this,aE,"f")<ut||(a(this,dE,"f")&&a(this,cE,"f").Queue(a(this,sE,"m",lE).call(this,{level:"warn",message:e,meta:a(this,sE,"m",pE).call(this,t)})),a(this,sE,"m",uE).call(this,"warn",e,t))}error(e,t){this._error(e,t),a(this,aE,"f")<dt||(a(this,dE,"f")&&a(this,cE,"f").Queue(a(this,sE,"m",lE).call(this,{level:"error",message:e,meta:a(this,sE,"m",pE).call(this,t)})),a(this,sE,"m",uE).call(this,"error",e,t))}}var mE,gE,vE;oE=new WeakMap,aE=new WeakMap,cE=new WeakMap,dE=new WeakMap,sE=new WeakSet,uE=function(e,t,...r){"function"==typeof this.onLogMessage&&this.onLogMessage(t,...a(this,sE,"m",lE).call(this,r),e)},lE=function(e){const t=new WeakMap;return function e(r,n=[]){if(!ri(r))return r;const i=t.get(r);if(i)return`[Circular *${i.join(".")}]`;t.set(r,n);const s=Array.isArray(r)?[]:{};return Object.entries(r).forEach((([t,r])=>{s[t]=e(r,[...n,t])})),t.delete(r),s}(e)},pE=function(e){const t=null!=e?e:{},{error:r}=t;return Object.assign(Object.assign(Object.assign(Object.assign({},t),{clientTimestamp:(new Date).toISOString(),from_sdk:!0,sdkVersion:ft}),r&&"object"==typeof r?{error:Vt(r)}:{}),{namespace:a(this,oE,"f")})};let yE=class{constructor(e,t,r,n,i){this.state=e,this.myPeer=r,this.signalingApiClient=n,this.channelAudioObserverEventHandler=i,mE.set(this,void 0),gE.set(this,void 0),vE.set(this,void 0),c(this,mE,t("DataChannels"),"f")}get channelMessagesDataConsumer(){return a(this,vE,"f")}createAudioObserver(e){return o(this,void 0,void 0,(function*(){var t;const r={channelId:this.state.channelId,appId:this.state.appId,peerId:null===(t=this.myPeer)||void 0===t?void 0:t.id};try{const{producerId:t}=yield this.getAudioObserverProducer();c(this,gE,yield this.createDataConsumer({producerId:t,appId:this.state.appId,channelId:this.state.channelId,transport:e}),"f")}catch(e){if(e instanceof Bt)throw e;return void a(this,mE,"f").error("Failed to create audio observer",Object.assign(Object.assign({},r),{error:Vt(e)}))}const n=this.channelAudioObserverEventHandler.handle.bind(this.channelAudioObserverEventHandler),i=()=>{var e,t;null===(e=a(this,gE,"f"))||void 0===e||e.removeListener("message",n),null===(t=a(this,gE,"f"))||void 0===t||t.removeListener("close",i)};a(this,gE,"f").on("close",i),a(this,gE,"f").on("message",n),a(this,mE,"f").debug("Successfully create audio observer",r)}))}createChannelMessagesDataConsumer(e){return o(this,void 0,void 0,(function*(){var t;const r={channelId:this.state.channelId,appId:this.state.appId,peerId:null===(t=this.myPeer)||void 0===t?void 0:t.id};try{const{id:t}=yield this.createDataProducer(e.id,"channel-messages-data-producer");c(this,vE,yield this.createDataConsumer({producerId:t,appId:this.state.appId,channelId:this.state.channelId,ordered:!0,transport:e}),"f"),a(this,mE,"f").debug("Successfully created channel messages data consumer",Object.assign(Object.assign({},r),{producerId:t}))}catch(e){throw a(this,mE,"f").error("Failed to create channel messages data consumer",Object.assign(Object.assign({},r),{error:e})),e}}))}closeAudioObserver(){var e;null===(e=a(this,gE,"f"))||void 0===e||e.close()}closeChannelMessagesDataConsumer(){var e;null===(e=a(this,vE,"f"))||void 0===e||e.close()}createDataProducer(e,t){return o(this,void 0,void 0,(function*(){const{data:r}=yield this.signalingApiClient.transport.produceDataToTransport(e,{label:t});return r}))}createDataConsumer(e){return o(this,arguments,void 0,(function*({producerId:e,appId:t,channelId:r,ordered:n,transport:i}){if(!i)throw a(this,mE,"f").error("createDataConsumer()",{reason:"missing receive transport"}),new Bt("create_data_consumer_failed",new Error("Missing receive transport"));a(this,mE,"f").debug("createDataConsumer()",{producerId:e});const s=(yield this.signalingApiClient.dataConsumer.createDataConsumer({ordered:n,dataProducerId:e,transportId:i.id,appData:{peerId:this.myPeer.id,producerId:e,appId:t,channelId:r}})).data;try{const e=yield i.consumeData(s);return a(this,mE,"f").debug("Data consumer created",{consumerId:e.id}),e}catch(e){throw new Bt("transport_consume_data_failed",e)}}))}getAudioObserverProducer(){return o(this,void 0,void 0,(function*(){const{data:e}=yield this.signalingApiClient.producer.getAudioObserverProducer();return e}))}};mE=new WeakMap,gE=new WeakMap,vE=new WeakMap,yE=n([ot(),i(0,ct(mi.CallState)),i(1,ct(mi.LoggerFactory)),i(2,ct(mi.MyPeer)),i(3,ct(mi.SignalingApiClient)),i(4,ct(mi.ChannelAudioObserverEventHandler)),s("design:paramtypes",[gi,Function,io,rd,j_])],yE);var bE,_E,EE,wE,SE,CE,TE=yE;let PE=class{constructor(e){bE.set(this,void 0),_E.set(this,void 0),EE.set(this,void 0),wE.set(this,[]),SE.set(this,void 0),CE.set(this,new Uint8Array(0)),c(this,SE,e("DatachannelHeartbeater"),"f")}init(e,t){c(this,EE,e,"f"),c(this,_E,t,"f"),this.subscribeToDataProducerEvents(t),this.startHeartbeatInterval()}dispose(){this.stopHeartbeatInterval(),this.cleanupDataProducerEvents(),c(this,_E,void 0,"f"),c(this,EE,void 0,"f")}startHeartbeatInterval(){a(this,bE,"f")||(c(this,bE,setInterval((()=>{this.sendHeartbeat()}),5e3),"f"),a(this,SE,"f").debug("Datachannel heartbeat interval started"))}stopHeartbeatInterval(){a(this,bE,"f")&&(clearInterval(a(this,bE,"f")),c(this,bE,void 0,"f"),a(this,SE,"f").debug("Datachannel heartbeat interval stopped"))}canSendHeartbeat(){return!(!a(this,_E,"f")||!a(this,EE,"f"))&&(!a(this,_E,"f").closed&&"connected"===a(this,EE,"f").connectionState&&"open"===a(this,_E,"f").readyState)}subscribeToDataProducerEvents(e){this.cleanupDataProducerEvents();const t=t=>{a(this,SE,"f").debug(`Heartbeat data producer ${t}`,{readyState:e.readyState,closed:e.closed})},r=()=>t("open"),n=()=>t("close"),i=()=>t("transport closed");e.on("open",r),e.on("close",n),e.on("transportclose",i),c(this,wE,[()=>e.off("open",r),()=>e.off("close",n),()=>e.off("transportclose",i)],"f")}cleanupDataProducerEvents(){a(this,wE,"f").forEach((e=>e())),c(this,wE,[],"f")}sendHeartbeat(){if(a(this,_E,"f")&&this.canSendHeartbeat())try{a(this,_E,"f").send(a(this,CE,"f"))}catch(e){a(this,SE,"f").debug("Failed to send datachannel heartbeat",{error:Vt(e)})}}};bE=new WeakMap,_E=new WeakMap,EE=new WeakMap,wE=new WeakMap,SE=new WeakMap,CE=new WeakMap,PE=n([ot(),i(0,ct(mi.LoggerFactory)),s("design:paramtypes",[Function])],PE);var RE,kE,DE=PE;let IE=class{constructor(e,t){this.signalingApiClient=t,RE.set(this,void 0),kE.set(this,void 0),c(this,kE,e("SignalingHeartbeater"),"f")}start(){a(this,RE,"f")||(c(this,RE,setInterval((()=>o(this,void 0,void 0,(function*(){yield this.sendHeartbeat()}))),15e3),"f"),a(this,kE,"f").debug("Signaling heartbeat interval started"))}dispose(){a(this,RE,"f")&&(clearInterval(a(this,RE,"f")),c(this,RE,void 0,"f"),a(this,kE,"f").debug("Signaling heartbeat interval stopped"))}sendHeartbeat(){return o(this,void 0,void 0,(function*(){try{yield this.signalingApiClient.ping.pingPeer()}catch(e){a(this,kE,"f").debug("Failed to send signaling heartbeat",{error:Vt(e)})}}))}};RE=new WeakMap,kE=new WeakMap,IE=n([ot(),i(0,ct(mi.LoggerFactory)),i(1,ct(mi.SignalingApiClient)),s("design:paramtypes",[Function,rd])],IE);var AE=IE;let OE=class{constructor(e){this.peerTrackFactory=e,this.tracksByConsumerId=new Map}register(e,t){this.tracksByConsumerId.set(e,t)}get(e){return this.tracksByConsumerId.get(e)}delete(e){return this.tracksByConsumerId.delete(e)}reset(){this.tracksByConsumerId.clear()}create(e){const{consumer:t,label:r,muted:n=!1,mediaStreamTrack:i,paused:s,peerEventEmitter:o}=e,a=this.peerTrackFactory({consumer:t,label:r,mediaStreamTrack:i,paused:s,peerEventEmitter:o,muted:n,onClose:()=>{void 0!==a.consumerId&&this.delete(a.consumerId)}});return void 0!==a.consumerId&&this.register(a.consumerId,a),a}};var ME,NE,LE;OE=n([ot(),i(0,ct(mi.PeerTrackFactory)),s("design:paramtypes",[Function])],OE);const xE=["frozen-video-track","network-media-sync-failure","encoder-cpu-throttling","decoder-cpu-throttling","missing-video-stream-data","missing-audio-stream-data"];let FE=class{constructor(e,t,r,n,i,s){this.analyticsApiClient=e,this.peers=t,this.myPeer=r,this.transportsStatsProvider=i,this.clientMetaProvider=s,ME.set(this,void 0),NE.set(this,void 0),LE.set(this,void 0),c(this,LE,n("IntegrationsService"),"f"),c(this,NE,new U_.MessageBatcher({MaxBatchSize:50,MaxDelay:6e4,MinDelay:3e4}),"f"),a(this,NE,"f").on("batch",(e=>{this.analyticsApiClient.metrics.sendWIDMetrics({reasons:e,clientMeta:this.getClientMeta()}).catch((e=>{a(this,LE,"f").debug("Failed to sendWIDMetrics",{error:Vt(e)})}))})),c(this,ME,new U_.MessageBatcher({MaxBatchSize:20,MaxDelay:6e4,MinDelay:2e4}),"f"),a(this,ME,"f").on("batch",(e=>{this.analyticsApiClient.metrics.sendNetworkMetrics({metrics:this.getWorstPerDirectionMetric(e),clientMeta:this.getClientMeta()}).catch((e=>{a(this,LE,"f").debug("Failed to sendNetworkMetrics",{error:Vt(e)})}))}))}handleIssues(e){e.forEach((e=>a(this,LE,"f").info("WebRTCIssue",e)));const t=e.filter((e=>xE.includes(e.reason)));0!==t.length&&t.forEach((e=>a(this,NE,"f").Queue(e.reason)))}handleNetworkScores(e){var t,r,n,i,s,o,c,d,u,l,p,h;const{inbound:f,outbound:m,statsSamples:{inboundStatsSample:g,outboundStatsSample:v}}=e,y=this.getNodeActiveStreamsStat(),b=this.transportsStatsProvider.getStats();if(void 0!==f&&g){const e={jitter:Math.round(g.avgJitter),packetLoss:g.packetsLoss,rtt:g.rtt,mos:Math.round(10*f)/10,streams:y.inboundActiveStreams,direction:"inbound",node:null!==(t=this.clientMetaProvider.meta.datacenterName)&&void 0!==t?t:"unknown node",bitrate:null!==(n=null===(r=null==b?void 0:b.inbound)||void 0===r?void 0:r.bitrate)&&void 0!==n?n:0,timestamp:(new Date).toISOString(),Qa:null===(i=null==b?void 0:b.inbound)||void 0===i?void 0:i.Qa,Qv:null===(s=null==b?void 0:b.inbound)||void 0===s?void 0:s.Qv,Qav:null===(o=null==b?void 0:b.inbound)||void 0===o?void 0:o.Qav};a(this,LE,"f").debug("Queueing inbound network score metric",e),a(this,ME,"f").Queue(e)}if(void 0!==m&&v){const e={jitter:Math.round(v.avgJitter),packetLoss:v.packetsLoss,rtt:v.rtt,mos:Math.round(10*m)/10,streams:y.outboundActiveStreams,direction:"outbound",node:null!==(c=this.clientMetaProvider.meta.datacenterName)&&void 0!==c?c:"unknown node",bitrate:null!==(u=null===(d=null==b?void 0:b.outbound)||void 0===d?void 0:d.bitrate)&&void 0!==u?u:0,timestamp:(new Date).toISOString(),Qa:null===(l=null==b?void 0:b.outbound)||void 0===l?void 0:l.Qa,Qv:null===(p=null==b?void 0:b.outbound)||void 0===p?void 0:p.Qv,Qav:null===(h=null==b?void 0:b.outbound)||void 0===h?void 0:h.Qav};a(this,LE,"f").debug("Queueing outbound network score metric",e),a(this,ME,"f").Queue(e)}}getNodeActiveStreamsStat(){var e;const t=this.peers.hosts().filter((e=>{var t;return e.id!==(null===(t=this.myPeer)||void 0===t?void 0:t.id)})).reduce(((e,t)=>e+t.getActiveTracksCount()),0),r=this.myPeer.get();return{inboundActiveStreams:t,outboundActiveStreams:null!==(e=null==r?void 0:r.getActivePublishersCount())&&void 0!==e?e:0}}getClientMeta(){return Object.assign(Object.assign({},this.clientMetaProvider.meta),{clientUniqueId:this.clientMetaProvider.meta.clUId})}getWorstPerDirectionMetric(e){return["inbound","outbound"].map((t=>this.pickWorstMetric(e.filter((e=>e.direction===t))))).filter((e=>void 0!==e))}pickWorstMetric(e){if(!e.length)return;const t=e.filter((e=>"number"==typeof e.Qav));return t.length?t.reduce(((e,t)=>t.Qav<e.Qav?t:e)):e.reduce(((e,t)=>t.jitter>e.jitter?t:e))}};ME=new WeakMap,NE=new WeakMap,LE=new WeakMap,FE=n([ot(),i(0,ct(mi.AnalyticsApiClient)),i(1,ct(mi.Peers)),i(2,ct(mi.MyPeer)),i(3,ct(mi.LoggerFactory)),i(4,ct(mi.TransportsStatsProvider)),i(5,ct(mi.ClientMetaProvider)),s("design:paramtypes",[k_,Object,io,Function,$v,Vr])],FE);var jE=FE;let UE=class{constructor(e,t,r){this.widHandler=e,this.clientEventEmitter=t,this.config=r}handle(e){var t;this.widHandler.handleNetworkScores(e),null===(t=this.config.get("onNetworkScoresUpdated"))||void 0===t||t(e),this.clientEventEmitter.safeEmit(fn,e)}};UE=n([ot(),i(0,ct(mi.WIDHandler)),i(1,ct(mi.ClientEventEmitter)),i(2,ct(mi.Config)),s("design:paramtypes",[Function,Function,Function])],UE);var VE=UE;let BE=class{constructor(e){this.handles=new Map,this.logger=e("TransportStateMonitor")}schedule(e){var t;const{transport:r,options:n,restartIce:i}=e;if(this.handles.has(r.id))return void this.logger.debug("restartIce attempt skipped",{transportId:r.id,direction:r.direction});const s=null!==(t=n.intervalMs)&&void 0!==t?t:1500,a=(e=>{const{callback:t,intervalMs:r,immediate:n=!1}=e;let i,s=!0;const a=()=>o(void 0,void 0,void 0,(function*(){if(s){try{yield t()}catch(e){}s&&(i=setTimeout(a,r))}}));return n?a():i=setTimeout(a,r),{stop:()=>{s=!1,void 0!==i&&(clearTimeout(i),i=void 0)}}})({callback:()=>o(this,void 0,void 0,(function*(){try{yield i(r)}catch(e){this.logger.debug("restartIce attempt failed",{intervalMs:s,error:e instanceof Error?e.message:e,transportId:r.id,direction:r.direction})}})),intervalMs:s,immediate:n.immediate});this.handles.set(r.id,a)}cancel(e){const t=this.handles.get(e);t&&(t.stop(),this.handles.delete(e))}cancelAll(){this.handles.forEach((e=>e.stop())),this.handles.clear()}};BE=n([ot(),i(0,ct(mi.LoggerFactory)),s("design:paramtypes",[Function])],BE);var WE=BE;let HE=class{constructor(e,t,r){this.signalingApiClient=e,this.transportStateMonitor=r,this.logger=t("IceRecoveryService")}getIceParameters(e){return o(this,void 0,void 0,(function*(){const{data:{iceParameters:t}}=yield this.signalingApiClient.transport.getTransportIceParameters(e.id);return t}))}restartIce(e){return o(this,void 0,void 0,(function*(){try{const t=yield this.getIceParameters(e);yield e.restartIce({iceParameters:t}),this.logger.info("restartIce completed",{iceParameters:t})}catch(e){if(e instanceof Yn||e instanceof Qn)return void this.logger.debug("Cannot update ice due to connection not found on server",{error:Vt(e)});(Jn(e)?this.logger.debug.bind(this.logger):this.logger.error.bind(this.logger))("restartIce() error",{error:Vt(e)})}}))}handleConnectionStateChange(e,t){["closed","connected"].includes(t)?this.transportStateMonitor.cancel(e.id):["disconnected","failed"].includes(t)&&this.transportStateMonitor.schedule({transport:e,restartIce:this.restartIce.bind(this),options:{immediate:"failed"===t,intervalMs:1500}})}cancelAll(){this.transportStateMonitor.cancelAll()}};HE=n([ot(),i(0,ct(mi.SignalingApiClient)),i(1,ct(mi.LoggerFactory)),i(2,ct(mi.TransportStateMonitor)),s("design:paramtypes",[Function,Function,Function])],HE);var qE,zE,GE,YE,$E,KE,JE,QE,ZE,XE=HE;!function(e){e.INFO="info",e.WARNING="warning",e.ERROR="error"}(JE||(JE={})),function(e){e[e.PERFORMANCE_STOP=1001]="PERFORMANCE_STOP",e[e.REDUCE_LATENCY=1002]="REDUCE_LATENCY",e[e.MODEL_LOAD_FAILED=1010]="MODEL_LOAD_FAILED",e[e.PROCESSOR_INIT_ISSUE=1020]="PROCESSOR_INIT_ISSUE",e[e.AUTH_ISSUE=1030]="AUTH_ISSUE",e[e.SUPPORT_ISSUE=1040]="SUPPORT_ISSUE",e[e.PROCESSING_PROGRESS=1060]="PROCESSING_PROGRESS"}(QE||(QE={})),function(e){e.ATSVB="atsvb",e.STREAM_PROCESSOR="stream_processor",e.ML_INFERENCE="ml_inference",e.MODEL="model",e.WORKLET="worklet",e.WORKER="worker",e.MODEL_LOADER="model_loader"}(ZE||(ZE={}));const ew=()=>{};class tw{constructor(e){qE.set(this,void 0),zE.set(this,void 0),GE.set(this,null),YE.set(this,new Map),$E.set(this,void 0),this.type="asdk",KE.set(this,void 0);const{loggerFactory:t}=e;c(this,zE,t("ASDKTrackProcessor"),"f"),c(this,KE,"function"==typeof e.onError?e.onError:ew,"f"),c(this,qE,new window.atsvb(e.asdkCustomerId),"f");const r=e.config.get("staticFilesPath"),{localDir:n,version:i,sdk_url:s,api_url:o}=e.config.get("asdk");let d=`https://effectssdk.ai/sdk/audio/dev/${null!=i?i:"2.5.1"}`;if(n){d=new URL(`${n}/${null!=i?i:"2.5.1"}`,r).href}const u={preset:"balanced",sample_rate:48e3,api_url:o,wasmPaths:{"ort-wasm.wasm":`${d}/ort-wasm.wasm`,"ort-wasm-simd.wasm":`${d}/ort-wasm-simd.wasm`}},l=!s&&n,p=l?`${d}/`:s;l&&a(this,zE,"f").warn("Using static ASDK path due to missing config",Object.assign(Object.assign({case:"Denoiser",type:"asdk"},e.config.get("asdk")),{sdkUrl:u.sdk_url})),p&&(u.sdk_url=p),a(this,qE,"f").config(u),a(this,qE,"f").onError(this.onError.bind(this))}setOnError(e){c(this,KE,e,"f")}init(){return o(this,void 0,void 0,(function*(){yield a(this,qE,"f").preload()}))}release(){a(this,qE,"f").stop(),a(this,qE,"f").clear()}get isProcessing(){return!!a(this,$E,"f")}processTrack(e){return o(this,void 0,void 0,(function*(){var t;if(a(this,GE,"f")===e||"ended"===e.readyState)return(null===(t=a(this,qE,"f").getStream())||void 0===t?void 0:t.getAudioTracks()[0])||e;this.stopProcessing();try{const t=new Promise(((t,r)=>{a(this,qE,"f").onReady=()=>{try{const r=a(this,qE,"f").getStream(),n=null==r?void 0:r.getAudioTracks()[0];if(!n)return void t(e);c(this,GE,e,"f"),c(this,$E,n,"f"),t(n),a(this,qE,"f").run()}catch(e){r(e)}finally{a(this,qE,"f").onReady=void 0}}}));a(this,qE,"f").useStream(new MediaStream([e]));const r=yield t;return a(this,zE,"f").info("processTrack()",{case:"Denoiser",type:this.type,track:e.id}),r}catch(t){throw a(this,zE,"f").error("processTrack()",{error:Vt(t),type:this.type,case:"Denoiser",track:e}),a(this,KE,"f").call(this,"ASDK processTrack() error",t),c(this,KE,ew,"f"),new Bt("asdk_process_track_failed",t)}}))}stopProcessing(){try{a(this,qE,"f").stop()}catch(e){a(this,zE,"f").error("stopProcessing()",{type:this.type,case:"Denoiser",error:Vt(e)})}finally{c(this,GE,null,"f")}}getUpdatedDebounceCounter(e){var t;let r=null!==(t=a(this,YE,"f").get(e))&&void 0!==t?t:0;return r+=1,a(this,YE,"f").set(e,r),setTimeout((()=>{var t;const r=null!==(t=a(this,YE,"f").get(e))&&void 0!==t?t:0;r<=0?a(this,YE,"f").set(e,0):a(this,YE,"f").set(e,r-1)}),1e4),r}onError(e){const{message:t,type:n,cause:i}=e,s=r(e,["message","type","cause"]);if(n===JE.ERROR)if(a(this,zE,"f").error(t,Object.assign(Object.assign({error:Vt(i),cause:i},s),{type:this.type,case:"Denoiser"})),s.code===QE.REDUCE_LATENCY||s.code===QE.PERFORMANCE_STOP){this.getUpdatedDebounceCounter(s.code)>3&&(a(this,YE,"f").set(s.code,0),a(this,KE,"f").call(this,`ASDK performance issue(${s.code}): ${t}`,i),c(this,KE,ew,"f"))}else a(this,KE,"f").call(this,`ASDK runtime error: ${t}`,i),c(this,KE,ew,"f");n===JE.WARNING&&a(this,zE,"f").warn(t,Object.assign(Object.assign({},s),{type:this.type,case:"Denoiser"})),n===JE.INFO&&a(this,zE,"f").debug(t,Object.assign(Object.assign({},s),{type:this.type,case:"Denoiser"}))}}qE=new WeakMap,zE=new WeakMap,GE=new WeakMap,YE=new WeakMap,$E=new WeakMap,KE=new WeakMap,n([Xh(1e4),s("design:type",Function),s("design:paramtypes",[]),s("design:returntype",Promise)],tw.prototype,"init",null);class rw extends AudioWorkletNode{constructor(e){super(e.context,"rnnoise",{channelCountMode:"explicit",channelCount:1,channelInterpretation:"speakers",numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{module:e.noiseSuppressor.module}}),this.port.onmessage=({data:e})=>{const t=Object.assign(new Event("status"),e);this.dispatchEvent(t)}}update(e){this.port.postMessage(e)}static register(e){return o(this,void 0,void 0,(function*(){const t=uS.get(mi.Config);yield e.audioWorklet.addModule(`${t.get("staticFilesPath")}/noiseSuppressionWorklet.js`)}))}}var nw,iw,sw,ow,aw,cw;class dw{constructor(e){nw.set(this,void 0),iw.set(this,void 0),sw.set(this,void 0),ow.set(this,void 0),aw.set(this,void 0),cw.set(this,!0),c(this,nw,e.noiseSuppressor.instance.exports,"f"),c(this,iw,e.context,"f"),c(this,sw,new Float32Array(a(this,nw,"f").memory.buffer),"f"),c(this,ow,a(this,nw,"f").newState(),"f"),c(this,aw,a(this,iw,"f").createScriptProcessor(),"f"),this.setOnAudioProcess()}get noiseSuppressionScriptProcessorNode(){return a(this,aw,"f")}update(e){e||(c(this,cw,!1,"f"),a(this,nw,"f").deleteState(a(this,ow,"f")));const t=Object.assign(new Event("status"),{vadProb:a(this,nw,"f").getVadProb(a(this,ow,"f"))});a(this,aw,"f").dispatchEvent(t)}setOnAudioProcess(){a(this,aw,"f").addEventListener("audioprocess",(({inputBuffer:e,outputBuffer:t})=>{if(!a(this,cw,"f"))return;a(this,sw,"f").set(e.getChannelData(0),a(this,nw,"f").getInput(a(this,ow,"f"))/4);const r=t.getChannelData(0),n=a(this,nw,"f").pipe(a(this,ow,"f"),r.length)/4;n&&r.set(a(this,sw,"f").subarray(n,n+r.length))}))}}var uw,lw,pw,hw,fw,mw,gw,vw,yw,bw,_w,Ew,ww,Sw,Cw,Tw,Pw,Rw,kw,Dw,Iw,Aw,Ow,Mw,Nw,Lw,xw,Fw,jw,Uw,Vw,Bw,Ww,Hw,qw,zw,Gw,Yw,$w,Kw,Jw,Qw,Zw,Xw,eS;nw=new WeakMap,iw=new WeakMap,sw=new WeakMap,ow=new WeakMap,aw=new WeakMap,cw=new WeakMap;class tS{constructor({context:e,noiseSuppressor:t}){uw.set(this,void 0),lw.set(this,void 0),pw.set(this,void 0),c(this,uw,e,"f"),c(this,lw,t,"f")}createNoiseSuppressionNode(){return o(this,void 0,void 0,(function*(){return/apple/i.test(navigator.vendor)?this.createScriptProcessorNode():yield this.createAudioWorkletNode()}))}stop(){var e;null===(e=a(this,pw,"f"))||void 0===e||e.update(!1)}createAudioWorkletNode(){return o(this,void 0,void 0,(function*(){return yield rw.register(a(this,uw,"f")),c(this,pw,new rw({context:a(this,uw,"f"),noiseSuppressor:a(this,lw,"f")}),"f"),a(this,pw,"f")}))}createScriptProcessorNode(){return c(this,pw,new dw({context:a(this,uw,"f"),noiseSuppressor:a(this,lw,"f")}),"f"),a(this,pw,"f").noiseSuppressionScriptProcessorNode}}uw=new WeakMap,lw=new WeakMap,pw=new WeakMap;class rS{constructor(e){hw.set(this,void 0),fw.set(this,void 0),mw.set(this,void 0),gw.set(this,void 0),this.type="rnnoise",c(this,hw,e.noiseSuppressor,"f"),c(this,mw,e.loggerFactory("TrackProcessor"),"f")}get isProcessing(){return!!a(this,gw,"f")}release(){this.stopProcessing()}processTrack(e){return o(this,void 0,void 0,(function*(){const t=(e=>{const t=window.AudioContext||window.webkitAudioContext||!1;return t?new t(e):null})();if(!t)throw new Error("AudioContext is not available");const r=new MediaStreamAudioDestinationNode(t,{channelCountMode:"explicit",channelCount:1,channelInterpretation:"speakers"});yield rw.register(t);const n=t.createMediaStreamSource(new MediaStream([e])),i=new tS({context:t,noiseSuppressor:a(this,hw,"f")}),s=yield i.createNoiseSuppressionNode();s.connect(r),n.connect(s);const[o]=r.stream.getTracks();return c(this,fw,{audioContext:t,streamDestination:r,noiseSuppressionNode:s,noiseSuppressionProvider:i},"f"),c(this,gw,o,"f"),a(this,mw,"f").info("processTrack()",{case:"Denoiser",type:this.type,track:e.id}),o}))}stopProcessing(){var e;if(this.isProcessing)if(a(this,fw,"f"))try{a(this,fw,"f").noiseSuppressionProvider.stop(),a(this,fw,"f").noiseSuppressionNode.disconnect(),a(this,fw,"f").streamDestination.disconnect(),a(this,fw,"f").audioContext.close().catch((e=>{a(this,mw,"f").error("stopProcessing()",{success:!1,error:Vt(e),case:"Denoiser",type:this.type})})),null===(e=a(this,gw,"f"))||void 0===e||e.stop(),c(this,gw,void 0,"f"),a(this,mw,"f").info("stopProcessing()",{success:!0,case:"Denoiser",type:this.type})}catch(e){a(this,mw,"f").error("stopProcessing()",{success:!1,error:Vt(e),case:"Denoiser",type:this.type})}else a(this,mw,"f").debug("stopProcessing()",{success:!1,description:"Processing context is not available",case:"Denoiser",type:this.type});else a(this,mw,"f").debug("stopProcessing()",{description:"Track is not processed",case:"Denoiser",type:this.type})}}hw=new WeakMap,fw=new WeakMap,mw=new WeakMap,gw=new WeakMap;class nS extends tm{constructor(e){super(e),vw.set(this,!1),yw.set(this,void 0),bw.set(this,void 0),_w.set(this,void 0),c(this,_w,e.clientEventEmitter,"f")}get isDenoiserRequireActivation(){var e;return!(null===(e=a(this,yw,"f"))||void 0===e?void 0:e.isProcessing)&&a(this,vw,"f")}setTrackProcessor(e){if(!e)throw new Bt("track_processor_missing",new Error("trackProcessor must be passed as parameter"));this.logger.debug("Setting trackProcessor to AudioTrack",{case:"Denoiser",type:e.type}),c(this,yw,e,"f")}unsetTrackProcessor(){c(this,yw,void 0,"f")}get isEffectsProcessing(){var e;return Boolean(null===(e=a(this,yw,"f"))||void 0===e?void 0:e.isProcessing)}getEncoderConfig(){return this.encoderConfig}getEncodings(){var e;return ui(this.getPreferredCodec())?[]:null!==(e=this.getEncoderConfig().encodings)&&void 0!==e?e:jh}buildProduceEncodings(){return this.getEncodings()}getCodecOptions(){var e,t;return ui(this.getPreferredCodec())?{}:{opusFec:null===(e=this.getEncoderConfig().enableFec)||void 0===e||e,opusDtx:null===(t=this.getEncoderConfig().enableDtx)||void 0===t||t}}getPreferredCodec(){const{preferredCodec:e}=this.getEncoderConfig();return e||"opus"}enableNoiseSuppression(){return o(this,void 0,void 0,(function*(){var e,t;if(c(this,vw,!0,"f"),!a(this,yw,"f"))return this.logger.warn("enableNoiseSuppression()",{description:"Track suppressor is not defined"}),void a(this,_w,"f").emit(un,{cause:"Track suppressor is not defined"});try{yield this.performEnableNoiseSuppression(a(this,yw,"f")),this.logger.debug("Denoiser activated",{case:"Denoiser",type:(null===(e=a(this,yw,"f"))||void 0===e?void 0:e.type)||"none"}),a(this,_w,"f").emit(an,{type:null===(t=a(this,yw,"f"))||void 0===t?void 0:t.type})}catch(e){throw this.logger.warn("enableNoiseSuppression()",{description:"Can not enable noise suppression",track:this.logCtx,error:Vt(e)}),a(this,_w,"f").emit(un,{cause:"Failed to enable noise suppression",error:e}),new Bt("noise_suppression_enable_failed",e)}}))}disableNoiseSuppression(){return o(this,void 0,void 0,(function*(){var e,t,r;if(c(this,vw,!1,"f"),null===(e=a(this,yw,"f"))||void 0===e?void 0:e.isProcessing)if(a(this,bw,"f"))try{yield this.performDisableNoiseSuppression(),this.logger.debug("Denoiser deactivated",{case:"Denoiser",type:(null===(t=a(this,yw,"f"))||void 0===t?void 0:t.type)||"none"}),a(this,_w,"f").emit(cn,{type:null===(r=a(this,yw,"f"))||void 0===r?void 0:r.type})}catch(e){throw this.logger.warn("disableNoiseSuppression()",{description:"Can not disable noise suppression",track:this.logCtx,error:Vt(e)}),a(this,_w,"f").emit(un,{cause:"Failed to disable noise suppression",error:e}),new Bt("noise_suppression_disable_failed",e)}else this.logger.debug("disableNoiseSuppression()",{description:"Original track missing"});else this.logger.debug("stopProcessing()",{description:"Track is not processed"})}))}publish(){return o(this,void 0,void 0,(function*(){yield this.produce({preferredCodec:this.getPreferredCodec(),codecOptions:this.getCodecOptions()}),yield this.setPriority("high"),this.internalEventEmitter.emit(gn,this)}))}pause(){return o(this,void 0,void 0,(function*(){yield this.mute()}))}performEnableNoiseSuppression(e){return o(this,void 0,void 0,(function*(){const t=yield e.processTrack(this.mediaStreamTrack);c(this,bw,this.mediaStreamTrack,"f"),yield this.replaceTrack(t)}))}performDisableNoiseSuppression(){return o(this,void 0,void 0,(function*(){var e;a(this,bw,"f")&&(yield this.replaceTrack(a(this,bw,"f"))),null===(e=a(this,yw,"f"))||void 0===e||e.stopProcessing()}))}}vw=new WeakMap,yw=new WeakMap,bw=new WeakMap,_w=new WeakMap,n([Xh(1e4,"DefaultAudioTrack.enableNoiseSuppression"),s("design:type",Function),s("design:paramtypes",[Object]),s("design:returntype",Promise)],nS.prototype,"performEnableNoiseSuppression",null),n([Xh(1e4,"DefaultAudioTrack.disableNoiseSuppression"),s("design:type",Function),s("design:paramtypes",[]),s("design:returntype",Promise)],nS.prototype,"performDisableNoiseSuppression",null);class iS extends If{constructor({track:e,statsHandler:t,widStatsAdapter:r,scoresCalculator:n,getExpectedVideoParams:i,isStaticContent:s}){super({track:e}),Ew.set(this,void 0),ww.set(this,void 0),Sw.set(this,void 0),Cw.set(this,void 0),Tw.set(this,void 0),Pw.set(this,void 0),Rw.set(this,void 0),kw.set(this,void 0),this.handleWebRTCStats(e,t),c(this,Pw,r,"f"),c(this,Tw,n,"f"),c(this,Rw,i,"f"),c(this,kw,s,"f")}get videoWebRTCStats(){var e;return null===(e=a(this,Ew,"f"))||void 0===e?void 0:e.inbound}get audioWebRTCStats(){var e;return null===(e=a(this,ww,"f"))||void 0===e?void 0:e.inbound}get scores(){return{Qv:a(this,Sw,"f"),Qa:a(this,Cw,"f")}}handleWebRTCStats(e,t){e.addEventListener("ended",(()=>{t.removeInboundVideoHandler(e.id),t.removeInboundAudioHandler(e.id)}),{once:!0}),"video"!==e.kind?t.addInboundAudioHandler(e.id,this.setAudioWebRTCStats.bind(this)):t.addInboundVideoHandler(e.id,this.setVideoWebRTCStats.bind(this))}setVideoWebRTCStats(e){var t,r;this.touchLastReceivedStatsTimestamp();const n=null===(t=a(this,Rw,"f"))||void 0===t?void 0:t.call(this),i=a(this,Pw,"f").adaptInboundVideoStats({stats:e.inbound,connectionStats:e.connection,prevStats:null===(r=a(this,Ew,"f"))||void 0===r?void 0:r.inbound,expectedWidth:null==n?void 0:n.width,expectedHeight:null==n?void 0:n.height,expectedFrameRate:null==n?void 0:n.maxFramerate,isStaticContent:a(this,kw,"f")});c(this,Sw,a(this,Tw,"f").calculateVideoMOS(i),"f"),c(this,Ew,e,"f")}setAudioWebRTCStats(e){var t,r,n;this.touchLastReceivedStatsTimestamp();const{inbound:i}=e,s=a(this,Pw,"f").adaptInboundAudioStats({stats:i,connectionStats:e.connection,fec:null===(t=Ar("qosInboundFec"))||void 0===t||t,dtx:null===(r=Ar("qosInboundDtx"))||void 0===r||r,prevStats:null===(n=a(this,ww,"f"))||void 0===n?void 0:n.inbound});c(this,Cw,a(this,Tw,"f").calculateAudioMOS(s),"f"),c(this,ww,e,"f")}cleanupStats(){c(this,Ew,void 0,"f"),c(this,ww,void 0,"f"),c(this,Sw,void 0,"f"),c(this,Cw,void 0,"f")}}Ew=new WeakMap,ww=new WeakMap,Sw=new WeakMap,Cw=new WeakMap,Tw=new WeakMap,Pw=new WeakMap,Rw=new WeakMap,kw=new WeakMap;class sS{constructor(e){this.label=exports.TrackLabel.Unknown,Dw.set(this,void 0),Iw.set(this,void 0),Aw.set(this,void 0),Ow.set(this,void 0),Mw.set(this,void 0),Nw.set(this,void 0),Lw.set(this,void 0),xw.set(this,void 0),Fw.set(this,void 0),jw.set(this,!1),Uw.set(this,void 0),Vw.set(this,!1),Bw.set(this,new Um),Ww.set(this,!1),Hw.set(this,0),qw.set(this,void 0),this.observer=new Ft,c(this,Lw,e.mediaStreamTrack,"f"),this.label=e.label,c(this,xw,e.consumer,"f"),c(this,Ow,e.peerConsumerFactory,"f"),c(this,Mw,e.loggerFactory("PeerTrack"),"f"),c(this,Nw,e.peerEventEmitter,"f"),c(this,Ww,e.muted,"f"),c(this,Fw,e.paused,"f"),c(this,Dw,e.network,"f"),c(this,Iw,e.media,"f"),c(this,Aw,e.onClose,"f"),c(this,qw,new iS({track:e.mediaStreamTrack,statsHandler:e.statsHandler,widStatsAdapter:e.widStatsAdapter,scoresCalculator:e.scoresCalculator,getExpectedVideoParams:()=>{var e;return null===(e=a(this,xw,"f"))||void 0===e?void 0:e.currentSpatialLayerParams}}),"f")}get consumer(){return a(this,xw,"f")}get videoWebRTCStats(){return a(this,qw,"f").videoWebRTCStats}get audioWebRTCStats(){return a(this,qw,"f").audioWebRTCStats}get connectionScores(){return a(this,qw,"f").scores}get logCtx(){var e,t;return{id:a(this,Lw,"f").id,label:this.label,consumerId:null===(e=a(this,xw,"f"))||void 0===e?void 0:e.id,producerId:null===(t=a(this,xw,"f"))||void 0===t?void 0:t.producerId,muted:a(this,Ww,"f"),paused:a(this,Fw,"f"),closed:a(this,Vw,"f")}}get volume(){return a(this,Hw,"f")}get isRemote(){return!!a(this,xw,"f")}get mediaStreamTrack(){return a(this,Lw,"f")}get kind(){return this.mediaStreamTrack.kind}get isPaused(){return a(this,Fw,"f")}get isMuted(){return a(this,Ww,"f")}get consumerId(){var e;return null===(e=a(this,xw,"f"))||void 0===e?void 0:e.id}get currentSpatialLayer(){var e,t;return null!==(t=null===(e=a(this,xw,"f"))||void 0===e?void 0:e.currentSpatialLayer)&&void 0!==t?t:Vh}close(){return o(this,arguments,void 0,(function*({closeRemote:e=!0}={}){a(this,Vw,"f")||(a(this,xw,"f")&&(yield this.closeConsumer({closeRemote:e}),this.clearCheckStateTimeout()),a(this,Nw,"f").safeEmit(kn,this),c(this,Vw,!0,"f"),a(this,Aw,"f").call(this))}))}mute(){return o(this,void 0,void 0,(function*(){yield a(this,Bw,"f").push((()=>o(this,void 0,void 0,(function*(){a(this,Mw,"f").debug("mute()",{track:this.logCtx}),yield this.pauseConsumer(),c(this,Ww,!0,"f")}))))}))}unmute(){return o(this,void 0,void 0,(function*(){yield a(this,Bw,"f").push((()=>o(this,void 0,void 0,(function*(){a(this,Mw,"f").debug("unmute()",{track:this.logCtx}),yield this.resumeConsumer(),c(this,Ww,!1,"f")}))))}))}pause(){return o(this,arguments,void 0,(function*(e=!0){yield a(this,Bw,"f").push((()=>o(this,void 0,void 0,(function*(){if(!a(this,xw,"f")||this.isMuted)return c(this,Fw,!0,"f"),a(this,Nw,"f").safeEmit(Dn,this),void a(this,Mw,"f").debug("pause()",{track:this.logCtx});yield this.pauseConsumer(e),c(this,Fw,!0,"f"),a(this,Nw,"f").safeEmit(Dn,this)}))))}))}resume(){return o(this,arguments,void 0,(function*(e=!0){yield a(this,Bw,"f").push((()=>o(this,void 0,void 0,(function*(){if(!a(this,xw,"f")||this.isMuted)return c(this,Fw,!1,"f"),a(this,Nw,"f").safeEmit(In,this),void a(this,Mw,"f").debug("resume()",{track:this.logCtx});yield this.resumeConsumer(e),c(this,Fw,!1,"f"),a(this,Nw,"f").safeEmit(In,this)}))))}))}resumeConsumer(){return o(this,arguments,void 0,(function*(e=!0){if(a(this,xw,"f"))try{a(this,xw,"f").resume(),e&&(yield a(this,Dw,"f").resumeRemoteConsumer(a(this,xw,"f").id)),this.checkConsumerState().catch((e=>{a(this,Mw,"f").warn("Failed to checkConsumerState()",{track:this.logCtx,error:Vt(e)})})),a(this,Mw,"f").debug("resumeConsumer()",{track:this.logCtx})}catch(e){(Jn(e)?a(this,Mw,"f").debug.bind(a(this,Mw,"f")):a(this,Mw,"f").warn.bind(a(this,Mw,"f")))("resumeConsumer()",{error:Vt(e),track:this.logCtx})}}))}pauseConsumer(){return o(this,arguments,void 0,(function*(e=!0){if(a(this,xw,"f"))try{if(this.clearCheckStateTimeout(),e&&(yield a(this,Dw,"f").pauseRemoteConsumer(a(this,xw,"f").id)),"audio"===this.kind)return void a(this,Mw,"f").debug("pauseConsumer() - skipping for audio",{track:this.logCtx});a(this,xw,"f").pause(),c(this,jw,!1,"f"),a(this,Mw,"f").debug("pauseConsumer()",{track:this.logCtx})}catch(e){(Jn(e)?a(this,Mw,"f").debug.bind(a(this,Mw,"f")):a(this,Mw,"f").warn.bind(a(this,Mw,"f")))("pauseConsumer()",{error:Vt(e),track:this.logCtx})}}))}requestVideoPreferredLayers(e){return o(this,arguments,void 0,(function*({spatialLayer:e,temporalLayer:t}){if(a(this,xw,"f"))try{if(a(this,xw,"f").isAudio)return void a(this,Mw,"f").debug("Only video consumers support layers",{case:"requestVideoPreferredLayers"});if(e===a(this,xw,"f").currentSpatialLayer)return;if(e>a(this,xw,"f").spatialLayers)return void a(this,Mw,"f").debug("Invalid spatial layer",{spatialLayer:e,consumerSpatialLayers:a(this,xw,"f").spatialLayers,case:"requestVideoPreferredLayers"});if(e>a(this,xw,"f").currentMaxSpatialLayer)return void(yield this.requestMaxSpatialLayer(a(this,xw,"f").id,e));yield a(this,Dw,"f").updateConsumerPreferredLayers(a(this,xw,"f").id,e,t),a(this,Mw,"f").debug("requestVideoPreferredLayers()",{track:this.logCtx,consumer:a(this,xw,"f"),spatialLayer:e,temporalLayer:t})}catch(e){throw(Jn(e)?a(this,Mw,"f").debug.bind(a(this,Mw,"f")):a(this,Mw,"f").error.bind(a(this,Mw,"f")))("Failed to request preferred layers",{case:"requestVideoPreferredLayers",track:{id:this.mediaStreamTrack.id,kind:this.mediaStreamTrack.kind,label:this.mediaStreamTrack.label},consumerId:a(this,xw,"f").id,spatialLayers:a(this,xw,"f").spatialLayers,temporalLayers:a(this,xw,"f").temporalLayers,error:Vt(e)}),new Bt("peer_track_request_preferred_layers_failed",e)}}))}requestKeyFrame(){return o(this,void 0,void 0,(function*(){if(this.consumerId){a(this,Mw,"f").debug("requestKeyFrame()",{track:this.logCtx});try{yield a(this,Dw,"f").requestConsumerKeyFrame(this.consumerId)}catch(e){throw(Jn(e)?a(this,Mw,"f").debug.bind(a(this,Mw,"f")):a(this,Mw,"f").error.bind(a(this,Mw,"f")))("requestKeyFrame()",{error:Vt(e),track:this.logCtx,consumerId:this.consumerId}),new Bt("peer_track_request_key_frame_failed",e)}}}))}getVideoAvailableLayers(){if(a(this,xw,"f")){if(!a(this,xw,"f").isAudio)return a(this,xw,"f").availableSpatialLayers;a(this,Mw,"f").debug("Only video consumers support layers",{case:"getVideoAvailableLayers"})}}getInfo(){return o(this,void 0,void 0,(function*(){var e;const{width:t,height:r,frameRate:n,aspectRatio:i}=a(this,Lw,"f").getSettings();return{trackId:a(this,Lw,"f").id,readyState:a(this,Lw,"f").readyState,isRemote:this.isRemote,kind:this.kind,label:this.label,width:t,height:r,frameRate:n,aspectRatio:i,paused:a(this,Fw,"f"),trackInboundStats:yield null===(e=a(this,xw,"f"))||void 0===e?void 0:e.getStats(),trackOutboundStats:yield this.getOutboundStats()}}))}getOutboundStats(){return o(this,void 0,void 0,(function*(){if(this.isRemote)return;const e=a(this,Iw,"f").getAllTracks().find((e=>e.getLabel()===this.label));return e?yield e.getStats():void 0}))}requestMaxSpatialLayer(e,t){return o(this,void 0,void 0,(function*(){try{if(!a(this,xw,"f"))return;if(a(this,xw,"f").isAudio||0===a(this,xw,"f").spatialLayers||a(this,xw,"f").currentMaxSpatialLayer===t||t<a(this,xw,"f").currentMaxSpatialLayer)return void a(this,Mw,"f").warn("Can`t request this spatial layer",{case:"requestMaxSpatialLayer",consumerId:e,spatialLayer:t});a(this,xw,"f").setRequestedSpatialLayer(t),yield a(this,Dw,"f").requestProducerMaxSpatialLayer(a(this,xw,"f").producerId,t),a(this,Mw,"f").debug("requestMaxSpatialLayer()",{consumerId:e,spatialLayer:t})}catch(r){(Jn(r)?a(this,Mw,"f").debug.bind(a(this,Mw,"f")):a(this,Mw,"f").warn.bind(a(this,Mw,"f")))("Failed to request max spatial layer",{case:"requestMaxSpatialLayer",consumerId:e,spatialLayer:t,error:Vt(r)})}}))}checkConsumerState(){return o(this,void 0,void 0,(function*(){try{if(a(this,Vw,"f")||"audio"===this.kind)return;a(this,Mw,"f").debug("checkConsumerState()",{track:this.logCtx});if((yield this.isInboundRTPStreamActive())||a(this,Vw,"f"))return;yield this.requestKeyFrame();if((yield this.isInboundRTPStreamActive())||a(this,Vw,"f"))return;if(a(this,jw,"f"))return a(this,Nw,"f").emit(An,this),void a(this,Mw,"f").debug("trackFail()",{track:this.logCtx});yield this.restartConsumer()}catch(e){a(this,Mw,"f").warn("checkConsumerState()",{track:this,error:e})}}))}setVolume(e){a(this,Hw,"f")!==e&&(c(this,Hw,e,"f"),this.observer.safeEmit(mn,{value:e}))}closeConsumer(){return o(this,arguments,void 0,(function*({closeRemote:e=!0}={}){a(this,xw,"f")&&(e&&(yield a(this,Dw,"f").closeRemoteConsumer(a(this,xw,"f").id)),a(this,xw,"f").close())}))}restartConsumer(){return o(this,void 0,void 0,(function*(){try{if(!a(this,xw,"f")||a(this,Vw,"f"))return;a(this,Mw,"f").debug("restartConsumer()",{track:this.logCtx}),a(this,Nw,"f").emit(kn,this),c(this,Fw,!0,"f"),yield this.closeConsumer();const{consumer:e}=yield a(this,Dw,"f").createConsumer({producerId:a(this,xw,"f").producerId,rtpCapabilities:a(this,Iw,"f").mediasoupDevice.rtpCapabilities,producerPeerId:a(this,xw,"f").appData.producerData.peerId});c(this,jw,!0,"f"),c(this,xw,a(this,Ow,"f").call(this,{consumer:e}),"f"),c(this,Lw,e.track,"f"),yield this.resume(),a(this,Nw,"f").emit(Rn,this)}catch(e){c(this,jw,!0,"f"),a(this,Mw,"f").warn("restartConsumer()",{track:this,error:e})}}))}isInboundRTPStreamActive(){return o(this,void 0,void 0,(function*(){if(!a(this,xw,"f")||a(this,Vw,"f"))return!1;const{framesDecoded:e}=yield a(this,xw,"f").getInboundRTPStreamStats();return yield new Promise((t=>{c(this,Uw,setTimeout((()=>o(this,void 0,void 0,(function*(){try{if(!a(this,xw,"f"))return void t(!1);const{framesDecoded:r}=yield a(this,xw,"f").getInboundRTPStreamStats();if(e===r&&!this.isPaused)return void t(!1);t(!0)}catch(e){a(this,Mw,"f").debug("isInboundRTPStreamActive()",{error:e,track:this.logCtx}),t(!1)}}))),4500),"f")}))}))}clearCheckStateTimeout(){a(this,Uw,"f")||clearTimeout(a(this,Uw,"f"))}}Dw=new WeakMap,Iw=new WeakMap,Aw=new WeakMap,Ow=new WeakMap,Mw=new WeakMap,Nw=new WeakMap,Lw=new WeakMap,xw=new WeakMap,Fw=new WeakMap,jw=new WeakMap,Uw=new WeakMap,Vw=new WeakMap,Bw=new WeakMap,Ww=new WeakMap,Hw=new WeakMap,qw=new WeakMap;class oS{constructor(e){this.encodings=[],zw.set(this,void 0);const{id:t,kind:r,peerId:n,label:i,paused:s}=e;this.id=t,this.kind=r,this.peerId=n,this.label=i,this.paused=s,this.encodings=e.encodings,this.trackTransformParams=e.trackTransformParams,this.maxSpatialLayer=e.maxSpatialLayer,c(this,zw,Date.now(),"f")}setPaused(e){this.paused=e,c(this,zw,Date.now(),"f")}getStateChangedAt(){return a(this,zw,"f")}}zw=new WeakMap;class aS{constructor({id:e,channelIds:t,groups:r,producePermissions:n,appId:i,loginDate:s,producers:o=[],appData:a,uid:d,role:u,loggerFactory:l,myPeer:p,callState:h,peers:f,remotePeerTracks:m,media:g,network:v,peerConsumerFactory:y}){this.producers=new Map,this.tracks=new Map,Gw.set(this,void 0),Yw.set(this,void 0),$w.set(this,void 0),Kw.set(this,void 0),Jw.set(this,void 0),Qw.set(this,void 0),Zw.set(this,void 0),Xw.set(this,void 0),this._observer=new Ft,this.id=e,this.channelIds=t,this.groups=r,this.producePermissions=n,this.appId=i,this.loginDate=s,this.applicationData=null!=a?a:{},this.uid=d,this.role=u,c(this,Jw,p,"f"),c(this,Qw,h,"f"),c(this,Gw,f,"f"),c(this,Yw,m,"f"),c(this,Zw,y,"f"),c(this,$w,v,"f"),c(this,Kw,g,"f"),c(this,Xw,l("Peer"),"f"),o.forEach(this.handleNewProducer.bind(this)),this.handlePeerEvents()}get appData(){return this.applicationData}get observer(){return this._observer}get isMe(){return this.id===a(this,Jw,"f").id}get isModerator(){return this.groups.includes("moderator")}get isUser(){return this.groups.includes("user")}get publishedMedia(){return Array.from(this.producers.values()).map((e=>({producerId:e.id,kind:e.kind,label:e.label,paused:e.paused})))}get shortData(){return{id:this.id,producers:Array.from(this.producers.values()).map((e=>({id:e.id,paused:e.paused}))),appData:this.appData}}hasPermission(e){return this.producePermissions.includes(e)}hasGroup(e){return this.groups.includes(e)}subscribe(e){return o(this,arguments,void 0,(function*({producerId:e,muted:t=!1}){try{const r=this.producers.get(e);if(!r)return void a(this,Xw,"f").debug("subscribe()",{error:"Peer does not have a producer",peer:no(this),producerId:e});if(this.getAllConsumers().find((t=>t.producerId===e)))return void a(this,Xw,"f").debug("subscribe()",{error:"Already subscribed to producer",peer:no(this),producerId:e});const{consumer:n,isProducerPaused:i}=yield a(this,$w,"f").createConsumer({producerId:r.id,rtpCapabilities:a(this,Kw,"f").mediasoupDevice.rtpCapabilities,producerPeerId:this.id});if(!this.producePermissions.includes(r.label)&&Object.values(exports.TrackLabel).includes(r.label))return void a(this,Xw,"f").debug("subscribe()",{error:"Producer is not allowed anymore",peer:no(this),producerId:e});const s=a(this,Yw,"f").create({mediaStreamTrack:n.track,label:r.label,consumer:a(this,Zw,"f").call(this,{consumer:n}),muted:t,paused:i,peerEventEmitter:this.observer});t||(yield s.unmute()),this.tracks.set(s.label,s),a(this,Xw,"f").debug(`Subscribed for ${r.kind}`,{peer:no(this)})}catch(t){throw(Jn(t)?a(this,Xw,"f").debug.bind(a(this,Xw,"f")):a(this,Xw,"f").error.bind(a(this,Xw,"f")))("subscribe()",{producerId:e,error:t,peer:no(this)}),new Bt("peer_subscribe_failed",t)}}))}unsubscribe(e){return o(this,void 0,void 0,(function*(){try{const t=this.getConsumerByProducerId(e);if(!t)return;const r=this.getTrackByConsumerId(t.id);if(!r)return;yield r.close(),this.tracks.delete(r.label),a(this,Xw,"f").debug(`Unsubscribed consumer ${t.kind}`,{peer:no(this)})}catch(t){throw(Jn(t)?a(this,Xw,"f").debug.bind(a(this,Xw,"f")):a(this,Xw,"f").error.bind(a(this,Xw,"f")))("unsubscribe()",{producerId:e,error:t}),new Bt("peer_unsubscribe_failed",t)}}))}setProducePermissions(e){return o(this,void 0,void 0,(function*(){this.throwIfIamNotModerator();try{yield a(this,$w,"f").changePeerProducePermissions(this.id,e)}catch(e){throw new Bt("peer_set_produce_permissions_failed",e)}a(this,Xw,"f").debug("Produce permissions changed",{peerId:this.id,producePermissions:e})}))}addProducePermission(e){return o(this,void 0,void 0,(function*(){this.throwIfIamNotModerator();try{yield a(this,$w,"f").addPeerProducePermission(this.id,e)}catch(e){throw new Bt("peer_add_produce_permission_failed",e)}a(this,Xw,"f").debug("Add produce permission requested",{peerId:this.id,label:e})}))}removeProducePermission(e){return o(this,void 0,void 0,(function*(){this.throwIfIamNotModerator();try{yield a(this,$w,"f").removePeerProducePermission(this.id,e)}catch(e){throw new Bt("peer_remove_produce_permission_failed",e)}a(this,Xw,"f").debug("Remove produce permission requested",{peerId:this.id,label:e})}))}getInfo(){return o(this,void 0,void 0,(function*(){try{return{id:this.id,appData:this.appData,role:this.role,channelIds:this.channelIds,appId:this.appId,uid:this.uid,loginDate:this.loginDate,tracks:yield Promise.all(Array.from(this.tracks.values()).map((e=>o(this,void 0,void 0,(function*(){return yield e.getInfo()})))))}}catch(e){throw a(this,Xw,"f").error("getInfo()",{peer:no(this),error:e}),new Bt("peer_get_info_failed",e)}}))}getProducers(){return Array.from(this.producers.values())}getConsumersState(){return this.getAllConsumers().map((e=>({id:e.id,paused:e.paused,producerId:e.producerId})))}handleNewProducer(e){if(this.producers.get(e.id))return;const t=new oS(e);this.producers.set(t.id,t),a(this,Xw,"f").debug("Peer published media:",{peer:no(this),producer:t});const r={producerId:t.id,kind:t.kind,label:t.label,paused:t.paused};this.observer.safeEmit(Sn,r)}handlePeerEvents(){this.observer.on(Ln,this.handleNewProducer.bind(this)),this.observer.on(xn,(e=>o(this,void 0,void 0,(function*(){this.producers.delete(e.id),a(this,Xw,"f").debug("Peer unpublished media:",{peer:no(this),producer:e}),this.observer.safeEmit(Cn,{producerId:e.id,kind:e.kind,label:e.label,paused:e.paused});const t=this.tracks.get(e.label);if(t)try{yield t.close({closeRemote:!1})}catch(e){(Jn(e)?a(this,Xw,"f").debug.bind(a(this,Xw,"f")):a(this,Xw,"f").warn.bind(a(this,Xw,"f")))("Failed to close peer track due to producer closed",{label:t.label,peerId:this.id,error:Vt(e)})}})))),this.observer.on(Un,(e=>o(this,void 0,void 0,(function*(){const t=this.getTrackByConsumerId(e);if(t)try{yield t.close({closeRemote:!1}),this.tracks.delete(t.label),a(this,Xw,"f").debug("Peer video track was ended:",{peer:no(this),trackLabel:t.label})}catch(e){(e instanceof Yn?a(this,Xw,"f").debug.bind(a(this,Xw,"f")):a(this,Xw,"f").warn.bind(a(this,Xw,"f")))("Failed to close peer track due to consumer closed",{label:t.label,peerId:this.id,error:Vt(e)})}})))),this.observer.on(Vn,(e=>o(this,void 0,void 0,(function*(){const t=this.getTrackByConsumerId(e);t&&(yield t.pause(!1))})))),this.observer.on(Bn,(e=>o(this,void 0,void 0,(function*(){const t=this.getTrackByConsumerId(e);t&&(yield t.resume(!1))})))),this.observer.on(Wn,(e=>{const t=this.getConsumerById(e.consumerId);(null==t?void 0:t.isVideo)&&(t.applyLayersUpdate({spatialLayer:e.spatialLayer,temporalLayer:e.temporalLayer}),e.spatialLayer===t.requestedSpatialLayer&&t.setRequestedSpatialLayer(void 0),a(this,Xw,"f").debug("consumerChangePreferredLayers()",Object.assign({},e)))})),this.observer.on(Fn,(e=>o(this,void 0,void 0,(function*(){const{producerId:t,spatialLayer:r}=e,n=this.getConsumerByProducerId(t);n?(n.setCurrentMaxSpatialLayer(r),a(this,Xw,"f").debug("producerSetMaxSpatialLayer()",{producerId:t,consumerId:n.id,spatialLayer:r}),n.requestedSpatialLayer===r?(yield a(this,$w,"f").updateConsumerPreferredLayers(n.id,r),a(this,Xw,"f").debug("requestVideoPreferredLayers()",{producerId:t,consumerId:n.id,spatialLayer:r})):a(this,Xw,"f").debug("producerSetMaxSpatialLayer()",{message:"No need to request new preferred layer",currentMaxSpatialLayer:r,requestedMaxSpatialLayer:n.requestedSpatialLayer})):a(this,Xw,"f").debug("producerSetMaxSpatialLayer()",{message:"Consumer for producer not created, ignore MaxSpatialLayer change"})})))),this.observer.on(Br,(e=>{try{Xn(e),this.setAppData(e),this.observer.emit(On,e),a(this,Xw,"f").debug("updatePeerAppData",{peer:no(this),appData:e})}catch(t){a(this,Xw,"f").error("updatePeerAppData",{peer:no(this),appData:e,error:t})}}))}reset(){return o(this,void 0,void 0,(function*(){this.producers.clear();try{yield Promise.all(Array.from(this.tracks.values()).map((e=>o(this,void 0,void 0,(function*(){return yield e.close({closeRemote:!1})})))))}catch(e){a(this,Xw,"f").debug("Failed to reset peer tracks",{peer:no(this),error:Vt(e)})}this.tracks.clear();[Ln,xn,Un,Vn,Bn,Wn,Fn,Br].forEach((e=>this.observer.removeAllListeners(e)))}))}getActiveTracksCount(){return Array.from(this.tracks.values()).map((e=>e.consumer)).filter((e=>!(null==e?void 0:e.paused))).length}getActivePublishersCount(){return Array.from(this.producers.values()).filter((e=>!e.paused)).length}handleProducePermissionsChange(e){this.producePermissions=e,Object.values(exports.TrackLabel).filter((e=>!this.producePermissions.includes(e))).forEach((e=>{const t=this.tracks.get(e);t&&(this.tracks.delete(t.label),t.close({closeRemote:!1}).catch((e=>{a(this,Xw,"f").error("Failed to close track",{case:"Peer",error:Vt(e)})})))})),this.observer.safeEmit(Mn,{labels:this.producePermissions})}handleGroupsChange(e){this.groups=e,this.observer.safeEmit(Nn,{groups:e})}getAllConsumers(){return Array.from(this.tracks.values()).map((e=>e.consumer)).filter((e=>!!e))}getConsumerByProducerId(e){return this.getAllConsumers().find((t=>t.producerId===e))}getConsumerById(e){return this.getAllConsumers().find((t=>t.id===e))}getTrackByConsumerId(e){return Array.from(this.tracks.values()).find((t=>t.consumerId===e))}setAppData(e){this.applicationData=e}throwIfIamNotModerator(){if(!a(this,Gw,"f").isModerator(a(this,Jw,"f").id))throw new Bt("not_enough_access",new Error("Not enough access"))}}Gw=new WeakMap,Yw=new WeakMap,$w=new WeakMap,Kw=new WeakMap,Jw=new WeakMap,Qw=new WeakMap,Zw=new WeakMap,Xw=new WeakMap;class cS{constructor(e){this.spatialLayers=Vh,this.temporalLayers=Wh,this.currentSpatialLayer=Vh,this.currentTemporalLayer=Wh,this.availableSpatialLayers=[],eS.set(this,void 0);const{consumer:t,loggerFactory:r}=e;this.id=t.id,this.kind=t.kind,this.producerId=t.producerId,this.appData=t.appData,this.consumer=t,c(this,eS,r("PeerConsumer"),"f"),this.currentMaxSpatialLayer=this.appData.producerData.maxSpatialLayer,this.parseScalabilityMode(),this.initAvailableSpatialLayers(),this.setCurrentSpatialLayerParams()}get paused(){return this.consumer.paused}pause(){this.consumer.pause()}resume(){this.consumer.resume()}close(){this.consumer.close()}get isVideo(){return"video"===this.kind}get isAudio(){return"audio"===this.kind}parseScalabilityMode(){if(this.consumer.rtpParameters.encodings){const{scalabilityMode:e}=this.consumer.rtpParameters.encodings[0],{spatialLayers:t,temporalLayers:r}=fd.parseScalabilityMode(e);this.spatialLayers=t,this.temporalLayers=r,a(this,eS,"f").debug("parseScalabilityMode()",{scalabilityMode:e,spatialLayers:t,temporalLayers:r})}}initAvailableSpatialLayers(){const{encodings:e,trackTransformParams:t}=this.appData.producerData;if(!Array.isArray(e))return;if(this.availableSpatialLayers=e.map((e=>this.tryPrepareSpatialLayerParams(e))),!t||this.availableSpatialLayers.length>1||this.spatialLayers<Bh)return void a(this,eS,"f").debug("Using available spatial layers",{case:"initAvailableSpatialLayers"});a(this,eS,"f").debug("Pre-generating encodings with spatial layer params",{case:"initAvailableSpatialLayers"});const r=[],n=e[e.length-1];for(let e=this.spatialLayers-1;e>=0;e-=1)r.push(this.tryPrepareSpatialLayerParams(Object.assign(Object.assign({},n),{scaleResolutionDownBy:Math.pow(2,e)})));this.availableSpatialLayers=r}setCurrentSpatialLayerParams(){const{encodings:e}=this.appData.producerData;(null==e?void 0:e[this.currentSpatialLayer])&&(this.currentSpatialLayerParams=this.tryPrepareSpatialLayerParams(e[this.currentSpatialLayer]),a(this,eS,"f").debug("setCurrentSpatialLayerParams()",{currentSpatialLayerParams:this.currentSpatialLayerParams}))}tryPrepareSpatialLayerParams(e){var t;const{trackTransformParams:r}=this.appData.producerData;if(!r)return e;const{width:n,height:i}=r,s=null!==(t=e.scaleResolutionDownBy)&&void 0!==t?t:1;return n&&i?Object.assign({width:n/s,height:i/s},e):e}setCurrentSpatialLayer(e){if(!this.isVideo)throw new Error("setCurrentSpatialLayer applies to video consumers only");this.currentSpatialLayer=e,a(this,eS,"f").debug("setCurrentSpatialLayer()",{currentSpatialLayer:e}),this.setCurrentSpatialLayerParams()}setCurrentTemporalLayer(e){if(!this.isVideo)throw new Error("setCurrentTemporalLayer applies to video consumers only");this.currentTemporalLayer=e,a(this,eS,"f").debug("setCurrentTemporalLayer()",{currentTemporalLayer:e})}applyLayersUpdate(e){if(!this.isVideo)throw new Error("applyLayersUpdate applies to video consumers only");const{spatialLayer:t,temporalLayer:r}=e;void 0!==t&&this.setCurrentSpatialLayer(t),void 0!==r&&this.setCurrentTemporalLayer(r)}setRequestedSpatialLayer(e){this.requestedSpatialLayer=e}setCurrentMaxSpatialLayer(e){this.currentMaxSpatialLayer=e}getStats(){return o(this,void 0,void 0,(function*(){var e,t;try{return{consumerId:this.consumer.id,codec:this.consumer.rtpParameters.codecs.find((e=>Pf(e))),dtlsState:null===(t=null===(e=this.consumer.rtpReceiver)||void 0===e?void 0:e.transport)||void 0===t?void 0:t.state,availableSpatialLayers:this.availableSpatialLayers,currentSpatialLayerParams:this.currentSpatialLayerParams,requestedSpatialLayer:this.requestedSpatialLayer,rtcStats:yield this.getInboundRTPStreamStats()}}catch(e){return void a(this,eS,"f").debug("getStats()",{error:e})}}))}getInboundRTPStreamStats(){return o(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>{const r=(...n)=>o(this,[...n],void 0,(function*(n=0){try{const i=yield this.consumer.getStats(),s=Array.from(i.values()).find((e=>"inbound-rtp"===e.type));if(!s&&n<5)return void setTimeout((()=>{r(n+1).catch((e=>{a(this,eS,"f").debug("Error getting RTCStatsReport",{attempt:n,error:Vt(e)})}))}),150);n>=5&&!s&&t(new Error("InboundRTPStreamStat not exist")),e(s)}catch(e){t(new Error("Can not get RTCStatsReport")),a(this,eS,"f").debug("getInboundRTPStreamStats()",{error:e})}}));r().catch((e=>{a(this,eS,"f").debug("Error executing getRTCStatsReport",{case:"PeerConsumer",error:Vt(e)})}))}))}))}}eS=new WeakMap;let dS=class{adaptInboundAudioStats(e){const{stats:t,connectionStats:r,fec:n,dtx:i,prevStats:s}=e,o=this.calculateDeltaPacketLoss({packetsLost:t.packetsLost,packetsReceivedOrSent:t.packetsReceived},s?{packetsLost:s.packetsLost,packetsReceivedOrSent:s.packetsReceived}:void 0),a=this.calculateJitterBufferDelay(t.jitterBufferDelay,t.jitterBufferEmittedCount);return{ssrc:t.ssrc,dtx:i,fec:n,packetLoss:o,bufferDelay:a,bitrate:t.bitrate,roundTripTime:1e3*r.currentRoundTripTime}}adaptInboundVideoStats(e){var t,r,n;const{stats:i,connectionStats:s,prevStats:o}=e,a=this.calculateDeltaPacketLoss({packetsLost:i.packetsLost,packetsReceivedOrSent:i.packetsReceived},o?{packetsLost:o.packetsLost,packetsReceivedOrSent:o.packetsReceived}:void 0),c=this.calculateJitterBufferDelay(i.jitterBufferDelay,i.jitterBufferEmittedCount),d=i,u=o,l=this.calculateDeltaAverageQP(d.qpSum,d.framesDecoded,null==u?void 0:u.qpSum,null==u?void 0:u.framesDecoded);return{ssrc:i.ssrc,packetLoss:a,bufferDelay:c,bitrate:i.bitrate,roundTripTime:1e3*s.currentRoundTripTime,width:i.frameWidth,height:i.frameHeight,expectedWidth:null!==(t=e.expectedWidth)&&void 0!==t?t:i.frameWidth,expectedHeight:null!==(r=e.expectedHeight)&&void 0!==r?r:i.frameHeight,frameRate:i.framesPerSecond,expectedFrameRate:null!==(n=e.expectedFrameRate)&&void 0!==n?n:i.framesPerSecond,isStaticContent:e.isStaticContent,averageQP:l}}adaptOutboundAudioStats(e){const{stats:t,remoteInboundStats:r,fec:n,dtx:i,prevStats:s}=e,o=r?this.calculateDeltaPacketLoss({packetsLost:r.packetsLost,packetsReceivedOrSent:t.packetsSent},s?{packetsLost:s.remoteInbound.packetsLost,packetsReceivedOrSent:s.outbound.packetsSent}:void 0):0,a=(null==r?void 0:r.roundTripTime)?1e3*r.roundTripTime:50,c=(null==r?void 0:r.jitter)?1e3*r.jitter:0;return{ssrc:t.ssrc,fec:n,dtx:i,packetLoss:o,bufferDelay:c,roundTripTime:a,bitrate:t.bitrate}}adaptOutboundVideoStats(e){var t,r,n,i,s,o,a;const{stats:c,remoteInboundStats:d,prevStats:u}=e,l=d?this.calculateDeltaPacketLoss({packetsLost:d.packetsLost,packetsReceivedOrSent:c.packetsSent},u?{packetsLost:u.remoteInbound.packetsLost,packetsReceivedOrSent:u.outbound.packetsSent}:void 0):0,p=(null==d?void 0:d.roundTripTime)?1e3*d.roundTripTime:50,h=(null==d?void 0:d.jitter)?1e3*d.jitter:0,f=this.calculateDeltaAverageQP(c.qpSum,c.framesEncoded,null==u?void 0:u.outbound.qpSum,null==u?void 0:u.outbound.framesEncoded);return{ssrc:c.ssrc,packetLoss:l,bufferDelay:h,bitrate:c.bitrate,roundTripTime:p,width:c.frameWidth,height:c.frameHeight,expectedWidth:null!==(t=c.frameWidth)&&void 0!==t?t:null===(r=c.track)||void 0===r?void 0:r.width,expectedHeight:null!==(n=c.frameHeight)&&void 0!==n?n:null===(i=c.track)||void 0===i?void 0:i.height,frameRate:c.framesPerSecond,expectedFrameRate:null!==(s=c.framesPerSecond)&&void 0!==s?s:null===(o=c.track)||void 0===o?void 0:o.framesPerSecond,decreaseOutboundPenalty:null===(a=Ar("qosDecreaseOutboundPenalty"))||void 0===a||a,isStaticContent:e.isStaticContent,averageQP:f,qualityLimitationReason:c.qualityLimitationReason}}calculateDeltaPacketLoss(e,t){var r,n;const i=kv(e.packetsLost-(null!==(r=null==t?void 0:t.packetsLost)&&void 0!==r?r:0),0,e.packetsLost),s=kv(e.packetsReceivedOrSent-(null!==(n=null==t?void 0:t.packetsReceivedOrSent)&&void 0!==n?n:0),0,e.packetsReceivedOrSent);return s||i?i/(i+s)*100:0}calculateDeltaAverageQP(e,t,r,n){if(void 0===e||void 0===t)return;const i=t-(null!=n?n:0);return i<=0?void 0:(e-(null!=r?r:0))/i}calculateJitterBufferDelay(e,t){return 0===t?0:e/t*1e3}};dS=n([ot()],dS);const uS=new tt({autoBindInjectable:!0});var lS,pS,hS;uS.bind(mi.ClientMetaProvider).to(Vr).inSingletonScope(),uS.bind(mi.LocalMutex).to(Ev).inSingletonScope(),uS.bind(mi.SignalingApiClient).toDynamicValue((e=>new rd(e.container.get(mi.Config)))).inSingletonScope(),uS.bind(mi.CallState).to(gi).inSingletonScope(),uS.bind(mi.MyPeer).to(io).inSingletonScope(),uS.bind(mi.LoggerFactory).toFactory((e=>{const t=e.container.get(mi.Config),r=t.get("logLevel"),n=t.get("sendAnalytics"),i=t.get("onLogMessage"),s=e.container.get(mi.ClientMetaProvider),o=e.container.get(mi.AnalyticsApiClient),a=new U_.MessageBatcher({MaxBatchSize:50,MaxDelay:2e3,MinDelay:500});return a.on("batch",(e=>{o.log.batch({logs:e,clientMeta:s.meta})})),e=>new fE({logLevel:r,namespace:e,onLogMessage:i,sendAnalytics:n,logToRemoteBatcher:a})})),uS.bind(mi.System).to(Tv).inSingletonScope(),uS.bind(mi.ProcessorsCache).to(Kh).inSingletonScope(),uS.bind(mi.IntegrationsService).to(Zh).inSingletonScope(),uS.bind(mi.MediaStreamTrackManager).to(vm).inSingletonScope(),uS.bind(mi.Media).to(bm).inSingletonScope(),uS.bind(mi.Network).to(po).inSingletonScope(),uS.bind(mi.NetworkTransportPolicyManager).to(lv).inSingletonScope(),uS.bind(mi.TransportStateMonitor).to(WE).inSingletonScope(),uS.bind(mi.IceRecoveryService).to(XE).inSingletonScope(),uS.bind(mi.PendingClosureProducerStorage).to(Xg).inSingletonScope(),uS.bind(mi.ProducerCloseManager).to(cv).inSingletonScope(),uS.bind(mi.RemotePeerTracks).to(OE).inSingletonScope(),uS.bind(mi.Peers).to(mo).inSingletonScope(),uS.bind(mi.MediaEventHandler).to(Jg).inSingletonScope(),uS.bind(mi.ChannelEventHandler).to(xm).inSingletonScope(),uS.bind(mi.ChannelAudioObserverEventHandler).to(j_).inSingletonScope(),uS.bind(mi.ChannelAudioObserverMissingProducerRestorer).to(x_).inSingletonScope(),uS.bind(mi.EventsQueue).to(ro).inSingletonScope(),uS.bind(mi.ChannelStateSynchronizer).to(Nm).inSingletonScope(),uS.bind(mi.ChannelStateSyncEventHandler).to(hd).inSingletonScope(),uS.bind(mi.StatsHandler).to(Gv).inSingletonScope(),uS.bind(mi.WIDHandler).to(jE).inSingletonScope(),uS.bind(mi.NetworkScoresUpdatedEventHandler).to(VE).inSingletonScope(),uS.bind(mi.WIDIgnoreSsrcList).toConstantValue([1234]),uS.bind(mi.CompositeStatsParser).toDynamicValue((e=>{const t=e.container.get(mi.LoggerFactory)("WID"),r=e.container.get(mi.WIDIgnoreSsrcList);return new Sr({statsParser:new Cr({ignoreSSRCList:r,logger:t})})})).inSingletonScope(),uS.bind(mi.PeriodicStatsReporter).toDynamicValue((e=>{const t=e.container.get(mi.Config),r=e.container.get(mi.CompositeStatsParser);return new sr({compositeStatsParser:r,getStatsInterval:t.get("getStatsInterval")})})).inSingletonScope(),uS.bind(mi.WebRTCIssueDetector).toDynamicValue((e=>{const t=e.container.get(mi.Config),r=e.container.get(mi.WIDHandler);if(t.get("disableWid"))return;const n=e.container.get(mi.StatsHandler),i=e.container.get(mi.NetworkScoresUpdatedEventHandler),s=e.container.get(mi.WIDIgnoreSsrcList),o=e.container.get(mi.LoggerFactory)("WID"),a=e.container.get(mi.CompositeStatsParser),c=e.container.get(mi.PeriodicStatsReporter);return new Tr({onIssues:e=>{var n;r.handleIssues(e),null===(n=t.get("onIssues"))||void 0===n||n(e)},issueEmitter:new ir,networkScoresCalculator:new ar,detectors:[new hr,new ur,new pr,new lr,new dr,new fr,new yr({minMosQuality:zt.GOOD,avgFreezeDurationThresholdMs:2e3,frozenDurationThresholdPct:50}),new br({minMosQuality:zt.GOOD,volatilityThreshold:10,affectedStreamsPercentThreshold:60})],statsReporter:c,onNetworkScoresUpdated:e=>{i.handle(e)},onStats:n.handle.bind(n),ignoreSSRCList:s,compositeStatsParser:a,logger:o,autoAddPeerConnections:!1})})).inSingletonScope(),uS.bind(mi.WIDStatsAdapter).to(dS).inSingletonScope(),uS.bind(mi.ScoresCalculator).toDynamicValue((()=>new exports.ScoresCalculator)).inSingletonScope(),uS.bind(mi.Engine).to(ry).inSingletonScope(),uS.bind(mi.PeerTrackFactory).toFactory((function(e){const t=e.container.get(mi.LoggerFactory),r=e.container.get(mi.CallState),n=e.container.get(mi.StatsHandler);return i=>{const s={callState:r,loggerFactory:t,media:e.container.get(mi.Media),network:e.container.get(mi.Network),peerConsumerFactory:e.container.get(mi.PeerConsumerFactory),widStatsAdapter:e.container.get(mi.WIDStatsAdapter),scoresCalculator:e.container.get(mi.ScoresCalculator)},{peerEventEmitter:o}=i,a=new sS(Object.assign(Object.assign(Object.assign({},i),s),{statsHandler:n}));return o.safeEmit(Rn,a),a}})),uS.bind(mi.PeerFactory).toFactory((function(e){const t=e.container.get(mi.LoggerFactory),r=e.container.get(mi.CallState);return n=>{const i={callState:r,loggerFactory:t,media:e.container.get(mi.Media),myPeer:e.container.get(mi.MyPeer),network:e.container.get(mi.Network),peers:e.container.get(mi.Peers),remotePeerTracks:e.container.get(mi.RemotePeerTracks),peerConsumerFactory:e.container.get(mi.PeerConsumerFactory)};return new aS(Object.assign(Object.assign({},i),n))}})),uS.bind(mi.PeerConsumerFactory).toFactory((function(e){const t=e.container.get(mi.LoggerFactory);return e=>{const r={loggerFactory:t};return new cS(Object.assign(Object.assign({},r),e))}})),uS.bind(mi.AudioTrackFactory).toFactory((function(e){const t=e.container.get(mi.LoggerFactory),r=e.container.get(mi.StatsHandler);return n=>{const i={internalEventEmitter:e.container.get(mi.InternalEventEmitter),loggerFactory:t,media:e.container.get(mi.Media),mediaStreamTrackManager:e.container.get(mi.MediaStreamTrackManager),myPeer:e.container.get(mi.MyPeer),network:e.container.get(mi.Network),producerCloseManager:e.container.get(mi.ProducerCloseManager),mutex:e.container.get(mi.LocalMutex),processorFactory:e.container.get(mi.AudioTrackProcessorFactory),clientEventEmitter:e.container.get(mi.ClientEventEmitter),statsHandler:r,widStatsAdapter:e.container.get(mi.WIDStatsAdapter),scoresCalculator:e.container.get(mi.ScoresCalculator)};return new nS(Object.assign(Object.assign({},i),n))}})),uS.bind(mi.VideoTrackFactory).toFactory((function(e){const t=e.container.get(mi.LoggerFactory),r=e.container.get(mi.StatsHandler);return n=>{const i={internalEventEmitter:e.container.get(mi.InternalEventEmitter),loggerFactory:t,media:e.container.get(mi.Media),mediaStreamTrackManager:e.container.get(mi.MediaStreamTrackManager),myPeer:e.container.get(mi.MyPeer),network:e.container.get(mi.Network),producerCloseManager:e.container.get(mi.ProducerCloseManager),mutex:e.container.get(mi.LocalMutex),clientEventEmitter:e.container.get(mi.ClientEventEmitter),statsHandler:r,widStatsAdapter:e.container.get(mi.WIDStatsAdapter),scoresCalculator:e.container.get(mi.ScoresCalculator)};return new om(Object.assign(Object.assign({},i),n))}})),uS.bind(mi.EncodedVideoTrackFactory).toFactory((function(e){const t=e.container.get(mi.LoggerFactory),r=e.container.get(mi.StatsHandler);return n=>{const i={internalEventEmitter:e.container.get(mi.InternalEventEmitter),loggerFactory:t,media:e.container.get(mi.Media),mediaStreamTrackManager:e.container.get(mi.MediaStreamTrackManager),myPeer:e.container.get(mi.MyPeer),network:e.container.get(mi.Network),producerCloseManager:e.container.get(mi.ProducerCloseManager),mutex:e.container.get(mi.LocalMutex),clientEventEmitter:e.container.get(mi.ClientEventEmitter),statsHandler:r,widStatsAdapter:e.container.get(mi.WIDStatsAdapter),scoresCalculator:e.container.get(mi.ScoresCalculator)};return new zg(Object.assign(Object.assign({},i),n))}})),uS.bind(mi.AudioTrackProcessorFactory).toFactory((function(e){const t=e.container.get(mi.LoggerFactory),r=e.container.get(mi.Config),n=e.container.get(mi.ProcessorsCache),i=r.get("asdk");return e=>{const s=r.get("denoiser");let o=n.get(s,e.trackLabel);if(o)return o;if("rnnoise"===s&&e.noiseSuppressor&&(o=new rS({noiseSuppressor:e.noiseSuppressor,loggerFactory:t})),"asdk"===s&&(null==i?void 0:i.customerId)&&(o=new tw({asdkCustomerId:i.customerId,loggerFactory:t,config:r})),!o)throw new TypeError("Incorrect parameters passed to AudioTrackProcessorFactory");return o}})),uS.bind(mi.DataChannelsManager).to(TE).inSingletonScope(),uS.bind(mi.DatachannelHeartbeater).to(DE).inSingletonScope(),uS.bind(mi.SignalingHeartbeater).to(AE).inSingletonScope(),uS.bind(mi.AnalyticsApiClient).toDynamicValue((e=>{const t=e.container.get(mi.Config);return new k_(t.get("analyticsApiUrl"))})).inSingletonScope(),uS.bind(mi.PeersStorage).to(fo).inSingletonScope(),uS.bind(mi.TransportsStatsProvider).to($v).inSingletonScope();class fS{constructor(e){lS.set(this,void 0),pS.set(this,void 0),hS.set(this,void 0),this.canUseNoiseSuppression=!0;const{clientEventEmitter:t,internalEventEmitter:r}=e;uS.bind(mi.Config).toDynamicValue((()=>new Et(e))).inSingletonScope(),uS.bind(mi.InternalEventEmitter).toDynamicValue((()=>null!=r?r:new Ft)).inSingletonScope(),uS.bind(mi.ClientEventEmitter).toDynamicValue((()=>null!=t?t:new Ft)).inSingletonScope(),uS.get(mi.IntegrationsService),this.clientEventEmitter=uS.get(mi.ClientEventEmitter),c(this,lS,uS.get(mi.Engine),"f"),c(this,pS,uS.get(mi.NetworkTransportPolicyManager),"f"),c(this,hS,uS.get(mi.ClientMetaProvider),"f")}get meta(){return a(this,hS,"f").meta}get observer(){return this.clientEventEmitter}get id(){return a(this,lS,"f").myPeerId}get peers(){return a(this,lS,"f").getPeers()}get availableVideoDevices(){return a(this,lS,"f").system.availableVideoDevices}get availableAudioDevices(){return a(this,lS,"f").system.availableAudioDevices}get effectsSDKInitialized(){return a(this,lS,"f").media.effectsSDKInitialized}get scoresCalculator(){return a(this,lS,"f").scoresCalculator}detectDevices(e){return o(this,void 0,void 0,(function*(){try{return yield a(this,lS,"f").system.detectDevices(e)}catch(e){throw new Bt("detect_devices_failed",e)}}))}initEffectsSDK(){return o(this,void 0,void 0,(function*(){try{return yield a(this,lS,"f").media.initEffectsSDK()}catch(e){throw new Bt("init_effects_sdk_failed",e)}}))}join(e){return o(this,void 0,void 0,(function*(){yield a(this,lS,"f").join(e)}))}leave(e){return o(this,void 0,void 0,(function*(){yield a(this,lS,"f").release(e)}))}confirmActivity(){return o(this,void 0,void 0,(function*(){yield a(this,lS,"f").confirmActivity()}))}createCameraVideoTrack(e){return o(this,void 0,void 0,(function*(){return yield a(this,lS,"f").createCameraVideoTrack(e)}))}createMicrophoneAudioTrack(e){return o(this,void 0,void 0,(function*(){return yield a(this,lS,"f").createMicrophoneAudioTrack(e)}))}createScreenMediaTracks(e){return o(this,void 0,void 0,(function*(){return yield a(this,lS,"f").createScreenMediaTracks(e)}))}createCustomAudioTrack(e){return a(this,lS,"f").createCustomAudioTrack(e)}createCustomVideoTrack(e){return o(this,void 0,void 0,(function*(){return yield a(this,lS,"f").createCustomVideoTrack(e)}))}deleteTrack(e){return o(this,void 0,void 0,(function*(){yield a(this,lS,"f").deleteTrack(e)}))}requestChannelStateSync(){return o(this,void 0,void 0,(function*(){yield a(this,lS,"f").requestChannelStateSync()}))}updateAppData(e){return o(this,void 0,void 0,(function*(){yield a(this,lS,"f").updateAppData(e)}))}getTransportsInfo(){return o(this,void 0,void 0,(function*(){try{return yield a(this,lS,"f").network.getTransportsStateInfo()}catch(e){throw new Bt("get_transports_info_failed",e)}}))}setPreferRelay(e){a(this,lS,"f").network.setPreferRelay(e)}getPreferRelay(){return a(this,lS,"f").network.getPreferRelay()}isRelayEnforced(){return a(this,lS,"f").network.isRelayEnforced()}changeIceTransportPolicy(e){return o(this,void 0,void 0,(function*(){try{yield a(this,pS,"f").changeIceTransportPolicy(e)}catch(e){throw new Bt("change_ice_transport_policy_failed",e)}}))}restartIce(){return o(this,void 0,void 0,(function*(){try{const e=[a(this,lS,"f").network.sendTransport,a(this,lS,"f").network.receiveTransport,a(this,lS,"f").network.signalingTransport].filter((e=>!!e));yield Promise.all(e.map((e=>o(this,void 0,void 0,(function*(){return yield a(this,lS,"f").network.restartIce(e)})))))}catch(e){throw new Bt("restart_ice_failed",e)}}))}transportsStats(){return a(this,lS,"f").transportsStats()}setSignalingServerUrl(e){a(this,lS,"f").setSignalingServerUrl(e)}setMeta(e){a(this,hS,"f").setExternalMeta(e)}}lS=new WeakMap,pS=new WeakMap,hS=new WeakMap,exports.Client=fS,exports.EnhancedEventEmitter=Ft,exports.Peer=aS,exports.PeerProducer=oS,exports.default=fS;
39
39
  //# sourceMappingURL=index.js.map