@livedigital/client 3.43.0 → 3.43.1-debug-esdk.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.es.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 l?l:"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 k(e,t)}if(!G(e))throw new TypeError;if(!B(t))throw new TypeError;if(!B(n)&&!F(n)&&!j(n))throw new TypeError;return j(n)&&(n=void 0),R(e,t,r=z(r),n)}function y(e,t){function r(r,n){if(!B(r))throw new TypeError;if(!F(n)&&!J(n))throw new TypeError;N(e,t,r,n)}return r}function _(e,t,r,n){if(!B(r))throw new TypeError;return F(n)||(n=z(n)),N(e,t,r,n)}function b(e,t,r){if(!B(t))throw new TypeError;return F(r)||(r=z(r)),I(e,t,r)}function E(e,t,r){if(!B(t))throw new TypeError;return F(r)||(r=z(r)),D(e,t,r)}function w(e,t,r){if(!B(t))throw new TypeError;return F(r)||(r=z(r)),A(e,t,r)}function S(e,t,r){if(!B(t))throw new TypeError;return F(r)||(r=z(r)),O(e,t,r)}function C(e,t){if(!B(e))throw new TypeError;return F(t)||(t=z(t)),M(e,t)}function P(e,t){if(!B(e))throw new TypeError;return F(t)||(t=z(t)),L(e,t)}function T(e,t,r){if(!B(t))throw new TypeError;if(F(r)||(r=z(r)),!B(t))throw new TypeError;F(r)||(r=z(r));var n=ae(t,r,!1);return!F(n)&&n.OrdinaryDeleteMetadata(e,t,r)}function k(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 R(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(!B(s))throw new TypeError;n=s}}return n}function I(e,t,r){if(D(e,t,r))return!0;var n=re(t);return!j(n)&&I(e,n,r)}function D(e,t,r){var n=ae(t,r,!1);return!F(n)&&H(n.OrdinaryHasOwnMetadata(e,t,r))}function A(e,t,r){if(D(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 N(e,t,r,n){ae(r,n,!0).OrdinaryDefineOwnMetadata(e,t,r,n)}function M(e,t){var r=L(e,t),n=re(e);if(null===n)return r;var i=M(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 B(e){return"object"==typeof e?null!==e:"function"==typeof e}function V(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(B(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(!B(i=r.call(e)))return i;if(Y(n=e.valueOf))if(!B(i=n.call(e)))return i}else{var n;if(Y(n=e.valueOf))if(!B(i=n.call(e)))return i;var i,s=e.toString;if(Y(s))if(!B(i=s.call(e)))return i}throw new TypeError}function H(e){return!!e}function q(e){return""+e}function z(e){var t=V(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 K(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(!B(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)&&B(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[f]),F(e)&&(e=ne()),!F(f)&&B(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--,K(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(!K(this._cacheKey,e)){this._cacheIndex=-1;for(var r=0;r<this._keys.length;r++)if(K(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(){var e=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}();return 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",_),e("hasMetadata",b),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)}()}(u||(u={}));var f=["inject","multi_inject","name","unmanaged","named","optional"],m="Request",g="Singleton",v="Transient",y="ConstantValue",_="Constructor",b="DynamicValue",E="Factory",w="Function",S="Instance",C="Invalid",P="Provider",T="ClassProperty",k="ConstructorArgument",R="Variable",I=0;function D(){return I++}var A=function(){function e(e,t){this.id=D(),this.activated=!1,this.serviceIdentifier=e,this.scope=t,this.type=C,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===g&&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}(),O="No matching bindings found for serviceIdentifier:",N="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},L=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}(),x=0,F=1;function j(e){return e instanceof RangeError||"Maximum call stack size exceeded"===e.message}function U(e){return"function"==typeof e?e.name:"symbol"==typeof e?e.toString():e}function B(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=H(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 W(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=U(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)}W(e)}))}function H(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 q=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}(),z=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}(),G=function(e,t){this.parentContext=e,this.rootRequest=t},Y=function(){function e(e){this._cb=e}return e.prototype.unwrap=function(){return this._cb()},e}(),$=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}(),J=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 $(i||""),this.identifier=t,this.metadata=new Array;var s=null;"string"==typeof n?s=new z("named",n):n instanceof z&&(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 f.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 f.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 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=Z(o,e,t,r,n);null!==a&&s.push(a)}return s}(n,t,s,o,c||d?a.length:r.length),l=ee(e,r,t);return K(K([],u,!0),l,!0)}function Z(e,t,r,n,i){var s=i[e.toString()]||[],o=re(s),a=!0!==o.unmanaged,c=n[e],d=o.inject||o.multiInject;if((c=d||c)instanceof Y&&(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 J(k,o.targetName,c);return u.metadata=s,u}return null}function X(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 ee(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=re(d),l=u.targetName||c,p=X(u.inject,u.multiInject,c,r),h=new J(T,l,p);h.metadata=d,i.push(h)}var f=Object.getPrototypeOf(t.prototype).constructor;if(f!==Object){var m=ee(e,f,r);i=K(K([],i,!0),m,!0)}return i}function te(e,t){var r=Object.getPrototypeOf(t.prototype).constructor;if(r!==Object){var n=Q(e,H(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:te(e,r)}return 0}function re(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 ne=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 ie(e){return e._bindingDictionary}function se(e,t,r,n,i){var s=ae(r.container,i.serviceIdentifier),o=[];return s.length===x&&r.container.options.autoBindInjectable&&"function"==typeof i.serviceIdentifier&&e.getConstructorMetadata(i.serviceIdentifier).compilerGeneratedMetadata&&(r.container.bind(i.serviceIdentifier).toSelf(),s=ae(r.container,i.serviceIdentifier)),o=t?s:s.filter((function(e){var t=new ne(e.serviceIdentifier,r,n,e,i);return e.constraint(t)})),function(e,t,r,n){switch(t.length){case x:if(r.isOptional())return t;var i=U(e),s=O;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+=B(n,i,ae),new Error(s);case F:return t;default:if(r.isArray())return t;s="Ambiguous match found for serviceIdentifier: "+(i=U(e));throw s+=B(n,i,ae),new Error(s)}}(i.serviceIdentifier,o,i,r.container),o}function oe(e,t,r,n,i,s){var o,a;if(null===i){o=se(e,t,n,null,s),a=new ne(r,n,null,o,s);var c=new G(n,a);n.addPlan(c)}else o=se(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===S&&null!==t.implementationType){var i=function(e,t){return Q(e,H(t),t,!1)}(e,t.implementationType);if(!n.container.options.skipBaseClassChecks){var o=te(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."}(H(t.implementationType));throw new Error(c)}}i.forEach((function(t){oe(e,!1,t.serviceIdentifier,n,r,t)}))}}))}function ae(e,t){var r=[],n=ie(e);return n.hasKey(t)?r=n.get(t):null!==e.parent&&(r=ae(e.parent,t)),r}function ce(e,t,r,n,i,s,o,a){void 0===a&&(a=!1);var c=new q(t),d=function(e,t,r,n,i,s){var o=new z(e?"multi_inject":"inject",r),a=new J(t,n,r,o);if(void 0!==i){var c=new z(i,s);a.metadata.push(c)}return a}(r,n,i,"",s,o);try{return oe(e,a,i,c,null,d),c}catch(e){throw j(e)&&W(c.plan.rootRequest),e}}function de(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&"function"==typeof e.then}function ue(e){return!!de(e)||Array.isArray(e)&&e.some(de)}var le,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){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))},he=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])}}},fe=function(e,t,r){e.has(t.id)||e.set(t.id,r)},me=function(e,t){e.cache=t,e.activated=!0,de(t)&&ge(e,t)},ge=function(e,t){return pe(void 0,void 0,void 0,(function(){var r,n;return he(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"}(le||(le={}));var ve=function(){return ve=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},ve.apply(this,arguments)},ye=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){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))},_e=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 Ee(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===k?e.constructorInjections.push(n):(e.propertyRequests.push(r),e.propertyInjections.push(n)),e.isAsync||(e.isAsync=ue(n)),e}),{constructorInjections:[],propertyInjections:[],propertyRequests:[],isAsync:!1})}(t,r),s=ve(ve({},i),{constr:e});n=i.isAsync?function(e){return ye(this,void 0,void 0,(function(){var t,r;return _e(this,(function(n){switch(n.label){case 0:return[4,Se(e.constructorInjections)];case 1:return t=n.sent(),[4,Se(e.propertyInjections)];case 2:return r=n.sent(),[2,we(ve(ve({},e),{constructorInjections:t,propertyInjections:r}))]}}))}))}(s):we(s)}else n=new e;return n}function we(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 Se(e){return ye(this,void 0,void 0,(function(){var t,r,n,i;return _e(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 Ce(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 de(r)?r.then((function(){return t})):t}function Pe(e,t){e.scope!==g&&function(e,t){var r="Class cannot be instantiated in "+(e.scope===m?"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){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))},ke=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 Oe(e,t,o)}}},Ie=function(e,t){var r=function(e){switch(e.type){case E:return{factory:e.factory,factoryType:le.Factory};case P:return{factory:e.provider,factoryType:le.Provider};case b:return{factory:e.dynamicValue,factoryType:le.DynamicValue};default:throw new Error("Unexpected factory type "+e.type)}}(e);return function(e,t){try{return e()}catch(e){throw j(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 y:case w:t=e.cache;break;case _:case S:t=e.implementationType;break;case b:t=e.dynamicValue;break;case P:t=e.provider;break;case E:t=e.factory}if(null===t){var r=U(e.serviceIdentifier);throw new Error("Invalid binding type: "+r)}}(r),r.type){case y:case w:n=r.cache;break;case _:n=r.implementationType;break;case S:n=function(e,t,r,n){Pe(e,t);var i=Ee(t,r,n);return de(i)?i.then((function(e){return Ce(t,e)})):Ce(t,i)}(r,r.implementationType,i,Re(e));break;default:n=Ie(r,t.parentContext)}return n},Ae=function(e,t,r){var n=function(e,t){return t.scope===g&&t.activated?t.cache:t.scope===m&&e.has(t.id)?e.get(t.id):null}(e,t);return null!==n||function(e,t,r){t.scope===g&&me(t,r),t.scope===m&&fe(e,t,r)}(e,t,n=r()),n},Oe=function(e,t,r){return Ae(e,r,(function(){var n=De(e,t,r);return n=de(n)?n.then((function(e){return Ne(t,r,e)})):Ne(t,r,n)}))};function Ne(e,t,r){var n,i=Me(e.parentContext,t,r),s=je(e.parentContext.container),o=s.next();do{n=o.value;var a=e.parentContext,c=e.serviceIdentifier,d=Fe(n,c);i=de(i)?xe(d,a,i):Le(d,a,i),o=s.next()}while(!0!==o.done&&!ie(n).hasKey(e.serviceIdentifier));return i}var Me=function(e,t,r){return"function"==typeof t.onActivation?t.onActivation(e,r):r},Le=function(e,t,r){for(var n=e.next();!n.done;){if(de(r=n.value(t,r)))return xe(e,t,r);n=e.next()}return r},xe=function(e,t,r){return Te(void 0,void 0,void 0,(function(){var n,i;return ke(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]}}))}))},Fe=function(e,t){var r=e._activations;return r.hasKey(t)?r.get(t).values():[].values()},je=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 Ue=function(e,t){var r=e.parentRequest;return null!==r&&(!!t(r)||Ue(r,t))},Be=function(e){return function(t){var r=function(r){return null!==r&&null!==r.target&&r.target.matchesTag(e)(t)};return r.metaData=new z(e,t),r}},Ve=Be("named"),We=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}},He=function(){function e(e){this._binding=e}return e.prototype.when=function(e){return this._binding.constraint=e,new qe(this._binding)},e.prototype.whenTargetNamed=function(e){return this._binding.constraint=Ve(e),new qe(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 qe(this._binding)},e.prototype.whenTargetTagged=function(e,t){return this._binding.constraint=Be(e)(t),new qe(this._binding)},e.prototype.whenInjectedInto=function(e){return this._binding.constraint=function(t){return null!==t&&We(e)(t.parentRequest)},new qe(this._binding)},e.prototype.whenParentNamed=function(e){return this._binding.constraint=function(t){return null!==t&&Ve(e)(t.parentRequest)},new qe(this._binding)},e.prototype.whenParentTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&Be(e)(t)(r.parentRequest)},new qe(this._binding)},e.prototype.whenAnyAncestorIs=function(e){return this._binding.constraint=function(t){return null!==t&&Ue(t,We(e))},new qe(this._binding)},e.prototype.whenNoAncestorIs=function(e){return this._binding.constraint=function(t){return null!==t&&!Ue(t,We(e))},new qe(this._binding)},e.prototype.whenAnyAncestorNamed=function(e){return this._binding.constraint=function(t){return null!==t&&Ue(t,Ve(e))},new qe(this._binding)},e.prototype.whenNoAncestorNamed=function(e){return this._binding.constraint=function(t){return null!==t&&!Ue(t,Ve(e))},new qe(this._binding)},e.prototype.whenAnyAncestorTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&Ue(r,Be(e)(t))},new qe(this._binding)},e.prototype.whenNoAncestorTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&!Ue(r,Be(e)(t))},new qe(this._binding)},e.prototype.whenAnyAncestorMatches=function(e){return this._binding.constraint=function(t){return null!==t&&Ue(t,e)},new qe(this._binding)},e.prototype.whenNoAncestorMatches=function(e){return this._binding.constraint=function(t){return null!==t&&!Ue(t,e)},new qe(this._binding)},e}(),qe=function(){function e(e){this._binding=e}return e.prototype.onActivation=function(e){return this._binding.onActivation=e,new He(this._binding)},e.prototype.onDeactivation=function(e){return this._binding.onDeactivation=e,new He(this._binding)},e}(),ze=function(){function e(e){this._binding=e,this._bindingWhenSyntax=new He(this._binding),this._bindingOnSyntax=new qe(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}(),Ge=function(){function e(e){this._binding=e}return e.prototype.inRequestScope=function(){return this._binding.scope=m,new ze(this._binding)},e.prototype.inSingletonScope=function(){return this._binding.scope=g,new ze(this._binding)},e.prototype.inTransientScope=function(){return this._binding.scope=v,new ze(this._binding)},e}(),Ye=function(){function e(e){this._binding=e,this._bindingWhenSyntax=new He(this._binding),this._bindingOnSyntax=new qe(this._binding),this._bindingInSyntax=new Ge(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}(),$e=function(){function e(e){this._binding=e}return e.prototype.to=function(e){return this._binding.type=S,this._binding.implementationType=e,new Ye(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=y,this._binding.cache=e,this._binding.dynamicValue=null,this._binding.implementationType=null,this._binding.scope=g,new ze(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 Ye(this._binding)},e.prototype.toConstructor=function(e){return this._binding.type=_,this._binding.implementationType=e,this._binding.scope=g,new ze(this._binding)},e.prototype.toFactory=function(e){return this._binding.type=E,this._binding.factory=e,this._binding.scope=g,new ze(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=w,this._binding.scope=g,t},e.prototype.toAutoFactory=function(e){return this._binding.type=E,this._binding.factory=function(t){return function(){return t.container.get(e)}},this._binding.scope=g,new ze(this._binding)},e.prototype.toAutoNamedFactory=function(e){return this._binding.type=E,this._binding.factory=function(t){return function(r){return t.container.getNamed(e,r)}},new ze(this._binding)},e.prototype.toProvider=function(e){return this._binding.type=P,this._binding.provider=e,this._binding.scope=g,new ze(this._binding)},e.prototype.toService=function(e){this.toDynamicValue((function(t){return t.container.get(e)}))},e}(),Je=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}(),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 Ke,onDeactivations:new Ke}},e}(),Ze=function(){return Ze=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},Ze.apply(this,arguments)},Xe=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){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))},et=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])}}},tt=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))},rt=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=v;else if(t.defaultScope!==g&&t.defaultScope!==v&&t.defaultScope!==m)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 L,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=tt([t,r],n,!0).map((function(e){return ie(e)})),a=ie(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 Xe(this,void 0,void 0,(function(){var t,r,n,i,s;return et(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 Xe(this,void 0,void 0,(function(){var t,r,n,i;return et(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||v,r=new A(e,t);return this._bindingDictionary.add(e,r),new $e(r)},e.prototype.rebind=function(e){return this.unbind(e),this.bind(e)},e.prototype.rebindAsync=function(e){return Xe(this,void 0,void 0,(function(){return et(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 Xe(this,void 0,void 0,(function(){var t;return et(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 Xe(this,void 0,void 0,(function(){var e,t=this;return et(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 J(R,"",t,new z(r,n)),s=new q(e);return new ne(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(Je.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 Xe(this,void 0,void 0,(function(){var t;return et(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 Xe(this,void 0,void 0,(function(){var n;return et(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(de(i))return this._handleDeactivationError(i.then((function(){return r._propagateContainerDeactivationThenBindingAndPreDestroyAsync(e,t,n)})),n)}var s=this._propagateContainerDeactivationThenBindingAndPreDestroy(e,t,n);if(de(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 Xe(this,void 0,void 0,(function(){var r;return et(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(de(i))return i.then((function(){return r._deactivateContainerAsync(e,t)}));n=t.next()}},e.prototype._deactivateContainerAsync=function(e,t){return Xe(this,void 0,void 0,(function(){var r;return et(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=Ze(Ze({},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(ue(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=ce(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 de(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(de(this._deactivateIfSingleton(n)))throw new Error("Attempting to unbind dependency with asynchronous destruction (@preDestroy or onDeactivation)")}},e.prototype._deactivateSingletonsAsync=function(e){return Xe(this,void 0,void 0,(function(){var t=this;return et(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 Xe(this,void 0,void 0,(function(){return et(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: "+U(e))}},e.prototype._bindingDeactivationAndPreDestroy=function(e,t,r){var n=this;if("function"==typeof e.onDeactivation){var i=e.onDeactivation(t);if(de(i))return i.then((function(){return n._preDestroy(r,t)}))}return this._preDestroy(r,t)},e.prototype._bindingDeactivationAndPreDestroyAsync=function(e,t,r){return Xe(this,void 0,void 0,(function(){return et(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 nt(e,t,r,n){!function(e){if(void 0!==e)throw new Error(N)}(t),st("inversify:tagged",e,r.toString(),n)}function it(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 st(e,t,r,n){var i=it(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 ot(e){return function(t,r,n){"number"==typeof n?nt(t,r,n,e):function(e,t,r){if(void 0!==e.prototype)throw new Error(N);st("inversify:tagged_props",e.constructor,t,r)}(t,r,e)}}function at(){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 ct,dt=(ct="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(function(e){return"@inject called with undefined this could mean that the class "+e+" has a circular dependency problem. You can use a LazyServiceIdentifier to overcome this limitation."}(i))}return ot(new z(ct,e))(t,r,n)}});const ut=3,lt=4,pt=6,ht=7;var ft;!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"}(ft||(ft={}));var mt;const gt={baseURL:"https://lb.livedigital.space/v1",timeout:5e3},vt={customerId:String("b149fa74b11d989a60fb08e98e6a82883de0b468"),sdk_url:String("https://effectssdk.ai/sdk/audio/"),api_url:String("https://effectssdk.ai/sdk/session/"),version:"2.3.5"},yt={customerId:String("89c41ecf3b3f46fef5dfa9f96842014c21d4901c"),sdk_url:String("https://effectssdk.ai/sdk/"),api_url:String("https://effectssdk.ai/sdk/session/")},_t=()=>{};let bt=class{constructor(e){var t,r,n,i,s,o,a,c,u;mt.set(this,void 0),d(this,mt,{denoiser:null!==(t=e.denoiser)&&void 0!==t?t:"rnnoise",asdk:Object.assign(Object.assign({},vt),e.asdk),loadbalancer:Object.assign(gt,null!==(n=null===(r=e.network)||void 0===r?void 0:r.loadbalancer)&&void 0!==n?n:{}),logLevel:null!==(i=e.logLevel)&&void 0!==i?i:ut,sendAnalytics:null!==(s=e.sendAnalytics)&&void 0!==s&&s,onLogMessage:null!==(o=e.onLogMessage)&&void 0!==o?o:_t,onIssues:null!==(a=e.onIssues)&&void 0!==a?a:_t,disableWid:null!==(c=e.disableWid)&&void 0!==c&&c,effectsSDKParams:Object.assign(Object.assign({},yt),e.effectsSDKParams),onNetworkScoresUpdated:null!==(u=e.onNetworkScoresUpdated)&&void 0!==u?u:_t,staticFilesPath:e.staticFilesPath||window.location.origin},"f")}get(e){return c(this,mt,"f")[e]}set(e,t){c(this,mt,"f")[e]=t}};mt=new WeakMap,bt=i([at(),o("design:paramtypes",[Object])],bt);var Et,wt,St,Ct,Pt=bt;class Tt extends t{constructor(){super(),this.addListener=(e,t)=>this.on(e,t),this.removeListener=(e,t)=>this.off(e,t),this.prependListener=(e,t)=>(super.prependListener(e,t),this),this.prependOnceListener=(e,t)=>(super.prependOnceListener(e,t),this),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)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}removeAllListeners(e){return super.removeAllListeners(e),this}}function kt(){}function Rt(){Rt.init.call(this)}function It(e){return void 0===e._maxListeners?Rt.defaultMaxListeners:e._maxListeners}function Dt(e,t,r){if(t)e.call(r);else for(var n=e.length,i=jt(e,n),s=0;s<n;++s)i[s].call(r)}function At(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,s=jt(e,i),o=0;o<i;++o)s[o].call(r,n)}function Ot(e,t,r,n,i){if(t)e.call(r,n,i);else for(var s=e.length,o=jt(e,s),a=0;a<s;++a)o[a].call(r,n,i)}function Nt(e,t,r,n,i,s){if(t)e.call(r,n,i,s);else for(var o=e.length,a=jt(e,o),c=0;c<o;++c)a[c].call(r,n,i,s)}function Mt(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,s=jt(e,i),o=0;o<i;++o)s[o].apply(r,n)}function Lt(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 kt,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=It(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 xt(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 Ft(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 jt(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}kt.prototype=Object.create(null),Rt.EventEmitter=Rt,Rt.usingDomains=!1,Rt.prototype.domain=void 0,Rt.prototype._events=void 0,Rt.prototype._maxListeners=void 0,Rt.defaultMaxListeners=10,Rt.init=function(){this.domain=null,Rt.usingDomains&&(void 0).active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new kt,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Rt.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},Rt.prototype.getMaxListeners=function(){return It(this)},Rt.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:Dt(r,u,this);break;case 2:At(r,u,this,arguments[1]);break;case 3:Ot(r,u,this,arguments[1],arguments[2]);break;case 4:Nt(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];Mt(r,u,this,i)}return!0},Rt.prototype.addListener=function(e,t){return Lt(this,e,t,!1)},Rt.prototype.on=Rt.prototype.addListener,Rt.prototype.prependListener=function(e,t){return Lt(this,e,t,!0)},Rt.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,xt(this,e,t)),this},Rt.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,xt(this,e,t)),this},Rt.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 kt:(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 kt,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},Rt.prototype.off=function(e,t){return this.removeListener(e,t)},Rt.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new kt,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new kt: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 kt,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},Rt.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):[]},Rt.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Ft.call(e,t)},Rt.prototype.listenerCount=Ft,Rt.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class Ut extends Rt{}!function(e){e.Issue="issue",e.NetworkScoresUpdated="network-scores-updated",e.StatsParsingFinished="stats-parsing-finished"}(Et||(Et={})),function(e){e.Network="network",e.CPU="cpu",e.Server="server",e.Stream="stream"}(wt||(wt={})),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"}(St||(St={})),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"}(Ct||(Ct={}));class Bt extends Rt{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(Bt.STATS_REPORTS_PARSED,{timeTaken:r,reportItems:t}),t.forEach((e=>{this.emit(Bt.STATS_REPORT_READY_EVENT,e)}))}}const Vt=(()=>{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 Wt{#e={};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,Vt({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=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=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;return i-=2.5*r,1+.035*i+7e-6*i*(i-60)*(100-i)}}class Ht{#t=new Map;#r;#n;constructor(e={}){this.#r=e.statsCleanupTtlMs??35e3,this.#n=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.#t.has(t)&&Vt({taskId:t,delayMs:this.#r,callback:()=>{this.deleteLastProcessedStats(t),"function"==typeof r&&r()}})}setLastProcessedStats(e,t){if(!e||t.connection.id!==e)return;const r=this.#t.get(e)??[];r.push(t),r.length>this.#n&&r.shift(),this.#t.set(e,r)}getLastProcessedStats(e){const t=this.#t.get(e);return t?.[t.length-1]}getAllLastProcessedStats(e){return this.#t.get(e)??[]}deleteLastProcessedStats(e){this.#t.delete(e)}}class qt extends Ht{#i;constructor(e={}){super(e),this.#i=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.#i?(t.push({statsSample:s,type:wt.Network,reason:St.OutboundNetworkThroughput}),t):t}}class zt extends Ht{#s;#o;#a;#c;constructor(e={}){super(),this.#s=e.highPacketLossThresholdPct??5,this.#o=e.highJitterThreshold??200,this.#a=e.highJitterBufferDelayThresholdMs??500,this.#c=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=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.#s,v=l>=this.#o,y=c>=this.#c,_=p>this.#a,b=y&&!v&&!g,E=g&&v,w=v&&_,S={rtt:c,packetLossPct:m,avgJitter:l,avgJitterBufferDelay:p};return(v||g)&&t.push({statsSample:S,type:wt.Network,reason:St.InboundNetworkQuality,iceCandidate:e.connection.local.id}),b&&t.push({statsSample:S,type:wt.Server,reason:St.ServerIssue,iceCandidate:e.connection.remote.id}),E&&t.push({statsSample:S,type:wt.Network,reason:St.InboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),w&&t.push({statsSample:S,type:wt.Network,reason:St.NetworkMediaSyncFailure,iceCandidate:e.connection.local.id}),t}}class Gt extends Ht{#d;constructor(e={}){super(),this.#d=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,a=i-s,c=Math.round(100*a/o),d={correctedSamplesPct:c};c>this.#d&&r.push({statsSample:d,type:wt.Network,reason:St.NetworkMediaSyncFailure,ssrc:e.ssrc})})),r):r}}class Yt extends Ht{#s;#o;constructor(e={}){super(),this.#s=e.highPacketLossThresholdPct??5,this.#o=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=d/r.length,l=s-o,p=a.packetsLost-a.lastPacketsLost,h=l&&p?Math.round(100*p/(l+p)):0,f=h>this.#s,m=u>=this.#o,g=!f&&m||m||f,v={rtt:c,avgJitter:u,packetLossPct:h};return f&&m&&t.push({statsSample:v,type:wt.Network,reason:St.OutboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),g&&t.push({statsSample:v,type:wt.Network,reason:St.OutboundNetworkQuality,iceCandidate:e.connection.local.id}),t}}class $t extends Ht{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:wt.CPU,reason:St.EncoderCPUThrottling,ssrc:e.ssrc}),"bandwidth"===e.qualityLimitationReason&&r.push({statsSample:i,type:wt.Network,reason:St.OutboundNetworkThroughput,ssrc:e.ssrc}))})),r):r}}class Jt extends Ht{UNKNOWN_DECODER="unknown";#u={};performDetection(e){return this.processData(e)}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:r}=e;super.performPrevStatsCleanup({...e,cleanupCallback:()=>{delete this.#u[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:wt.Stream,reason:St.UnknownVideoDecoderIssue,trackIdentifier:e.track.trackIdentifier})}}else this.setLastDecoderWithIssue(r,s,void 0)})),t}setLastDecoderWithIssue(e,t,r){const n=this.#u[e]??{};void 0===r?delete n[t]:n[t]=r,this.#u[e]=n}hadLastDecoderWithIssue(e,t){const r=this.#u[e];return(r&&r[t])===this.UNKNOWN_DECODER}}const Kt=e=>e.reduce(((e,t)=>e+t),0)/e.length,Qt=(e,t,r=30)=>{const n=[];for(let r=1;r<t.length-1;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)(Kt(e),e);return Math.sqrt(t)})(n)>r},Zt=(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 Xt extends Ht{#l;#p;#h;constructor(e={}){super(),this.#l=e.avgFreezeDurationThresholdMs??1e3,this.#p=e.frozenDurationThresholdPct??30,this.#h=e.minMosQuality??Ct.BAD}performDetection(e){const t=e.networkScores.inbound;return void 0!==t&&t<=this.#h?[]: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(Zt(t.ssrc,[r[r.length-1],e]))return;if(Qt(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.#p||o>this.#l?{ssrc:t.ssrc,avgFreezeDurationMs:o,frozenDurationPct:a}:void 0})).filter((e=>void 0!==e));return n.length>0&&(t.push({type:wt.Stream,reason:St.FrozenVideoTrack,statsSample:{ssrcs:n.map((e=>e.ssrc))}}),this.deleteLastProcessedStats(e.connection.id)),t}}class er extends Ht{#f;#m;#h;constructor(e={}){super(e),this.#f=e.volatilityThreshold??8,this.#m=e.affectedStreamsPercentThreshold??30,this.#h=e.minMosQuality??Ct.BAD}performDetection(e){return[...this.getAllLastProcessedStats(e.connection.id),e].find((e=>void 0!==e.networkScores.inbound&&e.networkScores.inbound<=this.#h))?[]: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(Zt(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(Qt(e.ssrc,r))return;const n=(e=>{if(0===e.length)throw new Error("Cannot calculate volatility for empty array");const t=Kt(e);return e.reduce(((e,r)=>e+Math.abs(r-t)),0)/e.length*100/t})(t);return n>this.#f?{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.#m&&(t.push({type:wt.CPU,reason:St.DecoderCPUThrottling,statsSample:{affectedStreamsPercent:i,throtthedStreams:n}}),this.deleteLastProcessedStats(e.connection.id)),t}}const tr=e=>"closed"===e.iceConnectionState||"closed"===e.connectionState,rr=(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 nr{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(!tr(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 ir{prevStats=new Map;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(!tr(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()}),Vt({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=rr(e,r,"bytesReceived"),e.packetRate=rr(e,r,"packetsReceived")})),e.audio.outbound.forEach((e=>{const r=t.audio.outbound.find((({id:t})=>t===e.id));e.bitrate=rr(e,r,"bytesSent"),e.packetRate=rr(e,r,"packetsSent")})),e.video.inbound.forEach((e=>{const r=t.video.inbound.find((({id:t})=>t===e.id));e.bitrate=rr(e,r,"bytesReceived"),e.packetRate=rr(e,r,"packetsReceived")})),e.video.outbound.forEach((e=>{const r=t.video.outbound.find((({id:t})=>t===e.id));e.bitrate=rr(e,r,"bytesSent"),e.packetRate=rr(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 sr extends Ht{#g=new Map;#v;#y;constructor(e={}){super(),this.#v=e.timeoutMs??15e3,this.#y=e.steps??3}performDetection(e){return this.processData(e)}processData(e){const t=[],r=[...this.getAllLastProcessedStats(e.connection.id),e];if(r.length<this.#y)return t;const n=r.slice(-this.#y),i=n.map((e=>e.video.inbound)),s=n.map((e=>e.audio.inbound));return t.push(...this.detectMissingData(s,wt.Stream,St.MissingAudioStreamData)),t.push(...this.detectMissingData(i,wt.Stream,St.MissingVideoStreamData)),new Set(this.#g.keys()).forEach((e=>{const t=this.#g.get(e);t&&Date.now()-t>this.#v&&this.removeMarkedIssue(e)})),t}detectMissingData(e,t,r){const n=[],i=e.pop(),s=sr.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(!sr.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.#g.get(e);return(!r||t-r>this.#v)&&(this.#g.set(e,t),!0)}removeMarkedIssue(e){this.#g.delete(e)}}class or{eventEmitter;#_=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;autoAddPeerConnections;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new Ut,e.onIssues&&this.eventEmitter.on(Et.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(Et.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new $t,new zt,new Yt,new Gt,new qt,new Jt,new Xt,new er,new sr],this.networkScoresCalculator=e.networkScoresCalculator??new Wt,this.compositeStatsParser=e.compositeStatsParser??new nr({statsParser:new ir({ignoreSSRCList:e.ignoreSSRCList,logger:this.logger})}),this.statsReporter=e.statsReporter??new Bt({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.autoAddPeerConnections=e.autoAddPeerConnections??!0,this.autoAddPeerConnections&&this.wrapRTCPeerConnection(),this.statsReporter.on(Bt.STATS_REPORT_READY_EVENT,(e=>{const t=this.calculateNetworkScores(e.stats);this.detectIssues({data:e.stats},t)})),this.statsReporter.on(Bt.STATS_REPORTS_PARSED,(t=>{const r={timeTaken:t.timeTaken,ts:Date.now()};e.onStats&&e.onStats(t.reportItems),this.eventEmitter.emit(Et.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(Et.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(Et.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}}Error;const ar=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0}],cr=({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]=cr({from:e[r],seen:t.slice(),forceEnumerable:n}):i[r]=s);for(const{property:t,enumerable:r}of ar)"string"==typeof e[t]&&Object.defineProperty(i,t,{value:e[t],enumerable:!!n||r,configurable:!0,writable:!0});return i};var dr,ur,lr,pr=e=>"object"==typeof e&&null!==e?cr({from:e,seen:[],forceEnumerable:!0}):"function"==typeof e?`[Function: ${e.name||"anonymous"}]`:e;dr=new WeakMap,ur=new WeakMap,lr=new WeakMap;var hr=new class{constructor(){dr.set(this,void 0),ur.set(this,void 0),lr.set(this,void 0)}get meta(){return{peerId:c(this,dr,"f"),channelId:c(this,ur,"f"),appId:c(this,lr,"f")}}setPeerId(e){d(this,dr,e,"f")}setChannelId(e){d(this,ur,e,"f")}setAppId(e){d(this,lr,e,"f")}clear(){d(this,dr,void 0,"f"),d(this,ur,void 0,"f"),d(this,lr,void 0,"f")}};const fr="channel.join",mr="channel.getPeers",gr="channel.triggerStateEvent",vr="peer.updateAppData",yr="channel.confirmActivity",_r="channel.getAudioObserverProducer",br="peer.changeProducePermissions",Er="peer.addProducePermissions",wr="peer.removeProducePermissions",Sr="peer.ping",Cr="channel-event",Pr="peer-joined",Tr="peer-left",kr="channel-activity-confirmation-required",Rr="channel-activity-confirmation-acquired",Ir="channel-activity-confirmation-expired",Dr="channel-rejoin-required",Ar="devices-list-updated",Or="transport-connection-timeout",Nr="track-force-closed",Mr="track-failed",Lr="active-speaker-changed",xr="channel-state-inconsistent",Fr="connection-lost",jr="connection-restored",Ur="forced-disconnect",Br="reject-unauthorized",Vr="denoiser-initializing",Wr="channel-state-synced",Hr="denoiser-enabled",qr="denoiser-disabled",zr="denoiser-fallback",Gr="denoiser-failed",Yr="volume-changed",$r={trackProduced:"track-produced",trackUnproduced:"track-unproduced",trackPaused:"track-paused",trackResumed:"track-resumed",trackClosed:"track-closed",trackReopened:"track-reopened",trackFailed:"track-failed"},Jr="media-published",Kr="media-unpublished",Qr="publisher-paused",Zr="publisher-resumed",Xr="track-start",en="track-end",tn="track-paused",rn="track-resumed",nn="track-failed",sn="app-data-updated",on="produce-permissions-changed",an="groups-changed",cn="peer.newProducer",dn="producer.close",un="producer.pause",ln="producer.resume",pn="producer.setMaxSpatialLayer",hn="producer.requestMaxSpatialLayer",fn="consumer.create",mn="dataConsumer.create",gn="consumer.close",vn="consumer.pause",yn="consumer.resume",_n="consumer.changeConsumerPreferredLayers",bn="consumer.requestKeyFrame",En="transport.create",wn="transport.connect",Sn="transport.produce",Cn="transport.produceData",Pn="transport.connectionTimeout",Tn="transport.getIceParameters",kn=[En,wn,Sn,Cn,Tn,dn,un,ln,vn,yn,fn,gn,Sr],Rn="socket-state",In="transport-state";class Dn extends Error{constructor(e,t,r){super(e),this.errorCode=null!=t?t:"unknown_error",this.meta=r}}class An extends Dn{constructor(e,t){super(e,null!=t?t:"unsupported_error")}}An.UNSUPPORTED_DEVICE_CODE="unsupported_device_error",An.UNSUPPORTED_OPERATION_CODE="unsupported_operation_error";const On=e=>{let t;try{t=JSON.stringify(e)}catch(e){throw new Error("Invalid appData")}if(!((new TextEncoder).encode(t).length<=2048))throw new Error("Maximum size appData reached")};function Nn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Mn(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=Nn(n)&&Nn(s);(o&&!Mn(n,s)||!o&&n!==s)&&(i=!1)})),i}function Ln(e,t,r=!1){let n=null;return function(...i){return a(this,void 0,void 0,(function*(){const s=r&&!n;"number"==typeof n&&clearTimeout(n),n=setTimeout((()=>a(this,void 0,void 0,(function*(){n=null,r||(yield e.apply(this,i))}))),t),s&&(yield e.apply(this,i))}))}}var xn={exports:{}},Fn=p(xn.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}}));const jn=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:[]},Un=e=>["video/vp9","vp9"].includes(e.toLowerCase());class Bn{sleepMs(e){return a(this,void 0,void 0,(function*(){yield new Promise((t=>setTimeout(t,e)))}))}now(){return new Date(Date.now())}}const Vn=new Bn,Wn=(e,...t)=>a(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:pr(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 Vn.sleepMs(Math.min(e,null!==(s=t.maxBackoffDelayMs)&&void 0!==s?s:e))}}}throw null!=c?c:new Error("retryAsync logic failed")}));var Hn,qn,zn,Gn,Yn;!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.ChannelStateSynchronizer="ChannelStateSynchronizer",e.ChannelStateSyncEventHandler="ChannelStateSyncEventHandler",e.WebRTCIssueDetector="WebRTCIssueDetector",e.LoggerFactory="LoggerFactory",e.MediaStreamTrackManager="MediaStreamTrackManager",e.SocketIO="SocketIO",e.LoadBalancerApiClient="LoadBalancerApiClient",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"}(Hn||(Hn={})),function(e){e.P2P="p2p",e.Common="common"}(qn||(qn={})),function(e){e.Camera="camera",e.CameraPreview="camera-preview",e.Microphone="microphone",e.MicrophonePreview="microphone-preview",e.ScreenVideo="screen-video",e.ScreenAudio="screen-audio",e.CustomVideo="custom-video",e.CustomAudio="custom-audio",e.Unknown="unknown"}(zn||(zn={})),function(e){e.NotFoundError="NotFoundError",e.NoDevices="NoDevices",e.DeviceIsBusy="DeviceIsBusy",e.NotAllowedError="NotAllowedError",e.RequestDevicesUnknownError="RequestDevicesUnknownError"}(Gn||(Gn={})),function(e){e.Connect="connect",e.Connected="connected",e.ConnectError="connect_error",e.Reconnect="reconnect",e.Reconnecting="reconnecting",e.Reconnected="reconnected",e.ReconnectAttempt="reconnect_attempt",e.ReconnectFailed="reconnect_failed",e.ReconnectError="reconnect_error",e.NeedToJoinFirst="need_to_join_first",e.Disconnect="disconnect",e.Disconnected="disconnected",e.Error="error",e.State="state",e.BufferingStart="buffering_start",e.BufferingEnd="buffering_end"}(Yn||(Yn={}));let $n=class{constructor(){this.isJoined=!1,this.isChannelJoining=!1}reset(){this.appId=void 0,this.channelId=void 0}};function Jn(){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 Kn(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)}}$n=i([at()],$n);function Qn(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):Xn(n,i)}function Zn(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()+ti(s)+ti(i)}function Xn(e,t){return{lo:0|e,hi:0|t}}function ei(e,t){return t=~t,e?e=1+~e:t+=1,Xn(e,t)}const ti=e=>{const t=String(e);return"0000000".slice(t.length)+t};function ri(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 ni(){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 ii=si();function si(){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()),oi(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),ai(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),oi(e),Qn(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),ai(e),Qn(e)),dec:(e,t)=>function(e,t){let r=Xn(e,t);const n=2147483648&r.hi;n&&(r=ei(r.lo,r.hi));const i=Zn(r.lo,r.hi);return n?"-"+i:i}(e,t),uDec:(e,t)=>Zn(e,t)}}function oi(e){if(!/^-?[0-9]+$/.test(e))throw new Error("invalid int64: "+e)}function ai(e){if(!/^[0-9]+$/.test(e))throw new Error("invalid uint64: "+e)}const ci=Symbol.for("@bufbuild/protobuf/text-encoding");function di(){if(null==globalThis[ci]){const e=new globalThis.TextEncoder,t=new globalThis.TextDecoder;globalThis[ci]={encodeUtf8:t=>e.encode(t),decodeUtf8:e=>t.decode(e),checkUtf8(e){try{return encodeURIComponent(e),!0}catch(e){return!1}}}}return globalThis[ci]}var ui;!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"}(ui||(ui={}));const li=34028234663852886e22,pi=-34028234663852886e22;class hi{constructor(e=di().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(gi(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return mi(e),ri(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>li||e<pi))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){gi(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){mi(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return mi(e),ri(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),r=new DataView(t.buffer),n=ii.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=ii.uEnc(e);return r.setInt32(0,n.lo,!0),r.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=ii.enc(e);return Kn(t.lo,t.hi,this.buf),this}sint64(e){const t=ii.enc(e),r=t.hi>>31;return Kn(t.lo<<1^r,(t.hi<<1|t.lo>>>31)^r,this.buf),this}uint64(e){const t=ii.uEnc(e);return Kn(t.lo,t.hi,this.buf),this}}class fi{constructor(e,t=di().decodeUtf8){this.decodeUtf8=t,this.varint64=Jn,this.uint32=ni,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 ui.Varint:for(;128&this.buf[this.pos++];);break;case ui.Bit64:this.pos+=4;case ui.Bit32:this.pos+=4;break;case ui.LengthDelimited:let r=this.uint32();this.pos+=r;break;case ui.StartGroup:for(;;){const[e,r]=this.tag();if(r===ui.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 ii.dec(...this.varint64())}uint64(){return ii.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),r=-(1&e);return e=(e>>>1|(1&t)<<31)^r,t=t>>>1^r,ii.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 ii.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ii.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 mi(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 gi(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 vi={encode:(e,t=new hi)=>(0!==e.time&&t.uint32(8).int64(e.time),t),decode(e,t){const r=e instanceof fi?e:new fi(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=yi(r.int64());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({time:_i(e.time)?globalThis.Number(e.time):0}),toJSON(e){const t={};return 0!==e.time&&(t.time=Math.round(e.time)),t},create:e=>vi.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 yi(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 _i(e){return null!=e}var bi;function Ei(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 wi={encode:(e,t=new hi)=>(Object.entries(e.fields).forEach((([e,r])=>{void 0!==r&&Si.encode({key:e,value:r},t.uint32(10).fork()).join()})),t),decode(e,t){const r=e instanceof fi?e:new fi(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=Si.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:Ti(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 Si={encode:(e,t=new hi)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&Ci.encode(Ci.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof fi?e:new fi(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=Ci.unwrap(Ci.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:ki(e.key)?globalThis.String(e.key):"",value:ki(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=>Si.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 Ci={encode:(e,t=new hi)=>(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&&Pi.encode(Pi.wrap(e.listValue),t.uint32(50).fork()).join(),t),decode(e,t){const r=e instanceof fi?e:new fi(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=Pi.unwrap(Pi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({nullValue:ki(e.nullValue)?Ei(e.nullValue):void 0,numberValue:ki(e.numberValue)?globalThis.Number(e.numberValue):void 0,stringValue:ki(e.stringValue)?globalThis.String(e.stringValue):void 0,boolValue:ki(e.boolValue)?globalThis.Boolean(e.boolValue):void 0,structValue:Ti(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=>Ci.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 Pi={encode(e,t=new hi){for(const r of e.values)Ci.encode(Ci.wrap(r),t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof fi?e:new fi(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(Ci.unwrap(Ci.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=>Pi.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 Ti(e){return"object"==typeof e&&null!==e}function ki(e){return null!=e}const Ri={encode:(e,t=new hi)=>(Object.entries(e.event).forEach((([e,r])=>{void 0!==r&&Ii.encode({key:e,value:r},t.uint32(10).fork()).join()})),t),decode(e,t){const r=e instanceof fi?e:new fi(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=Ii.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=>({event:Di(e.event)?Object.entries(e.event).reduce(((e,[t,r])=>(e[t]=r,e)),{}):{}}),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=>Ri.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 Ii={encode:(e,t=new hi)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&Ci.encode(Ci.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof fi?e:new fi(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=Ci.unwrap(Ci.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:Ai(e.key)?globalThis.String(e.key):"",value:Ai(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=>Ii.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 Di(e){return"object"==typeof e&&null!==e}function Ai(e){return null!=e}var Oi,Ni;function Mi(e){switch(e){case 0:case"PEER_GROUP_UNSPECIFIED":return Oi.PEER_GROUP_UNSPECIFIED;case 1:case"PEER_GROUP_MODERATOR":return Oi.PEER_GROUP_MODERATOR;case 2:case"PEER_GROUP_USER":return Oi.PEER_GROUP_USER;default:return Oi.UNRECOGNIZED}}function Li(e){switch(e){case Oi.PEER_GROUP_UNSPECIFIED:return"PEER_GROUP_UNSPECIFIED";case Oi.PEER_GROUP_MODERATOR:return"PEER_GROUP_MODERATOR";case Oi.PEER_GROUP_USER:return"PEER_GROUP_USER";case Oi.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function xi(e){switch(e){case 0:case"PRODUCER_LABEL_UNSPECIFIED":return Ni.PRODUCER_LABEL_UNSPECIFIED;case 1:case"PRODUCER_LABEL_CAMERA":return Ni.PRODUCER_LABEL_CAMERA;case 2:case"PRODUCER_LABEL_MICROPHONE":return Ni.PRODUCER_LABEL_MICROPHONE;case 3:case"PRODUCER_LABEL_SCREEN_VIDEO":return Ni.PRODUCER_LABEL_SCREEN_VIDEO;case 4:case"PRODUCER_LABEL_SCREEN_AUDIO":return Ni.PRODUCER_LABEL_SCREEN_AUDIO;case 5:case"PRODUCER_LABEL_CUSTOM_VIDEO":return Ni.PRODUCER_LABEL_CUSTOM_VIDEO;case 6:case"PRODUCER_LABEL_CUSTOM_AUDIO":return Ni.PRODUCER_LABEL_CUSTOM_AUDIO;case 7:case"PRODUCER_LABEL_UNKNOWN":return Ni.PRODUCER_LABEL_UNKNOWN;default:return Ni.UNRECOGNIZED}}function Fi(e){switch(e){case Ni.PRODUCER_LABEL_UNSPECIFIED:return"PRODUCER_LABEL_UNSPECIFIED";case Ni.PRODUCER_LABEL_CAMERA:return"PRODUCER_LABEL_CAMERA";case Ni.PRODUCER_LABEL_MICROPHONE:return"PRODUCER_LABEL_MICROPHONE";case Ni.PRODUCER_LABEL_SCREEN_VIDEO:return"PRODUCER_LABEL_SCREEN_VIDEO";case Ni.PRODUCER_LABEL_SCREEN_AUDIO:return"PRODUCER_LABEL_SCREEN_AUDIO";case Ni.PRODUCER_LABEL_CUSTOM_VIDEO:return"PRODUCER_LABEL_CUSTOM_VIDEO";case Ni.PRODUCER_LABEL_CUSTOM_AUDIO:return"PRODUCER_LABEL_CUSTOM_AUDIO";case Ni.PRODUCER_LABEL_UNKNOWN:return"PRODUCER_LABEL_UNKNOWN";case Ni.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"}(Oi||(Oi={})),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"}(Ni||(Ni={}));const ji={encode(e,t=new hi){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 fi?e:new fi(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=>Mi(e))):[],producePermissions:globalThis.Array.isArray(null==e?void 0:e.producePermissions)?e.producePermissions.map((e=>xi(e))):[],changedProducePermissions:globalThis.Array.isArray(null==e?void 0:e.changedProducePermissions)?e.changedProducePermissions.map((e=>xi(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=>Li(e)))),(null===(r=e.producePermissions)||void 0===r?void 0:r.length)&&(i.producePermissions=e.producePermissions.map((e=>Fi(e)))),(null===(n=e.changedProducePermissions)||void 0===n?void 0:n.length)&&(i.changedProducePermissions=e.changedProducePermissions.map((e=>Fi(e)))),i},create:e=>ji.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 Ui={encode:(e,t=new hi)=>(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 fi?e:new fi(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=Bi(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:Vi(e.seconds)?globalThis.Number(e.seconds):0,nanos:Vi(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=>Ui.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 Bi(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 Vi(e){return null!=e}var Wi;function Hi(e){switch(e){case 0:case"PRODUCER_KIND_UNSPECIFIED":return Wi.PRODUCER_KIND_UNSPECIFIED;case 1:case"PRODUCER_KIND_AUDIO":return Wi.PRODUCER_KIND_AUDIO;case 2:case"PRODUCER_KIND_VIDEO":return Wi.PRODUCER_KIND_VIDEO;default:return Wi.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"}(Wi||(Wi={}));const qi={encode(e,t=new hi){""!==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)Ci.encode(Ci.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 fi?e:new fi(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(Ci.unwrap(Ci.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:zi(e.id)?globalThis.String(e.id):"",kind:zi(e.kind)?Hi(e.kind):0,label:zi(e.label)?xi(e.label):0,peerId:zi(e.peerId)?globalThis.String(e.peerId):"",paused:!!zi(e.paused)&&globalThis.Boolean(e.paused),encodings:globalThis.Array.isArray(null==e?void 0:e.encodings)?[...e.encodings]:[],maxSpatialLayer:zi(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 Wi.PRODUCER_KIND_UNSPECIFIED:return"PRODUCER_KIND_UNSPECIFIED";case Wi.PRODUCER_KIND_AUDIO:return"PRODUCER_KIND_AUDIO";case Wi.PRODUCER_KIND_VIDEO:return"PRODUCER_KIND_VIDEO";case Wi.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.kind)),0!==e.label&&(r.label=Fi(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=>qi.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 zi(e){return null!=e}var Gi;function Yi(e){switch(e){case 0:case"PEER_ROLE_UNSPECIFIED":return Gi.PEER_ROLE_UNSPECIFIED;case 1:case"PEER_ROLE_HOST":return Gi.PEER_ROLE_HOST;case 2:case"PEER_ROLE_AUDIENCE":return Gi.PEER_ROLE_AUDIENCE;default:return Gi.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"}(Gi||(Gi={}));const $i={encode(e,t=new hi){""!==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)qi.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&&Ji.encode({key:e,value:r},t.uint32(66).fork()).join()})),0!==e.role&&t.uint32(72).int32(e.role),void 0!==e.loginDate&&Ui.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 fi?e:new fi(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(qi.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=Ji.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=Ki(Ui.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=>({id:Xi(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=>qi.fromJSON(e))):[],uid:Xi(e.uid)?globalThis.String(e.uid):"",appId:Xi(e.appId)?globalThis.String(e.appId):"",appData:Zi(e.appData)?Object.entries(e.appData).reduce(((e,[t,r])=>(e[t]=r,e)),{}):{},role:Xi(e.role)?Yi(e.role):0,loginDate:Xi(e.loginDate)?Qi(e.loginDate):void 0,groups:globalThis.Array.isArray(null==e?void 0:e.groups)?e.groups.map((e=>Mi(e))):[],producePermissions:globalThis.Array.isArray(null==e?void 0:e.producePermissions)?e.producePermissions.map((e=>xi(e))):[]}),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=>qi.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 Gi.PEER_ROLE_UNSPECIFIED:return"PEER_ROLE_UNSPECIFIED";case Gi.PEER_ROLE_HOST:return"PEER_ROLE_HOST";case Gi.PEER_ROLE_AUDIENCE:return"PEER_ROLE_AUDIENCE";case Gi.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=>Li(e)))),(null===(i=e.producePermissions)||void 0===i?void 0:i.length)&&(s.producePermissions=e.producePermissions.map((e=>Fi(e)))),s},create:e=>$i.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=>qi.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 Ji={encode:(e,t=new hi)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&Ci.encode(Ci.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof fi?e:new fi(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=Ci.unwrap(Ci.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:Xi(e.key)?globalThis.String(e.key):"",value:Xi(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 Ki(e){let t=1e3*(e.seconds||0);return t+=(e.nanos||0)/1e6,new globalThis.Date(t)}function Qi(e){return e instanceof globalThis.Date?e:"string"==typeof e?new globalThis.Date(e):Ki(Ui.fromJSON(e))}function Zi(e){return"object"==typeof e&&null!==e}function Xi(e){return null!=e}const es={encode(e,t=new hi){for(const r of e.peers)$i.encode(r,t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof fi?e:new fi(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($i.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=>$i.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=>$i.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=>$i.fromPartial(e))))||[],r}};const ts={encode:(e,t=new hi)=>(""!==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 fi?e:new fi(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:is(e.id)?globalThis.String(e.id):"",paused:!!is(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=>ts.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 rs={encode(e,t=new hi){""!==e.id&&t.uint32(10).string(e.id);for(const r of e.producers)ts.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 fi?e:new fi(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(ts.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:is(e.id)?globalThis.String(e.id):"",producers:globalThis.Array.isArray(null==e?void 0:e.producers)?e.producers.map((e=>ts.fromJSON(e))):[],appDataHash:is(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=>ts.toJSON(e)))),void 0!==e.appDataHash&&(r.appDataHash=e.appDataHash),r},create:e=>rs.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=>ts.fromPartial(e))))||[],i.appDataHash=null!==(n=e.appDataHash)&&void 0!==n?n:void 0,i}};const ns={encode(e,t=new hi){for(const r of e.peers)rs.encode(r,t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof fi?e:new fi(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(rs.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=>rs.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=>rs.toJSON(e)))),r},create:e=>ns.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=>rs.fromPartial(e))))||[],r}};function is(e){return null!=e}var ss;function os(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 as(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 cs={encode:(e,t=new hi)=>(0!==e.eventType&&t.uint32(8).int32(e.eventType),void 0!==e.channelState&&es.encode(e.channelState,t.uint32(18).fork()).join(),void 0!==e.channelStateShort&&ns.encode(e.channelStateShort,t.uint32(26).fork()).join(),void 0!==e.channelActivityConfirmationTime&&vi.encode(e.channelActivityConfirmationTime,t.uint32(34).fork()).join(),void 0!==e.channelManagementEvent&&Ri.encode(e.channelManagementEvent,t.uint32(42).fork()).join(),void 0!==e.channelProducePermissions&&ji.encode(e.channelProducePermissions,t.uint32(50).fork()).join(),void 0!==e.peer&&$i.encode(e.peer,t.uint32(58).fork()).join(),t),decode(e,t){const r=e instanceof fi?e:new fi(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=es.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.channelStateShort=ns.decode(r,r.uint32());continue;case 4:if(34!==e)break;i.channelActivityConfirmationTime=vi.decode(r,r.uint32());continue;case 5:if(42!==e)break;i.channelManagementEvent=Ri.decode(r,r.uint32());continue;case 6:if(50!==e)break;i.channelProducePermissions=ji.decode(r,r.uint32());continue;case 7:if(58!==e)break;i.peer=$i.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({eventType:ds(e.eventType)?os(e.eventType):0,channelState:ds(e.channelState)?es.fromJSON(e.channelState):void 0,channelStateShort:ds(e.channelStateShort)?ns.fromJSON(e.channelStateShort):void 0,channelActivityConfirmationTime:ds(e.channelActivityConfirmationTime)?vi.fromJSON(e.channelActivityConfirmationTime):void 0,channelManagementEvent:ds(e.channelManagementEvent)?Ri.fromJSON(e.channelManagementEvent):void 0,channelProducePermissions:ds(e.channelProducePermissions)?ji.fromJSON(e.channelProducePermissions):void 0,peer:ds(e.peer)?$i.fromJSON(e.peer):void 0}),toJSON(e){const t={};return 0!==e.eventType&&(t.eventType=as(e.eventType)),void 0!==e.channelState&&(t.channelState=es.toJSON(e.channelState)),void 0!==e.channelStateShort&&(t.channelStateShort=ns.toJSON(e.channelStateShort)),void 0!==e.channelActivityConfirmationTime&&(t.channelActivityConfirmationTime=vi.toJSON(e.channelActivityConfirmationTime)),void 0!==e.channelManagementEvent&&(t.channelManagementEvent=Ri.toJSON(e.channelManagementEvent)),void 0!==e.channelProducePermissions&&(t.channelProducePermissions=ji.toJSON(e.channelProducePermissions)),void 0!==e.peer&&(t.peer=$i.toJSON(e.peer)),t},create:e=>cs.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?es.fromPartial(e.channelState):void 0,r.channelStateShort=void 0!==e.channelStateShort&&null!==e.channelStateShort?ns.fromPartial(e.channelStateShort):void 0,r.channelActivityConfirmationTime=void 0!==e.channelActivityConfirmationTime&&null!==e.channelActivityConfirmationTime?vi.fromPartial(e.channelActivityConfirmationTime):void 0,r.channelManagementEvent=void 0!==e.channelManagementEvent&&null!==e.channelManagementEvent?Ri.fromPartial(e.channelManagementEvent):void 0,r.channelProducePermissions=void 0!==e.channelProducePermissions&&null!==e.channelProducePermissions?ji.fromPartial(e.channelProducePermissions):void 0,r.peer=void 0!==e.peer&&null!==e.peer?$i.fromPartial(e.peer):void 0,r}};function ds(e){return null!=e}const us={encode:(e,t=new hi)=>(""!==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 fi?e:new fi(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:ls(e.id)?globalThis.String(e.id):"",peerId:ls(e.peerId)?globalThis.String(e.peerId):"",producerPeerId:ls(e.producerPeerId)?globalThis.String(e.producerPeerId):"",spatialLayer:ls(e.spatialLayer)?globalThis.Number(e.spatialLayer):void 0,temporalLayer:ls(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=>us.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 ls(e){return null!=e}const ps={encode:(e,t=new hi)=>(""!==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 fi?e:new fi(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:hs(e.producerId)?globalThis.String(e.producerId):"",spatialLayer:hs(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=>ps.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 hs(e){return null!=e}var fs,ms;function gs(e){switch(e){case 0:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED":return fs.TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED;case 1:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS":return fs.TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS;case 2:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE":return fs.TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE;default:return fs.UNRECOGNIZED}}function vs(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"}(fs||(fs={})),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 ys={encode:(e,t=new hi)=>(""!==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 fi?e:new fi(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:_s(e.transportId)?globalThis.String(e.transportId):"",timeout:_s(e.timeout)?globalThis.Number(e.timeout):0,direction:_s(e.direction)?vs(e.direction):0,reason:_s(e.reason)?gs(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 fs.TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED";case fs.TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS";case fs.TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE";case fs.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.reason)),t},create:e=>ys.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 _s(e){return null!=e}var bs;function Es(e){switch(e){case 0:case"MEDIA_EVENT_TYPE_UNSPECIFIED":return bs.MEDIA_EVENT_TYPE_UNSPECIFIED;case 1:case"MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT":return bs.MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT;case 2:case"MEDIA_EVENT_TYPE_PRODUCER_CREATED":return bs.MEDIA_EVENT_TYPE_PRODUCER_CREATED;case 3:case"MEDIA_EVENT_TYPE_PRODUCER_PAUSED":return bs.MEDIA_EVENT_TYPE_PRODUCER_PAUSED;case 4:case"MEDIA_EVENT_TYPE_PRODUCER_RESUMED":return bs.MEDIA_EVENT_TYPE_PRODUCER_RESUMED;case 5:case"MEDIA_EVENT_TYPE_PRODUCER_CLOSED":return bs.MEDIA_EVENT_TYPE_PRODUCER_CLOSED;case 6:case"MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED":return bs.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED;case 7:case"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED":return bs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED;case 8:case"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED":return bs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED;case 9:case"MEDIA_EVENT_TYPE_CONSUMER_CLOSED":return bs.MEDIA_EVENT_TYPE_CONSUMER_CLOSED;case 10:case"MEDIA_EVENT_TYPE_CONSUMER_PAUSED":return bs.MEDIA_EVENT_TYPE_CONSUMER_PAUSED;case 11:case"MEDIA_EVENT_TYPE_CONSUMER_RESUMED":return bs.MEDIA_EVENT_TYPE_CONSUMER_RESUMED;case 12:case"MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED":return bs.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED;default:return bs.UNRECOGNIZED}}function ws(e){switch(e){case bs.MEDIA_EVENT_TYPE_UNSPECIFIED:return"MEDIA_EVENT_TYPE_UNSPECIFIED";case bs.MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT:return"MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT";case bs.MEDIA_EVENT_TYPE_PRODUCER_CREATED:return"MEDIA_EVENT_TYPE_PRODUCER_CREATED";case bs.MEDIA_EVENT_TYPE_PRODUCER_PAUSED:return"MEDIA_EVENT_TYPE_PRODUCER_PAUSED";case bs.MEDIA_EVENT_TYPE_PRODUCER_RESUMED:return"MEDIA_EVENT_TYPE_PRODUCER_RESUMED";case bs.MEDIA_EVENT_TYPE_PRODUCER_CLOSED:return"MEDIA_EVENT_TYPE_PRODUCER_CLOSED";case bs.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED:return"MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED";case bs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED:return"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED";case bs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED:return"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED";case bs.MEDIA_EVENT_TYPE_CONSUMER_CLOSED:return"MEDIA_EVENT_TYPE_CONSUMER_CLOSED";case bs.MEDIA_EVENT_TYPE_CONSUMER_PAUSED:return"MEDIA_EVENT_TYPE_CONSUMER_PAUSED";case bs.MEDIA_EVENT_TYPE_CONSUMER_RESUMED:return"MEDIA_EVENT_TYPE_CONSUMER_RESUMED";case bs.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED:return"MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED";case bs.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"}(bs||(bs={}));const Ss={encode:(e,t=new hi)=>(0!==e.eventType&&t.uint32(8).int32(e.eventType),void 0!==e.producer&&qi.encode(e.producer,t.uint32(18).fork()).join(),void 0!==e.consumer&&us.encode(e.consumer,t.uint32(26).fork()).join(),void 0!==e.producerSpatialLayerRequest&&ps.encode(e.producerSpatialLayerRequest,t.uint32(34).fork()).join(),void 0!==e.transportConnectionTimeout&&ys.encode(e.transportConnectionTimeout,t.uint32(42).fork()).join(),t),decode(e,t){const r=e instanceof fi?e:new fi(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=qi.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.consumer=us.decode(r,r.uint32());continue;case 4:if(34!==e)break;i.producerSpatialLayerRequest=ps.decode(r,r.uint32());continue;case 5:if(42!==e)break;i.transportConnectionTimeout=ys.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({eventType:Cs(e.eventType)?Es(e.eventType):0,producer:Cs(e.producer)?qi.fromJSON(e.producer):void 0,consumer:Cs(e.consumer)?us.fromJSON(e.consumer):void 0,producerSpatialLayerRequest:Cs(e.producerSpatialLayerRequest)?ps.fromJSON(e.producerSpatialLayerRequest):void 0,transportConnectionTimeout:Cs(e.transportConnectionTimeout)?ys.fromJSON(e.transportConnectionTimeout):void 0}),toJSON(e){const t={};return 0!==e.eventType&&(t.eventType=ws(e.eventType)),void 0!==e.producer&&(t.producer=qi.toJSON(e.producer)),void 0!==e.consumer&&(t.consumer=us.toJSON(e.consumer)),void 0!==e.producerSpatialLayerRequest&&(t.producerSpatialLayerRequest=ps.toJSON(e.producerSpatialLayerRequest)),void 0!==e.transportConnectionTimeout&&(t.transportConnectionTimeout=ys.toJSON(e.transportConnectionTimeout)),t},create:e=>Ss.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?qi.fromPartial(e.producer):void 0,r.consumer=void 0!==e.consumer&&null!==e.consumer?us.fromPartial(e.consumer):void 0,r.producerSpatialLayerRequest=void 0!==e.producerSpatialLayerRequest&&null!==e.producerSpatialLayerRequest?ps.fromPartial(e.producerSpatialLayerRequest):void 0,r.transportConnectionTimeout=void 0!==e.transportConnectionTimeout&&null!==e.transportConnectionTimeout?ys.fromPartial(e.transportConnectionTimeout):void 0,r}};function Cs(e){return null!=e}const Ps={encode:(e,t=new hi)=>(0!==e.id&&t.uint32(8).int32(e.id),void 0!==e.channelEvent&&cs.encode(e.channelEvent,t.uint32(18).fork()).join(),void 0!==e.mediaEvent&&Ss.encode(e.mediaEvent,t.uint32(26).fork()).join(),t),decode(e,t){const r=e instanceof fi?e:new fi(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=cs.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.mediaEvent=Ss.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({id:Ts(e.id)?globalThis.Number(e.id):0,channelEvent:Ts(e.channelEvent)?cs.fromJSON(e.channelEvent):void 0,mediaEvent:Ts(e.mediaEvent)?Ss.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=cs.toJSON(e.channelEvent)),void 0!==e.mediaEvent&&(t.mediaEvent=Ss.toJSON(e.mediaEvent)),t},create:e=>Ps.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?cs.fromPartial(e.channelEvent):void 0,r.mediaEvent=void 0!==e.mediaEvent&&null!==e.mediaEvent?Ss.fromPartial(e.mediaEvent):void 0,r}};function Ts(e){return null!=e}var ks,Rs,Is,Ds,As,Os,Ns,Ms;let Ls=class{constructor(e){ks.set(this,[]),Rs.set(this,!1),Is.set(this,!1),Ds.set(this,void 0),As.set(this,void 0),Os.set(this,new Map),Ns.set(this,void 0),Ms.set(this,new Set),d(this,Ns,e("EventsQueue"),"f")}setMediaEventHandler(e){d(this,Ds,e,"f"),c(this,Ns,"f").info("Media event handler set",{case:"EventsQueue"})}setChannelEventHandler(e){d(this,As,e,"f"),c(this,Ns,"f").info("Channel event handler set",{case:"EventsQueue"})}subscribe(e){d(this,Ms,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=Ps.decode(n);i.id&&(c(this,Ms,"f").has(i.id)&&c(this,Ns,"f").warn("Received duplicate message",{case:"EventsQueue",lastReceivedMsgId:t,currentReceivedMsgId:i.id}),i.id>t+1&&c(this,Ns,"f").warn("Received out of order message",{case:"EventsQueue",lastReceivedMsgId:t,currentReceivedMsgId:i.id})),c(this,Ms,"f").add(i.id),t=i.id,this.push(i)}catch(e){c(this,Ns,"f").error("Failed to parse channel message",{error:pr(e),case:"EventsQueue"})}},n=()=>{e.removeListener("message",r),e.removeListener("close",n)};e.on("close",n),e.on("message",r),c(this,Ns,"f").info("Subscribed to data channel",{case:"EventsQueue"})}push(e){c(this,ks,"f").push(e),this.process()}process(){return a(this,void 0,void 0,(function*(){if(!c(this,Rs,"f")&&!c(this,Is,"f")){for(d(this,Is,!0,"f");!c(this,Rs,"f")&&c(this,ks,"f").length>0;){const e=c(this,ks,"f").shift();if(e)try{if(e.channelEvent&&c(this,As,"f")){c(this,Ns,"f").debug("Handle channel event",{case:"EventsQueue",id:e.id,type:as(e.channelEvent.eventType),event:e.channelEvent}),yield c(this,As,"f").call(this,e.channelEvent);continue}if(e.mediaEvent&&c(this,Ds,"f")){c(this,Ns,"f").debug("Handle media event",{case:"EventsQueue",id:e.id,type:ws(e.mediaEvent.eventType),event:e.mediaEvent}),yield c(this,Ds,"f").call(this,e.mediaEvent);continue}c(this,Ns,"f").warn("Received unknown message",{message:e,case:"EventsQueue"})}catch(t){c(this,Ns,"f").error("Failed to handle event",{case:"EventsQueue",id:e.id,error:pr(t)})}}d(this,Is,!1,"f"),!c(this,Rs,"f")&&c(this,ks,"f").length>0&&queueMicrotask((()=>{this.process()}))}}))}processMessageChunk(e){const t=new Uint8Array(e);if(t.length<12)return void c(this,Ns,"f").warn("Chunk too small",{case:"EventsQueue",bytesLength:t.length});const{msgId:r,index:n,total:i}=this.parseMessageChunkHeader(t),s=t.slice(12);c(this,Os,"f").has(r)||c(this,Os,"f").set(r,{msgId:r,total:i,received:[]});const o=c(this,Os,"f").get(r);if(o)return o.received[n]=s,o.msgId=r,o;c(this,Ns,"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 c(this,Os,"f").delete(e.msgId),t}pause(){d(this,Rs,!0,"f")}size(){return c(this,ks,"f").length}resume(){d(this,Rs,!1,"f"),this.process()}isMessageReceived(e){return c(this,Ms,"f").has(e)}};ks=new WeakMap,Rs=new WeakMap,Is=new WeakMap,Ds=new WeakMap,As=new WeakMap,Os=new WeakMap,Ns=new WeakMap,Ms=new WeakMap,Ls=i([at(),s(0,dt(Hn.LoggerFactory)),o("design:paramtypes",[Function])],Ls);var xs=Ls;function Fs(e){return{id:e.id,appId:e.appId,role:e.role,groups:e.groups,producePermissions:e.producePermissions}}let js=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)}};js=i([at()],js);class Us extends Dn{constructor(e,t,r){super(e,null!=t?t:"something_went_wrong",r)}}const Bs=Object.create(null);Bs.open="0",Bs.close="1",Bs.ping="2",Bs.pong="3",Bs.message="4",Bs.upgrade="5",Bs.noop="6";const Vs=Object.create(null);Object.keys(Bs).forEach((e=>{Vs[Bs[e]]=e}));const Ws={type:"error",data:"parser error"},Hs="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),qs="function"==typeof ArrayBuffer,zs=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Gs=({type:e,data:t},r,n)=>Hs&&t instanceof Blob?r?n(t):Ys(t,n):qs&&(t instanceof ArrayBuffer||zs(t))?r?n(t):Ys(new Blob([t]),n):n(Bs[e]+(t||"")),Ys=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function $s(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Js;const Ks="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Qs="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<Ks.length;e++)Qs[Ks.charCodeAt(e)]=e;const Zs="function"==typeof ArrayBuffer,Xs=(e,t)=>{if("string"!=typeof e)return{type:"message",data:to(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:eo(e.substring(1),t)};return Vs[r]?e.length>1?{type:Vs[r],data:e.substring(1)}:{type:Vs[r]}:Ws},eo=(e,t)=>{if(Zs){const r=(e=>{let t,r,n,i,s,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const d=new ArrayBuffer(o),u=new Uint8Array(d);for(t=0;t<a;t+=4)r=Qs[e.charCodeAt(t)],n=Qs[e.charCodeAt(t+1)],i=Qs[e.charCodeAt(t+2)],s=Qs[e.charCodeAt(t+3)],u[c++]=r<<2|n>>4,u[c++]=(15&n)<<4|i>>2,u[c++]=(3&i)<<6|63&s;return d})(e);return to(r,t)}return{base64:!0,data:e}},to=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,ro=String.fromCharCode(30);function no(){return new TransformStream({transform(e,t){!function(e,t){Hs&&e.data instanceof Blob?e.data.arrayBuffer().then($s).then(t):qs&&(e.data instanceof ArrayBuffer||zs(e.data))?t($s(e.data)):Gs(e,!1,(e=>{Js||(Js=new TextEncoder),t(Js.encode(e))}))}(e,(r=>{const n=r.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,n)}else{i=new Uint8Array(9);const e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(n))}e.data&&"string"!=typeof e.data&&(i[0]|=128),t.enqueue(i),t.enqueue(r)}))}})}let io;function so(e){return e.reduce(((e,t)=>e+t.length),0)}function oo(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let n=0;for(let i=0;i<t;i++)r[i]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),r}function ao(e){if(e)return function(e){for(var t in ao.prototype)e[t]=ao.prototype[t];return e}(e)}ao.prototype.on=ao.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},ao.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},ao.prototype.off=ao.prototype.removeListener=ao.prototype.removeAllListeners=ao.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<n.length;i++)if((r=n[i])===t||r.fn===t){n.splice(i,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},ao.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){n=0;for(var i=(r=r.slice(0)).length;n<i;++n)r[n].apply(this,t)}return this},ao.prototype.emitReserved=ao.prototype.emit,ao.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},ao.prototype.hasListeners=function(e){return!!this.listeners(e).length};const co="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function uo(e,...t){return t.reduce(((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t)),{})}const lo=co.setTimeout,po=co.clearTimeout;function ho(e,t){t.useNativeTimers?(e.setTimeoutFn=lo.bind(co),e.clearTimeoutFn=po.bind(co)):(e.setTimeoutFn=co.setTimeout.bind(co),e.clearTimeoutFn=co.clearTimeout.bind(co))}class fo extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class mo extends ao{constructor(e){super(),this.writable=!1,ho(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new fo(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=Xs(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}const go="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),vo={};let yo,_o=0,bo=0;function Eo(e){let t="";do{t=go[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function wo(){const e=Eo(+new Date);return e!==yo?(_o=0,yo=e):e+"."+Eo(_o++)}for(;bo<64;bo++)vo[go[bo]]=bo;let So=!1;try{So="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}const Co=So;function Po(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Co))return new XMLHttpRequest}catch(e){}if(!t)try{return new(co[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function To(){}const ko=null!=new Po({xdomain:!1}).responseType;class Ro extends ao{constructor(e,t){super(),ho(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var e;const t=uo(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const r=this.xhr=new Po(t);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{r.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var e;3===r.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(r)),4===r.readyState&&(200===r.status||1223===r.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof r.status?r.status:0)}),0))},r.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=Ro.requestsCount++,Ro.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=To,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete Ro.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(Ro.requestsCount=0,Ro.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Io);else if("function"==typeof addEventListener){addEventListener("onpagehide"in co?"pagehide":"unload",Io,!1)}function Io(){for(let e in Ro.requests)Ro.requests.hasOwnProperty(e)&&Ro.requests[e].abort()}const Do="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Ao=co.WebSocket||co.MozWebSocket,Oo="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const No={websocket:class extends mo{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,r=Oo?{}:uo(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=Oo?new Ao(e,t,r):t?new Ao(e,t):new Ao(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],n=t===e.length-1;Gs(r,this.supportsBinary,(e=>{try{this.ws.send(e)}catch(e){}n&&Do((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=wo()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!Ao}},webtransport:class extends mo{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then((()=>{this.onClose()})).catch((e=>{this.onError("webtransport error",e)})),this.transport.ready.then((()=>{this.transport.createBidirectionalStream().then((e=>{const t=function(e,t){io||(io=new TextDecoder);const r=[];let n=0,i=-1,s=!1;return new TransformStream({transform(o,a){for(r.push(o);;){if(0===n){if(so(r)<1)break;const e=oo(r,1);s=128==(128&e[0]),i=127&e[0],n=i<126?3:126===i?1:2}else if(1===n){if(so(r)<2)break;const e=oo(r,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),n=3}else if(2===n){if(so(r)<8)break;const e=oo(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){a.enqueue(Ws);break}i=s*Math.pow(2,32)+t.getUint32(4),n=3}else{if(so(r)<i)break;const e=oo(r,i);a.enqueue(Xs(s?e:io.decode(e),t)),n=0}if(0===i||i>e){a.enqueue(Ws);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),n=no();n.readable.pipeTo(e.writable),this.writer=n.writable.getWriter();const i=()=>{r.read().then((({done:e,value:t})=>{e||(this.onPacket(t),i())})).catch((e=>{}))};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then((()=>this.onOpen()))}))})))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],n=t===e.length-1;this.writer.write(r).then((()=>{n&&Do((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends mo{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}const t=e&&e.forceBase64;this.supportsBinary=ko&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",(function(){--e||t()}))),this.writable||(e++,this.once("drain",(function(){--e||t()})))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(ro),n=[];for(let e=0;e<r.length;e++){const i=Xs(r[e],t);if(n.push(i),"error"===i.type)break}return n})(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,n=new Array(r);let i=0;e.forEach(((e,s)=>{Gs(e,!1,(e=>{n[s]=e,++i===r&&t(n.join(ro))}))}))})(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=wo()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Ro(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}},Mo=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Lo=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function xo(e){const t=e,r=e.indexOf("["),n=e.indexOf("]");-1!=r&&-1!=n&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let i=Mo.exec(e||""),s={},o=14;for(;o--;)s[Lo[o]]=i[o]||"";return-1!=r&&-1!=n&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=function(e,t){const r=/\/{2,9}/g,n=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1);"/"==t.slice(-1)&&n.splice(n.length-1,1);return n}(0,s.path),s.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,n){t&&(r[t]=n)})),r}(0,s.query),s}class Fo extends ao{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=xo(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=xo(t.host).host),ho(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let e=0,n=r.length;e<n;e++){let n=r[e].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new No[e](r)}open(){let e;if(this.opts.rememberUpgrade&&Fo.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(e){let t=this.createTransport(e),r=!1;Fo.priorWebsocketSuccess=!1;const n=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",(e=>{if(!r)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Fo.priorWebsocketSuccess="websocket"===t.name,this.transport.pause((()=>{r||"closed"!==this.readyState&&(d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())}))}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}})))};function i(){r||(r=!0,d(),t.close(),t=null)}const s=e=>{const r=new Error("probe error: "+e);r.transport=t.name,i(),this.emitReserved("upgradeError",r)};function o(){s("transport closed")}function a(){s("socket closed")}function c(e){t&&e.name!==t.name&&i()}const d=()=>{t.removeListener("open",n),t.removeListener("error",s),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",n),t.once("error",s),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn((()=>{r||t.open()}),200):t.open()}onOpen(){if(this.readyState="open",Fo.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let r=0;r<this.writeBuffer.length;r++){const n=this.writeBuffer[r].data;if(n&&(e+="string"==typeof(t=n)?function(e){let t=0,r=0;for(let n=0,i=e.length;n<i;n++)t=e.charCodeAt(n),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(n++,r+=4);return r}(t):Math.ceil(1.33*(t.byteLength||t.size))),r>0&&e>this.maxPayload)return this.writeBuffer.slice(0,r);e+=2}var t;return this.writeBuffer}write(e,t,r){return this.sendPacket("message",e,t,r),this}send(e,t,r){return this.sendPacket("message",e,t,r),this}sendPacket(e,t,r,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof r&&(n=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?r():e()})):this.upgrading?r():e()),this}onError(e){Fo.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let r=0;const n=e.length;for(;r<n;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}Fo.protocol=4;const jo="function"==typeof ArrayBuffer,Uo=Object.prototype.toString,Bo="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Uo.call(Blob),Vo="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Uo.call(File);function Wo(e){return jo&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Bo&&e instanceof Blob||Vo&&e instanceof File}function Ho(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Ho(e[t]))return!0;return!1}if(Wo(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Ho(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Ho(e[t]))return!0;return!1}function qo(e){const t=[],r=e.data,n=e;return n.data=zo(r,t),n.attachments=t.length,{packet:n,buffers:t}}function zo(e,t){if(!e)return e;if(Wo(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=zo(e[n],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=zo(e[n],t));return r}return e}function Go(e,t){return e.data=Yo(e.data,t),delete e.attachments,e}function Yo(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=Yo(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Yo(e[r],t));return e}const $o=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Jo;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(Jo||(Jo={}));function Ko(e){return"[object Object]"===Object.prototype.toString.call(e)}class Qo extends ao{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===Jo.BINARY_EVENT;r||t.type===Jo.BINARY_ACK?(t.type=r?Jo.EVENT:Jo.ACK,this.reconstructor=new Zo(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Wo(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===Jo[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Jo.BINARY_EVENT||r.type===Jo.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(n,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(i)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(n,t)}else r.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!Qo.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case Jo.CONNECT:return Ko(t);case Jo.DISCONNECT:return void 0===t;case Jo.CONNECT_ERROR:return"string"==typeof t||Ko(t);case Jo.EVENT:case Jo.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===$o.indexOf(t[0]));case Jo.ACK:case Jo.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Zo{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Go(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var Xo=Object.freeze({__proto__:null,protocol:5,get PacketType(){return Jo},Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Jo.EVENT&&e.type!==Jo.ACK||!Ho(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Jo.EVENT?Jo.BINARY_EVENT:Jo.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Jo.BINARY_EVENT&&e.type!==Jo.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=qo(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}},Decoder:Qo});function ea(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const ta=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ra extends ao{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[ea(e,"open",this.onopen.bind(this)),ea(e,"packet",this.onpacket.bind(this)),ea(e,"error",this.onerror.bind(this)),ea(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(ta.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const r={type:Jo.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),r.id=e}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!n||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var r;const n=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===n)return void(this.acks[e]=t);const i=this.io.setTimeoutFn((()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))}),n);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,[null,...e])}}emitWithAck(e,...t){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((n,i)=>{t.push(((e,t)=>r?e?i(e):n(t):n(e))),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...n)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...n)),r.pending=!1,this._drainQueue()})),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Jo.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Jo.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Jo.EVENT:case Jo.BINARY_EVENT:this.onevent(e);break;case Jo.ACK:case Jo.BINARY_ACK:this.onack(e);break;case Jo.DISCONNECT:this.ondisconnect();break;case Jo.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...n){r||(r=!0,t.packet({type:Jo.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Jo.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function na(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}na.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-r:e+r}return 0|Math.min(e,this.max)},na.prototype.reset=function(){this.attempts=0},na.prototype.setMin=function(e){this.ms=e},na.prototype.setMax=function(e){this.max=e},na.prototype.setJitter=function(e){this.jitter=e};class ia extends ao{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,ho(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new na({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const n=t.parser||Xo;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Fo(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const n=ea(t,"open",(function(){r.onopen(),e&&e()})),i=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=ea(t,"error",i);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn((()=>{n(),i(new Error("timeout")),t.close()}),e);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}return this.subs.push(n),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(ea(e,"ping",this.onping.bind(this)),ea(e,"data",this.ondata.bind(this)),ea(e,"error",this.onerror.bind(this)),ea(e,"close",this.onclose.bind(this)),ea(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){Do((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new ra(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn((()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()})))}),t);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const sa={};function oa(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let n=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),n=xo(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(r&&r.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=r.source,i=r.id,s=r.path,o=sa[i]&&s in sa[i].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new ia(n,t):(sa[i]||(sa[i]=new ia(n,t)),a=sa[i]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}var aa,ca;Object.assign(oa,{Manager:ia,Socket:ra,io:oa,connect:oa});let da=class{constructor(e){this.reconnectingAttempt=0,this.isConnected=!1,this._observer=new Tt,aa.set(this,void 0),this.knownDisconnectReasonsCodes={"io server disconnect":"server.disconnect","io client disconnect":"client.disconnect","ping timeout":"ping.timeout","transport close":"transport.close","transport error":"transport.error"},ca.set(this,!1),d(this,aa,e("Socket"),"f")}get observer(){return this._observer}get id(){var e;return null===(e=this.connection)||void 0===e?void 0:e.id}connect(e,t){const r=oa(e,{multiplex:!0,randomizationFactor:.2,reconnectionDelay:1e3,reconnection:!0,transports:["polling","websocket"],upgrade:!0,rememberUpgrade:!1,auth:{token:t,apiVersion:7}});this.connection=r,this.serverUrl=e,r.on(Yn.Connect,(()=>{const e=this.reconnectingAttempt?Yn.Reconnected:Yn.Connected;this.isConnected=!0,this.setReconnectingAttempt(0),c(this,aa,"f").debug(`connection.on('${Yn.Connect}')`,{connectionId:r.id,recovered:r.recovered}),this.observer.safeEmit(Yn.State,{state:e})})),r.on(Yn.ConnectError,(e=>{this.connectionError=e,c(this,aa,"f").error(`connection.on('${Yn.ConnectError}')`,{error:pr(e)}),this.observer.safeEmit(Yn.State,{state:Yn.Error,error:e}),this.reconnectingAttempt>100&&(r.disconnect(),this.observer.safeEmit(Yn.State,{state:Yn.Disconnected,code:"server.disconnect"}))})),r.on(Yn.ReconnectError,(e=>{c(this,aa,"f").error(`connection.on('${Yn.ReconnectError}')`,{case:"SocketReconnect",error:pr(e)})})),r.on(Yn.Disconnect,(e=>{this.isConnected=!1,this.setReconnectingAttempt(0),this.disconnectReason=e,c(this,aa,"f").info(`connection.on('${Yn.Disconnect}')`,{reason:e});const t=this.getDisconnectReasonCode(e);"server.disconnect"===t&&r.disconnect(),this.observer.safeEmit(Yn.State,{state:Yn.Disconnected,code:t})})),r.io.on(Yn.ReconnectAttempt,(e=>{this.setReconnectingAttempt(e),c(this,aa,"f").info(`connection.on('${Yn.ReconnectAttempt}')`,{attempt:e}),this.observer.safeEmit(Yn.State,{state:Yn.Reconnecting})})),r.io.on(Yn.Reconnect,(()=>{c(this,aa,"f").debug(`connection.on('${Yn.Reconnect}')`,{connectionId:r.id}),this.observer.safeEmit(Yn.State,{state:Yn.Reconnect})}))}disconnect(){this.connection&&(this.connection.offAny(),this.connection.volatile.offAny(),this.connection.disconnect(),this.connection.io.removeAllListeners(),this.setReconnectingAttempt(0))}request(e){return a(this,arguments,void 0,(function*(e,t={}){return yield new Promise(((r,n)=>{this.connection?this.connection.timeout(8e3).emit(e,t,((t,i)=>{if(t){const r=kn.includes(e);return"operation has timed out"===(null==t?void 0:t.message)&&!c(this,ca,"f")&&r&&(d(this,ca,!0,"f"),this.observer.safeEmit(Yn.State,{state:Yn.BufferingStart})),void n(t)}i&&i.error?("Need join to channel first"===i.error&&this.observer.safeEmit(Yn.State,{code:Yn.NeedToJoinFirst}),n(new Us(i.error,i.errorCode,Object.assign({},i)))):(c(this,ca,"f")&&(d(this,ca,!1,"f"),this.observer.safeEmit(Yn.State,{state:Yn.BufferingEnd})),r(i))})):n(new Error("Socket request: Socket connection is not initialized"))}))}))}getServerUrl(){return this.serverUrl}getDisconnectReasonCode(e){const t=String(e).toLowerCase();return this.knownDisconnectReasonsCodes[t]||t}setReconnectingAttempt(e){this.reconnectingAttempt=e}};aa=new WeakMap,ca=new WeakMap,da=i([at(),s(0,dt(Hn.LoggerFactory)),o("design:paramtypes",[Function])],da);var ua,la=da;class pa extends Dn{constructor(e,t){super(e,null!=t?t:"invalid_payload")}}!function(e){e.DominantSpeaker="dominant-speaker",e.PeersVolumes="peers-volumes",e.Silence="silence"}(ua||(ua={}));let ha=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()}};ha=i([at()],ha);var fa,ma,ga,va,ya,_a=ha;let ba=ya=class{constructor(e,t,r){this.peersStorage=e,this.clientEventEmitter=t,fa.set(this,void 0),ma.set(this,void 0),ga.set(this,void 0),va.set(this,void 0),d(this,fa,r("ChannelAudioObserverEventHandler"),"f"),this.watchPeersLeave()}handle(e){try{const t=JSON.parse(e);switch(ya.validateEventPayload(t),t.event){case ua.DominantSpeaker:this.handleDominantSpeaker(t);break;case ua.PeersVolumes:this.handlePeerVolumes(t);break;case ua.Silence:this.handleSilence()}}catch(t){c(this,fa,"f").warn("Failed to handle audio observer event",{error:pr(t),eventData:e})}}handleDominantSpeaker(e){const{peerId:t}=e.data,r=this.peersStorage.get(t);d(this,ga,r,"f"),d(this,va,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&&!c(this,ga,"f")&&s.id===(null===(t=c(this,va,"f"))||void 0===t?void 0:t.id)&&(d(this,ga,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))),d(this,ga,void 0,"f"),this.setActiveSpeaker(void 0)}watchPeersLeave(){this.clientEventEmitter.on(Tr,(e=>{var t;e===(null===(t=c(this,ga,"f"))||void 0===t?void 0:t.id)&&this.setActiveSpeaker(void 0)}))}setActiveSpeaker(e){c(this,ma,"f")!==(null==e?void 0:e.id)&&(d(this,ma,null==e?void 0:e.id,"f"),this.clientEventEmitter.safeEmit(Lr,{peer:e}))}static validateEventPayload(e){switch(e.event){case ua.Silence:break;case ua.DominantSpeaker:{e.data||ya.throwInvalidPayload();const{peerId:t,producerId:r,trackLabel:n}=e.data;"string"==typeof t&&"string"==typeof r&&n===zn.Microphone||ya.throwInvalidPayload();break}case ua.PeersVolumes:Array.isArray(e.volumes)||ya.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===zn.Microphone||ya.throwInvalidPayload()}));break;default:ya.throwInvalidPayload()}}static throwInvalidPayload(){throw new pa("Invalid channel audio observer event handler payload")}};fa=new WeakMap,ma=new WeakMap,ga=new WeakMap,va=new WeakMap,ba=ya=i([at(),s(0,dt(Hn.PeersStorage)),s(1,dt(Hn.ClientEventEmitter)),s(2,dt(Hn.LoggerFactory)),o("design:paramtypes",[_a,Tt,Function])],ba);var Ea,wa,Sa,Ca=ba;let Pa=class{constructor(e,t,r,n,i){this.state=e,this.myPeer=r,this.socket=n,this.channelAudioObserverEventHandler=i,Ea.set(this,void 0),wa.set(this,void 0),Sa.set(this,void 0),d(this,Ea,t("DataChannels"),"f")}get channelMessagesDataConsumer(){return c(this,Sa,"f")}createAudioObserver(e){return a(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();d(this,wa,yield this.createDataConsumer({producerId:t,appId:this.state.appId,channelId:this.state.channelId,transport:e}),"f");const n=this.channelAudioObserverEventHandler.handle.bind(this.channelAudioObserverEventHandler),i=()=>{var e,t;null===(e=c(this,wa,"f"))||void 0===e||e.removeListener("message",n),null===(t=c(this,wa,"f"))||void 0===t||t.removeListener("close",i)};c(this,wa,"f").on("close",i),c(this,wa,"f").on("message",n),c(this,Ea,"f").debug("Successfully create audio observer",r)}catch(e){c(this,Ea,"f").error("Failed to create audio observer",Object.assign(Object.assign({},r),{error:pr(e)}))}}))}createChannelMessagesDataConsumer(e){return a(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");d(this,Sa,yield this.createDataConsumer({producerId:t,appId:this.state.appId,channelId:this.state.channelId,ordered:!0,transport:e}),"f"),c(this,Ea,"f").debug("Successfully created channel messages data consumer",Object.assign(Object.assign({},r),{producerId:t}))}catch(e){throw c(this,Ea,"f").error("Failed to create channel messages data consumer",Object.assign(Object.assign({},r),{error:e})),e}}))}closeAudioObserver(){var e;null===(e=c(this,wa,"f"))||void 0===e||e.close()}closeChannelMessagesDataConsumer(){var e;null===(e=c(this,Sa,"f"))||void 0===e||e.close()}createDataProducer(e,t){return a(this,void 0,void 0,(function*(){return yield this.socket.request(Cn,{transportId:e,label:t})}))}createDataConsumer(e){return a(this,arguments,void 0,(function*({producerId:e,appId:t,channelId:r,ordered:n,transport:i}){if(!i)throw c(this,Ea,"f").error("createDataConsumer()",{reason:"missing receive transport"}),new Error("Failed to create consumer");c(this,Ea,"f").debug("createDataConsumer()",{producerId:e});const s=yield this.socket.request(mn,{ordered:n,dataProducerId:e,transportId:i.id,appData:{peerId:this.myPeer.id,producerId:e,appId:t,channelId:r}}),o=yield i.consumeData(s);return c(this,Ea,"f").debug("Data consumer created",{consumerId:o.id}),o}))}getAudioObserverProducer(){return a(this,void 0,void 0,(function*(){return yield this.socket.request(_r)}))}};Ea=new WeakMap,wa=new WeakMap,Sa=new WeakMap,Pa=i([at(),s(0,dt(Hn.CallState)),s(1,dt(Hn.LoggerFactory)),s(2,dt(Hn.MyPeer)),s(3,dt(Hn.SocketIO)),s(4,dt(Hn.ChannelAudioObserverEventHandler)),o("design:paramtypes",[$n,Function,js,la,Ca])],Pa);var Ta,ka,Ra,Ia=Pa;let Da=class{constructor(e,t,r,n,i,s){this.state=e,this.myPeer=t,this.socket=n,this.clientEventEmitter=i,this.dataChannelsManager=s,Ta.set(this,new Map),ka.set(this,void 0),Ra.set(this,void 0),this.peersLoaded=!1,d(this,Ra,r("Network"),"f"),d(this,ka,new Tt,"f"),this.socket.observer.on(Yn.State,(e=>{c(this,ka,"f").safeEmit(Rn,e)}))}get isNetworkActive(){var e,t,r,n,i;return!!(null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&["connected","new"].includes(null!==(r=null===(t=this.receiveTransport)||void 0===t?void 0:t.connectionState)&&void 0!==r?r:"")&&["connected","new"].includes(null!==(i=null===(n=this.sendTransport)||void 0===n?void 0:n.connectionState)&&void 0!==i?i:"")}get observer(){return c(this,ka,"f")}get isSocketConnectionActive(){try{return this.checkSocketConnectionActivity(),!0}catch(e){return c(this,Ra,"f").warn("isSocketConnectionActive()",{error:pr(e)}),!1}}checkSocketConnectionActivity(){var e;if(!this.state.channelId||this.state.isChannelJoining)throw new Error("Connect to the channel first");if(!(null===(e=this.socket.connection)||void 0===e?void 0:e.active))throw new Error("Socket is inactive");if(!this.socket.connection.connected)throw new Error("Socket disconnected")}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.stopRestartIceAttempts(),this.removeEventListeners()}closeRemoteProducer(e){return a(this,void 0,void 0,(function*(){yield this.socket.request(dn,{peerId:this.myPeer.id,producerId:e})}))}closeSendTransport(){var e;this.sendTransport?((null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&this.closeTransport(this.sendTransport),this.sendTransport.close(),this.sendTransport=void 0):c(this,Ra,"f").warn("closeSendTransport()",{message:"No available send transport"})}closeReceiveTransport(){var e;this.receiveTransport?((null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&this.closeTransport(this.receiveTransport),this.receiveTransport.close(),this.receiveTransport=void 0):c(this,Ra,"f").warn("closeReceiveTransport()",{message:"No available receive transport"})}closeConnectionTransport(){return a(this,void 0,void 0,(function*(){var e;this.signalingTransport?(yield this.closePingConsumer(),(null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&this.closeTransport(this.signalingTransport),this.signalingTransport.close(),this.signalingTransport=void 0):c(this,Ra,"f").warn("closeConnectionTransport()",{message:"No available connection transport"})}))}closeTransport(e){try{e.close(),c(this,Ra,"f").debug("closeTransport()",{transportId:e.id,direction:e.direction})}catch(t){c(this,Ra,"f").error("closeTransport()",{error:t,transportId:e.id,direction:e.direction})}}createSendTransport(e){return a(this,void 0,void 0,(function*(){if(this.sendTransport)throw c(this,Ra,"f").warn("createSendTransport()",{message:"Send transport already exists"}),new Dn("Send transport already exists","already_exists");const t=yield this.socket.request(En,{sctpCapabilities:e.sctpCapabilities,localDirection:"send"}),r=e.createSendTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return c(this,Ra,"f").debug("createSendTransport()",{transportId:r.id,direction:r.direction}),this.sendTransport=r,this.subscribeCommonTransportEvents(r),r}))}createRecvTransport(e){return a(this,void 0,void 0,(function*(){if(this.receiveTransport)throw c(this,Ra,"f").warn("createReceiveTransport()",{message:"Receive transport already exists"}),new Dn("Receive transport already exists","already_exists");const t=yield this.socket.request(En,{localDirection:"receive"}),r=e.createRecvTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return c(this,Ra,"f").debug("createReceiveTransport()",{transportId:r.id,direction:r.direction}),this.receiveTransport=r,this.subscribeCommonTransportEvents(r),r}))}createSignalingTransport(e){return a(this,void 0,void 0,(function*(){if(this.signalingTransport)throw c(this,Ra,"f").warn("createConnectionTransport()",{message:"Connection transport already exists"}),new Dn("Connection transport already exists","already_exists");const t=yield this.socket.request(En,{localDirection:"receive",tcpOnly:!0}),r=e.createSendTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return c(this,Ra,"f").debug("createConnectionTransport()",{transportId:r.id,direction:r.direction,tcpOnly:!0}),this.signalingTransport=r,this.subscribeCommonTransportEvents(r),r}))}getIceParameters(e){return a(this,void 0,void 0,(function*(){const t=yield this.socket.request(Tn,{transportId:e.id}),{error:r}=t;if(r)throw new Error(r);const{iceParameters:n}=t;return c(this,Ra,"f").debug("getIceParameters()",{iceParameters:n}),n}))}restartIce(e){return a(this,void 0,void 0,(function*(){try{const t=yield this.getIceParameters(e);yield e.restartIce({iceParameters:t}),c(this,Ra,"f").info("restartIce completed",{iceParameters:t})}catch(e){c(this,Ra,"f").error("restartIce error",{error:e})}}))}createConsumer(e){return a(this,arguments,void 0,(function*({producerId:e,rtpCapabilities:t,appId:r,channelId:n,producerPeerId:i}){var s;const o=this.receiveTransport;if(!o)throw c(this,Ra,"f").error("createConsumer()",{reason:"missing receive transport"}),new Error("Failed to create consumer");let a;c(this,Ra,"f").debug("createConsumer()",{producerId:e});try{a=yield this.socket.request(fn,{producerId:e,transportId:o.id,rtpCapabilities:t,appData:{peerId:this.myPeer.id,appId:r,channelId:n},producerPeerId:i})}catch(o){if(!(o instanceof Us&&(null===(s=o.meta)||void 0===s?void 0:s.existedConsumer)))throw c(this,Ra,"f").error("Failed to get consumer options",{producerId:e,rtpCapabilities:t,appId:r,channelId:n,producerPeerId:i,error:pr(o)}),new Error("Failed to create consumer");a=o.meta.existedConsumer}const d=yield o.consume(a),{producerPaused:u}=a;return u&&d.pause(),c(this,Ra,"f").debug("Consumer created",{consumerId:d.id,label:d.appData.label,isProducerPaused:u}),{consumer:d,isProducerPaused:u}}))}createSignalingConsumer(){return a(this,void 0,void 0,(function*(){var e,t;const r=this.signalingTransport;if(!r)throw c(this,Ra,"f").error("createSignalingConsumer()",{reason:"missing signaling transport"}),new Error("Failed to create data consumer");this.signalingDataProducer=yield r.produceData({label:"heart-beater",protocol:"json"});const n=null===(e=this.signalingDataProducer)||void 0===e?void 0:e.id;if(!n)throw new TypeError("dataProducerId is missing for connectionTransport");try{const e=yield this.socket.request(mn,{ordered:!0,dataProducerId:n,transportId:r.id,appData:{peerId:this.myPeer.id,producerId:n,appId:this.state.appId,channelId:this.state.channelId}});this.signalingConsumerId=e.consumerId}catch(e){c(this,Ra,"f").error("Failed to setup TCP DataChannel for connectionTransport",{transportId:r.id,dataProducerId:null===(t=this.signalingDataProducer)||void 0===t?void 0:t.id,error:pr(e)})}}))}get channelMessagesDataConsumer(){return this.dataChannelsManager.channelMessagesDataConsumer}closePingConsumer(){return a(this,void 0,void 0,(function*(){try{if(!this.signalingConsumerId)return;yield this.closeRemoteConsumer(this.signalingConsumerId)}catch(e){c(this,Ra,"f").debug("closeConsumer()",{track:this,error:pr(e)})}}))}closeRemoteConsumer(e){return a(this,void 0,void 0,(function*(){return yield this.socket.request(gn,{peerId:this.myPeer.id,consumerId:e})}))}resumeRemoteConsumer(e){return a(this,void 0,void 0,(function*(){return yield this.socket.request(yn,{consumerId:e})}))}pauseRemoteProducer(e){return a(this,void 0,void 0,(function*(){return yield this.socket.request(un,{producerId:e})}))}pauseRemoteConsumer(e){return a(this,void 0,void 0,(function*(){return yield this.socket.request(vn,{consumerId:e})}))}updatePeerAppData(e){return a(this,arguments,void 0,(function*({peerId:e,appData:t}){return yield this.socket.request(vr,{peerId:e,appData:t})}))}getTransportsStateInfo(){return a(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}getPreferRelay(){var e;return null!==(e=this.preferRelay)&&void 0!==e&&e}getChannelPeers(e){return a(this,void 0,void 0,(function*(){const t=yield this.socket.request(mr,{role:e});return this.peersLoaded=!0,t}))}createAllDataChannels(){return a(this,void 0,void 0,(function*(){if(!this.receiveTransport)throw new Error("Receive transport is not created");yield Promise.all([this.dataChannelsManager.createAudioObserver(this.receiveTransport),this.dataChannelsManager.createChannelMessagesDataConsumer(this.receiveTransport)])}))}closeAllDataChannels(){this.dataChannelsManager.closeAudioObserver(),this.dataChannelsManager.closeChannelMessagesDataConsumer()}waitForReceiveTransportConnected(){return a(this,void 0,void 0,(function*(){if(!this.receiveTransport)throw new Error("receiveTransport is not initialized");yield this.waitForTransportConnected(this.receiveTransport)}))}triggerChannelStateEvent(e){return a(this,void 0,void 0,(function*(){const{messageId:t}=yield this.socket.request(gr,{peersRole:e});return t}))}waitForChannelMessagesDataConsumerConnected(){return a(this,void 0,void 0,(function*(){if(!this.dataChannelsManager.channelMessagesDataConsumer)throw new Error("channelMessagesDataConsumer is not initialized");yield this.waitForDataConsumerConnected(this.dataChannelsManager.channelMessagesDataConsumer)}))}waitForTransportConnected(e){return a(this,arguments,void 0,(function*(e,t=6e4){"connected"!==e.connectionState&&(yield new Promise(((r,n)=>{const i=setTimeout((()=>{s(),n(new Error("Timed out waiting for receiveTransport to connect"))}),t),s=()=>{clearTimeout(i),e.off("connectionstatechange",o)},o=()=>{"connected"===e.connectionState?(s(),r()):"failed"!==e.connectionState&&"closed"!==e.connectionState||(s(),n(new Error(`receiveTransport connection failed: ${e.connectionState}`)))};e.on("connectionstatechange",o)})))}))}waitForDataConsumerConnected(e){return a(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 a(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 c(this,Ra,"f").warn("getParsedTransportStats()",{error:e})}else c(this,Ra,"f").debug("getParsedTransportStats()",{message:"Transport is missing"})}))}logTransportDetails(e){return a(this,void 0,void 0,(function*(){var t,r,n,i;let s;try{s=yield e.getStats()}catch(t){return void c(this,Ra,"f").error("Failed to log detailed WebRTC transport stats",{error:pr(t),transportId:e.id,reason:"failed to parse getStats"})}try{const o=[...s],[,a]=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==a?void 0:a.iceRole,iceState:null==a?void 0:a.iceState,dtlsRole:null==a?void 0:a.dtlsRole,dtlsState:null==a?void 0:a.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)),c(this,Ra,"f").info("Detailed WebRTC transport stats",p)}catch(t){c(this,Ra,"f").error("Failed to log detailed WebRTC transport stats",{error:pr(t),transportId:e.id,reason:"-"})}}))}stopRestartIceAttempts(){Array.from(c(this,Ta,"f").values()).forEach((e=>clearInterval(e)))}subscribeCommonTransportEvents(e){e.on("connect",((t,r,n)=>a(this,[t,r,n],void 0,(function*({dtlsParameters:t},r,n){try{yield this.socket.request(wn,{transportId:e.id,dtlsParameters:t}),r(),c(this,Ra,"f").debug(`${e.direction}Transport.connect()`,{transportId:e.id,dtlsRole:t.role}),setTimeout((()=>a(this,void 0,void 0,(function*(){return yield this.logTransportDetails(e)}))),2e3),setTimeout((()=>a(this,void 0,void 0,(function*(){return yield this.checkTransportState(e)}))),15e3)}catch(t){c(this,Ra,"f").error(`${e.direction}Transport.on('connect')`,{error:t}),n(t)}})))),e.on("produce",((t,r,n)=>a(this,void 0,void 0,(function*(){try{const{id:n}=yield this.socket.request(Sn,{transportId:e.id,kind:t.kind,rtpParameters:t.rtpParameters,appData:t.appData});r({id:n}),c(this,Ra,"f").debug(`${e.direction}Transport.produce()`,{producerId:n,transportId:e.id,kind:t.kind})}catch(r){c(this,Ra,"f").error(`${e.direction}Transport.produce()`,{error:pr(r),transportId:e.id,kind:t.kind}),n(r)}})))),e.on("producedata",((t,r,n)=>a(this,void 0,void 0,(function*(){try{const{id:n}=yield this.socket.request(Cn,{transportId:e.id,label:t.label,sctpParameters:t.sctpStreamParameters,appData:t.appData});r({id:n}),c(this,Ra,"f").debug(`${e.direction}Transport.produceData()`,{producerId:n,transportId:e.id,label:t.label})}catch(r){c(this,Ra,"f").error(`${e.direction}Transport.produceData()`,{error:pr(r),transportId:e.id,label:t.label}),n(r)}})))),e.on("connectionstatechange",(t=>{if(c(this,Ra,"f").info(`${e.direction}Transport.state`,{state:t}),["closed","connected"].includes(t))return c(this,ka,"f").safeEmit(In,{state:t,direction:e.direction}),c(this,Ta,"f").has(e.id)&&(c(this,Ra,"f").debug("Stop receiveTransport.restartIce() retries",{recvTransportId:e.id}),clearInterval(c(this,Ta,"f").get(e.id)),c(this,Ta,"f").delete(e.id),"connected"===t&&c(this,ka,"f").safeEmit(In,{state:"reconnected",direction:e.direction})),void("connected"===t&&setTimeout((()=>{this.logTransportDetails(e).catch((e=>{c(this,Ra,"f").debug("Failed to log transport details",{error:pr(e)})}))}),1500));if(c(this,ka,"f").safeEmit(In,{state:t,direction:e.direction}),["disconnected","failed"].includes(t)){if(c(this,Ta,"f").has(e.id))return;"failed"===t&&(c(this,Ra,"f").debug(`${e.id} transport.restartIce()`,{transportId:e.id,direction:e.direction}),this.restartIce(e).catch((t=>{c(this,Ra,"f").debug("Failed to execute restartIce",{error:pr(t),transportId:e.id,direction:e.direction})}))),c(this,Ta,"f").set(e.id,setInterval((()=>{this.restartIce(e).catch((t=>{c(this,Ra,"f").debug("Failed to execute restartIce",{error:pr(t),transportId:e.id,direction:e.direction})})),c(this,Ra,"f").debug(`${e.id} transport.restartIce() attempt`,{recvTransportId:e.id,transportId:e.id,direction:e.direction})}),5e3))}})),e.on("icegatheringstatechange",(t=>{c(this,Ra,"f").info("icegatheringstatechange",{state:t,transportId:e.id,transportDirection:e.direction})}))}checkTransportState(e){return a(this,void 0,void 0,(function*(){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(Or,{direction:r,reason:"ice"}),void c(this,Ra,"f").warn(Pn,{reason:"ice",transportId:e.id,direction:r});"connected"!==t.dtlsState&&(this.clientEventEmitter.emit(Or,{direction:r,reason:"dtls"}),c(this,Ra,"f").warn(Pn,{reason:"dtls",transportId:e.id,direction:r}))}catch(t){c(this,Ra,"f").error("checkTransportState()",{error:pr(t),transportId:e.id,direction:e.direction})}}))}};Ta=new WeakMap,ka=new WeakMap,Ra=new WeakMap,Da=i([at(),s(0,dt(Hn.CallState)),s(1,dt(Hn.MyPeer)),s(2,dt(Hn.LoggerFactory)),s(3,dt(Hn.SocketIO)),s(4,dt(Hn.ClientEventEmitter)),s(5,dt(Hn.DataChannelsManager)),o("design:paramtypes",[$n,js,Function,la,Tt,Ia])],Da);var Aa=Da;let Oa=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 a(this,void 0,void 0,(function*(){const t=this.get(e);t&&(yield t.reset(),this.delete(e),this.clientEventEmitter.safeEmit(Tr,e))}))}all(){return this.peersStorage.all()}hosts(){return this.peersStorage.hosts()}audience(){return this.peersStorage.audience()}reset(){return a(this,void 0,void 0,(function*(){yield Promise.all(this.peersStorage.all().map((e=>a(this,void 0,void 0,(function*(){return yield e.reset()}))))),this.peersStorage.clear()}))}load(e){return a(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(Pr,n),n}isModerator(e){if(void 0===e)return!1;const t=this.get(e);return!!t&&t.isModerator}};function Na(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 Ma(e,t,r,n){var i=Na(Na(Na(e,r),function(e){return Object.prototype.toString.call(e)}(t)),typeof t);if(null===t)return Na(i,"null");if(void 0===t)return Na(i,"undefined");if("object"==typeof t||"function"==typeof t){if(-1!==n.indexOf(t))return Na(i,"[Circular]"+r);n.push(t);var s=function(e,t,r){return Object.keys(t).sort().reduce((function(e,n){return Ma(e,t[n],n,r)}),e)}(i,t,n);if(!("valueOf"in t)||"function"!=typeof t.valueOf)return s;try{return Na(s,String(t.valueOf()))}catch(e){return Na(s,"[valueOf exception]"+(e.stack||e.message))}}return Na(i,t.toString())}Oa=i([at(),s(0,dt(Hn.MyPeer)),s(1,dt(Hn.Network)),s(2,dt(Hn.PeerFactory)),s(3,dt(Hn.ClientEventEmitter)),s(4,dt(Hn.PeersStorage)),o("design:paramtypes",[js,Aa,Function,Tt,_a])],Oa);var La=function(e){return function(e,t){for(;e.length<t;)e="0"+e;return e}(Ma(0,e,"",[]).toString(16),8)};class xa{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 Fa{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 xa({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 ja,Ua,Ba,Va,Wa,Ha,qa;!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"}(ja||(ja={}));let za=class{constructor(e,t,r,n,i,s,o){var a;this.network=t,this.callState=r,this.socket=n,this.peersStorage=i,this.clientEventEmitter=s,this.webRtcIssueDetector=o,Ua.set(this,void 0),Ba.set(this,void 0),Va.set(this,[]),Wa.set(this,!1),Ha.set(this,{inbound:4.3,outbound:4.3}),qa.set(this,(new Date).getTime()-15e3),d(this,Ba,null===(a=this.webRtcIssueDetector)||void 0===a?void 0:a.eventEmitter,"f"),d(this,Ua,e("ChannelStateSyncEventHandler"),"f"),this.debouncedHandleChannelStateEvent=Ln(this.handleChannelStateEvent.bind(this),3e3),this.listenNetworkScoresUpdatedEvents()}handleChannelStateShort(e){return a(this,void 0,void 0,(function*(){try{yield this.debouncedHandleChannelStateEvent(e)}catch(e){c(this,Ua,"f").error("handleChannelStateSyncEvent()",{error:pr(e)})}}))}handleChannelStateEvent(e){return a(this,void 0,void 0,(function*(){if(c(this,Wa,"f"))c(this,Ua,"f").warn("Channel state event is already being handled, skipping new event",{case:"handleChannelStateEvent"});else{d(this,Wa,!0,"f");try{yield this.collectProbableInconsistencyCases(e);const t=this.getConfirmedInconsistencyResult();if(!(null==t?void 0:t.hasInconsistencyCases()))return;if(this.isRestoreStateRequestToEarly())return void c(this,Ua,"f").info("Inconsistency detected, but restore skipped",Object.assign({},t));this.handleConfirmedInconsistencyResult(t)}finally{d(this,Wa,!1,"f")}}}))}getLastInconsistencyCheckResult(){return c(this,Va,"f")[c(this,Va,"f").length-1]}handleConfirmedInconsistencyResult(e){e.missingPeers.forEach((e=>{this.clientEventEmitter.safeEmit(xr,{peerId:e,peersLoaded:this.network.peersLoaded,sdkInstances:Array.from(window._sdkMarks||[]).length,type:ja.MissingPeer})})),e.missingProducers.forEach((e=>{this.clientEventEmitter.safeEmit(xr,{producerId:e,type:ja.MissingProducer})})),e.producersWithInconsistentState.forEach((e=>{this.clientEventEmitter.safeEmit(xr,{producerId:e,type:ja.IncorrectProducerState})})),e.peersWithInconsistentAppData.forEach((e=>{this.clientEventEmitter.safeEmit(xr,{peerId:e,type:ja.IncorrectAppData})}))}getConfirmedInconsistencyResult(){const e=this.getLastInconsistencyCheckResult();if(!e)return;return new xa({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 a(this,void 0,void 0,(function*(){const t=new Fa({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(){d(this,Va,[],"f")}rotateLastProbableInconsistencyCheckResults(e){4===c(this,Va,"f").length&&c(this,Va,"f").shift(),c(this,Va,"f").push(e)}isReachedMaxCheckRetries(e,t,r=4){let n=0;return c(this,Va,"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:La(e.appData),producers:e.getProducers().map((e=>({id:e.id,paused:e.paused,stateChangedAt:e.getStateChangedAt()}))),consumers:e.getConsumersState()})))}}getIsConnectionActive(){return a(this,void 0,void 0,(function*(){var e;try{if(this.network.checkSocketConnectionActivity(),!this.network.isNetworkActive)return!1;const{success:t}=yield null===(e=this.socket.connection)||void 0===e?void 0:e.timeout(1e3).emitWithAck(Sr,{});return t}catch(e){return!1}}))}listenNetworkScoresUpdatedEvents(){c(this,Ba,"f")&&c(this,Ba,"f").on(Et.NetworkScoresUpdated,(e=>{e.inbound&&(c(this,Ha,"f").inbound=e.inbound),e.outbound&&(c(this,Ha,"f").outbound=e.outbound)}))}isBadNetworkScore(){const{inbound:e,outbound:t}=c(this,Ha,"f");return e<=2.6||t<=2.6}compareCheckedAndRestoredResults(e,t){return new xa({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()-c(this,qa,"f")<=15e3}};Ua=new WeakMap,Ba=new WeakMap,Va=new WeakMap,Wa=new WeakMap,Ha=new WeakMap,qa=new WeakMap,za=i([at(),s(0,dt(Hn.LoggerFactory)),s(1,dt(Hn.Network)),s(2,dt(Hn.CallState)),s(3,dt(Hn.SocketIO)),s(4,dt(Hn.PeersStorage)),s(5,dt(Hn.ClientEventEmitter)),s(6,dt(Hn.WebRTCIssueDetector)),o("design:paramtypes",[Function,Aa,$n,la,_a,Tt,or])],za);var Ga=za,Ya={},$a={exports:{}},Ja=1e3,Ka=6e4,Qa=60*Ka,Za=24*Qa,Xa=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*Za;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Qa;case"minutes":case"minute":case"mins":case"min":case"m":return r*Ka;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>=Za)return ec(e,t,Za,"day");if(t>=Qa)return ec(e,t,Qa,"hour");if(t>=Ka)return ec(e,t,Ka,"minute");if(t>=1e3)return ec(e,t,1e3,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=Za)return Math.round(e/Za)+"d";if(t>=Qa)return Math.round(e/Qa)+"h";if(t>=Ka)return Math.round(e/Ka)+"m";if(t>=Ja)return Math.round(e/Ja)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function ec(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}var tc=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=Xa,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=tc(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}($a,$a.exports);var rc={};Object.defineProperty(rc,"__esModule",{value:!0});var nc={},ic=Object.defineProperty,sc=Object.getOwnPropertyDescriptor,oc=Object.getOwnPropertyNames,ac=Object.prototype.hasOwnProperty,cc={};((e,t)=>{for(var r in t)ic(e,r,{get:t[r],enumerable:!0})})(cc,{BrowserDetector:()=>fc,KnownBrowsers:()=>uc,KnownPlatforms:()=>lc,default:()=>mc});var dc=(e=>((e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of oc(t))!ac.call(e,i)&&i!==r&&ic(e,i,{get:()=>t[i],enumerable:!(n=sc(t,i))||n.enumerable});return e})(ic({},"__esModule",{value:!0}),e))(cc),uc={chrome:"Google Chrome",brave:"Brave",crios:"Google Chrome",edge:"Microsoft Edge",edg:"Microsoft Edge",edgios:"Microsoft Edge",fennec:"Mozilla Firefox",jsdom:"JsDOM",mozilla:"Mozilla Firefox",fxios:"Mozilla Firefox",msie:"Microsoft Internet Explorer",opera:"Opera",opios:"Opera",opr:"Opera",opt:"Opera",rv:"Microsoft Internet Explorer",safari:"Safari",samsungbrowser:"Samsung Browser",electron:"Electron"},lc={android:"Android",androidTablet:"Android Tablet",cros:"Chrome OS",fennec:"Android Tablet",ipad:"IPad",ipod:"IPod",iphone:"IPhone",jsdom:"JsDOM",linux:"Linux",mac:"Macintosh",tablet:"Android Tablet",win:"Windows","windows phone":"Windows Phone",xbox:"Microsoft Xbox"},pc=(e,t=-1)=>{let r=new RegExp(`^-?\\d+(?:.\\d{0,${t}})?`),n=Number(e).toString().match(r);return n?n[0]:null},hc=()=>typeof window<"u"?window.navigator:null,fc=class{userAgent;constructor(e){this.userAgent=e||hc()?.userAgent||null}static get VERSION(){return"4.1.0"}parseUserAgent(e){let t={},r=e||this.userAgent||"",n=r.toLowerCase().replace(/\s\s+/g," "),i=/(edge)\/([\w.]+)/.exec(n)||/(edg)[/]([\w.]+)/.exec(n)||/(opr)[/]([\w.]+)/.exec(n)||/(opt)[/]([\w.]+)/.exec(n)||/(fxios)[/]([\w.]+)/.exec(n)||/(edgios)[/]([\w.]+)/.exec(n)||/(jsdom)[/]([\w.]+)/.exec(n)||/(samsungbrowser)[/]([\w.]+)/.exec(n)||/(electron)[/]([\w.]+)/.exec(n)||/(chrome)[/]([\w.]+)/.exec(n)||/(crios)[/]([\w.]+)/.exec(n)||/(opios)[/]([\w.]+)/.exec(n)||/(version)(applewebkit)[/]([\w.]+).*(safari)[/]([\w.]+)/.exec(n)||/(webkit)[/]([\w.]+).*(version)[/]([\w.]+).*(safari)[/]([\w.]+)/.exec(n)||/(applewebkit)[/]([\w.]+).*(safari)[/]([\w.]+)/.exec(n)||/(webkit)[/]([\w.]+)/.exec(n)||/(opera)(?:.*version|)[/]([\w.]+)/.exec(n)||/(msie) ([\w.]+)/.exec(n)||/(fennec)[/]([\w.]+)/.exec(n)||n.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(n)||n.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(n)||[],s=/(ipad)/.exec(n)||/(ipod)/.exec(n)||/(iphone)/.exec(n)||/(jsdom)/.exec(n)||/(windows phone)/.exec(n)||/(xbox)/.exec(n)||/(win)/.exec(n)||/(tablet)/.exec(n)||/(android)/.test(n)&&!1===/(mobile)/.test(n)&&["androidTablet"]||/(android)/.exec(n)||/(mac)/.exec(n)||/(linux)/.exec(n)||/(cros)/.exec(n)||[],o=i[5]||i[3]||i[1]||null,a=s[0]||null,c=i[4]||i[2]||null,d=hc();"chrome"===o&&"function"==typeof d?.brave?.isBrave&&(o="brave"),o&&(t[o]=!0),a&&(t[a]=!0);let u=!!(t.tablet||t.android||t.androidTablet),l=!!(t.ipad||t.tablet||t.androidTablet),p=!!(t.android||t.androidTablet||t.tablet||t.ipad||t.ipod||t.iphone||t["windows phone"]),h=!!(t.cros||t.mac||t.linux||t.win),f=!!(t.brave||t.chrome||t.crios||t.opr||t.safari||t.edg||t.electron),m=!(!t.msie&&!t.rv),g=!(!t.chrome&&!t.crios),v=!!(t.fxios||t.fennec||t.mozilla),y=!!t.safari,_=!!(t.opera||t.opios||t.opr||t.opt),b=!!(t.edg||t.edge||t.edgios);return{name:uc[o]??null,platform:lc[a]??null,userAgent:r,version:c,shortVersion:c?pc(parseFloat(c),2):null,isAndroid:u,isTablet:l,isMobile:p,isDesktop:h,isWebkit:f,isIE:m,isChrome:g,isFireFox:v,isSafari:y,isOpera:_,isEdge:b}}getBrowserInfo(){let e=this.parseUserAgent();return{name:e.name,platform:e.platform,userAgent:e.userAgent,version:e.version,shortVersion:e.shortVersion}}},mc=fc,gc={};Object.defineProperty(gc,"__esModule",{value:!0}),gc.Logger=void 0;const vc=$a.exports,yc="mediasoup-client";gc.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,vc.default)(`${yc}:${e}`),this._warn=(0,vc.default)(`${yc}:WARN:${e}`),this._error=(0,vc.default)(`${yc}:ERROR:${e}`)):(this._debug=(0,vc.default)(yc),this._warn=(0,vc.default)(`${yc}:WARN`),this._error=(0,vc.default)(`${yc}: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 _c,bc={},Ec={exports:{}},wc="object"==typeof Reflect?Reflect:null,Sc=wc&&"function"==typeof wc.apply?wc.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};_c=wc&&"function"==typeof wc.ownKeys?wc.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var Cc=Number.isNaN||function(e){return e!=e};function Pc(){Pc.init.call(this)}Ec.exports=Pc,Ec.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))}Lc(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&Lc(e,"error",t,r)}(e,i,{once:!0})}))},Pc.EventEmitter=Pc,Pc.prototype._events=void 0,Pc.prototype._eventsCount=0,Pc.prototype._maxListeners=void 0;var Tc=10;function kc(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function Rc(e){return void 0===e._maxListeners?Pc.defaultMaxListeners:e._maxListeners}function Ic(e,t,r,n){var i,s,o,a;if(kc(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=Rc(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 Dc(){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 Ac(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=Dc.bind(n);return i.listener=r,n.wrapFn=i,i}function Oc(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):Mc(i,i.length)}function Nc(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 Mc(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function Lc(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(Pc,"defaultMaxListeners",{enumerable:!0,get:function(){return Tc},set:function(e){if("number"!=typeof e||e<0||Cc(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Tc=e}}),Pc.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},Pc.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||Cc(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},Pc.prototype.getMaxListeners=function(){return Rc(this)},Pc.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)Sc(a,this,t);else{var c=a.length,d=Mc(a,c);for(r=0;r<c;++r)Sc(d[r],this,t)}return!0},Pc.prototype.addListener=function(e,t){return Ic(this,e,t,!1)},Pc.prototype.on=Pc.prototype.addListener,Pc.prototype.prependListener=function(e,t){return Ic(this,e,t,!0)},Pc.prototype.once=function(e,t){return kc(t),this.on(e,Ac(this,e,t)),this},Pc.prototype.prependOnceListener=function(e,t){return kc(t),this.prependListener(e,Ac(this,e,t)),this},Pc.prototype.removeListener=function(e,t){var r,n,i,s,o;if(kc(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},Pc.prototype.off=Pc.prototype.removeListener,Pc.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},Pc.prototype.listeners=function(e){return Oc(this,e,!0)},Pc.prototype.rawListeners=function(e){return Oc(this,e,!1)},Pc.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Nc.call(e,t)},Pc.prototype.listenerCount=Nc,Pc.prototype.eventNames=function(){return this._eventsCount>0?_c(this._events):[]},Object.defineProperty(bc,"__esModule",{value:!0}),bc.EnhancedEventEmitter=void 0;const xc=Ec.exports,Fc=new gc.Logger("EnhancedEventEmitter");class jc extends xc.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){Fc.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)}}bc.EnhancedEventEmitter=jc;var Uc={};Object.defineProperty(Uc,"__esModule",{value:!0}),Uc.InvalidStateError=Uc.UnsupportedError=void 0;class Bc extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Bc):this.stack=new Error(e).stack}}Uc.UnsupportedError=Bc;class Vc extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Vc):this.stack=new Error(e).stack}}Uc.InvalidStateError=Vc;var Wc={};Object.defineProperty(Wc,"__esModule",{value:!0}),Wc.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))},Wc.generateRandomNumber=function(){return Math.round(1e7*Math.random())},Wc.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 Hc={},qc={},zc={},Gc={exports:{}};var Yc=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=Xa,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=Yc(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Gc,Gc.exports);var $c=l&&l.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(zc,"__esModule",{value:!0}),zc.Logger=void 0;const Jc=$c(Gc.exports),Kc="h264-profile-level-id";zc.Logger=class{constructor(e){e?(this._debug=(0,Jc.default)(`${Kc}:${e}`),this._warn=(0,Jc.default)(`${Kc}:WARN:${e}`),this._error=(0,Jc.default)(`${Kc}:ERROR:${e}`)):(this._debug=(0,Jc.default)(Kc),this._warn=(0,Jc.default)(`${Kc}:WARN`),this._error=(0,Jc.default)(`${Kc}: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(qc,"__esModule",{value:!0}),qc.ProfileLevelId=qc.Level=qc.Profile=void 0,qc.parseProfileLevelId=od,qc.profileLevelIdToString=ad,qc.profileToString=function(e){switch(e){case Zc.ConstrainedBaseline:return"ConstrainedBaseline";case Zc.Baseline:return"Baseline";case Zc.Main:return"Main";case Zc.ConstrainedHigh:return"ConstrainedHigh";case Zc.High:return"High";case Zc.PredictiveHigh444:return"PredictiveHigh444";default:return void Qc.warn(`profileToString() | unrecognized profile ${e}`)}},qc.levelToString=function(e){switch(e){case Xc.L1_b:return"1b";case Xc.L1:return"1";case Xc.L1_1:return"1.1";case Xc.L1_2:return"1.2";case Xc.L1_3:return"1.3";case Xc.L2:return"2";case Xc.L2_1:return"2.1";case Xc.L2_2:return"2.2";case Xc.L3:return"3";case Xc.L3_1:return"3.1";case Xc.L3_2:return"3.2";case Xc.L4:return"4";case Xc.L4_1:return"4.1";case Xc.L4_2:return"4.2";case Xc.L5:return"5";case Xc.L5_1:return"5.1";case Xc.L5_2:return"5.2";default:return void Qc.warn(`levelToString() | unrecognized level ${e}`)}},qc.parseSdpProfileLevelId=cd,qc.isSameProfile=function(e={},t={}){const r=cd(e),n=cd(t);return Boolean(r&&n&&r.profile===n.profile)},qc.isSameProfileAndLevel=function(e={},t={}){const r=cd(e),n=cd(t);return Boolean(r&&n&&r.profile===n.profile&&r.level==n.level)},qc.generateProfileLevelIdStringForAnswer=function(e={},t={}){if(!e["profile-level-id"]&&!t["profile-level-id"])return void Qc.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");const r=cd(e),n=cd(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=ud(e)&&ud(t),s=r.level,o=n.level,a=function(e,t){return function(e,t){if(e===Xc.L1_b)return t!==Xc.L1&&t!==Xc.L1_b;if(t===Xc.L1_b)return e!==Xc.L1;return e<t}(e,t)?e:t}(s,o),c=i?s:a;return Qc.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${r.profile}, level:${c}]`),ad(new ed(r.profile,c))},qc.supportedLevel=function(e,t){for(let r=sd.length-1;r>=0;--r){const n=sd[r];if(256*n.max_macroblock_frame_size<=e&&n.max_macroblocks_per_second<=t*n.max_macroblock_frame_size)return Qc.debug(`supportedLevel() | result [max_frame_pixel_count:${e}, max_fps:${t}, level:${n.level}]`),n.level}return void Qc.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${e}, max_fps:${t}]`)};const Qc=new zc.Logger;var Zc,Xc;!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"}(Zc||(qc.Profile=Zc={})),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"}(Xc||(qc.Level=Xc={}));class ed{constructor(e,t){this.profile=e,this.level=t}}qc.ProfileLevelId=ed;const td=new ed(Zc.ConstrainedBaseline,Xc.L3_1);class rd{constructor(e){this.mask=~dd("x",e),this.masked_value=dd("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}}class nd{constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}}const id=[new nd(66,new rd("x1xx0000"),Zc.ConstrainedBaseline),new nd(77,new rd("1xxx0000"),Zc.ConstrainedBaseline),new nd(88,new rd("11xx0000"),Zc.ConstrainedBaseline),new nd(66,new rd("x0xx0000"),Zc.Baseline),new nd(88,new rd("10xx0000"),Zc.Baseline),new nd(77,new rd("0x0x0000"),Zc.Main),new nd(100,new rd("00000000"),Zc.High),new nd(100,new rd("00001100"),Zc.ConstrainedHigh),new nd(244,new rd("00000000"),Zc.PredictiveHigh444)],sd=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:Xc.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:Xc.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:Xc.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:Xc.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:Xc.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:Xc.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:Xc.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:Xc.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:Xc.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:Xc.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:Xc.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:Xc.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:Xc.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:Xc.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:Xc.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:Xc.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:Xc.L5_2}];function od(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 Xc.L1_1:s=0!=(16&n)?Xc.L1_b:Xc.L1_1;break;case Xc.L1:case Xc.L1_2:case Xc.L1_3:case Xc.L2:case Xc.L2_1:case Xc.L2_2:case Xc.L3:case Xc.L3_1:case Xc.L3_2:case Xc.L4:case Xc.L4_1:case Xc.L4_2:case Xc.L5:case Xc.L5_1:case Xc.L5_2:s=r;break;default:return void Qc.warn(`parseProfileLevelId() | unrecognized level_idc [str:${e}, level_idc:${r}]`)}for(const t of id)if(i===t.profile_idc&&t.profile_iop.isMatch(n))return Qc.debug(`parseProfileLevelId() | result [str:${e}, profile:${t.profile}, level:${s}]`),new ed(t.profile,s);Qc.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${e}, profile_idc:${i}, profile_iop:${n}]`)}function ad(e){if(e.level==Xc.L1_b)switch(e.profile){case Zc.ConstrainedBaseline:return"42f00b";case Zc.Baseline:return"42100b";case Zc.Main:return"4d100b";default:return void Qc.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${e.profile}`)}let t;switch(e.profile){case Zc.ConstrainedBaseline:t="42e0";break;case Zc.Baseline:t="4200";break;case Zc.Main:t="4d00";break;case Zc.ConstrainedHigh:t="640c";break;case Zc.High:t="6400";break;case Zc.PredictiveHigh444:t="f400";break;default:return void Qc.warn(`profileLevelIdToString() | unrecognized profile ${e.profile}`)}let r=e.level.toString(16);return 1===r.length&&(r=`0${r}`),`${t}${r}`}function cd(e={}){const t=e["profile-level-id"];return t?od(t):td}function dd(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 ud(e={}){const t=e["level-asymmetry-allowed"];return!0===t||1===t||"1"===t}Object.defineProperty(Hc,"__esModule",{value:!0}),Hc.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)fd(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)gd(t)},Hc.validateAndNormalizeRtpParameters=hd,Hc.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")},Hc.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)},Hc.getExtendedRtpCapabilities=function(e,t,r){const n={codecs:[],headerExtensions:[]};if(r)for(const r of e.codecs??[]){if(bd(r))continue;const e=(t.codecs??[]).find((e=>Ed(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:Sd(r,e)};n.codecs.push(i)}else for(const r of t.codecs??[]){if(bd(r))continue;const t=(e.codecs??[]).find((e=>Ed(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:Sd(t,r)};n.codecs.push(i)}for(const r of n.codecs){const n=e.codecs.find((e=>bd(e)&&e.parameters?.apt===r.localPayloadType)),i=t.codecs.find((e=>bd(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=>wd(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},Hc.getRecvRtpCapabilities=function(e){const t={codecs:[],headerExtensions:[]};for(const r of e.codecs){const e={kind:r.kind,mimeType:r.mimeType,preferredPayloadType:r.remotePayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.localParameters,rtcpFeedback:r.rtcpFeedback};if(t.codecs.push(e),!r.remoteRtxPayloadType)continue;const n={kind:r.kind,mimeType:`${r.kind}/rtx`,preferredPayloadType:r.remoteRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.remotePayloadType},rtcpFeedback:[]};t.codecs.push(n)}for(const r of e.headerExtensions){if("sendrecv"!==r.direction&&"recvonly"!==r.direction)continue;const e={kind:r.kind,uri:r.uri,preferredId:r.recvId,preferredEncrypt:r.encrypt??!1,direction:r.direction};t.headerExtensions.push(e)}return t},Hc.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},Hc.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},Hc.reduceCodecs=function(e,t){const r=[];if(t){for(let n=0;n<e.length;++n)if(Ed(e[n],t,{strict:!0})){r.push(e[n]),bd(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]),bd(e[1])&&r.push(e[1]);return r},Hc.generateProbatorRtpParameters=function(e){hd(e=pd.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},Hc.canSend=function(e,t){return(t.codecs??[]).some((t=>t.kind===e))},Hc.canReceive=function(e,t){if(hd(e),0===e.codecs.length)return!1;const r=e.codecs[0];return(t.codecs??[]).some((e=>e.preferredPayloadType===r.payloadType))};const ld=qc,pd=Wc;function hd(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)vd(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)yd(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)_d(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 fd(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)md(t)}function md(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 gd(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 vd(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)md(t)}function yd(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 _d(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 bd(e){return!!e&&/.+\/rtx$/i.test(e.mimeType)}function Ed(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(!ld.isSameProfile(e.parameters,t.parameters))return!1;let r;try{r=ld.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 wd(e,t){return(!e.kind||!t.kind||e.kind===t.kind)&&e.uri===t.uri}function Sd(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 Cd={},Pd={},Td={},kd={};Object.defineProperty(kd,"__esModule",{value:!0}),kd.Logger=void 0;const Rd=$a.exports,Id="awaitqueue";kd.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=Rd(`awaitqueue:${e}`),this._warn=Rd(`awaitqueue:WARN:${e}`),this._error=Rd(`awaitqueue:ERROR:${e}`)):(this._debug=Rd(Id),this._warn=Rd("awaitqueue:WARN"),this._error=Rd("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 Dd={};Object.defineProperty(Dd,"__esModule",{value:!0}),Dd.AwaitQueueRemovedTaskError=Dd.AwaitQueueStoppedError=void 0;class Ad extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Ad)}}Dd.AwaitQueueStoppedError=Ad;class Od extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Od)}}Dd.AwaitQueueRemovedTaskError=Od,Object.defineProperty(Td,"__esModule",{value:!0}),Td.AwaitQueue=void 0;const Nd=Dd,Md=new kd.Logger("AwaitQueue");Td.AwaitQueue=class{pendingTasks=new Map;nextTaskId=0;stopping=!1;constructor(){Md.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t){if(t=t??e.name,Md.debug(`push() [name:${t}]`),"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(((r,n)=>{const i={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:e=>{if(i.completed)return;i.completed=!0,this.pendingTasks.delete(i.id),Md.debug(`resolving task [name:${i.name}]`),r(e);const[t]=this.pendingTasks.values();t&&!t.executedAt&&this.execute(t)},reject:e=>{if(!i.completed&&(i.completed=!0,this.pendingTasks.delete(i.id),Md.debug(`rejecting task [name:${i.name}]: %s`,String(e)),n(e),!this.stopping)){const[e]=this.pendingTasks.values();e&&!e.executedAt&&this.execute(e)}}};this.pendingTasks.set(i.id,i),1===this.pendingTasks.size&&this.execute(i)}))}stop(){Md.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())Md.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Nd.AwaitQueueStoppedError);this.stopping=!1}remove(e){Md.debug(`remove() [taskIdx:${e}]`);const t=Array.from(this.pendingTasks.values())[e];t?t.reject(new Nd.AwaitQueueRemovedTaskError):Md.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(Md.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)}}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AwaitQueueRemovedTaskError=e.AwaitQueueStoppedError=e.AwaitQueue=void 0;var t=Td;Object.defineProperty(e,"AwaitQueue",{enumerable:!0,get:function(){return t.AwaitQueue}});var r=Dd;Object.defineProperty(e,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return r.AwaitQueueStoppedError}}),Object.defineProperty(e,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return r.AwaitQueueRemovedTaskError}})}(Pd);var Ld={};Object.defineProperty(Ld,"__esModule",{value:!0}),Ld.Producer=void 0;const xd=bc,Fd=Uc,jd=new gc.Logger("Producer");class Ud extends xd.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new xd.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:r,track:n,rtpParameters:i,stopTracks:s,disableTrackOnPause:o,zeroRtpOnPause:a,appData:c}){super(),jd.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||(jd.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(jd.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Fd.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){jd.debug("pause()"),this._closed?jd.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(){jd.debug("resume()"),this._closed?jd.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(jd.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch(e){}throw new Fd.InvalidStateError("closed")}if(e&&"ended"===e.readyState)throw new Fd.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()):jd.debug("replaceTrack() | same track, ignored")}async setMaxSpatialLayer(e){if(this._closed)throw new Fd.InvalidStateError("closed");if("video"!==this._kind)throw new Fd.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 Fd.InvalidStateError("closed");if("object"!=typeof e)throw new TypeError("invalid params");await new Promise(((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)}))}onTrackEnded(){jd.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){}}}Ld.Producer=Ud;var Bd={};Object.defineProperty(Bd,"__esModule",{value:!0}),Bd.Consumer=void 0;const Vd=bc,Wd=Uc,Hd=new gc.Logger("Consumer");class qd extends Vd.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new Vd.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:r,rtpReceiver:n,track:i,rtpParameters:s,appData:o}){super(),Hd.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||(Hd.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Hd.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Wd.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){Hd.debug("pause()"),this._closed?Hd.error("pause() | Consumer closed"):this._paused?Hd.debug("pause() | Consumer is already paused"):(this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause"))}resume(){Hd.debug("resume()"),this._closed?Hd.error("resume() | Consumer closed"):this._paused?(this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")):Hd.debug("resume() | Consumer is already resumed")}onTrackEnded(){Hd.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){}}}Bd.Consumer=qd;var zd={};Object.defineProperty(zd,"__esModule",{value:!0}),zd.DataProducer=void 0;const Gd=bc,Yd=Uc,$d=new gc.Logger("DataProducer");class Jd extends Gd.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new Gd.EnhancedEventEmitter;constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:n}){super(),$d.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||($d.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||($d.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if($d.debug("send()"),this._closed)throw new Yd.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||($d.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?$d.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):$d.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||($d.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))})),this._dataChannel.addEventListener("message",(()=>{this._closed||$d.warn('DataChannel "message" event in a DataProducer, message discarded')})),this._dataChannel.addEventListener("bufferedamountlow",(()=>{this._closed||this.safeEmit("bufferedamountlow")}))}}zd.DataProducer=Jd;var Kd={};Object.defineProperty(Kd,"__esModule",{value:!0}),Kd.DataConsumer=void 0;const Qd=bc,Zd=new gc.Logger("DataConsumer");class Xd extends Qd.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new Qd.EnhancedEventEmitter;constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:n,appData:i}){super(),Zd.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||(Zd.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Zd.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(Zd.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?Zd.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):Zd.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(Zd.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)}))}}Kd.DataConsumer=Xd,Object.defineProperty(Cd,"__esModule",{value:!0}),Cd.Transport=void 0;const eu=Pd,tu=bc,ru=Uc,nu=Wc,iu=Hc,su=Ld,ou=Bd,au=zd,cu=Kd,du=new gc.Logger("Transport");class uu{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class lu extends tu.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 eu.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new tu.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(),du.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=nu.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){du.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 ru.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(du.debug("restartIce()"),this._closed)throw new ru.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(du.debug("updateIceServers()"),this._closed)throw new ru.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,encodings:t,codecOptions:r,codec:n,stopTracks:i=!0,disableTrackOnPause:s=!0,zeroRtpOnPause:o=!1,onRtpSender:a,appData:c={}}={}){if(du.debug("produce() [track:%o]",e),this._closed)throw new ru.InvalidStateError("closed");if(!e)throw new TypeError("missing track");if("send"!==this._direction)throw new ru.UnsupportedError("not a sending Transport");if(!this._canProduceByKind[e.kind])throw new ru.UnsupportedError(`cannot produce ${e.kind}`);if("ended"===e.readyState)throw new ru.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(c&&"object"!=typeof c)throw new TypeError("if given, appData must be an object");return this._awaitQueue.push((async()=>{let d;if(t&&!Array.isArray(t))throw TypeError("encodings must be an array");t&&0===t.length?d=void 0:t&&(d=t.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:u,rtpParameters:l,rtpSender:p}=await this._handler.send({track:e,encodings:d,codecOptions:r,codec:n,onRtpSender:a});try{iu.validateAndNormalizeRtpParameters(l);const{id:t}=await new Promise(((t,r)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:l,appData:c},t,r)})),r=new su.Producer({id:t,localId:u,rtpSender:p,track:e,rtpParameters:l,stopTracks:i,disableTrackOnPause:s,zeroRtpOnPause:o,appData:c});return this._producers.set(r.id,r),this.handleProducer(r),this._observer.safeEmit("newproducer",r),r}catch(e){throw this._handler.stopSending(u).catch((()=>{})),e}}),"transport.produce()").catch((t=>{if(i)try{e.stop()}catch(e){}throw t}))}async consume({id:e,producerId:t,kind:r,rtpParameters:n,streamId:i,onRtpReceiver:s,appData:o={}}){if(du.debug("consume()"),this._closed)throw new ru.InvalidStateError("closed");if("recv"!==this._direction)throw new ru.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=nu.clone(n);if(!iu.canReceive(a,this._recvRtpCapabilities))throw new ru.UnsupportedError("cannot consume this Producer");const c=new uu({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(du.debug("produceData()"),this._closed)throw new ru.InvalidStateError("closed");if("send"!==this._direction)throw new ru.UnsupportedError("not a sending Transport");if(!this._maxSctpMessageSize)throw new ru.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});iu.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 au.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(du.debug("consumeData()"),this._closed)throw new ru.InvalidStateError("closed");if("recv"!==this._direction)throw new ru.UnsupportedError("not a receiving Transport");if(!this._maxSctpMessageSize)throw new ru.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=nu.clone(r);return iu.validateAndNormalizeSctpStreamParameters(o),this._awaitQueue.push((async()=>{const{dataChannel:r}=await this._handler.receiveDataChannel({sctpStreamParameters:o,label:n,protocol:i}),a=new cu.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 du.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 ou.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=iu.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:e}]),du.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(e){du.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 du.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){du.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 du.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){du.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 du.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){du.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 ru.InvalidStateError("closed")):this.safeEmit("connect",{dtlsParameters:e},t,r)})),e.on("@icegatheringstatechange",(e=>{e!==this._iceGatheringState&&(du.debug("ICE gathering state changed to %s",e),this._iceGatheringState=e,this._closed||this.safeEmit("icegatheringstatechange",e))})),e.on("@icecandidateerror",(e=>{du.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&&(du.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=>du.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 ru.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 ru.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)}))}}Cd.Transport=lu;var pu={},hu={},fu={},mu={exports:{}},gu=mu.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"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",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(gu).forEach((function(e){gu[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=mu.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}}))}))}}(fu);var vu=mu.exports,yu=/%[sdv%]/g,_u=function(e){var t=1,r=arguments,n=r.length;return e.replace(yu,(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""}}))},bu=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 _u.apply(null,n)},Eu=["v","o","s","i","u","e","p","c","b","t","r","z","a"],wu=["i","c","b","a"],Su=fu,Cu=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||Eu,n=t.innerOrder||wu,i=[];return r.forEach((function(t){vu[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(bu(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(bu(t,r,e))}))}))})),e.media.forEach((function(e){i.push(bu("m",vu.m[0],e)),n.forEach((function(t){vu[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(bu(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(bu(t,r,e))}))}))}))})),i.join("\r\n")+"\r\n"},Pu=mu.exports;hu.grammar=Pu,hu.write=Cu,hu.parse=Su.parse,hu.parseParams=Su.parseParams,hu.parseFmtpConfig=Su.parseFmtpConfig,hu.parsePayloads=Su.parsePayloads,hu.parseRemoteCandidates=Su.parseRemoteCandidates,hu.parseImageAttributes=Su.parseImageAttributes,hu.parseSimulcastStreamList=Su.parseSimulcastStreamList;var Tu={};Object.defineProperty(Tu,"__esModule",{value:!0}),Tu.parse=function(e){const t=ku.exec(e??"");return t?{spatialLayers:Number(t[1]),temporalLayers:Number(t[2])}:{spatialLayers:1,temporalLayers:1}};const ku=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");var Ru={};Object.defineProperty(Ru,"__esModule",{value:!0}),Ru.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=Iu.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())}},Ru.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??=t.setup,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}]}},Ru.getCname=function({offerMediaObject:e}){const t=(e.ssrcs??[]).find((e=>"cname"===e.attribute));if(!t)return"";return t.value},Ru.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=Iu.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]}`}};const Iu=hu;var Du={};Object.defineProperty(Du,"__esModule",{value:!0}),Du.getRtpEncodings=function({offerMediaObject:e}){const t=new Set;for(const r of e.ssrcs??[]){const e=r.id;e&&t.add(e)}if(0===t.size)throw new Error("no a=ssrc lines found");const r=new Map;for(const n of e.ssrcGroups??[]){if("FID"!==n.semantics)continue;const e=n.ssrcs.split(/\s+/),i=Number(e[0]),s=Number(e[1]);t.has(i)&&(t.delete(i),t.delete(s),r.set(i,s))}for(const e of t)r.set(e,void 0);const n=[];for(const[e,t]of r){const r={ssrc:e};t&&(r.rtx={ssrc:t}),n.push(r)}return n},Du.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 Au={};Object.defineProperty(Au,"__esModule",{value:!0}),Au.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"}))};var Ou={},Nu={};Object.defineProperty(Nu,"__esModule",{value:!0}),Nu.OfferMediaSection=Nu.AnswerMediaSection=Nu.MediaSection=void 0;const Mu=hu,Lu=Wc;class xu{_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(),delete this._mediaObject.ext,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}close(){this.disable(),this._mediaObject.port=0}}Nu.MediaSection=xu;Nu.AnswerMediaSection=class extends xu{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:Fu(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r=Lu.clone(e.parameters)??{};let n=Lu.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=Mu.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 Fu(e){const t=new RegExp("^(audio|video)/(.+)","i").exec(e.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}Nu.OfferMediaSection=class extends xu{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=`${c??"-"} ${d}`;for(const e of a.codecs){const t={payload:e.payloadType,codec:Fu(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(Ou,"__esModule",{value:!0}),Ou.RemoteSdp=void 0;const ju=hu,Uu=Nu,Bu=["av1","h264"],Vu=new gc.Logger("RemoteSdp");Ou.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"},name:"-",timing:{start:0,stop:0},media:[]},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){Vu.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){Vu.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(const t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){Vu.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 Uu.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=>Bu.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 Uu.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));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?(Vu.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 Uu.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 Uu.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++,ju.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(" "))}},Object.defineProperty(pu,"__esModule",{value:!0}),pu.Chrome111=void 0;const Wu=hu,Hu=bc,qu=Hc,zu=Uc,Gu=Tu,Yu=Ru,$u=Du,Ju=Au,Ku=Ou,Qu=new gc.Logger("Chrome111"),Zu={OS:1024,MIS:1024};class Xu extends Hu.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 Xu(e),getNativeRtpCapabilities:async()=>{Qu.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video",{sendEncodings:[{scalabilityMode:"L3T3"}]});const t=await e.createOffer();try{e.close()}catch(e){}e=void 0;const r=Wu.parse(t.sdp);return Xu.getLocalRtpCapabilities(r)}catch(t){try{e?.close()}catch(e){}throw e=void 0,t}},getNativeSctpCapabilities:async()=>(Qu.debug("getNativeSctpCapabilities()"),{numStreams:Zu})}}static getLocalRtpCapabilities(e){const t=Yu.extractRtpCapabilities({sdpObject:e});return qu.validateAndNormalizeRtpCapabilities(t),Ju.addNackSupportForOpus(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Qu.debug("constructor()"),this._direction=e,this._remoteSdp=new Ku.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):(Qu.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Chrome111"}close(){if(Qu.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(),Qu.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Qu.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Qu.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Qu.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Qu.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Qu.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,encodings:t,codecOptions:r,codec:n,onRtpSender:i}){if(this.assertNotClosed(),this.assertSendDirection(),Qu.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1){let e=1;for(const r of t){const t=r.scalabilityMode?(0,Gu.parse)(r.scalabilityMode).temporalLayers:3;t>e&&(e=t)}t.forEach(((t,r)=>{t.rid=`r${r}`,t.scalabilityMode=`L1T${e}`}))}const s=this._remoteSdp.getNextMediaSectionIdx(),o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(o.sender);const a=await this._pc.createOffer();let c=Wu.parse(a.sdp);c.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const d=Xu.getLocalRtpCapabilities(c),u=this._getSendExtendedRtpCapabilities(d),l=qu.getSendingRtpParameters(e.kind,u);l.codecs=qu.reduceCodecs(l.codecs,n);const p=qu.getSendingRemoteRtpParameters(e.kind,u);p.codecs=qu.reduceCodecs(p.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:c}),Qu.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const h=o.mid;l.mid=h,c=Wu.parse(this._pc.localDescription.sdp);const f=c.media[s.idx];if(l.rtcp.cname=Yu.getCname({offerMediaObject:f}),t)if(1===t.length){const e=$u.getRtpEncodings({offerMediaObject:f});Object.assign(e[0],t[0]),l.encodings=e}else l.encodings=t;else l.encodings=$u.getRtpEncodings({offerMediaObject:f});this._remoteSdp.send({offerMediaObject:f,reuseMid:s.reuseMid,offerRtpParameters:l,answerRtpParameters:p,codecOptions:r});const m={type:"answer",sdp:this._remoteSdp.getSdp()};return Qu.debug("send() | calling pc.setRemoteDescription() [answer:%o]",m),await this._pc.setRemoteDescription(m),this._mapMidTransceiver.set(h,o),{localId:h,rtpParameters:l,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),Qu.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();Qu.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Qu.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Qu.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();Qu.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Qu.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Qu.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();Qu.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Qu.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Qu.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Qu.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(),Qu.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();Qu.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Qu.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Qu.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();Qu.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Qu.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};Qu.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Zu.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Wu.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Qu.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()};Qu.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;Qu.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Qu.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=Wu.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));Yu.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Wu.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Qu.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){Qu.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()};Qu.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Qu.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){Qu.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()};Qu.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Qu.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){Qu.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()};Qu.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Qu.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};Qu.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()};Qu.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Wu.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Qu.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=Wu.parse(this._pc.localDescription.sdp));const r=Yu.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 zu.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')}}pu.Chrome111=Xu;var el={};Object.defineProperty(el,"__esModule",{value:!0}),el.Chrome74=void 0;const tl=hu,rl=bc,nl=Hc,il=Uc,sl=Tu,ol=Ru,al=Du,cl=Au,dl=Ou,ul=new gc.Logger("Chrome74"),ll={OS:1024,MIS:1024};class pl extends rl.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 pl(e),getNativeRtpCapabilities:async()=>{ul.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}e=void 0;const r=tl.parse(t.sdp);return pl.getLocalRtpCapabilities(r)}catch(t){try{e?.close()}catch(e){}throw e=void 0,t}},getNativeSctpCapabilities:async()=>(ul.debug("getNativeSctpCapabilities()"),{numStreams:ll})}}static getLocalRtpCapabilities(e){const t=ol.extractRtpCapabilities({sdpObject:e});return nl.validateAndNormalizeRtpCapabilities(t),cl.addNackSupportForOpus(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),ul.debug("constructor()"),this._direction=e,this._remoteSdp=new dl.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):(ul.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Chrome74"}close(){if(ul.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(),ul.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),ul.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});ul.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};ul.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};ul.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();ul.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,encodings:t,codecOptions:r,codec:n}){this.assertNotClosed(),this.assertSendDirection(),ul.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach(((e,t)=>{e.rid=`r${t}`}));const i=this._remoteSdp.getNextMediaSectionIdx(),s=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});let o=await this._pc.createOffer(),a=tl.parse(o.sdp);a.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const c=pl.getLocalRtpCapabilities(a),d=this._getSendExtendedRtpCapabilities(c),u=nl.getSendingRtpParameters(e.kind,d);u.codecs=nl.reduceCodecs(u.codecs,n);const l=nl.getSendingRemoteRtpParameters(e.kind,d);l.codecs=nl.reduceCodecs(l.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:a});let p=!1;const h=(0,sl.parse)((t??[{}])[0].scalabilityMode);let f;t&&1===t.length&&h.spatialLayers>1&&"video/vp9"===u.codecs[0].mimeType.toLowerCase()&&(ul.debug("send() | enabling legacy simulcast for VP9 SVC"),p=!0,a=tl.parse(o.sdp),f=a.media[i.idx],al.addLegacySimulcast({offerMediaObject:f,numStreams:h.spatialLayers}),o={type:"offer",sdp:tl.write(a)}),ul.debug("send() | calling pc.setLocalDescription() [offer:%o]",o),await this._pc.setLocalDescription(o);const m=s.mid;if(u.mid=m,a=tl.parse(this._pc.localDescription.sdp),f=a.media[i.idx],u.rtcp.cname=ol.getCname({offerMediaObject:f}),t)if(1===t.length){let e=al.getRtpEncodings({offerMediaObject:f});Object.assign(e[0],t[0]),p&&(e=[e[0]]),u.encodings=e}else u.encodings=t;else u.encodings=al.getRtpEncodings({offerMediaObject:f});if(u.encodings.length>1&&("video/vp8"===u.codecs[0].mimeType.toLowerCase()||"video/h264"===u.codecs[0].mimeType.toLowerCase()))for(const e of u.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${h.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:f,reuseMid:i.reuseMid,offerRtpParameters:u,answerRtpParameters:l,codecOptions:r});const g={type:"answer",sdp:this._remoteSdp.getSdp()};return ul.debug("send() | calling pc.setRemoteDescription() [answer:%o]",g),await this._pc.setRemoteDescription(g),this._mapMidTransceiver.set(m,s),{localId:m,rtpParameters:u,rtpSender:s.sender}}async stopSending(e){if(this.assertSendDirection(),ul.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();ul.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};ul.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),ul.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();ul.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};ul.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),ul.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();ul.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};ul.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?ul.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):ul.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(),ul.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();ul.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};ul.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),ul.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();ul.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};ul.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};ul.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%ll.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=tl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),ul.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()};ul.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;ul.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};ul.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer();const s=tl.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));ol.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:tl.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),ul.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){ul.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()};ul.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ul.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){ul.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()};ul.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ul.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){ul.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()};ul.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ul.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};ul.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()};ul.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=tl.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}ul.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=tl.parse(this._pc.localDescription.sdp));const r=ol.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 il.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')}}el.Chrome74=pl;var hl={};Object.defineProperty(hl,"__esModule",{value:!0}),hl.Firefox120=void 0;const fl=hu,ml=bc,gl=Uc,vl=Hc,yl=Tu,_l=Ru,bl=Du,El=Ou,wl=new gc.Logger("Firefox120"),Sl={OS:16,MIS:2048};class Cl extends ml.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 Cl(e),getNativeRtpCapabilities:async()=>{wl.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});const t=document.createElement("canvas");t.getContext("2d");const r=t.captureStream().getVideoTracks()[0];try{e.addTransceiver("audio",{direction:"sendrecv"}),e.addTransceiver(r,{direction:"sendrecv",sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});const n=await e.createOffer();try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}e=void 0;const i=fl.parse(n.sdp);return Cl.getLocalRtpCapabilities(i)}catch(n){try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e?.close()}catch(e){}throw e=void 0,n}},getNativeSctpCapabilities:async()=>(wl.debug("getNativeSctpCapabilities()"),{numStreams:Sl})}}static getLocalRtpCapabilities(e){const t=_l.extractRtpCapabilities({sdpObject:e});return vl.validateAndNormalizeRtpCapabilities(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),wl.debug("constructor()"),this._direction=e,this._remoteSdp=new El.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):(wl.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Firefox120"}close(){if(wl.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 gl.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),wl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});wl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};wl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};wl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();wl.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,encodings:t,codecOptions:r,codec:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),wl.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach(((e,t)=>{e.rid=`r${t}`}));const s=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(s.sender);const o=await this._pc.createOffer();let a=fl.parse(o.sdp);a.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const c=Cl.getLocalRtpCapabilities(a),d=this._getSendExtendedRtpCapabilities(c),u=vl.getSendingRtpParameters(e.kind,d);u.codecs=vl.reduceCodecs(u.codecs,n);const l=vl.getSendingRemoteRtpParameters(e.kind,d);l.codecs=vl.reduceCodecs(l.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:a});const p=(0,yl.parse)((t??[{}])[0].scalabilityMode);wl.debug("send() | calling pc.setLocalDescription() [offer:%o]",o),await this._pc.setLocalDescription(o);const h=s.mid;u.mid=h,a=fl.parse(this._pc.localDescription.sdp);const f=a.media[a.media.length-1];if(u.rtcp.cname=_l.getCname({offerMediaObject:f}),t)if(1===t.length){const e=bl.getRtpEncodings({offerMediaObject:f});Object.assign(e[0],t[0]),u.encodings=e}else u.encodings=t;else u.encodings=bl.getRtpEncodings({offerMediaObject:f});if(u.encodings.length>1&&("video/vp8"===u.codecs[0].mimeType.toLowerCase()||"video/h264"===u.codecs[0].mimeType.toLowerCase()))for(const e of u.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${p.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:f,offerRtpParameters:u,answerRtpParameters:l,codecOptions:r});const m={type:"answer",sdp:this._remoteSdp.getSdp()};return wl.debug("send() | calling pc.setRemoteDescription() [answer:%o]",m),await this._pc.setRemoteDescription(m),this._mapMidTransceiver.set(h,s),{localId:h,rtpParameters:u,rtpSender:s.sender}}async stopSending(e){if(this.assertSendDirection(),wl.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();wl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};wl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),wl.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();wl.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};wl.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),wl.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();wl.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};wl.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?wl.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):wl.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(),wl.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();wl.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};wl.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),wl.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();wl.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};wl.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};wl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Sl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=fl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),wl.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()};wl.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;wl.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};wl.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=fl.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));_l.applyCodecParameters({offerRtpParameters:n,answerMediaObject:a}),i={type:"answer",sdp:fl.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),wl.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){wl.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()};wl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();wl.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){wl.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()};wl.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();wl.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){wl.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()};wl.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();wl.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};wl.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()};wl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=fl.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}wl.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=fl.parse(this._pc.localDescription.sdp));const r=_l.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 gl.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')}}hl.Firefox120=Cl;var Pl={};Object.defineProperty(Pl,"__esModule",{value:!0}),Pl.Safari12=void 0;const Tl=hu,kl=bc,Rl=Hc,Il=Uc,Dl=Tu,Al=Ou,Ol=Ru,Nl=Du,Ml=Au,Ll=new gc.Logger("Safari12"),xl={OS:1024,MIS:1024};class Fl extends kl.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 Fl(e),getNativeRtpCapabilities:async()=>{Ll.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}e=void 0;const r=Tl.parse(t.sdp);return Fl.getLocalRtpCapabilities(r)}catch(t){try{e?.close()}catch(e){}throw e=void 0,t}},getNativeSctpCapabilities:async()=>(Ll.debug("getNativeSctpCapabilities()"),{numStreams:xl})}}static getLocalRtpCapabilities(e){const t=Ol.extractRtpCapabilities({sdpObject:e});return Rl.validateAndNormalizeRtpCapabilities(t),Ml.addNackSupportForOpus(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Ll.debug("constructor()"),this._direction=e,this._remoteSdp=new Al.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):(Ll.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Safari12"}close(){if(Ll.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(),Ll.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Ll.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Ll.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Ll.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Ll.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Ll.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,encodings:t,codecOptions:r,codec:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),Ll.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const s=this._remoteSdp.getNextMediaSectionIdx(),o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});i&&i(o.sender);let a=await this._pc.createOffer(),c=Tl.parse(a.sdp);c.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const d=Fl.getLocalRtpCapabilities(c),u=this._getSendExtendedRtpCapabilities(d),l=Rl.getSendingRtpParameters(e.kind,u);l.codecs=Rl.reduceCodecs(l.codecs,n);const p=Rl.getSendingRemoteRtpParameters(e.kind,u);let h;p.codecs=Rl.reduceCodecs(p.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:c});const f=(0,Dl.parse)((t??[{}])[0].scalabilityMode);t&&t.length>1&&(Ll.debug("send() | enabling legacy simulcast"),c=Tl.parse(a.sdp),h=c.media[s.idx],Nl.addLegacySimulcast({offerMediaObject:h,numStreams:t.length}),a={type:"offer",sdp:Tl.write(c)}),Ll.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const m=o.mid;if(l.mid=m,c=Tl.parse(this._pc.localDescription.sdp),h=c.media[s.idx],l.rtcp.cname=Ol.getCname({offerMediaObject:h}),l.encodings=Nl.getRtpEncodings({offerMediaObject:h}),t)for(let e=0;e<l.encodings.length;++e)t[e]&&Object.assign(l.encodings[e],t[e]);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${f.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:h,reuseMid:s.reuseMid,offerRtpParameters:l,answerRtpParameters:p,codecOptions:r});const g={type:"answer",sdp:this._remoteSdp.getSdp()};return Ll.debug("send() | calling pc.setRemoteDescription() [answer:%o]",g),await this._pc.setRemoteDescription(g),this._mapMidTransceiver.set(m,o),{localId:m,rtpParameters:l,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Ll.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();Ll.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Ll.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Ll.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();Ll.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Ll.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Ll.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();Ll.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Ll.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Ll.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Ll.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(),Ll.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();Ll.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Ll.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Ll.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();Ll.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Ll.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};Ll.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%xl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Tl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Ll.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()};Ll.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;Ll.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Ll.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=Tl.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));Ol.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Tl.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Ll.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){Ll.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()};Ll.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Ll.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){Ll.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()};Ll.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Ll.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){Ll.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()};Ll.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Ll.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};Ll.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()};Ll.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Tl.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Ll.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=Tl.parse(this._pc.localDescription.sdp));const r=Ol.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 Il.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')}}Pl.Safari12=Fl;var jl={};Object.defineProperty(jl,"__esModule",{value:!0}),jl.ReactNative106=void 0;const Ul=hu,Bl=bc,Vl=Hc,Wl=Uc,Hl=Tu,ql=Ou,zl=Ru,Gl=Du,Yl=Au,$l=new gc.Logger("ReactNative106"),Jl={OS:1024,MIS:1024};class Kl extends Bl.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 Kl(e),getNativeRtpCapabilities:async()=>{$l.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}e=void 0;const r=Ul.parse(t.sdp);return Kl.getLocalRtpCapabilities(r)}catch(t){try{e?.close()}catch(e){}throw e=void 0,t}},getNativeSctpCapabilities:async()=>($l.debug("getNativeSctpCapabilities()"),{numStreams:Jl})}}static getLocalRtpCapabilities(e){const t=zl.extractRtpCapabilities({sdpObject:e});return Vl.validateAndNormalizeRtpCapabilities(t),Yl.addNackSupportForOpus(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),$l.debug("constructor()"),this._direction=e,this._remoteSdp=new ql.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):($l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"ReactNative106"}close(){if($l.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(),$l.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),$l.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});$l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};$l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};$l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();$l.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,encodings:t,codecOptions:r,codec:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),$l.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach(((e,t)=>{e.rid=`r${t}`}));const s=this._remoteSdp.getNextMediaSectionIdx(),o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(o.sender);let a=await this._pc.createOffer(),c=Ul.parse(a.sdp);c.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const d=Kl.getLocalRtpCapabilities(c),u=this._getSendExtendedRtpCapabilities(d),l=Vl.getSendingRtpParameters(e.kind,u);l.codecs=Vl.reduceCodecs(l.codecs,n);const p=Vl.getSendingRemoteRtpParameters(e.kind,u);p.codecs=Vl.reduceCodecs(p.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:c});let h=!1;const f=(0,Hl.parse)((t??[{}])[0].scalabilityMode);let m;t&&1===t.length&&f.spatialLayers>1&&"video/vp9"===l.codecs[0].mimeType.toLowerCase()&&($l.debug("send() | enabling legacy simulcast for VP9 SVC"),h=!0,c=Ul.parse(a.sdp),m=c.media[s.idx],Gl.addLegacySimulcast({offerMediaObject:m,numStreams:f.spatialLayers}),a={type:"offer",sdp:Ul.write(c)}),$l.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);let g=o.mid??void 0;if(g||$l.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),l.mid=g,c=Ul.parse(this._pc.localDescription.sdp),m=c.media[s.idx],l.rtcp.cname=zl.getCname({offerMediaObject:m}),t)if(1===t.length){let e=Gl.getRtpEncodings({offerMediaObject:m});Object.assign(e[0],t[0]),h&&(e=[e[0]]),l.encodings=e}else l.encodings=t;else l.encodings=Gl.getRtpEncodings({offerMediaObject:m});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${f.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:m,reuseMid:s.reuseMid,offerRtpParameters:l,answerRtpParameters:p,codecOptions:r});const v={type:"answer",sdp:this._remoteSdp.getSdp()};return $l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",v),await this._pc.setRemoteDescription(v),g||(g=o.mid,l.mid=g),this._mapMidTransceiver.set(g,o),{localId:g,rtpParameters:l,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;$l.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();$l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};$l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),$l.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();$l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};$l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),$l.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();$l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};$l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?$l.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):$l.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(),$l.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();$l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};$l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),$l.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();$l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};$l.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};$l.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Jl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Ul.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),$l.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()};$l.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;$l.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};$l.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=Ul.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));zl.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Ul.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),$l.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){$l.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()};$l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();$l.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){$l.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()};$l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();$l.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){$l.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()};$l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();$l.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};$l.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()};$l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Ul.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}$l.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=Ul.parse(this._pc.localDescription.sdp));const r=zl.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 Wl.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')}}jl.ReactNative106=Kl,Object.defineProperty(nc,"__esModule",{value:!0}),nc.Device=void 0,nc.detectDevice=dp,nc.detectDeviceAsync=up;const Ql=dc,Zl=bc,Xl=Uc,ep=Wc,tp=Hc,rp=Cd,np=pu,ip=el,sp=hl,op=Pl,ap=jl,cp=new gc.Logger("Device");function dp(e){cp.debug("detectDevice() [userAgent:%s]",e),e||"object"!=typeof navigator||(e=navigator.userAgent);return pp(new Ql.default(e))}async function up(e){cp.debug("detectDeviceAsync() [userAgent:%s]",e),e||"object"!=typeof navigator||(e=navigator.userAgent);return pp(new Ql.default(e))}class lp{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new Zl.EnhancedEventEmitter;static async factory({handlerName:e,handlerFactory:t}={}){if(cp.debug("factory()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!e&&!t&&!(e=await up()))throw new Xl.UnsupportedError("device not supported");return new lp({handlerName:e,handlerFactory:t})}constructor({handlerName:e,handlerFactory:t}={}){if(cp.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)cp.debug("constructor() | handler given: %s",e);else{if(!(e=dp()))throw new Xl.UnsupportedError("device not supported");cp.debug("constructor() | detected handler: %s",e)}switch(e){case"Chrome111":this._handlerFactory=np.Chrome111.createFactory();break;case"Chrome74":this._handlerFactory=ip.Chrome74.createFactory();break;case"Firefox120":this._handlerFactory=sp.Firefox120.createFactory();break;case"Safari12":this._handlerFactory=op.Safari12.createFactory();break;case"ReactNative106":this._handlerFactory=ap.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(){if(!this._loaded)throw new Xl.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new Xl.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e,preferLocalCodecsOrder:t=!1}){if(cp.debug("load() [routerRtpCapabilities:%o]",e),this._loaded)throw new Xl.InvalidStateError("already loaded");const r=ep.clone(e);tp.validateAndNormalizeRtpCapabilities(r);const{getNativeRtpCapabilities:n,getNativeSctpCapabilities:i}=this._handlerFactory,s=ep.clone(await n());tp.validateAndNormalizeRtpCapabilities(s),cp.debug("load() | got native RTP capabilities:%o",s),this._getSendExtendedRtpCapabilities=e=>ep.clone(tp.getExtendedRtpCapabilities(e,r,t));const o=tp.getExtendedRtpCapabilities(s,r,!1);this._recvRtpCapabilities=tp.getRecvRtpCapabilities(o),tp.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities),cp.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),this._canProduceByKind.audio=tp.canSend("audio",this._recvRtpCapabilities),this._canProduceByKind.video=tp.canSend("video",this._recvRtpCapabilities),this._sctpCapabilities=await i(),tp.validateSctpCapabilities(this._sctpCapabilities),cp.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),cp.debug("load() succeeded"),this._loaded=!0}canProduce(e){if(!this._loaded)throw new Xl.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 cp.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 cp.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 Xl.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 rp.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 pp(e){if("object"==typeof navigator&&"ReactNative"===navigator.product)return cp.debug("detectDeviceImpl() | React-Native detected"),"undefined"==typeof RTCPeerConnection||"undefined"==typeof RTCRtpTransceiver?void cp.warn("detectDeviceImpl() | unsupported react-native-webrtc without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?"):"ReactNative106";{const t=e.parseUserAgent(),r=/^\d+/.exec(t?.shortVersion??"0"),n=parseInt(r?.[0]??"0",10),i=t.platform===Ql.KnownPlatforms.iphone||t.platform===Ql.KnownPlatforms.ipad||t.platform===Ql.KnownPlatforms.mac&&(t.isMobile||t.isTablet||"object"==typeof navigator&&navigator?.maxTouchPoints>=2),s=t.isChrome,o=t.isFireFox,a=t.isSafari,c=t.isEdge,d=t.isDesktop&&t.name===Ql.KnownBrowsers.electron,u=t.isWebkit,l={browserMajorVersion:n,isIOS:i,isChrome:s,isFirefox:o,isSafari:a,isElectron:d,isWebkit:u};if(cp.debug("detectDeviceImpl() | detected browser [userAgent:%s, parsed:%o, result:%o]",t.userAgent,t,l),(s||c)&&!i&&n>=111)return"Chrome111";if(s&&!i&&n>=74||c&&!i&&n>=88)return"Chrome74";if(d)return"Chrome111";if(o&&!i&&n>=120)return"Firefox120";if(a&&n>=12&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(i&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(u){const t=e.userAgent?.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(t){return Number(t[1])>=111?"Chrome111":"Chrome74"}return"Chrome111"}return void cp.warn("detectDeviceImpl() | browser not supported [userAgent:%s, parsed:%o, result:%o]",t.userAgent,t,l)}}nc.Device=lp;var hp={},fp={},mp={},gp={};Object.defineProperty(gp,"__esModule",{value:!0}),gp.default="ffffffff-ffff-ffff-ffff-ffffffffffff";var vp={};Object.defineProperty(vp,"__esModule",{value:!0}),vp.default="00000000-0000-0000-0000-000000000000";var yp={},_p={},bp={};Object.defineProperty(bp,"__esModule",{value:!0}),bp.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i,Object.defineProperty(_p,"__esModule",{value:!0});const Ep=bp;_p.default=function(e){return"string"==typeof e&&Ep.default.test(e)},Object.defineProperty(yp,"__esModule",{value:!0});const wp=_p;yp.default=function(e){if(!(0,wp.default)(e))throw TypeError("Invalid UUID");let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,255&t,(t=parseInt(e.slice(9,13),16))>>>8,255&t,(t=parseInt(e.slice(14,18),16))>>>8,255&t,(t=parseInt(e.slice(19,23),16))>>>8,255&t,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,255&t)};var Sp={};Object.defineProperty(Sp,"__esModule",{value:!0}),Sp.unsafeStringify=void 0;const Cp=_p,Pp=[];for(let e=0;e<256;++e)Pp.push((e+256).toString(16).slice(1));function Tp(e,t=0){return(Pp[e[t+0]]+Pp[e[t+1]]+Pp[e[t+2]]+Pp[e[t+3]]+"-"+Pp[e[t+4]]+Pp[e[t+5]]+"-"+Pp[e[t+6]]+Pp[e[t+7]]+"-"+Pp[e[t+8]]+Pp[e[t+9]]+"-"+Pp[e[t+10]]+Pp[e[t+11]]+Pp[e[t+12]]+Pp[e[t+13]]+Pp[e[t+14]]+Pp[e[t+15]]).toLowerCase()}Sp.unsafeStringify=Tp,Sp.default=function(e,t=0){const r=Tp(e,t);if(!(0,Cp.default)(r))throw TypeError("Stringified UUID is invalid");return r};var kp={},Rp={};let Ip;Object.defineProperty(Rp,"__esModule",{value:!0});const Dp=new Uint8Array(16);Rp.default=function(){if(!Ip){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ip=crypto.getRandomValues.bind(crypto)}return Ip(Dp)},Object.defineProperty(kp,"__esModule",{value:!0}),kp.updateV1State=void 0;const Ap=Rp,Op=Sp,Np={};function Mp(e,t,r){return e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0),e.node||(e.node=r.slice(10,16),e.node[0]|=1,e.clockseq=16383&(r[8]<<8|r[9])),e.msecs=t,e}function Lp(e,t,r,n,i,s,o=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(s){if(o<0||o+16>s.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`)}else s=new Uint8Array(16),o=0;t??=Date.now(),r??=0,n??=16383&(e[8]<<8|e[9]),i??=e.slice(10,16);const a=(1e4*(268435455&(t+=122192928e5))+r)%4294967296;s[o++]=a>>>24&255,s[o++]=a>>>16&255,s[o++]=a>>>8&255,s[o++]=255&a;const c=t/4294967296*1e4&268435455;s[o++]=c>>>8&255,s[o++]=255&c,s[o++]=c>>>24&15|16,s[o++]=c>>>16&255,s[o++]=n>>>8|128,s[o++]=255&n;for(let e=0;e<6;++e)s[o++]=i[e];return s}kp.updateV1State=Mp,kp.default=function(e,t,r){let n;const i=e?._v6??!1;if(e){const t=Object.keys(e);1===t.length&&"_v6"===t[0]&&(e=void 0)}if(e)n=Lp(e.random??e.rng?.()??(0,Ap.default)(),e.msecs,e.nsecs,e.clockseq,e.node,t,r);else{const e=Date.now(),s=(0,Ap.default)();Mp(Np,e,s),n=Lp(s,Np.msecs,Np.nsecs,i?void 0:Np.clockseq,i?void 0:Np.node,t,r)}return t??(0,Op.unsafeStringify)(n)};var xp={};Object.defineProperty(xp,"__esModule",{value:!0});const Fp=yp,jp=Sp;xp.default=function(e){const t=function(e){return Uint8Array.of((15&e[6])<<4|e[7]>>4&15,(15&e[7])<<4|(240&e[4])>>4,(15&e[4])<<4|(240&e[5])>>4,(15&e[5])<<4|(240&e[0])>>4,(15&e[0])<<4|(240&e[1])>>4,(15&e[1])<<4|(240&e[2])>>4,96|15&e[2],e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}("string"==typeof e?(0,Fp.default)(e):e);return"string"==typeof e?(0,jp.unsafeStringify)(t):t};var Up={},Bp={};function Vp(e){return 14+(e+64>>>9<<4)+1}function Wp(e,t){const r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function Hp(e,t,r,n,i,s){return Wp((o=Wp(Wp(t,e),Wp(n,s)))<<(a=i)|o>>>32-a,r);var o,a}function qp(e,t,r,n,i,s,o){return Hp(t&r|~t&n,e,t,i,s,o)}function zp(e,t,r,n,i,s,o){return Hp(t&n|r&~n,e,t,i,s,o)}function Gp(e,t,r,n,i,s,o){return Hp(t^r^n,e,t,i,s,o)}function Yp(e,t,r,n,i,s,o){return Hp(r^(t|~n),e,t,i,s,o)}Object.defineProperty(Bp,"__esModule",{value:!0}),Bp.default=function(e){const t=function(e){if(0===e.length)return new Uint32Array;const t=new Uint32Array(Vp(8*e.length)).fill(0);for(let r=0;r<e.length;r++)t[r>>2]|=(255&e[r])<<r%4*8;return t}(e),r=function(e,t){const r=new Uint32Array(Vp(t)).fill(0);r.set(e),r[t>>5]|=128<<t%32,r[r.length-1]=t,e=r;let n=1732584193,i=-271733879,s=-1732584194,o=271733878;for(let t=0;t<e.length;t+=16){const r=n,a=i,c=s,d=o;n=qp(n,i,s,o,e[t],7,-680876936),o=qp(o,n,i,s,e[t+1],12,-389564586),s=qp(s,o,n,i,e[t+2],17,606105819),i=qp(i,s,o,n,e[t+3],22,-1044525330),n=qp(n,i,s,o,e[t+4],7,-176418897),o=qp(o,n,i,s,e[t+5],12,1200080426),s=qp(s,o,n,i,e[t+6],17,-1473231341),i=qp(i,s,o,n,e[t+7],22,-45705983),n=qp(n,i,s,o,e[t+8],7,1770035416),o=qp(o,n,i,s,e[t+9],12,-1958414417),s=qp(s,o,n,i,e[t+10],17,-42063),i=qp(i,s,o,n,e[t+11],22,-1990404162),n=qp(n,i,s,o,e[t+12],7,1804603682),o=qp(o,n,i,s,e[t+13],12,-40341101),s=qp(s,o,n,i,e[t+14],17,-1502002290),i=qp(i,s,o,n,e[t+15],22,1236535329),n=zp(n,i,s,o,e[t+1],5,-165796510),o=zp(o,n,i,s,e[t+6],9,-1069501632),s=zp(s,o,n,i,e[t+11],14,643717713),i=zp(i,s,o,n,e[t],20,-373897302),n=zp(n,i,s,o,e[t+5],5,-701558691),o=zp(o,n,i,s,e[t+10],9,38016083),s=zp(s,o,n,i,e[t+15],14,-660478335),i=zp(i,s,o,n,e[t+4],20,-405537848),n=zp(n,i,s,o,e[t+9],5,568446438),o=zp(o,n,i,s,e[t+14],9,-1019803690),s=zp(s,o,n,i,e[t+3],14,-187363961),i=zp(i,s,o,n,e[t+8],20,1163531501),n=zp(n,i,s,o,e[t+13],5,-1444681467),o=zp(o,n,i,s,e[t+2],9,-51403784),s=zp(s,o,n,i,e[t+7],14,1735328473),i=zp(i,s,o,n,e[t+12],20,-1926607734),n=Gp(n,i,s,o,e[t+5],4,-378558),o=Gp(o,n,i,s,e[t+8],11,-2022574463),s=Gp(s,o,n,i,e[t+11],16,1839030562),i=Gp(i,s,o,n,e[t+14],23,-35309556),n=Gp(n,i,s,o,e[t+1],4,-1530992060),o=Gp(o,n,i,s,e[t+4],11,1272893353),s=Gp(s,o,n,i,e[t+7],16,-155497632),i=Gp(i,s,o,n,e[t+10],23,-1094730640),n=Gp(n,i,s,o,e[t+13],4,681279174),o=Gp(o,n,i,s,e[t],11,-358537222),s=Gp(s,o,n,i,e[t+3],16,-722521979),i=Gp(i,s,o,n,e[t+6],23,76029189),n=Gp(n,i,s,o,e[t+9],4,-640364487),o=Gp(o,n,i,s,e[t+12],11,-421815835),s=Gp(s,o,n,i,e[t+15],16,530742520),i=Gp(i,s,o,n,e[t+2],23,-995338651),n=Yp(n,i,s,o,e[t],6,-198630844),o=Yp(o,n,i,s,e[t+7],10,1126891415),s=Yp(s,o,n,i,e[t+14],15,-1416354905),i=Yp(i,s,o,n,e[t+5],21,-57434055),n=Yp(n,i,s,o,e[t+12],6,1700485571),o=Yp(o,n,i,s,e[t+3],10,-1894986606),s=Yp(s,o,n,i,e[t+10],15,-1051523),i=Yp(i,s,o,n,e[t+1],21,-2054922799),n=Yp(n,i,s,o,e[t+8],6,1873313359),o=Yp(o,n,i,s,e[t+15],10,-30611744),s=Yp(s,o,n,i,e[t+6],15,-1560198380),i=Yp(i,s,o,n,e[t+13],21,1309151649),n=Yp(n,i,s,o,e[t+4],6,-145523070),o=Yp(o,n,i,s,e[t+11],10,-1120210379),s=Yp(s,o,n,i,e[t+2],15,718787259),i=Yp(i,s,o,n,e[t+9],21,-343485551),n=Wp(n,r),i=Wp(i,a),s=Wp(s,c),o=Wp(o,d)}return Uint32Array.of(n,i,s,o)}(t,8*e.length);return function(e){const t=new Uint8Array(4*e.length);for(let r=0;r<4*e.length;r++)t[r]=e[r>>2]>>>r%4*8&255;return t}(r)};var $p={};Object.defineProperty($p,"__esModule",{value:!0}),$p.URL=$p.DNS=$p.stringToBytes=void 0;const Jp=yp,Kp=Sp;function Qp(e){e=unescape(encodeURIComponent(e));const t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}$p.stringToBytes=Qp,$p.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",$p.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",$p.default=function(e,t,r,n,i,s){const o="string"==typeof r?Qp(r):r,a="string"==typeof n?(0,Jp.default)(n):n;if("string"==typeof n&&(n=(0,Jp.default)(n)),16!==n?.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+o.length);if(c.set(a),c.set(o,a.length),c=t(c),c[6]=15&c[6]|e,c[8]=63&c[8]|128,i){s=s||0;for(let e=0;e<16;++e)i[s+e]=c[e];return i}return(0,Kp.unsafeStringify)(c)},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.URL=e.DNS=void 0;const t=Bp,r=$p;var n=$p;function i(e,n,i,s){return(0,r.default)(48,t.default,e,n,i,s)}Object.defineProperty(e,"DNS",{enumerable:!0,get:function(){return n.DNS}}),Object.defineProperty(e,"URL",{enumerable:!0,get:function(){return n.URL}}),i.DNS=r.DNS,i.URL=r.URL,e.default=i}(Up);var Zp={},Xp={};Object.defineProperty(Xp,"__esModule",{value:!0});const eh="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);Xp.default={randomUUID:eh},Object.defineProperty(Zp,"__esModule",{value:!0});const th=Xp,rh=Rp,nh=Sp;Zp.default=function(e,t,r){if(th.default.randomUUID&&!t&&!e)return th.default.randomUUID();const n=(e=e||{}).random??e.rng?.()??(0,rh.default)();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){if((r=r||0)<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=n[e];return t}return(0,nh.unsafeStringify)(n)};var ih={},sh={};function oh(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:case 3:return t^r^n;case 2:return t&r^t&n^r&n}}function ah(e,t){return e<<t|e>>>32-t}Object.defineProperty(sh,"__esModule",{value:!0}),sh.default=function(e){const t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(e.length+1);n.set(e),n[e.length]=128;const i=(e=n).length/4+2,s=Math.ceil(i/16),o=new Array(s);for(let t=0;t<s;++t){const r=new Uint32Array(16);for(let n=0;n<16;++n)r[n]=e[64*t+4*n]<<24|e[64*t+4*n+1]<<16|e[64*t+4*n+2]<<8|e[64*t+4*n+3];o[t]=r}o[s-1][14]=8*(e.length-1)/Math.pow(2,32),o[s-1][14]=Math.floor(o[s-1][14]),o[s-1][15]=8*(e.length-1)&4294967295;for(let e=0;e<s;++e){const n=new Uint32Array(80);for(let t=0;t<16;++t)n[t]=o[e][t];for(let e=16;e<80;++e)n[e]=ah(n[e-3]^n[e-8]^n[e-14]^n[e-16],1);let i=r[0],s=r[1],a=r[2],c=r[3],d=r[4];for(let e=0;e<80;++e){const r=Math.floor(e/20),o=ah(i,5)+oh(r,s,a,c)+d+t[r]+n[e]>>>0;d=c,c=a,a=ah(s,30)>>>0,s=i,i=o}r[0]=r[0]+i>>>0,r[1]=r[1]+s>>>0,r[2]=r[2]+a>>>0,r[3]=r[3]+c>>>0,r[4]=r[4]+d>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.URL=e.DNS=void 0;const t=sh,r=$p;var n=$p;function i(e,n,i,s){return(0,r.default)(80,t.default,e,n,i,s)}Object.defineProperty(e,"DNS",{enumerable:!0,get:function(){return n.DNS}}),Object.defineProperty(e,"URL",{enumerable:!0,get:function(){return n.URL}}),i.DNS=r.DNS,i.URL=r.URL,e.default=i}(ih);var ch={};Object.defineProperty(ch,"__esModule",{value:!0});const dh=Sp,uh=kp,lh=xp;ch.default=function(e,t,r){e??={},r??=0;let n=(0,uh.default)({...e,_v6:!0},new Uint8Array(16));if(n=(0,lh.default)(n),t){for(let e=0;e<16;e++)t[r+e]=n[e];return t}return(0,dh.unsafeStringify)(n)};var ph={};Object.defineProperty(ph,"__esModule",{value:!0});const hh=yp,fh=Sp;ph.default=function(e){const t=function(e){return Uint8Array.of((15&e[3])<<4|e[4]>>4&15,(15&e[4])<<4|(240&e[5])>>4,(15&e[5])<<4|15&e[6],e[7],(15&e[1])<<4|(240&e[2])>>4,(15&e[2])<<4|(240&e[3])>>4,16|(240&e[0])>>4,(15&e[0])<<4|(240&e[1])>>4,e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}("string"==typeof e?(0,hh.default)(e):e);return"string"==typeof e?(0,fh.unsafeStringify)(t):t};var mh={};Object.defineProperty(mh,"__esModule",{value:!0}),mh.updateV7State=void 0;const gh=Rp,vh=Sp,yh={};function _h(e,t,r){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],e.msecs=t):(e.seq=e.seq+1|0,0===e.seq&&e.msecs++),e}function bh(e,t,r,n,i=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(n){if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`)}else n=new Uint8Array(16),i=0;return t??=Date.now(),r??=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9],n[i++]=t/1099511627776&255,n[i++]=t/4294967296&255,n[i++]=t/16777216&255,n[i++]=t/65536&255,n[i++]=t/256&255,n[i++]=255&t,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|3&e[10],n[i++]=e[11],n[i++]=e[12],n[i++]=e[13],n[i++]=e[14],n[i++]=e[15],n}mh.updateV7State=_h,mh.default=function(e,t,r){let n;if(e)n=bh(e.random??e.rng?.()??(0,gh.default)(),e.msecs,e.seq,t,r);else{const e=Date.now(),i=(0,gh.default)();_h(yh,e,i),n=bh(i,yh.msecs,yh.seq,t,r)}return t??(0,vh.unsafeStringify)(n)};var Eh={};Object.defineProperty(Eh,"__esModule",{value:!0});const wh=_p;Eh.default=function(e){if(!(0,wh.default)(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.version=e.validate=e.v7=e.v6ToV1=e.v6=e.v5=e.v4=e.v3=e.v1ToV6=e.v1=e.stringify=e.parse=e.NIL=e.MAX=void 0;var t=gp;Object.defineProperty(e,"MAX",{enumerable:!0,get:function(){return t.default}});var r=vp;Object.defineProperty(e,"NIL",{enumerable:!0,get:function(){return r.default}});var n=yp;Object.defineProperty(e,"parse",{enumerable:!0,get:function(){return n.default}});var i=Sp;Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return i.default}});var s=kp;Object.defineProperty(e,"v1",{enumerable:!0,get:function(){return s.default}});var o=xp;Object.defineProperty(e,"v1ToV6",{enumerable:!0,get:function(){return o.default}});var a=Up;Object.defineProperty(e,"v3",{enumerable:!0,get:function(){return a.default}});var c=Zp;Object.defineProperty(e,"v4",{enumerable:!0,get:function(){return c.default}});var d=ih;Object.defineProperty(e,"v5",{enumerable:!0,get:function(){return d.default}});var u=ch;Object.defineProperty(e,"v6",{enumerable:!0,get:function(){return u.default}});var l=ph;Object.defineProperty(e,"v6ToV1",{enumerable:!0,get:function(){return l.default}});var p=mh;Object.defineProperty(e,"v7",{enumerable:!0,get:function(){return p.default}});var h=_p;Object.defineProperty(e,"validate",{enumerable:!0,get:function(){return h.default}});var f=Eh;Object.defineProperty(e,"version",{enumerable:!0,get:function(){return f.default}})}(mp);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].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 Ch={};Object.defineProperty(Ch,"__esModule",{value:!0}),Ch.FakeEvent=void 0;Ch.FakeEvent=class{NONE=0;CAPTURING_PHASE=1;AT_TARGET=2;BUBBLING_PHASE=3;type;bubbles;cancelable;defaultPrevented=!1;composed=!1;currentTarget=null;eventPhase=l.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 Ph={};Object.defineProperty(Ph,"__esModule",{value:!0}),Ph.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(fp,"__esModule",{value:!0}),fp.FakeMediaStreamTrack=void 0;const Th=mp,kh=Sh,Rh=Ch,Ih=Ph;class Dh extends kh.FakeEventTarget{#b;#E;#w;#S;#C;#P;#T;#k;#R;#I;#D;#A=null;#O=null;#N=null;#M=null;#L=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.#b=t??(0,Th.v4)(),this.#E=e,this.#w=r??"",this.#T=n??"",this.#C=i??!0,this.#P=s??!1,this.#S=o??"live",this.#k=a??{},this.#R=c??{},this.#I=d??{},this.#D=u??{}}get id(){return this.#b}get kind(){return this.#E}get label(){return this.#w}get contentHint(){return this.#T}set contentHint(e){this.#T=e}get enabled(){return this.#C}set enabled(e){const t=this.#C!==e;this.#C=e,t&&this.dispatchEvent(new Rh.FakeEvent("enabledchange"))}get muted(){return this.#P}get readyState(){return this.#S}get data(){return this.#D}set data(e){this.#D=e}get onmute(){return this.#A}set onmute(e){this.#A&&this.removeEventListener("mute",this.#A),this.#A=e,e&&this.addEventListener("mute",e)}get onunmute(){return this.#O}set onunmute(e){this.#O&&this.removeEventListener("unmute",this.#O),this.#O=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.#M}set onenabledchange(e){this.#M&&this.removeEventListener("enabledchange",this.#M),this.#M=e,e&&this.addEventListener("enabledchange",e)}get onstopped(){return this.#L}set onstopped(e){this.#L&&this.removeEventListener("stopped",this.#L),this.#L=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.#S&&(this.#S="ended",this.dispatchEvent(new Rh.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new Dh({id:e??(0,Th.v4)(),kind:this.#E,label:this.#w,contentHint:this.#T,enabled:this.#C,muted:this.#P,readyState:this.#S,capabilities:(0,Ih.clone)(this.#k),constraints:(0,Ih.clone)(this.#R),settings:(0,Ih.clone)(this.#I),data:t??(0,Ih.clone)(this.#D)})}getCapabilities(){return this.#k}getConstraints(){return this.#R}async applyConstraints(e={}){return this.#R=e,Promise.resolve()}getSettings(){return this.#I}remoteStop(){"ended"!==this.#S&&(this.#S="ended",this.dispatchEvent(new Rh.FakeEvent("stopped")),this.dispatchEvent(new Rh.FakeEvent("ended")))}remoteMute(){this.#P||(this.#P=!0,this.dispatchEvent(new Rh.FakeEvent("mute")))}remoteUnmute(){this.#P&&(this.#P=!1,this.dispatchEvent(new Rh.FakeEvent("unmute")))}}fp.FakeMediaStreamTrack=Dh;var Ah={};Object.defineProperty(Ah,"__esModule",{value:!0}),Ah.FakeEventTarget=void 0;Ah.FakeEventTarget=class{listeners={};addEventListener(e,t,r){t&&(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(hp,"__esModule",{value:!0}),hp.FakeHandler=void 0;const Oh=fp,Nh=bc,Mh=Wc,Lh=Hc,xh=Uc,Fh=Ah,jh=new gc.Logger("FakeHandler");class Uh extends Nh.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${Mh.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:"FakeHandler",factory:t=>new Uh(t,e),getNativeRtpCapabilities:async()=>(jh.debug("getNativeRtpCapabilities()"),Uh.getLocalRtpCapabilities(e)),getNativeSctpCapabilities:async()=>(jh.debug("getNativeSctpCapabilities()"),e.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(e){const t=e.generateNativeRtpCapabilities();return Lh.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),jh.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return"FakeHandler"}close(){jh.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(),jh.debug("updateIceServers()")}async restartIce(e){this.assertNotClosed(),jh.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:e,encodings:t,codecOptions:r,codec:n}){this.assertNotClosed(),jh.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});const i=Uh.getLocalRtpCapabilities(this._fakeParameters),s=this._getSendExtendedRtpCapabilities(i),o=Lh.getSendingRtpParameters(e.kind,s);o.codecs=Lh.reduceCodecs(o.codecs,n);const a=o.codecs.some((e=>/.+\/rtx$/i.test(e.mimeType)));o.mid=`mid-${Mh.generateRandomNumber()}`,t||(t=[{}]);for(const e of t)e.ssrc=Mh.generateRandomNumber(),a&&(e.rtx={ssrc:Mh.generateRandomNumber()});o.encodings=t,o.rtcp={cname:this._cname,reducedSize:!0,mux:!0};const c=this._nextLocalId++;return this._tracks.set(c,e),{localId:String(c),rtpParameters:o}}async stopSending(e){if(jh.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?jh.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):jh.debug("replaceTrack() [localId:%s, no track]",e),this._tracks.delete(Number(e)),this._tracks.set(Number(e),t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),jh.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),jh.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"}),jh.debug("sendDataChannel()");return{dataChannel:new Bh({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"}),jh.debug("receive() [trackId:%s, kind:%s]",e,n);const i=this._nextLocalId++,s=new Oh.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)jh.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"}),jh.debug("receiveDataChannel()");return{dataChannel:new Bh({id:e.streamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:t,protocol:r})}}async setupTransport({localDtlsRole:e,localSdpObject:t}){const r=Mh.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 xh.InvalidStateError("method called in a closed handler")}}hp.FakeHandler=Uh;class Bh extends Fh.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(),jh.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 xh.InvalidStateError("not open")}}var Vh={};Object.defineProperty(Vh,"__esModule",{value:!0}),Vh.generateRouterRtpCapabilities=function(){return Wh.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"}]})},Vh.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}]}},Vh.generateNativeSctpCapabilities=function(){return Wh.deepFreeze({numStreams:{OS:2048,MIS:2048}})},Vh.generateLocalDtlsParameters=function(){return Wh.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"})},Vh.generateTransportRemoteParameters=function(){return{id:Hh(),iceParameters:Wh.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:Wh.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:Wh.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:Wh.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}},Vh.generateProducerRemoteParameters=function(){return Wh.deepFreeze({id:Hh()})},Vh.generateConsumerRemoteParameters=function({id:e,codecMimeType:t}={}){switch(t){case"audio/opus":return{id:e??Hh(),producerId:Hh(),kind:"audio",rtpParameters:Wh.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??Hh(),producerId:Hh(),kind:"audio",rtpParameters:Wh.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??Hh(),producerId:Hh(),kind:"video",rtpParameters:Wh.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??Hh(),producerId:Hh(),kind:"video",rtpParameters:Wh.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}'`)}},Vh.generateDataProducerRemoteParameters=function(){return Wh.deepFreeze({id:Hh()})},Vh.generateDataConsumerRemoteParameters=function({id:e}={}){return{id:e??Hh(),dataProducerId:Hh(),sctpStreamParameters:Wh.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}};const Wh=Wc;function Hh(){return String(Wh.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=$a.exports;e.debug=t.default,e.types=rc,e.version="3.15.6";var r=nc;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=Tu;Object.defineProperty(e,"parseScalabilityMode",{enumerable:!0,get:function(){return n.parse}}),e.ortc=Hc,e.enhancedEvents=bc;var i=hp;Object.defineProperty(e,"FakeHandler",{enumerable:!0,get:function(){return i.FakeHandler}}),e.testFakeParameters=Vh}(Ya);const qh=[{scaleResolutionDownBy:4,maxBitrate:15e4,maxFramerate:12},{scaleResolutionDownBy:2,maxBitrate:35e4,maxFramerate:18},{scaleResolutionDownBy:1,maxBitrate:9e5,maxFramerate:24}],zh=[{maxBitrate:1e6,dtx:!0}],Gh=[{maxBitrate:4e4,dtx:!0}],Yh={width:1280,height:720},$h=0,Jh=2,Kh=0;function Qh(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 Zh(e,t){e.onreadystatechange=function(){"complete"!=this.readyState&&"loaded"!=this.readyState||(this.onreadystatechange=null,t(null,e))}}const Xh=new Bn,ef=e=>a(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?Qh:Zh)(i,r),i.onload||Qh(i,r),n.appendChild(i)}(e,((e,n)=>{e?r(e):t(n)}))}))})),tf=(e,...t)=>a(void 0,[e,...t],void 0,(function*(e,t=3,r=500){let n=0;for(;n<t;)try{return void(yield ef(e))}catch(e){if(n+=1,!(n<t))throw e;yield Xh.sleepMs(r)}}));var rf;let nf=class{constructor(){rf.set(this,new Map)}add(e,t,r){const n=this.getKey(e,t);if(c(this,rf,"f").has(n))throw new Error("Attempt to rewrite cached track processor");c(this,rf,"f").set(n,r)}get(e,t){return c(this,rf,"f").get(this.getKey(e,t))}has(e,t){return c(this,rf,"f").has(this.getKey(e,t))}getKey(e,t){return`${e}:${t}`}reset(){for(const e of c(this,rf,"f").values())e.stopProcessing(),e.release();c(this,rf,"f").clear()}};var sf,of;rf=new WeakMap,nf=i([at()],nf);let af=class{constructor(e,t,r,n){this.config=e,this.processorsCache=t,this.audioTrackProcessorFactory=r,sf.set(this,new Map),of.set(this,void 0),d(this,of,n("IntegrationsService"),"f")}init(){const e=this.config.get("denoiser");if("asdk"===e){c(this,of,"f").info("Start integration of ASDK",{denoiser:e});const t={integrated:!1,initPromise:this.integrateASDK()};c(this,sf,"f").set("asdk",t)}else{c(this,of,"f").info("Start integration of RNNoise",{denoiser:e});const t={integrated:!1,initPromise:this.integrateRNNoise()};c(this,sf,"f").set("rnnoise",t)}}integrateASDK(){return a(this,void 0,void 0,(function*(){const e=this.config.get("asdk"),t=this.config.get("staticFilesPath");if(!window.atsvb){const s=`https://effectssdk.ai/sdk/audio/dev/${e.version}/atsvb-web.js`;let o=s;if(e.localDir){const n=`${e.localDir}/${e.version}/atsvb-web.js`;o=new r(n,t).href}yield(n=o,i=s,a(void 0,void 0,void 0,(function*(){try{yield tf(n)}catch(e){if(!i)throw e;yield tf(i)}})))}var n,i;if(!window.atsvb)throw c(this,of,"f").info("Audio Effects SDK is not loaded, skipping initialization",{case:"initAudioSDK"}),new Error("windows.atsvb is still missing");const s=this.audioTrackProcessorFactory({trackLabel:zn.Microphone});yield s.init(),this.processorsCache.add("asdk",zn.Microphone,s);const o=c(this,sf,"f").get("asdk");if(!o)throw Error("IntegrationContext is missing for ASDK");o.integrated=!0}))}get audio(){return"asdk"===this.config.get("denoiser")?this.getASDKState():this.getRNNoiseState()}getASDKState(){var e,t;const r=c(this,sf,"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=c(this,sf,"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 a(this,void 0,void 0,(function*(){const e=yield function(e){return a(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:zn.Microphone,noiseSuppressor:e});this.processorsCache.add("rnnoise",zn.Microphone,t);const r=c(this,sf,"f").get("rnnoise");if(!r)throw Error("IntegrationContext is missing for RNNoise");r.integrated=!0}))}reset(){c(this,sf,"f").clear()}};var cf,df,uf,lf,pf,hf,ff,mf,gf;sf=new WeakMap,of=new WeakMap,af=i([at(),s(0,dt(Hn.Config)),s(1,dt(Hn.ProcessorsCache)),s(2,dt(Hn.AudioTrackProcessorFactory)),s(3,dt(Hn.LoggerFactory)),o("design:paramtypes",[Pt,nf,Function,Function])],af),function(e){e.INFO="info",e.WARNING="warning",e.ERROR="error"}(mf||(mf={})),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"}(gf||(gf={}));class vf{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,void 0);const{loggerFactory:t}=e;if(d(this,df,t("EffectsSDKTrackProcessor"),"f"),d(this,ff,e.onModelsLoaded,"f"),!e.customerId)throw new Error("Customer ID must be provided");d(this,cf,new window.tsvb(e.customerId),"f"),c(this,cf,"f").onError(this.tsvbErrorHandler.bind(this)),c(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.5.8"}`:`https://effectssdk.ai/sdk/web/${null!=i?i:"3.5.8"}`,o={preset:"balanced",provider:"webgpu",sdk_url:e.sdk_url,api_url:e.api_url,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`}};c(this,cf,"f").config(o)}init(){return a(this,void 0,void 0,(function*(){yield c(this,cf,"f").preload(),yield c(this,cf,"f").cache(),d(this,hf,!0,"f")}))}awaitReady(){return a(this,void 0,void 0,(function*(){yield new Promise(((e,t)=>{const r=Date.now(),n=setInterval((()=>{if(this.isModelsLoaded)return clearInterval(n),void e();Date.now()-r>6e4&&(clearInterval(n),t(new Error("ESDK init timeout")))}),100)}))}))}tsvbErrorHandler(e){var t;const{emitter:r,type:i}=e,s=n(e,["emitter","type"]),o=null!=r?r:"N/A emitter";i===mf.ERROR&&c(this,df,"f").error(o,Object.assign({error:pr(e)},s)),i===mf.WARNING&&c(this,df,"f").warn(o,Object.assign({},s)),i===mf.INFO&&c(this,df,"f").info(o,Object.assign({},s)),r===gf.ML_INFERENCE&&(s.message.toLocaleLowerCase().includes("init lowlighter")&&(c(this,uf,"f").lowLighter=!0),s.message.toLocaleLowerCase().includes("init colorcorrector")&&(c(this,uf,"f").colorCorrector=!0),s.message.toLocaleLowerCase().includes("init facedetector")&&(c(this,uf,"f").faceDetector=!0),s.message.toLocaleLowerCase().includes("init segmentation")&&(c(this,uf,"f").segmentation=!0),this.isModelsLoaded&&(null===(t=c(this,ff,"f"))||void 0===t||t.call(this)))}get isModelsLoaded(){return c(this,uf,"f").colorCorrector&&c(this,uf,"f").faceDetector&&c(this,uf,"f").lowLighter&&c(this,uf,"f").segmentation}get modelsLoadProgress(){return Object.values(c(this,uf,"f")).filter(Boolean).length/Object.keys(c(this,uf,"f")).length}get isReady(){return c(this,hf,"f")}setOnLoadModels(e){d(this,ff,e,"f"),this.isModelsLoaded&&c(this,ff,"f").call(this)}onReady(){d(this,hf,!0,"f"),c(this,df,"f").debug("onReady()",{description:"ESDK is ready"}),this.updateEffects(c(this,pf,"f"))}processTrack(e){var t,r,n;if(c(this,lf,"f")===e||"ended"===e.readyState)return null!==(r=null===(t=c(this,cf,"f").getStream())||void 0===t?void 0:t.getVideoTracks()[0])&&void 0!==r?r:e;this.stopProcessing();try{c(this,cf,"f").useStream(new MediaStream([e]));const t=null===(n=c(this,cf,"f").getStream())||void 0===n?void 0:n.getVideoTracks()[0];return t?(d(this,lf,e,"f"),t):e}catch(t){throw c(this,df,"f").error("processTrack()",{error:t,track:e}),new Error("Can not process this track")}}stopProcessing(){try{c(this,cf,"f").clear(),c(this,cf,"f").stop()}catch(e){c(this,df,"f").error("stopProcessing()",{error:e})}finally{d(this,lf,null,"f")}}updateEffects(e){var t,r,n,i,s,o,a,u,l,p,h,f,m,g,v,y,_,b,E,w,S,C;if(d(this,pf,e,"f"),!c(this,hf,"f"))return void c(this,df,"f").warn("updateEffects()",{description:"Esdk not ready"});if(!c(this,pf,"f")||0===Object.keys(c(this,pf,"f")).length)return void c(this,cf,"f").stop();let P=0;if((null===(t=c(this,pf,"f"))||void 0===t?void 0:t.blur)&&!(null===(r=c(this,pf,"f"))||void 0===r?void 0:r.backgroundColor)?(c(this,cf,"f").setBlur(c(this,pf,"f").blur),P+=1):c(this,cf,"f").clearBlur(),void 0!==(null===(n=c(this,pf,"f"))||void 0===n?void 0:n.background)?(c(this,cf,"f").setBackground(c(this,pf,"f").background),P+=1):void 0!==(null===(i=c(this,pf,"f"))||void 0===i?void 0:i.backgroundColor)?(c(this,cf,"f").setBackgroundColor(null===(s=c(this,pf,"f"))||void 0===s?void 0:s.backgroundColor),c(this,cf,"f").setBackground("color"),P+=1):c(this,cf,"f").clearBackground(),(null===(o=c(this,pf,"f"))||void 0===o?void 0:o.beautification)?(c(this,cf,"f").enableBeautification(),c(this,cf,"f").setBeautificationLevel(c(this,pf,"f").beautification),P+=1):c(this,cf,"f").disableBeautification(),(null===(a=c(this,pf,"f"))||void 0===a?void 0:a.lowLightEffect)?(c(this,cf,"f").enableLowLightEffect(),c(this,cf,"f").setLowLightEffectPower(c(this,pf,"f").lowLightEffect),P+=1):c(this,cf,"f").disableLowLightEffect(),(null===(u=c(this,pf,"f"))||void 0===u?void 0:u.colorCorrector)?(c(this,cf,"f").enableColorCorrector(),c(this,cf,"f").setColorCorrectorPower(c(this,pf,"f").colorCorrector),P+=1):c(this,cf,"f").disableColorCorrector(),(null===(l=c(this,pf,"f"))||void 0===l?void 0:l.smartZoom)?(c(this,cf,"f").enableSmartZoom(),c(this,cf,"f").setFaceArea(c(this,pf,"f").smartZoom),P+=1):c(this,cf,"f").disableSmartZoom(),(null===(p=c(this,pf,"f"))||void 0===p?void 0:p.layout)?(c(this,cf,"f").setLayout(c(this,pf,"f").layout),P+=1):c(this,cf,"f").setLayout("center"),(null===(h=c(this,pf,"f"))||void 0===h?void 0:h.colorFilter)&&(null===(f=c(this,pf,"f"))||void 0===f?void 0:f.colorFilter.power)&&(null===(m=c(this,pf,"f"))||void 0===m?void 0:m.colorFilter.url)?(c(this,cf,"f").setColorFilterConfig({lut:c(this,pf,"f").colorFilter.url,power:c(this,pf,"f").colorFilter.power}),c(this,cf,"f").enableColorFilter(),P+=1):c(this,cf,"f").disableColorFilter(),null===(g=c(this,pf,"f"))||void 0===g?void 0:g.lowerThird){const e=c(this,cf,"f").createComponent({component:c(this,pf,"f").lowerThird.type,options:null!==(v=c(this,pf,"f").lowerThird.options)&&void 0!==v?v:{}});null===(b=null===(_=null===(y=c(this,cf,"f").components)||void 0===y?void 0:y.lowerThird)||void 0===_?void 0:_.hideLowerThird)||void 0===b||b.call(_),c(this,cf,"f").addComponent(e,"lowerThird"),c(this,cf,"f").components.lowerThird.showLowerThird(),P+=1}else null===(S=null===(w=null===(E=c(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=c(this,pf,"f"))||void 0===C?void 0:C.sharpness)?(c(this,cf,"f").setSharpnessEffectConfig(c(this,pf,"f").sharpness),P+=1):c(this,cf,"f").disableSharpnessEffect(),P>2?c(this,cf,"f").enableFrameSkipping():c(this,cf,"f").disableFrameSkipping(),c(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;const yf=e=>"rtx"!==e.mimeType;var _f,bf,Ef,wf,Sf,Cf,Pf,Tf,kf,Rf,If,Df,Af,Of,Nf,Mf,Lf;class xf{constructor({track:e,statsHandler:t}){_f.set(this,void 0),bf.set(this,void 0),this.handleWebRTCStats(e,t)}get videoWebRTCStats(){return c(this,_f,"f")}get audioWebRTCStats(){return c(this,bf,"f")}handleWebRTCStats(e,t){e.addEventListener("ended",(()=>{t.removeInboundVideoHandler(e.id),t.removeInboundAudioHandler(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){d(this,_f,e,"f")}setAudioWebRTCStats(e){d(this,bf,e,"f")}}_f=new WeakMap,bf=new WeakMap,function(e){e.CloseProducer="CloseProducer",e.Mute="Mute",e.Resume="Resume"}(Ef||(Ef={}));class Ff{constructor(e){wf.set(this,void 0),Sf.set(this,void 0),this.encoderConfig={},this.label=zn.Unknown,Cf.set(this,void 0),Pf.set(this,void 0),Tf.set(this,void 0),kf.set(this,void 0),Rf.set(this,void 0),If.set(this,void 0),Df.set(this,void 0),Af.set(this,void 0),Of.set(this,!0),Nf.set(this,void 0),Mf.set(this,void 0),Lf.set(this,void 0);const{mediaStreamTrack:t,internalEventEmitter:r,constraints:n,mediaStreamTrackManager:i,media:s,myPeer:o,network:a,socket:c,mutex:u,loggerFactory:l,loggerNamespace:p,statsHandler:h}=e;d(this,wf,t,"f"),d(this,Rf,r,"f"),d(this,If,n,"f"),d(this,Df,i,"f"),d(this,Af,new Tt,"f"),this.logger=l(p),d(this,Nf,u,"f"),d(this,Pf,s,"f"),d(this,Cf,o,"f"),d(this,Tf,a,"f"),d(this,kf,c,"f"),d(this,Lf,h,"f"),d(this,Mf,new xf({track:t,statsHandler:h}),"f")}get videoWebRTCStats(){return c(this,Mf,"f").videoWebRTCStats}get audioWebRTCStats(){return c(this,Mf,"f").audioWebRTCStats}get logCtx(){return{label:this.getLabel(),id:this.id,kind:this.kind,producerId:this.producerId,paused:this.isPaused,published:this.isPublished}}get observer(){return c(this,Af,"f")}get mediaStreamTrack(){return c(this,wf,"f")}get originalTrack(){return c(this,Sf,"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 c(this,Rf,"f")}getLabel(){return this.label}setLabel(e){this.label=e}setEncoderConfig(e){this.encoderConfig=e}getEncoderConfig(){return this.encoderConfig}setProducer(e){this.producer=e}setStopTrackOnPause(e){this.isPublished||d(this,Of,e,"f")}getProducer(){return this.producer}setOriginalTrack(){d(this,Sf,this.mediaStreamTrack,"f")}closeProducer(){return a(this,arguments,void 0,(function*(e=!0){const t=yield c(this,Nf,"f").lock(Ef.CloseProducer);if(!this.producer)return void t();const{producerId:r}=this;try{r&&(yield c(this,Tf,"f").closeRemoteProducer(r),this.logger.info("Remote producer closed",{producerId:r}))}catch(e){this.logger.warn("closeProducer()",{label:this.getLabel(),error:pr(e),producerId:r})}this.producer.close(),this.producer=void 0,e&&this.stopMediaStreamTrack(),t()}))}setPriority(e){return a(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.warn("setPriority()",{priority:e,reason:"Not published yet"})}))}stopMediaStreamTrack(){this.mediaStreamTrack.stop(),this.mediaStreamTrack.dispatchEvent(new Event("ended")),this.stopOriginalTrack()}stopOriginalTrack(){c(this,Sf,"f")&&(c(this,Sf,"f").stop(),d(this,Sf,void 0,"f"))}produce(e){return a(this,arguments,void 0,(function*({encodings:e,codecOptions:t,preferredCodec:r,transformParams:n,keyFrameRequestDelay:i}){var s,o,a,d,u;if(!c(this,Cf,"f").canPublish)throw this.logger.error("produce()",{message:"Not enough access to produce"}),new Error("Not enough access to produce");if(this.producer)throw new Error("Track already produced");try{yield c(this,kf,"f").request(Sr);const{rtpCapabilities:{codecs:l}}=c(this,Pf,"f").mediasoupDevice,p=null==l?void 0:l.find((e=>e.mimeType.toLowerCase()===`${this.kind}/${r}`)),h=0,f=this.prepareProducerEncodings({codec:p,encodings:null!=e?e:[],maxSpatialLayer:(null!=e?e:[]).length-1}),m={trackTransformParams:n,peerId:String(c(this,Cf,"f").id),label:this.getLabel(),maxSpatialLayer:h,encodings:f,codecOptions:t,preferredCodec:r,codec:p,keyFrameRequestDelay:i},g=yield null===(s=c(this,Tf,"f").sendTransport)||void 0===s?void 0:s.produce({track:this.mediaStreamTrack,encodings:f,codecOptions:t,codec:p,stopTracks:!1,disableTrackOnPause:!0,zeroRtpOnPause:!0,appData:m});if(!g)return;const v=g.rtpSender,y=()=>/Safari/i.test(navigator.userAgent);if(e&&v&&y()){const t=v.getParameters();e.forEach((({maxBitrate:e,scaleResolutionDownBy:r},n)=>{t.encodings[n]&&(t.encodings[n].maxBitrate=e,t.encodings[n].scaleResolutionDownBy=r)})),yield v.setParameters(t)}this.setProducer(g),(null===(a=null===(o=this.producer)||void 0===o?void 0:o.track)||void 0===a?void 0:a.id)!==c(this,wf,"f").id&&(this.logger.info("Producer initialized with old track, updating",{oldTrackId:null===(u=null===(d=this.producer)||void 0===d?void 0:d.track)||void 0===u?void 0:u.id,newTrackId:c(this,wf,"f").id}),yield this.replaceTrack(c(this,wf,"f"))),"video"===this.kind&&(e&&v&&p&&Un(p.mimeType)&&!y()?yield v.setParameters(Object.assign(Object.assign({},v.getParameters()),{encodings:this.prepareProducerEncodings({encodings:e,codec:p,maxSpatialLayer:h})})):yield g.setMaxSpatialLayer(h),yield c(this,kf,"f").request(pn,{producerId:g.id,maxSpatialLayer:h})),"audio"===this.kind&&(yield this.setPriority("high")),this.logger.debug("produce()",{track:this.logCtx,encodings:e,codecOptions:t})}catch(e){throw this.logger.error("produce()",{error:e,track:this.logCtx}),new Error("Publish track failed")}}))}publish(){return a(this,void 0,void 0,(function*(){yield this.produce({}),this.internalEventEmitter.emit($r.trackProduced,this)}))}unpublish(){return a(this,arguments,void 0,(function*(e=!0){try{e&&this.stopMediaStreamTrack(),this.internalEventEmitter.emit($r.trackUnproduced,this),this.producer&&(yield this.closeProducer()),this.logger.debug("unpublish()",{track:this.logCtx})}catch(e){this.logger.error("unpublish()",{error:e})}}))}pauseRemoteProducer(e){return a(this,void 0,void 0,(function*(){return yield c(this,kf,"f").request(un,{producerId:e})}))}resumeRemoteProducer(e){return a(this,void 0,void 0,(function*(){return yield c(this,kf,"f").request(ln,{producerId:e})}))}mute(e){return a(this,void 0,void 0,(function*(){const t=yield c(this,Nf,"f").lock(Ef.Mute);if(!this.producer)return this.logger.warn("pause()",{message:"Track is not published",track:this.logCtx}),void t();try{if(this.producer.pause(),this.logger.debug("pause()",{track:this.logCtx}),c(this,Of,"f"))return null==e||e(),c(this,wf,"f").stop(),this.stopOriginalTrack(),this.internalEventEmitter.emit($r.trackClosed,this),void(yield this.pauseRemoteProducer(this.producer.id));yield this.pauseRemoteProducer(this.producer.id),this.internalEventEmitter.emit($r.trackPaused,this)}catch(e){throw this.logger.error("pause()",{error:e,track:this.logCtx}),yield c(this,Pf,"f").deleteTrack(this),this.internalEventEmitter.emit($r.trackFailed,this),new Error("Can`t pause track, removing")}finally{t()}}))}resume(){return a(this,void 0,void 0,(function*(){const e=yield c(this,Nf,"f").lock(Ef.Resume);if(!this.producer)return this.logger.warn("resume()",{message:"Track is not published",track:this.logCtx}),void e();try{if(this.logger.debug("resume()",{track:this.logCtx}),c(this,Of,"f"))return yield this.reopenMediaStreamTrack(),yield this.resumeProducer(),void this.internalEventEmitter.emit($r.trackReopened,this);yield this.resumeProducer(),this.internalEventEmitter.emit($r.trackResumed,this)}catch(e){throw this.logger.error("resume()",{error:e,track:this.logCtx}),new Error("Can`t resume track")}finally{e()}}))}getInfo(){return a(this,void 0,void 0,(function*(){const{width:e,height:t,frameRate:r,aspectRatio:n}=c(this,wf,"f").getSettings();return{trackId:c(this,wf,"f").id,readyState:c(this,wf,"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 a(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=>yf(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 a(this,void 0,void 0,(function*(){var t;try{d(this,wf,e,"f"),this.internalEventEmitter.emit($r.trackReopened,this),this.observer.safeEmit("track-changed",{track:e}),yield null===(t=this.producer)||void 0===t?void 0:t.replaceTrack({track:e}),d(this,Mf,new xf({track:e,statsHandler:c(this,Lf,"f")}),"f")}catch(e){this.logger.warn("replaceTrack()",{error:e})}}))}resumeProducer(){return a(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 a(this,void 0,void 0,(function*(){var e;const t=yield c(this,Df,"f").createMediaStreamTrack({label:this.label,constraints:c(this,If,"f")});d(this,wf,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&&t.length>1&&r&&Un(r.mimeType)?[t[n]||t[0]]:t}getOutboundRTPStreamStats(){return a(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>{const r=(...n)=>a(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((()=>a(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:pr(e)})}))}))}))}}var jf,Uf,Bf,Vf;wf=new WeakMap,Sf=new WeakMap,Cf=new WeakMap,Pf=new WeakMap,Tf=new WeakMap,kf=new WeakMap,Rf=new WeakMap,If=new WeakMap,Df=new WeakMap,Af=new WeakMap,Of=new WeakMap,Nf=new WeakMap,Mf=new WeakMap,Lf=new WeakMap;class Wf extends Ff{constructor(e){super(e),this.transformParams={},jf.set(this,void 0),Uf.set(this,void 0),Bf.set(this,!1),Vf.set(this,(()=>{})),d(this,Uf,e,"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(c(this,jf,"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()===zn.ScreenVideo?"vp8":"h264")}getEncodings(){var e;return null!==(e=this.getEncoderConfig().encodings)&&void 0!==e?e:qh}setTransformParams(e){this.transformParams=e}setMaxSpatialLayer(e){return a(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.warn("setMaxSpatialLayer()",{message:"Not produced yet"})}))}getMaxSpatialLayer(){const e=this.getProducer();if(e)return e.maxSpatialLayer;this.logger.warn("getMaxSpatialLayer()",{message:"Not produced yet"})}enableEffects(){return a(this,void 0,void 0,(function*(){if(!c(this,Bf,"f")){d(this,Bf,!0,"f");try{if(c(this,jf,"f"))return this.logger.debug("enableEffects()",{description:"Track is already processed"}),void d(this,Bf,!1,"f");if("ended"===this.mediaStreamTrack.readyState)return void this.logger.warn("Track already ended",{case:"enableEffects"});const{media:e}=c(this,Uf,"f");if(!e.effectsSDKInitialized)return void this.logger.warn("Effects SDK not initialized",{case:"enableEffects"});const t=Date.now();d(this,jf,yield e.createEffectsSDKTrackProcessor(this.getLabel()),"f"),this.setOriginalTrack();const r=c(this,jf,"f").processTrack(this.mediaStreamTrack),n=Date.now();this.logger.info("enableEffects() time",{time:(n-t)/1e3}),yield this.replaceTrack(r),this.logger.info("enableEffects()",{track:this.logCtx})}catch(e){this.logger.warn("enableEffects()",{track:this.logCtx,error:pr(e)}),this.disableEffects().catch((e=>{this.logger.warn("Failed to this.disableEffects() in catch{}",{track:this.logCtx,error:pr(e)})})),c(this,Vf,"f").call(this,e)}finally{d(this,Bf,!1,"f")}}}))}disableEffects(){return a(this,void 0,void 0,(function*(){var e;try{if(!c(this,jf,"f"))return void this.logger.debug("disableEffects()",{description:"Track is not processed"});this.originalTrack?yield this.replaceTrack(this.originalTrack):this.logger.warn("disableEffects()",{description:"Original track missing"}),null===(e=c(this,jf,"f"))||void 0===e||e.stopProcessing(),d(this,jf,void 0,"f"),this.logger.info("disableEffects()",{track:this.logCtx})}catch(e){this.logger.warn("disableEffects()",{track:this.logCtx,error:e})}}))}publish(){return a(this,arguments,void 0,(function*(e={}){var t;yield this.produce({encodings:this.getEncodings(),preferredCodec:this.getPreferredCodec(),transformParams:this.transformParams,codecOptions:this.getCodecOptions(),keyFrameRequestDelay:null!==(t=e.keyFrameRequestDelay)&&void 0!==t?t:0}),this.internalEventEmitter.emit($r.trackProduced,this)}))}adjustEncodingPresetToCurrentMaxSpatialLayer(e){return a(this,void 0,void 0,(function*(){var t;if(!Un(this.getPreferredCodec()))return;const{rtpSender:r}=null!==(t=this.getProducer())&&void 0!==t?t:{};if(!r)return void this.logger.warn("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 a(this,void 0,void 0,(function*(){var t;try{!this.isEffectsProcessing&&Object.keys(e).length>0&&(yield this.enableEffects()),null===(t=c(this,jf,"f"))||void 0===t||t.updateEffects(e)}catch(e){c(this,Vf,"f").call(this,e)}}))}resetEffects(){var e;null===(e=c(this,jf,"f"))||void 0===e||e.updateEffects({})}setOnLoadModels(e){var t;null===(t=c(this,jf,"f"))||void 0===t||t.setOnLoadModels(e)}get modelsLoadProgress(){var e,t;return null!==(t=null===(e=c(this,jf,"f"))||void 0===e?void 0:e.modelsLoadProgress)&&void 0!==t?t:0}pause(){return a(this,void 0,void 0,(function*(){yield this.mute((()=>{var e;c(this,jf,"f")&&(null===(e=c(this,jf,"f"))||void 0===e||e.stopProcessing(),d(this,jf,void 0,"f"))}))}))}setOnEffectError(e){d(this,Vf,e,"f")}}var Hf,qf;jf=new WeakMap,Uf=new WeakMap,Bf=new WeakMap,Vf=new WeakMap;let zf=qf=class{constructor(e){Hf.set(this,void 0),d(this,Hf,e("MediaStreamTrackManager"),"f")}createMediaStreamTrack(e){return a(this,arguments,void 0,(function*({label:e,constraints:t}){if(qf.isDisplayMedia(e)){const[e]=yield this.createDisplayMediaTracks(t);return e}const[r]=yield this.createUserMediaTracks(t);return r}))}static isDisplayMedia(e){return[zn.ScreenVideo,zn.ScreenAudio].includes(e)}createUserMediaTracks(e){return a(this,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.getUserMedia(e);return c(this,Hf,"f").debug("createUserMediaTracks() stream created",{streamId:t.id}),t.getTracks()}))}createDisplayMediaTracks(e){return a(this,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.getDisplayMedia(e);return c(this,Hf,"f").debug("getDisplayMediaTracks() stream created",{streamId:t.id}),t.getTracks()}))}};Hf=new WeakMap,zf=qf=i([at(),s(0,dt(Hn.LoggerFactory)),o("design:paramtypes",[Function])],zf);var Gf,Yf,$f,Jf,Kf,Qf,Zf,Xf=zf;let em=class{constructor(e,t,r,n,i,s,o,a,c){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.socket=c,this.isDeviceLoaded=!1,this.tracks=new Map,Gf.set(this,void 0),Yf.set(this,null),$f.set(this,!1),Jf.set(this,new Map),Kf.set(this,!1),Qf.set(this,!1),Zf.set(this,void 0);const u=this.config.get("effectsSDKParams");d(this,Zf,this.config.get("denoiser"),"f"),d(this,Gf,this.loggerFactory("Media"),"f"),d(this,Yf,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 c(this,$f,"f")}get effectsSDKParams(){return c(this,Yf,"f")}getTrack(e){return this.tracks.get(e)}loadDevice(e){return a(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()}`));c(this,Gf,"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"})),c(this,Gf,"f").debug("createTrack() track created",{trackId:n.id,kind:n.kind}),n}))}createUserMediaTracks(e){return a(this,void 0,void 0,(function*(){const t=yield this.mediaStreamTrackManager.createUserMediaTracks(e);return this.createTracks({constraints:e,mediaStreamTracks:t})}))}createDisplayMediaTracks(e){return a(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 a(this,void 0,void 0,(function*(){const t={trackId:e.id,label:e.getLabel(),producerId:e.producerId};try{"disableNoiseSuppression"in e&&(yield e.disableNoiseSuppression()),"disableEffects"in e&&(yield e.disableEffects())}catch(e){c(this,Gf,"f").warn("deleteTrack()",Object.assign({error:e},t))}try{this.tracks.delete(e.getLabel()),e.stopMediaStreamTrack(),yield e.closeProducer()}catch(e){c(this,Gf,"f").error("deleteTrack()",{error:e})}finally{c(this,Gf,"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){c(this,Gf,"f").warn("clearTracks()",{error:e})}finally{this.tracks.clear()}}unpublishTracks(){return a(this,void 0,void 0,(function*(){try{yield Promise.all(this.publishedTracks().map((e=>a(this,void 0,void 0,(function*(){return yield e.unpublish(!1)})))))}catch(e){c(this,Gf,"f").warn("unpublishTracks()",{error:e})}}))}setTrack(e){this.tracks.set(e.getLabel(),e)}initEffectsSDK(){return a(this,void 0,void 0,(function*(){if(c(this,$f,"f"))return!0;if(!c(this,Yf,"f"))throw c(this,Gf,"f").error("Effects SDK config params not provided",{case:"initEffectsSDK"}),new Error("Effects SDK config not provided");const e=(e,t)=>a(this,void 0,void 0,(function*(){if(!window.tsvb)return c(this,Gf,"f").info("Effects SDK not loaded, skipping initialization",{case:"initEffectsSDK"}),void e(!1);c(this,Gf,"f").info("Effects SDK initializing",{case:"initEffectsSDK"});try{c(this,Jf,"f").set(zn.Camera,yield this.createEffectsSDKTrackProcessor(zn.Camera)),c(this,Jf,"f").set(zn.CameraPreview,yield this.createEffectsSDKTrackProcessor(zn.CameraPreview)),d(this,$f,!0,"f"),c(this,Gf,"f").info("Effects SDK initialized",{case:"initEffectsSDK"}),e(!0)}catch(e){c(this,Gf,"f").error("Failed to initialize Effects SDK",{error:e,case:"initEffectsSDK"}),t(e)}}));return yield new Promise(((t,r)=>{if(!window.tsvb)return c(this,Gf,"f").info("Effects SDK tsvb-web.js is not ready, waiting",{case:"initEffectsSDK"}),void window.addEventListener("load",(()=>a(this,void 0,void 0,(function*(){return yield e(t,r)}))));e(t,r).catch((e=>{c(this,Gf,"f").error("Failed to execute init() in initEffectsSDK",{error:pr(e)})}))}))}))}initDenoiser(e,t){return a(this,void 0,void 0,(function*(){if(!c(this,Kf,"f"))try{d(this,Kf,!0,"f"),this.clientEventEmitter.emit(Vr,!0);try{yield this.integrationsService.audio.waitForInitialization}catch(e){"asdk"===c(this,Zf,"f")&&(d(this,Qf,!0,"f"),d(this,Zf,"rnnoise","f"),this.config.set("denoiser",c(this,Zf,"f")),c(this,Gf,"f").debug("Set config to rnnoise denoiser",{case:"Denoiser",error:pr(e),type:this.config.get("denoiser")}),this.clientEventEmitter.emit(zr),this.integrationsService.init(),yield this.integrationsService.audio.waitForInitialization)}c(this,Gf,"f").debug("Denoiser initialized, activating",{case:"Denoiser",type:this.integrationsService.audio.type,trackLabel:e.getLabel()});const r=e,n=this.processorsCache.get(c(this,Zf,"f"),zn.Microphone);if(!n)return void c(this,Gf,"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(Vr,!0),this.fallbackToRNoise(e,{reason:r,options:t,error:n}).catch((t=>{c(this,Gf,"f").error("Failed to fallback to RNNoise through onError",{case:"Denoiser",type:c(this,Zf,"f"),error:pr(t),label:e.getLabel()})})).then((()=>{this.clientEventEmitter.emit(Vr,!1)})).catch((()=>{}))})),r.setTrackProcessor(n),c(this,Gf,"f").debug("Denoiser trackProcessor set, check if activation is needed",{case:"Denoiser",type:c(this,Zf,"f"),shouldEnableDenoiser:null==t?void 0:t.noiseSuppression,trackLabel:e.getLabel()}),(null==t?void 0:t.noiseSuppression)&&(yield e.enableNoiseSuppression())}catch(r){if(c(this,Gf,"f").warn("Failed to start noise suppression, featured original track",{case:"Denoiser",type:c(this,Zf,"f"),error:pr(r),label:e.getLabel()}),"asdk"===c(this,Zf,"f"))try{c(this,Gf,"f").warn("Fallback to RNNoise",{error:pr(r)}),yield this.fallbackToRNoise(e,{options:t,reason:"ASDK init error",error:r})}catch(t){c(this,Gf,"f").error("Failed to fallback to RNNoise through catch",{case:"Denoiser",type:c(this,Zf,"f"),error:pr(t),label:e.getLabel()})}}finally{this.clientEventEmitter.emit(Vr,!1),d(this,Kf,!1,"f")}}))}fallbackToRNoise(e,t){return a(this,void 0,void 0,(function*(){var r;if(c(this,Qf,"f"))return;if(d(this,Qf,!0,"f"),"rnnoise"===c(this,Zf,"f"))return;this.clientEventEmitter.emit(zr),c(this,Gf,"f").info("Fallback to RNNoise",{reason:null==t?void 0:t.reason,error:pr(null==t?void 0:t.error),case:"Denoiser"});const n=e;yield n.disableNoiseSuppression(),n.unsetTrackProcessor(),d(this,Zf,"rnnoise","f"),this.config.set("denoiser",c(this,Zf,"f")),c(this,Gf,"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(c(this,Zf,"f"),zn.Microphone);i?(n.setTrackProcessor(i),(null===(r=null==t?void 0:t.options)||void 0===r?void 0:r.noiseSuppression)&&(yield n.enableNoiseSuppression())):c(this,Gf,"f").error("No cached trackProcessor found",{case:"Denoiser",trackLabel:e.getLabel(),type:this.integrationsService.audio.type})}))}createEffectsSDKTrackProcessor(e){return a(this,void 0,void 0,(function*(){var t,r,n;if(e){const t=c(this,Jf,"f").get(e);if(t)return t}if(!c(this,Yf,"f"))throw c(this,Gf,"f").error("Effects SDK config params not provided",{case:"initEffectsSDK"}),new Error("Effects SDK config not provided");const i=new vf({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(),c(this,Gf,"f").info("Track effects processor initialized",{trackLabel:e}),i}))}handleProducerSetMaxSpatialLayer(e){return a(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 c(this,Gf,"f").warn("producerRequestMaxSpatialLayer()",{message:"Producer not found"});if(!(r instanceof Wf))return void c(this,Gf,"f").warn("producerRequestMaxSpatialLayer()",{message:"Wrong producer kind"});const n=null!=t?t:$h,i=r.getMaxSpatialLayer();i!==n?(r.getEncodings().length>1&&(yield r.setMaxSpatialLayer(n)),yield this.socket.request(pn,{producerId:e,maxSpatialLayer:n}),yield r.adjustEncodingPresetToCurrentMaxSpatialLayer(n)):c(this,Gf,"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:Yh.width,height:null!==(r=n.height)&&void 0!==r?r:Yh.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:Yh.width},height:{max:Yh.height}},encoderConfig:null!==(r=null==e?void 0:e.videoEncoderConfig)&&void 0!==r?r:{encodings:zh}}}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:Yh.width},height:{max:Yh.height}},encoderConfig:null!==(r=null==e?void 0:e.encoderConfig)&&void 0!==r?r:{encodings:qh}}}createDevice(){const e=(e=>{const t=null!=e?e:null===navigator||void 0===navigator?void 0:navigator.userAgent;if(!t)return;const r=Fn.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":void 0})();return c(this,Gf,"f").debug("Creating a media device",{handlerName:null!=e?e:"not specified"}),new Ya.Device({handlerName:e})}};Gf=new WeakMap,Yf=new WeakMap,$f=new WeakMap,Jf=new WeakMap,Kf=new WeakMap,Qf=new WeakMap,Zf=new WeakMap,em=i([at(),s(0,dt(Hn.Config)),s(1,dt(Hn.LoggerFactory)),s(2,dt(Hn.AudioTrackFactory)),s(3,dt(Hn.ClientEventEmitter)),s(4,dt(Hn.IntegrationsService)),s(5,dt(Hn.ProcessorsCache)),s(6,dt(Hn.VideoTrackFactory)),s(7,dt(Hn.MediaStreamTrackManager)),s(8,dt(Hn.SocketIO)),o("design:paramtypes",[Pt,Function,Function,Tt,af,nf,Function,Xf,la])],em);var tm=em;const rm={[Wi.PRODUCER_KIND_VIDEO]:"video",[Wi.PRODUCER_KIND_AUDIO]:"audio"},nm={[Gi.PEER_ROLE_HOST]:"host",[Gi.PEER_ROLE_AUDIENCE]:"audience"},im={[Ni.PRODUCER_LABEL_CAMERA]:zn.Camera,[Ni.PRODUCER_LABEL_MICROPHONE]:zn.Microphone,[Ni.PRODUCER_LABEL_SCREEN_VIDEO]:zn.ScreenVideo,[Ni.PRODUCER_LABEL_SCREEN_AUDIO]:zn.ScreenAudio,[Ni.PRODUCER_LABEL_CUSTOM_VIDEO]:zn.CustomVideo,[Ni.PRODUCER_LABEL_CUSTOM_AUDIO]:zn.CustomAudio,[Ni.PRODUCER_LABEL_UNKNOWN]:zn.Unknown,[Ni.PRODUCER_LABEL_UNSPECIFIED]:zn.Unknown},sm={[Oi.PEER_GROUP_MODERATOR]:"moderator",[Oi.PEER_GROUP_USER]:"user"},om=e=>{const t=rm[e];if(!t)throw new Error(`Unknown producer kind: ${e}`);return t},am=e=>{const t=sm[e];if(!t)throw new Error(`Unknown peer group: ${e}`);return t},cm=e=>{const t=im[e];if(!t)throw new Error(`Unknown producer label: ${e}`);return t},dm=e=>{const t=nm[e];if(!t)throw new Error(`Unknown peer role: ${e}`);return t},um=e=>({id:e.id,channelIds:e.channelIds,groups:e.groups.map(am),producePermissions:e.producePermissions.map(cm),appId:e.appId,producers:e.producers.map(lm),uid:e.uid,appData:e.appData,role:dm(e.role),loginDate:e.loginDate}),lm=e=>{var t;return{id:e.id,kind:om(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}},pm=e=>{switch(e){case"moderator":return Oi.PEER_GROUP_MODERATOR;case"user":return Oi.PEER_GROUP_USER;default:return Oi.PEER_GROUP_UNSPECIFIED}};var hm;let fm=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,hm.set(this,void 0),d(this,hm,o("ChannelStateSyncEventHandler"),"f"),this.debouncedTriggerChannelStateEvent=Ln(this.triggerChannelStateEvent.bind(this),3e3),this.watchNetworkState()}handleChannelStateEvent(e){return a(this,void 0,void 0,(function*(){this.network.peersLoaded?yield this.restoreState(e):this.loadChannelState(e),this.clientEventEmitter.emit(Wr)}))}watchNetworkState(){this.clientEventEmitter.on(jr,(()=>{this.debouncedTriggerChannelStateEvent()}))}triggerChannelStateEvent(){return a(this,void 0,void 0,(function*(){const e=()=>a(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>a(this,void 0,void 0,(function*(){const r=yield this.network.triggerChannelStateEvent("host"),n=setTimeout((()=>{this.eventsQueue.isMessageReceived(r)?(c(this,hm,"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(Fr,i),e()};this.clientEventEmitter.on(Fr,i)}))))}));try{yield Wn(e,{maxRetries:5,actionName:"triggerChannelStateEventWithRetry",logger:c(this,hm,"f")})}catch(e){c(this,hm,"f").warn("Failed to trigger channel state event",{case:"ChannelStateSynchronizer.triggerChannelStateEvent",error:pr(e)})}}))}loadChannelState(e){c(this,hm,"f").info("Loading channel state",{case:"loadChannelState"});try{const t=this.peers.hosts().map((e=>e.shortData)),r=e.peers.filter((e=>e.role===Gi.PEER_ROLE_HOST));this.setMissingPeers(t,r),this.restoreLocalPeersState(r),this.network.peersLoaded=!0}catch(e){c(this,hm,"f").error("Failed to load channel state",{case:"loadState",error:pr(e)})}}restoreState(e){return a(this,void 0,void 0,(function*(){const{peers:t}=e,r={missingPeers:[],removedPeers:[],missingProducers:[],removedProducers:[],fixedProducersState:[],fixedConsumersState:[],restoredAppDataPeers:[]};try{if(!this.network.isSocketConnectionActive)return c(this,hm,"f").info("Connection inactive, skipping restore local state",{case:"restoreLocalState"}),r;c(this,hm,"f").info("Restoring local state",{case:"restoreLocalState"});const e=this.peers.hosts().map((e=>e.shortData)),n=t.filter((e=>e.role===Gi.PEER_ROLE_HOST)),{removedProducers:i,fixedProducersState:s}=yield this.restoreRemoteProducersState(n);r.removedProducers.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 c(this,hm,"f").info("Failed to restore local state",{case:"restoreLocalState",error:pr(e)}),r}}))}restoreRemoteProducersState(e){return a(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=this.media.getAllTracks(),s=n.producers.filter((e=>!i.map((e=>e.producerId)).some((t=>e.id===t))));yield Promise.all(s.map((e=>a(this,void 0,void 0,(function*(){yield this.network.closeRemoteProducer(e.id),r.producers.delete(e.id),t.removedProducers.push(e.id),c(this,hm,"f").info("Unnecessary local producer closed",{case:"restoreLocalState",removedProducerId:e.id,removedProducerPeerId:e.peerId})})))));const o=n.producers.filter((e=>!!i.find((t=>t.isPaused&&t.isPaused!==e.paused))));return yield Promise.all(o.map((e=>a(this,void 0,void 0,(function*(){yield this.network.pauseRemoteProducer(e.id),t.fixedProducersState.push(e.id),c(this,hm,"f").info("Remote producer state repaired",{case:"restoreLocalState",removedProducerId:e.id,removedProducerPeerId:e.peerId})}))))),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=>{c(this,hm,"f").error("Failed to remove peer",{error:pr(e)})})),r.push(e.id),c(this,hm,"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(um(t));r.push(n.id),c(this,hm,"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 c(this,hm,"f").warn("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)})),c(this,hm,"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(dn,t),r.push(t.id),c(this,hm,"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(cn,lm(t)),r.missingProducers.push(t.id),void c(this,hm,"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?Qr:Zr;e.observer.safeEmit(n,{producerId:i.id,kind:i.kind,label:i.label,paused:i.paused}),r.fixedProducersState.push(t.id),c(this,hm,"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:yn;e.observer.safeEmit(s,n),r.fixedConsumersState.push(n),c(this,hm,"f").info("Consumer state fixed",{case:"restoreLocalState",consumerId:n,consumerProducerId:t.id,consumerProducerPeerId:t.peerId})}})),r}restoreAppData(e,t){return!Mn(e.appData,t.appData)&&(e.observer.emit(vr,t.appData),c(this,hm,"f").info("Application data restored",{case:"restoreLocalState",peerId:e.id,appData:t.appData}),!0)}};hm=new WeakMap,fm=i([at(),s(0,dt(Hn.Network)),s(1,dt(Hn.Media)),s(2,dt(Hn.MyPeer)),s(3,dt(Hn.EventsQueue)),s(4,dt(Hn.ClientEventEmitter)),s(5,dt(Hn.Peers)),s(6,dt(Hn.LoggerFactory)),o("design:paramtypes",[Aa,tm,js,xs,Tt,Oa,Function])],fm);var mm,gm=fm;let vm=class{constructor(e,t,r,n,i){this.peers=e,this.clientEventEmitter=t,this.channelStateSyncEventHandler=n,this.channelStateSynchronizer=i,mm.set(this,void 0),d(this,mm,r("ChannelEvents"),"f")}handleChannelEvent(e){return a(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;this.clientEventEmitter.safeEmit(Cr,t),c(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(um(e.peer));c(this,mm,"f").debug("Peer joined to the channel",{peer:Fs(t)})}handlePeerLeft(e){if(!e.peer)throw new Error("Missing peer in PEER_LEFT event");this.peers.remove(e.peer.id).catch((e=>{c(this,mm,"f").debug("Failed to remove peer",{error:pr(e)})})),c(this,mm,"f").debug("Peer left the channel",{peerId:e.peer.id})}handleChannelState(e){return a(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){c(this,mm,"f").error("Failed to restore channel state",{case:"restoreLocalState",error:pr(e)})}}))}handleChannelStateShort(e){if(!e.channelStateShort)throw new Error("Missing channelStateShort in CHANNEL_STATE_SHORT event");this.channelStateSyncEventHandler.handleChannelStateShort(e.channelStateShort).catch((e=>{c(this,mm,"f").error("Failed to handle channel state short event",{error:pr(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(vr,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(am))}handleChannelActivityConfirmationExpired(){this.clientEventEmitter.safeEmit(Ir),c(this,mm,"f").info("Notify the channel that it has disconnected due to the activity confirmation expiring",{})}handleChannelActivityConfirmationAcquired(){this.clientEventEmitter.safeEmit(Rr),c(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(kr,t),c(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(pm(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)})),c(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(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(pm(e)))))),n=e.channelProducePermissions.producePermissions.map(cm);r.forEach((e=>{const t=e.producePermissions.filter((e=>!n.includes(e)));e.handleProducePermissionsChange(t)})),c(this,mm,"f").info("Peers deleted produce permissions",{groups:t,producePermissions:n})}};mm=new WeakMap,vm=i([at(),s(0,dt(Hn.Peers)),s(1,dt(Hn.ClientEventEmitter)),s(2,dt(Hn.LoggerFactory)),s(3,dt(Hn.ChannelStateSyncEventHandler)),s(4,dt(Hn.ChannelStateSynchronizer)),o("design:paramtypes",[Oa,Tt,Function,Ga,gm])],vm);var ym=vm,_m={},bm=l&&l.__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){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(_m,"__esModule",{value:!0});var Em,wm,Sm=_m.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 bm(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 bm(this,void 0,void 0,(function*(){const e=this.pendingTasks[0];e&&(yield this.executeTask(e),this.pendingTasks.shift(),this.next())}))}executeTask(e){return bm(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 Cm=class{constructor(e,t,r,n,i){this.media=e,this.internalEventEmitter=t,this.peersStorage=r,this.clientEventEmitter=n,Em.set(this,new Sm),wm.set(this,void 0),d(this,wm,i("MediaEvents"),"f")}handleMediaEvent(e){switch(e.eventType){case bs.MEDIA_EVENT_TYPE_PRODUCER_CREATED:this.handleProducerCreated(e);break;case bs.MEDIA_EVENT_TYPE_PRODUCER_CLOSED:this.handleProducerClosed(e);break;case bs.MEDIA_EVENT_TYPE_PRODUCER_PAUSED:this.handleProducerPaused(e);break;case bs.MEDIA_EVENT_TYPE_PRODUCER_RESUMED:this.handleProducerResumed(e);break;case bs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED:this.handleProducerMaxSpatialLayerChanged(e);break;case bs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED:this.handleProducerRequestMaxSpatialLayer(e).catch((e=>{c(this,wm,"f").error("Failed to handle producer max spatial layer requested event",{error:pr(e)})}));break;case bs.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED:this.handleProducerForciblyClosed(e).catch((e=>{c(this,wm,"f").error("Failed to handle producer forcibly closed event",{error:pr(e)})}));break;case bs.MEDIA_EVENT_TYPE_CONSUMER_CLOSED:this.handleConsumerClosed(e);break;case bs.MEDIA_EVENT_TYPE_CONSUMER_RESUMED:this.handleConsumerResumed(e);break;case bs.MEDIA_EVENT_TYPE_CONSUMER_PAUSED:this.handleConsumerPaused(e);break;case bs.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED:this.handleConsumerPreferredLayersChanged(e);break;case bs.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(cn,lm(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(dn,lm(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(Qr,{producerId:r.id,kind:r.kind,label:r.label,paused:r.paused}))}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(Zr,{producerId:r.id,kind:r.kind,label:r.label,paused:r.paused}))}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(pn,{peerId:e.producer.peerId,producerId:e.producer.id,spatialLayer:e.producer.maxSpatialLayer})}handleProducerRequestMaxSpatialLayer(e){return a(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 c(this,Em,"f").push((()=>a(this,void 0,void 0,(function*(){yield this.media.handleProducerSetMaxSpatialLayer({producerId:t,spatialLayer:r})}))),hn)}))}handleProducerForciblyClosed(e){return a(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.getTrack(t);if(!r)return;r.stopMediaStreamTrack(),this.internalEventEmitter.safeEmit($r.trackClosed,r);const n={label:t};this.clientEventEmitter.emit(Nr,n),yield this.media.deleteTrack(r)}))}handleConsumerClosed(e){if(!e.consumer)throw new Error("Missing consumer in MEDIA_EVENT_TYPE_CONSUMER_CLOSED");const t=this.peersStorage.get(e.consumer.producerPeerId);null==t||t.observer.safeEmit(gn,e.consumer.id)}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(yn,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){if(!e.consumer)throw new Error("Missing consumer in MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED");if(void 0===e.consumer.spatialLayer||void 0===e.consumer.temporalLayer)return;const t=this.peersStorage.get(e.consumer.peerId);null==t||t.observer.safeEmit(_n,{consumerId:e.consumer.id,spatialLayer:e.consumer.spatialLayer,temporalLayer:e.consumer.temporalLayer})}handleTransportConnectionTimeout(e){if(!e.transportConnectionTimeout)throw new Error("Missing transportConnectionTimeout in MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT");c(this,wm,"f").warn("Transport connection timed out",{transportId:e.transportConnectionTimeout.transportId,direction:e.transportConnectionTimeout.direction,timeout:e.transportConnectionTimeout.timeout,reason:e.transportConnectionTimeout.reason})}};Em=new WeakMap,wm=new WeakMap,Cm=i([at(),s(0,dt(Hn.Media)),s(1,dt(Hn.InternalEventEmitter)),s(2,dt(Hn.PeersStorage)),s(3,dt(Hn.ClientEventEmitter)),s(4,dt(Hn.LoggerFactory)),o("design:paramtypes",[tm,Tt,_a,Tt,Function])],Cm);var Pm=Cm,Tm={exports:{}},km=function(e,t){return function(){for(var r=new Array(arguments.length),n=0;n<r.length;n++)r[n]=arguments[n];return e.apply(t,r)}},Rm=km,Im=Object.prototype.toString;function Dm(e){return"[object Array]"===Im.call(e)}function Am(e){return void 0===e}function Om(e){return null!==e&&"object"==typeof e}function Nm(e){if("[object Object]"!==Im.call(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}function Mm(e){return"[object Function]"===Im.call(e)}function Lm(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),Dm(e))for(var r=0,n=e.length;r<n;r++)t.call(null,e[r],r,e);else for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.call(null,e[i],i,e)}var xm={isArray:Dm,isArrayBuffer:function(e){return"[object ArrayBuffer]"===Im.call(e)},isBuffer:function(e){return null!==e&&!Am(e)&&null!==e.constructor&&!Am(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){return"undefined"!=typeof FormData&&e instanceof FormData},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:Om,isPlainObject:Nm,isUndefined:Am,isDate:function(e){return"[object Date]"===Im.call(e)},isFile:function(e){return"[object File]"===Im.call(e)},isBlob:function(e){return"[object Blob]"===Im.call(e)},isFunction:Mm,isStream:function(e){return Om(e)&&Mm(e.pipe)},isURLSearchParams:function(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)},forEach:Lm,merge:function e(){var t={};function r(r,n){Nm(t[n])&&Nm(r)?t[n]=e(t[n],r):Nm(r)?t[n]=e({},r):Dm(r)?t[n]=r.slice():t[n]=r}for(var n=0,i=arguments.length;n<i;n++)Lm(arguments[n],r);return t},extend:function(e,t,r){return Lm(t,(function(t,n){e[n]=r&&"function"==typeof t?Rm(t,r):t})),e},trim:function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e}},Fm=xm;function jm(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var Um=function(e,t,r){if(!t)return e;var n;if(r)n=r(t);else if(Fm.isURLSearchParams(t))n=t.toString();else{var i=[];Fm.forEach(t,(function(e,t){null!=e&&(Fm.isArray(e)?t+="[]":e=[e],Fm.forEach(e,(function(e){Fm.isDate(e)?e=e.toISOString():Fm.isObject(e)&&(e=JSON.stringify(e)),i.push(jm(t)+"="+jm(e))})))})),n=i.join("&")}if(n){var s=e.indexOf("#");-1!==s&&(e=e.slice(0,s)),e+=(-1===e.indexOf("?")?"?":"&")+n}return e},Bm=xm;function Vm(){this.handlers=[]}Vm.prototype.use=function(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1},Vm.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},Vm.prototype.forEach=function(e){Bm.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var Wm=Vm,Hm=xm,qm=function(e,t,r,n,i){return e.config=t,r&&(e.code=r),e.request=n,e.response=i,e.isAxiosError=!0,e.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code}},e},zm=qm,Gm=function(e,t,r,n,i){var s=new Error(e);return zm(s,t,r,n,i)},Ym=Gm,$m=xm,Jm=$m.isStandardBrowserEnv()?{write:function(e,t,r,n,i,s){var o=[];o.push(e+"="+encodeURIComponent(t)),$m.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),$m.isString(n)&&o.push("path="+n),$m.isString(i)&&o.push("domain="+i),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},Km=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)},Qm=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},Zm=xm,Xm=["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"],eg=xm,tg=eg.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");function n(e){var n=e;return t&&(r.setAttribute("href",n),n=r.href),r.setAttribute("href",n),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:"/"===r.pathname.charAt(0)?r.pathname:"/"+r.pathname}}return e=n(window.location.href),function(t){var r=eg.isString(t)?n(t):t;return r.protocol===e.protocol&&r.host===e.host}}():function(){return!0},rg=xm,ng=function(e,t,r){var n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(Ym("Request failed with status code "+r.status,r.config,null,r.request,r)):e(r)},ig=Jm,sg=Um,og=function(e,t){return e&&!Km(t)?Qm(e,t):t},ag=function(e){var t,r,n,i={};return e?(Zm.forEach(e.split("\n"),(function(e){if(n=e.indexOf(":"),t=Zm.trim(e.substr(0,n)).toLowerCase(),r=Zm.trim(e.substr(n+1)),t){if(i[t]&&Xm.indexOf(t)>=0)return;i[t]="set-cookie"===t?(i[t]?i[t]:[]).concat([r]):i[t]?i[t]+", "+r:r}})),i):i},cg=tg,dg=Gm,ug=function(e){return new Promise((function(t,r){var n=e.data,i=e.headers,s=e.responseType;rg.isFormData(n)&&delete i["Content-Type"];var o=new XMLHttpRequest;if(e.auth){var a=e.auth.username||"",c=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.Authorization="Basic "+btoa(a+":"+c)}var d=og(e.baseURL,e.url);function u(){if(o){var n="getAllResponseHeaders"in o?ag(o.getAllResponseHeaders()):null,i={data:s&&"text"!==s&&"json"!==s?o.response:o.responseText,status:o.status,statusText:o.statusText,headers:n,config:e,request:o};ng(t,r,i),o=null}}if(o.open(e.method.toUpperCase(),sg(d,e.params,e.paramsSerializer),!0),o.timeout=e.timeout,"onloadend"in o?o.onloadend=u:o.onreadystatechange=function(){o&&4===o.readyState&&(0!==o.status||o.responseURL&&0===o.responseURL.indexOf("file:"))&&setTimeout(u)},o.onabort=function(){o&&(r(dg("Request aborted",e,"ECONNABORTED",o)),o=null)},o.onerror=function(){r(dg("Network Error",e,null,o)),o=null},o.ontimeout=function(){var t="timeout of "+e.timeout+"ms exceeded";e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),r(dg(t,e,e.transitional&&e.transitional.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",o)),o=null},rg.isStandardBrowserEnv()){var l=(e.withCredentials||cg(d))&&e.xsrfCookieName?ig.read(e.xsrfCookieName):void 0;l&&(i[e.xsrfHeaderName]=l)}"setRequestHeader"in o&&rg.forEach(i,(function(e,t){void 0===n&&"content-type"===t.toLowerCase()?delete i[t]:o.setRequestHeader(t,e)})),rg.isUndefined(e.withCredentials)||(o.withCredentials=!!e.withCredentials),s&&"json"!==s&&(o.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&o.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&o.upload&&o.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then((function(e){o&&(o.abort(),r(e),o=null)})),n||(n=null),o.send(n)}))},lg=xm,pg=function(e,t){Hm.forEach(e,(function(r,n){n!==t&&n.toUpperCase()===t.toUpperCase()&&(e[t]=r,delete e[n])}))},hg=qm,fg={"Content-Type":"application/x-www-form-urlencoded"};function mg(e,t){!lg.isUndefined(e)&&lg.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var gg,vg={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:(("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(gg=ug),gg),transformRequest:[function(e,t){return pg(t,"Accept"),pg(t,"Content-Type"),lg.isFormData(e)||lg.isArrayBuffer(e)||lg.isBuffer(e)||lg.isStream(e)||lg.isFile(e)||lg.isBlob(e)?e:lg.isArrayBufferView(e)?e.buffer:lg.isURLSearchParams(e)?(mg(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):lg.isObject(e)||t&&"application/json"===t["Content-Type"]?(mg(t,"application/json"),function(e,t,r){if(lg.isString(e))try{return(t||JSON.parse)(e),lg.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional,r=t&&t.silentJSONParsing,n=t&&t.forcedJSONParsing,i=!r&&"json"===this.responseType;if(i||n&&lg.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(i){if("SyntaxError"===e.name)throw hg(e,this,"E_JSON_PARSE");throw e}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(e){return e>=200&&e<300}};vg.headers={common:{Accept:"application/json, text/plain, */*"}},lg.forEach(["delete","get","head"],(function(e){vg.headers[e]={}})),lg.forEach(["post","put","patch"],(function(e){vg.headers[e]=lg.merge(fg)}));var yg=vg,_g=xm,bg=yg,Eg=function(e){return!(!e||!e.__CANCEL__)},wg=xm,Sg=function(e,t,r){var n=this||bg;return _g.forEach(r,(function(r){e=r.call(n,e,t)})),e},Cg=Eg,Pg=yg;function Tg(e){e.cancelToken&&e.cancelToken.throwIfRequested()}var kg=xm,Rg=function(e,t){t=t||{};var r={},n=["url","method","data"],i=["headers","auth","proxy","params"],s=["baseURL","transformRequest","transformResponse","paramsSerializer","timeout","timeoutMessage","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","decompress","maxContentLength","maxBodyLength","maxRedirects","transport","httpAgent","httpsAgent","cancelToken","socketPath","responseEncoding"],o=["validateStatus"];function a(e,t){return kg.isPlainObject(e)&&kg.isPlainObject(t)?kg.merge(e,t):kg.isPlainObject(t)?kg.merge({},t):kg.isArray(t)?t.slice():t}function c(n){kg.isUndefined(t[n])?kg.isUndefined(e[n])||(r[n]=a(void 0,e[n])):r[n]=a(e[n],t[n])}kg.forEach(n,(function(e){kg.isUndefined(t[e])||(r[e]=a(void 0,t[e]))})),kg.forEach(i,c),kg.forEach(s,(function(n){kg.isUndefined(t[n])?kg.isUndefined(e[n])||(r[n]=a(void 0,e[n])):r[n]=a(void 0,t[n])})),kg.forEach(o,(function(n){n in t?r[n]=a(e[n],t[n]):n in e&&(r[n]=a(void 0,e[n]))}));var d=n.concat(i).concat(s).concat(o),u=Object.keys(e).concat(Object.keys(t)).filter((function(e){return-1===d.indexOf(e)}));return kg.forEach(u,c),r},Ig={name:"axios",version:"0.21.4",description:"Promise based HTTP client for the browser and node.js",main:"index.js",scripts:{test:"grunt test",start:"node ./sandbox/server.js",build:"NODE_ENV=production grunt build",preversion:"npm test",version:"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json",postversion:"git push && git push --tags",examples:"node ./examples/server.js",coveralls:"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",fix:"eslint --fix lib/**/*.js"},repository:{type:"git",url:"https://github.com/axios/axios.git"},keywords:["xhr","http","ajax","promise","node"],author:"Matt Zabriskie",license:"MIT",bugs:{url:"https://github.com/axios/axios/issues"},homepage:"https://axios-http.com",devDependencies:{coveralls:"^3.0.0","es6-promise":"^4.2.4",grunt:"^1.3.0","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^23.0.0","grunt-karma":"^4.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^4.0.2","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1",karma:"^6.3.2","karma-chrome-launcher":"^3.1.0","karma-firefox-launcher":"^2.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^4.3.6","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.8","karma-webpack":"^4.0.2","load-grunt-tasks":"^3.5.2",minimist:"^1.2.0",mocha:"^8.2.1",sinon:"^4.5.0","terser-webpack-plugin":"^4.2.3",typescript:"^4.0.5","url-search-params":"^0.10.0",webpack:"^4.44.2","webpack-dev-server":"^3.11.0"},browser:{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},jsdelivr:"dist/axios.min.js",unpkg:"dist/axios.min.js",typings:"./index.d.ts",dependencies:{"follow-redirects":"^1.14.0"},bundlesize:[{path:"./dist/axios.min.js",threshold:"5kB"}]},Dg={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){Dg[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));var Ag={},Og=Ig.version.split(".");function Ng(e,t){for(var r=t?t.split("."):Og,n=e.split("."),i=0;i<3;i++){if(r[i]>n[i])return!0;if(r[i]<n[i])return!1}return!1}Dg.transitional=function(e,t,r){var n=t&&Ng(t);function i(e,t){return"[Axios v"+Ig.version+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return function(r,s,o){if(!1===e)throw new Error(i(s," has been removed in "+t));return n&&!Ag[s]&&(Ag[s]=!0,console.warn(i(s," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,s,o)}};var Mg={isOlderVersion:Ng,assertOptions:function(e,t,r){if("object"!=typeof e)throw new TypeError("options must be an object");for(var n=Object.keys(e),i=n.length;i-- >0;){var s=n[i],o=t[s];if(o){var a=e[s],c=void 0===a||o(a,s,e);if(!0!==c)throw new TypeError("option "+s+" must be "+c)}else if(!0!==r)throw Error("Unknown option "+s)}},validators:Dg},Lg=xm,xg=Um,Fg=Wm,jg=function(e){return Tg(e),e.headers=e.headers||{},e.data=Sg.call(e,e.data,e.headers,e.transformRequest),e.headers=wg.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),wg.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||Pg.adapter)(e).then((function(t){return Tg(e),t.data=Sg.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return Cg(t)||(Tg(e),t&&t.response&&(t.response.data=Sg.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},Ug=Rg,Bg=Mg,Vg=Bg.validators;function Wg(e){this.defaults=e,this.interceptors={request:new Fg,response:new Fg}}Wg.prototype.request=function(e){"string"==typeof e?(e=arguments[1]||{}).url=arguments[0]:e=e||{},(e=Ug(this.defaults,e)).method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var t=e.transitional;void 0!==t&&Bg.assertOptions(t,{silentJSONParsing:Vg.transitional(Vg.boolean,"1.0.0"),forcedJSONParsing:Vg.transitional(Vg.boolean,"1.0.0"),clarifyTimeoutError:Vg.transitional(Vg.boolean,"1.0.0")},!1);var r=[],n=!0;this.interceptors.request.forEach((function(t){"function"==typeof t.runWhen&&!1===t.runWhen(e)||(n=n&&t.synchronous,r.unshift(t.fulfilled,t.rejected))}));var i,s=[];if(this.interceptors.response.forEach((function(e){s.push(e.fulfilled,e.rejected)})),!n){var o=[jg,void 0];for(Array.prototype.unshift.apply(o,r),o=o.concat(s),i=Promise.resolve(e);o.length;)i=i.then(o.shift(),o.shift());return i}for(var a=e;r.length;){var c=r.shift(),d=r.shift();try{a=c(a)}catch(e){d(e);break}}try{i=jg(a)}catch(e){return Promise.reject(e)}for(;s.length;)i=i.then(s.shift(),s.shift());return i},Wg.prototype.getUri=function(e){return e=Ug(this.defaults,e),xg(e.url,e.params,e.paramsSerializer).replace(/^\?/,"")},Lg.forEach(["delete","get","head","options"],(function(e){Wg.prototype[e]=function(t,r){return this.request(Ug(r||{},{method:e,url:t,data:(r||{}).data}))}})),Lg.forEach(["post","put","patch"],(function(e){Wg.prototype[e]=function(t,r,n){return this.request(Ug(n||{},{method:e,url:t,data:r}))}}));var Hg=Wg;function qg(e){this.message=e}qg.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},qg.prototype.__CANCEL__=!0;var zg=qg,Gg=zg;function Yg(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var r=this;e((function(e){r.reason||(r.reason=new Gg(e),t(r.reason))}))}Yg.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},Yg.source=function(){var e,t=new Yg((function(t){e=t}));return{token:t,cancel:e}};var $g=Yg,Jg=xm,Kg=km,Qg=Hg,Zg=Rg;function Xg(e){var t=new Qg(e),r=Kg(Qg.prototype.request,t);return Jg.extend(r,Qg.prototype,t),Jg.extend(r,t),r}var ev=Xg(yg);ev.Axios=Qg,ev.create=function(e){return Xg(Zg(ev.defaults,e))},ev.Cancel=zg,ev.CancelToken=$g,ev.isCancel=Eg,ev.all=function(e){return Promise.all(e)},ev.spread=function(e){return function(t){return e.apply(null,t)}},ev.isAxiosError=function(e){return"object"==typeof e&&!0===e.isAxiosError},Tm.exports=ev,Tm.exports.default=ev;var tv=Tm.exports,rv="undefined"!=typeof Symbol&&Symbol,nv=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},iv="Function.prototype.bind called on incompatible ",sv=Array.prototype.slice,ov=Object.prototype.toString,av=function(e){var t=this;if("function"!=typeof t||"[object Function]"!==ov.call(t))throw new TypeError(iv+t);for(var r,n=sv.call(arguments,1),i=function(){if(this instanceof r){var i=t.apply(this,n.concat(sv.call(arguments)));return Object(i)===i?i:this}return t.apply(e,n.concat(sv.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},cv=Function.prototype.bind||av,dv="Function.prototype.bind called on incompatible ",uv=Array.prototype.slice,lv=Object.prototype.toString,pv=function(e){var t=this;if("function"!=typeof t||"[object Function]"!==lv.call(t))throw new TypeError(dv+t);for(var r,n=uv.call(arguments,1),i=function(){if(this instanceof r){var i=t.apply(this,n.concat(uv.call(arguments)));return Object(i)===i?i:this}return t.apply(e,n.concat(uv.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},hv=(Function.prototype.bind||pv).call(Function.call,Object.prototype.hasOwnProperty),fv=SyntaxError,mv=Function,gv=TypeError,vv=function(e){try{return mv('"use strict"; return ('+e+").constructor;")()}catch(e){}},yv=Object.getOwnPropertyDescriptor;if(yv)try{yv({},"")}catch(wt){yv=null}var _v=function(){throw new gv},bv=yv?function(){try{return _v}catch(e){try{return yv(arguments,"callee").get}catch(e){return _v}}}():_v,Ev="function"==typeof rv&&"function"==typeof Symbol&&"symbol"==typeof rv("foo")&&"symbol"==typeof Symbol("bar")&&nv(),wv=Object.getPrototypeOf||function(e){return e.__proto__},Sv={},Cv="undefined"==typeof Uint8Array?undefined:wv(Uint8Array),Pv={"%AggregateError%":"undefined"==typeof AggregateError?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":Ev?wv([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":Sv,"%AsyncGenerator%":Sv,"%AsyncGeneratorFunction%":Sv,"%AsyncIteratorPrototype%":Sv,"%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%":mv,"%GeneratorFunction%":Sv,"%Int8Array%":"undefined"==typeof Int8Array?undefined:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Ev?wv(wv([][Symbol.iterator]())):undefined,"%JSON%":"object"==typeof JSON?JSON:undefined,"%Map%":"undefined"==typeof Map?undefined:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&Ev?wv((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&&Ev?wv((new Set)[Symbol.iterator]()):undefined,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Ev?wv(""[Symbol.iterator]()):undefined,"%Symbol%":Ev?Symbol:undefined,"%SyntaxError%":fv,"%ThrowTypeError%":bv,"%TypedArray%":Cv,"%TypeError%":gv,"%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},Tv=function e(t){var r;if("%AsyncFunction%"===t)r=vv("async function () {}");else if("%GeneratorFunction%"===t)r=vv("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=vv("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&(r=wv(i.prototype))}return Pv[t]=r,r},kv={"%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"]},Rv=cv,Iv=hv,Dv=Rv.call(Function.call,Array.prototype.concat),Av=Rv.call(Function.apply,Array.prototype.splice),Ov=Rv.call(Function.call,String.prototype.replace),Nv=Rv.call(Function.call,String.prototype.slice),Mv=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Lv=/\\(\\)?/g,xv=function(e){var t=Nv(e,0,1),r=Nv(e,-1);if("%"===t&&"%"!==r)throw new fv("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new fv("invalid intrinsic syntax, expected opening `%`");var n=[];return Ov(e,Mv,(function(e,t,r,i){n[n.length]=r?Ov(i,Lv,"$1"):t||e})),n},Fv=function(e,t){var r,n=e;if(Iv(kv,n)&&(n="%"+(r=kv[n])[0]+"%"),Iv(Pv,n)){var i=Pv[n];if(i===Sv&&(i=Tv(n)),void 0===i&&!t)throw new gv("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:i}}throw new fv("intrinsic "+e+" does not exist!")},jv=function(e,t){if("string"!=typeof e||0===e.length)throw new gv("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new gv('"allowMissing" argument must be a boolean');var r=xv(e),n=r.length>0?r[0]:"",i=Fv("%"+n+"%",t),s=i.name,o=i.value,a=!1,c=i.alias;c&&(n=c[0],Av(r,Dv([0,1],c)));for(var d=1,u=!0;d<r.length;d+=1){var l=r[d],p=Nv(l,0,1),h=Nv(l,-1);if(('"'===p||"'"===p||"`"===p||'"'===h||"'"===h||"`"===h)&&p!==h)throw new fv("property names with quotes must have matching quotes");if("constructor"!==l&&u||(a=!0),Iv(Pv,s="%"+(n+="."+l)+"%"))o=Pv[s];else if(null!=o){if(!(l in o)){if(!t)throw new gv("base intrinsic for "+e+" exists, but the property is not available.");return}if(yv&&d+1>=r.length){var f=yv(o,l);o=(u=!!f)&&"get"in f&&!("originalValue"in f.get)?f.get:o[l]}else u=Iv(o,l),o=o[l];u&&!a&&(Pv[s]=o)}}return o},Uv={exports:{}};!function(e){var t=cv,r=jv,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}(Uv);var Bv=jv,Vv=Uv.exports,Wv=Vv(Bv("String.prototype.indexOf")),Hv=h(Object.freeze({__proto__:null,default:{}})),qv="function"==typeof Map&&Map.prototype,zv=Object.getOwnPropertyDescriptor&&qv?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Gv=qv&&zv&&"function"==typeof zv.get?zv.get:null,Yv=qv&&Map.prototype.forEach,$v="function"==typeof Set&&Set.prototype,Jv=Object.getOwnPropertyDescriptor&&$v?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,Kv=$v&&Jv&&"function"==typeof Jv.get?Jv.get:null,Qv=$v&&Set.prototype.forEach,Zv="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,Xv="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ey="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,ty=Boolean.prototype.valueOf,ry=Object.prototype.toString,ny=Function.prototype.toString,iy=String.prototype.match,sy="function"==typeof BigInt?BigInt.prototype.valueOf:null,oy=Object.getOwnPropertySymbols,ay="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,cy="function"==typeof Symbol&&"object"==typeof Symbol.iterator,dy=Object.prototype.propertyIsEnumerable,uy=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null),ly=Hv.custom,py=ly&&vy(ly)?ly:null,hy="function"==typeof Symbol&&void 0!==Symbol.toStringTag?Symbol.toStringTag:null;function fy(e,t,r){var n="double"===(r.quoteStyle||t)?'"':"'";return n+e+n}function my(e){return String(e).replace(/"/g,""")}function gy(e){return!("[object Array]"!==by(e)||hy&&"object"==typeof e&&hy in e)}function vy(e){if(cy)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!ay)return!1;try{return ay.call(e),!0}catch(e){}return!1}var yy=Object.prototype.hasOwnProperty||function(e){return e in this};function _y(e,t){return yy.call(e,t)}function by(e){return ry.call(e)}function Ey(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 wy(e,t){if(e.length>t.maxStringLength){var r=e.length-t.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return wy(e.slice(0,t.maxStringLength),t)+n}return fy(e.replace(/(['\\])/g,"\\$1").replace(/[\x00-\x1f]/g,Sy),"single",t)}function Sy(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 Cy(e){return"Object("+e+")"}function Py(e){return e+" { ? }"}function Ty(e,t,r,n){return e+" ("+t+") {"+(n?ky(r,n):r.join(", "))+"}"}function ky(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+e.join(","+r)+"\n"+t.prev}function Ry(e,t){var r=gy(e),n=[];if(r){n.length=e.length;for(var i=0;i<e.length;i++)n[i]=_y(e,i)?t(e[i],e):""}var s,o="function"==typeof oy?oy(e):[];if(cy){s={};for(var a=0;a<o.length;a++)s["$"+o[a]]=o[a]}for(var c in e)_y(e,c)&&(r&&String(Number(c))===c&&c<e.length||cy&&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 oy)for(var d=0;d<o.length;d++)dy.call(e,o[d])&&n.push("["+t(o[d])+"]: "+t(e[o[d]],e));return n}var Iy=jv,Dy=function(e,t){var r=Bv(e,!!t);return"function"==typeof r&&Wv(e,".prototype.")>-1?Vv(r):r},Ay=function e(t,r,n,i){var s=r||{};if(_y(s,"quoteStyle")&&"single"!==s.quoteStyle&&"double"!==s.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(_y(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=!_y(s,"customInspect")||s.customInspect;if("boolean"!=typeof o&&"symbol"!==o)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(_y(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 wy(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 gy(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(Ey(i,t)>=0)return"[Circular]";function d(t,r,o){if(r&&(i=i.slice()).push(r),o){var a={depth:s.depth};return _y(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=iy.call(ny.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),l=Ry(t,d);return"[Function"+(u?": "+u:" (anonymous)")+"]"+(l.length>0?" { "+l.join(", ")+" }":"")}if(vy(t)){var p=cy?String(t).replace(/^(Symbol\(.*\))_[^)]*$/,"$1"):ay.call(t);return"object"!=typeof t||cy?p:Cy(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+"="+fy(my(f[m].value),"double",s);return h+=">",t.childNodes&&t.childNodes.length&&(h+="..."),h+="</"+String(t.nodeName).toLowerCase()+">"}if(gy(t)){if(0===t.length)return"[]";var g=Ry(t,d);return c&&!function(e){for(var t=0;t<e.length;t++)if(Ey(e[t],"\n")>=0)return!1;return!0}(g)?"["+ky(g,c)+"]":"[ "+g.join(", ")+" ]"}if(function(e){return!("[object Error]"!==by(e)||hy&&"object"==typeof e&&hy in e)}(t)){var v=Ry(t,d);return 0===v.length?"["+String(t)+"]":"{ ["+String(t)+"] "+v.join(", ")+" }"}if("object"==typeof t&&o){if(py&&"function"==typeof t[py])return t[py]();if("symbol"!==o&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Gv||!e||"object"!=typeof e)return!1;try{Gv.call(e);try{Kv.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var y=[];return Yv.call(t,(function(e,r){y.push(d(r,t,!0)+" => "+d(e,t))})),Ty("Map",Gv.call(t),y,c)}if(function(e){if(!Kv||!e||"object"!=typeof e)return!1;try{Kv.call(e);try{Gv.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var _=[];return Qv.call(t,(function(e){_.push(d(e,t))})),Ty("Set",Kv.call(t),_,c)}if(function(e){if(!Zv||!e||"object"!=typeof e)return!1;try{Zv.call(e,Zv);try{Xv.call(e,Xv)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Py("WeakMap");if(function(e){if(!Xv||!e||"object"!=typeof e)return!1;try{Xv.call(e,Xv);try{Zv.call(e,Zv)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Py("WeakSet");if(function(e){if(!ey||!e||"object"!=typeof e)return!1;try{return ey.call(e),!0}catch(e){}return!1}(t))return Py("WeakRef");if(function(e){return!("[object Number]"!==by(e)||hy&&"object"==typeof e&&hy in e)}(t))return Cy(d(Number(t)));if(function(e){if(!e||"object"!=typeof e||!sy)return!1;try{return sy.call(e),!0}catch(e){}return!1}(t))return Cy(d(sy.call(t)));if(function(e){return!("[object Boolean]"!==by(e)||hy&&"object"==typeof e&&hy in e)}(t))return Cy(ty.call(t));if(function(e){return!("[object String]"!==by(e)||hy&&"object"==typeof e&&hy in e)}(t))return Cy(d(String(t)));if(!function(e){return!("[object Date]"!==by(e)||hy&&"object"==typeof e&&hy in e)}(t)&&!function(e){return!("[object RegExp]"!==by(e)||hy&&"object"==typeof e&&hy in e)}(t)){var b=Ry(t,d),E=uy?uy(t)===Object.prototype:t instanceof Object||t.constructor===Object,w=t instanceof Object?"":"null prototype",S=!E&&hy&&Object(t)===t&&hy in t?by(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===b.length?C+"{}":c?C+"{"+ky(b,c)+"}":C+"{ "+b.join(", ")+" }"}return String(t)},Oy=Iy("%TypeError%"),Ny=Iy("%WeakMap%",!0),My=Iy("%Map%",!0),Ly=Dy("WeakMap.prototype.get",!0),xy=Dy("WeakMap.prototype.set",!0),Fy=Dy("WeakMap.prototype.has",!0),jy=Dy("Map.prototype.get",!0),Uy=Dy("Map.prototype.set",!0),By=Dy("Map.prototype.has",!0),Vy=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},Wy=String.prototype.replace,Hy=/%20/g,qy="RFC3986",zy={default:qy,formatters:{RFC1738:function(e){return Wy.call(e,Hy,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:qy},Gy=zy,Yy=Object.prototype.hasOwnProperty,$y=Array.isArray,Jy=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),Ky=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:Ky,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($y(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===Gy.RFC1738&&(40===c||41===c)?o+=s.charAt(a):c<128?o+=Jy[c]:c<2048?o+=Jy[192|c>>6]+Jy[128|63&c]:c<55296||c>=57344?o+=Jy[224|c>>12]+Jy[128|c>>6&63]+Jy[128|63&c]:(a+=1,c=65536+((1023&c)<<10|1023&s.charCodeAt(a)),o+=Jy[240|c>>18]+Jy[128|c>>12&63]+Jy[128|c>>6&63]+Jy[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($y(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($y(t))t.push(r);else{if(!t||"object"!=typeof t)return[t,r];(n&&(n.plainObjects||n.allowPrototypes)||!Yy.call(Object.prototype,r))&&(t[r]=!0)}return t}if(!t||"object"!=typeof t)return[t].concat(r);var i=t;return $y(t)&&!$y(r)&&(i=Ky(t,n)),$y(t)&&$y(r)?(r.forEach((function(r,i){if(Yy.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 Yy.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 Oy("Side channel does not contain "+Ay(e))},get:function(n){if(Ny&&n&&("object"==typeof n||"function"==typeof n)){if(e)return Ly(e,n)}else if(My){if(t)return jy(t,n)}else if(r)return function(e,t){var r=Vy(e,t);return r&&r.value}(r,n)},has:function(n){if(Ny&&n&&("object"==typeof n||"function"==typeof n)){if(e)return Fy(e,n)}else if(My){if(t)return By(t,n)}else if(r)return function(e,t){return!!Vy(e,t)}(r,n);return!1},set:function(n,i){Ny&&n&&("object"==typeof n||"function"==typeof n)?(e||(e=new Ny),xy(e,n,i)):My?(t||(t=new My),Uy(t,n,i)):(r||(r={key:{},next:null}),function(e,t,r){var n=Vy(e,t);n?n.value=r:e.next={key:t,next:e.next,value:r}}(r,n,i))}};return n},Xy=Qy,e_=zy,t_=Object.prototype.hasOwnProperty,r_={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},n_=Array.isArray,i_=String.prototype.split,s_=Array.prototype.push,o_=function(e,t){s_.apply(e,n_(t)?t:[t])},a_=Date.prototype.toISOString,c_=e_.default,d_={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:Xy.encode,encodeValuesOnly:!1,format:c_,formatter:e_.formatters[c_],indices:!1,serializeDate:function(e){return a_.call(e)},skipNulls:!1,strictNullHandling:!1},u_={},l_=function e(t,r,n,i,s,o,a,c,d,u,l,p,h,f,m,g){for(var v=t,y=g,_=0,b=!1;void 0!==(y=y.get(u_))&&!b;){var E=y.get(t);if(_+=1,void 0!==E){if(E===_)throw new RangeError("Cyclic object value");b=!0}void 0===y.get(u_)&&(_=0)}if("function"==typeof c?v=c(r,v):v instanceof Date?v=l(v):"comma"===n&&n_(v)&&(v=Xy.maybeMap(v,(function(e){return e instanceof Date?l(e):e}))),null===v){if(s)return a&&!f?a(r,d_.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)||Xy.isBuffer(v)){if(a){var w=f?r:a(r,d_.encoder,m,"key",p);if("comma"===n&&f){for(var S=i_.call(String(v),","),C="",P=0;P<S.length;++P)C+=(0===P?"":",")+h(a(S[P],d_.encoder,m,"value",p));return[h(w)+(i&&n_(v)&&1===S.length?"[]":"")+"="+C]}return[h(w)+"="+h(a(v,d_.encoder,m,"value",p))]}return[h(r)+"="+h(String(v))]}var T,k=[];if(void 0===v)return k;if("comma"===n&&n_(v))T=[{value:v.length>0?v.join(",")||null:void 0}];else if(n_(c))T=c;else{var R=Object.keys(v);T=d?R.sort(d):R}for(var I=i&&n_(v)&&1===v.length?r+"[]":r,D=0;D<T.length;++D){var A=T[D],O="object"==typeof A&&void 0!==A.value?A.value:v[A];if(!o||null!==O){var N=n_(v)?"function"==typeof n?n(I,A):I:I+(u?"."+A:"["+A+"]");g.set(t,_);var M=Zy();M.set(u_,g),o_(k,e(O,N,n,i,s,o,a,c,d,u,l,p,h,f,m,M))}}return k},p_=Qy,h_=Object.prototype.hasOwnProperty,f_=Array.isArray,m_={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:p_.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},g_=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},v_=function(e,t){return e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1?e.split(","):e},y_=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&&h_.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&&h_.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:v_(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 d_;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||d_.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=e_.default;if(void 0!==e.format){if(!t_.call(e_.formatters,e.format))throw new TypeError("Unknown format option provided.");r=e.format}var n=e_.formatters[r],i=d_.filter;return("function"==typeof e.filter||n_(e.filter))&&(i=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:d_.addQueryPrefix,allowDots:void 0===e.allowDots?d_.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:d_.charsetSentinel,delimiter:void 0===e.delimiter?d_.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:d_.encode,encoder:"function"==typeof e.encoder?e.encoder:d_.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:d_.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:d_.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:d_.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:d_.strictNullHandling}}(t);"function"==typeof i.filter?n=(0,i.filter)("",n):n_(i.filter)&&(r=i.filter);var s,o=[];if("object"!=typeof n||null===n)return"";s=t&&t.arrayFormat in r_?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var a=r_[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]||o_(o,l_(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:""},b_=function(e,t){var r=function(e){if(!e)return m_;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?m_.charset:e.charset;return{allowDots:void 0===e.allowDots?m_.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:m_.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:m_.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:m_.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:m_.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:m_.comma,decoder:"function"==typeof e.decoder?e.decoder:m_.decoder,delimiter:"string"==typeof e.delimiter||p_.isRegExp(e.delimiter)?e.delimiter:m_.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:m_.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:m_.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:m_.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:m_.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:m_.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,m_.decoder,c,"key"),u=t.strictNullHandling?null:""):(d=t.decoder(l.slice(0,h),m_.decoder,c,"key"),u=p_.maybeMap(v_(l.slice(h+1),t),(function(e){return t.decoder(e,m_.decoder,c,"value")}))),u&&t.interpretNumericEntities&&"iso-8859-1"===c&&(u=g_(u)),l.indexOf("[]=")>-1&&(u=f_(u)?[u]:u),h_.call(n,d)?n[d]=p_.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=y_(a,n[a],r,"string"==typeof e);i=p_.merge(i,c,r)}return!0===r.allowSparse?i:p_.compact(i)},E_={formats:zy,parse:b_,stringify:__};let w_=class{constructor(e){this.config=e;const t=this.config.get("loadbalancer"),{baseURL:r,timeout:n,customNode:i}=t;this.api=tv.create({baseURL:null!=r?r:"https://lb.livedigital.space/v1",timeout:null!=n?n:5e3,withCredentials:!1,paramsSerializer:e=>E_.stringify(e)}),this.customNode=i}getNode(e){return a(this,void 0,void 0,(function*(){if(this.customNode)return this.customNode;const{data:t}=yield this.api.get("/nodes/best",{params:e});return t}))}checkServiceAvailability(){return a(this,arguments,void 0,(function*(e=2e3){try{const{status:t}=yield this.api.options("/nodes/best",{timeout:e});return[ft.OK,ft.NoContent].includes(t)}catch(e){return!1}}))}setBaseUrl(e){try{const t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw new Error("Only http and https protocols are supported.");this.api.defaults.baseURL=t.toString()}catch(e){throw new Error("Invalid URL provided")}}};w_=i([at(),s(0,dt(Hn.Config)),o("design:paramtypes",[Pt])],w_);var S_,C_=w_;let P_=class{constructor(e,t){this.clientEventEmitter=e,this.isEnableVideoDevicesLock=!1,this.isEnableAudioDevicesLock=!1,this.isDevicesDetected=!1,this.availableVideoDevices=[],this.availableAudioDevices=[],S_.set(this,void 0),d(this,S_,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}requestMediaDevicesAccess(){return a(this,arguments,void 0,(function*(e={video:!0,audio:!0}){try{return(yield navigator.mediaDevices.getUserMedia(e)).getTracks()}catch(t){if(c(this,S_,"f").error("getUserMedia()",{error:t,constraints:e}),"NotAllowedError"===t.name)throw new Error(Gn.NotAllowedError);if("NotReadableError"===t.name)throw new Error(Gn.DeviceIsBusy);if("NotFoundError"===t.name)throw new Error(Gn.NotFoundError);throw new Error(Gn.RequestDevicesUnknownError)}}))}hasAvailableMediaDevicesList(){return a(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 a(this,void 0,void 0,(function*(){const e=yield navigator.mediaDevices.enumerateDevices(),t=[],r=[];e.forEach((e=>{""!==e.deviceId&&("videoinput"===e.kind&&t.push(e),"audioinput"===e.kind&&r.push(e))})),this.setAvailableVideoDevices(t),this.setAvailableAudioDevices(r);const n=({label:e,kind:t})=>({label:e,kind:t});return c(this,S_,"f").debug("Devices list updated",{videoDevices:t.map(n),audioDevices:r.map(n)}),e}))}detectDevices(e){return a(this,void 0,void 0,(function*(){if(this.isDevicesDetected&&!e)return;(yield this.hasAvailableMediaDevicesList())||(yield this.tryToAccessDevices()),this.isDevicesDetected=!0;const t=yield this.refreshAvailableMediaDevicesList(),r=t.some((e=>"audioinput"===e.kind)),n=t.some((e=>"videoinput"===e.kind));if(!r&&!n)throw new Error(Gn.NoDevices)}))}deviceChangeHandler(){return a(this,void 0,void 0,(function*(){if(!this.isDevicesDetected)return;yield this.refreshAvailableMediaDevicesList();const e={audio:this.availableAudioDevices,video:this.availableVideoDevices};this.clientEventEmitter.safeEmit(Ar,e)}))}listenDevices(){navigator.mediaDevices.addEventListener("devicechange",this.deviceChangeHandler)}assertHasAccessToMediaDevices(){return a(this,arguments,void 0,(function*(e={video:!0,audio:!0}){(yield this.requestMediaDevicesAccess(e)).forEach((e=>e.stop()))}))}tryToAccessDevices(){return a(this,void 0,void 0,(function*(){try{(yield this.requestMediaDevicesAccess()).forEach((e=>e.stop()))}catch(t){if(e=t.message,![Gn.NotFoundError,Gn.NotAllowedError,Gn.DeviceIsBusy].includes(e))throw t;t.message!==Gn.DeviceIsBusy&&(yield this.assertHasAccessToMediaDevices({audio:!0}),yield this.assertHasAccessToMediaDevices({video:!0}))}var e}))}};S_=new WeakMap,P_=i([at(),s(0,dt(Hn.ClientEventEmitter)),s(1,dt(Hn.LoggerFactory)),o("design:paramtypes",[Tt,Function])],P_);var T_,k_,R_,I_,D_,A_,O_=P_;class N_{constructor({transport:e,statsHandler:t}){T_.set(this,void 0),this.handleWebRTCStats(e,t)}get connectionStats(){return c(this,T_,"f")}handleWebRTCStats(e,t){t.addConnectionHandler(e.id,this.setConnectionStats.bind(this)),e.observer.once("close",(()=>{t.removeConnectionHandler(e.id)}))}setConnectionStats(e){d(this,T_,e,"f")}}T_=new WeakMap;let M_=class{constructor(){k_.set(this,new Map),R_.set(this,new Map),I_.set(this,new Map),D_.set(this,new Map),A_.set(this,new Map)}handle(e){e.forEach((({id:e,stats:t})=>{var r;null===(r=c(this,k_,"f").get(e))||void 0===r||r(t.connection),t.video.inbound.forEach((e=>{var t;return null===(t=c(this,R_,"f").get(e.trackIdentifier))||void 0===t?void 0:t(e)})),t.audio.inbound.forEach((e=>{var t;return null===(t=c(this,I_,"f").get(e.trackIdentifier))||void 0===t?void 0:t(e)})),t.video.outbound.forEach((e=>{var t;return null===(t=c(this,D_,"f").get(e.track.trackIdentifier))||void 0===t?void 0:t(e)})),t.audio.outbound.forEach((e=>{var t;return null===(t=c(this,A_,"f").get(e.track.trackIdentifier))||void 0===t?void 0:t(e)}))}))}addConnectionHandler(e,t){c(this,k_,"f").set(e,t)}addInboundVideoHandler(e,t){c(this,R_,"f").set(e,t)}addInboundAudioHandler(e,t){c(this,I_,"f").set(e,t)}addOutboundVideoHandler(e,t){c(this,D_,"f").set(e,t)}addOutboundAudioHandler(e,t){c(this,A_,"f").set(e,t)}removeConnectionHandler(e){c(this,k_,"f").delete(e)}removeInboundVideoHandler(e){c(this,R_,"f").delete(e)}removeInboundAudioHandler(e){c(this,D_,"f").delete(e)}removeOutboundVideoHandler(e){c(this,A_,"f").delete(e)}removeOutboundAudioHandler(e){c(this,A_,"f").delete(e)}clear(){c(this,k_,"f").clear(),c(this,R_,"f").clear(),c(this,I_,"f").clear(),c(this,D_,"f").clear(),c(this,A_,"f").clear()}};k_=new WeakMap,R_=new WeakMap,I_=new WeakMap,D_=new WeakMap,A_=new WeakMap,M_=i([at()],M_);var L_,x_,F_,j_,U_,B_,V_=M_;let W_=class{constructor(e){L_.set(this,!1),x_.set(this,void 0),F_.set(this,void 0),j_.set(this,void 0),U_.set(this,void 0),B_.set(this,void 0),d(this,x_,e("IntegrationsService"),"f")}init({sendTransportConnectionManager:e,receiveTransportConnectionManager:t,media:r,peers:n}){d(this,F_,e,"f"),d(this,j_,t,"f"),d(this,U_,r,"f"),d(this,B_,n,"f"),d(this,L_,!0,"f")}getStats(){try{return this.doGetStats()}catch(e){return c(this,x_,"f").error("Failed to get stats",{error:pr(e)}),{}}}clear(){d(this,F_,void 0,"f"),d(this,j_,void 0,"f"),d(this,U_,void 0,"f"),d(this,B_,void 0,"f")}doGetStats(){var e,t,r,n;if(!c(this,L_,"f"))throw new Error("TransportsStatsProvider is not initialized");return Object.assign(Object.assign({},(null===(t=null===(e=c(this,F_,"f"))||void 0===e?void 0:e.connectionStats)||void 0===t?void 0:t.id)?{outbound:Object.assign(Object.assign({},c(this,F_,"f").connectionStats),{bitrate:this.calculateOutboundTracksBitrate()})}:{}),(null===(n=null===(r=c(this,j_,"f"))||void 0===r?void 0:r.connectionStats)||void 0===n?void 0:n.id)?{inbound:Object.assign(Object.assign({},c(this,j_,"f").connectionStats),{bitrate:this.calculateInboundTracksBitrate()})}:{})}calculateInboundTracksBitrate(){if(void 0===c(this,B_,"f"))throw new Error("Peers is undefined");return c(this,B_,"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)}calculateOutboundTracksBitrate(){if(void 0===c(this,U_,"f"))throw new Error("Media is undefined");return c(this,U_,"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)}};L_=new WeakMap,x_=new WeakMap,F_=new WeakMap,j_=new WeakMap,U_=new WeakMap,B_=new WeakMap,W_=i([at(),s(0,dt(Hn.LoggerFactory)),o("design:paramtypes",[Function])],W_);var H_=W_;const q_=Array.from({length:256},((e,t)=>(t+256).toString(16).slice(1)));function z_(e=24){const t=new Uint8Array(e);crypto.getRandomValues(t);let r="";for(let e=0;e<t.length;e++)r+=q_[t[e]];return r}var G_,Y_,$_,J_;let K_=class{constructor(e,t,r,n,i,s,o,a,c,u,l,p,h,f,m,g,v,y,_,b){var E;this.state=e,this.myPeer=t,this.integrationsService=n,this.processorsCache=i,this.mediaEventHandler=s,this.channelEventsHandler=o,this.peerTrackFactory=a,this.peers=c,this.system=u,this.media=l,this.network=p,this.loadBalancerClient=h,this.socket=f,this.eventsQueue=m,this.clientEventEmitter=g,this.internalEventEmitter=v,this.statsHandler=y,this.transportsStatsProvider=_,this.webRtcIssueDetector=b,G_.set(this,void 0),Y_.set(this,void 0),this.rejoinRequested=!1,this.isReleasing=!1,$_.set(this,!1),J_.set(this,!1),this.mark=z_(),d(this,G_,r("Engine"),"f"),d(this,Y_,r,"f"),this.watchNetworkState(),this.watchDocumentUnload(),E=this.mark,window._sdkMarks||(window._sdkMarks=new Set),window._sdkMarks.add(E)}get isChannelJoined(){return this.state.isJoined}initialize(){return a(this,void 0,void 0,(function*(){var e,t,r,n;try{const{rtpCapabilities:i}=yield this.socket.request("router.getRtpCapabilities");this.integrationsService.init(),yield this.media.loadDevice(i),c(this,G_,"f").info("Supported capabilities",{codecs:jn(this.media.mediasoupDevice)});const[s,o]=yield Promise.all([this.network.createSendTransport(this.media.mediasoupDevice),this.network.createRecvTransport(this.media.mediasoupDevice),this.network.createSignalingTransport(this.media.mediasoupDevice)]);null===(e=this.webRtcIssueDetector)||void 0===e||e.handleNewPeerConnection(s.handler._pc,s.id),null===(t=this.webRtcIssueDetector)||void 0===t||t.handleNewPeerConnection(o.handler._pc,o.id),this.transportsStatsProvider.init({media:this.media,peers:this.peers,receiveTransportConnectionManager:new N_({transport:o,statsHandler:this.statsHandler}),sendTransportConnectionManager:new N_({transport:s,statsHandler:this.statsHandler})}),c(this,G_,"f").debug("initialize()",{sendTransportId:null===(r=this.network.sendTransport)||void 0===r?void 0:r.id,recvTransportId:null===(n=this.network.receiveTransport)||void 0===n?void 0:n.id}),yield this.network.createSignalingConsumer()}catch(e){c(this,G_,"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 An("Device not supported",An.UNSUPPORTED_DEVICE_CODE);throw new Error("Error initialize engine")}}))}release(e){return a(this,void 0,void 0,(function*(){var t;if(!this.isReleasing){this.isReleasing=!0;try{this.state.isJoined=!1,this.network.peersLoaded=!1,this.state.reset(),this.myPeer.delete(),null===(t=this.webRtcIssueDetector)||void 0===t||t.stopWatchingNewPeerConnections(),yield this.peers.reset(),this.network.closeSendTransport(),this.network.closeReceiveTransport(),yield this.network.closeConnectionTransport(),yield this.media.unpublishTracks(),e||this.media.clearTracks(),this.processorsCache.reset(),this.integrationsService.reset(),this.network.closeAllDataChannels(),this.removeClientEventEmitterListeners(),this.network.reset(),this.socket.disconnect(),hr.clear(),this.transportsStatsProvider.clear(),this.statsHandler.clear(),c(this,G_,"f").debug("release()",{socketId:this.myPeerId})}catch(e){throw c(this,G_,"f").error("release()",{error:e}),new Error("Error release engine")}finally{this.isReleasing=!1}}}))}removeClientEventEmitterListeners(){Array.from(Object.values($r)).forEach((e=>this.internalEventEmitter.removeAllListeners(e)))}getPeers(){return this.peers.all()}get myPeerId(){return this.myPeer.id}confirmActivity(){return a(this,void 0,void 0,(function*(){this.network.checkSocketConnectionActivity(),yield this.socket.request(yr)}))}join(e){return a(this,void 0,void 0,(function*(){const t=()=>a(this,void 0,void 0,(function*(){this.watchClientEvents(),yield this.connectToSocketServerWithRetry(e),yield this.performJoin({appData:e.appData})}));try{c(this,G_,"f").debug("join()",{params:e}),this.state.isChannelJoining=!0,yield Wn(t,{maxRetries:4,minBackoffDelayMs:150,maxBackoffDelayMs:5e3,actionName:"joinWithRetry",logger:c(this,Y_,"f").call(this,"RetryJoinNode"),onError:()=>a(this,void 0,void 0,(function*(){yield this.release(!0)}))})}catch(e){throw c(this,G_,"f").error("join()",{error:e}),e}finally{this.state.isChannelJoining=!1,this.rejoinRequested=!1}}))}loadPeers(e){return a(this,void 0,void 0,(function*(){yield this.peers.load(e)}))}requestChannelStateSync(){Wn((()=>a(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>a(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)?(c(this,G_,"f").info("Channel state event received",{case:"Engine.requestChannelStateSync"}),e()):t(new Error("Channel state event not received"))}),5e3),i=()=>{clearTimeout(n),this.clientEventEmitter.off(Fr,i),e()};this.clientEventEmitter.on(Fr,i)}))))}))),{minBackoffDelayMs:0,maxBackoffDelayMs:0,maxRetries:10,actionName:"triggerChannelStateEventWithRetry",logger:c(this,G_,"f")}).catch((e=>{c(this,G_,"f").error("Failed to request channel state event",{case:"Engine.requestChannelStateSync",error:pr(e)})}))}setPeer(e,t=!0){return this.peers.add(e,t)}removePeer(e){return a(this,void 0,void 0,(function*(){yield this.peers.remove(e)}))}updateAppData(e){return a(this,void 0,void 0,(function*(){const t=this.myPeer.get();if(!t)throw new Error("Need join to channel first");try{On(e),yield this.network.updatePeerAppData({peerId:t.id,appData:e})}catch(e){throw c(this,G_,"f").error("updateAppData()",{error:e}),new Error("Can not update peer appData")}}))}createCameraVideoTrack(e){return a(this,void 0,void 0,(function*(){const t=tm.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 Wf&&(r.setLabel((null==e?void 0:e.isPreview)?zn.CameraPreview:zn.Camera),r.setEncoderConfig(t.encoderConfig),r.setTransformParams(tm.getVideoTrackTransformParams(r.mediaStreamTrack))),this.media.setTrack(r),c(this,G_,"f").debug("createCameraVideoTrack()",{trackParams:t}),r}catch(e){throw c(this,G_,"f").error("createCameraVideoTrack()",{error:e,trackParams:t}),new Error(`Can not create camera track: ${e.message}`)}}))}createMicrophoneAudioTrack(e){return a(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)?zn.MicrophonePreview:zn.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()!==zn.Microphone||c(this,J_,"f")||this.media.initDenoiser(t,e).catch((t=>{this.clientEventEmitter.emit(Gr,{cause:"Failed to initialize denoiser",error:t}),c(this,G_,"f").error("Failed to execute initDenoiser",{case:"Denoiser",options:e,error:pr(t)})})),this.media.setTrack(t),c(this,G_,"f").debug("createMicrophoneAudioTrack()",{options:e,trackLabel:t.getLabel()}),t}catch(t){throw c(this,G_,"f").error("createMicrophoneAudioTrack()",{error:t,options:e}),new Error(`Can not create microphone track: ${t.message}`)}}))}createScreenMediaTracks(e){return a(this,void 0,void 0,(function*(){const t=tm.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=>{c(this,G_,"f").error("Failed to unpublish screen track",{error:pr(e)})}))}),{once:!0}),r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof Wf){r.setLabel(zn.ScreenVideo),r.setEncoderConfig(t.encoderConfig);const e=tm.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(e),this.media.setTrack(r),void c(this,G_,"f").debug("createScreenMediaTrack()",{trackParams:t,transformParams:e,label:r.logCtx})}r.setLabel(zn.ScreenAudio),(null==e?void 0:e.audioEncoderConfig)&&r.setEncoderConfig(e.audioEncoderConfig),this.media.setTrack(r),c(this,G_,"f").debug("createScreenMediaTrack()",{trackParams:null==e?void 0:e.audio,encoderConfig:null==e?void 0:e.audioEncoderConfig})})),r}catch(e){throw c(this,G_,"f").error("createScreenMediaTrack()",{error:e,trackParams:t}),new Error(`Can not create screen media tracks: ${e.message}`)}}))}createCustomAudioTrack(e){if(!e.audioTrack)throw 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=>{c(this,G_,"f").error("Failed to unpublish custom audio track",{track:t,error:pr(e)})}))}),{once:!0}),t.setStopTrackOnPause(Boolean(e.stopTrackOnPause)),t.setLabel(zn.CustomAudio),e.audioEncoderConfig&&t.setEncoderConfig(e.audioEncoderConfig),this.media.setTrack(t),c(this,G_,"f").debug("createCustomAudioTrack()",{trackParams:e.audio,encoderConfig:e.audioEncoderConfig}),t}catch(t){throw c(this,G_,"f").error("createCustomAudioTrack()",{error:t,trackParams:e.audioTrack}),new Error(`Can not create custom media tracks: ${t.message}`)}}createCustomVideoTrack(e){const t=tm.getScreenVideoTrackParams(e);if(!e.videoTrack)throw 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=>{c(this,G_,"f").error("Failed to unpublish custom video track",{track:r,error:pr(e)})}))}),{once:!0}),r.mediaStreamTrack.contentHint="customVideo",r.setLabel(zn.CustomVideo),r.setEncoderConfig(t.encoderConfig);const n=tm.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(n),this.media.setTrack(r),c(this,G_,"f").debug("createCustomVideoTrack()",{trackParams:t,transformParams:n,label:r.logCtx}),r}catch(e){throw c(this,G_,"f").error("createCustomVideoTrack()",{error:e,trackParams:t}),new Error(`Failed to create custom video track: ${e.message}`)}}deleteTrack(e){return a(this,void 0,void 0,(function*(){yield this.media.deleteTrack(e)}))}transportsStats(){return this.transportsStatsProvider.getStats()}setLoadbalancerUrl(e){if(this.isChannelJoined||this.rejoinRequested||this.state.isChannelJoining)throw new Error("Method not available when joined channel");this.loadBalancerClient.setBaseUrl(e)}connectToSocketServerWithRetry(e){return a(this,void 0,void 0,(function*(){yield Wn((()=>a(this,void 0,void 0,(function*(){return yield this.connectToSocketServer(e)}))),{maxRetries:15,minBackoffDelayMs:150,maxBackoffDelayMs:5e3,actionName:"connectToSocketServer",logger:c(this,Y_,"f").call(this,"RetrySocketConnect"),abortOnError:e=>{var t;return"unauthorized"===(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.errorCode)}})}))}connectToSocketServer(e){return a(this,void 0,void 0,(function*(){const t=e.isP2pCall?qn.P2P:qn.Common,{webSocketUrl:r}=yield this.getAvailableNode({datacenterType:t,channelId:e.channelId,role:e.role});this.socket.connect(r,e.token);try{yield this.waitForSocketConnection()}catch(t){throw c(this,G_,"f").error("Failed to connect to socket server",{error:t,role:e.role,channelId:e.channelId,webSocketUrl:r}),this.socket.disconnect(),t}}))}getAvailableNode(e){return a(this,void 0,void 0,(function*(){try{return{webSocketUrl:(yield this.loadBalancerClient.getNode(e)).webSocketUrl}}catch(e){throw c(this,G_,"f").error("getAvailableNode()",{error:"No available nodes"}),e}}))}waitForSocketConnection(){return a(this,void 0,void 0,(function*(){yield new Promise(((e,t)=>{const r=n=>{const{error:i,state:s}=n,o=()=>this.socket.observer.removeListener(Yn.State,r),a=[Yn.Disconnected,Yn.Reconnecting].includes(s);return i?(o(),void t(i)):this.state.isChannelJoining&&a?(o(),void t(new Error(`Not expected socket state for new connection: ${s}`))):void(this.state.isChannelJoining&&[Yn.Connected,Yn.Reconnected].includes(s)&&(o(),e()))};this.socket.observer.on(Yn.State,r)}))}))}performJoin(e){return a(this,void 0,void 0,(function*(){try{const{appId:t,channelId:r,peerId:n}=yield this.sendJoinChannelRequestWithRetry(e);this.myPeer.id=n,this.state.appId=t,this.state.channelId=r,yield this.initialize(),yield this.network.createAllDataChannels(),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)),hr.setPeerId(n),hr.setChannelId(r),hr.setAppId(t),yield Promise.all([this.network.waitForReceiveTransportConnected(),this.network.waitForChannelMessagesDataConsumerConnected()]),this.state.isJoined=!0,c(this,G_,"f").info("Successfully joined channel",{channelId:r})}catch(e){throw c(this,G_,"f").error("performJoin()",{error:e}),e}}))}sendJoinChannelRequestWithRetry(e){return a(this,void 0,void 0,(function*(){return yield Wn((()=>a(this,void 0,void 0,(function*(){return yield this.sendJoinChannelRequest(e)}))),{maxRetries:3,minBackoffDelayMs:300,actionName:"sendJoinChannelRequest",logger:c(this,Y_,"f").call(this,"RetryJoin")})}))}sendJoinChannelRequest(e){return a(this,void 0,void 0,(function*(){return yield this.socket.request(fr,e)}))}watchClientEvents(){this.internalEventEmitter.on($r.trackProduced,(e=>a(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.internalEventEmitter.on($r.trackUnproduced,(e=>a(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=>{c(this,G_,"f").debug("Failed to close peerTrack",{error:pr(e)})})),yield this.media.deleteTrack(e)})))),this.internalEventEmitter.on($r.trackPaused,(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=>{c(this,G_,"f").debug("Failed to pause peerTrack",{error:pr(e)})}))})),this.internalEventEmitter.on($r.trackResumed,(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=>{c(this,G_,"f").debug("Failed to resume peerTrack",{error:pr(e)})}))})),this.internalEventEmitter.on($r.trackClosed,(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=>{c(this,G_,"f").debug("Failed to close peerTrack",{error:pr(e)})}))})),this.internalEventEmitter.on($r.trackReopened,(e=>a(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.internalEventEmitter.on($r.trackFailed,(e=>{this.clientEventEmitter.safeEmit(Mr,{label:e.getLabel()})}))}createSelfPeerTrack(e){return a(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.rejoinRequested&&!this.state.isChannelJoining||(c(this,G_,"f").debug("Triggering channel rejoin required event",{reason:e}),this.rejoinRequested=!0,this.clientEventEmitter.emit(Dr))}watchNetworkState(){this.network.observer.on(Rn,(e=>{var t;if(this.isReleasing)return;const{code:r,error:n,state:i}=e,s="unauthorized"===(null===(t=null==n?void 0:n.data)||void 0===t?void 0:t.errorCode)&&this.isChannelJoined,o=r===Yn.NeedToJoinFirst&&this.isChannelJoined;if(s&&this.clientEventEmitter.safeEmit(Br),"server.disconnect"!==r||c(this,$_,"f")){if(o||s){const e=s?"unauthorized error":"invalid channel state";this.triggerRejoinEventIfAppropriate(e)}i===Yn.Disconnected&&this.isChannelJoined&&!c(this,$_,"f")&&c(this,G_,"f").info("connection lost",{channel:"socket"}),i===Yn.Reconnected&&this.isChannelJoined&&c(this,G_,"f").info("connection restored",{channel:"socket"}),i===Yn.BufferingStart&&(d(this,$_,!0,"f"),this.clientEventEmitter.safeEmit(Fr),this.waitForReconnectOrTriggerRejoinEventIfAppropriate()),[Yn.BufferingEnd,Yn.Reconnected].includes(i)&&this.network.isNetworkActive&&(d(this,$_,!1,"f"),this.clientEventEmitter.safeEmit(jr))}else this.clientEventEmitter.safeEmit(Ur)})),this.network.observer.on(In,(({state:e,direction:t})=>{if(!this.isReleasing&&(["disconnected","failed"].includes(e)&&this.isChannelJoined&&!c(this,$_,"f")&&(d(this,$_,!0,"f"),c(this,G_,"f").info("connection lost",{channel:"webrtc-transport",direction:t}),this.clientEventEmitter.safeEmit(Fr),this.waitForReconnectOrTriggerRejoinEventIfAppropriate()),"reconnected"===e&&this.isChannelJoined&&c(this,G_,"f").info("connection restored",{channel:"webrtc-transport",direction:t}),"reconnected"===e&&this.isChannelJoined&&c(this,$_,"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;d(this,$_,!1,"f"),this.clientEventEmitter.safeEmit(jr)}}))}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){c(this,G_,"f").error("Failed to add watchDocumentUnload listener",{channelId:this.state.channelId,error:pr(e)})}}waitForReconnectOrTriggerRejoinEventIfAppropriate(){c(this,G_,"f").info("Start waiting for seamless reconnect and check loadbalancer availability",{case:"waitForReconnectOrTriggerRejoinEventIfAppropriate"});let e=0;const t=setInterval((()=>a(this,void 0,void 0,(function*(){if(this.isReleasing||!this.state.isJoined)return clearInterval(t),void c(this,G_,"f").info("Stop waiting for seamless reconnect due to call end",{case:"waitForReconnectOrTriggerRejoinEventIfAppropriate"});try{if(!c(this,$_,"f"))return void clearInterval(t);if(!(yield this.loadBalancerClient.checkServiceAvailability(9e3)))return void(e=0);e+=1,e>6&&(clearInterval(t),this.triggerRejoinEventIfAppropriate("loadbalancer available"))}catch(e){c(this,G_,"f").error("Check failed",{error:pr(e),case:"waitForReconnectOrTriggerRejoinEventIfAppropriate"})}}))),1e4)}};G_=new WeakMap,Y_=new WeakMap,$_=new WeakMap,J_=new WeakMap,K_=i([at(),s(0,dt(Hn.CallState)),s(1,dt(Hn.MyPeer)),s(2,dt(Hn.LoggerFactory)),s(3,dt(Hn.IntegrationsService)),s(4,dt(Hn.ProcessorsCache)),s(5,dt(Hn.MediaEventHandler)),s(6,dt(Hn.ChannelEventHandler)),s(7,dt(Hn.PeerTrackFactory)),s(8,dt(Hn.Peers)),s(9,dt(Hn.System)),s(10,dt(Hn.Media)),s(11,dt(Hn.Network)),s(12,dt(Hn.LoadBalancerApiClient)),s(13,dt(Hn.SocketIO)),s(14,dt(Hn.EventsQueue)),s(15,dt(Hn.ClientEventEmitter)),s(16,dt(Hn.InternalEventEmitter)),s(17,dt(Hn.StatsHandler)),s(18,dt(Hn.TransportsStatsProvider)),s(19,dt(Hn.WebRTCIssueDetector)),o("design:paramtypes",[$n,js,Function,af,nf,Pm,ym,Function,Object,O_,tm,Aa,C_,la,xs,Tt,Tt,V_,H_,or])],K_);var Q_=K_;let Z_,X_=!1;const eb=()=>{try{return X_?null:window.localStorage}catch(e){return console.error("Get local storage error",{error:pr(e)}),e instanceof Error&&"SecurityError"===e.name&&(X_=!0),null}};function tb(e){const t=eb();if(!t)return null;try{const r=t.getItem(e);return r?JSON.parse(r):null}catch(e){return null}}const rb=()=>{if(Z_)return Z_;const e=tb("sdk_clientUniqueId");if(e)return Z_=e,e;const t=z_(12);return Z_=t,function(e,t){const r=eb();if(r)try{r.setItem(e,JSON.stringify(t))}catch(e){console.error(e)}}("sdk_clientUniqueId",t),t},nb=()=>{const e=tb("sdk_clientUniqueId");return e||(null!=Z_?Z_:rb())},ib=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 sb(e){return!e.response&&(!!e.code&&(!["ERR_CANCELED","ECONNABORTED"].includes(e.code)&&(e=>!ib.has(e&&e.code))(e)))}const ob=["get","head","options"],ab=ob.concat(["put","delete"]);function cb(e){return"ECONNABORTED"!==e.code&&(!e.response||429===e.response.status||e.response.status>=500&&e.response.status<=599)}function db(e){return!!e.config?.method&&(cb(e)&&-1!==ab.indexOf(e.config.method))}function ub(e){return sb(e)||db(e)}function lb(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 pb={retries:3,retryCondition:ub,retryDelay:function(e=0,t){return Math.max(0,lb(t))},shouldResetTimeout:!1,onRetry:()=>{},onMaxRetryTimesExceeded:()=>{},validateResponse:null};function hb(e,t,r=!1){const n=function(e,t){return{...pb,...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 fb=(e,t)=>{const r=e.interceptors.request.use((e=>(hb(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=hb(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}};fb.isNetworkError=sb,fb.isSafeRequestError=function(e){return!!e.config?.method&&(cb(e)&&-1!==ob.indexOf(e.config.method))},fb.isIdempotentRequestError=db,fb.isNetworkOrIdempotentRequestError=ub,fb.exponentialDelay=function(e=0,t,r=100){const n=2**e*r,i=Math.max(n,lb(t));return i+.2*i*Math.random()},fb.linearDelay=function(e=100){return(t=0,r)=>{const n=t*e;return Math.max(n,lb(r))}},fb.isRetryableError=cb;class mb{constructor(e){this.api=e,fb(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 a(this,void 0,void 0,(function*(){yield this.api.post("/log/batch",e)}))}}class gb{constructor(e){this.api=e,fb(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 a(this,void 0,void 0,(function*(){yield this.api.post("/analytics/network-metrics",e)}))}sendWIDMetrics(e){return a(this,void 0,void 0,(function*(){yield this.api.post("/analytics/wid-metrics",Object.assign({},e))}))}}let vb=class{constructor(){this.api=tv.create({baseURL:"https://moodhood-analytics.livedigital.space/v1",timeout:1e4,withCredentials:!0,paramsSerializer:e=>E_.stringify(e),headers:{"x-cl-id":nb()}}),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=i([at(),o("design:paramtypes",[])],vb);var yb=vb;const _b=new Error("request for lock canceled");var bb=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){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class Eb{constructor(e,t=_b){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=wb(this._queue,(e=>t<=e.priority));-1===s&&e<=this._value?this._dispatchItem(i):this._queue.splice(s+1,0,i)}))}runExclusive(e){return bb(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=wb(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 wb(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1}var Sb,Cb=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){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class Pb{constructor(e){this._semaphore=new Eb(1,e)}acquire(){return Cb(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 Tb=class{constructor(){Sb.set(this,new Map)}lock(e){return a(this,void 0,void 0,(function*(){let t=c(this,Sb,"f").get(e);return t||(t=new Pb,c(this,Sb,"f").set(e,t)),t.isLocked()&&(yield t.waitForUnlock()),yield t.acquire()}))}isLocked(e){const t=c(this,Sb,"f").get(e);return!!t&&t.isLocked()}waitForUnlock(e){return a(this,void 0,void 0,(function*(){const t=c(this,Sb,"f").get(e);(null==t?void 0:t.isLocked())?yield t.waitForUnlock():yield Promise.resolve()}))}};Sb=new WeakMap,Tb=i([at()],Tb);var kb=Tb,Rb={exports:{}},Ib=1e3,Db=60*Ib,Ab=60*Db,Ob=24*Ab,Nb=7*Ob,Mb=365.25*Ob,Lb=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*Mb;case"weeks":case"week":case"w":return r*Nb;case"days":case"day":case"d":return r*Ob;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Ab;case"minutes":case"minute":case"mins":case"min":case"m":return r*Db;case"seconds":case"second":case"secs":case"sec":case"s":return r*Ib;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>=Ob)return xb(e,t,Ob,"day");if(t>=Ab)return xb(e,t,Ab,"hour");if(t>=Db)return xb(e,t,Db,"minute");if(t>=Ib)return xb(e,t,Ib,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=Ob)return Math.round(e/Ob)+"d";if(t>=Ab)return Math.round(e/Ab)+"h";if(t>=Db)return Math.round(e/Db)+"m";if(t>=Ib)return Math.round(e/Ib)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function xb(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}var Fb=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=Lb,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=Fb(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Rb,Rb.exports);var jb,Ub,Bb=Rb.exports,Vb={},Wb={},Hb={},qb={exports:{}};
|
|
29
|
+
***************************************************************************** */!function(e){!function(t){var r="object"==typeof globalThis?globalThis:"object"==typeof l?l:"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 k(e,t)}if(!G(e))throw new TypeError;if(!B(t))throw new TypeError;if(!B(n)&&!F(n)&&!j(n))throw new TypeError;return j(n)&&(n=void 0),R(e,t,r=z(r),n)}function y(e,t){function r(r,n){if(!B(r))throw new TypeError;if(!F(n)&&!J(n))throw new TypeError;N(e,t,r,n)}return r}function _(e,t,r,n){if(!B(r))throw new TypeError;return F(n)||(n=z(n)),N(e,t,r,n)}function b(e,t,r){if(!B(t))throw new TypeError;return F(r)||(r=z(r)),I(e,t,r)}function E(e,t,r){if(!B(t))throw new TypeError;return F(r)||(r=z(r)),D(e,t,r)}function w(e,t,r){if(!B(t))throw new TypeError;return F(r)||(r=z(r)),A(e,t,r)}function S(e,t,r){if(!B(t))throw new TypeError;return F(r)||(r=z(r)),O(e,t,r)}function C(e,t){if(!B(e))throw new TypeError;return F(t)||(t=z(t)),M(e,t)}function P(e,t){if(!B(e))throw new TypeError;return F(t)||(t=z(t)),L(e,t)}function T(e,t,r){if(!B(t))throw new TypeError;if(F(r)||(r=z(r)),!B(t))throw new TypeError;F(r)||(r=z(r));var n=ae(t,r,!1);return!F(n)&&n.OrdinaryDeleteMetadata(e,t,r)}function k(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 R(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(!B(s))throw new TypeError;n=s}}return n}function I(e,t,r){if(D(e,t,r))return!0;var n=re(t);return!j(n)&&I(e,n,r)}function D(e,t,r){var n=ae(t,r,!1);return!F(n)&&H(n.OrdinaryHasOwnMetadata(e,t,r))}function A(e,t,r){if(D(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 N(e,t,r,n){ae(r,n,!0).OrdinaryDefineOwnMetadata(e,t,r,n)}function M(e,t){var r=L(e,t),n=re(e);if(null===n)return r;var i=M(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 B(e){return"object"==typeof e?null!==e:"function"==typeof e}function V(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(B(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(!B(i=r.call(e)))return i;if(Y(n=e.valueOf))if(!B(i=n.call(e)))return i}else{var n;if(Y(n=e.valueOf))if(!B(i=n.call(e)))return i;var i,s=e.toString;if(Y(s))if(!B(i=s.call(e)))return i}throw new TypeError}function H(e){return!!e}function q(e){return""+e}function z(e){var t=V(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 K(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(!B(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)&&B(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[f]),F(e)&&(e=ne()),!F(f)&&B(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--,K(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(!K(this._cacheKey,e)){this._cacheIndex=-1;for(var r=0;r<this._keys.length;r++)if(K(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(){var e=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}();return 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",_),e("hasMetadata",b),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)}()}(u||(u={}));var f=["inject","multi_inject","name","unmanaged","named","optional"],m="Request",g="Singleton",v="Transient",y="ConstantValue",_="Constructor",b="DynamicValue",E="Factory",w="Function",S="Instance",C="Invalid",P="Provider",T="ClassProperty",k="ConstructorArgument",R="Variable",I=0;function D(){return I++}var A=function(){function e(e,t){this.id=D(),this.activated=!1,this.serviceIdentifier=e,this.scope=t,this.type=C,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===g&&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}(),O="No matching bindings found for serviceIdentifier:",N="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},L=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}(),x=0,F=1;function j(e){return e instanceof RangeError||"Maximum call stack size exceeded"===e.message}function U(e){return"function"==typeof e?e.name:"symbol"==typeof e?e.toString():e}function B(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=H(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 W(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=U(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)}W(e)}))}function H(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 q=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}(),z=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}(),G=function(e,t){this.parentContext=e,this.rootRequest=t},Y=function(){function e(e){this._cb=e}return e.prototype.unwrap=function(){return this._cb()},e}(),$=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}(),J=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 $(i||""),this.identifier=t,this.metadata=new Array;var s=null;"string"==typeof n?s=new z("named",n):n instanceof z&&(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 f.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 f.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 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=Z(o,e,t,r,n);null!==a&&s.push(a)}return s}(n,t,s,o,c||d?a.length:r.length),l=ee(e,r,t);return K(K([],u,!0),l,!0)}function Z(e,t,r,n,i){var s=i[e.toString()]||[],o=re(s),a=!0!==o.unmanaged,c=n[e],d=o.inject||o.multiInject;if((c=d||c)instanceof Y&&(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 J(k,o.targetName,c);return u.metadata=s,u}return null}function X(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 ee(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=re(d),l=u.targetName||c,p=X(u.inject,u.multiInject,c,r),h=new J(T,l,p);h.metadata=d,i.push(h)}var f=Object.getPrototypeOf(t.prototype).constructor;if(f!==Object){var m=ee(e,f,r);i=K(K([],i,!0),m,!0)}return i}function te(e,t){var r=Object.getPrototypeOf(t.prototype).constructor;if(r!==Object){var n=Q(e,H(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:te(e,r)}return 0}function re(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 ne=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 ie(e){return e._bindingDictionary}function se(e,t,r,n,i){var s=ae(r.container,i.serviceIdentifier),o=[];return s.length===x&&r.container.options.autoBindInjectable&&"function"==typeof i.serviceIdentifier&&e.getConstructorMetadata(i.serviceIdentifier).compilerGeneratedMetadata&&(r.container.bind(i.serviceIdentifier).toSelf(),s=ae(r.container,i.serviceIdentifier)),o=t?s:s.filter((function(e){var t=new ne(e.serviceIdentifier,r,n,e,i);return e.constraint(t)})),function(e,t,r,n){switch(t.length){case x:if(r.isOptional())return t;var i=U(e),s=O;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+=B(n,i,ae),new Error(s);case F:return t;default:if(r.isArray())return t;s="Ambiguous match found for serviceIdentifier: "+(i=U(e));throw s+=B(n,i,ae),new Error(s)}}(i.serviceIdentifier,o,i,r.container),o}function oe(e,t,r,n,i,s){var o,a;if(null===i){o=se(e,t,n,null,s),a=new ne(r,n,null,o,s);var c=new G(n,a);n.addPlan(c)}else o=se(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===S&&null!==t.implementationType){var i=function(e,t){return Q(e,H(t),t,!1)}(e,t.implementationType);if(!n.container.options.skipBaseClassChecks){var o=te(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."}(H(t.implementationType));throw new Error(c)}}i.forEach((function(t){oe(e,!1,t.serviceIdentifier,n,r,t)}))}}))}function ae(e,t){var r=[],n=ie(e);return n.hasKey(t)?r=n.get(t):null!==e.parent&&(r=ae(e.parent,t)),r}function ce(e,t,r,n,i,s,o,a){void 0===a&&(a=!1);var c=new q(t),d=function(e,t,r,n,i,s){var o=new z(e?"multi_inject":"inject",r),a=new J(t,n,r,o);if(void 0!==i){var c=new z(i,s);a.metadata.push(c)}return a}(r,n,i,"",s,o);try{return oe(e,a,i,c,null,d),c}catch(e){throw j(e)&&W(c.plan.rootRequest),e}}function de(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&"function"==typeof e.then}function ue(e){return!!de(e)||Array.isArray(e)&&e.some(de)}var le,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){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))},he=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])}}},fe=function(e,t,r){e.has(t.id)||e.set(t.id,r)},me=function(e,t){e.cache=t,e.activated=!0,de(t)&&ge(e,t)},ge=function(e,t){return pe(void 0,void 0,void 0,(function(){var r,n;return he(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"}(le||(le={}));var ve=function(){return ve=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},ve.apply(this,arguments)},ye=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){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))},_e=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 Ee(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===k?e.constructorInjections.push(n):(e.propertyRequests.push(r),e.propertyInjections.push(n)),e.isAsync||(e.isAsync=ue(n)),e}),{constructorInjections:[],propertyInjections:[],propertyRequests:[],isAsync:!1})}(t,r),s=ve(ve({},i),{constr:e});n=i.isAsync?function(e){return ye(this,void 0,void 0,(function(){var t,r;return _e(this,(function(n){switch(n.label){case 0:return[4,Se(e.constructorInjections)];case 1:return t=n.sent(),[4,Se(e.propertyInjections)];case 2:return r=n.sent(),[2,we(ve(ve({},e),{constructorInjections:t,propertyInjections:r}))]}}))}))}(s):we(s)}else n=new e;return n}function we(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 Se(e){return ye(this,void 0,void 0,(function(){var t,r,n,i;return _e(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 Ce(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 de(r)?r.then((function(){return t})):t}function Pe(e,t){e.scope!==g&&function(e,t){var r="Class cannot be instantiated in "+(e.scope===m?"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){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))},ke=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 Oe(e,t,o)}}},Ie=function(e,t){var r=function(e){switch(e.type){case E:return{factory:e.factory,factoryType:le.Factory};case P:return{factory:e.provider,factoryType:le.Provider};case b:return{factory:e.dynamicValue,factoryType:le.DynamicValue};default:throw new Error("Unexpected factory type "+e.type)}}(e);return function(e,t){try{return e()}catch(e){throw j(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 y:case w:t=e.cache;break;case _:case S:t=e.implementationType;break;case b:t=e.dynamicValue;break;case P:t=e.provider;break;case E:t=e.factory}if(null===t){var r=U(e.serviceIdentifier);throw new Error("Invalid binding type: "+r)}}(r),r.type){case y:case w:n=r.cache;break;case _:n=r.implementationType;break;case S:n=function(e,t,r,n){Pe(e,t);var i=Ee(t,r,n);return de(i)?i.then((function(e){return Ce(t,e)})):Ce(t,i)}(r,r.implementationType,i,Re(e));break;default:n=Ie(r,t.parentContext)}return n},Ae=function(e,t,r){var n=function(e,t){return t.scope===g&&t.activated?t.cache:t.scope===m&&e.has(t.id)?e.get(t.id):null}(e,t);return null!==n||function(e,t,r){t.scope===g&&me(t,r),t.scope===m&&fe(e,t,r)}(e,t,n=r()),n},Oe=function(e,t,r){return Ae(e,r,(function(){var n=De(e,t,r);return n=de(n)?n.then((function(e){return Ne(t,r,e)})):Ne(t,r,n)}))};function Ne(e,t,r){var n,i=Me(e.parentContext,t,r),s=je(e.parentContext.container),o=s.next();do{n=o.value;var a=e.parentContext,c=e.serviceIdentifier,d=Fe(n,c);i=de(i)?xe(d,a,i):Le(d,a,i),o=s.next()}while(!0!==o.done&&!ie(n).hasKey(e.serviceIdentifier));return i}var Me=function(e,t,r){return"function"==typeof t.onActivation?t.onActivation(e,r):r},Le=function(e,t,r){for(var n=e.next();!n.done;){if(de(r=n.value(t,r)))return xe(e,t,r);n=e.next()}return r},xe=function(e,t,r){return Te(void 0,void 0,void 0,(function(){var n,i;return ke(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]}}))}))},Fe=function(e,t){var r=e._activations;return r.hasKey(t)?r.get(t).values():[].values()},je=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 Ue=function(e,t){var r=e.parentRequest;return null!==r&&(!!t(r)||Ue(r,t))},Be=function(e){return function(t){var r=function(r){return null!==r&&null!==r.target&&r.target.matchesTag(e)(t)};return r.metaData=new z(e,t),r}},Ve=Be("named"),We=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}},He=function(){function e(e){this._binding=e}return e.prototype.when=function(e){return this._binding.constraint=e,new qe(this._binding)},e.prototype.whenTargetNamed=function(e){return this._binding.constraint=Ve(e),new qe(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 qe(this._binding)},e.prototype.whenTargetTagged=function(e,t){return this._binding.constraint=Be(e)(t),new qe(this._binding)},e.prototype.whenInjectedInto=function(e){return this._binding.constraint=function(t){return null!==t&&We(e)(t.parentRequest)},new qe(this._binding)},e.prototype.whenParentNamed=function(e){return this._binding.constraint=function(t){return null!==t&&Ve(e)(t.parentRequest)},new qe(this._binding)},e.prototype.whenParentTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&Be(e)(t)(r.parentRequest)},new qe(this._binding)},e.prototype.whenAnyAncestorIs=function(e){return this._binding.constraint=function(t){return null!==t&&Ue(t,We(e))},new qe(this._binding)},e.prototype.whenNoAncestorIs=function(e){return this._binding.constraint=function(t){return null!==t&&!Ue(t,We(e))},new qe(this._binding)},e.prototype.whenAnyAncestorNamed=function(e){return this._binding.constraint=function(t){return null!==t&&Ue(t,Ve(e))},new qe(this._binding)},e.prototype.whenNoAncestorNamed=function(e){return this._binding.constraint=function(t){return null!==t&&!Ue(t,Ve(e))},new qe(this._binding)},e.prototype.whenAnyAncestorTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&Ue(r,Be(e)(t))},new qe(this._binding)},e.prototype.whenNoAncestorTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&!Ue(r,Be(e)(t))},new qe(this._binding)},e.prototype.whenAnyAncestorMatches=function(e){return this._binding.constraint=function(t){return null!==t&&Ue(t,e)},new qe(this._binding)},e.prototype.whenNoAncestorMatches=function(e){return this._binding.constraint=function(t){return null!==t&&!Ue(t,e)},new qe(this._binding)},e}(),qe=function(){function e(e){this._binding=e}return e.prototype.onActivation=function(e){return this._binding.onActivation=e,new He(this._binding)},e.prototype.onDeactivation=function(e){return this._binding.onDeactivation=e,new He(this._binding)},e}(),ze=function(){function e(e){this._binding=e,this._bindingWhenSyntax=new He(this._binding),this._bindingOnSyntax=new qe(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}(),Ge=function(){function e(e){this._binding=e}return e.prototype.inRequestScope=function(){return this._binding.scope=m,new ze(this._binding)},e.prototype.inSingletonScope=function(){return this._binding.scope=g,new ze(this._binding)},e.prototype.inTransientScope=function(){return this._binding.scope=v,new ze(this._binding)},e}(),Ye=function(){function e(e){this._binding=e,this._bindingWhenSyntax=new He(this._binding),this._bindingOnSyntax=new qe(this._binding),this._bindingInSyntax=new Ge(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}(),$e=function(){function e(e){this._binding=e}return e.prototype.to=function(e){return this._binding.type=S,this._binding.implementationType=e,new Ye(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=y,this._binding.cache=e,this._binding.dynamicValue=null,this._binding.implementationType=null,this._binding.scope=g,new ze(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 Ye(this._binding)},e.prototype.toConstructor=function(e){return this._binding.type=_,this._binding.implementationType=e,this._binding.scope=g,new ze(this._binding)},e.prototype.toFactory=function(e){return this._binding.type=E,this._binding.factory=e,this._binding.scope=g,new ze(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=w,this._binding.scope=g,t},e.prototype.toAutoFactory=function(e){return this._binding.type=E,this._binding.factory=function(t){return function(){return t.container.get(e)}},this._binding.scope=g,new ze(this._binding)},e.prototype.toAutoNamedFactory=function(e){return this._binding.type=E,this._binding.factory=function(t){return function(r){return t.container.getNamed(e,r)}},new ze(this._binding)},e.prototype.toProvider=function(e){return this._binding.type=P,this._binding.provider=e,this._binding.scope=g,new ze(this._binding)},e.prototype.toService=function(e){this.toDynamicValue((function(t){return t.container.get(e)}))},e}(),Je=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}(),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 Ke,onDeactivations:new Ke}},e}(),Ze=function(){return Ze=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},Ze.apply(this,arguments)},Xe=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){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))},et=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])}}},tt=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))},rt=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=v;else if(t.defaultScope!==g&&t.defaultScope!==v&&t.defaultScope!==m)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 L,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=tt([t,r],n,!0).map((function(e){return ie(e)})),a=ie(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 Xe(this,void 0,void 0,(function(){var t,r,n,i,s;return et(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 Xe(this,void 0,void 0,(function(){var t,r,n,i;return et(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||v,r=new A(e,t);return this._bindingDictionary.add(e,r),new $e(r)},e.prototype.rebind=function(e){return this.unbind(e),this.bind(e)},e.prototype.rebindAsync=function(e){return Xe(this,void 0,void 0,(function(){return et(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 Xe(this,void 0,void 0,(function(){var t;return et(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 Xe(this,void 0,void 0,(function(){var e,t=this;return et(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 J(R,"",t,new z(r,n)),s=new q(e);return new ne(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(Je.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 Xe(this,void 0,void 0,(function(){var t;return et(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 Xe(this,void 0,void 0,(function(){var n;return et(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(de(i))return this._handleDeactivationError(i.then((function(){return r._propagateContainerDeactivationThenBindingAndPreDestroyAsync(e,t,n)})),n)}var s=this._propagateContainerDeactivationThenBindingAndPreDestroy(e,t,n);if(de(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 Xe(this,void 0,void 0,(function(){var r;return et(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(de(i))return i.then((function(){return r._deactivateContainerAsync(e,t)}));n=t.next()}},e.prototype._deactivateContainerAsync=function(e,t){return Xe(this,void 0,void 0,(function(){var r;return et(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=Ze(Ze({},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(ue(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=ce(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 de(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(de(this._deactivateIfSingleton(n)))throw new Error("Attempting to unbind dependency with asynchronous destruction (@preDestroy or onDeactivation)")}},e.prototype._deactivateSingletonsAsync=function(e){return Xe(this,void 0,void 0,(function(){var t=this;return et(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 Xe(this,void 0,void 0,(function(){return et(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: "+U(e))}},e.prototype._bindingDeactivationAndPreDestroy=function(e,t,r){var n=this;if("function"==typeof e.onDeactivation){var i=e.onDeactivation(t);if(de(i))return i.then((function(){return n._preDestroy(r,t)}))}return this._preDestroy(r,t)},e.prototype._bindingDeactivationAndPreDestroyAsync=function(e,t,r){return Xe(this,void 0,void 0,(function(){return et(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 nt(e,t,r,n){!function(e){if(void 0!==e)throw new Error(N)}(t),st("inversify:tagged",e,r.toString(),n)}function it(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 st(e,t,r,n){var i=it(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 ot(e){return function(t,r,n){"number"==typeof n?nt(t,r,n,e):function(e,t,r){if(void 0!==e.prototype)throw new Error(N);st("inversify:tagged_props",e.constructor,t,r)}(t,r,e)}}function at(){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 ct,dt=(ct="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(function(e){return"@inject called with undefined this could mean that the class "+e+" has a circular dependency problem. You can use a LazyServiceIdentifier to overcome this limitation."}(i))}return ot(new z(ct,e))(t,r,n)}});const ut=3,lt=4,pt=6,ht=7;var ft;!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"}(ft||(ft={}));var mt;const gt={baseURL:"https://lb.livedigital.space/v1",timeout:5e3},vt={customerId:String("b149fa74b11d989a60fb08e98e6a82883de0b468"),sdk_url:String("https://effectssdk.ai/sdk/audio/"),api_url:String("https://effectssdk.ai/sdk/session/"),version:"2.3.5"},yt={customerId:String("89c41ecf3b3f46fef5dfa9f96842014c21d4901c"),sdk_url:String("https://effectssdk.ai/sdk/"),api_url:String("https://effectssdk.ai/sdk/session/")},_t=()=>{};let bt=class{constructor(e){var t,r,n,i,s,o,a,c,u;mt.set(this,void 0),d(this,mt,{denoiser:null!==(t=e.denoiser)&&void 0!==t?t:"rnnoise",asdk:Object.assign(Object.assign({},vt),e.asdk),loadbalancer:Object.assign(gt,null!==(n=null===(r=e.network)||void 0===r?void 0:r.loadbalancer)&&void 0!==n?n:{}),logLevel:null!==(i=e.logLevel)&&void 0!==i?i:ut,sendAnalytics:null!==(s=e.sendAnalytics)&&void 0!==s&&s,onLogMessage:null!==(o=e.onLogMessage)&&void 0!==o?o:_t,onIssues:null!==(a=e.onIssues)&&void 0!==a?a:_t,disableWid:null!==(c=e.disableWid)&&void 0!==c&&c,effectsSDKParams:Object.assign(Object.assign({},yt),e.effectsSDKParams),onNetworkScoresUpdated:null!==(u=e.onNetworkScoresUpdated)&&void 0!==u?u:_t,staticFilesPath:e.staticFilesPath||window.location.origin},"f")}get(e){return c(this,mt,"f")[e]}set(e,t){c(this,mt,"f")[e]=t}};mt=new WeakMap,bt=i([at(),o("design:paramtypes",[Object])],bt);var Et,wt,St,Ct,Pt=bt;class Tt extends t{constructor(){super(),this.addListener=(e,t)=>this.on(e,t),this.removeListener=(e,t)=>this.off(e,t),this.prependListener=(e,t)=>(super.prependListener(e,t),this),this.prependOnceListener=(e,t)=>(super.prependOnceListener(e,t),this),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)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}removeAllListeners(e){return super.removeAllListeners(e),this}}function kt(){}function Rt(){Rt.init.call(this)}function It(e){return void 0===e._maxListeners?Rt.defaultMaxListeners:e._maxListeners}function Dt(e,t,r){if(t)e.call(r);else for(var n=e.length,i=jt(e,n),s=0;s<n;++s)i[s].call(r)}function At(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,s=jt(e,i),o=0;o<i;++o)s[o].call(r,n)}function Ot(e,t,r,n,i){if(t)e.call(r,n,i);else for(var s=e.length,o=jt(e,s),a=0;a<s;++a)o[a].call(r,n,i)}function Nt(e,t,r,n,i,s){if(t)e.call(r,n,i,s);else for(var o=e.length,a=jt(e,o),c=0;c<o;++c)a[c].call(r,n,i,s)}function Mt(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,s=jt(e,i),o=0;o<i;++o)s[o].apply(r,n)}function Lt(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 kt,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=It(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 xt(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 Ft(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 jt(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}kt.prototype=Object.create(null),Rt.EventEmitter=Rt,Rt.usingDomains=!1,Rt.prototype.domain=void 0,Rt.prototype._events=void 0,Rt.prototype._maxListeners=void 0,Rt.defaultMaxListeners=10,Rt.init=function(){this.domain=null,Rt.usingDomains&&(void 0).active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new kt,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Rt.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},Rt.prototype.getMaxListeners=function(){return It(this)},Rt.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:Dt(r,u,this);break;case 2:At(r,u,this,arguments[1]);break;case 3:Ot(r,u,this,arguments[1],arguments[2]);break;case 4:Nt(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];Mt(r,u,this,i)}return!0},Rt.prototype.addListener=function(e,t){return Lt(this,e,t,!1)},Rt.prototype.on=Rt.prototype.addListener,Rt.prototype.prependListener=function(e,t){return Lt(this,e,t,!0)},Rt.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,xt(this,e,t)),this},Rt.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,xt(this,e,t)),this},Rt.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 kt:(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 kt,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},Rt.prototype.off=function(e,t){return this.removeListener(e,t)},Rt.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new kt,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new kt: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 kt,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},Rt.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):[]},Rt.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Ft.call(e,t)},Rt.prototype.listenerCount=Ft,Rt.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class Ut extends Rt{}!function(e){e.Issue="issue",e.NetworkScoresUpdated="network-scores-updated",e.StatsParsingFinished="stats-parsing-finished"}(Et||(Et={})),function(e){e.Network="network",e.CPU="cpu",e.Server="server",e.Stream="stream"}(wt||(wt={})),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"}(St||(St={})),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"}(Ct||(Ct={}));class Bt extends Rt{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(Bt.STATS_REPORTS_PARSED,{timeTaken:r,reportItems:t}),t.forEach((e=>{this.emit(Bt.STATS_REPORT_READY_EVENT,e)}))}}const Vt=(()=>{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 Wt{#e={};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,Vt({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=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=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;return i-=2.5*r,1+.035*i+7e-6*i*(i-60)*(100-i)}}class Ht{#t=new Map;#r;#n;constructor(e={}){this.#r=e.statsCleanupTtlMs??35e3,this.#n=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.#t.has(t)&&Vt({taskId:t,delayMs:this.#r,callback:()=>{this.deleteLastProcessedStats(t),"function"==typeof r&&r()}})}setLastProcessedStats(e,t){if(!e||t.connection.id!==e)return;const r=this.#t.get(e)??[];r.push(t),r.length>this.#n&&r.shift(),this.#t.set(e,r)}getLastProcessedStats(e){const t=this.#t.get(e);return t?.[t.length-1]}getAllLastProcessedStats(e){return this.#t.get(e)??[]}deleteLastProcessedStats(e){this.#t.delete(e)}}class qt extends Ht{#i;constructor(e={}){super(e),this.#i=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.#i?(t.push({statsSample:s,type:wt.Network,reason:St.OutboundNetworkThroughput}),t):t}}class zt extends Ht{#s;#o;#a;#c;constructor(e={}){super(),this.#s=e.highPacketLossThresholdPct??5,this.#o=e.highJitterThreshold??200,this.#a=e.highJitterBufferDelayThresholdMs??500,this.#c=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=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.#s,v=l>=this.#o,y=c>=this.#c,_=p>this.#a,b=y&&!v&&!g,E=g&&v,w=v&&_,S={rtt:c,packetLossPct:m,avgJitter:l,avgJitterBufferDelay:p};return(v||g)&&t.push({statsSample:S,type:wt.Network,reason:St.InboundNetworkQuality,iceCandidate:e.connection.local.id}),b&&t.push({statsSample:S,type:wt.Server,reason:St.ServerIssue,iceCandidate:e.connection.remote.id}),E&&t.push({statsSample:S,type:wt.Network,reason:St.InboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),w&&t.push({statsSample:S,type:wt.Network,reason:St.NetworkMediaSyncFailure,iceCandidate:e.connection.local.id}),t}}class Gt extends Ht{#d;constructor(e={}){super(),this.#d=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,a=i-s,c=Math.round(100*a/o),d={correctedSamplesPct:c};c>this.#d&&r.push({statsSample:d,type:wt.Network,reason:St.NetworkMediaSyncFailure,ssrc:e.ssrc})})),r):r}}class Yt extends Ht{#s;#o;constructor(e={}){super(),this.#s=e.highPacketLossThresholdPct??5,this.#o=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=d/r.length,l=s-o,p=a.packetsLost-a.lastPacketsLost,h=l&&p?Math.round(100*p/(l+p)):0,f=h>this.#s,m=u>=this.#o,g=!f&&m||m||f,v={rtt:c,avgJitter:u,packetLossPct:h};return f&&m&&t.push({statsSample:v,type:wt.Network,reason:St.OutboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),g&&t.push({statsSample:v,type:wt.Network,reason:St.OutboundNetworkQuality,iceCandidate:e.connection.local.id}),t}}class $t extends Ht{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:wt.CPU,reason:St.EncoderCPUThrottling,ssrc:e.ssrc}),"bandwidth"===e.qualityLimitationReason&&r.push({statsSample:i,type:wt.Network,reason:St.OutboundNetworkThroughput,ssrc:e.ssrc}))})),r):r}}class Jt extends Ht{UNKNOWN_DECODER="unknown";#u={};performDetection(e){return this.processData(e)}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:r}=e;super.performPrevStatsCleanup({...e,cleanupCallback:()=>{delete this.#u[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:wt.Stream,reason:St.UnknownVideoDecoderIssue,trackIdentifier:e.track.trackIdentifier})}}else this.setLastDecoderWithIssue(r,s,void 0)})),t}setLastDecoderWithIssue(e,t,r){const n=this.#u[e]??{};void 0===r?delete n[t]:n[t]=r,this.#u[e]=n}hadLastDecoderWithIssue(e,t){const r=this.#u[e];return(r&&r[t])===this.UNKNOWN_DECODER}}const Kt=e=>e.reduce(((e,t)=>e+t),0)/e.length,Qt=(e,t,r=30)=>{const n=[];for(let r=1;r<t.length-1;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)(Kt(e),e);return Math.sqrt(t)})(n)>r},Zt=(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 Xt extends Ht{#l;#p;#h;constructor(e={}){super(),this.#l=e.avgFreezeDurationThresholdMs??1e3,this.#p=e.frozenDurationThresholdPct??30,this.#h=e.minMosQuality??Ct.BAD}performDetection(e){const t=e.networkScores.inbound;return void 0!==t&&t<=this.#h?[]: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(Zt(t.ssrc,[r[r.length-1],e]))return;if(Qt(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.#p||o>this.#l?{ssrc:t.ssrc,avgFreezeDurationMs:o,frozenDurationPct:a}:void 0})).filter((e=>void 0!==e));return n.length>0&&(t.push({type:wt.Stream,reason:St.FrozenVideoTrack,statsSample:{ssrcs:n.map((e=>e.ssrc))}}),this.deleteLastProcessedStats(e.connection.id)),t}}class er extends Ht{#f;#m;#h;constructor(e={}){super(e),this.#f=e.volatilityThreshold??8,this.#m=e.affectedStreamsPercentThreshold??30,this.#h=e.minMosQuality??Ct.BAD}performDetection(e){return[...this.getAllLastProcessedStats(e.connection.id),e].find((e=>void 0!==e.networkScores.inbound&&e.networkScores.inbound<=this.#h))?[]: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(Zt(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(Qt(e.ssrc,r))return;const n=(e=>{if(0===e.length)throw new Error("Cannot calculate volatility for empty array");const t=Kt(e);return e.reduce(((e,r)=>e+Math.abs(r-t)),0)/e.length*100/t})(t);return n>this.#f?{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.#m&&(t.push({type:wt.CPU,reason:St.DecoderCPUThrottling,statsSample:{affectedStreamsPercent:i,throtthedStreams:n}}),this.deleteLastProcessedStats(e.connection.id)),t}}const tr=e=>"closed"===e.iceConnectionState||"closed"===e.connectionState,rr=(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 nr{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(!tr(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 ir{prevStats=new Map;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(!tr(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()}),Vt({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=rr(e,r,"bytesReceived"),e.packetRate=rr(e,r,"packetsReceived")})),e.audio.outbound.forEach((e=>{const r=t.audio.outbound.find((({id:t})=>t===e.id));e.bitrate=rr(e,r,"bytesSent"),e.packetRate=rr(e,r,"packetsSent")})),e.video.inbound.forEach((e=>{const r=t.video.inbound.find((({id:t})=>t===e.id));e.bitrate=rr(e,r,"bytesReceived"),e.packetRate=rr(e,r,"packetsReceived")})),e.video.outbound.forEach((e=>{const r=t.video.outbound.find((({id:t})=>t===e.id));e.bitrate=rr(e,r,"bytesSent"),e.packetRate=rr(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 sr extends Ht{#g=new Map;#v;#y;constructor(e={}){super(),this.#v=e.timeoutMs??15e3,this.#y=e.steps??3}performDetection(e){return this.processData(e)}processData(e){const t=[],r=[...this.getAllLastProcessedStats(e.connection.id),e];if(r.length<this.#y)return t;const n=r.slice(-this.#y),i=n.map((e=>e.video.inbound)),s=n.map((e=>e.audio.inbound));return t.push(...this.detectMissingData(s,wt.Stream,St.MissingAudioStreamData)),t.push(...this.detectMissingData(i,wt.Stream,St.MissingVideoStreamData)),new Set(this.#g.keys()).forEach((e=>{const t=this.#g.get(e);t&&Date.now()-t>this.#v&&this.removeMarkedIssue(e)})),t}detectMissingData(e,t,r){const n=[],i=e.pop(),s=sr.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(!sr.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.#g.get(e);return(!r||t-r>this.#v)&&(this.#g.set(e,t),!0)}removeMarkedIssue(e){this.#g.delete(e)}}class or{eventEmitter;#_=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;autoAddPeerConnections;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new Ut,e.onIssues&&this.eventEmitter.on(Et.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(Et.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new $t,new zt,new Yt,new Gt,new qt,new Jt,new Xt,new er,new sr],this.networkScoresCalculator=e.networkScoresCalculator??new Wt,this.compositeStatsParser=e.compositeStatsParser??new nr({statsParser:new ir({ignoreSSRCList:e.ignoreSSRCList,logger:this.logger})}),this.statsReporter=e.statsReporter??new Bt({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.autoAddPeerConnections=e.autoAddPeerConnections??!0,this.autoAddPeerConnections&&this.wrapRTCPeerConnection(),this.statsReporter.on(Bt.STATS_REPORT_READY_EVENT,(e=>{const t=this.calculateNetworkScores(e.stats);this.detectIssues({data:e.stats},t)})),this.statsReporter.on(Bt.STATS_REPORTS_PARSED,(t=>{const r={timeTaken:t.timeTaken,ts:Date.now()};e.onStats&&e.onStats(t.reportItems),this.eventEmitter.emit(Et.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(Et.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(Et.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}}Error;const ar=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0}],cr=({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]=cr({from:e[r],seen:t.slice(),forceEnumerable:n}):i[r]=s);for(const{property:t,enumerable:r}of ar)"string"==typeof e[t]&&Object.defineProperty(i,t,{value:e[t],enumerable:!!n||r,configurable:!0,writable:!0});return i};var dr,ur,lr,pr=e=>"object"==typeof e&&null!==e?cr({from:e,seen:[],forceEnumerable:!0}):"function"==typeof e?`[Function: ${e.name||"anonymous"}]`:e;dr=new WeakMap,ur=new WeakMap,lr=new WeakMap;var hr=new class{constructor(){dr.set(this,void 0),ur.set(this,void 0),lr.set(this,void 0)}get meta(){return{peerId:c(this,dr,"f"),channelId:c(this,ur,"f"),appId:c(this,lr,"f")}}setPeerId(e){d(this,dr,e,"f")}setChannelId(e){d(this,ur,e,"f")}setAppId(e){d(this,lr,e,"f")}clear(){d(this,dr,void 0,"f"),d(this,ur,void 0,"f"),d(this,lr,void 0,"f")}};const fr="channel.join",mr="channel.getPeers",gr="channel.triggerStateEvent",vr="peer.updateAppData",yr="channel.confirmActivity",_r="channel.getAudioObserverProducer",br="peer.changeProducePermissions",Er="peer.addProducePermissions",wr="peer.removeProducePermissions",Sr="peer.ping",Cr="channel-event",Pr="peer-joined",Tr="peer-left",kr="channel-activity-confirmation-required",Rr="channel-activity-confirmation-acquired",Ir="channel-activity-confirmation-expired",Dr="channel-rejoin-required",Ar="devices-list-updated",Or="transport-connection-timeout",Nr="track-force-closed",Mr="track-failed",Lr="active-speaker-changed",xr="channel-state-inconsistent",Fr="connection-lost",jr="connection-restored",Ur="forced-disconnect",Br="reject-unauthorized",Vr="denoiser-initializing",Wr="channel-state-synced",Hr="denoiser-enabled",qr="denoiser-disabled",zr="denoiser-fallback",Gr="denoiser-failed",Yr="volume-changed",$r={trackProduced:"track-produced",trackUnproduced:"track-unproduced",trackPaused:"track-paused",trackResumed:"track-resumed",trackClosed:"track-closed",trackReopened:"track-reopened",trackFailed:"track-failed"},Jr="media-published",Kr="media-unpublished",Qr="publisher-paused",Zr="publisher-resumed",Xr="track-start",en="track-end",tn="track-paused",rn="track-resumed",nn="track-failed",sn="app-data-updated",on="produce-permissions-changed",an="groups-changed",cn="peer.newProducer",dn="producer.close",un="producer.pause",ln="producer.resume",pn="producer.setMaxSpatialLayer",hn="producer.requestMaxSpatialLayer",fn="consumer.create",mn="dataConsumer.create",gn="consumer.close",vn="consumer.pause",yn="consumer.resume",_n="consumer.changeConsumerPreferredLayers",bn="consumer.requestKeyFrame",En="transport.create",wn="transport.connect",Sn="transport.produce",Cn="transport.produceData",Pn="transport.connectionTimeout",Tn="transport.getIceParameters",kn=[En,wn,Sn,Cn,Tn,dn,un,ln,vn,yn,fn,gn,Sr],Rn="socket-state",In="transport-state";class Dn extends Error{constructor(e,t,r){super(e),this.errorCode=null!=t?t:"unknown_error",this.meta=r}}class An extends Dn{constructor(e,t){super(e,null!=t?t:"unsupported_error")}}An.UNSUPPORTED_DEVICE_CODE="unsupported_device_error",An.UNSUPPORTED_OPERATION_CODE="unsupported_operation_error";const On=e=>{let t;try{t=JSON.stringify(e)}catch(e){throw new Error("Invalid appData")}if(!((new TextEncoder).encode(t).length<=2048))throw new Error("Maximum size appData reached")};function Nn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Mn(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=Nn(n)&&Nn(s);(o&&!Mn(n,s)||!o&&n!==s)&&(i=!1)})),i}function Ln(e,t,r=!1){let n=null;return function(...i){return a(this,void 0,void 0,(function*(){const s=r&&!n;"number"==typeof n&&clearTimeout(n),n=setTimeout((()=>a(this,void 0,void 0,(function*(){n=null,r||(yield e.apply(this,i))}))),t),s&&(yield e.apply(this,i))}))}}var xn={exports:{}},Fn=p(xn.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}}));const jn=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:[]},Un=e=>["video/vp9","vp9"].includes(e.toLowerCase());class Bn{sleepMs(e){return a(this,void 0,void 0,(function*(){yield new Promise((t=>setTimeout(t,e)))}))}now(){return new Date(Date.now())}}const Vn=new Bn,Wn=(e,...t)=>a(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:pr(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 Vn.sleepMs(Math.min(e,null!==(s=t.maxBackoffDelayMs)&&void 0!==s?s:e))}}}throw null!=c?c:new Error("retryAsync logic failed")}));var Hn,qn,zn,Gn,Yn;!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.ChannelStateSynchronizer="ChannelStateSynchronizer",e.ChannelStateSyncEventHandler="ChannelStateSyncEventHandler",e.WebRTCIssueDetector="WebRTCIssueDetector",e.LoggerFactory="LoggerFactory",e.MediaStreamTrackManager="MediaStreamTrackManager",e.SocketIO="SocketIO",e.LoadBalancerApiClient="LoadBalancerApiClient",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"}(Hn||(Hn={})),function(e){e.P2P="p2p",e.Common="common"}(qn||(qn={})),function(e){e.Camera="camera",e.CameraPreview="camera-preview",e.Microphone="microphone",e.MicrophonePreview="microphone-preview",e.ScreenVideo="screen-video",e.ScreenAudio="screen-audio",e.CustomVideo="custom-video",e.CustomAudio="custom-audio",e.Unknown="unknown"}(zn||(zn={})),function(e){e.NotFoundError="NotFoundError",e.NoDevices="NoDevices",e.DeviceIsBusy="DeviceIsBusy",e.NotAllowedError="NotAllowedError",e.RequestDevicesUnknownError="RequestDevicesUnknownError"}(Gn||(Gn={})),function(e){e.Connect="connect",e.Connected="connected",e.ConnectError="connect_error",e.Reconnect="reconnect",e.Reconnecting="reconnecting",e.Reconnected="reconnected",e.ReconnectAttempt="reconnect_attempt",e.ReconnectFailed="reconnect_failed",e.ReconnectError="reconnect_error",e.NeedToJoinFirst="need_to_join_first",e.Disconnect="disconnect",e.Disconnected="disconnected",e.Error="error",e.State="state",e.BufferingStart="buffering_start",e.BufferingEnd="buffering_end"}(Yn||(Yn={}));let $n=class{constructor(){this.isJoined=!1,this.isChannelJoining=!1}reset(){this.appId=void 0,this.channelId=void 0}};function Jn(){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 Kn(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)}}$n=i([at()],$n);function Qn(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):Xn(n,i)}function Zn(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()+ti(s)+ti(i)}function Xn(e,t){return{lo:0|e,hi:0|t}}function ei(e,t){return t=~t,e?e=1+~e:t+=1,Xn(e,t)}const ti=e=>{const t=String(e);return"0000000".slice(t.length)+t};function ri(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 ni(){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 ii=si();function si(){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()),oi(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),ai(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),oi(e),Qn(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),ai(e),Qn(e)),dec:(e,t)=>function(e,t){let r=Xn(e,t);const n=2147483648&r.hi;n&&(r=ei(r.lo,r.hi));const i=Zn(r.lo,r.hi);return n?"-"+i:i}(e,t),uDec:(e,t)=>Zn(e,t)}}function oi(e){if(!/^-?[0-9]+$/.test(e))throw new Error("invalid int64: "+e)}function ai(e){if(!/^[0-9]+$/.test(e))throw new Error("invalid uint64: "+e)}const ci=Symbol.for("@bufbuild/protobuf/text-encoding");function di(){if(null==globalThis[ci]){const e=new globalThis.TextEncoder,t=new globalThis.TextDecoder;globalThis[ci]={encodeUtf8:t=>e.encode(t),decodeUtf8:e=>t.decode(e),checkUtf8(e){try{return encodeURIComponent(e),!0}catch(e){return!1}}}}return globalThis[ci]}var ui;!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"}(ui||(ui={}));const li=34028234663852886e22,pi=-34028234663852886e22;class hi{constructor(e=di().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(gi(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return mi(e),ri(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>li||e<pi))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){gi(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){mi(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return mi(e),ri(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),r=new DataView(t.buffer),n=ii.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=ii.uEnc(e);return r.setInt32(0,n.lo,!0),r.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=ii.enc(e);return Kn(t.lo,t.hi,this.buf),this}sint64(e){const t=ii.enc(e),r=t.hi>>31;return Kn(t.lo<<1^r,(t.hi<<1|t.lo>>>31)^r,this.buf),this}uint64(e){const t=ii.uEnc(e);return Kn(t.lo,t.hi,this.buf),this}}class fi{constructor(e,t=di().decodeUtf8){this.decodeUtf8=t,this.varint64=Jn,this.uint32=ni,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 ui.Varint:for(;128&this.buf[this.pos++];);break;case ui.Bit64:this.pos+=4;case ui.Bit32:this.pos+=4;break;case ui.LengthDelimited:let r=this.uint32();this.pos+=r;break;case ui.StartGroup:for(;;){const[e,r]=this.tag();if(r===ui.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 ii.dec(...this.varint64())}uint64(){return ii.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),r=-(1&e);return e=(e>>>1|(1&t)<<31)^r,t=t>>>1^r,ii.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 ii.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ii.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 mi(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 gi(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 vi={encode:(e,t=new hi)=>(0!==e.time&&t.uint32(8).int64(e.time),t),decode(e,t){const r=e instanceof fi?e:new fi(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=yi(r.int64());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({time:_i(e.time)?globalThis.Number(e.time):0}),toJSON(e){const t={};return 0!==e.time&&(t.time=Math.round(e.time)),t},create:e=>vi.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 yi(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 _i(e){return null!=e}var bi;function Ei(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 wi={encode:(e,t=new hi)=>(Object.entries(e.fields).forEach((([e,r])=>{void 0!==r&&Si.encode({key:e,value:r},t.uint32(10).fork()).join()})),t),decode(e,t){const r=e instanceof fi?e:new fi(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=Si.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:Ti(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 Si={encode:(e,t=new hi)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&Ci.encode(Ci.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof fi?e:new fi(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=Ci.unwrap(Ci.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:ki(e.key)?globalThis.String(e.key):"",value:ki(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=>Si.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 Ci={encode:(e,t=new hi)=>(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&&Pi.encode(Pi.wrap(e.listValue),t.uint32(50).fork()).join(),t),decode(e,t){const r=e instanceof fi?e:new fi(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=Pi.unwrap(Pi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({nullValue:ki(e.nullValue)?Ei(e.nullValue):void 0,numberValue:ki(e.numberValue)?globalThis.Number(e.numberValue):void 0,stringValue:ki(e.stringValue)?globalThis.String(e.stringValue):void 0,boolValue:ki(e.boolValue)?globalThis.Boolean(e.boolValue):void 0,structValue:Ti(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=>Ci.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 Pi={encode(e,t=new hi){for(const r of e.values)Ci.encode(Ci.wrap(r),t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof fi?e:new fi(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(Ci.unwrap(Ci.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=>Pi.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 Ti(e){return"object"==typeof e&&null!==e}function ki(e){return null!=e}const Ri={encode:(e,t=new hi)=>(Object.entries(e.event).forEach((([e,r])=>{void 0!==r&&Ii.encode({key:e,value:r},t.uint32(10).fork()).join()})),t),decode(e,t){const r=e instanceof fi?e:new fi(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=Ii.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=>({event:Di(e.event)?Object.entries(e.event).reduce(((e,[t,r])=>(e[t]=r,e)),{}):{}}),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=>Ri.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 Ii={encode:(e,t=new hi)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&Ci.encode(Ci.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof fi?e:new fi(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=Ci.unwrap(Ci.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:Ai(e.key)?globalThis.String(e.key):"",value:Ai(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=>Ii.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 Di(e){return"object"==typeof e&&null!==e}function Ai(e){return null!=e}var Oi,Ni;function Mi(e){switch(e){case 0:case"PEER_GROUP_UNSPECIFIED":return Oi.PEER_GROUP_UNSPECIFIED;case 1:case"PEER_GROUP_MODERATOR":return Oi.PEER_GROUP_MODERATOR;case 2:case"PEER_GROUP_USER":return Oi.PEER_GROUP_USER;default:return Oi.UNRECOGNIZED}}function Li(e){switch(e){case Oi.PEER_GROUP_UNSPECIFIED:return"PEER_GROUP_UNSPECIFIED";case Oi.PEER_GROUP_MODERATOR:return"PEER_GROUP_MODERATOR";case Oi.PEER_GROUP_USER:return"PEER_GROUP_USER";case Oi.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function xi(e){switch(e){case 0:case"PRODUCER_LABEL_UNSPECIFIED":return Ni.PRODUCER_LABEL_UNSPECIFIED;case 1:case"PRODUCER_LABEL_CAMERA":return Ni.PRODUCER_LABEL_CAMERA;case 2:case"PRODUCER_LABEL_MICROPHONE":return Ni.PRODUCER_LABEL_MICROPHONE;case 3:case"PRODUCER_LABEL_SCREEN_VIDEO":return Ni.PRODUCER_LABEL_SCREEN_VIDEO;case 4:case"PRODUCER_LABEL_SCREEN_AUDIO":return Ni.PRODUCER_LABEL_SCREEN_AUDIO;case 5:case"PRODUCER_LABEL_CUSTOM_VIDEO":return Ni.PRODUCER_LABEL_CUSTOM_VIDEO;case 6:case"PRODUCER_LABEL_CUSTOM_AUDIO":return Ni.PRODUCER_LABEL_CUSTOM_AUDIO;case 7:case"PRODUCER_LABEL_UNKNOWN":return Ni.PRODUCER_LABEL_UNKNOWN;default:return Ni.UNRECOGNIZED}}function Fi(e){switch(e){case Ni.PRODUCER_LABEL_UNSPECIFIED:return"PRODUCER_LABEL_UNSPECIFIED";case Ni.PRODUCER_LABEL_CAMERA:return"PRODUCER_LABEL_CAMERA";case Ni.PRODUCER_LABEL_MICROPHONE:return"PRODUCER_LABEL_MICROPHONE";case Ni.PRODUCER_LABEL_SCREEN_VIDEO:return"PRODUCER_LABEL_SCREEN_VIDEO";case Ni.PRODUCER_LABEL_SCREEN_AUDIO:return"PRODUCER_LABEL_SCREEN_AUDIO";case Ni.PRODUCER_LABEL_CUSTOM_VIDEO:return"PRODUCER_LABEL_CUSTOM_VIDEO";case Ni.PRODUCER_LABEL_CUSTOM_AUDIO:return"PRODUCER_LABEL_CUSTOM_AUDIO";case Ni.PRODUCER_LABEL_UNKNOWN:return"PRODUCER_LABEL_UNKNOWN";case Ni.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"}(Oi||(Oi={})),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"}(Ni||(Ni={}));const ji={encode(e,t=new hi){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 fi?e:new fi(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=>Mi(e))):[],producePermissions:globalThis.Array.isArray(null==e?void 0:e.producePermissions)?e.producePermissions.map((e=>xi(e))):[],changedProducePermissions:globalThis.Array.isArray(null==e?void 0:e.changedProducePermissions)?e.changedProducePermissions.map((e=>xi(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=>Li(e)))),(null===(r=e.producePermissions)||void 0===r?void 0:r.length)&&(i.producePermissions=e.producePermissions.map((e=>Fi(e)))),(null===(n=e.changedProducePermissions)||void 0===n?void 0:n.length)&&(i.changedProducePermissions=e.changedProducePermissions.map((e=>Fi(e)))),i},create:e=>ji.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 Ui={encode:(e,t=new hi)=>(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 fi?e:new fi(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=Bi(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:Vi(e.seconds)?globalThis.Number(e.seconds):0,nanos:Vi(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=>Ui.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 Bi(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 Vi(e){return null!=e}var Wi;function Hi(e){switch(e){case 0:case"PRODUCER_KIND_UNSPECIFIED":return Wi.PRODUCER_KIND_UNSPECIFIED;case 1:case"PRODUCER_KIND_AUDIO":return Wi.PRODUCER_KIND_AUDIO;case 2:case"PRODUCER_KIND_VIDEO":return Wi.PRODUCER_KIND_VIDEO;default:return Wi.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"}(Wi||(Wi={}));const qi={encode(e,t=new hi){""!==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)Ci.encode(Ci.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 fi?e:new fi(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(Ci.unwrap(Ci.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:zi(e.id)?globalThis.String(e.id):"",kind:zi(e.kind)?Hi(e.kind):0,label:zi(e.label)?xi(e.label):0,peerId:zi(e.peerId)?globalThis.String(e.peerId):"",paused:!!zi(e.paused)&&globalThis.Boolean(e.paused),encodings:globalThis.Array.isArray(null==e?void 0:e.encodings)?[...e.encodings]:[],maxSpatialLayer:zi(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 Wi.PRODUCER_KIND_UNSPECIFIED:return"PRODUCER_KIND_UNSPECIFIED";case Wi.PRODUCER_KIND_AUDIO:return"PRODUCER_KIND_AUDIO";case Wi.PRODUCER_KIND_VIDEO:return"PRODUCER_KIND_VIDEO";case Wi.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.kind)),0!==e.label&&(r.label=Fi(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=>qi.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 zi(e){return null!=e}var Gi;function Yi(e){switch(e){case 0:case"PEER_ROLE_UNSPECIFIED":return Gi.PEER_ROLE_UNSPECIFIED;case 1:case"PEER_ROLE_HOST":return Gi.PEER_ROLE_HOST;case 2:case"PEER_ROLE_AUDIENCE":return Gi.PEER_ROLE_AUDIENCE;default:return Gi.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"}(Gi||(Gi={}));const $i={encode(e,t=new hi){""!==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)qi.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&&Ji.encode({key:e,value:r},t.uint32(66).fork()).join()})),0!==e.role&&t.uint32(72).int32(e.role),void 0!==e.loginDate&&Ui.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 fi?e:new fi(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(qi.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=Ji.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=Ki(Ui.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=>({id:Xi(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=>qi.fromJSON(e))):[],uid:Xi(e.uid)?globalThis.String(e.uid):"",appId:Xi(e.appId)?globalThis.String(e.appId):"",appData:Zi(e.appData)?Object.entries(e.appData).reduce(((e,[t,r])=>(e[t]=r,e)),{}):{},role:Xi(e.role)?Yi(e.role):0,loginDate:Xi(e.loginDate)?Qi(e.loginDate):void 0,groups:globalThis.Array.isArray(null==e?void 0:e.groups)?e.groups.map((e=>Mi(e))):[],producePermissions:globalThis.Array.isArray(null==e?void 0:e.producePermissions)?e.producePermissions.map((e=>xi(e))):[]}),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=>qi.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 Gi.PEER_ROLE_UNSPECIFIED:return"PEER_ROLE_UNSPECIFIED";case Gi.PEER_ROLE_HOST:return"PEER_ROLE_HOST";case Gi.PEER_ROLE_AUDIENCE:return"PEER_ROLE_AUDIENCE";case Gi.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=>Li(e)))),(null===(i=e.producePermissions)||void 0===i?void 0:i.length)&&(s.producePermissions=e.producePermissions.map((e=>Fi(e)))),s},create:e=>$i.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=>qi.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 Ji={encode:(e,t=new hi)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&Ci.encode(Ci.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof fi?e:new fi(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=Ci.unwrap(Ci.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:Xi(e.key)?globalThis.String(e.key):"",value:Xi(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 Ki(e){let t=1e3*(e.seconds||0);return t+=(e.nanos||0)/1e6,new globalThis.Date(t)}function Qi(e){return e instanceof globalThis.Date?e:"string"==typeof e?new globalThis.Date(e):Ki(Ui.fromJSON(e))}function Zi(e){return"object"==typeof e&&null!==e}function Xi(e){return null!=e}const es={encode(e,t=new hi){for(const r of e.peers)$i.encode(r,t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof fi?e:new fi(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($i.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=>$i.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=>$i.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=>$i.fromPartial(e))))||[],r}};const ts={encode:(e,t=new hi)=>(""!==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 fi?e:new fi(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:is(e.id)?globalThis.String(e.id):"",paused:!!is(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=>ts.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 rs={encode(e,t=new hi){""!==e.id&&t.uint32(10).string(e.id);for(const r of e.producers)ts.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 fi?e:new fi(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(ts.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:is(e.id)?globalThis.String(e.id):"",producers:globalThis.Array.isArray(null==e?void 0:e.producers)?e.producers.map((e=>ts.fromJSON(e))):[],appDataHash:is(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=>ts.toJSON(e)))),void 0!==e.appDataHash&&(r.appDataHash=e.appDataHash),r},create:e=>rs.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=>ts.fromPartial(e))))||[],i.appDataHash=null!==(n=e.appDataHash)&&void 0!==n?n:void 0,i}};const ns={encode(e,t=new hi){for(const r of e.peers)rs.encode(r,t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof fi?e:new fi(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(rs.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=>rs.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=>rs.toJSON(e)))),r},create:e=>ns.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=>rs.fromPartial(e))))||[],r}};function is(e){return null!=e}var ss;function os(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 as(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 cs={encode:(e,t=new hi)=>(0!==e.eventType&&t.uint32(8).int32(e.eventType),void 0!==e.channelState&&es.encode(e.channelState,t.uint32(18).fork()).join(),void 0!==e.channelStateShort&&ns.encode(e.channelStateShort,t.uint32(26).fork()).join(),void 0!==e.channelActivityConfirmationTime&&vi.encode(e.channelActivityConfirmationTime,t.uint32(34).fork()).join(),void 0!==e.channelManagementEvent&&Ri.encode(e.channelManagementEvent,t.uint32(42).fork()).join(),void 0!==e.channelProducePermissions&&ji.encode(e.channelProducePermissions,t.uint32(50).fork()).join(),void 0!==e.peer&&$i.encode(e.peer,t.uint32(58).fork()).join(),t),decode(e,t){const r=e instanceof fi?e:new fi(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=es.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.channelStateShort=ns.decode(r,r.uint32());continue;case 4:if(34!==e)break;i.channelActivityConfirmationTime=vi.decode(r,r.uint32());continue;case 5:if(42!==e)break;i.channelManagementEvent=Ri.decode(r,r.uint32());continue;case 6:if(50!==e)break;i.channelProducePermissions=ji.decode(r,r.uint32());continue;case 7:if(58!==e)break;i.peer=$i.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({eventType:ds(e.eventType)?os(e.eventType):0,channelState:ds(e.channelState)?es.fromJSON(e.channelState):void 0,channelStateShort:ds(e.channelStateShort)?ns.fromJSON(e.channelStateShort):void 0,channelActivityConfirmationTime:ds(e.channelActivityConfirmationTime)?vi.fromJSON(e.channelActivityConfirmationTime):void 0,channelManagementEvent:ds(e.channelManagementEvent)?Ri.fromJSON(e.channelManagementEvent):void 0,channelProducePermissions:ds(e.channelProducePermissions)?ji.fromJSON(e.channelProducePermissions):void 0,peer:ds(e.peer)?$i.fromJSON(e.peer):void 0}),toJSON(e){const t={};return 0!==e.eventType&&(t.eventType=as(e.eventType)),void 0!==e.channelState&&(t.channelState=es.toJSON(e.channelState)),void 0!==e.channelStateShort&&(t.channelStateShort=ns.toJSON(e.channelStateShort)),void 0!==e.channelActivityConfirmationTime&&(t.channelActivityConfirmationTime=vi.toJSON(e.channelActivityConfirmationTime)),void 0!==e.channelManagementEvent&&(t.channelManagementEvent=Ri.toJSON(e.channelManagementEvent)),void 0!==e.channelProducePermissions&&(t.channelProducePermissions=ji.toJSON(e.channelProducePermissions)),void 0!==e.peer&&(t.peer=$i.toJSON(e.peer)),t},create:e=>cs.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?es.fromPartial(e.channelState):void 0,r.channelStateShort=void 0!==e.channelStateShort&&null!==e.channelStateShort?ns.fromPartial(e.channelStateShort):void 0,r.channelActivityConfirmationTime=void 0!==e.channelActivityConfirmationTime&&null!==e.channelActivityConfirmationTime?vi.fromPartial(e.channelActivityConfirmationTime):void 0,r.channelManagementEvent=void 0!==e.channelManagementEvent&&null!==e.channelManagementEvent?Ri.fromPartial(e.channelManagementEvent):void 0,r.channelProducePermissions=void 0!==e.channelProducePermissions&&null!==e.channelProducePermissions?ji.fromPartial(e.channelProducePermissions):void 0,r.peer=void 0!==e.peer&&null!==e.peer?$i.fromPartial(e.peer):void 0,r}};function ds(e){return null!=e}const us={encode:(e,t=new hi)=>(""!==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 fi?e:new fi(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:ls(e.id)?globalThis.String(e.id):"",peerId:ls(e.peerId)?globalThis.String(e.peerId):"",producerPeerId:ls(e.producerPeerId)?globalThis.String(e.producerPeerId):"",spatialLayer:ls(e.spatialLayer)?globalThis.Number(e.spatialLayer):void 0,temporalLayer:ls(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=>us.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 ls(e){return null!=e}const ps={encode:(e,t=new hi)=>(""!==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 fi?e:new fi(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:hs(e.producerId)?globalThis.String(e.producerId):"",spatialLayer:hs(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=>ps.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 hs(e){return null!=e}var fs,ms;function gs(e){switch(e){case 0:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED":return fs.TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED;case 1:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS":return fs.TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS;case 2:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE":return fs.TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE;default:return fs.UNRECOGNIZED}}function vs(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"}(fs||(fs={})),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 ys={encode:(e,t=new hi)=>(""!==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 fi?e:new fi(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:_s(e.transportId)?globalThis.String(e.transportId):"",timeout:_s(e.timeout)?globalThis.Number(e.timeout):0,direction:_s(e.direction)?vs(e.direction):0,reason:_s(e.reason)?gs(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 fs.TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED";case fs.TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS";case fs.TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE";case fs.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.reason)),t},create:e=>ys.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 _s(e){return null!=e}var bs;function Es(e){switch(e){case 0:case"MEDIA_EVENT_TYPE_UNSPECIFIED":return bs.MEDIA_EVENT_TYPE_UNSPECIFIED;case 1:case"MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT":return bs.MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT;case 2:case"MEDIA_EVENT_TYPE_PRODUCER_CREATED":return bs.MEDIA_EVENT_TYPE_PRODUCER_CREATED;case 3:case"MEDIA_EVENT_TYPE_PRODUCER_PAUSED":return bs.MEDIA_EVENT_TYPE_PRODUCER_PAUSED;case 4:case"MEDIA_EVENT_TYPE_PRODUCER_RESUMED":return bs.MEDIA_EVENT_TYPE_PRODUCER_RESUMED;case 5:case"MEDIA_EVENT_TYPE_PRODUCER_CLOSED":return bs.MEDIA_EVENT_TYPE_PRODUCER_CLOSED;case 6:case"MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED":return bs.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED;case 7:case"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED":return bs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED;case 8:case"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED":return bs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED;case 9:case"MEDIA_EVENT_TYPE_CONSUMER_CLOSED":return bs.MEDIA_EVENT_TYPE_CONSUMER_CLOSED;case 10:case"MEDIA_EVENT_TYPE_CONSUMER_PAUSED":return bs.MEDIA_EVENT_TYPE_CONSUMER_PAUSED;case 11:case"MEDIA_EVENT_TYPE_CONSUMER_RESUMED":return bs.MEDIA_EVENT_TYPE_CONSUMER_RESUMED;case 12:case"MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED":return bs.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED;default:return bs.UNRECOGNIZED}}function ws(e){switch(e){case bs.MEDIA_EVENT_TYPE_UNSPECIFIED:return"MEDIA_EVENT_TYPE_UNSPECIFIED";case bs.MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT:return"MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT";case bs.MEDIA_EVENT_TYPE_PRODUCER_CREATED:return"MEDIA_EVENT_TYPE_PRODUCER_CREATED";case bs.MEDIA_EVENT_TYPE_PRODUCER_PAUSED:return"MEDIA_EVENT_TYPE_PRODUCER_PAUSED";case bs.MEDIA_EVENT_TYPE_PRODUCER_RESUMED:return"MEDIA_EVENT_TYPE_PRODUCER_RESUMED";case bs.MEDIA_EVENT_TYPE_PRODUCER_CLOSED:return"MEDIA_EVENT_TYPE_PRODUCER_CLOSED";case bs.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED:return"MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED";case bs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED:return"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED";case bs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED:return"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED";case bs.MEDIA_EVENT_TYPE_CONSUMER_CLOSED:return"MEDIA_EVENT_TYPE_CONSUMER_CLOSED";case bs.MEDIA_EVENT_TYPE_CONSUMER_PAUSED:return"MEDIA_EVENT_TYPE_CONSUMER_PAUSED";case bs.MEDIA_EVENT_TYPE_CONSUMER_RESUMED:return"MEDIA_EVENT_TYPE_CONSUMER_RESUMED";case bs.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED:return"MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED";case bs.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"}(bs||(bs={}));const Ss={encode:(e,t=new hi)=>(0!==e.eventType&&t.uint32(8).int32(e.eventType),void 0!==e.producer&&qi.encode(e.producer,t.uint32(18).fork()).join(),void 0!==e.consumer&&us.encode(e.consumer,t.uint32(26).fork()).join(),void 0!==e.producerSpatialLayerRequest&&ps.encode(e.producerSpatialLayerRequest,t.uint32(34).fork()).join(),void 0!==e.transportConnectionTimeout&&ys.encode(e.transportConnectionTimeout,t.uint32(42).fork()).join(),t),decode(e,t){const r=e instanceof fi?e:new fi(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=qi.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.consumer=us.decode(r,r.uint32());continue;case 4:if(34!==e)break;i.producerSpatialLayerRequest=ps.decode(r,r.uint32());continue;case 5:if(42!==e)break;i.transportConnectionTimeout=ys.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({eventType:Cs(e.eventType)?Es(e.eventType):0,producer:Cs(e.producer)?qi.fromJSON(e.producer):void 0,consumer:Cs(e.consumer)?us.fromJSON(e.consumer):void 0,producerSpatialLayerRequest:Cs(e.producerSpatialLayerRequest)?ps.fromJSON(e.producerSpatialLayerRequest):void 0,transportConnectionTimeout:Cs(e.transportConnectionTimeout)?ys.fromJSON(e.transportConnectionTimeout):void 0}),toJSON(e){const t={};return 0!==e.eventType&&(t.eventType=ws(e.eventType)),void 0!==e.producer&&(t.producer=qi.toJSON(e.producer)),void 0!==e.consumer&&(t.consumer=us.toJSON(e.consumer)),void 0!==e.producerSpatialLayerRequest&&(t.producerSpatialLayerRequest=ps.toJSON(e.producerSpatialLayerRequest)),void 0!==e.transportConnectionTimeout&&(t.transportConnectionTimeout=ys.toJSON(e.transportConnectionTimeout)),t},create:e=>Ss.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?qi.fromPartial(e.producer):void 0,r.consumer=void 0!==e.consumer&&null!==e.consumer?us.fromPartial(e.consumer):void 0,r.producerSpatialLayerRequest=void 0!==e.producerSpatialLayerRequest&&null!==e.producerSpatialLayerRequest?ps.fromPartial(e.producerSpatialLayerRequest):void 0,r.transportConnectionTimeout=void 0!==e.transportConnectionTimeout&&null!==e.transportConnectionTimeout?ys.fromPartial(e.transportConnectionTimeout):void 0,r}};function Cs(e){return null!=e}const Ps={encode:(e,t=new hi)=>(0!==e.id&&t.uint32(8).int32(e.id),void 0!==e.channelEvent&&cs.encode(e.channelEvent,t.uint32(18).fork()).join(),void 0!==e.mediaEvent&&Ss.encode(e.mediaEvent,t.uint32(26).fork()).join(),t),decode(e,t){const r=e instanceof fi?e:new fi(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=cs.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.mediaEvent=Ss.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({id:Ts(e.id)?globalThis.Number(e.id):0,channelEvent:Ts(e.channelEvent)?cs.fromJSON(e.channelEvent):void 0,mediaEvent:Ts(e.mediaEvent)?Ss.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=cs.toJSON(e.channelEvent)),void 0!==e.mediaEvent&&(t.mediaEvent=Ss.toJSON(e.mediaEvent)),t},create:e=>Ps.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?cs.fromPartial(e.channelEvent):void 0,r.mediaEvent=void 0!==e.mediaEvent&&null!==e.mediaEvent?Ss.fromPartial(e.mediaEvent):void 0,r}};function Ts(e){return null!=e}var ks,Rs,Is,Ds,As,Os,Ns,Ms;let Ls=class{constructor(e){ks.set(this,[]),Rs.set(this,!1),Is.set(this,!1),Ds.set(this,void 0),As.set(this,void 0),Os.set(this,new Map),Ns.set(this,void 0),Ms.set(this,new Set),d(this,Ns,e("EventsQueue"),"f")}setMediaEventHandler(e){d(this,Ds,e,"f"),c(this,Ns,"f").info("Media event handler set",{case:"EventsQueue"})}setChannelEventHandler(e){d(this,As,e,"f"),c(this,Ns,"f").info("Channel event handler set",{case:"EventsQueue"})}subscribe(e){d(this,Ms,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=Ps.decode(n);i.id&&(c(this,Ms,"f").has(i.id)&&c(this,Ns,"f").warn("Received duplicate message",{case:"EventsQueue",lastReceivedMsgId:t,currentReceivedMsgId:i.id}),i.id>t+1&&c(this,Ns,"f").warn("Received out of order message",{case:"EventsQueue",lastReceivedMsgId:t,currentReceivedMsgId:i.id})),c(this,Ms,"f").add(i.id),t=i.id,this.push(i)}catch(e){c(this,Ns,"f").error("Failed to parse channel message",{error:pr(e),case:"EventsQueue"})}},n=()=>{e.removeListener("message",r),e.removeListener("close",n)};e.on("close",n),e.on("message",r),c(this,Ns,"f").info("Subscribed to data channel",{case:"EventsQueue"})}push(e){c(this,ks,"f").push(e),this.process()}process(){return a(this,void 0,void 0,(function*(){if(!c(this,Rs,"f")&&!c(this,Is,"f")){for(d(this,Is,!0,"f");!c(this,Rs,"f")&&c(this,ks,"f").length>0;){const e=c(this,ks,"f").shift();if(e)try{if(e.channelEvent&&c(this,As,"f")){c(this,Ns,"f").debug("Handle channel event",{case:"EventsQueue",id:e.id,type:as(e.channelEvent.eventType),event:e.channelEvent}),yield c(this,As,"f").call(this,e.channelEvent);continue}if(e.mediaEvent&&c(this,Ds,"f")){c(this,Ns,"f").debug("Handle media event",{case:"EventsQueue",id:e.id,type:ws(e.mediaEvent.eventType),event:e.mediaEvent}),yield c(this,Ds,"f").call(this,e.mediaEvent);continue}c(this,Ns,"f").warn("Received unknown message",{message:e,case:"EventsQueue"})}catch(t){c(this,Ns,"f").error("Failed to handle event",{case:"EventsQueue",id:e.id,error:pr(t)})}}d(this,Is,!1,"f"),!c(this,Rs,"f")&&c(this,ks,"f").length>0&&queueMicrotask((()=>{this.process()}))}}))}processMessageChunk(e){const t=new Uint8Array(e);if(t.length<12)return void c(this,Ns,"f").warn("Chunk too small",{case:"EventsQueue",bytesLength:t.length});const{msgId:r,index:n,total:i}=this.parseMessageChunkHeader(t),s=t.slice(12);c(this,Os,"f").has(r)||c(this,Os,"f").set(r,{msgId:r,total:i,received:[]});const o=c(this,Os,"f").get(r);if(o)return o.received[n]=s,o.msgId=r,o;c(this,Ns,"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 c(this,Os,"f").delete(e.msgId),t}pause(){d(this,Rs,!0,"f")}size(){return c(this,ks,"f").length}resume(){d(this,Rs,!1,"f"),this.process()}isMessageReceived(e){return c(this,Ms,"f").has(e)}};ks=new WeakMap,Rs=new WeakMap,Is=new WeakMap,Ds=new WeakMap,As=new WeakMap,Os=new WeakMap,Ns=new WeakMap,Ms=new WeakMap,Ls=i([at(),s(0,dt(Hn.LoggerFactory)),o("design:paramtypes",[Function])],Ls);var xs=Ls;function Fs(e){return{id:e.id,appId:e.appId,role:e.role,groups:e.groups,producePermissions:e.producePermissions}}let js=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)}};js=i([at()],js);class Us extends Dn{constructor(e,t,r){super(e,null!=t?t:"something_went_wrong",r)}}const Bs=Object.create(null);Bs.open="0",Bs.close="1",Bs.ping="2",Bs.pong="3",Bs.message="4",Bs.upgrade="5",Bs.noop="6";const Vs=Object.create(null);Object.keys(Bs).forEach((e=>{Vs[Bs[e]]=e}));const Ws={type:"error",data:"parser error"},Hs="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),qs="function"==typeof ArrayBuffer,zs=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Gs=({type:e,data:t},r,n)=>Hs&&t instanceof Blob?r?n(t):Ys(t,n):qs&&(t instanceof ArrayBuffer||zs(t))?r?n(t):Ys(new Blob([t]),n):n(Bs[e]+(t||"")),Ys=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function $s(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Js;const Ks="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Qs="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<Ks.length;e++)Qs[Ks.charCodeAt(e)]=e;const Zs="function"==typeof ArrayBuffer,Xs=(e,t)=>{if("string"!=typeof e)return{type:"message",data:to(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:eo(e.substring(1),t)};return Vs[r]?e.length>1?{type:Vs[r],data:e.substring(1)}:{type:Vs[r]}:Ws},eo=(e,t)=>{if(Zs){const r=(e=>{let t,r,n,i,s,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const d=new ArrayBuffer(o),u=new Uint8Array(d);for(t=0;t<a;t+=4)r=Qs[e.charCodeAt(t)],n=Qs[e.charCodeAt(t+1)],i=Qs[e.charCodeAt(t+2)],s=Qs[e.charCodeAt(t+3)],u[c++]=r<<2|n>>4,u[c++]=(15&n)<<4|i>>2,u[c++]=(3&i)<<6|63&s;return d})(e);return to(r,t)}return{base64:!0,data:e}},to=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,ro=String.fromCharCode(30);function no(){return new TransformStream({transform(e,t){!function(e,t){Hs&&e.data instanceof Blob?e.data.arrayBuffer().then($s).then(t):qs&&(e.data instanceof ArrayBuffer||zs(e.data))?t($s(e.data)):Gs(e,!1,(e=>{Js||(Js=new TextEncoder),t(Js.encode(e))}))}(e,(r=>{const n=r.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,n)}else{i=new Uint8Array(9);const e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(n))}e.data&&"string"!=typeof e.data&&(i[0]|=128),t.enqueue(i),t.enqueue(r)}))}})}let io;function so(e){return e.reduce(((e,t)=>e+t.length),0)}function oo(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let n=0;for(let i=0;i<t;i++)r[i]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),r}function ao(e){if(e)return function(e){for(var t in ao.prototype)e[t]=ao.prototype[t];return e}(e)}ao.prototype.on=ao.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},ao.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},ao.prototype.off=ao.prototype.removeListener=ao.prototype.removeAllListeners=ao.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<n.length;i++)if((r=n[i])===t||r.fn===t){n.splice(i,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},ao.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){n=0;for(var i=(r=r.slice(0)).length;n<i;++n)r[n].apply(this,t)}return this},ao.prototype.emitReserved=ao.prototype.emit,ao.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},ao.prototype.hasListeners=function(e){return!!this.listeners(e).length};const co="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function uo(e,...t){return t.reduce(((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t)),{})}const lo=co.setTimeout,po=co.clearTimeout;function ho(e,t){t.useNativeTimers?(e.setTimeoutFn=lo.bind(co),e.clearTimeoutFn=po.bind(co)):(e.setTimeoutFn=co.setTimeout.bind(co),e.clearTimeoutFn=co.clearTimeout.bind(co))}class fo extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class mo extends ao{constructor(e){super(),this.writable=!1,ho(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new fo(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=Xs(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}const go="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),vo={};let yo,_o=0,bo=0;function Eo(e){let t="";do{t=go[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function wo(){const e=Eo(+new Date);return e!==yo?(_o=0,yo=e):e+"."+Eo(_o++)}for(;bo<64;bo++)vo[go[bo]]=bo;let So=!1;try{So="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}const Co=So;function Po(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Co))return new XMLHttpRequest}catch(e){}if(!t)try{return new(co[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function To(){}const ko=null!=new Po({xdomain:!1}).responseType;class Ro extends ao{constructor(e,t){super(),ho(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var e;const t=uo(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const r=this.xhr=new Po(t);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{r.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var e;3===r.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(r)),4===r.readyState&&(200===r.status||1223===r.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof r.status?r.status:0)}),0))},r.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=Ro.requestsCount++,Ro.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=To,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete Ro.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(Ro.requestsCount=0,Ro.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Io);else if("function"==typeof addEventListener){addEventListener("onpagehide"in co?"pagehide":"unload",Io,!1)}function Io(){for(let e in Ro.requests)Ro.requests.hasOwnProperty(e)&&Ro.requests[e].abort()}const Do="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Ao=co.WebSocket||co.MozWebSocket,Oo="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const No={websocket:class extends mo{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,r=Oo?{}:uo(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=Oo?new Ao(e,t,r):t?new Ao(e,t):new Ao(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],n=t===e.length-1;Gs(r,this.supportsBinary,(e=>{try{this.ws.send(e)}catch(e){}n&&Do((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=wo()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!Ao}},webtransport:class extends mo{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then((()=>{this.onClose()})).catch((e=>{this.onError("webtransport error",e)})),this.transport.ready.then((()=>{this.transport.createBidirectionalStream().then((e=>{const t=function(e,t){io||(io=new TextDecoder);const r=[];let n=0,i=-1,s=!1;return new TransformStream({transform(o,a){for(r.push(o);;){if(0===n){if(so(r)<1)break;const e=oo(r,1);s=128==(128&e[0]),i=127&e[0],n=i<126?3:126===i?1:2}else if(1===n){if(so(r)<2)break;const e=oo(r,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),n=3}else if(2===n){if(so(r)<8)break;const e=oo(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){a.enqueue(Ws);break}i=s*Math.pow(2,32)+t.getUint32(4),n=3}else{if(so(r)<i)break;const e=oo(r,i);a.enqueue(Xs(s?e:io.decode(e),t)),n=0}if(0===i||i>e){a.enqueue(Ws);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),n=no();n.readable.pipeTo(e.writable),this.writer=n.writable.getWriter();const i=()=>{r.read().then((({done:e,value:t})=>{e||(this.onPacket(t),i())})).catch((e=>{}))};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then((()=>this.onOpen()))}))})))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],n=t===e.length-1;this.writer.write(r).then((()=>{n&&Do((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends mo{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}const t=e&&e.forceBase64;this.supportsBinary=ko&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",(function(){--e||t()}))),this.writable||(e++,this.once("drain",(function(){--e||t()})))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(ro),n=[];for(let e=0;e<r.length;e++){const i=Xs(r[e],t);if(n.push(i),"error"===i.type)break}return n})(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,n=new Array(r);let i=0;e.forEach(((e,s)=>{Gs(e,!1,(e=>{n[s]=e,++i===r&&t(n.join(ro))}))}))})(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=wo()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Ro(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}},Mo=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Lo=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function xo(e){const t=e,r=e.indexOf("["),n=e.indexOf("]");-1!=r&&-1!=n&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let i=Mo.exec(e||""),s={},o=14;for(;o--;)s[Lo[o]]=i[o]||"";return-1!=r&&-1!=n&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=function(e,t){const r=/\/{2,9}/g,n=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1);"/"==t.slice(-1)&&n.splice(n.length-1,1);return n}(0,s.path),s.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,n){t&&(r[t]=n)})),r}(0,s.query),s}class Fo extends ao{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=xo(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=xo(t.host).host),ho(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let e=0,n=r.length;e<n;e++){let n=r[e].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new No[e](r)}open(){let e;if(this.opts.rememberUpgrade&&Fo.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(e){let t=this.createTransport(e),r=!1;Fo.priorWebsocketSuccess=!1;const n=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",(e=>{if(!r)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Fo.priorWebsocketSuccess="websocket"===t.name,this.transport.pause((()=>{r||"closed"!==this.readyState&&(d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())}))}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}})))};function i(){r||(r=!0,d(),t.close(),t=null)}const s=e=>{const r=new Error("probe error: "+e);r.transport=t.name,i(),this.emitReserved("upgradeError",r)};function o(){s("transport closed")}function a(){s("socket closed")}function c(e){t&&e.name!==t.name&&i()}const d=()=>{t.removeListener("open",n),t.removeListener("error",s),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",n),t.once("error",s),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn((()=>{r||t.open()}),200):t.open()}onOpen(){if(this.readyState="open",Fo.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let r=0;r<this.writeBuffer.length;r++){const n=this.writeBuffer[r].data;if(n&&(e+="string"==typeof(t=n)?function(e){let t=0,r=0;for(let n=0,i=e.length;n<i;n++)t=e.charCodeAt(n),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(n++,r+=4);return r}(t):Math.ceil(1.33*(t.byteLength||t.size))),r>0&&e>this.maxPayload)return this.writeBuffer.slice(0,r);e+=2}var t;return this.writeBuffer}write(e,t,r){return this.sendPacket("message",e,t,r),this}send(e,t,r){return this.sendPacket("message",e,t,r),this}sendPacket(e,t,r,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof r&&(n=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?r():e()})):this.upgrading?r():e()),this}onError(e){Fo.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let r=0;const n=e.length;for(;r<n;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}Fo.protocol=4;const jo="function"==typeof ArrayBuffer,Uo=Object.prototype.toString,Bo="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Uo.call(Blob),Vo="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Uo.call(File);function Wo(e){return jo&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Bo&&e instanceof Blob||Vo&&e instanceof File}function Ho(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Ho(e[t]))return!0;return!1}if(Wo(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Ho(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Ho(e[t]))return!0;return!1}function qo(e){const t=[],r=e.data,n=e;return n.data=zo(r,t),n.attachments=t.length,{packet:n,buffers:t}}function zo(e,t){if(!e)return e;if(Wo(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=zo(e[n],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=zo(e[n],t));return r}return e}function Go(e,t){return e.data=Yo(e.data,t),delete e.attachments,e}function Yo(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=Yo(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Yo(e[r],t));return e}const $o=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Jo;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(Jo||(Jo={}));function Ko(e){return"[object Object]"===Object.prototype.toString.call(e)}class Qo extends ao{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===Jo.BINARY_EVENT;r||t.type===Jo.BINARY_ACK?(t.type=r?Jo.EVENT:Jo.ACK,this.reconstructor=new Zo(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Wo(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===Jo[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Jo.BINARY_EVENT||r.type===Jo.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(n,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(i)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(n,t)}else r.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!Qo.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case Jo.CONNECT:return Ko(t);case Jo.DISCONNECT:return void 0===t;case Jo.CONNECT_ERROR:return"string"==typeof t||Ko(t);case Jo.EVENT:case Jo.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===$o.indexOf(t[0]));case Jo.ACK:case Jo.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Zo{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Go(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var Xo=Object.freeze({__proto__:null,protocol:5,get PacketType(){return Jo},Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Jo.EVENT&&e.type!==Jo.ACK||!Ho(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Jo.EVENT?Jo.BINARY_EVENT:Jo.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Jo.BINARY_EVENT&&e.type!==Jo.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=qo(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}},Decoder:Qo});function ea(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const ta=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ra extends ao{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[ea(e,"open",this.onopen.bind(this)),ea(e,"packet",this.onpacket.bind(this)),ea(e,"error",this.onerror.bind(this)),ea(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(ta.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const r={type:Jo.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),r.id=e}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!n||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var r;const n=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===n)return void(this.acks[e]=t);const i=this.io.setTimeoutFn((()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))}),n);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,[null,...e])}}emitWithAck(e,...t){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((n,i)=>{t.push(((e,t)=>r?e?i(e):n(t):n(e))),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...n)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...n)),r.pending=!1,this._drainQueue()})),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Jo.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Jo.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Jo.EVENT:case Jo.BINARY_EVENT:this.onevent(e);break;case Jo.ACK:case Jo.BINARY_ACK:this.onack(e);break;case Jo.DISCONNECT:this.ondisconnect();break;case Jo.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...n){r||(r=!0,t.packet({type:Jo.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Jo.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function na(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}na.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-r:e+r}return 0|Math.min(e,this.max)},na.prototype.reset=function(){this.attempts=0},na.prototype.setMin=function(e){this.ms=e},na.prototype.setMax=function(e){this.max=e},na.prototype.setJitter=function(e){this.jitter=e};class ia extends ao{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,ho(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new na({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const n=t.parser||Xo;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Fo(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const n=ea(t,"open",(function(){r.onopen(),e&&e()})),i=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=ea(t,"error",i);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn((()=>{n(),i(new Error("timeout")),t.close()}),e);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}return this.subs.push(n),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(ea(e,"ping",this.onping.bind(this)),ea(e,"data",this.ondata.bind(this)),ea(e,"error",this.onerror.bind(this)),ea(e,"close",this.onclose.bind(this)),ea(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){Do((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new ra(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn((()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()})))}),t);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const sa={};function oa(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let n=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),n=xo(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(r&&r.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=r.source,i=r.id,s=r.path,o=sa[i]&&s in sa[i].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new ia(n,t):(sa[i]||(sa[i]=new ia(n,t)),a=sa[i]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}var aa,ca;Object.assign(oa,{Manager:ia,Socket:ra,io:oa,connect:oa});let da=class{constructor(e){this.reconnectingAttempt=0,this.isConnected=!1,this._observer=new Tt,aa.set(this,void 0),this.knownDisconnectReasonsCodes={"io server disconnect":"server.disconnect","io client disconnect":"client.disconnect","ping timeout":"ping.timeout","transport close":"transport.close","transport error":"transport.error"},ca.set(this,!1),d(this,aa,e("Socket"),"f")}get observer(){return this._observer}get id(){var e;return null===(e=this.connection)||void 0===e?void 0:e.id}connect(e,t){const r=oa(e,{multiplex:!0,randomizationFactor:.2,reconnectionDelay:1e3,reconnection:!0,transports:["polling","websocket"],upgrade:!0,rememberUpgrade:!1,auth:{token:t,apiVersion:7}});this.connection=r,this.serverUrl=e,r.on(Yn.Connect,(()=>{const e=this.reconnectingAttempt?Yn.Reconnected:Yn.Connected;this.isConnected=!0,this.setReconnectingAttempt(0),c(this,aa,"f").debug(`connection.on('${Yn.Connect}')`,{connectionId:r.id,recovered:r.recovered}),this.observer.safeEmit(Yn.State,{state:e})})),r.on(Yn.ConnectError,(e=>{this.connectionError=e,c(this,aa,"f").error(`connection.on('${Yn.ConnectError}')`,{error:pr(e)}),this.observer.safeEmit(Yn.State,{state:Yn.Error,error:e}),this.reconnectingAttempt>100&&(r.disconnect(),this.observer.safeEmit(Yn.State,{state:Yn.Disconnected,code:"server.disconnect"}))})),r.on(Yn.ReconnectError,(e=>{c(this,aa,"f").error(`connection.on('${Yn.ReconnectError}')`,{case:"SocketReconnect",error:pr(e)})})),r.on(Yn.Disconnect,(e=>{this.isConnected=!1,this.setReconnectingAttempt(0),this.disconnectReason=e,c(this,aa,"f").info(`connection.on('${Yn.Disconnect}')`,{reason:e});const t=this.getDisconnectReasonCode(e);"server.disconnect"===t&&r.disconnect(),this.observer.safeEmit(Yn.State,{state:Yn.Disconnected,code:t})})),r.io.on(Yn.ReconnectAttempt,(e=>{this.setReconnectingAttempt(e),c(this,aa,"f").info(`connection.on('${Yn.ReconnectAttempt}')`,{attempt:e}),this.observer.safeEmit(Yn.State,{state:Yn.Reconnecting})})),r.io.on(Yn.Reconnect,(()=>{c(this,aa,"f").debug(`connection.on('${Yn.Reconnect}')`,{connectionId:r.id}),this.observer.safeEmit(Yn.State,{state:Yn.Reconnect})}))}disconnect(){this.connection&&(this.connection.offAny(),this.connection.volatile.offAny(),this.connection.disconnect(),this.connection.io.removeAllListeners(),this.setReconnectingAttempt(0))}request(e){return a(this,arguments,void 0,(function*(e,t={}){return yield new Promise(((r,n)=>{this.connection?this.connection.timeout(8e3).emit(e,t,((t,i)=>{if(t){const r=kn.includes(e);return"operation has timed out"===(null==t?void 0:t.message)&&!c(this,ca,"f")&&r&&(d(this,ca,!0,"f"),this.observer.safeEmit(Yn.State,{state:Yn.BufferingStart})),void n(t)}i&&i.error?("Need join to channel first"===i.error&&this.observer.safeEmit(Yn.State,{code:Yn.NeedToJoinFirst}),n(new Us(i.error,i.errorCode,Object.assign({},i)))):(c(this,ca,"f")&&(d(this,ca,!1,"f"),this.observer.safeEmit(Yn.State,{state:Yn.BufferingEnd})),r(i))})):n(new Error("Socket request: Socket connection is not initialized"))}))}))}getServerUrl(){return this.serverUrl}getDisconnectReasonCode(e){const t=String(e).toLowerCase();return this.knownDisconnectReasonsCodes[t]||t}setReconnectingAttempt(e){this.reconnectingAttempt=e}};aa=new WeakMap,ca=new WeakMap,da=i([at(),s(0,dt(Hn.LoggerFactory)),o("design:paramtypes",[Function])],da);var ua,la=da;class pa extends Dn{constructor(e,t){super(e,null!=t?t:"invalid_payload")}}!function(e){e.DominantSpeaker="dominant-speaker",e.PeersVolumes="peers-volumes",e.Silence="silence"}(ua||(ua={}));let ha=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()}};ha=i([at()],ha);var fa,ma,ga,va,ya,_a=ha;let ba=ya=class{constructor(e,t,r){this.peersStorage=e,this.clientEventEmitter=t,fa.set(this,void 0),ma.set(this,void 0),ga.set(this,void 0),va.set(this,void 0),d(this,fa,r("ChannelAudioObserverEventHandler"),"f"),this.watchPeersLeave()}handle(e){try{const t=JSON.parse(e);switch(ya.validateEventPayload(t),t.event){case ua.DominantSpeaker:this.handleDominantSpeaker(t);break;case ua.PeersVolumes:this.handlePeerVolumes(t);break;case ua.Silence:this.handleSilence()}}catch(t){c(this,fa,"f").warn("Failed to handle audio observer event",{error:pr(t),eventData:e})}}handleDominantSpeaker(e){const{peerId:t}=e.data,r=this.peersStorage.get(t);d(this,ga,r,"f"),d(this,va,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&&!c(this,ga,"f")&&s.id===(null===(t=c(this,va,"f"))||void 0===t?void 0:t.id)&&(d(this,ga,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))),d(this,ga,void 0,"f"),this.setActiveSpeaker(void 0)}watchPeersLeave(){this.clientEventEmitter.on(Tr,(e=>{var t;e===(null===(t=c(this,ga,"f"))||void 0===t?void 0:t.id)&&this.setActiveSpeaker(void 0)}))}setActiveSpeaker(e){c(this,ma,"f")!==(null==e?void 0:e.id)&&(d(this,ma,null==e?void 0:e.id,"f"),this.clientEventEmitter.safeEmit(Lr,{peer:e}))}static validateEventPayload(e){switch(e.event){case ua.Silence:break;case ua.DominantSpeaker:{e.data||ya.throwInvalidPayload();const{peerId:t,producerId:r,trackLabel:n}=e.data;"string"==typeof t&&"string"==typeof r&&n===zn.Microphone||ya.throwInvalidPayload();break}case ua.PeersVolumes:Array.isArray(e.volumes)||ya.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===zn.Microphone||ya.throwInvalidPayload()}));break;default:ya.throwInvalidPayload()}}static throwInvalidPayload(){throw new pa("Invalid channel audio observer event handler payload")}};fa=new WeakMap,ma=new WeakMap,ga=new WeakMap,va=new WeakMap,ba=ya=i([at(),s(0,dt(Hn.PeersStorage)),s(1,dt(Hn.ClientEventEmitter)),s(2,dt(Hn.LoggerFactory)),o("design:paramtypes",[_a,Tt,Function])],ba);var Ea,wa,Sa,Ca=ba;let Pa=class{constructor(e,t,r,n,i){this.state=e,this.myPeer=r,this.socket=n,this.channelAudioObserverEventHandler=i,Ea.set(this,void 0),wa.set(this,void 0),Sa.set(this,void 0),d(this,Ea,t("DataChannels"),"f")}get channelMessagesDataConsumer(){return c(this,Sa,"f")}createAudioObserver(e){return a(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();d(this,wa,yield this.createDataConsumer({producerId:t,appId:this.state.appId,channelId:this.state.channelId,transport:e}),"f");const n=this.channelAudioObserverEventHandler.handle.bind(this.channelAudioObserverEventHandler),i=()=>{var e,t;null===(e=c(this,wa,"f"))||void 0===e||e.removeListener("message",n),null===(t=c(this,wa,"f"))||void 0===t||t.removeListener("close",i)};c(this,wa,"f").on("close",i),c(this,wa,"f").on("message",n),c(this,Ea,"f").debug("Successfully create audio observer",r)}catch(e){c(this,Ea,"f").error("Failed to create audio observer",Object.assign(Object.assign({},r),{error:pr(e)}))}}))}createChannelMessagesDataConsumer(e){return a(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");d(this,Sa,yield this.createDataConsumer({producerId:t,appId:this.state.appId,channelId:this.state.channelId,ordered:!0,transport:e}),"f"),c(this,Ea,"f").debug("Successfully created channel messages data consumer",Object.assign(Object.assign({},r),{producerId:t}))}catch(e){throw c(this,Ea,"f").error("Failed to create channel messages data consumer",Object.assign(Object.assign({},r),{error:e})),e}}))}closeAudioObserver(){var e;null===(e=c(this,wa,"f"))||void 0===e||e.close()}closeChannelMessagesDataConsumer(){var e;null===(e=c(this,Sa,"f"))||void 0===e||e.close()}createDataProducer(e,t){return a(this,void 0,void 0,(function*(){return yield this.socket.request(Cn,{transportId:e,label:t})}))}createDataConsumer(e){return a(this,arguments,void 0,(function*({producerId:e,appId:t,channelId:r,ordered:n,transport:i}){if(!i)throw c(this,Ea,"f").error("createDataConsumer()",{reason:"missing receive transport"}),new Error("Failed to create consumer");c(this,Ea,"f").debug("createDataConsumer()",{producerId:e});const s=yield this.socket.request(mn,{ordered:n,dataProducerId:e,transportId:i.id,appData:{peerId:this.myPeer.id,producerId:e,appId:t,channelId:r}}),o=yield i.consumeData(s);return c(this,Ea,"f").debug("Data consumer created",{consumerId:o.id}),o}))}getAudioObserverProducer(){return a(this,void 0,void 0,(function*(){return yield this.socket.request(_r)}))}};Ea=new WeakMap,wa=new WeakMap,Sa=new WeakMap,Pa=i([at(),s(0,dt(Hn.CallState)),s(1,dt(Hn.LoggerFactory)),s(2,dt(Hn.MyPeer)),s(3,dt(Hn.SocketIO)),s(4,dt(Hn.ChannelAudioObserverEventHandler)),o("design:paramtypes",[$n,Function,js,la,Ca])],Pa);var Ta,ka,Ra,Ia=Pa;let Da=class{constructor(e,t,r,n,i,s){this.state=e,this.myPeer=t,this.socket=n,this.clientEventEmitter=i,this.dataChannelsManager=s,Ta.set(this,new Map),ka.set(this,void 0),Ra.set(this,void 0),this.peersLoaded=!1,d(this,Ra,r("Network"),"f"),d(this,ka,new Tt,"f"),this.socket.observer.on(Yn.State,(e=>{c(this,ka,"f").safeEmit(Rn,e)}))}get isNetworkActive(){var e,t,r,n,i;return!!(null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&["connected","new"].includes(null!==(r=null===(t=this.receiveTransport)||void 0===t?void 0:t.connectionState)&&void 0!==r?r:"")&&["connected","new"].includes(null!==(i=null===(n=this.sendTransport)||void 0===n?void 0:n.connectionState)&&void 0!==i?i:"")}get observer(){return c(this,ka,"f")}get isSocketConnectionActive(){try{return this.checkSocketConnectionActivity(),!0}catch(e){return c(this,Ra,"f").warn("isSocketConnectionActive()",{error:pr(e)}),!1}}checkSocketConnectionActivity(){var e;if(!this.state.channelId||this.state.isChannelJoining)throw new Error("Connect to the channel first");if(!(null===(e=this.socket.connection)||void 0===e?void 0:e.active))throw new Error("Socket is inactive");if(!this.socket.connection.connected)throw new Error("Socket disconnected")}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.stopRestartIceAttempts(),this.removeEventListeners()}closeRemoteProducer(e){return a(this,void 0,void 0,(function*(){yield this.socket.request(dn,{peerId:this.myPeer.id,producerId:e})}))}closeSendTransport(){var e;this.sendTransport?((null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&this.closeTransport(this.sendTransport),this.sendTransport.close(),this.sendTransport=void 0):c(this,Ra,"f").warn("closeSendTransport()",{message:"No available send transport"})}closeReceiveTransport(){var e;this.receiveTransport?((null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&this.closeTransport(this.receiveTransport),this.receiveTransport.close(),this.receiveTransport=void 0):c(this,Ra,"f").warn("closeReceiveTransport()",{message:"No available receive transport"})}closeConnectionTransport(){return a(this,void 0,void 0,(function*(){var e;this.signalingTransport?(yield this.closePingConsumer(),(null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&this.closeTransport(this.signalingTransport),this.signalingTransport.close(),this.signalingTransport=void 0):c(this,Ra,"f").warn("closeConnectionTransport()",{message:"No available connection transport"})}))}closeTransport(e){try{e.close(),c(this,Ra,"f").debug("closeTransport()",{transportId:e.id,direction:e.direction})}catch(t){c(this,Ra,"f").error("closeTransport()",{error:t,transportId:e.id,direction:e.direction})}}createSendTransport(e){return a(this,void 0,void 0,(function*(){if(this.sendTransport)throw c(this,Ra,"f").warn("createSendTransport()",{message:"Send transport already exists"}),new Dn("Send transport already exists","already_exists");const t=yield this.socket.request(En,{sctpCapabilities:e.sctpCapabilities,localDirection:"send"}),r=e.createSendTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return c(this,Ra,"f").debug("createSendTransport()",{transportId:r.id,direction:r.direction}),this.sendTransport=r,this.subscribeCommonTransportEvents(r),r}))}createRecvTransport(e){return a(this,void 0,void 0,(function*(){if(this.receiveTransport)throw c(this,Ra,"f").warn("createReceiveTransport()",{message:"Receive transport already exists"}),new Dn("Receive transport already exists","already_exists");const t=yield this.socket.request(En,{localDirection:"receive"}),r=e.createRecvTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return c(this,Ra,"f").debug("createReceiveTransport()",{transportId:r.id,direction:r.direction}),this.receiveTransport=r,this.subscribeCommonTransportEvents(r),r}))}createSignalingTransport(e){return a(this,void 0,void 0,(function*(){if(this.signalingTransport)throw c(this,Ra,"f").warn("createConnectionTransport()",{message:"Connection transport already exists"}),new Dn("Connection transport already exists","already_exists");const t=yield this.socket.request(En,{localDirection:"receive",tcpOnly:!0}),r=e.createSendTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return c(this,Ra,"f").debug("createConnectionTransport()",{transportId:r.id,direction:r.direction,tcpOnly:!0}),this.signalingTransport=r,this.subscribeCommonTransportEvents(r),r}))}getIceParameters(e){return a(this,void 0,void 0,(function*(){const t=yield this.socket.request(Tn,{transportId:e.id}),{error:r}=t;if(r)throw new Error(r);const{iceParameters:n}=t;return c(this,Ra,"f").debug("getIceParameters()",{iceParameters:n}),n}))}restartIce(e){return a(this,void 0,void 0,(function*(){try{const t=yield this.getIceParameters(e);yield e.restartIce({iceParameters:t}),c(this,Ra,"f").info("restartIce completed",{iceParameters:t})}catch(e){c(this,Ra,"f").error("restartIce error",{error:e})}}))}createConsumer(e){return a(this,arguments,void 0,(function*({producerId:e,rtpCapabilities:t,appId:r,channelId:n,producerPeerId:i}){var s;const o=this.receiveTransport;if(!o)throw c(this,Ra,"f").error("createConsumer()",{reason:"missing receive transport"}),new Error("Failed to create consumer");let a;c(this,Ra,"f").debug("createConsumer()",{producerId:e});try{a=yield this.socket.request(fn,{producerId:e,transportId:o.id,rtpCapabilities:t,appData:{peerId:this.myPeer.id,appId:r,channelId:n},producerPeerId:i})}catch(o){if(!(o instanceof Us&&(null===(s=o.meta)||void 0===s?void 0:s.existedConsumer)))throw c(this,Ra,"f").error("Failed to get consumer options",{producerId:e,rtpCapabilities:t,appId:r,channelId:n,producerPeerId:i,error:pr(o)}),new Error("Failed to create consumer");a=o.meta.existedConsumer}const d=yield o.consume(a),{producerPaused:u}=a;return u&&d.pause(),c(this,Ra,"f").debug("Consumer created",{consumerId:d.id,label:d.appData.label,isProducerPaused:u}),{consumer:d,isProducerPaused:u}}))}createSignalingConsumer(){return a(this,void 0,void 0,(function*(){var e,t;const r=this.signalingTransport;if(!r)throw c(this,Ra,"f").error("createSignalingConsumer()",{reason:"missing signaling transport"}),new Error("Failed to create data consumer");this.signalingDataProducer=yield r.produceData({label:"heart-beater",protocol:"json"});const n=null===(e=this.signalingDataProducer)||void 0===e?void 0:e.id;if(!n)throw new TypeError("dataProducerId is missing for connectionTransport");try{const e=yield this.socket.request(mn,{ordered:!0,dataProducerId:n,transportId:r.id,appData:{peerId:this.myPeer.id,producerId:n,appId:this.state.appId,channelId:this.state.channelId}});this.signalingConsumerId=e.consumerId}catch(e){c(this,Ra,"f").error("Failed to setup TCP DataChannel for connectionTransport",{transportId:r.id,dataProducerId:null===(t=this.signalingDataProducer)||void 0===t?void 0:t.id,error:pr(e)})}}))}get channelMessagesDataConsumer(){return this.dataChannelsManager.channelMessagesDataConsumer}closePingConsumer(){return a(this,void 0,void 0,(function*(){try{if(!this.signalingConsumerId)return;yield this.closeRemoteConsumer(this.signalingConsumerId)}catch(e){c(this,Ra,"f").debug("closeConsumer()",{track:this,error:pr(e)})}}))}closeRemoteConsumer(e){return a(this,void 0,void 0,(function*(){return yield this.socket.request(gn,{peerId:this.myPeer.id,consumerId:e})}))}resumeRemoteConsumer(e){return a(this,void 0,void 0,(function*(){return yield this.socket.request(yn,{consumerId:e})}))}pauseRemoteProducer(e){return a(this,void 0,void 0,(function*(){return yield this.socket.request(un,{producerId:e})}))}pauseRemoteConsumer(e){return a(this,void 0,void 0,(function*(){return yield this.socket.request(vn,{consumerId:e})}))}updatePeerAppData(e){return a(this,arguments,void 0,(function*({peerId:e,appData:t}){return yield this.socket.request(vr,{peerId:e,appData:t})}))}getTransportsStateInfo(){return a(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}getPreferRelay(){var e;return null!==(e=this.preferRelay)&&void 0!==e&&e}getChannelPeers(e){return a(this,void 0,void 0,(function*(){const t=yield this.socket.request(mr,{role:e});return this.peersLoaded=!0,t}))}createAllDataChannels(){return a(this,void 0,void 0,(function*(){if(!this.receiveTransport)throw new Error("Receive transport is not created");yield Promise.all([this.dataChannelsManager.createAudioObserver(this.receiveTransport),this.dataChannelsManager.createChannelMessagesDataConsumer(this.receiveTransport)])}))}closeAllDataChannels(){this.dataChannelsManager.closeAudioObserver(),this.dataChannelsManager.closeChannelMessagesDataConsumer()}waitForReceiveTransportConnected(){return a(this,void 0,void 0,(function*(){if(!this.receiveTransport)throw new Error("receiveTransport is not initialized");yield this.waitForTransportConnected(this.receiveTransport)}))}triggerChannelStateEvent(e){return a(this,void 0,void 0,(function*(){const{messageId:t}=yield this.socket.request(gr,{peersRole:e});return t}))}waitForChannelMessagesDataConsumerConnected(){return a(this,void 0,void 0,(function*(){if(!this.dataChannelsManager.channelMessagesDataConsumer)throw new Error("channelMessagesDataConsumer is not initialized");yield this.waitForDataConsumerConnected(this.dataChannelsManager.channelMessagesDataConsumer)}))}waitForTransportConnected(e){return a(this,arguments,void 0,(function*(e,t=6e4){"connected"!==e.connectionState&&(yield new Promise(((r,n)=>{const i=setTimeout((()=>{s(),n(new Error("Timed out waiting for receiveTransport to connect"))}),t),s=()=>{clearTimeout(i),e.off("connectionstatechange",o)},o=()=>{"connected"===e.connectionState?(s(),r()):"failed"!==e.connectionState&&"closed"!==e.connectionState||(s(),n(new Error(`receiveTransport connection failed: ${e.connectionState}`)))};e.on("connectionstatechange",o)})))}))}waitForDataConsumerConnected(e){return a(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 a(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 c(this,Ra,"f").warn("getParsedTransportStats()",{error:e})}else c(this,Ra,"f").debug("getParsedTransportStats()",{message:"Transport is missing"})}))}logTransportDetails(e){return a(this,void 0,void 0,(function*(){var t,r,n,i;let s;try{s=yield e.getStats()}catch(t){return void c(this,Ra,"f").error("Failed to log detailed WebRTC transport stats",{error:pr(t),transportId:e.id,reason:"failed to parse getStats"})}try{const o=[...s],[,a]=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==a?void 0:a.iceRole,iceState:null==a?void 0:a.iceState,dtlsRole:null==a?void 0:a.dtlsRole,dtlsState:null==a?void 0:a.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)),c(this,Ra,"f").info("Detailed WebRTC transport stats",p)}catch(t){c(this,Ra,"f").error("Failed to log detailed WebRTC transport stats",{error:pr(t),transportId:e.id,reason:"-"})}}))}stopRestartIceAttempts(){Array.from(c(this,Ta,"f").values()).forEach((e=>clearInterval(e)))}subscribeCommonTransportEvents(e){e.on("connect",((t,r,n)=>a(this,[t,r,n],void 0,(function*({dtlsParameters:t},r,n){try{yield this.socket.request(wn,{transportId:e.id,dtlsParameters:t}),r(),c(this,Ra,"f").debug(`${e.direction}Transport.connect()`,{transportId:e.id,dtlsRole:t.role}),setTimeout((()=>a(this,void 0,void 0,(function*(){return yield this.logTransportDetails(e)}))),2e3),setTimeout((()=>a(this,void 0,void 0,(function*(){return yield this.checkTransportState(e)}))),15e3)}catch(t){c(this,Ra,"f").error(`${e.direction}Transport.on('connect')`,{error:t}),n(t)}})))),e.on("produce",((t,r,n)=>a(this,void 0,void 0,(function*(){try{const{id:n}=yield this.socket.request(Sn,{transportId:e.id,kind:t.kind,rtpParameters:t.rtpParameters,appData:t.appData});r({id:n}),c(this,Ra,"f").debug(`${e.direction}Transport.produce()`,{producerId:n,transportId:e.id,kind:t.kind})}catch(r){c(this,Ra,"f").error(`${e.direction}Transport.produce()`,{error:pr(r),transportId:e.id,kind:t.kind}),n(r)}})))),e.on("producedata",((t,r,n)=>a(this,void 0,void 0,(function*(){try{const{id:n}=yield this.socket.request(Cn,{transportId:e.id,label:t.label,sctpParameters:t.sctpStreamParameters,appData:t.appData});r({id:n}),c(this,Ra,"f").debug(`${e.direction}Transport.produceData()`,{producerId:n,transportId:e.id,label:t.label})}catch(r){c(this,Ra,"f").error(`${e.direction}Transport.produceData()`,{error:pr(r),transportId:e.id,label:t.label}),n(r)}})))),e.on("connectionstatechange",(t=>{if(c(this,Ra,"f").info(`${e.direction}Transport.state`,{state:t}),["closed","connected"].includes(t))return c(this,ka,"f").safeEmit(In,{state:t,direction:e.direction}),c(this,Ta,"f").has(e.id)&&(c(this,Ra,"f").debug("Stop receiveTransport.restartIce() retries",{recvTransportId:e.id}),clearInterval(c(this,Ta,"f").get(e.id)),c(this,Ta,"f").delete(e.id),"connected"===t&&c(this,ka,"f").safeEmit(In,{state:"reconnected",direction:e.direction})),void("connected"===t&&setTimeout((()=>{this.logTransportDetails(e).catch((e=>{c(this,Ra,"f").debug("Failed to log transport details",{error:pr(e)})}))}),1500));if(c(this,ka,"f").safeEmit(In,{state:t,direction:e.direction}),["disconnected","failed"].includes(t)){if(c(this,Ta,"f").has(e.id))return;"failed"===t&&(c(this,Ra,"f").debug(`${e.id} transport.restartIce()`,{transportId:e.id,direction:e.direction}),this.restartIce(e).catch((t=>{c(this,Ra,"f").debug("Failed to execute restartIce",{error:pr(t),transportId:e.id,direction:e.direction})}))),c(this,Ta,"f").set(e.id,setInterval((()=>{this.restartIce(e).catch((t=>{c(this,Ra,"f").debug("Failed to execute restartIce",{error:pr(t),transportId:e.id,direction:e.direction})})),c(this,Ra,"f").debug(`${e.id} transport.restartIce() attempt`,{recvTransportId:e.id,transportId:e.id,direction:e.direction})}),5e3))}})),e.on("icegatheringstatechange",(t=>{c(this,Ra,"f").info("icegatheringstatechange",{state:t,transportId:e.id,transportDirection:e.direction})}))}checkTransportState(e){return a(this,void 0,void 0,(function*(){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(Or,{direction:r,reason:"ice"}),void c(this,Ra,"f").warn(Pn,{reason:"ice",transportId:e.id,direction:r});"connected"!==t.dtlsState&&(this.clientEventEmitter.emit(Or,{direction:r,reason:"dtls"}),c(this,Ra,"f").warn(Pn,{reason:"dtls",transportId:e.id,direction:r}))}catch(t){c(this,Ra,"f").error("checkTransportState()",{error:pr(t),transportId:e.id,direction:e.direction})}}))}};Ta=new WeakMap,ka=new WeakMap,Ra=new WeakMap,Da=i([at(),s(0,dt(Hn.CallState)),s(1,dt(Hn.MyPeer)),s(2,dt(Hn.LoggerFactory)),s(3,dt(Hn.SocketIO)),s(4,dt(Hn.ClientEventEmitter)),s(5,dt(Hn.DataChannelsManager)),o("design:paramtypes",[$n,js,Function,la,Tt,Ia])],Da);var Aa=Da;let Oa=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 a(this,void 0,void 0,(function*(){const t=this.get(e);t&&(yield t.reset(),this.delete(e),this.clientEventEmitter.safeEmit(Tr,e))}))}all(){return this.peersStorage.all()}hosts(){return this.peersStorage.hosts()}audience(){return this.peersStorage.audience()}reset(){return a(this,void 0,void 0,(function*(){yield Promise.all(this.peersStorage.all().map((e=>a(this,void 0,void 0,(function*(){return yield e.reset()}))))),this.peersStorage.clear()}))}load(e){return a(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(Pr,n),n}isModerator(e){if(void 0===e)return!1;const t=this.get(e);return!!t&&t.isModerator}};function Na(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 Ma(e,t,r,n){var i=Na(Na(Na(e,r),function(e){return Object.prototype.toString.call(e)}(t)),typeof t);if(null===t)return Na(i,"null");if(void 0===t)return Na(i,"undefined");if("object"==typeof t||"function"==typeof t){if(-1!==n.indexOf(t))return Na(i,"[Circular]"+r);n.push(t);var s=function(e,t,r){return Object.keys(t).sort().reduce((function(e,n){return Ma(e,t[n],n,r)}),e)}(i,t,n);if(!("valueOf"in t)||"function"!=typeof t.valueOf)return s;try{return Na(s,String(t.valueOf()))}catch(e){return Na(s,"[valueOf exception]"+(e.stack||e.message))}}return Na(i,t.toString())}Oa=i([at(),s(0,dt(Hn.MyPeer)),s(1,dt(Hn.Network)),s(2,dt(Hn.PeerFactory)),s(3,dt(Hn.ClientEventEmitter)),s(4,dt(Hn.PeersStorage)),o("design:paramtypes",[js,Aa,Function,Tt,_a])],Oa);var La=function(e){return function(e,t){for(;e.length<t;)e="0"+e;return e}(Ma(0,e,"",[]).toString(16),8)};class xa{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 Fa{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 xa({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 ja,Ua,Ba,Va,Wa,Ha,qa;!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"}(ja||(ja={}));let za=class{constructor(e,t,r,n,i,s,o){var a;this.network=t,this.callState=r,this.socket=n,this.peersStorage=i,this.clientEventEmitter=s,this.webRtcIssueDetector=o,Ua.set(this,void 0),Ba.set(this,void 0),Va.set(this,[]),Wa.set(this,!1),Ha.set(this,{inbound:4.3,outbound:4.3}),qa.set(this,(new Date).getTime()-15e3),d(this,Ba,null===(a=this.webRtcIssueDetector)||void 0===a?void 0:a.eventEmitter,"f"),d(this,Ua,e("ChannelStateSyncEventHandler"),"f"),this.debouncedHandleChannelStateEvent=Ln(this.handleChannelStateEvent.bind(this),3e3),this.listenNetworkScoresUpdatedEvents()}handleChannelStateShort(e){return a(this,void 0,void 0,(function*(){try{yield this.debouncedHandleChannelStateEvent(e)}catch(e){c(this,Ua,"f").error("handleChannelStateSyncEvent()",{error:pr(e)})}}))}handleChannelStateEvent(e){return a(this,void 0,void 0,(function*(){if(c(this,Wa,"f"))c(this,Ua,"f").warn("Channel state event is already being handled, skipping new event",{case:"handleChannelStateEvent"});else{d(this,Wa,!0,"f");try{yield this.collectProbableInconsistencyCases(e);const t=this.getConfirmedInconsistencyResult();if(!(null==t?void 0:t.hasInconsistencyCases()))return;if(this.isRestoreStateRequestToEarly())return void c(this,Ua,"f").info("Inconsistency detected, but restore skipped",Object.assign({},t));this.handleConfirmedInconsistencyResult(t)}finally{d(this,Wa,!1,"f")}}}))}getLastInconsistencyCheckResult(){return c(this,Va,"f")[c(this,Va,"f").length-1]}handleConfirmedInconsistencyResult(e){e.missingPeers.forEach((e=>{this.clientEventEmitter.safeEmit(xr,{peerId:e,peersLoaded:this.network.peersLoaded,sdkInstances:Array.from(window._sdkMarks||[]).length,type:ja.MissingPeer})})),e.missingProducers.forEach((e=>{this.clientEventEmitter.safeEmit(xr,{producerId:e,type:ja.MissingProducer})})),e.producersWithInconsistentState.forEach((e=>{this.clientEventEmitter.safeEmit(xr,{producerId:e,type:ja.IncorrectProducerState})})),e.peersWithInconsistentAppData.forEach((e=>{this.clientEventEmitter.safeEmit(xr,{peerId:e,type:ja.IncorrectAppData})}))}getConfirmedInconsistencyResult(){const e=this.getLastInconsistencyCheckResult();if(!e)return;return new xa({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 a(this,void 0,void 0,(function*(){const t=new Fa({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(){d(this,Va,[],"f")}rotateLastProbableInconsistencyCheckResults(e){4===c(this,Va,"f").length&&c(this,Va,"f").shift(),c(this,Va,"f").push(e)}isReachedMaxCheckRetries(e,t,r=4){let n=0;return c(this,Va,"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:La(e.appData),producers:e.getProducers().map((e=>({id:e.id,paused:e.paused,stateChangedAt:e.getStateChangedAt()}))),consumers:e.getConsumersState()})))}}getIsConnectionActive(){return a(this,void 0,void 0,(function*(){var e;try{if(this.network.checkSocketConnectionActivity(),!this.network.isNetworkActive)return!1;const{success:t}=yield null===(e=this.socket.connection)||void 0===e?void 0:e.timeout(1e3).emitWithAck(Sr,{});return t}catch(e){return!1}}))}listenNetworkScoresUpdatedEvents(){c(this,Ba,"f")&&c(this,Ba,"f").on(Et.NetworkScoresUpdated,(e=>{e.inbound&&(c(this,Ha,"f").inbound=e.inbound),e.outbound&&(c(this,Ha,"f").outbound=e.outbound)}))}isBadNetworkScore(){const{inbound:e,outbound:t}=c(this,Ha,"f");return e<=2.6||t<=2.6}compareCheckedAndRestoredResults(e,t){return new xa({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()-c(this,qa,"f")<=15e3}};Ua=new WeakMap,Ba=new WeakMap,Va=new WeakMap,Wa=new WeakMap,Ha=new WeakMap,qa=new WeakMap,za=i([at(),s(0,dt(Hn.LoggerFactory)),s(1,dt(Hn.Network)),s(2,dt(Hn.CallState)),s(3,dt(Hn.SocketIO)),s(4,dt(Hn.PeersStorage)),s(5,dt(Hn.ClientEventEmitter)),s(6,dt(Hn.WebRTCIssueDetector)),o("design:paramtypes",[Function,Aa,$n,la,_a,Tt,or])],za);var Ga=za,Ya={},$a={exports:{}},Ja=1e3,Ka=6e4,Qa=60*Ka,Za=24*Qa,Xa=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*Za;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Qa;case"minutes":case"minute":case"mins":case"min":case"m":return r*Ka;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>=Za)return ec(e,t,Za,"day");if(t>=Qa)return ec(e,t,Qa,"hour");if(t>=Ka)return ec(e,t,Ka,"minute");if(t>=1e3)return ec(e,t,1e3,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=Za)return Math.round(e/Za)+"d";if(t>=Qa)return Math.round(e/Qa)+"h";if(t>=Ka)return Math.round(e/Ka)+"m";if(t>=Ja)return Math.round(e/Ja)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function ec(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}var tc=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=Xa,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=tc(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}($a,$a.exports);var rc={};Object.defineProperty(rc,"__esModule",{value:!0});var nc={},ic=Object.defineProperty,sc=Object.getOwnPropertyDescriptor,oc=Object.getOwnPropertyNames,ac=Object.prototype.hasOwnProperty,cc={};((e,t)=>{for(var r in t)ic(e,r,{get:t[r],enumerable:!0})})(cc,{BrowserDetector:()=>fc,KnownBrowsers:()=>uc,KnownPlatforms:()=>lc,default:()=>mc});var dc=(e=>((e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of oc(t))!ac.call(e,i)&&i!==r&&ic(e,i,{get:()=>t[i],enumerable:!(n=sc(t,i))||n.enumerable});return e})(ic({},"__esModule",{value:!0}),e))(cc),uc={chrome:"Google Chrome",brave:"Brave",crios:"Google Chrome",edge:"Microsoft Edge",edg:"Microsoft Edge",edgios:"Microsoft Edge",fennec:"Mozilla Firefox",jsdom:"JsDOM",mozilla:"Mozilla Firefox",fxios:"Mozilla Firefox",msie:"Microsoft Internet Explorer",opera:"Opera",opios:"Opera",opr:"Opera",opt:"Opera",rv:"Microsoft Internet Explorer",safari:"Safari",samsungbrowser:"Samsung Browser",electron:"Electron"},lc={android:"Android",androidTablet:"Android Tablet",cros:"Chrome OS",fennec:"Android Tablet",ipad:"IPad",ipod:"IPod",iphone:"IPhone",jsdom:"JsDOM",linux:"Linux",mac:"Macintosh",tablet:"Android Tablet",win:"Windows","windows phone":"Windows Phone",xbox:"Microsoft Xbox"},pc=(e,t=-1)=>{let r=new RegExp(`^-?\\d+(?:.\\d{0,${t}})?`),n=Number(e).toString().match(r);return n?n[0]:null},hc=()=>typeof window<"u"?window.navigator:null,fc=class{userAgent;constructor(e){this.userAgent=e||hc()?.userAgent||null}static get VERSION(){return"4.1.0"}parseUserAgent(e){let t={},r=e||this.userAgent||"",n=r.toLowerCase().replace(/\s\s+/g," "),i=/(edge)\/([\w.]+)/.exec(n)||/(edg)[/]([\w.]+)/.exec(n)||/(opr)[/]([\w.]+)/.exec(n)||/(opt)[/]([\w.]+)/.exec(n)||/(fxios)[/]([\w.]+)/.exec(n)||/(edgios)[/]([\w.]+)/.exec(n)||/(jsdom)[/]([\w.]+)/.exec(n)||/(samsungbrowser)[/]([\w.]+)/.exec(n)||/(electron)[/]([\w.]+)/.exec(n)||/(chrome)[/]([\w.]+)/.exec(n)||/(crios)[/]([\w.]+)/.exec(n)||/(opios)[/]([\w.]+)/.exec(n)||/(version)(applewebkit)[/]([\w.]+).*(safari)[/]([\w.]+)/.exec(n)||/(webkit)[/]([\w.]+).*(version)[/]([\w.]+).*(safari)[/]([\w.]+)/.exec(n)||/(applewebkit)[/]([\w.]+).*(safari)[/]([\w.]+)/.exec(n)||/(webkit)[/]([\w.]+)/.exec(n)||/(opera)(?:.*version|)[/]([\w.]+)/.exec(n)||/(msie) ([\w.]+)/.exec(n)||/(fennec)[/]([\w.]+)/.exec(n)||n.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(n)||n.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(n)||[],s=/(ipad)/.exec(n)||/(ipod)/.exec(n)||/(iphone)/.exec(n)||/(jsdom)/.exec(n)||/(windows phone)/.exec(n)||/(xbox)/.exec(n)||/(win)/.exec(n)||/(tablet)/.exec(n)||/(android)/.test(n)&&!1===/(mobile)/.test(n)&&["androidTablet"]||/(android)/.exec(n)||/(mac)/.exec(n)||/(linux)/.exec(n)||/(cros)/.exec(n)||[],o=i[5]||i[3]||i[1]||null,a=s[0]||null,c=i[4]||i[2]||null,d=hc();"chrome"===o&&"function"==typeof d?.brave?.isBrave&&(o="brave"),o&&(t[o]=!0),a&&(t[a]=!0);let u=!!(t.tablet||t.android||t.androidTablet),l=!!(t.ipad||t.tablet||t.androidTablet),p=!!(t.android||t.androidTablet||t.tablet||t.ipad||t.ipod||t.iphone||t["windows phone"]),h=!!(t.cros||t.mac||t.linux||t.win),f=!!(t.brave||t.chrome||t.crios||t.opr||t.safari||t.edg||t.electron),m=!(!t.msie&&!t.rv),g=!(!t.chrome&&!t.crios),v=!!(t.fxios||t.fennec||t.mozilla),y=!!t.safari,_=!!(t.opera||t.opios||t.opr||t.opt),b=!!(t.edg||t.edge||t.edgios);return{name:uc[o]??null,platform:lc[a]??null,userAgent:r,version:c,shortVersion:c?pc(parseFloat(c),2):null,isAndroid:u,isTablet:l,isMobile:p,isDesktop:h,isWebkit:f,isIE:m,isChrome:g,isFireFox:v,isSafari:y,isOpera:_,isEdge:b}}getBrowserInfo(){let e=this.parseUserAgent();return{name:e.name,platform:e.platform,userAgent:e.userAgent,version:e.version,shortVersion:e.shortVersion}}},mc=fc,gc={};Object.defineProperty(gc,"__esModule",{value:!0}),gc.Logger=void 0;const vc=$a.exports,yc="mediasoup-client";gc.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,vc.default)(`${yc}:${e}`),this._warn=(0,vc.default)(`${yc}:WARN:${e}`),this._error=(0,vc.default)(`${yc}:ERROR:${e}`)):(this._debug=(0,vc.default)(yc),this._warn=(0,vc.default)(`${yc}:WARN`),this._error=(0,vc.default)(`${yc}: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 _c,bc={},Ec={exports:{}},wc="object"==typeof Reflect?Reflect:null,Sc=wc&&"function"==typeof wc.apply?wc.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};_c=wc&&"function"==typeof wc.ownKeys?wc.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var Cc=Number.isNaN||function(e){return e!=e};function Pc(){Pc.init.call(this)}Ec.exports=Pc,Ec.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))}Lc(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&Lc(e,"error",t,r)}(e,i,{once:!0})}))},Pc.EventEmitter=Pc,Pc.prototype._events=void 0,Pc.prototype._eventsCount=0,Pc.prototype._maxListeners=void 0;var Tc=10;function kc(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function Rc(e){return void 0===e._maxListeners?Pc.defaultMaxListeners:e._maxListeners}function Ic(e,t,r,n){var i,s,o,a;if(kc(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=Rc(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 Dc(){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 Ac(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=Dc.bind(n);return i.listener=r,n.wrapFn=i,i}function Oc(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):Mc(i,i.length)}function Nc(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 Mc(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function Lc(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(Pc,"defaultMaxListeners",{enumerable:!0,get:function(){return Tc},set:function(e){if("number"!=typeof e||e<0||Cc(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Tc=e}}),Pc.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},Pc.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||Cc(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},Pc.prototype.getMaxListeners=function(){return Rc(this)},Pc.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)Sc(a,this,t);else{var c=a.length,d=Mc(a,c);for(r=0;r<c;++r)Sc(d[r],this,t)}return!0},Pc.prototype.addListener=function(e,t){return Ic(this,e,t,!1)},Pc.prototype.on=Pc.prototype.addListener,Pc.prototype.prependListener=function(e,t){return Ic(this,e,t,!0)},Pc.prototype.once=function(e,t){return kc(t),this.on(e,Ac(this,e,t)),this},Pc.prototype.prependOnceListener=function(e,t){return kc(t),this.prependListener(e,Ac(this,e,t)),this},Pc.prototype.removeListener=function(e,t){var r,n,i,s,o;if(kc(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},Pc.prototype.off=Pc.prototype.removeListener,Pc.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},Pc.prototype.listeners=function(e){return Oc(this,e,!0)},Pc.prototype.rawListeners=function(e){return Oc(this,e,!1)},Pc.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Nc.call(e,t)},Pc.prototype.listenerCount=Nc,Pc.prototype.eventNames=function(){return this._eventsCount>0?_c(this._events):[]},Object.defineProperty(bc,"__esModule",{value:!0}),bc.EnhancedEventEmitter=void 0;const xc=Ec.exports,Fc=new gc.Logger("EnhancedEventEmitter");class jc extends xc.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){Fc.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)}}bc.EnhancedEventEmitter=jc;var Uc={};Object.defineProperty(Uc,"__esModule",{value:!0}),Uc.InvalidStateError=Uc.UnsupportedError=void 0;class Bc extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Bc):this.stack=new Error(e).stack}}Uc.UnsupportedError=Bc;class Vc extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Vc):this.stack=new Error(e).stack}}Uc.InvalidStateError=Vc;var Wc={};Object.defineProperty(Wc,"__esModule",{value:!0}),Wc.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))},Wc.generateRandomNumber=function(){return Math.round(1e7*Math.random())},Wc.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 Hc={},qc={},zc={},Gc={exports:{}};var Yc=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=Xa,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=Yc(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Gc,Gc.exports);var $c=l&&l.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(zc,"__esModule",{value:!0}),zc.Logger=void 0;const Jc=$c(Gc.exports),Kc="h264-profile-level-id";zc.Logger=class{constructor(e){e?(this._debug=(0,Jc.default)(`${Kc}:${e}`),this._warn=(0,Jc.default)(`${Kc}:WARN:${e}`),this._error=(0,Jc.default)(`${Kc}:ERROR:${e}`)):(this._debug=(0,Jc.default)(Kc),this._warn=(0,Jc.default)(`${Kc}:WARN`),this._error=(0,Jc.default)(`${Kc}: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(qc,"__esModule",{value:!0}),qc.ProfileLevelId=qc.Level=qc.Profile=void 0,qc.parseProfileLevelId=od,qc.profileLevelIdToString=ad,qc.profileToString=function(e){switch(e){case Zc.ConstrainedBaseline:return"ConstrainedBaseline";case Zc.Baseline:return"Baseline";case Zc.Main:return"Main";case Zc.ConstrainedHigh:return"ConstrainedHigh";case Zc.High:return"High";case Zc.PredictiveHigh444:return"PredictiveHigh444";default:return void Qc.warn(`profileToString() | unrecognized profile ${e}`)}},qc.levelToString=function(e){switch(e){case Xc.L1_b:return"1b";case Xc.L1:return"1";case Xc.L1_1:return"1.1";case Xc.L1_2:return"1.2";case Xc.L1_3:return"1.3";case Xc.L2:return"2";case Xc.L2_1:return"2.1";case Xc.L2_2:return"2.2";case Xc.L3:return"3";case Xc.L3_1:return"3.1";case Xc.L3_2:return"3.2";case Xc.L4:return"4";case Xc.L4_1:return"4.1";case Xc.L4_2:return"4.2";case Xc.L5:return"5";case Xc.L5_1:return"5.1";case Xc.L5_2:return"5.2";default:return void Qc.warn(`levelToString() | unrecognized level ${e}`)}},qc.parseSdpProfileLevelId=cd,qc.isSameProfile=function(e={},t={}){const r=cd(e),n=cd(t);return Boolean(r&&n&&r.profile===n.profile)},qc.isSameProfileAndLevel=function(e={},t={}){const r=cd(e),n=cd(t);return Boolean(r&&n&&r.profile===n.profile&&r.level==n.level)},qc.generateProfileLevelIdStringForAnswer=function(e={},t={}){if(!e["profile-level-id"]&&!t["profile-level-id"])return void Qc.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");const r=cd(e),n=cd(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=ud(e)&&ud(t),s=r.level,o=n.level,a=function(e,t){return function(e,t){if(e===Xc.L1_b)return t!==Xc.L1&&t!==Xc.L1_b;if(t===Xc.L1_b)return e!==Xc.L1;return e<t}(e,t)?e:t}(s,o),c=i?s:a;return Qc.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${r.profile}, level:${c}]`),ad(new ed(r.profile,c))},qc.supportedLevel=function(e,t){for(let r=sd.length-1;r>=0;--r){const n=sd[r];if(256*n.max_macroblock_frame_size<=e&&n.max_macroblocks_per_second<=t*n.max_macroblock_frame_size)return Qc.debug(`supportedLevel() | result [max_frame_pixel_count:${e}, max_fps:${t}, level:${n.level}]`),n.level}return void Qc.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${e}, max_fps:${t}]`)};const Qc=new zc.Logger;var Zc,Xc;!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"}(Zc||(qc.Profile=Zc={})),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"}(Xc||(qc.Level=Xc={}));class ed{constructor(e,t){this.profile=e,this.level=t}}qc.ProfileLevelId=ed;const td=new ed(Zc.ConstrainedBaseline,Xc.L3_1);class rd{constructor(e){this.mask=~dd("x",e),this.masked_value=dd("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}}class nd{constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}}const id=[new nd(66,new rd("x1xx0000"),Zc.ConstrainedBaseline),new nd(77,new rd("1xxx0000"),Zc.ConstrainedBaseline),new nd(88,new rd("11xx0000"),Zc.ConstrainedBaseline),new nd(66,new rd("x0xx0000"),Zc.Baseline),new nd(88,new rd("10xx0000"),Zc.Baseline),new nd(77,new rd("0x0x0000"),Zc.Main),new nd(100,new rd("00000000"),Zc.High),new nd(100,new rd("00001100"),Zc.ConstrainedHigh),new nd(244,new rd("00000000"),Zc.PredictiveHigh444)],sd=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:Xc.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:Xc.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:Xc.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:Xc.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:Xc.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:Xc.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:Xc.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:Xc.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:Xc.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:Xc.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:Xc.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:Xc.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:Xc.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:Xc.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:Xc.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:Xc.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:Xc.L5_2}];function od(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 Xc.L1_1:s=0!=(16&n)?Xc.L1_b:Xc.L1_1;break;case Xc.L1:case Xc.L1_2:case Xc.L1_3:case Xc.L2:case Xc.L2_1:case Xc.L2_2:case Xc.L3:case Xc.L3_1:case Xc.L3_2:case Xc.L4:case Xc.L4_1:case Xc.L4_2:case Xc.L5:case Xc.L5_1:case Xc.L5_2:s=r;break;default:return void Qc.warn(`parseProfileLevelId() | unrecognized level_idc [str:${e}, level_idc:${r}]`)}for(const t of id)if(i===t.profile_idc&&t.profile_iop.isMatch(n))return Qc.debug(`parseProfileLevelId() | result [str:${e}, profile:${t.profile}, level:${s}]`),new ed(t.profile,s);Qc.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${e}, profile_idc:${i}, profile_iop:${n}]`)}function ad(e){if(e.level==Xc.L1_b)switch(e.profile){case Zc.ConstrainedBaseline:return"42f00b";case Zc.Baseline:return"42100b";case Zc.Main:return"4d100b";default:return void Qc.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${e.profile}`)}let t;switch(e.profile){case Zc.ConstrainedBaseline:t="42e0";break;case Zc.Baseline:t="4200";break;case Zc.Main:t="4d00";break;case Zc.ConstrainedHigh:t="640c";break;case Zc.High:t="6400";break;case Zc.PredictiveHigh444:t="f400";break;default:return void Qc.warn(`profileLevelIdToString() | unrecognized profile ${e.profile}`)}let r=e.level.toString(16);return 1===r.length&&(r=`0${r}`),`${t}${r}`}function cd(e={}){const t=e["profile-level-id"];return t?od(t):td}function dd(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 ud(e={}){const t=e["level-asymmetry-allowed"];return!0===t||1===t||"1"===t}Object.defineProperty(Hc,"__esModule",{value:!0}),Hc.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)fd(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)gd(t)},Hc.validateAndNormalizeRtpParameters=hd,Hc.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")},Hc.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)},Hc.getExtendedRtpCapabilities=function(e,t,r){const n={codecs:[],headerExtensions:[]};if(r)for(const r of e.codecs??[]){if(bd(r))continue;const e=(t.codecs??[]).find((e=>Ed(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:Sd(r,e)};n.codecs.push(i)}else for(const r of t.codecs??[]){if(bd(r))continue;const t=(e.codecs??[]).find((e=>Ed(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:Sd(t,r)};n.codecs.push(i)}for(const r of n.codecs){const n=e.codecs.find((e=>bd(e)&&e.parameters?.apt===r.localPayloadType)),i=t.codecs.find((e=>bd(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=>wd(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},Hc.getRecvRtpCapabilities=function(e){const t={codecs:[],headerExtensions:[]};for(const r of e.codecs){const e={kind:r.kind,mimeType:r.mimeType,preferredPayloadType:r.remotePayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.localParameters,rtcpFeedback:r.rtcpFeedback};if(t.codecs.push(e),!r.remoteRtxPayloadType)continue;const n={kind:r.kind,mimeType:`${r.kind}/rtx`,preferredPayloadType:r.remoteRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.remotePayloadType},rtcpFeedback:[]};t.codecs.push(n)}for(const r of e.headerExtensions){if("sendrecv"!==r.direction&&"recvonly"!==r.direction)continue;const e={kind:r.kind,uri:r.uri,preferredId:r.recvId,preferredEncrypt:r.encrypt??!1,direction:r.direction};t.headerExtensions.push(e)}return t},Hc.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},Hc.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},Hc.reduceCodecs=function(e,t){const r=[];if(t){for(let n=0;n<e.length;++n)if(Ed(e[n],t,{strict:!0})){r.push(e[n]),bd(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]),bd(e[1])&&r.push(e[1]);return r},Hc.generateProbatorRtpParameters=function(e){hd(e=pd.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},Hc.canSend=function(e,t){return(t.codecs??[]).some((t=>t.kind===e))},Hc.canReceive=function(e,t){if(hd(e),0===e.codecs.length)return!1;const r=e.codecs[0];return(t.codecs??[]).some((e=>e.preferredPayloadType===r.payloadType))};const ld=qc,pd=Wc;function hd(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)vd(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)yd(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)_d(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 fd(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)md(t)}function md(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 gd(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 vd(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)md(t)}function yd(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 _d(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 bd(e){return!!e&&/.+\/rtx$/i.test(e.mimeType)}function Ed(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(!ld.isSameProfile(e.parameters,t.parameters))return!1;let r;try{r=ld.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 wd(e,t){return(!e.kind||!t.kind||e.kind===t.kind)&&e.uri===t.uri}function Sd(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 Cd={},Pd={},Td={},kd={};Object.defineProperty(kd,"__esModule",{value:!0}),kd.Logger=void 0;const Rd=$a.exports,Id="awaitqueue";kd.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=Rd(`awaitqueue:${e}`),this._warn=Rd(`awaitqueue:WARN:${e}`),this._error=Rd(`awaitqueue:ERROR:${e}`)):(this._debug=Rd(Id),this._warn=Rd("awaitqueue:WARN"),this._error=Rd("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 Dd={};Object.defineProperty(Dd,"__esModule",{value:!0}),Dd.AwaitQueueRemovedTaskError=Dd.AwaitQueueStoppedError=void 0;class Ad extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Ad)}}Dd.AwaitQueueStoppedError=Ad;class Od extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Od)}}Dd.AwaitQueueRemovedTaskError=Od,Object.defineProperty(Td,"__esModule",{value:!0}),Td.AwaitQueue=void 0;const Nd=Dd,Md=new kd.Logger("AwaitQueue");Td.AwaitQueue=class{pendingTasks=new Map;nextTaskId=0;stopping=!1;constructor(){Md.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t){if(t=t??e.name,Md.debug(`push() [name:${t}]`),"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(((r,n)=>{const i={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:e=>{if(i.completed)return;i.completed=!0,this.pendingTasks.delete(i.id),Md.debug(`resolving task [name:${i.name}]`),r(e);const[t]=this.pendingTasks.values();t&&!t.executedAt&&this.execute(t)},reject:e=>{if(!i.completed&&(i.completed=!0,this.pendingTasks.delete(i.id),Md.debug(`rejecting task [name:${i.name}]: %s`,String(e)),n(e),!this.stopping)){const[e]=this.pendingTasks.values();e&&!e.executedAt&&this.execute(e)}}};this.pendingTasks.set(i.id,i),1===this.pendingTasks.size&&this.execute(i)}))}stop(){Md.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())Md.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Nd.AwaitQueueStoppedError);this.stopping=!1}remove(e){Md.debug(`remove() [taskIdx:${e}]`);const t=Array.from(this.pendingTasks.values())[e];t?t.reject(new Nd.AwaitQueueRemovedTaskError):Md.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(Md.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)}}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AwaitQueueRemovedTaskError=e.AwaitQueueStoppedError=e.AwaitQueue=void 0;var t=Td;Object.defineProperty(e,"AwaitQueue",{enumerable:!0,get:function(){return t.AwaitQueue}});var r=Dd;Object.defineProperty(e,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return r.AwaitQueueStoppedError}}),Object.defineProperty(e,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return r.AwaitQueueRemovedTaskError}})}(Pd);var Ld={};Object.defineProperty(Ld,"__esModule",{value:!0}),Ld.Producer=void 0;const xd=bc,Fd=Uc,jd=new gc.Logger("Producer");class Ud extends xd.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new xd.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:r,track:n,rtpParameters:i,stopTracks:s,disableTrackOnPause:o,zeroRtpOnPause:a,appData:c}){super(),jd.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||(jd.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(jd.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Fd.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){jd.debug("pause()"),this._closed?jd.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(){jd.debug("resume()"),this._closed?jd.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(jd.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch(e){}throw new Fd.InvalidStateError("closed")}if(e&&"ended"===e.readyState)throw new Fd.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()):jd.debug("replaceTrack() | same track, ignored")}async setMaxSpatialLayer(e){if(this._closed)throw new Fd.InvalidStateError("closed");if("video"!==this._kind)throw new Fd.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 Fd.InvalidStateError("closed");if("object"!=typeof e)throw new TypeError("invalid params");await new Promise(((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)}))}onTrackEnded(){jd.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){}}}Ld.Producer=Ud;var Bd={};Object.defineProperty(Bd,"__esModule",{value:!0}),Bd.Consumer=void 0;const Vd=bc,Wd=Uc,Hd=new gc.Logger("Consumer");class qd extends Vd.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new Vd.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:r,rtpReceiver:n,track:i,rtpParameters:s,appData:o}){super(),Hd.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||(Hd.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Hd.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Wd.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){Hd.debug("pause()"),this._closed?Hd.error("pause() | Consumer closed"):this._paused?Hd.debug("pause() | Consumer is already paused"):(this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause"))}resume(){Hd.debug("resume()"),this._closed?Hd.error("resume() | Consumer closed"):this._paused?(this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")):Hd.debug("resume() | Consumer is already resumed")}onTrackEnded(){Hd.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){}}}Bd.Consumer=qd;var zd={};Object.defineProperty(zd,"__esModule",{value:!0}),zd.DataProducer=void 0;const Gd=bc,Yd=Uc,$d=new gc.Logger("DataProducer");class Jd extends Gd.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new Gd.EnhancedEventEmitter;constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:n}){super(),$d.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||($d.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||($d.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if($d.debug("send()"),this._closed)throw new Yd.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||($d.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?$d.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):$d.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||($d.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))})),this._dataChannel.addEventListener("message",(()=>{this._closed||$d.warn('DataChannel "message" event in a DataProducer, message discarded')})),this._dataChannel.addEventListener("bufferedamountlow",(()=>{this._closed||this.safeEmit("bufferedamountlow")}))}}zd.DataProducer=Jd;var Kd={};Object.defineProperty(Kd,"__esModule",{value:!0}),Kd.DataConsumer=void 0;const Qd=bc,Zd=new gc.Logger("DataConsumer");class Xd extends Qd.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new Qd.EnhancedEventEmitter;constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:n,appData:i}){super(),Zd.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||(Zd.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Zd.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(Zd.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?Zd.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):Zd.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(Zd.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)}))}}Kd.DataConsumer=Xd,Object.defineProperty(Cd,"__esModule",{value:!0}),Cd.Transport=void 0;const eu=Pd,tu=bc,ru=Uc,nu=Wc,iu=Hc,su=Ld,ou=Bd,au=zd,cu=Kd,du=new gc.Logger("Transport");class uu{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class lu extends tu.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 eu.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new tu.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(),du.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=nu.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){du.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 ru.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(du.debug("restartIce()"),this._closed)throw new ru.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(du.debug("updateIceServers()"),this._closed)throw new ru.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,encodings:t,codecOptions:r,codec:n,stopTracks:i=!0,disableTrackOnPause:s=!0,zeroRtpOnPause:o=!1,onRtpSender:a,appData:c={}}={}){if(du.debug("produce() [track:%o]",e),this._closed)throw new ru.InvalidStateError("closed");if(!e)throw new TypeError("missing track");if("send"!==this._direction)throw new ru.UnsupportedError("not a sending Transport");if(!this._canProduceByKind[e.kind])throw new ru.UnsupportedError(`cannot produce ${e.kind}`);if("ended"===e.readyState)throw new ru.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(c&&"object"!=typeof c)throw new TypeError("if given, appData must be an object");return this._awaitQueue.push((async()=>{let d;if(t&&!Array.isArray(t))throw TypeError("encodings must be an array");t&&0===t.length?d=void 0:t&&(d=t.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:u,rtpParameters:l,rtpSender:p}=await this._handler.send({track:e,encodings:d,codecOptions:r,codec:n,onRtpSender:a});try{iu.validateAndNormalizeRtpParameters(l);const{id:t}=await new Promise(((t,r)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:l,appData:c},t,r)})),r=new su.Producer({id:t,localId:u,rtpSender:p,track:e,rtpParameters:l,stopTracks:i,disableTrackOnPause:s,zeroRtpOnPause:o,appData:c});return this._producers.set(r.id,r),this.handleProducer(r),this._observer.safeEmit("newproducer",r),r}catch(e){throw this._handler.stopSending(u).catch((()=>{})),e}}),"transport.produce()").catch((t=>{if(i)try{e.stop()}catch(e){}throw t}))}async consume({id:e,producerId:t,kind:r,rtpParameters:n,streamId:i,onRtpReceiver:s,appData:o={}}){if(du.debug("consume()"),this._closed)throw new ru.InvalidStateError("closed");if("recv"!==this._direction)throw new ru.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=nu.clone(n);if(!iu.canReceive(a,this._recvRtpCapabilities))throw new ru.UnsupportedError("cannot consume this Producer");const c=new uu({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(du.debug("produceData()"),this._closed)throw new ru.InvalidStateError("closed");if("send"!==this._direction)throw new ru.UnsupportedError("not a sending Transport");if(!this._maxSctpMessageSize)throw new ru.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});iu.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 au.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(du.debug("consumeData()"),this._closed)throw new ru.InvalidStateError("closed");if("recv"!==this._direction)throw new ru.UnsupportedError("not a receiving Transport");if(!this._maxSctpMessageSize)throw new ru.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=nu.clone(r);return iu.validateAndNormalizeSctpStreamParameters(o),this._awaitQueue.push((async()=>{const{dataChannel:r}=await this._handler.receiveDataChannel({sctpStreamParameters:o,label:n,protocol:i}),a=new cu.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 du.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 ou.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=iu.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:e}]),du.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(e){du.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 du.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){du.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 du.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){du.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 du.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){du.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 ru.InvalidStateError("closed")):this.safeEmit("connect",{dtlsParameters:e},t,r)})),e.on("@icegatheringstatechange",(e=>{e!==this._iceGatheringState&&(du.debug("ICE gathering state changed to %s",e),this._iceGatheringState=e,this._closed||this.safeEmit("icegatheringstatechange",e))})),e.on("@icecandidateerror",(e=>{du.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&&(du.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=>du.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 ru.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 ru.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)}))}}Cd.Transport=lu;var pu={},hu={},fu={},mu={exports:{}},gu=mu.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"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",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(gu).forEach((function(e){gu[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=mu.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}}))}))}}(fu);var vu=mu.exports,yu=/%[sdv%]/g,_u=function(e){var t=1,r=arguments,n=r.length;return e.replace(yu,(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""}}))},bu=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 _u.apply(null,n)},Eu=["v","o","s","i","u","e","p","c","b","t","r","z","a"],wu=["i","c","b","a"],Su=fu,Cu=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||Eu,n=t.innerOrder||wu,i=[];return r.forEach((function(t){vu[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(bu(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(bu(t,r,e))}))}))})),e.media.forEach((function(e){i.push(bu("m",vu.m[0],e)),n.forEach((function(t){vu[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(bu(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(bu(t,r,e))}))}))}))})),i.join("\r\n")+"\r\n"},Pu=mu.exports;hu.grammar=Pu,hu.write=Cu,hu.parse=Su.parse,hu.parseParams=Su.parseParams,hu.parseFmtpConfig=Su.parseFmtpConfig,hu.parsePayloads=Su.parsePayloads,hu.parseRemoteCandidates=Su.parseRemoteCandidates,hu.parseImageAttributes=Su.parseImageAttributes,hu.parseSimulcastStreamList=Su.parseSimulcastStreamList;var Tu={};Object.defineProperty(Tu,"__esModule",{value:!0}),Tu.parse=function(e){const t=ku.exec(e??"");return t?{spatialLayers:Number(t[1]),temporalLayers:Number(t[2])}:{spatialLayers:1,temporalLayers:1}};const ku=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");var Ru={};Object.defineProperty(Ru,"__esModule",{value:!0}),Ru.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=Iu.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())}},Ru.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??=t.setup,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}]}},Ru.getCname=function({offerMediaObject:e}){const t=(e.ssrcs??[]).find((e=>"cname"===e.attribute));if(!t)return"";return t.value},Ru.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=Iu.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]}`}};const Iu=hu;var Du={};Object.defineProperty(Du,"__esModule",{value:!0}),Du.getRtpEncodings=function({offerMediaObject:e}){const t=new Set;for(const r of e.ssrcs??[]){const e=r.id;e&&t.add(e)}if(0===t.size)throw new Error("no a=ssrc lines found");const r=new Map;for(const n of e.ssrcGroups??[]){if("FID"!==n.semantics)continue;const e=n.ssrcs.split(/\s+/),i=Number(e[0]),s=Number(e[1]);t.has(i)&&(t.delete(i),t.delete(s),r.set(i,s))}for(const e of t)r.set(e,void 0);const n=[];for(const[e,t]of r){const r={ssrc:e};t&&(r.rtx={ssrc:t}),n.push(r)}return n},Du.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 Au={};Object.defineProperty(Au,"__esModule",{value:!0}),Au.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"}))};var Ou={},Nu={};Object.defineProperty(Nu,"__esModule",{value:!0}),Nu.OfferMediaSection=Nu.AnswerMediaSection=Nu.MediaSection=void 0;const Mu=hu,Lu=Wc;class xu{_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(),delete this._mediaObject.ext,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}close(){this.disable(),this._mediaObject.port=0}}Nu.MediaSection=xu;Nu.AnswerMediaSection=class extends xu{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:Fu(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r=Lu.clone(e.parameters)??{};let n=Lu.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=Mu.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 Fu(e){const t=new RegExp("^(audio|video)/(.+)","i").exec(e.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}Nu.OfferMediaSection=class extends xu{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=`${c??"-"} ${d}`;for(const e of a.codecs){const t={payload:e.payloadType,codec:Fu(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(Ou,"__esModule",{value:!0}),Ou.RemoteSdp=void 0;const ju=hu,Uu=Nu,Bu=["av1","h264"],Vu=new gc.Logger("RemoteSdp");Ou.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"},name:"-",timing:{start:0,stop:0},media:[]},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){Vu.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){Vu.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(const t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){Vu.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 Uu.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=>Bu.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 Uu.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));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?(Vu.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 Uu.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 Uu.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++,ju.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(" "))}},Object.defineProperty(pu,"__esModule",{value:!0}),pu.Chrome111=void 0;const Wu=hu,Hu=bc,qu=Hc,zu=Uc,Gu=Tu,Yu=Ru,$u=Du,Ju=Au,Ku=Ou,Qu=new gc.Logger("Chrome111"),Zu={OS:1024,MIS:1024};class Xu extends Hu.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 Xu(e),getNativeRtpCapabilities:async()=>{Qu.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video",{sendEncodings:[{scalabilityMode:"L3T3"}]});const t=await e.createOffer();try{e.close()}catch(e){}e=void 0;const r=Wu.parse(t.sdp);return Xu.getLocalRtpCapabilities(r)}catch(t){try{e?.close()}catch(e){}throw e=void 0,t}},getNativeSctpCapabilities:async()=>(Qu.debug("getNativeSctpCapabilities()"),{numStreams:Zu})}}static getLocalRtpCapabilities(e){const t=Yu.extractRtpCapabilities({sdpObject:e});return qu.validateAndNormalizeRtpCapabilities(t),Ju.addNackSupportForOpus(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Qu.debug("constructor()"),this._direction=e,this._remoteSdp=new Ku.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):(Qu.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Chrome111"}close(){if(Qu.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(),Qu.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Qu.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Qu.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Qu.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Qu.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Qu.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,encodings:t,codecOptions:r,codec:n,onRtpSender:i}){if(this.assertNotClosed(),this.assertSendDirection(),Qu.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1){let e=1;for(const r of t){const t=r.scalabilityMode?(0,Gu.parse)(r.scalabilityMode).temporalLayers:3;t>e&&(e=t)}t.forEach(((t,r)=>{t.rid=`r${r}`,t.scalabilityMode=`L1T${e}`}))}const s=this._remoteSdp.getNextMediaSectionIdx(),o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(o.sender);const a=await this._pc.createOffer();let c=Wu.parse(a.sdp);c.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const d=Xu.getLocalRtpCapabilities(c),u=this._getSendExtendedRtpCapabilities(d),l=qu.getSendingRtpParameters(e.kind,u);l.codecs=qu.reduceCodecs(l.codecs,n);const p=qu.getSendingRemoteRtpParameters(e.kind,u);p.codecs=qu.reduceCodecs(p.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:c}),Qu.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const h=o.mid;l.mid=h,c=Wu.parse(this._pc.localDescription.sdp);const f=c.media[s.idx];if(l.rtcp.cname=Yu.getCname({offerMediaObject:f}),t)if(1===t.length){const e=$u.getRtpEncodings({offerMediaObject:f});Object.assign(e[0],t[0]),l.encodings=e}else l.encodings=t;else l.encodings=$u.getRtpEncodings({offerMediaObject:f});this._remoteSdp.send({offerMediaObject:f,reuseMid:s.reuseMid,offerRtpParameters:l,answerRtpParameters:p,codecOptions:r});const m={type:"answer",sdp:this._remoteSdp.getSdp()};return Qu.debug("send() | calling pc.setRemoteDescription() [answer:%o]",m),await this._pc.setRemoteDescription(m),this._mapMidTransceiver.set(h,o),{localId:h,rtpParameters:l,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),Qu.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();Qu.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Qu.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Qu.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();Qu.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Qu.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Qu.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();Qu.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Qu.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Qu.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Qu.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(),Qu.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();Qu.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Qu.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Qu.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();Qu.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Qu.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};Qu.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Zu.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Wu.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Qu.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()};Qu.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;Qu.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Qu.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=Wu.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));Yu.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Wu.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Qu.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){Qu.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()};Qu.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Qu.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){Qu.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()};Qu.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Qu.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){Qu.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()};Qu.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Qu.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};Qu.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()};Qu.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Wu.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Qu.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=Wu.parse(this._pc.localDescription.sdp));const r=Yu.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 zu.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')}}pu.Chrome111=Xu;var el={};Object.defineProperty(el,"__esModule",{value:!0}),el.Chrome74=void 0;const tl=hu,rl=bc,nl=Hc,il=Uc,sl=Tu,ol=Ru,al=Du,cl=Au,dl=Ou,ul=new gc.Logger("Chrome74"),ll={OS:1024,MIS:1024};class pl extends rl.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 pl(e),getNativeRtpCapabilities:async()=>{ul.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}e=void 0;const r=tl.parse(t.sdp);return pl.getLocalRtpCapabilities(r)}catch(t){try{e?.close()}catch(e){}throw e=void 0,t}},getNativeSctpCapabilities:async()=>(ul.debug("getNativeSctpCapabilities()"),{numStreams:ll})}}static getLocalRtpCapabilities(e){const t=ol.extractRtpCapabilities({sdpObject:e});return nl.validateAndNormalizeRtpCapabilities(t),cl.addNackSupportForOpus(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),ul.debug("constructor()"),this._direction=e,this._remoteSdp=new dl.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):(ul.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Chrome74"}close(){if(ul.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(),ul.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),ul.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});ul.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};ul.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};ul.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();ul.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,encodings:t,codecOptions:r,codec:n}){this.assertNotClosed(),this.assertSendDirection(),ul.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach(((e,t)=>{e.rid=`r${t}`}));const i=this._remoteSdp.getNextMediaSectionIdx(),s=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});let o=await this._pc.createOffer(),a=tl.parse(o.sdp);a.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const c=pl.getLocalRtpCapabilities(a),d=this._getSendExtendedRtpCapabilities(c),u=nl.getSendingRtpParameters(e.kind,d);u.codecs=nl.reduceCodecs(u.codecs,n);const l=nl.getSendingRemoteRtpParameters(e.kind,d);l.codecs=nl.reduceCodecs(l.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:a});let p=!1;const h=(0,sl.parse)((t??[{}])[0].scalabilityMode);let f;t&&1===t.length&&h.spatialLayers>1&&"video/vp9"===u.codecs[0].mimeType.toLowerCase()&&(ul.debug("send() | enabling legacy simulcast for VP9 SVC"),p=!0,a=tl.parse(o.sdp),f=a.media[i.idx],al.addLegacySimulcast({offerMediaObject:f,numStreams:h.spatialLayers}),o={type:"offer",sdp:tl.write(a)}),ul.debug("send() | calling pc.setLocalDescription() [offer:%o]",o),await this._pc.setLocalDescription(o);const m=s.mid;if(u.mid=m,a=tl.parse(this._pc.localDescription.sdp),f=a.media[i.idx],u.rtcp.cname=ol.getCname({offerMediaObject:f}),t)if(1===t.length){let e=al.getRtpEncodings({offerMediaObject:f});Object.assign(e[0],t[0]),p&&(e=[e[0]]),u.encodings=e}else u.encodings=t;else u.encodings=al.getRtpEncodings({offerMediaObject:f});if(u.encodings.length>1&&("video/vp8"===u.codecs[0].mimeType.toLowerCase()||"video/h264"===u.codecs[0].mimeType.toLowerCase()))for(const e of u.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${h.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:f,reuseMid:i.reuseMid,offerRtpParameters:u,answerRtpParameters:l,codecOptions:r});const g={type:"answer",sdp:this._remoteSdp.getSdp()};return ul.debug("send() | calling pc.setRemoteDescription() [answer:%o]",g),await this._pc.setRemoteDescription(g),this._mapMidTransceiver.set(m,s),{localId:m,rtpParameters:u,rtpSender:s.sender}}async stopSending(e){if(this.assertSendDirection(),ul.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();ul.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};ul.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),ul.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();ul.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};ul.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),ul.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();ul.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};ul.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?ul.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):ul.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(),ul.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();ul.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};ul.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),ul.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();ul.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};ul.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};ul.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%ll.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=tl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),ul.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()};ul.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;ul.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};ul.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer();const s=tl.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));ol.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:tl.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),ul.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){ul.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()};ul.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ul.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){ul.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()};ul.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ul.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){ul.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()};ul.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ul.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};ul.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()};ul.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=tl.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}ul.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=tl.parse(this._pc.localDescription.sdp));const r=ol.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 il.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')}}el.Chrome74=pl;var hl={};Object.defineProperty(hl,"__esModule",{value:!0}),hl.Firefox120=void 0;const fl=hu,ml=bc,gl=Uc,vl=Hc,yl=Tu,_l=Ru,bl=Du,El=Ou,wl=new gc.Logger("Firefox120"),Sl={OS:16,MIS:2048};class Cl extends ml.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 Cl(e),getNativeRtpCapabilities:async()=>{wl.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});const t=document.createElement("canvas");t.getContext("2d");const r=t.captureStream().getVideoTracks()[0];try{e.addTransceiver("audio",{direction:"sendrecv"}),e.addTransceiver(r,{direction:"sendrecv",sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});const n=await e.createOffer();try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}e=void 0;const i=fl.parse(n.sdp);return Cl.getLocalRtpCapabilities(i)}catch(n){try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e?.close()}catch(e){}throw e=void 0,n}},getNativeSctpCapabilities:async()=>(wl.debug("getNativeSctpCapabilities()"),{numStreams:Sl})}}static getLocalRtpCapabilities(e){const t=_l.extractRtpCapabilities({sdpObject:e});return vl.validateAndNormalizeRtpCapabilities(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),wl.debug("constructor()"),this._direction=e,this._remoteSdp=new El.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):(wl.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Firefox120"}close(){if(wl.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 gl.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),wl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});wl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};wl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};wl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();wl.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,encodings:t,codecOptions:r,codec:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),wl.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach(((e,t)=>{e.rid=`r${t}`}));const s=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(s.sender);const o=await this._pc.createOffer();let a=fl.parse(o.sdp);a.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const c=Cl.getLocalRtpCapabilities(a),d=this._getSendExtendedRtpCapabilities(c),u=vl.getSendingRtpParameters(e.kind,d);u.codecs=vl.reduceCodecs(u.codecs,n);const l=vl.getSendingRemoteRtpParameters(e.kind,d);l.codecs=vl.reduceCodecs(l.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:a});const p=(0,yl.parse)((t??[{}])[0].scalabilityMode);wl.debug("send() | calling pc.setLocalDescription() [offer:%o]",o),await this._pc.setLocalDescription(o);const h=s.mid;u.mid=h,a=fl.parse(this._pc.localDescription.sdp);const f=a.media[a.media.length-1];if(u.rtcp.cname=_l.getCname({offerMediaObject:f}),t)if(1===t.length){const e=bl.getRtpEncodings({offerMediaObject:f});Object.assign(e[0],t[0]),u.encodings=e}else u.encodings=t;else u.encodings=bl.getRtpEncodings({offerMediaObject:f});if(u.encodings.length>1&&("video/vp8"===u.codecs[0].mimeType.toLowerCase()||"video/h264"===u.codecs[0].mimeType.toLowerCase()))for(const e of u.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${p.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:f,offerRtpParameters:u,answerRtpParameters:l,codecOptions:r});const m={type:"answer",sdp:this._remoteSdp.getSdp()};return wl.debug("send() | calling pc.setRemoteDescription() [answer:%o]",m),await this._pc.setRemoteDescription(m),this._mapMidTransceiver.set(h,s),{localId:h,rtpParameters:u,rtpSender:s.sender}}async stopSending(e){if(this.assertSendDirection(),wl.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();wl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};wl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),wl.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();wl.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};wl.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),wl.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();wl.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};wl.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?wl.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):wl.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(),wl.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();wl.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};wl.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),wl.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();wl.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};wl.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};wl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Sl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=fl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),wl.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()};wl.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;wl.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};wl.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=fl.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));_l.applyCodecParameters({offerRtpParameters:n,answerMediaObject:a}),i={type:"answer",sdp:fl.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),wl.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){wl.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()};wl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();wl.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){wl.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()};wl.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();wl.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){wl.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()};wl.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();wl.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};wl.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()};wl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=fl.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}wl.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=fl.parse(this._pc.localDescription.sdp));const r=_l.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 gl.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')}}hl.Firefox120=Cl;var Pl={};Object.defineProperty(Pl,"__esModule",{value:!0}),Pl.Safari12=void 0;const Tl=hu,kl=bc,Rl=Hc,Il=Uc,Dl=Tu,Al=Ou,Ol=Ru,Nl=Du,Ml=Au,Ll=new gc.Logger("Safari12"),xl={OS:1024,MIS:1024};class Fl extends kl.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 Fl(e),getNativeRtpCapabilities:async()=>{Ll.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}e=void 0;const r=Tl.parse(t.sdp);return Fl.getLocalRtpCapabilities(r)}catch(t){try{e?.close()}catch(e){}throw e=void 0,t}},getNativeSctpCapabilities:async()=>(Ll.debug("getNativeSctpCapabilities()"),{numStreams:xl})}}static getLocalRtpCapabilities(e){const t=Ol.extractRtpCapabilities({sdpObject:e});return Rl.validateAndNormalizeRtpCapabilities(t),Ml.addNackSupportForOpus(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Ll.debug("constructor()"),this._direction=e,this._remoteSdp=new Al.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):(Ll.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Safari12"}close(){if(Ll.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(),Ll.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Ll.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Ll.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Ll.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Ll.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Ll.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,encodings:t,codecOptions:r,codec:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),Ll.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const s=this._remoteSdp.getNextMediaSectionIdx(),o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});i&&i(o.sender);let a=await this._pc.createOffer(),c=Tl.parse(a.sdp);c.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const d=Fl.getLocalRtpCapabilities(c),u=this._getSendExtendedRtpCapabilities(d),l=Rl.getSendingRtpParameters(e.kind,u);l.codecs=Rl.reduceCodecs(l.codecs,n);const p=Rl.getSendingRemoteRtpParameters(e.kind,u);let h;p.codecs=Rl.reduceCodecs(p.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:c});const f=(0,Dl.parse)((t??[{}])[0].scalabilityMode);t&&t.length>1&&(Ll.debug("send() | enabling legacy simulcast"),c=Tl.parse(a.sdp),h=c.media[s.idx],Nl.addLegacySimulcast({offerMediaObject:h,numStreams:t.length}),a={type:"offer",sdp:Tl.write(c)}),Ll.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const m=o.mid;if(l.mid=m,c=Tl.parse(this._pc.localDescription.sdp),h=c.media[s.idx],l.rtcp.cname=Ol.getCname({offerMediaObject:h}),l.encodings=Nl.getRtpEncodings({offerMediaObject:h}),t)for(let e=0;e<l.encodings.length;++e)t[e]&&Object.assign(l.encodings[e],t[e]);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${f.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:h,reuseMid:s.reuseMid,offerRtpParameters:l,answerRtpParameters:p,codecOptions:r});const g={type:"answer",sdp:this._remoteSdp.getSdp()};return Ll.debug("send() | calling pc.setRemoteDescription() [answer:%o]",g),await this._pc.setRemoteDescription(g),this._mapMidTransceiver.set(m,o),{localId:m,rtpParameters:l,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Ll.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();Ll.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Ll.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Ll.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();Ll.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Ll.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Ll.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();Ll.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Ll.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Ll.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Ll.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(),Ll.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();Ll.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Ll.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Ll.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();Ll.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Ll.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};Ll.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%xl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Tl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Ll.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()};Ll.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;Ll.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Ll.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=Tl.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));Ol.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Tl.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Ll.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){Ll.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()};Ll.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Ll.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){Ll.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()};Ll.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Ll.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){Ll.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()};Ll.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Ll.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};Ll.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()};Ll.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Tl.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Ll.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=Tl.parse(this._pc.localDescription.sdp));const r=Ol.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 Il.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')}}Pl.Safari12=Fl;var jl={};Object.defineProperty(jl,"__esModule",{value:!0}),jl.ReactNative106=void 0;const Ul=hu,Bl=bc,Vl=Hc,Wl=Uc,Hl=Tu,ql=Ou,zl=Ru,Gl=Du,Yl=Au,$l=new gc.Logger("ReactNative106"),Jl={OS:1024,MIS:1024};class Kl extends Bl.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 Kl(e),getNativeRtpCapabilities:async()=>{$l.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}e=void 0;const r=Ul.parse(t.sdp);return Kl.getLocalRtpCapabilities(r)}catch(t){try{e?.close()}catch(e){}throw e=void 0,t}},getNativeSctpCapabilities:async()=>($l.debug("getNativeSctpCapabilities()"),{numStreams:Jl})}}static getLocalRtpCapabilities(e){const t=zl.extractRtpCapabilities({sdpObject:e});return Vl.validateAndNormalizeRtpCapabilities(t),Yl.addNackSupportForOpus(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),$l.debug("constructor()"),this._direction=e,this._remoteSdp=new ql.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):($l.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"ReactNative106"}close(){if($l.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(),$l.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),$l.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});$l.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};$l.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};$l.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();$l.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,encodings:t,codecOptions:r,codec:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),$l.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach(((e,t)=>{e.rid=`r${t}`}));const s=this._remoteSdp.getNextMediaSectionIdx(),o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(o.sender);let a=await this._pc.createOffer(),c=Ul.parse(a.sdp);c.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const d=Kl.getLocalRtpCapabilities(c),u=this._getSendExtendedRtpCapabilities(d),l=Vl.getSendingRtpParameters(e.kind,u);l.codecs=Vl.reduceCodecs(l.codecs,n);const p=Vl.getSendingRemoteRtpParameters(e.kind,u);p.codecs=Vl.reduceCodecs(p.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:c});let h=!1;const f=(0,Hl.parse)((t??[{}])[0].scalabilityMode);let m;t&&1===t.length&&f.spatialLayers>1&&"video/vp9"===l.codecs[0].mimeType.toLowerCase()&&($l.debug("send() | enabling legacy simulcast for VP9 SVC"),h=!0,c=Ul.parse(a.sdp),m=c.media[s.idx],Gl.addLegacySimulcast({offerMediaObject:m,numStreams:f.spatialLayers}),a={type:"offer",sdp:Ul.write(c)}),$l.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);let g=o.mid??void 0;if(g||$l.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),l.mid=g,c=Ul.parse(this._pc.localDescription.sdp),m=c.media[s.idx],l.rtcp.cname=zl.getCname({offerMediaObject:m}),t)if(1===t.length){let e=Gl.getRtpEncodings({offerMediaObject:m});Object.assign(e[0],t[0]),h&&(e=[e[0]]),l.encodings=e}else l.encodings=t;else l.encodings=Gl.getRtpEncodings({offerMediaObject:m});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${f.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:m,reuseMid:s.reuseMid,offerRtpParameters:l,answerRtpParameters:p,codecOptions:r});const v={type:"answer",sdp:this._remoteSdp.getSdp()};return $l.debug("send() | calling pc.setRemoteDescription() [answer:%o]",v),await this._pc.setRemoteDescription(v),g||(g=o.mid,l.mid=g),this._mapMidTransceiver.set(g,o),{localId:g,rtpParameters:l,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;$l.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();$l.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};$l.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),$l.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();$l.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};$l.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),$l.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();$l.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};$l.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?$l.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):$l.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(),$l.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();$l.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};$l.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),$l.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();$l.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};$l.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};$l.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Jl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Ul.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),$l.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()};$l.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;$l.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};$l.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=Ul.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));zl.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Ul.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),$l.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){$l.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()};$l.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();$l.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){$l.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()};$l.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();$l.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){$l.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()};$l.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();$l.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};$l.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()};$l.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Ul.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}$l.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=Ul.parse(this._pc.localDescription.sdp));const r=zl.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 Wl.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')}}jl.ReactNative106=Kl,Object.defineProperty(nc,"__esModule",{value:!0}),nc.Device=void 0,nc.detectDevice=dp,nc.detectDeviceAsync=up;const Ql=dc,Zl=bc,Xl=Uc,ep=Wc,tp=Hc,rp=Cd,np=pu,ip=el,sp=hl,op=Pl,ap=jl,cp=new gc.Logger("Device");function dp(e){cp.debug("detectDevice() [userAgent:%s]",e),e||"object"!=typeof navigator||(e=navigator.userAgent);return pp(new Ql.default(e))}async function up(e){cp.debug("detectDeviceAsync() [userAgent:%s]",e),e||"object"!=typeof navigator||(e=navigator.userAgent);return pp(new Ql.default(e))}class lp{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new Zl.EnhancedEventEmitter;static async factory({handlerName:e,handlerFactory:t}={}){if(cp.debug("factory()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!e&&!t&&!(e=await up()))throw new Xl.UnsupportedError("device not supported");return new lp({handlerName:e,handlerFactory:t})}constructor({handlerName:e,handlerFactory:t}={}){if(cp.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)cp.debug("constructor() | handler given: %s",e);else{if(!(e=dp()))throw new Xl.UnsupportedError("device not supported");cp.debug("constructor() | detected handler: %s",e)}switch(e){case"Chrome111":this._handlerFactory=np.Chrome111.createFactory();break;case"Chrome74":this._handlerFactory=ip.Chrome74.createFactory();break;case"Firefox120":this._handlerFactory=sp.Firefox120.createFactory();break;case"Safari12":this._handlerFactory=op.Safari12.createFactory();break;case"ReactNative106":this._handlerFactory=ap.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(){if(!this._loaded)throw new Xl.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new Xl.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e,preferLocalCodecsOrder:t=!1}){if(cp.debug("load() [routerRtpCapabilities:%o]",e),this._loaded)throw new Xl.InvalidStateError("already loaded");const r=ep.clone(e);tp.validateAndNormalizeRtpCapabilities(r);const{getNativeRtpCapabilities:n,getNativeSctpCapabilities:i}=this._handlerFactory,s=ep.clone(await n());tp.validateAndNormalizeRtpCapabilities(s),cp.debug("load() | got native RTP capabilities:%o",s),this._getSendExtendedRtpCapabilities=e=>ep.clone(tp.getExtendedRtpCapabilities(e,r,t));const o=tp.getExtendedRtpCapabilities(s,r,!1);this._recvRtpCapabilities=tp.getRecvRtpCapabilities(o),tp.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities),cp.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),this._canProduceByKind.audio=tp.canSend("audio",this._recvRtpCapabilities),this._canProduceByKind.video=tp.canSend("video",this._recvRtpCapabilities),this._sctpCapabilities=await i(),tp.validateSctpCapabilities(this._sctpCapabilities),cp.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),cp.debug("load() succeeded"),this._loaded=!0}canProduce(e){if(!this._loaded)throw new Xl.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 cp.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 cp.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 Xl.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 rp.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 pp(e){if("object"==typeof navigator&&"ReactNative"===navigator.product)return cp.debug("detectDeviceImpl() | React-Native detected"),"undefined"==typeof RTCPeerConnection||"undefined"==typeof RTCRtpTransceiver?void cp.warn("detectDeviceImpl() | unsupported react-native-webrtc without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?"):"ReactNative106";{const t=e.parseUserAgent(),r=/^\d+/.exec(t?.shortVersion??"0"),n=parseInt(r?.[0]??"0",10),i=t.platform===Ql.KnownPlatforms.iphone||t.platform===Ql.KnownPlatforms.ipad||t.platform===Ql.KnownPlatforms.mac&&(t.isMobile||t.isTablet||"object"==typeof navigator&&navigator?.maxTouchPoints>=2),s=t.isChrome,o=t.isFireFox,a=t.isSafari,c=t.isEdge,d=t.isDesktop&&t.name===Ql.KnownBrowsers.electron,u=t.isWebkit,l={browserMajorVersion:n,isIOS:i,isChrome:s,isFirefox:o,isSafari:a,isElectron:d,isWebkit:u};if(cp.debug("detectDeviceImpl() | detected browser [userAgent:%s, parsed:%o, result:%o]",t.userAgent,t,l),(s||c)&&!i&&n>=111)return"Chrome111";if(s&&!i&&n>=74||c&&!i&&n>=88)return"Chrome74";if(d)return"Chrome111";if(o&&!i&&n>=120)return"Firefox120";if(a&&n>=12&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(i&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(u){const t=e.userAgent?.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(t){return Number(t[1])>=111?"Chrome111":"Chrome74"}return"Chrome111"}return void cp.warn("detectDeviceImpl() | browser not supported [userAgent:%s, parsed:%o, result:%o]",t.userAgent,t,l)}}nc.Device=lp;var hp={},fp={},mp={},gp={};Object.defineProperty(gp,"__esModule",{value:!0}),gp.default="ffffffff-ffff-ffff-ffff-ffffffffffff";var vp={};Object.defineProperty(vp,"__esModule",{value:!0}),vp.default="00000000-0000-0000-0000-000000000000";var yp={},_p={},bp={};Object.defineProperty(bp,"__esModule",{value:!0}),bp.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i,Object.defineProperty(_p,"__esModule",{value:!0});const Ep=bp;_p.default=function(e){return"string"==typeof e&&Ep.default.test(e)},Object.defineProperty(yp,"__esModule",{value:!0});const wp=_p;yp.default=function(e){if(!(0,wp.default)(e))throw TypeError("Invalid UUID");let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,255&t,(t=parseInt(e.slice(9,13),16))>>>8,255&t,(t=parseInt(e.slice(14,18),16))>>>8,255&t,(t=parseInt(e.slice(19,23),16))>>>8,255&t,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,255&t)};var Sp={};Object.defineProperty(Sp,"__esModule",{value:!0}),Sp.unsafeStringify=void 0;const Cp=_p,Pp=[];for(let e=0;e<256;++e)Pp.push((e+256).toString(16).slice(1));function Tp(e,t=0){return(Pp[e[t+0]]+Pp[e[t+1]]+Pp[e[t+2]]+Pp[e[t+3]]+"-"+Pp[e[t+4]]+Pp[e[t+5]]+"-"+Pp[e[t+6]]+Pp[e[t+7]]+"-"+Pp[e[t+8]]+Pp[e[t+9]]+"-"+Pp[e[t+10]]+Pp[e[t+11]]+Pp[e[t+12]]+Pp[e[t+13]]+Pp[e[t+14]]+Pp[e[t+15]]).toLowerCase()}Sp.unsafeStringify=Tp,Sp.default=function(e,t=0){const r=Tp(e,t);if(!(0,Cp.default)(r))throw TypeError("Stringified UUID is invalid");return r};var kp={},Rp={};let Ip;Object.defineProperty(Rp,"__esModule",{value:!0});const Dp=new Uint8Array(16);Rp.default=function(){if(!Ip){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ip=crypto.getRandomValues.bind(crypto)}return Ip(Dp)},Object.defineProperty(kp,"__esModule",{value:!0}),kp.updateV1State=void 0;const Ap=Rp,Op=Sp,Np={};function Mp(e,t,r){return e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0),e.node||(e.node=r.slice(10,16),e.node[0]|=1,e.clockseq=16383&(r[8]<<8|r[9])),e.msecs=t,e}function Lp(e,t,r,n,i,s,o=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(s){if(o<0||o+16>s.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`)}else s=new Uint8Array(16),o=0;t??=Date.now(),r??=0,n??=16383&(e[8]<<8|e[9]),i??=e.slice(10,16);const a=(1e4*(268435455&(t+=122192928e5))+r)%4294967296;s[o++]=a>>>24&255,s[o++]=a>>>16&255,s[o++]=a>>>8&255,s[o++]=255&a;const c=t/4294967296*1e4&268435455;s[o++]=c>>>8&255,s[o++]=255&c,s[o++]=c>>>24&15|16,s[o++]=c>>>16&255,s[o++]=n>>>8|128,s[o++]=255&n;for(let e=0;e<6;++e)s[o++]=i[e];return s}kp.updateV1State=Mp,kp.default=function(e,t,r){let n;const i=e?._v6??!1;if(e){const t=Object.keys(e);1===t.length&&"_v6"===t[0]&&(e=void 0)}if(e)n=Lp(e.random??e.rng?.()??(0,Ap.default)(),e.msecs,e.nsecs,e.clockseq,e.node,t,r);else{const e=Date.now(),s=(0,Ap.default)();Mp(Np,e,s),n=Lp(s,Np.msecs,Np.nsecs,i?void 0:Np.clockseq,i?void 0:Np.node,t,r)}return t??(0,Op.unsafeStringify)(n)};var xp={};Object.defineProperty(xp,"__esModule",{value:!0});const Fp=yp,jp=Sp;xp.default=function(e){const t=function(e){return Uint8Array.of((15&e[6])<<4|e[7]>>4&15,(15&e[7])<<4|(240&e[4])>>4,(15&e[4])<<4|(240&e[5])>>4,(15&e[5])<<4|(240&e[0])>>4,(15&e[0])<<4|(240&e[1])>>4,(15&e[1])<<4|(240&e[2])>>4,96|15&e[2],e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}("string"==typeof e?(0,Fp.default)(e):e);return"string"==typeof e?(0,jp.unsafeStringify)(t):t};var Up={},Bp={};function Vp(e){return 14+(e+64>>>9<<4)+1}function Wp(e,t){const r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function Hp(e,t,r,n,i,s){return Wp((o=Wp(Wp(t,e),Wp(n,s)))<<(a=i)|o>>>32-a,r);var o,a}function qp(e,t,r,n,i,s,o){return Hp(t&r|~t&n,e,t,i,s,o)}function zp(e,t,r,n,i,s,o){return Hp(t&n|r&~n,e,t,i,s,o)}function Gp(e,t,r,n,i,s,o){return Hp(t^r^n,e,t,i,s,o)}function Yp(e,t,r,n,i,s,o){return Hp(r^(t|~n),e,t,i,s,o)}Object.defineProperty(Bp,"__esModule",{value:!0}),Bp.default=function(e){const t=function(e){if(0===e.length)return new Uint32Array;const t=new Uint32Array(Vp(8*e.length)).fill(0);for(let r=0;r<e.length;r++)t[r>>2]|=(255&e[r])<<r%4*8;return t}(e),r=function(e,t){const r=new Uint32Array(Vp(t)).fill(0);r.set(e),r[t>>5]|=128<<t%32,r[r.length-1]=t,e=r;let n=1732584193,i=-271733879,s=-1732584194,o=271733878;for(let t=0;t<e.length;t+=16){const r=n,a=i,c=s,d=o;n=qp(n,i,s,o,e[t],7,-680876936),o=qp(o,n,i,s,e[t+1],12,-389564586),s=qp(s,o,n,i,e[t+2],17,606105819),i=qp(i,s,o,n,e[t+3],22,-1044525330),n=qp(n,i,s,o,e[t+4],7,-176418897),o=qp(o,n,i,s,e[t+5],12,1200080426),s=qp(s,o,n,i,e[t+6],17,-1473231341),i=qp(i,s,o,n,e[t+7],22,-45705983),n=qp(n,i,s,o,e[t+8],7,1770035416),o=qp(o,n,i,s,e[t+9],12,-1958414417),s=qp(s,o,n,i,e[t+10],17,-42063),i=qp(i,s,o,n,e[t+11],22,-1990404162),n=qp(n,i,s,o,e[t+12],7,1804603682),o=qp(o,n,i,s,e[t+13],12,-40341101),s=qp(s,o,n,i,e[t+14],17,-1502002290),i=qp(i,s,o,n,e[t+15],22,1236535329),n=zp(n,i,s,o,e[t+1],5,-165796510),o=zp(o,n,i,s,e[t+6],9,-1069501632),s=zp(s,o,n,i,e[t+11],14,643717713),i=zp(i,s,o,n,e[t],20,-373897302),n=zp(n,i,s,o,e[t+5],5,-701558691),o=zp(o,n,i,s,e[t+10],9,38016083),s=zp(s,o,n,i,e[t+15],14,-660478335),i=zp(i,s,o,n,e[t+4],20,-405537848),n=zp(n,i,s,o,e[t+9],5,568446438),o=zp(o,n,i,s,e[t+14],9,-1019803690),s=zp(s,o,n,i,e[t+3],14,-187363961),i=zp(i,s,o,n,e[t+8],20,1163531501),n=zp(n,i,s,o,e[t+13],5,-1444681467),o=zp(o,n,i,s,e[t+2],9,-51403784),s=zp(s,o,n,i,e[t+7],14,1735328473),i=zp(i,s,o,n,e[t+12],20,-1926607734),n=Gp(n,i,s,o,e[t+5],4,-378558),o=Gp(o,n,i,s,e[t+8],11,-2022574463),s=Gp(s,o,n,i,e[t+11],16,1839030562),i=Gp(i,s,o,n,e[t+14],23,-35309556),n=Gp(n,i,s,o,e[t+1],4,-1530992060),o=Gp(o,n,i,s,e[t+4],11,1272893353),s=Gp(s,o,n,i,e[t+7],16,-155497632),i=Gp(i,s,o,n,e[t+10],23,-1094730640),n=Gp(n,i,s,o,e[t+13],4,681279174),o=Gp(o,n,i,s,e[t],11,-358537222),s=Gp(s,o,n,i,e[t+3],16,-722521979),i=Gp(i,s,o,n,e[t+6],23,76029189),n=Gp(n,i,s,o,e[t+9],4,-640364487),o=Gp(o,n,i,s,e[t+12],11,-421815835),s=Gp(s,o,n,i,e[t+15],16,530742520),i=Gp(i,s,o,n,e[t+2],23,-995338651),n=Yp(n,i,s,o,e[t],6,-198630844),o=Yp(o,n,i,s,e[t+7],10,1126891415),s=Yp(s,o,n,i,e[t+14],15,-1416354905),i=Yp(i,s,o,n,e[t+5],21,-57434055),n=Yp(n,i,s,o,e[t+12],6,1700485571),o=Yp(o,n,i,s,e[t+3],10,-1894986606),s=Yp(s,o,n,i,e[t+10],15,-1051523),i=Yp(i,s,o,n,e[t+1],21,-2054922799),n=Yp(n,i,s,o,e[t+8],6,1873313359),o=Yp(o,n,i,s,e[t+15],10,-30611744),s=Yp(s,o,n,i,e[t+6],15,-1560198380),i=Yp(i,s,o,n,e[t+13],21,1309151649),n=Yp(n,i,s,o,e[t+4],6,-145523070),o=Yp(o,n,i,s,e[t+11],10,-1120210379),s=Yp(s,o,n,i,e[t+2],15,718787259),i=Yp(i,s,o,n,e[t+9],21,-343485551),n=Wp(n,r),i=Wp(i,a),s=Wp(s,c),o=Wp(o,d)}return Uint32Array.of(n,i,s,o)}(t,8*e.length);return function(e){const t=new Uint8Array(4*e.length);for(let r=0;r<4*e.length;r++)t[r]=e[r>>2]>>>r%4*8&255;return t}(r)};var $p={};Object.defineProperty($p,"__esModule",{value:!0}),$p.URL=$p.DNS=$p.stringToBytes=void 0;const Jp=yp,Kp=Sp;function Qp(e){e=unescape(encodeURIComponent(e));const t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}$p.stringToBytes=Qp,$p.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",$p.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",$p.default=function(e,t,r,n,i,s){const o="string"==typeof r?Qp(r):r,a="string"==typeof n?(0,Jp.default)(n):n;if("string"==typeof n&&(n=(0,Jp.default)(n)),16!==n?.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+o.length);if(c.set(a),c.set(o,a.length),c=t(c),c[6]=15&c[6]|e,c[8]=63&c[8]|128,i){s=s||0;for(let e=0;e<16;++e)i[s+e]=c[e];return i}return(0,Kp.unsafeStringify)(c)},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.URL=e.DNS=void 0;const t=Bp,r=$p;var n=$p;function i(e,n,i,s){return(0,r.default)(48,t.default,e,n,i,s)}Object.defineProperty(e,"DNS",{enumerable:!0,get:function(){return n.DNS}}),Object.defineProperty(e,"URL",{enumerable:!0,get:function(){return n.URL}}),i.DNS=r.DNS,i.URL=r.URL,e.default=i}(Up);var Zp={},Xp={};Object.defineProperty(Xp,"__esModule",{value:!0});const eh="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);Xp.default={randomUUID:eh},Object.defineProperty(Zp,"__esModule",{value:!0});const th=Xp,rh=Rp,nh=Sp;Zp.default=function(e,t,r){if(th.default.randomUUID&&!t&&!e)return th.default.randomUUID();const n=(e=e||{}).random??e.rng?.()??(0,rh.default)();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){if((r=r||0)<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=n[e];return t}return(0,nh.unsafeStringify)(n)};var ih={},sh={};function oh(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:case 3:return t^r^n;case 2:return t&r^t&n^r&n}}function ah(e,t){return e<<t|e>>>32-t}Object.defineProperty(sh,"__esModule",{value:!0}),sh.default=function(e){const t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(e.length+1);n.set(e),n[e.length]=128;const i=(e=n).length/4+2,s=Math.ceil(i/16),o=new Array(s);for(let t=0;t<s;++t){const r=new Uint32Array(16);for(let n=0;n<16;++n)r[n]=e[64*t+4*n]<<24|e[64*t+4*n+1]<<16|e[64*t+4*n+2]<<8|e[64*t+4*n+3];o[t]=r}o[s-1][14]=8*(e.length-1)/Math.pow(2,32),o[s-1][14]=Math.floor(o[s-1][14]),o[s-1][15]=8*(e.length-1)&4294967295;for(let e=0;e<s;++e){const n=new Uint32Array(80);for(let t=0;t<16;++t)n[t]=o[e][t];for(let e=16;e<80;++e)n[e]=ah(n[e-3]^n[e-8]^n[e-14]^n[e-16],1);let i=r[0],s=r[1],a=r[2],c=r[3],d=r[4];for(let e=0;e<80;++e){const r=Math.floor(e/20),o=ah(i,5)+oh(r,s,a,c)+d+t[r]+n[e]>>>0;d=c,c=a,a=ah(s,30)>>>0,s=i,i=o}r[0]=r[0]+i>>>0,r[1]=r[1]+s>>>0,r[2]=r[2]+a>>>0,r[3]=r[3]+c>>>0,r[4]=r[4]+d>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.URL=e.DNS=void 0;const t=sh,r=$p;var n=$p;function i(e,n,i,s){return(0,r.default)(80,t.default,e,n,i,s)}Object.defineProperty(e,"DNS",{enumerable:!0,get:function(){return n.DNS}}),Object.defineProperty(e,"URL",{enumerable:!0,get:function(){return n.URL}}),i.DNS=r.DNS,i.URL=r.URL,e.default=i}(ih);var ch={};Object.defineProperty(ch,"__esModule",{value:!0});const dh=Sp,uh=kp,lh=xp;ch.default=function(e,t,r){e??={},r??=0;let n=(0,uh.default)({...e,_v6:!0},new Uint8Array(16));if(n=(0,lh.default)(n),t){for(let e=0;e<16;e++)t[r+e]=n[e];return t}return(0,dh.unsafeStringify)(n)};var ph={};Object.defineProperty(ph,"__esModule",{value:!0});const hh=yp,fh=Sp;ph.default=function(e){const t=function(e){return Uint8Array.of((15&e[3])<<4|e[4]>>4&15,(15&e[4])<<4|(240&e[5])>>4,(15&e[5])<<4|15&e[6],e[7],(15&e[1])<<4|(240&e[2])>>4,(15&e[2])<<4|(240&e[3])>>4,16|(240&e[0])>>4,(15&e[0])<<4|(240&e[1])>>4,e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}("string"==typeof e?(0,hh.default)(e):e);return"string"==typeof e?(0,fh.unsafeStringify)(t):t};var mh={};Object.defineProperty(mh,"__esModule",{value:!0}),mh.updateV7State=void 0;const gh=Rp,vh=Sp,yh={};function _h(e,t,r){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],e.msecs=t):(e.seq=e.seq+1|0,0===e.seq&&e.msecs++),e}function bh(e,t,r,n,i=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(n){if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`)}else n=new Uint8Array(16),i=0;return t??=Date.now(),r??=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9],n[i++]=t/1099511627776&255,n[i++]=t/4294967296&255,n[i++]=t/16777216&255,n[i++]=t/65536&255,n[i++]=t/256&255,n[i++]=255&t,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|3&e[10],n[i++]=e[11],n[i++]=e[12],n[i++]=e[13],n[i++]=e[14],n[i++]=e[15],n}mh.updateV7State=_h,mh.default=function(e,t,r){let n;if(e)n=bh(e.random??e.rng?.()??(0,gh.default)(),e.msecs,e.seq,t,r);else{const e=Date.now(),i=(0,gh.default)();_h(yh,e,i),n=bh(i,yh.msecs,yh.seq,t,r)}return t??(0,vh.unsafeStringify)(n)};var Eh={};Object.defineProperty(Eh,"__esModule",{value:!0});const wh=_p;Eh.default=function(e){if(!(0,wh.default)(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.version=e.validate=e.v7=e.v6ToV1=e.v6=e.v5=e.v4=e.v3=e.v1ToV6=e.v1=e.stringify=e.parse=e.NIL=e.MAX=void 0;var t=gp;Object.defineProperty(e,"MAX",{enumerable:!0,get:function(){return t.default}});var r=vp;Object.defineProperty(e,"NIL",{enumerable:!0,get:function(){return r.default}});var n=yp;Object.defineProperty(e,"parse",{enumerable:!0,get:function(){return n.default}});var i=Sp;Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return i.default}});var s=kp;Object.defineProperty(e,"v1",{enumerable:!0,get:function(){return s.default}});var o=xp;Object.defineProperty(e,"v1ToV6",{enumerable:!0,get:function(){return o.default}});var a=Up;Object.defineProperty(e,"v3",{enumerable:!0,get:function(){return a.default}});var c=Zp;Object.defineProperty(e,"v4",{enumerable:!0,get:function(){return c.default}});var d=ih;Object.defineProperty(e,"v5",{enumerable:!0,get:function(){return d.default}});var u=ch;Object.defineProperty(e,"v6",{enumerable:!0,get:function(){return u.default}});var l=ph;Object.defineProperty(e,"v6ToV1",{enumerable:!0,get:function(){return l.default}});var p=mh;Object.defineProperty(e,"v7",{enumerable:!0,get:function(){return p.default}});var h=_p;Object.defineProperty(e,"validate",{enumerable:!0,get:function(){return h.default}});var f=Eh;Object.defineProperty(e,"version",{enumerable:!0,get:function(){return f.default}})}(mp);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].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 Ch={};Object.defineProperty(Ch,"__esModule",{value:!0}),Ch.FakeEvent=void 0;Ch.FakeEvent=class{NONE=0;CAPTURING_PHASE=1;AT_TARGET=2;BUBBLING_PHASE=3;type;bubbles;cancelable;defaultPrevented=!1;composed=!1;currentTarget=null;eventPhase=l.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 Ph={};Object.defineProperty(Ph,"__esModule",{value:!0}),Ph.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(fp,"__esModule",{value:!0}),fp.FakeMediaStreamTrack=void 0;const Th=mp,kh=Sh,Rh=Ch,Ih=Ph;class Dh extends kh.FakeEventTarget{#b;#E;#w;#S;#C;#P;#T;#k;#R;#I;#D;#A=null;#O=null;#N=null;#M=null;#L=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.#b=t??(0,Th.v4)(),this.#E=e,this.#w=r??"",this.#T=n??"",this.#C=i??!0,this.#P=s??!1,this.#S=o??"live",this.#k=a??{},this.#R=c??{},this.#I=d??{},this.#D=u??{}}get id(){return this.#b}get kind(){return this.#E}get label(){return this.#w}get contentHint(){return this.#T}set contentHint(e){this.#T=e}get enabled(){return this.#C}set enabled(e){const t=this.#C!==e;this.#C=e,t&&this.dispatchEvent(new Rh.FakeEvent("enabledchange"))}get muted(){return this.#P}get readyState(){return this.#S}get data(){return this.#D}set data(e){this.#D=e}get onmute(){return this.#A}set onmute(e){this.#A&&this.removeEventListener("mute",this.#A),this.#A=e,e&&this.addEventListener("mute",e)}get onunmute(){return this.#O}set onunmute(e){this.#O&&this.removeEventListener("unmute",this.#O),this.#O=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.#M}set onenabledchange(e){this.#M&&this.removeEventListener("enabledchange",this.#M),this.#M=e,e&&this.addEventListener("enabledchange",e)}get onstopped(){return this.#L}set onstopped(e){this.#L&&this.removeEventListener("stopped",this.#L),this.#L=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.#S&&(this.#S="ended",this.dispatchEvent(new Rh.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new Dh({id:e??(0,Th.v4)(),kind:this.#E,label:this.#w,contentHint:this.#T,enabled:this.#C,muted:this.#P,readyState:this.#S,capabilities:(0,Ih.clone)(this.#k),constraints:(0,Ih.clone)(this.#R),settings:(0,Ih.clone)(this.#I),data:t??(0,Ih.clone)(this.#D)})}getCapabilities(){return this.#k}getConstraints(){return this.#R}async applyConstraints(e={}){return this.#R=e,Promise.resolve()}getSettings(){return this.#I}remoteStop(){"ended"!==this.#S&&(this.#S="ended",this.dispatchEvent(new Rh.FakeEvent("stopped")),this.dispatchEvent(new Rh.FakeEvent("ended")))}remoteMute(){this.#P||(this.#P=!0,this.dispatchEvent(new Rh.FakeEvent("mute")))}remoteUnmute(){this.#P&&(this.#P=!1,this.dispatchEvent(new Rh.FakeEvent("unmute")))}}fp.FakeMediaStreamTrack=Dh;var Ah={};Object.defineProperty(Ah,"__esModule",{value:!0}),Ah.FakeEventTarget=void 0;Ah.FakeEventTarget=class{listeners={};addEventListener(e,t,r){t&&(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(hp,"__esModule",{value:!0}),hp.FakeHandler=void 0;const Oh=fp,Nh=bc,Mh=Wc,Lh=Hc,xh=Uc,Fh=Ah,jh=new gc.Logger("FakeHandler");class Uh extends Nh.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${Mh.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:"FakeHandler",factory:t=>new Uh(t,e),getNativeRtpCapabilities:async()=>(jh.debug("getNativeRtpCapabilities()"),Uh.getLocalRtpCapabilities(e)),getNativeSctpCapabilities:async()=>(jh.debug("getNativeSctpCapabilities()"),e.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(e){const t=e.generateNativeRtpCapabilities();return Lh.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),jh.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return"FakeHandler"}close(){jh.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(),jh.debug("updateIceServers()")}async restartIce(e){this.assertNotClosed(),jh.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:e,encodings:t,codecOptions:r,codec:n}){this.assertNotClosed(),jh.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});const i=Uh.getLocalRtpCapabilities(this._fakeParameters),s=this._getSendExtendedRtpCapabilities(i),o=Lh.getSendingRtpParameters(e.kind,s);o.codecs=Lh.reduceCodecs(o.codecs,n);const a=o.codecs.some((e=>/.+\/rtx$/i.test(e.mimeType)));o.mid=`mid-${Mh.generateRandomNumber()}`,t||(t=[{}]);for(const e of t)e.ssrc=Mh.generateRandomNumber(),a&&(e.rtx={ssrc:Mh.generateRandomNumber()});o.encodings=t,o.rtcp={cname:this._cname,reducedSize:!0,mux:!0};const c=this._nextLocalId++;return this._tracks.set(c,e),{localId:String(c),rtpParameters:o}}async stopSending(e){if(jh.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?jh.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):jh.debug("replaceTrack() [localId:%s, no track]",e),this._tracks.delete(Number(e)),this._tracks.set(Number(e),t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),jh.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),jh.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"}),jh.debug("sendDataChannel()");return{dataChannel:new Bh({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"}),jh.debug("receive() [trackId:%s, kind:%s]",e,n);const i=this._nextLocalId++,s=new Oh.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)jh.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"}),jh.debug("receiveDataChannel()");return{dataChannel:new Bh({id:e.streamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:t,protocol:r})}}async setupTransport({localDtlsRole:e,localSdpObject:t}){const r=Mh.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 xh.InvalidStateError("method called in a closed handler")}}hp.FakeHandler=Uh;class Bh extends Fh.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(),jh.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 xh.InvalidStateError("not open")}}var Vh={};Object.defineProperty(Vh,"__esModule",{value:!0}),Vh.generateRouterRtpCapabilities=function(){return Wh.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"}]})},Vh.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}]}},Vh.generateNativeSctpCapabilities=function(){return Wh.deepFreeze({numStreams:{OS:2048,MIS:2048}})},Vh.generateLocalDtlsParameters=function(){return Wh.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"})},Vh.generateTransportRemoteParameters=function(){return{id:Hh(),iceParameters:Wh.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:Wh.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:Wh.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:Wh.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}},Vh.generateProducerRemoteParameters=function(){return Wh.deepFreeze({id:Hh()})},Vh.generateConsumerRemoteParameters=function({id:e,codecMimeType:t}={}){switch(t){case"audio/opus":return{id:e??Hh(),producerId:Hh(),kind:"audio",rtpParameters:Wh.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??Hh(),producerId:Hh(),kind:"audio",rtpParameters:Wh.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??Hh(),producerId:Hh(),kind:"video",rtpParameters:Wh.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??Hh(),producerId:Hh(),kind:"video",rtpParameters:Wh.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}'`)}},Vh.generateDataProducerRemoteParameters=function(){return Wh.deepFreeze({id:Hh()})},Vh.generateDataConsumerRemoteParameters=function({id:e}={}){return{id:e??Hh(),dataProducerId:Hh(),sctpStreamParameters:Wh.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}};const Wh=Wc;function Hh(){return String(Wh.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=$a.exports;e.debug=t.default,e.types=rc,e.version="3.15.6";var r=nc;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=Tu;Object.defineProperty(e,"parseScalabilityMode",{enumerable:!0,get:function(){return n.parse}}),e.ortc=Hc,e.enhancedEvents=bc;var i=hp;Object.defineProperty(e,"FakeHandler",{enumerable:!0,get:function(){return i.FakeHandler}}),e.testFakeParameters=Vh}(Ya);const qh=[{scaleResolutionDownBy:4,maxBitrate:15e4,maxFramerate:12},{scaleResolutionDownBy:2,maxBitrate:35e4,maxFramerate:18},{scaleResolutionDownBy:1,maxBitrate:9e5,maxFramerate:24}],zh=[{maxBitrate:1e6,dtx:!0}],Gh=[{maxBitrate:4e4,dtx:!0}],Yh={width:1280,height:720},$h=0,Jh=2,Kh=0;function Qh(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 Zh(e,t){e.onreadystatechange=function(){"complete"!=this.readyState&&"loaded"!=this.readyState||(this.onreadystatechange=null,t(null,e))}}const Xh=new Bn,ef=e=>a(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?Qh:Zh)(i,r),i.onload||Qh(i,r),n.appendChild(i)}(e,((e,n)=>{e?r(e):t(n)}))}))})),tf=(e,...t)=>a(void 0,[e,...t],void 0,(function*(e,t=3,r=500){let n=0;for(;n<t;)try{return void(yield ef(e))}catch(e){if(n+=1,!(n<t))throw e;yield Xh.sleepMs(r)}}));var rf;let nf=class{constructor(){rf.set(this,new Map)}add(e,t,r){const n=this.getKey(e,t);if(c(this,rf,"f").has(n))throw new Error("Attempt to rewrite cached track processor");c(this,rf,"f").set(n,r)}get(e,t){return c(this,rf,"f").get(this.getKey(e,t))}has(e,t){return c(this,rf,"f").has(this.getKey(e,t))}getKey(e,t){return`${e}:${t}`}reset(){for(const e of c(this,rf,"f").values())e.stopProcessing(),e.release();c(this,rf,"f").clear()}};var sf,of;rf=new WeakMap,nf=i([at()],nf);let af=class{constructor(e,t,r,n){this.config=e,this.processorsCache=t,this.audioTrackProcessorFactory=r,sf.set(this,new Map),of.set(this,void 0),d(this,of,n("IntegrationsService"),"f")}init(){const e=this.config.get("denoiser");if("asdk"===e){c(this,of,"f").info("Start integration of ASDK",{denoiser:e});const t={integrated:!1,initPromise:this.integrateASDK()};c(this,sf,"f").set("asdk",t)}else{c(this,of,"f").info("Start integration of RNNoise",{denoiser:e});const t={integrated:!1,initPromise:this.integrateRNNoise()};c(this,sf,"f").set("rnnoise",t)}}integrateASDK(){return a(this,void 0,void 0,(function*(){const e=this.config.get("asdk"),t=this.config.get("staticFilesPath");if(!window.atsvb){const s=`https://effectssdk.ai/sdk/audio/dev/${e.version}/atsvb-web.js`;let o=s;if(e.localDir){const n=`${e.localDir}/${e.version}/atsvb-web.js`;o=new r(n,t).href}yield(n=o,i=s,a(void 0,void 0,void 0,(function*(){try{yield tf(n)}catch(e){if(!i)throw e;yield tf(i)}})))}var n,i;if(!window.atsvb)throw c(this,of,"f").info("Audio Effects SDK is not loaded, skipping initialization",{case:"initAudioSDK"}),new Error("windows.atsvb is still missing");const s=this.audioTrackProcessorFactory({trackLabel:zn.Microphone});yield s.init(),this.processorsCache.add("asdk",zn.Microphone,s);const o=c(this,sf,"f").get("asdk");if(!o)throw Error("IntegrationContext is missing for ASDK");o.integrated=!0}))}get audio(){return"asdk"===this.config.get("denoiser")?this.getASDKState():this.getRNNoiseState()}getASDKState(){var e,t;const r=c(this,sf,"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=c(this,sf,"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 a(this,void 0,void 0,(function*(){const e=yield function(e){return a(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:zn.Microphone,noiseSuppressor:e});this.processorsCache.add("rnnoise",zn.Microphone,t);const r=c(this,sf,"f").get("rnnoise");if(!r)throw Error("IntegrationContext is missing for RNNoise");r.integrated=!0}))}reset(){c(this,sf,"f").clear()}};var cf,df,uf,lf,pf,hf,ff,mf,gf;sf=new WeakMap,of=new WeakMap,af=i([at(),s(0,dt(Hn.Config)),s(1,dt(Hn.ProcessorsCache)),s(2,dt(Hn.AudioTrackProcessorFactory)),s(3,dt(Hn.LoggerFactory)),o("design:paramtypes",[Pt,nf,Function,Function])],af),function(e){e.INFO="info",e.WARNING="warning",e.ERROR="error"}(mf||(mf={})),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"}(gf||(gf={}));class vf{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,void 0);const{loggerFactory:t}=e;if(d(this,df,t("EffectsSDKTrackProcessor"),"f"),d(this,ff,e.onModelsLoaded,"f"),!e.customerId)throw new Error("Customer ID must be provided");d(this,cf,new window.tsvb(e.customerId),"f"),c(this,cf,"f").onError(this.tsvbErrorHandler.bind(this)),c(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.5.8"}`:`https://effectssdk.ai/sdk/web/${null!=i?i:"3.5.8"}`,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`}};c(this,cf,"f").config(o)}init(){return a(this,void 0,void 0,(function*(){yield c(this,cf,"f").preload(),yield c(this,cf,"f").cache(),d(this,hf,!0,"f")}))}awaitReady(){return a(this,void 0,void 0,(function*(){yield new Promise(((e,t)=>{const r=Date.now(),n=setInterval((()=>{if(this.isModelsLoaded)return clearInterval(n),void e();Date.now()-r>6e4&&(clearInterval(n),t(new Error("ESDK init timeout")))}),100)}))}))}tsvbErrorHandler(e){var t;const{emitter:r,type:i}=e,s=n(e,["emitter","type"]),o=null!=r?r:"N/A emitter";i===mf.ERROR&&c(this,df,"f").error(o,Object.assign({error:pr(e)},s)),i===mf.WARNING&&c(this,df,"f").warn(o,Object.assign({},s)),i===mf.INFO&&c(this,df,"f").info(o,Object.assign({},s)),r===gf.ML_INFERENCE&&(s.message.toLocaleLowerCase().includes("init lowlighter")&&(c(this,uf,"f").lowLighter=!0),s.message.toLocaleLowerCase().includes("init colorcorrector")&&(c(this,uf,"f").colorCorrector=!0),s.message.toLocaleLowerCase().includes("init facedetector")&&(c(this,uf,"f").faceDetector=!0),s.message.toLocaleLowerCase().includes("init segmentation")&&(c(this,uf,"f").segmentation=!0),this.isModelsLoaded&&(null===(t=c(this,ff,"f"))||void 0===t||t.call(this)))}get isModelsLoaded(){return c(this,uf,"f").colorCorrector&&c(this,uf,"f").faceDetector&&c(this,uf,"f").lowLighter&&c(this,uf,"f").segmentation}get modelsLoadProgress(){return Object.values(c(this,uf,"f")).filter(Boolean).length/Object.keys(c(this,uf,"f")).length}get isReady(){return c(this,hf,"f")}setOnLoadModels(e){d(this,ff,e,"f"),this.isModelsLoaded&&c(this,ff,"f").call(this)}onReady(){d(this,hf,!0,"f"),c(this,df,"f").debug("onReady()",{description:"ESDK is ready"}),this.updateEffects(c(this,pf,"f"))}processTrack(e){var t,r,n;if(c(this,lf,"f")===e||"ended"===e.readyState)return null!==(r=null===(t=c(this,cf,"f").getStream())||void 0===t?void 0:t.getVideoTracks()[0])&&void 0!==r?r:e;this.stopProcessing();try{c(this,cf,"f").useStream(new MediaStream([e]));const t=null===(n=c(this,cf,"f").getStream())||void 0===n?void 0:n.getVideoTracks()[0];return t?(d(this,lf,e,"f"),t):e}catch(t){throw c(this,df,"f").error("processTrack()",{error:t,track:e}),new Error("Can not process this track")}}stopProcessing(){try{c(this,cf,"f").clear(),c(this,cf,"f").stop()}catch(e){c(this,df,"f").error("stopProcessing()",{error:e})}finally{d(this,lf,null,"f")}}updateEffects(e){var t,r,n,i,s,o,a,u,l,p,h,f,m,g,v,y,_,b,E,w,S,C;if(d(this,pf,e,"f"),!c(this,hf,"f"))return void c(this,df,"f").warn("updateEffects()",{description:"Esdk not ready"});if(!c(this,pf,"f")||0===Object.keys(c(this,pf,"f")).length)return void c(this,cf,"f").stop();let P=0;if((null===(t=c(this,pf,"f"))||void 0===t?void 0:t.blur)&&!(null===(r=c(this,pf,"f"))||void 0===r?void 0:r.backgroundColor)?(c(this,cf,"f").setBlur(c(this,pf,"f").blur),P+=1):c(this,cf,"f").clearBlur(),void 0!==(null===(n=c(this,pf,"f"))||void 0===n?void 0:n.background)?(c(this,cf,"f").setBackground(c(this,pf,"f").background),P+=1):void 0!==(null===(i=c(this,pf,"f"))||void 0===i?void 0:i.backgroundColor)?(c(this,cf,"f").setBackgroundColor(null===(s=c(this,pf,"f"))||void 0===s?void 0:s.backgroundColor),c(this,cf,"f").setBackground("color"),P+=1):c(this,cf,"f").clearBackground(),(null===(o=c(this,pf,"f"))||void 0===o?void 0:o.beautification)?(c(this,cf,"f").enableBeautification(),c(this,cf,"f").setBeautificationLevel(c(this,pf,"f").beautification),P+=1):c(this,cf,"f").disableBeautification(),(null===(a=c(this,pf,"f"))||void 0===a?void 0:a.lowLightEffect)?(c(this,cf,"f").enableLowLightEffect(),c(this,cf,"f").setLowLightEffectPower(c(this,pf,"f").lowLightEffect),P+=1):c(this,cf,"f").disableLowLightEffect(),(null===(u=c(this,pf,"f"))||void 0===u?void 0:u.colorCorrector)?(c(this,cf,"f").enableColorCorrector(),c(this,cf,"f").setColorCorrectorPower(c(this,pf,"f").colorCorrector),P+=1):c(this,cf,"f").disableColorCorrector(),(null===(l=c(this,pf,"f"))||void 0===l?void 0:l.smartZoom)?(c(this,cf,"f").enableSmartZoom(),c(this,cf,"f").setFaceArea(c(this,pf,"f").smartZoom),P+=1):c(this,cf,"f").disableSmartZoom(),(null===(p=c(this,pf,"f"))||void 0===p?void 0:p.layout)?(c(this,cf,"f").setLayout(c(this,pf,"f").layout),P+=1):c(this,cf,"f").setLayout("center"),(null===(h=c(this,pf,"f"))||void 0===h?void 0:h.colorFilter)&&(null===(f=c(this,pf,"f"))||void 0===f?void 0:f.colorFilter.power)&&(null===(m=c(this,pf,"f"))||void 0===m?void 0:m.colorFilter.url)?(c(this,cf,"f").setColorFilterConfig({lut:c(this,pf,"f").colorFilter.url,power:c(this,pf,"f").colorFilter.power}),c(this,cf,"f").enableColorFilter(),P+=1):c(this,cf,"f").disableColorFilter(),null===(g=c(this,pf,"f"))||void 0===g?void 0:g.lowerThird){const e=c(this,cf,"f").createComponent({component:c(this,pf,"f").lowerThird.type,options:null!==(v=c(this,pf,"f").lowerThird.options)&&void 0!==v?v:{}});null===(b=null===(_=null===(y=c(this,cf,"f").components)||void 0===y?void 0:y.lowerThird)||void 0===_?void 0:_.hideLowerThird)||void 0===b||b.call(_),c(this,cf,"f").addComponent(e,"lowerThird"),c(this,cf,"f").components.lowerThird.showLowerThird(),P+=1}else null===(S=null===(w=null===(E=c(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=c(this,pf,"f"))||void 0===C?void 0:C.sharpness)?(c(this,cf,"f").setSharpnessEffectConfig(c(this,pf,"f").sharpness),P+=1):c(this,cf,"f").disableSharpnessEffect(),P>2?c(this,cf,"f").enableFrameSkipping():c(this,cf,"f").disableFrameSkipping(),c(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;const yf=e=>"rtx"!==e.mimeType;var _f,bf,Ef,wf,Sf,Cf,Pf,Tf,kf,Rf,If,Df,Af,Of,Nf,Mf,Lf;class xf{constructor({track:e,statsHandler:t}){_f.set(this,void 0),bf.set(this,void 0),this.handleWebRTCStats(e,t)}get videoWebRTCStats(){return c(this,_f,"f")}get audioWebRTCStats(){return c(this,bf,"f")}handleWebRTCStats(e,t){e.addEventListener("ended",(()=>{t.removeInboundVideoHandler(e.id),t.removeInboundAudioHandler(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){d(this,_f,e,"f")}setAudioWebRTCStats(e){d(this,bf,e,"f")}}_f=new WeakMap,bf=new WeakMap,function(e){e.CloseProducer="CloseProducer",e.Mute="Mute",e.Resume="Resume"}(Ef||(Ef={}));class Ff{constructor(e){wf.set(this,void 0),Sf.set(this,void 0),this.encoderConfig={},this.label=zn.Unknown,Cf.set(this,void 0),Pf.set(this,void 0),Tf.set(this,void 0),kf.set(this,void 0),Rf.set(this,void 0),If.set(this,void 0),Df.set(this,void 0),Af.set(this,void 0),Of.set(this,!0),Nf.set(this,void 0),Mf.set(this,void 0),Lf.set(this,void 0);const{mediaStreamTrack:t,internalEventEmitter:r,constraints:n,mediaStreamTrackManager:i,media:s,myPeer:o,network:a,socket:c,mutex:u,loggerFactory:l,loggerNamespace:p,statsHandler:h}=e;d(this,wf,t,"f"),d(this,Rf,r,"f"),d(this,If,n,"f"),d(this,Df,i,"f"),d(this,Af,new Tt,"f"),this.logger=l(p),d(this,Nf,u,"f"),d(this,Pf,s,"f"),d(this,Cf,o,"f"),d(this,Tf,a,"f"),d(this,kf,c,"f"),d(this,Lf,h,"f"),d(this,Mf,new xf({track:t,statsHandler:h}),"f")}get videoWebRTCStats(){return c(this,Mf,"f").videoWebRTCStats}get audioWebRTCStats(){return c(this,Mf,"f").audioWebRTCStats}get logCtx(){return{label:this.getLabel(),id:this.id,kind:this.kind,producerId:this.producerId,paused:this.isPaused,published:this.isPublished}}get observer(){return c(this,Af,"f")}get mediaStreamTrack(){return c(this,wf,"f")}get originalTrack(){return c(this,Sf,"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 c(this,Rf,"f")}getLabel(){return this.label}setLabel(e){this.label=e}setEncoderConfig(e){this.encoderConfig=e}getEncoderConfig(){return this.encoderConfig}setProducer(e){this.producer=e}setStopTrackOnPause(e){this.isPublished||d(this,Of,e,"f")}getProducer(){return this.producer}setOriginalTrack(){d(this,Sf,this.mediaStreamTrack,"f")}closeProducer(){return a(this,arguments,void 0,(function*(e=!0){const t=yield c(this,Nf,"f").lock(Ef.CloseProducer);if(!this.producer)return void t();const{producerId:r}=this;try{r&&(yield c(this,Tf,"f").closeRemoteProducer(r),this.logger.info("Remote producer closed",{producerId:r}))}catch(e){this.logger.warn("closeProducer()",{label:this.getLabel(),error:pr(e),producerId:r})}this.producer.close(),this.producer=void 0,e&&this.stopMediaStreamTrack(),t()}))}setPriority(e){return a(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.warn("setPriority()",{priority:e,reason:"Not published yet"})}))}stopMediaStreamTrack(){this.mediaStreamTrack.stop(),this.mediaStreamTrack.dispatchEvent(new Event("ended")),this.stopOriginalTrack()}stopOriginalTrack(){c(this,Sf,"f")&&(c(this,Sf,"f").stop(),d(this,Sf,void 0,"f"))}produce(e){return a(this,arguments,void 0,(function*({encodings:e,codecOptions:t,preferredCodec:r,transformParams:n,keyFrameRequestDelay:i}){var s,o,a,d,u;if(!c(this,Cf,"f").canPublish)throw this.logger.error("produce()",{message:"Not enough access to produce"}),new Error("Not enough access to produce");if(this.producer)throw new Error("Track already produced");try{yield c(this,kf,"f").request(Sr);const{rtpCapabilities:{codecs:l}}=c(this,Pf,"f").mediasoupDevice,p=null==l?void 0:l.find((e=>e.mimeType.toLowerCase()===`${this.kind}/${r}`)),h=0,f=this.prepareProducerEncodings({codec:p,encodings:null!=e?e:[],maxSpatialLayer:(null!=e?e:[]).length-1}),m={trackTransformParams:n,peerId:String(c(this,Cf,"f").id),label:this.getLabel(),maxSpatialLayer:h,encodings:f,codecOptions:t,preferredCodec:r,codec:p,keyFrameRequestDelay:i},g=yield null===(s=c(this,Tf,"f").sendTransport)||void 0===s?void 0:s.produce({track:this.mediaStreamTrack,encodings:f,codecOptions:t,codec:p,stopTracks:!1,disableTrackOnPause:!0,zeroRtpOnPause:!0,appData:m});if(!g)return;const v=g.rtpSender,y=()=>/Safari/i.test(navigator.userAgent);if(e&&v&&y()){const t=v.getParameters();e.forEach((({maxBitrate:e,scaleResolutionDownBy:r},n)=>{t.encodings[n]&&(t.encodings[n].maxBitrate=e,t.encodings[n].scaleResolutionDownBy=r)})),yield v.setParameters(t)}this.setProducer(g),(null===(a=null===(o=this.producer)||void 0===o?void 0:o.track)||void 0===a?void 0:a.id)!==c(this,wf,"f").id&&(this.logger.info("Producer initialized with old track, updating",{oldTrackId:null===(u=null===(d=this.producer)||void 0===d?void 0:d.track)||void 0===u?void 0:u.id,newTrackId:c(this,wf,"f").id}),yield this.replaceTrack(c(this,wf,"f"))),"video"===this.kind&&(e&&v&&p&&Un(p.mimeType)&&!y()?yield v.setParameters(Object.assign(Object.assign({},v.getParameters()),{encodings:this.prepareProducerEncodings({encodings:e,codec:p,maxSpatialLayer:h})})):yield g.setMaxSpatialLayer(h),yield c(this,kf,"f").request(pn,{producerId:g.id,maxSpatialLayer:h})),"audio"===this.kind&&(yield this.setPriority("high")),this.logger.debug("produce()",{track:this.logCtx,encodings:e,codecOptions:t})}catch(e){throw this.logger.error("produce()",{error:e,track:this.logCtx}),new Error("Publish track failed")}}))}publish(){return a(this,void 0,void 0,(function*(){yield this.produce({}),this.internalEventEmitter.emit($r.trackProduced,this)}))}unpublish(){return a(this,arguments,void 0,(function*(e=!0){try{e&&this.stopMediaStreamTrack(),this.internalEventEmitter.emit($r.trackUnproduced,this),this.producer&&(yield this.closeProducer()),this.logger.debug("unpublish()",{track:this.logCtx})}catch(e){this.logger.error("unpublish()",{error:e})}}))}pauseRemoteProducer(e){return a(this,void 0,void 0,(function*(){return yield c(this,kf,"f").request(un,{producerId:e})}))}resumeRemoteProducer(e){return a(this,void 0,void 0,(function*(){return yield c(this,kf,"f").request(ln,{producerId:e})}))}mute(e){return a(this,void 0,void 0,(function*(){const t=yield c(this,Nf,"f").lock(Ef.Mute);if(!this.producer)return this.logger.warn("pause()",{message:"Track is not published",track:this.logCtx}),void t();try{if(this.producer.pause(),this.logger.debug("pause()",{track:this.logCtx}),c(this,Of,"f"))return null==e||e(),c(this,wf,"f").stop(),this.stopOriginalTrack(),this.internalEventEmitter.emit($r.trackClosed,this),void(yield this.pauseRemoteProducer(this.producer.id));yield this.pauseRemoteProducer(this.producer.id),this.internalEventEmitter.emit($r.trackPaused,this)}catch(e){throw this.logger.error("pause()",{error:e,track:this.logCtx}),yield c(this,Pf,"f").deleteTrack(this),this.internalEventEmitter.emit($r.trackFailed,this),new Error("Can`t pause track, removing")}finally{t()}}))}resume(){return a(this,void 0,void 0,(function*(){const e=yield c(this,Nf,"f").lock(Ef.Resume);if(!this.producer)return this.logger.warn("resume()",{message:"Track is not published",track:this.logCtx}),void e();try{if(this.logger.debug("resume()",{track:this.logCtx}),c(this,Of,"f"))return yield this.reopenMediaStreamTrack(),yield this.resumeProducer(),void this.internalEventEmitter.emit($r.trackReopened,this);yield this.resumeProducer(),this.internalEventEmitter.emit($r.trackResumed,this)}catch(e){throw this.logger.error("resume()",{error:e,track:this.logCtx}),new Error("Can`t resume track")}finally{e()}}))}getInfo(){return a(this,void 0,void 0,(function*(){const{width:e,height:t,frameRate:r,aspectRatio:n}=c(this,wf,"f").getSettings();return{trackId:c(this,wf,"f").id,readyState:c(this,wf,"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 a(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=>yf(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 a(this,void 0,void 0,(function*(){var t;try{d(this,wf,e,"f"),this.internalEventEmitter.emit($r.trackReopened,this),this.observer.safeEmit("track-changed",{track:e}),yield null===(t=this.producer)||void 0===t?void 0:t.replaceTrack({track:e}),d(this,Mf,new xf({track:e,statsHandler:c(this,Lf,"f")}),"f")}catch(e){this.logger.warn("replaceTrack()",{error:e})}}))}resumeProducer(){return a(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 a(this,void 0,void 0,(function*(){var e;const t=yield c(this,Df,"f").createMediaStreamTrack({label:this.label,constraints:c(this,If,"f")});d(this,wf,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&&t.length>1&&r&&Un(r.mimeType)?[t[n]||t[0]]:t}getOutboundRTPStreamStats(){return a(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>{const r=(...n)=>a(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((()=>a(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:pr(e)})}))}))}))}}var jf,Uf,Bf,Vf;wf=new WeakMap,Sf=new WeakMap,Cf=new WeakMap,Pf=new WeakMap,Tf=new WeakMap,kf=new WeakMap,Rf=new WeakMap,If=new WeakMap,Df=new WeakMap,Af=new WeakMap,Of=new WeakMap,Nf=new WeakMap,Mf=new WeakMap,Lf=new WeakMap;class Wf extends Ff{constructor(e){super(e),this.transformParams={},jf.set(this,void 0),Uf.set(this,void 0),Bf.set(this,!1),Vf.set(this,(()=>{})),d(this,Uf,e,"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(c(this,jf,"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()===zn.ScreenVideo?"vp8":"h264")}getEncodings(){var e;return null!==(e=this.getEncoderConfig().encodings)&&void 0!==e?e:qh}setTransformParams(e){this.transformParams=e}setMaxSpatialLayer(e){return a(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.warn("setMaxSpatialLayer()",{message:"Not produced yet"})}))}getMaxSpatialLayer(){const e=this.getProducer();if(e)return e.maxSpatialLayer;this.logger.warn("getMaxSpatialLayer()",{message:"Not produced yet"})}enableEffects(){return a(this,void 0,void 0,(function*(){if(!c(this,Bf,"f")){d(this,Bf,!0,"f");try{if(c(this,jf,"f"))return this.logger.debug("enableEffects()",{description:"Track is already processed"}),void d(this,Bf,!1,"f");if("ended"===this.mediaStreamTrack.readyState)return void this.logger.warn("Track already ended",{case:"enableEffects"});const{media:e}=c(this,Uf,"f");if(!e.effectsSDKInitialized)return void this.logger.warn("Effects SDK not initialized",{case:"enableEffects"});const t=Date.now();d(this,jf,yield e.createEffectsSDKTrackProcessor(this.getLabel()),"f"),this.setOriginalTrack();const r=c(this,jf,"f").processTrack(this.mediaStreamTrack),n=Date.now();this.logger.info("enableEffects() time",{time:(n-t)/1e3}),yield this.replaceTrack(r),this.logger.info("enableEffects()",{track:this.logCtx})}catch(e){this.logger.warn("enableEffects()",{track:this.logCtx,error:pr(e)}),this.disableEffects().catch((e=>{this.logger.warn("Failed to this.disableEffects() in catch{}",{track:this.logCtx,error:pr(e)})})),c(this,Vf,"f").call(this,e)}finally{d(this,Bf,!1,"f")}}}))}disableEffects(){return a(this,void 0,void 0,(function*(){var e;try{if(!c(this,jf,"f"))return void this.logger.debug("disableEffects()",{description:"Track is not processed"});this.originalTrack?yield this.replaceTrack(this.originalTrack):this.logger.warn("disableEffects()",{description:"Original track missing"}),null===(e=c(this,jf,"f"))||void 0===e||e.stopProcessing(),d(this,jf,void 0,"f"),this.logger.info("disableEffects()",{track:this.logCtx})}catch(e){this.logger.warn("disableEffects()",{track:this.logCtx,error:e})}}))}publish(){return a(this,arguments,void 0,(function*(e={}){var t;yield this.produce({encodings:this.getEncodings(),preferredCodec:this.getPreferredCodec(),transformParams:this.transformParams,codecOptions:this.getCodecOptions(),keyFrameRequestDelay:null!==(t=e.keyFrameRequestDelay)&&void 0!==t?t:0}),this.internalEventEmitter.emit($r.trackProduced,this)}))}adjustEncodingPresetToCurrentMaxSpatialLayer(e){return a(this,void 0,void 0,(function*(){var t;if(!Un(this.getPreferredCodec()))return;const{rtpSender:r}=null!==(t=this.getProducer())&&void 0!==t?t:{};if(!r)return void this.logger.warn("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 a(this,void 0,void 0,(function*(){var t;try{!this.isEffectsProcessing&&Object.keys(e).length>0&&(yield this.enableEffects()),null===(t=c(this,jf,"f"))||void 0===t||t.updateEffects(e)}catch(e){c(this,Vf,"f").call(this,e)}}))}resetEffects(){var e;null===(e=c(this,jf,"f"))||void 0===e||e.updateEffects({})}setOnLoadModels(e){var t;null===(t=c(this,jf,"f"))||void 0===t||t.setOnLoadModels(e)}get modelsLoadProgress(){var e,t;return null!==(t=null===(e=c(this,jf,"f"))||void 0===e?void 0:e.modelsLoadProgress)&&void 0!==t?t:0}pause(){return a(this,void 0,void 0,(function*(){yield this.mute((()=>{var e;c(this,jf,"f")&&(null===(e=c(this,jf,"f"))||void 0===e||e.stopProcessing(),d(this,jf,void 0,"f"))}))}))}setOnEffectError(e){d(this,Vf,e,"f")}}var Hf,qf;jf=new WeakMap,Uf=new WeakMap,Bf=new WeakMap,Vf=new WeakMap;let zf=qf=class{constructor(e){Hf.set(this,void 0),d(this,Hf,e("MediaStreamTrackManager"),"f")}createMediaStreamTrack(e){return a(this,arguments,void 0,(function*({label:e,constraints:t}){if(qf.isDisplayMedia(e)){const[e]=yield this.createDisplayMediaTracks(t);return e}const[r]=yield this.createUserMediaTracks(t);return r}))}static isDisplayMedia(e){return[zn.ScreenVideo,zn.ScreenAudio].includes(e)}createUserMediaTracks(e){return a(this,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.getUserMedia(e);return c(this,Hf,"f").debug("createUserMediaTracks() stream created",{streamId:t.id}),t.getTracks()}))}createDisplayMediaTracks(e){return a(this,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.getDisplayMedia(e);return c(this,Hf,"f").debug("getDisplayMediaTracks() stream created",{streamId:t.id}),t.getTracks()}))}};Hf=new WeakMap,zf=qf=i([at(),s(0,dt(Hn.LoggerFactory)),o("design:paramtypes",[Function])],zf);var Gf,Yf,$f,Jf,Kf,Qf,Zf,Xf=zf;let em=class{constructor(e,t,r,n,i,s,o,a,c){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.socket=c,this.isDeviceLoaded=!1,this.tracks=new Map,Gf.set(this,void 0),Yf.set(this,null),$f.set(this,!1),Jf.set(this,new Map),Kf.set(this,!1),Qf.set(this,!1),Zf.set(this,void 0);const u=this.config.get("effectsSDKParams");d(this,Zf,this.config.get("denoiser"),"f"),d(this,Gf,this.loggerFactory("Media"),"f"),d(this,Yf,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 c(this,$f,"f")}get effectsSDKParams(){return c(this,Yf,"f")}getTrack(e){return this.tracks.get(e)}loadDevice(e){return a(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()}`));c(this,Gf,"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"})),c(this,Gf,"f").debug("createTrack() track created",{trackId:n.id,kind:n.kind}),n}))}createUserMediaTracks(e){return a(this,void 0,void 0,(function*(){const t=yield this.mediaStreamTrackManager.createUserMediaTracks(e);return this.createTracks({constraints:e,mediaStreamTracks:t})}))}createDisplayMediaTracks(e){return a(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 a(this,void 0,void 0,(function*(){const t={trackId:e.id,label:e.getLabel(),producerId:e.producerId};try{"disableNoiseSuppression"in e&&(yield e.disableNoiseSuppression()),"disableEffects"in e&&(yield e.disableEffects())}catch(e){c(this,Gf,"f").warn("deleteTrack()",Object.assign({error:e},t))}try{this.tracks.delete(e.getLabel()),e.stopMediaStreamTrack(),yield e.closeProducer()}catch(e){c(this,Gf,"f").error("deleteTrack()",{error:e})}finally{c(this,Gf,"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){c(this,Gf,"f").warn("clearTracks()",{error:e})}finally{this.tracks.clear()}}unpublishTracks(){return a(this,void 0,void 0,(function*(){try{yield Promise.all(this.publishedTracks().map((e=>a(this,void 0,void 0,(function*(){return yield e.unpublish(!1)})))))}catch(e){c(this,Gf,"f").warn("unpublishTracks()",{error:e})}}))}setTrack(e){this.tracks.set(e.getLabel(),e)}initEffectsSDK(){return a(this,void 0,void 0,(function*(){if(c(this,$f,"f"))return!0;if(!c(this,Yf,"f"))throw c(this,Gf,"f").error("Effects SDK config params not provided",{case:"initEffectsSDK"}),new Error("Effects SDK config not provided");const e=(e,t)=>a(this,void 0,void 0,(function*(){if(!window.tsvb)return c(this,Gf,"f").info("Effects SDK not loaded, skipping initialization",{case:"initEffectsSDK"}),void e(!1);c(this,Gf,"f").info("Effects SDK initializing",{case:"initEffectsSDK"});try{c(this,Jf,"f").set(zn.Camera,yield this.createEffectsSDKTrackProcessor(zn.Camera)),c(this,Jf,"f").set(zn.CameraPreview,yield this.createEffectsSDKTrackProcessor(zn.CameraPreview)),d(this,$f,!0,"f"),c(this,Gf,"f").info("Effects SDK initialized",{case:"initEffectsSDK"}),e(!0)}catch(e){c(this,Gf,"f").error("Failed to initialize Effects SDK",{error:e,case:"initEffectsSDK"}),t(e)}}));return yield new Promise(((t,r)=>{if(!window.tsvb)return c(this,Gf,"f").info("Effects SDK tsvb-web.js is not ready, waiting",{case:"initEffectsSDK"}),void window.addEventListener("load",(()=>a(this,void 0,void 0,(function*(){return yield e(t,r)}))));e(t,r).catch((e=>{c(this,Gf,"f").error("Failed to execute init() in initEffectsSDK",{error:pr(e)})}))}))}))}initDenoiser(e,t){return a(this,void 0,void 0,(function*(){if(!c(this,Kf,"f"))try{d(this,Kf,!0,"f"),this.clientEventEmitter.emit(Vr,!0);try{yield this.integrationsService.audio.waitForInitialization}catch(e){"asdk"===c(this,Zf,"f")&&(d(this,Qf,!0,"f"),d(this,Zf,"rnnoise","f"),this.config.set("denoiser",c(this,Zf,"f")),c(this,Gf,"f").debug("Set config to rnnoise denoiser",{case:"Denoiser",error:pr(e),type:this.config.get("denoiser")}),this.clientEventEmitter.emit(zr),this.integrationsService.init(),yield this.integrationsService.audio.waitForInitialization)}c(this,Gf,"f").debug("Denoiser initialized, activating",{case:"Denoiser",type:this.integrationsService.audio.type,trackLabel:e.getLabel()});const r=e,n=this.processorsCache.get(c(this,Zf,"f"),zn.Microphone);if(!n)return void c(this,Gf,"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(Vr,!0),this.fallbackToRNoise(e,{reason:r,options:t,error:n}).catch((t=>{c(this,Gf,"f").error("Failed to fallback to RNNoise through onError",{case:"Denoiser",type:c(this,Zf,"f"),error:pr(t),label:e.getLabel()})})).then((()=>{this.clientEventEmitter.emit(Vr,!1)})).catch((()=>{}))})),r.setTrackProcessor(n),c(this,Gf,"f").debug("Denoiser trackProcessor set, check if activation is needed",{case:"Denoiser",type:c(this,Zf,"f"),shouldEnableDenoiser:null==t?void 0:t.noiseSuppression,trackLabel:e.getLabel()}),(null==t?void 0:t.noiseSuppression)&&(yield e.enableNoiseSuppression())}catch(r){if(c(this,Gf,"f").warn("Failed to start noise suppression, featured original track",{case:"Denoiser",type:c(this,Zf,"f"),error:pr(r),label:e.getLabel()}),"asdk"===c(this,Zf,"f"))try{c(this,Gf,"f").warn("Fallback to RNNoise",{error:pr(r)}),yield this.fallbackToRNoise(e,{options:t,reason:"ASDK init error",error:r})}catch(t){c(this,Gf,"f").error("Failed to fallback to RNNoise through catch",{case:"Denoiser",type:c(this,Zf,"f"),error:pr(t),label:e.getLabel()})}}finally{this.clientEventEmitter.emit(Vr,!1),d(this,Kf,!1,"f")}}))}fallbackToRNoise(e,t){return a(this,void 0,void 0,(function*(){var r;if(c(this,Qf,"f"))return;if(d(this,Qf,!0,"f"),"rnnoise"===c(this,Zf,"f"))return;this.clientEventEmitter.emit(zr),c(this,Gf,"f").info("Fallback to RNNoise",{reason:null==t?void 0:t.reason,error:pr(null==t?void 0:t.error),case:"Denoiser"});const n=e;yield n.disableNoiseSuppression(),n.unsetTrackProcessor(),d(this,Zf,"rnnoise","f"),this.config.set("denoiser",c(this,Zf,"f")),c(this,Gf,"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(c(this,Zf,"f"),zn.Microphone);i?(n.setTrackProcessor(i),(null===(r=null==t?void 0:t.options)||void 0===r?void 0:r.noiseSuppression)&&(yield n.enableNoiseSuppression())):c(this,Gf,"f").error("No cached trackProcessor found",{case:"Denoiser",trackLabel:e.getLabel(),type:this.integrationsService.audio.type})}))}createEffectsSDKTrackProcessor(e){return a(this,void 0,void 0,(function*(){var t,r,n;if(e){const t=c(this,Jf,"f").get(e);if(t)return t}if(!c(this,Yf,"f"))throw c(this,Gf,"f").error("Effects SDK config params not provided",{case:"initEffectsSDK"}),new Error("Effects SDK config not provided");const i=new vf({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(),c(this,Gf,"f").info("Track effects processor initialized",{trackLabel:e}),i}))}handleProducerSetMaxSpatialLayer(e){return a(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 c(this,Gf,"f").warn("producerRequestMaxSpatialLayer()",{message:"Producer not found"});if(!(r instanceof Wf))return void c(this,Gf,"f").warn("producerRequestMaxSpatialLayer()",{message:"Wrong producer kind"});const n=null!=t?t:$h,i=r.getMaxSpatialLayer();i!==n?(r.getEncodings().length>1&&(yield r.setMaxSpatialLayer(n)),yield this.socket.request(pn,{producerId:e,maxSpatialLayer:n}),yield r.adjustEncodingPresetToCurrentMaxSpatialLayer(n)):c(this,Gf,"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:Yh.width,height:null!==(r=n.height)&&void 0!==r?r:Yh.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:Yh.width},height:{max:Yh.height}},encoderConfig:null!==(r=null==e?void 0:e.videoEncoderConfig)&&void 0!==r?r:{encodings:zh}}}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:Yh.width},height:{max:Yh.height}},encoderConfig:null!==(r=null==e?void 0:e.encoderConfig)&&void 0!==r?r:{encodings:qh}}}createDevice(){const e=(e=>{const t=null!=e?e:null===navigator||void 0===navigator?void 0:navigator.userAgent;if(!t)return;const r=Fn.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":void 0})();return c(this,Gf,"f").debug("Creating a media device",{handlerName:null!=e?e:"not specified"}),new Ya.Device({handlerName:e})}};Gf=new WeakMap,Yf=new WeakMap,$f=new WeakMap,Jf=new WeakMap,Kf=new WeakMap,Qf=new WeakMap,Zf=new WeakMap,em=i([at(),s(0,dt(Hn.Config)),s(1,dt(Hn.LoggerFactory)),s(2,dt(Hn.AudioTrackFactory)),s(3,dt(Hn.ClientEventEmitter)),s(4,dt(Hn.IntegrationsService)),s(5,dt(Hn.ProcessorsCache)),s(6,dt(Hn.VideoTrackFactory)),s(7,dt(Hn.MediaStreamTrackManager)),s(8,dt(Hn.SocketIO)),o("design:paramtypes",[Pt,Function,Function,Tt,af,nf,Function,Xf,la])],em);var tm=em;const rm={[Wi.PRODUCER_KIND_VIDEO]:"video",[Wi.PRODUCER_KIND_AUDIO]:"audio"},nm={[Gi.PEER_ROLE_HOST]:"host",[Gi.PEER_ROLE_AUDIENCE]:"audience"},im={[Ni.PRODUCER_LABEL_CAMERA]:zn.Camera,[Ni.PRODUCER_LABEL_MICROPHONE]:zn.Microphone,[Ni.PRODUCER_LABEL_SCREEN_VIDEO]:zn.ScreenVideo,[Ni.PRODUCER_LABEL_SCREEN_AUDIO]:zn.ScreenAudio,[Ni.PRODUCER_LABEL_CUSTOM_VIDEO]:zn.CustomVideo,[Ni.PRODUCER_LABEL_CUSTOM_AUDIO]:zn.CustomAudio,[Ni.PRODUCER_LABEL_UNKNOWN]:zn.Unknown,[Ni.PRODUCER_LABEL_UNSPECIFIED]:zn.Unknown},sm={[Oi.PEER_GROUP_MODERATOR]:"moderator",[Oi.PEER_GROUP_USER]:"user"},om=e=>{const t=rm[e];if(!t)throw new Error(`Unknown producer kind: ${e}`);return t},am=e=>{const t=sm[e];if(!t)throw new Error(`Unknown peer group: ${e}`);return t},cm=e=>{const t=im[e];if(!t)throw new Error(`Unknown producer label: ${e}`);return t},dm=e=>{const t=nm[e];if(!t)throw new Error(`Unknown peer role: ${e}`);return t},um=e=>({id:e.id,channelIds:e.channelIds,groups:e.groups.map(am),producePermissions:e.producePermissions.map(cm),appId:e.appId,producers:e.producers.map(lm),uid:e.uid,appData:e.appData,role:dm(e.role),loginDate:e.loginDate}),lm=e=>{var t;return{id:e.id,kind:om(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}},pm=e=>{switch(e){case"moderator":return Oi.PEER_GROUP_MODERATOR;case"user":return Oi.PEER_GROUP_USER;default:return Oi.PEER_GROUP_UNSPECIFIED}};var hm;let fm=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,hm.set(this,void 0),d(this,hm,o("ChannelStateSyncEventHandler"),"f"),this.debouncedTriggerChannelStateEvent=Ln(this.triggerChannelStateEvent.bind(this),3e3),this.watchNetworkState()}handleChannelStateEvent(e){return a(this,void 0,void 0,(function*(){this.network.peersLoaded?yield this.restoreState(e):this.loadChannelState(e),this.clientEventEmitter.emit(Wr)}))}watchNetworkState(){this.clientEventEmitter.on(jr,(()=>{this.debouncedTriggerChannelStateEvent()}))}triggerChannelStateEvent(){return a(this,void 0,void 0,(function*(){const e=()=>a(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>a(this,void 0,void 0,(function*(){const r=yield this.network.triggerChannelStateEvent("host"),n=setTimeout((()=>{this.eventsQueue.isMessageReceived(r)?(c(this,hm,"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(Fr,i),e()};this.clientEventEmitter.on(Fr,i)}))))}));try{yield Wn(e,{maxRetries:5,actionName:"triggerChannelStateEventWithRetry",logger:c(this,hm,"f")})}catch(e){c(this,hm,"f").warn("Failed to trigger channel state event",{case:"ChannelStateSynchronizer.triggerChannelStateEvent",error:pr(e)})}}))}loadChannelState(e){c(this,hm,"f").info("Loading channel state",{case:"loadChannelState"});try{const t=this.peers.hosts().map((e=>e.shortData)),r=e.peers.filter((e=>e.role===Gi.PEER_ROLE_HOST));this.setMissingPeers(t,r),this.restoreLocalPeersState(r),this.network.peersLoaded=!0}catch(e){c(this,hm,"f").error("Failed to load channel state",{case:"loadState",error:pr(e)})}}restoreState(e){return a(this,void 0,void 0,(function*(){const{peers:t}=e,r={missingPeers:[],removedPeers:[],missingProducers:[],removedProducers:[],fixedProducersState:[],fixedConsumersState:[],restoredAppDataPeers:[]};try{if(!this.network.isSocketConnectionActive)return c(this,hm,"f").info("Connection inactive, skipping restore local state",{case:"restoreLocalState"}),r;c(this,hm,"f").info("Restoring local state",{case:"restoreLocalState"});const e=this.peers.hosts().map((e=>e.shortData)),n=t.filter((e=>e.role===Gi.PEER_ROLE_HOST)),{removedProducers:i,fixedProducersState:s}=yield this.restoreRemoteProducersState(n);r.removedProducers.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 c(this,hm,"f").info("Failed to restore local state",{case:"restoreLocalState",error:pr(e)}),r}}))}restoreRemoteProducersState(e){return a(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=this.media.getAllTracks(),s=n.producers.filter((e=>!i.map((e=>e.producerId)).some((t=>e.id===t))));yield Promise.all(s.map((e=>a(this,void 0,void 0,(function*(){yield this.network.closeRemoteProducer(e.id),r.producers.delete(e.id),t.removedProducers.push(e.id),c(this,hm,"f").info("Unnecessary local producer closed",{case:"restoreLocalState",removedProducerId:e.id,removedProducerPeerId:e.peerId})})))));const o=n.producers.filter((e=>!!i.find((t=>t.isPaused&&t.isPaused!==e.paused))));return yield Promise.all(o.map((e=>a(this,void 0,void 0,(function*(){yield this.network.pauseRemoteProducer(e.id),t.fixedProducersState.push(e.id),c(this,hm,"f").info("Remote producer state repaired",{case:"restoreLocalState",removedProducerId:e.id,removedProducerPeerId:e.peerId})}))))),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=>{c(this,hm,"f").error("Failed to remove peer",{error:pr(e)})})),r.push(e.id),c(this,hm,"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(um(t));r.push(n.id),c(this,hm,"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 c(this,hm,"f").warn("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)})),c(this,hm,"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(dn,t),r.push(t.id),c(this,hm,"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(cn,lm(t)),r.missingProducers.push(t.id),void c(this,hm,"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?Qr:Zr;e.observer.safeEmit(n,{producerId:i.id,kind:i.kind,label:i.label,paused:i.paused}),r.fixedProducersState.push(t.id),c(this,hm,"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:yn;e.observer.safeEmit(s,n),r.fixedConsumersState.push(n),c(this,hm,"f").info("Consumer state fixed",{case:"restoreLocalState",consumerId:n,consumerProducerId:t.id,consumerProducerPeerId:t.peerId})}})),r}restoreAppData(e,t){return!Mn(e.appData,t.appData)&&(e.observer.emit(vr,t.appData),c(this,hm,"f").info("Application data restored",{case:"restoreLocalState",peerId:e.id,appData:t.appData}),!0)}};hm=new WeakMap,fm=i([at(),s(0,dt(Hn.Network)),s(1,dt(Hn.Media)),s(2,dt(Hn.MyPeer)),s(3,dt(Hn.EventsQueue)),s(4,dt(Hn.ClientEventEmitter)),s(5,dt(Hn.Peers)),s(6,dt(Hn.LoggerFactory)),o("design:paramtypes",[Aa,tm,js,xs,Tt,Oa,Function])],fm);var mm,gm=fm;let vm=class{constructor(e,t,r,n,i){this.peers=e,this.clientEventEmitter=t,this.channelStateSyncEventHandler=n,this.channelStateSynchronizer=i,mm.set(this,void 0),d(this,mm,r("ChannelEvents"),"f")}handleChannelEvent(e){return a(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;this.clientEventEmitter.safeEmit(Cr,t),c(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(um(e.peer));c(this,mm,"f").debug("Peer joined to the channel",{peer:Fs(t)})}handlePeerLeft(e){if(!e.peer)throw new Error("Missing peer in PEER_LEFT event");this.peers.remove(e.peer.id).catch((e=>{c(this,mm,"f").debug("Failed to remove peer",{error:pr(e)})})),c(this,mm,"f").debug("Peer left the channel",{peerId:e.peer.id})}handleChannelState(e){return a(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){c(this,mm,"f").error("Failed to restore channel state",{case:"restoreLocalState",error:pr(e)})}}))}handleChannelStateShort(e){if(!e.channelStateShort)throw new Error("Missing channelStateShort in CHANNEL_STATE_SHORT event");this.channelStateSyncEventHandler.handleChannelStateShort(e.channelStateShort).catch((e=>{c(this,mm,"f").error("Failed to handle channel state short event",{error:pr(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(vr,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(am))}handleChannelActivityConfirmationExpired(){this.clientEventEmitter.safeEmit(Ir),c(this,mm,"f").info("Notify the channel that it has disconnected due to the activity confirmation expiring",{})}handleChannelActivityConfirmationAcquired(){this.clientEventEmitter.safeEmit(Rr),c(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(kr,t),c(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(pm(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)})),c(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(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(pm(e)))))),n=e.channelProducePermissions.producePermissions.map(cm);r.forEach((e=>{const t=e.producePermissions.filter((e=>!n.includes(e)));e.handleProducePermissionsChange(t)})),c(this,mm,"f").info("Peers deleted produce permissions",{groups:t,producePermissions:n})}};mm=new WeakMap,vm=i([at(),s(0,dt(Hn.Peers)),s(1,dt(Hn.ClientEventEmitter)),s(2,dt(Hn.LoggerFactory)),s(3,dt(Hn.ChannelStateSyncEventHandler)),s(4,dt(Hn.ChannelStateSynchronizer)),o("design:paramtypes",[Oa,Tt,Function,Ga,gm])],vm);var ym=vm,_m={},bm=l&&l.__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){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(_m,"__esModule",{value:!0});var Em,wm,Sm=_m.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 bm(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 bm(this,void 0,void 0,(function*(){const e=this.pendingTasks[0];e&&(yield this.executeTask(e),this.pendingTasks.shift(),this.next())}))}executeTask(e){return bm(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 Cm=class{constructor(e,t,r,n,i){this.media=e,this.internalEventEmitter=t,this.peersStorage=r,this.clientEventEmitter=n,Em.set(this,new Sm),wm.set(this,void 0),d(this,wm,i("MediaEvents"),"f")}handleMediaEvent(e){switch(e.eventType){case bs.MEDIA_EVENT_TYPE_PRODUCER_CREATED:this.handleProducerCreated(e);break;case bs.MEDIA_EVENT_TYPE_PRODUCER_CLOSED:this.handleProducerClosed(e);break;case bs.MEDIA_EVENT_TYPE_PRODUCER_PAUSED:this.handleProducerPaused(e);break;case bs.MEDIA_EVENT_TYPE_PRODUCER_RESUMED:this.handleProducerResumed(e);break;case bs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED:this.handleProducerMaxSpatialLayerChanged(e);break;case bs.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED:this.handleProducerRequestMaxSpatialLayer(e).catch((e=>{c(this,wm,"f").error("Failed to handle producer max spatial layer requested event",{error:pr(e)})}));break;case bs.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED:this.handleProducerForciblyClosed(e).catch((e=>{c(this,wm,"f").error("Failed to handle producer forcibly closed event",{error:pr(e)})}));break;case bs.MEDIA_EVENT_TYPE_CONSUMER_CLOSED:this.handleConsumerClosed(e);break;case bs.MEDIA_EVENT_TYPE_CONSUMER_RESUMED:this.handleConsumerResumed(e);break;case bs.MEDIA_EVENT_TYPE_CONSUMER_PAUSED:this.handleConsumerPaused(e);break;case bs.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED:this.handleConsumerPreferredLayersChanged(e);break;case bs.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(cn,lm(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(dn,lm(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(Qr,{producerId:r.id,kind:r.kind,label:r.label,paused:r.paused}))}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(Zr,{producerId:r.id,kind:r.kind,label:r.label,paused:r.paused}))}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(pn,{peerId:e.producer.peerId,producerId:e.producer.id,spatialLayer:e.producer.maxSpatialLayer})}handleProducerRequestMaxSpatialLayer(e){return a(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 c(this,Em,"f").push((()=>a(this,void 0,void 0,(function*(){yield this.media.handleProducerSetMaxSpatialLayer({producerId:t,spatialLayer:r})}))),hn)}))}handleProducerForciblyClosed(e){return a(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.getTrack(t);if(!r)return;r.stopMediaStreamTrack(),this.internalEventEmitter.safeEmit($r.trackClosed,r);const n={label:t};this.clientEventEmitter.emit(Nr,n),yield this.media.deleteTrack(r)}))}handleConsumerClosed(e){if(!e.consumer)throw new Error("Missing consumer in MEDIA_EVENT_TYPE_CONSUMER_CLOSED");const t=this.peersStorage.get(e.consumer.producerPeerId);null==t||t.observer.safeEmit(gn,e.consumer.id)}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(yn,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){if(!e.consumer)throw new Error("Missing consumer in MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED");if(void 0===e.consumer.spatialLayer||void 0===e.consumer.temporalLayer)return;const t=this.peersStorage.get(e.consumer.peerId);null==t||t.observer.safeEmit(_n,{consumerId:e.consumer.id,spatialLayer:e.consumer.spatialLayer,temporalLayer:e.consumer.temporalLayer})}handleTransportConnectionTimeout(e){if(!e.transportConnectionTimeout)throw new Error("Missing transportConnectionTimeout in MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT");c(this,wm,"f").warn("Transport connection timed out",{transportId:e.transportConnectionTimeout.transportId,direction:e.transportConnectionTimeout.direction,timeout:e.transportConnectionTimeout.timeout,reason:e.transportConnectionTimeout.reason})}};Em=new WeakMap,wm=new WeakMap,Cm=i([at(),s(0,dt(Hn.Media)),s(1,dt(Hn.InternalEventEmitter)),s(2,dt(Hn.PeersStorage)),s(3,dt(Hn.ClientEventEmitter)),s(4,dt(Hn.LoggerFactory)),o("design:paramtypes",[tm,Tt,_a,Tt,Function])],Cm);var Pm=Cm,Tm={exports:{}},km=function(e,t){return function(){for(var r=new Array(arguments.length),n=0;n<r.length;n++)r[n]=arguments[n];return e.apply(t,r)}},Rm=km,Im=Object.prototype.toString;function Dm(e){return"[object Array]"===Im.call(e)}function Am(e){return void 0===e}function Om(e){return null!==e&&"object"==typeof e}function Nm(e){if("[object Object]"!==Im.call(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}function Mm(e){return"[object Function]"===Im.call(e)}function Lm(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),Dm(e))for(var r=0,n=e.length;r<n;r++)t.call(null,e[r],r,e);else for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.call(null,e[i],i,e)}var xm={isArray:Dm,isArrayBuffer:function(e){return"[object ArrayBuffer]"===Im.call(e)},isBuffer:function(e){return null!==e&&!Am(e)&&null!==e.constructor&&!Am(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){return"undefined"!=typeof FormData&&e instanceof FormData},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:Om,isPlainObject:Nm,isUndefined:Am,isDate:function(e){return"[object Date]"===Im.call(e)},isFile:function(e){return"[object File]"===Im.call(e)},isBlob:function(e){return"[object Blob]"===Im.call(e)},isFunction:Mm,isStream:function(e){return Om(e)&&Mm(e.pipe)},isURLSearchParams:function(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)},forEach:Lm,merge:function e(){var t={};function r(r,n){Nm(t[n])&&Nm(r)?t[n]=e(t[n],r):Nm(r)?t[n]=e({},r):Dm(r)?t[n]=r.slice():t[n]=r}for(var n=0,i=arguments.length;n<i;n++)Lm(arguments[n],r);return t},extend:function(e,t,r){return Lm(t,(function(t,n){e[n]=r&&"function"==typeof t?Rm(t,r):t})),e},trim:function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e}},Fm=xm;function jm(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var Um=function(e,t,r){if(!t)return e;var n;if(r)n=r(t);else if(Fm.isURLSearchParams(t))n=t.toString();else{var i=[];Fm.forEach(t,(function(e,t){null!=e&&(Fm.isArray(e)?t+="[]":e=[e],Fm.forEach(e,(function(e){Fm.isDate(e)?e=e.toISOString():Fm.isObject(e)&&(e=JSON.stringify(e)),i.push(jm(t)+"="+jm(e))})))})),n=i.join("&")}if(n){var s=e.indexOf("#");-1!==s&&(e=e.slice(0,s)),e+=(-1===e.indexOf("?")?"?":"&")+n}return e},Bm=xm;function Vm(){this.handlers=[]}Vm.prototype.use=function(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1},Vm.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},Vm.prototype.forEach=function(e){Bm.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var Wm=Vm,Hm=xm,qm=function(e,t,r,n,i){return e.config=t,r&&(e.code=r),e.request=n,e.response=i,e.isAxiosError=!0,e.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code}},e},zm=qm,Gm=function(e,t,r,n,i){var s=new Error(e);return zm(s,t,r,n,i)},Ym=Gm,$m=xm,Jm=$m.isStandardBrowserEnv()?{write:function(e,t,r,n,i,s){var o=[];o.push(e+"="+encodeURIComponent(t)),$m.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),$m.isString(n)&&o.push("path="+n),$m.isString(i)&&o.push("domain="+i),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},Km=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)},Qm=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},Zm=xm,Xm=["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"],eg=xm,tg=eg.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");function n(e){var n=e;return t&&(r.setAttribute("href",n),n=r.href),r.setAttribute("href",n),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:"/"===r.pathname.charAt(0)?r.pathname:"/"+r.pathname}}return e=n(window.location.href),function(t){var r=eg.isString(t)?n(t):t;return r.protocol===e.protocol&&r.host===e.host}}():function(){return!0},rg=xm,ng=function(e,t,r){var n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(Ym("Request failed with status code "+r.status,r.config,null,r.request,r)):e(r)},ig=Jm,sg=Um,og=function(e,t){return e&&!Km(t)?Qm(e,t):t},ag=function(e){var t,r,n,i={};return e?(Zm.forEach(e.split("\n"),(function(e){if(n=e.indexOf(":"),t=Zm.trim(e.substr(0,n)).toLowerCase(),r=Zm.trim(e.substr(n+1)),t){if(i[t]&&Xm.indexOf(t)>=0)return;i[t]="set-cookie"===t?(i[t]?i[t]:[]).concat([r]):i[t]?i[t]+", "+r:r}})),i):i},cg=tg,dg=Gm,ug=function(e){return new Promise((function(t,r){var n=e.data,i=e.headers,s=e.responseType;rg.isFormData(n)&&delete i["Content-Type"];var o=new XMLHttpRequest;if(e.auth){var a=e.auth.username||"",c=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.Authorization="Basic "+btoa(a+":"+c)}var d=og(e.baseURL,e.url);function u(){if(o){var n="getAllResponseHeaders"in o?ag(o.getAllResponseHeaders()):null,i={data:s&&"text"!==s&&"json"!==s?o.response:o.responseText,status:o.status,statusText:o.statusText,headers:n,config:e,request:o};ng(t,r,i),o=null}}if(o.open(e.method.toUpperCase(),sg(d,e.params,e.paramsSerializer),!0),o.timeout=e.timeout,"onloadend"in o?o.onloadend=u:o.onreadystatechange=function(){o&&4===o.readyState&&(0!==o.status||o.responseURL&&0===o.responseURL.indexOf("file:"))&&setTimeout(u)},o.onabort=function(){o&&(r(dg("Request aborted",e,"ECONNABORTED",o)),o=null)},o.onerror=function(){r(dg("Network Error",e,null,o)),o=null},o.ontimeout=function(){var t="timeout of "+e.timeout+"ms exceeded";e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),r(dg(t,e,e.transitional&&e.transitional.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",o)),o=null},rg.isStandardBrowserEnv()){var l=(e.withCredentials||cg(d))&&e.xsrfCookieName?ig.read(e.xsrfCookieName):void 0;l&&(i[e.xsrfHeaderName]=l)}"setRequestHeader"in o&&rg.forEach(i,(function(e,t){void 0===n&&"content-type"===t.toLowerCase()?delete i[t]:o.setRequestHeader(t,e)})),rg.isUndefined(e.withCredentials)||(o.withCredentials=!!e.withCredentials),s&&"json"!==s&&(o.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&o.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&o.upload&&o.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then((function(e){o&&(o.abort(),r(e),o=null)})),n||(n=null),o.send(n)}))},lg=xm,pg=function(e,t){Hm.forEach(e,(function(r,n){n!==t&&n.toUpperCase()===t.toUpperCase()&&(e[t]=r,delete e[n])}))},hg=qm,fg={"Content-Type":"application/x-www-form-urlencoded"};function mg(e,t){!lg.isUndefined(e)&&lg.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var gg,vg={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:(("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(gg=ug),gg),transformRequest:[function(e,t){return pg(t,"Accept"),pg(t,"Content-Type"),lg.isFormData(e)||lg.isArrayBuffer(e)||lg.isBuffer(e)||lg.isStream(e)||lg.isFile(e)||lg.isBlob(e)?e:lg.isArrayBufferView(e)?e.buffer:lg.isURLSearchParams(e)?(mg(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):lg.isObject(e)||t&&"application/json"===t["Content-Type"]?(mg(t,"application/json"),function(e,t,r){if(lg.isString(e))try{return(t||JSON.parse)(e),lg.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional,r=t&&t.silentJSONParsing,n=t&&t.forcedJSONParsing,i=!r&&"json"===this.responseType;if(i||n&&lg.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(i){if("SyntaxError"===e.name)throw hg(e,this,"E_JSON_PARSE");throw e}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(e){return e>=200&&e<300}};vg.headers={common:{Accept:"application/json, text/plain, */*"}},lg.forEach(["delete","get","head"],(function(e){vg.headers[e]={}})),lg.forEach(["post","put","patch"],(function(e){vg.headers[e]=lg.merge(fg)}));var yg=vg,_g=xm,bg=yg,Eg=function(e){return!(!e||!e.__CANCEL__)},wg=xm,Sg=function(e,t,r){var n=this||bg;return _g.forEach(r,(function(r){e=r.call(n,e,t)})),e},Cg=Eg,Pg=yg;function Tg(e){e.cancelToken&&e.cancelToken.throwIfRequested()}var kg=xm,Rg=function(e,t){t=t||{};var r={},n=["url","method","data"],i=["headers","auth","proxy","params"],s=["baseURL","transformRequest","transformResponse","paramsSerializer","timeout","timeoutMessage","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","decompress","maxContentLength","maxBodyLength","maxRedirects","transport","httpAgent","httpsAgent","cancelToken","socketPath","responseEncoding"],o=["validateStatus"];function a(e,t){return kg.isPlainObject(e)&&kg.isPlainObject(t)?kg.merge(e,t):kg.isPlainObject(t)?kg.merge({},t):kg.isArray(t)?t.slice():t}function c(n){kg.isUndefined(t[n])?kg.isUndefined(e[n])||(r[n]=a(void 0,e[n])):r[n]=a(e[n],t[n])}kg.forEach(n,(function(e){kg.isUndefined(t[e])||(r[e]=a(void 0,t[e]))})),kg.forEach(i,c),kg.forEach(s,(function(n){kg.isUndefined(t[n])?kg.isUndefined(e[n])||(r[n]=a(void 0,e[n])):r[n]=a(void 0,t[n])})),kg.forEach(o,(function(n){n in t?r[n]=a(e[n],t[n]):n in e&&(r[n]=a(void 0,e[n]))}));var d=n.concat(i).concat(s).concat(o),u=Object.keys(e).concat(Object.keys(t)).filter((function(e){return-1===d.indexOf(e)}));return kg.forEach(u,c),r},Ig={name:"axios",version:"0.21.4",description:"Promise based HTTP client for the browser and node.js",main:"index.js",scripts:{test:"grunt test",start:"node ./sandbox/server.js",build:"NODE_ENV=production grunt build",preversion:"npm test",version:"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json",postversion:"git push && git push --tags",examples:"node ./examples/server.js",coveralls:"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",fix:"eslint --fix lib/**/*.js"},repository:{type:"git",url:"https://github.com/axios/axios.git"},keywords:["xhr","http","ajax","promise","node"],author:"Matt Zabriskie",license:"MIT",bugs:{url:"https://github.com/axios/axios/issues"},homepage:"https://axios-http.com",devDependencies:{coveralls:"^3.0.0","es6-promise":"^4.2.4",grunt:"^1.3.0","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^23.0.0","grunt-karma":"^4.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^4.0.2","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1",karma:"^6.3.2","karma-chrome-launcher":"^3.1.0","karma-firefox-launcher":"^2.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^4.3.6","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.8","karma-webpack":"^4.0.2","load-grunt-tasks":"^3.5.2",minimist:"^1.2.0",mocha:"^8.2.1",sinon:"^4.5.0","terser-webpack-plugin":"^4.2.3",typescript:"^4.0.5","url-search-params":"^0.10.0",webpack:"^4.44.2","webpack-dev-server":"^3.11.0"},browser:{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},jsdelivr:"dist/axios.min.js",unpkg:"dist/axios.min.js",typings:"./index.d.ts",dependencies:{"follow-redirects":"^1.14.0"},bundlesize:[{path:"./dist/axios.min.js",threshold:"5kB"}]},Dg={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){Dg[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));var Ag={},Og=Ig.version.split(".");function Ng(e,t){for(var r=t?t.split("."):Og,n=e.split("."),i=0;i<3;i++){if(r[i]>n[i])return!0;if(r[i]<n[i])return!1}return!1}Dg.transitional=function(e,t,r){var n=t&&Ng(t);function i(e,t){return"[Axios v"+Ig.version+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return function(r,s,o){if(!1===e)throw new Error(i(s," has been removed in "+t));return n&&!Ag[s]&&(Ag[s]=!0,console.warn(i(s," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,s,o)}};var Mg={isOlderVersion:Ng,assertOptions:function(e,t,r){if("object"!=typeof e)throw new TypeError("options must be an object");for(var n=Object.keys(e),i=n.length;i-- >0;){var s=n[i],o=t[s];if(o){var a=e[s],c=void 0===a||o(a,s,e);if(!0!==c)throw new TypeError("option "+s+" must be "+c)}else if(!0!==r)throw Error("Unknown option "+s)}},validators:Dg},Lg=xm,xg=Um,Fg=Wm,jg=function(e){return Tg(e),e.headers=e.headers||{},e.data=Sg.call(e,e.data,e.headers,e.transformRequest),e.headers=wg.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),wg.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||Pg.adapter)(e).then((function(t){return Tg(e),t.data=Sg.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return Cg(t)||(Tg(e),t&&t.response&&(t.response.data=Sg.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},Ug=Rg,Bg=Mg,Vg=Bg.validators;function Wg(e){this.defaults=e,this.interceptors={request:new Fg,response:new Fg}}Wg.prototype.request=function(e){"string"==typeof e?(e=arguments[1]||{}).url=arguments[0]:e=e||{},(e=Ug(this.defaults,e)).method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var t=e.transitional;void 0!==t&&Bg.assertOptions(t,{silentJSONParsing:Vg.transitional(Vg.boolean,"1.0.0"),forcedJSONParsing:Vg.transitional(Vg.boolean,"1.0.0"),clarifyTimeoutError:Vg.transitional(Vg.boolean,"1.0.0")},!1);var r=[],n=!0;this.interceptors.request.forEach((function(t){"function"==typeof t.runWhen&&!1===t.runWhen(e)||(n=n&&t.synchronous,r.unshift(t.fulfilled,t.rejected))}));var i,s=[];if(this.interceptors.response.forEach((function(e){s.push(e.fulfilled,e.rejected)})),!n){var o=[jg,void 0];for(Array.prototype.unshift.apply(o,r),o=o.concat(s),i=Promise.resolve(e);o.length;)i=i.then(o.shift(),o.shift());return i}for(var a=e;r.length;){var c=r.shift(),d=r.shift();try{a=c(a)}catch(e){d(e);break}}try{i=jg(a)}catch(e){return Promise.reject(e)}for(;s.length;)i=i.then(s.shift(),s.shift());return i},Wg.prototype.getUri=function(e){return e=Ug(this.defaults,e),xg(e.url,e.params,e.paramsSerializer).replace(/^\?/,"")},Lg.forEach(["delete","get","head","options"],(function(e){Wg.prototype[e]=function(t,r){return this.request(Ug(r||{},{method:e,url:t,data:(r||{}).data}))}})),Lg.forEach(["post","put","patch"],(function(e){Wg.prototype[e]=function(t,r,n){return this.request(Ug(n||{},{method:e,url:t,data:r}))}}));var Hg=Wg;function qg(e){this.message=e}qg.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},qg.prototype.__CANCEL__=!0;var zg=qg,Gg=zg;function Yg(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var r=this;e((function(e){r.reason||(r.reason=new Gg(e),t(r.reason))}))}Yg.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},Yg.source=function(){var e,t=new Yg((function(t){e=t}));return{token:t,cancel:e}};var $g=Yg,Jg=xm,Kg=km,Qg=Hg,Zg=Rg;function Xg(e){var t=new Qg(e),r=Kg(Qg.prototype.request,t);return Jg.extend(r,Qg.prototype,t),Jg.extend(r,t),r}var ev=Xg(yg);ev.Axios=Qg,ev.create=function(e){return Xg(Zg(ev.defaults,e))},ev.Cancel=zg,ev.CancelToken=$g,ev.isCancel=Eg,ev.all=function(e){return Promise.all(e)},ev.spread=function(e){return function(t){return e.apply(null,t)}},ev.isAxiosError=function(e){return"object"==typeof e&&!0===e.isAxiosError},Tm.exports=ev,Tm.exports.default=ev;var tv=Tm.exports,rv="undefined"!=typeof Symbol&&Symbol,nv=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},iv="Function.prototype.bind called on incompatible ",sv=Array.prototype.slice,ov=Object.prototype.toString,av=function(e){var t=this;if("function"!=typeof t||"[object Function]"!==ov.call(t))throw new TypeError(iv+t);for(var r,n=sv.call(arguments,1),i=function(){if(this instanceof r){var i=t.apply(this,n.concat(sv.call(arguments)));return Object(i)===i?i:this}return t.apply(e,n.concat(sv.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},cv=Function.prototype.bind||av,dv="Function.prototype.bind called on incompatible ",uv=Array.prototype.slice,lv=Object.prototype.toString,pv=function(e){var t=this;if("function"!=typeof t||"[object Function]"!==lv.call(t))throw new TypeError(dv+t);for(var r,n=uv.call(arguments,1),i=function(){if(this instanceof r){var i=t.apply(this,n.concat(uv.call(arguments)));return Object(i)===i?i:this}return t.apply(e,n.concat(uv.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},hv=(Function.prototype.bind||pv).call(Function.call,Object.prototype.hasOwnProperty),fv=SyntaxError,mv=Function,gv=TypeError,vv=function(e){try{return mv('"use strict"; return ('+e+").constructor;")()}catch(e){}},yv=Object.getOwnPropertyDescriptor;if(yv)try{yv({},"")}catch(wt){yv=null}var _v=function(){throw new gv},bv=yv?function(){try{return _v}catch(e){try{return yv(arguments,"callee").get}catch(e){return _v}}}():_v,Ev="function"==typeof rv&&"function"==typeof Symbol&&"symbol"==typeof rv("foo")&&"symbol"==typeof Symbol("bar")&&nv(),wv=Object.getPrototypeOf||function(e){return e.__proto__},Sv={},Cv="undefined"==typeof Uint8Array?undefined:wv(Uint8Array),Pv={"%AggregateError%":"undefined"==typeof AggregateError?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":Ev?wv([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":Sv,"%AsyncGenerator%":Sv,"%AsyncGeneratorFunction%":Sv,"%AsyncIteratorPrototype%":Sv,"%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%":mv,"%GeneratorFunction%":Sv,"%Int8Array%":"undefined"==typeof Int8Array?undefined:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Ev?wv(wv([][Symbol.iterator]())):undefined,"%JSON%":"object"==typeof JSON?JSON:undefined,"%Map%":"undefined"==typeof Map?undefined:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&Ev?wv((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&&Ev?wv((new Set)[Symbol.iterator]()):undefined,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Ev?wv(""[Symbol.iterator]()):undefined,"%Symbol%":Ev?Symbol:undefined,"%SyntaxError%":fv,"%ThrowTypeError%":bv,"%TypedArray%":Cv,"%TypeError%":gv,"%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},Tv=function e(t){var r;if("%AsyncFunction%"===t)r=vv("async function () {}");else if("%GeneratorFunction%"===t)r=vv("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=vv("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&(r=wv(i.prototype))}return Pv[t]=r,r},kv={"%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"]},Rv=cv,Iv=hv,Dv=Rv.call(Function.call,Array.prototype.concat),Av=Rv.call(Function.apply,Array.prototype.splice),Ov=Rv.call(Function.call,String.prototype.replace),Nv=Rv.call(Function.call,String.prototype.slice),Mv=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Lv=/\\(\\)?/g,xv=function(e){var t=Nv(e,0,1),r=Nv(e,-1);if("%"===t&&"%"!==r)throw new fv("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new fv("invalid intrinsic syntax, expected opening `%`");var n=[];return Ov(e,Mv,(function(e,t,r,i){n[n.length]=r?Ov(i,Lv,"$1"):t||e})),n},Fv=function(e,t){var r,n=e;if(Iv(kv,n)&&(n="%"+(r=kv[n])[0]+"%"),Iv(Pv,n)){var i=Pv[n];if(i===Sv&&(i=Tv(n)),void 0===i&&!t)throw new gv("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:i}}throw new fv("intrinsic "+e+" does not exist!")},jv=function(e,t){if("string"!=typeof e||0===e.length)throw new gv("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new gv('"allowMissing" argument must be a boolean');var r=xv(e),n=r.length>0?r[0]:"",i=Fv("%"+n+"%",t),s=i.name,o=i.value,a=!1,c=i.alias;c&&(n=c[0],Av(r,Dv([0,1],c)));for(var d=1,u=!0;d<r.length;d+=1){var l=r[d],p=Nv(l,0,1),h=Nv(l,-1);if(('"'===p||"'"===p||"`"===p||'"'===h||"'"===h||"`"===h)&&p!==h)throw new fv("property names with quotes must have matching quotes");if("constructor"!==l&&u||(a=!0),Iv(Pv,s="%"+(n+="."+l)+"%"))o=Pv[s];else if(null!=o){if(!(l in o)){if(!t)throw new gv("base intrinsic for "+e+" exists, but the property is not available.");return}if(yv&&d+1>=r.length){var f=yv(o,l);o=(u=!!f)&&"get"in f&&!("originalValue"in f.get)?f.get:o[l]}else u=Iv(o,l),o=o[l];u&&!a&&(Pv[s]=o)}}return o},Uv={exports:{}};!function(e){var t=cv,r=jv,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}(Uv);var Bv=jv,Vv=Uv.exports,Wv=Vv(Bv("String.prototype.indexOf")),Hv=h(Object.freeze({__proto__:null,default:{}})),qv="function"==typeof Map&&Map.prototype,zv=Object.getOwnPropertyDescriptor&&qv?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Gv=qv&&zv&&"function"==typeof zv.get?zv.get:null,Yv=qv&&Map.prototype.forEach,$v="function"==typeof Set&&Set.prototype,Jv=Object.getOwnPropertyDescriptor&&$v?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,Kv=$v&&Jv&&"function"==typeof Jv.get?Jv.get:null,Qv=$v&&Set.prototype.forEach,Zv="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,Xv="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,ey="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,ty=Boolean.prototype.valueOf,ry=Object.prototype.toString,ny=Function.prototype.toString,iy=String.prototype.match,sy="function"==typeof BigInt?BigInt.prototype.valueOf:null,oy=Object.getOwnPropertySymbols,ay="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,cy="function"==typeof Symbol&&"object"==typeof Symbol.iterator,dy=Object.prototype.propertyIsEnumerable,uy=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null),ly=Hv.custom,py=ly&&vy(ly)?ly:null,hy="function"==typeof Symbol&&void 0!==Symbol.toStringTag?Symbol.toStringTag:null;function fy(e,t,r){var n="double"===(r.quoteStyle||t)?'"':"'";return n+e+n}function my(e){return String(e).replace(/"/g,""")}function gy(e){return!("[object Array]"!==by(e)||hy&&"object"==typeof e&&hy in e)}function vy(e){if(cy)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!ay)return!1;try{return ay.call(e),!0}catch(e){}return!1}var yy=Object.prototype.hasOwnProperty||function(e){return e in this};function _y(e,t){return yy.call(e,t)}function by(e){return ry.call(e)}function Ey(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 wy(e,t){if(e.length>t.maxStringLength){var r=e.length-t.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return wy(e.slice(0,t.maxStringLength),t)+n}return fy(e.replace(/(['\\])/g,"\\$1").replace(/[\x00-\x1f]/g,Sy),"single",t)}function Sy(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 Cy(e){return"Object("+e+")"}function Py(e){return e+" { ? }"}function Ty(e,t,r,n){return e+" ("+t+") {"+(n?ky(r,n):r.join(", "))+"}"}function ky(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+e.join(","+r)+"\n"+t.prev}function Ry(e,t){var r=gy(e),n=[];if(r){n.length=e.length;for(var i=0;i<e.length;i++)n[i]=_y(e,i)?t(e[i],e):""}var s,o="function"==typeof oy?oy(e):[];if(cy){s={};for(var a=0;a<o.length;a++)s["$"+o[a]]=o[a]}for(var c in e)_y(e,c)&&(r&&String(Number(c))===c&&c<e.length||cy&&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 oy)for(var d=0;d<o.length;d++)dy.call(e,o[d])&&n.push("["+t(o[d])+"]: "+t(e[o[d]],e));return n}var Iy=jv,Dy=function(e,t){var r=Bv(e,!!t);return"function"==typeof r&&Wv(e,".prototype.")>-1?Vv(r):r},Ay=function e(t,r,n,i){var s=r||{};if(_y(s,"quoteStyle")&&"single"!==s.quoteStyle&&"double"!==s.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(_y(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=!_y(s,"customInspect")||s.customInspect;if("boolean"!=typeof o&&"symbol"!==o)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(_y(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 wy(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 gy(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(Ey(i,t)>=0)return"[Circular]";function d(t,r,o){if(r&&(i=i.slice()).push(r),o){var a={depth:s.depth};return _y(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=iy.call(ny.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),l=Ry(t,d);return"[Function"+(u?": "+u:" (anonymous)")+"]"+(l.length>0?" { "+l.join(", ")+" }":"")}if(vy(t)){var p=cy?String(t).replace(/^(Symbol\(.*\))_[^)]*$/,"$1"):ay.call(t);return"object"!=typeof t||cy?p:Cy(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+"="+fy(my(f[m].value),"double",s);return h+=">",t.childNodes&&t.childNodes.length&&(h+="..."),h+="</"+String(t.nodeName).toLowerCase()+">"}if(gy(t)){if(0===t.length)return"[]";var g=Ry(t,d);return c&&!function(e){for(var t=0;t<e.length;t++)if(Ey(e[t],"\n")>=0)return!1;return!0}(g)?"["+ky(g,c)+"]":"[ "+g.join(", ")+" ]"}if(function(e){return!("[object Error]"!==by(e)||hy&&"object"==typeof e&&hy in e)}(t)){var v=Ry(t,d);return 0===v.length?"["+String(t)+"]":"{ ["+String(t)+"] "+v.join(", ")+" }"}if("object"==typeof t&&o){if(py&&"function"==typeof t[py])return t[py]();if("symbol"!==o&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Gv||!e||"object"!=typeof e)return!1;try{Gv.call(e);try{Kv.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var y=[];return Yv.call(t,(function(e,r){y.push(d(r,t,!0)+" => "+d(e,t))})),Ty("Map",Gv.call(t),y,c)}if(function(e){if(!Kv||!e||"object"!=typeof e)return!1;try{Kv.call(e);try{Gv.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var _=[];return Qv.call(t,(function(e){_.push(d(e,t))})),Ty("Set",Kv.call(t),_,c)}if(function(e){if(!Zv||!e||"object"!=typeof e)return!1;try{Zv.call(e,Zv);try{Xv.call(e,Xv)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Py("WeakMap");if(function(e){if(!Xv||!e||"object"!=typeof e)return!1;try{Xv.call(e,Xv);try{Zv.call(e,Zv)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Py("WeakSet");if(function(e){if(!ey||!e||"object"!=typeof e)return!1;try{return ey.call(e),!0}catch(e){}return!1}(t))return Py("WeakRef");if(function(e){return!("[object Number]"!==by(e)||hy&&"object"==typeof e&&hy in e)}(t))return Cy(d(Number(t)));if(function(e){if(!e||"object"!=typeof e||!sy)return!1;try{return sy.call(e),!0}catch(e){}return!1}(t))return Cy(d(sy.call(t)));if(function(e){return!("[object Boolean]"!==by(e)||hy&&"object"==typeof e&&hy in e)}(t))return Cy(ty.call(t));if(function(e){return!("[object String]"!==by(e)||hy&&"object"==typeof e&&hy in e)}(t))return Cy(d(String(t)));if(!function(e){return!("[object Date]"!==by(e)||hy&&"object"==typeof e&&hy in e)}(t)&&!function(e){return!("[object RegExp]"!==by(e)||hy&&"object"==typeof e&&hy in e)}(t)){var b=Ry(t,d),E=uy?uy(t)===Object.prototype:t instanceof Object||t.constructor===Object,w=t instanceof Object?"":"null prototype",S=!E&&hy&&Object(t)===t&&hy in t?by(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===b.length?C+"{}":c?C+"{"+ky(b,c)+"}":C+"{ "+b.join(", ")+" }"}return String(t)},Oy=Iy("%TypeError%"),Ny=Iy("%WeakMap%",!0),My=Iy("%Map%",!0),Ly=Dy("WeakMap.prototype.get",!0),xy=Dy("WeakMap.prototype.set",!0),Fy=Dy("WeakMap.prototype.has",!0),jy=Dy("Map.prototype.get",!0),Uy=Dy("Map.prototype.set",!0),By=Dy("Map.prototype.has",!0),Vy=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},Wy=String.prototype.replace,Hy=/%20/g,qy="RFC3986",zy={default:qy,formatters:{RFC1738:function(e){return Wy.call(e,Hy,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:qy},Gy=zy,Yy=Object.prototype.hasOwnProperty,$y=Array.isArray,Jy=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),Ky=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:Ky,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($y(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===Gy.RFC1738&&(40===c||41===c)?o+=s.charAt(a):c<128?o+=Jy[c]:c<2048?o+=Jy[192|c>>6]+Jy[128|63&c]:c<55296||c>=57344?o+=Jy[224|c>>12]+Jy[128|c>>6&63]+Jy[128|63&c]:(a+=1,c=65536+((1023&c)<<10|1023&s.charCodeAt(a)),o+=Jy[240|c>>18]+Jy[128|c>>12&63]+Jy[128|c>>6&63]+Jy[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($y(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($y(t))t.push(r);else{if(!t||"object"!=typeof t)return[t,r];(n&&(n.plainObjects||n.allowPrototypes)||!Yy.call(Object.prototype,r))&&(t[r]=!0)}return t}if(!t||"object"!=typeof t)return[t].concat(r);var i=t;return $y(t)&&!$y(r)&&(i=Ky(t,n)),$y(t)&&$y(r)?(r.forEach((function(r,i){if(Yy.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 Yy.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 Oy("Side channel does not contain "+Ay(e))},get:function(n){if(Ny&&n&&("object"==typeof n||"function"==typeof n)){if(e)return Ly(e,n)}else if(My){if(t)return jy(t,n)}else if(r)return function(e,t){var r=Vy(e,t);return r&&r.value}(r,n)},has:function(n){if(Ny&&n&&("object"==typeof n||"function"==typeof n)){if(e)return Fy(e,n)}else if(My){if(t)return By(t,n)}else if(r)return function(e,t){return!!Vy(e,t)}(r,n);return!1},set:function(n,i){Ny&&n&&("object"==typeof n||"function"==typeof n)?(e||(e=new Ny),xy(e,n,i)):My?(t||(t=new My),Uy(t,n,i)):(r||(r={key:{},next:null}),function(e,t,r){var n=Vy(e,t);n?n.value=r:e.next={key:t,next:e.next,value:r}}(r,n,i))}};return n},Xy=Qy,e_=zy,t_=Object.prototype.hasOwnProperty,r_={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},n_=Array.isArray,i_=String.prototype.split,s_=Array.prototype.push,o_=function(e,t){s_.apply(e,n_(t)?t:[t])},a_=Date.prototype.toISOString,c_=e_.default,d_={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:Xy.encode,encodeValuesOnly:!1,format:c_,formatter:e_.formatters[c_],indices:!1,serializeDate:function(e){return a_.call(e)},skipNulls:!1,strictNullHandling:!1},u_={},l_=function e(t,r,n,i,s,o,a,c,d,u,l,p,h,f,m,g){for(var v=t,y=g,_=0,b=!1;void 0!==(y=y.get(u_))&&!b;){var E=y.get(t);if(_+=1,void 0!==E){if(E===_)throw new RangeError("Cyclic object value");b=!0}void 0===y.get(u_)&&(_=0)}if("function"==typeof c?v=c(r,v):v instanceof Date?v=l(v):"comma"===n&&n_(v)&&(v=Xy.maybeMap(v,(function(e){return e instanceof Date?l(e):e}))),null===v){if(s)return a&&!f?a(r,d_.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)||Xy.isBuffer(v)){if(a){var w=f?r:a(r,d_.encoder,m,"key",p);if("comma"===n&&f){for(var S=i_.call(String(v),","),C="",P=0;P<S.length;++P)C+=(0===P?"":",")+h(a(S[P],d_.encoder,m,"value",p));return[h(w)+(i&&n_(v)&&1===S.length?"[]":"")+"="+C]}return[h(w)+"="+h(a(v,d_.encoder,m,"value",p))]}return[h(r)+"="+h(String(v))]}var T,k=[];if(void 0===v)return k;if("comma"===n&&n_(v))T=[{value:v.length>0?v.join(",")||null:void 0}];else if(n_(c))T=c;else{var R=Object.keys(v);T=d?R.sort(d):R}for(var I=i&&n_(v)&&1===v.length?r+"[]":r,D=0;D<T.length;++D){var A=T[D],O="object"==typeof A&&void 0!==A.value?A.value:v[A];if(!o||null!==O){var N=n_(v)?"function"==typeof n?n(I,A):I:I+(u?"."+A:"["+A+"]");g.set(t,_);var M=Zy();M.set(u_,g),o_(k,e(O,N,n,i,s,o,a,c,d,u,l,p,h,f,m,M))}}return k},p_=Qy,h_=Object.prototype.hasOwnProperty,f_=Array.isArray,m_={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:p_.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},g_=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},v_=function(e,t){return e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1?e.split(","):e},y_=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&&h_.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&&h_.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:v_(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 d_;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||d_.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=e_.default;if(void 0!==e.format){if(!t_.call(e_.formatters,e.format))throw new TypeError("Unknown format option provided.");r=e.format}var n=e_.formatters[r],i=d_.filter;return("function"==typeof e.filter||n_(e.filter))&&(i=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:d_.addQueryPrefix,allowDots:void 0===e.allowDots?d_.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:d_.charsetSentinel,delimiter:void 0===e.delimiter?d_.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:d_.encode,encoder:"function"==typeof e.encoder?e.encoder:d_.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:d_.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:d_.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:d_.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:d_.strictNullHandling}}(t);"function"==typeof i.filter?n=(0,i.filter)("",n):n_(i.filter)&&(r=i.filter);var s,o=[];if("object"!=typeof n||null===n)return"";s=t&&t.arrayFormat in r_?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var a=r_[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]||o_(o,l_(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:""},b_=function(e,t){var r=function(e){if(!e)return m_;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?m_.charset:e.charset;return{allowDots:void 0===e.allowDots?m_.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:m_.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:m_.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:m_.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:m_.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:m_.comma,decoder:"function"==typeof e.decoder?e.decoder:m_.decoder,delimiter:"string"==typeof e.delimiter||p_.isRegExp(e.delimiter)?e.delimiter:m_.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:m_.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:m_.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:m_.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:m_.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:m_.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,m_.decoder,c,"key"),u=t.strictNullHandling?null:""):(d=t.decoder(l.slice(0,h),m_.decoder,c,"key"),u=p_.maybeMap(v_(l.slice(h+1),t),(function(e){return t.decoder(e,m_.decoder,c,"value")}))),u&&t.interpretNumericEntities&&"iso-8859-1"===c&&(u=g_(u)),l.indexOf("[]=")>-1&&(u=f_(u)?[u]:u),h_.call(n,d)?n[d]=p_.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=y_(a,n[a],r,"string"==typeof e);i=p_.merge(i,c,r)}return!0===r.allowSparse?i:p_.compact(i)},E_={formats:zy,parse:b_,stringify:__};let w_=class{constructor(e){this.config=e;const t=this.config.get("loadbalancer"),{baseURL:r,timeout:n,customNode:i}=t;this.api=tv.create({baseURL:null!=r?r:"https://lb.livedigital.space/v1",timeout:null!=n?n:5e3,withCredentials:!1,paramsSerializer:e=>E_.stringify(e)}),this.customNode=i}getNode(e){return a(this,void 0,void 0,(function*(){if(this.customNode)return this.customNode;const{data:t}=yield this.api.get("/nodes/best",{params:e});return t}))}checkServiceAvailability(){return a(this,arguments,void 0,(function*(e=2e3){try{const{status:t}=yield this.api.options("/nodes/best",{timeout:e});return[ft.OK,ft.NoContent].includes(t)}catch(e){return!1}}))}setBaseUrl(e){try{const t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw new Error("Only http and https protocols are supported.");this.api.defaults.baseURL=t.toString()}catch(e){throw new Error("Invalid URL provided")}}};w_=i([at(),s(0,dt(Hn.Config)),o("design:paramtypes",[Pt])],w_);var S_,C_=w_;let P_=class{constructor(e,t){this.clientEventEmitter=e,this.isEnableVideoDevicesLock=!1,this.isEnableAudioDevicesLock=!1,this.isDevicesDetected=!1,this.availableVideoDevices=[],this.availableAudioDevices=[],S_.set(this,void 0),d(this,S_,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}requestMediaDevicesAccess(){return a(this,arguments,void 0,(function*(e={video:!0,audio:!0}){try{return(yield navigator.mediaDevices.getUserMedia(e)).getTracks()}catch(t){if(c(this,S_,"f").error("getUserMedia()",{error:t,constraints:e}),"NotAllowedError"===t.name)throw new Error(Gn.NotAllowedError);if("NotReadableError"===t.name)throw new Error(Gn.DeviceIsBusy);if("NotFoundError"===t.name)throw new Error(Gn.NotFoundError);throw new Error(Gn.RequestDevicesUnknownError)}}))}hasAvailableMediaDevicesList(){return a(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 a(this,void 0,void 0,(function*(){const e=yield navigator.mediaDevices.enumerateDevices(),t=[],r=[];e.forEach((e=>{""!==e.deviceId&&("videoinput"===e.kind&&t.push(e),"audioinput"===e.kind&&r.push(e))})),this.setAvailableVideoDevices(t),this.setAvailableAudioDevices(r);const n=({label:e,kind:t})=>({label:e,kind:t});return c(this,S_,"f").debug("Devices list updated",{videoDevices:t.map(n),audioDevices:r.map(n)}),e}))}detectDevices(e){return a(this,void 0,void 0,(function*(){if(this.isDevicesDetected&&!e)return;(yield this.hasAvailableMediaDevicesList())||(yield this.tryToAccessDevices()),this.isDevicesDetected=!0;const t=yield this.refreshAvailableMediaDevicesList(),r=t.some((e=>"audioinput"===e.kind)),n=t.some((e=>"videoinput"===e.kind));if(!r&&!n)throw new Error(Gn.NoDevices)}))}deviceChangeHandler(){return a(this,void 0,void 0,(function*(){if(!this.isDevicesDetected)return;yield this.refreshAvailableMediaDevicesList();const e={audio:this.availableAudioDevices,video:this.availableVideoDevices};this.clientEventEmitter.safeEmit(Ar,e)}))}listenDevices(){navigator.mediaDevices.addEventListener("devicechange",this.deviceChangeHandler)}assertHasAccessToMediaDevices(){return a(this,arguments,void 0,(function*(e={video:!0,audio:!0}){(yield this.requestMediaDevicesAccess(e)).forEach((e=>e.stop()))}))}tryToAccessDevices(){return a(this,void 0,void 0,(function*(){try{(yield this.requestMediaDevicesAccess()).forEach((e=>e.stop()))}catch(t){if(e=t.message,![Gn.NotFoundError,Gn.NotAllowedError,Gn.DeviceIsBusy].includes(e))throw t;t.message!==Gn.DeviceIsBusy&&(yield this.assertHasAccessToMediaDevices({audio:!0}),yield this.assertHasAccessToMediaDevices({video:!0}))}var e}))}};S_=new WeakMap,P_=i([at(),s(0,dt(Hn.ClientEventEmitter)),s(1,dt(Hn.LoggerFactory)),o("design:paramtypes",[Tt,Function])],P_);var T_,k_,R_,I_,D_,A_,O_=P_;class N_{constructor({transport:e,statsHandler:t}){T_.set(this,void 0),this.handleWebRTCStats(e,t)}get connectionStats(){return c(this,T_,"f")}handleWebRTCStats(e,t){t.addConnectionHandler(e.id,this.setConnectionStats.bind(this)),e.observer.once("close",(()=>{t.removeConnectionHandler(e.id)}))}setConnectionStats(e){d(this,T_,e,"f")}}T_=new WeakMap;let M_=class{constructor(){k_.set(this,new Map),R_.set(this,new Map),I_.set(this,new Map),D_.set(this,new Map),A_.set(this,new Map)}handle(e){e.forEach((({id:e,stats:t})=>{var r;null===(r=c(this,k_,"f").get(e))||void 0===r||r(t.connection),t.video.inbound.forEach((e=>{var t;return null===(t=c(this,R_,"f").get(e.trackIdentifier))||void 0===t?void 0:t(e)})),t.audio.inbound.forEach((e=>{var t;return null===(t=c(this,I_,"f").get(e.trackIdentifier))||void 0===t?void 0:t(e)})),t.video.outbound.forEach((e=>{var t;return null===(t=c(this,D_,"f").get(e.track.trackIdentifier))||void 0===t?void 0:t(e)})),t.audio.outbound.forEach((e=>{var t;return null===(t=c(this,A_,"f").get(e.track.trackIdentifier))||void 0===t?void 0:t(e)}))}))}addConnectionHandler(e,t){c(this,k_,"f").set(e,t)}addInboundVideoHandler(e,t){c(this,R_,"f").set(e,t)}addInboundAudioHandler(e,t){c(this,I_,"f").set(e,t)}addOutboundVideoHandler(e,t){c(this,D_,"f").set(e,t)}addOutboundAudioHandler(e,t){c(this,A_,"f").set(e,t)}removeConnectionHandler(e){c(this,k_,"f").delete(e)}removeInboundVideoHandler(e){c(this,R_,"f").delete(e)}removeInboundAudioHandler(e){c(this,D_,"f").delete(e)}removeOutboundVideoHandler(e){c(this,A_,"f").delete(e)}removeOutboundAudioHandler(e){c(this,A_,"f").delete(e)}clear(){c(this,k_,"f").clear(),c(this,R_,"f").clear(),c(this,I_,"f").clear(),c(this,D_,"f").clear(),c(this,A_,"f").clear()}};k_=new WeakMap,R_=new WeakMap,I_=new WeakMap,D_=new WeakMap,A_=new WeakMap,M_=i([at()],M_);var L_,x_,F_,j_,U_,B_,V_=M_;let W_=class{constructor(e){L_.set(this,!1),x_.set(this,void 0),F_.set(this,void 0),j_.set(this,void 0),U_.set(this,void 0),B_.set(this,void 0),d(this,x_,e("IntegrationsService"),"f")}init({sendTransportConnectionManager:e,receiveTransportConnectionManager:t,media:r,peers:n}){d(this,F_,e,"f"),d(this,j_,t,"f"),d(this,U_,r,"f"),d(this,B_,n,"f"),d(this,L_,!0,"f")}getStats(){try{return this.doGetStats()}catch(e){return c(this,x_,"f").error("Failed to get stats",{error:pr(e)}),{}}}clear(){d(this,F_,void 0,"f"),d(this,j_,void 0,"f"),d(this,U_,void 0,"f"),d(this,B_,void 0,"f")}doGetStats(){var e,t,r,n;if(!c(this,L_,"f"))throw new Error("TransportsStatsProvider is not initialized");return Object.assign(Object.assign({},(null===(t=null===(e=c(this,F_,"f"))||void 0===e?void 0:e.connectionStats)||void 0===t?void 0:t.id)?{outbound:Object.assign(Object.assign({},c(this,F_,"f").connectionStats),{bitrate:this.calculateOutboundTracksBitrate()})}:{}),(null===(n=null===(r=c(this,j_,"f"))||void 0===r?void 0:r.connectionStats)||void 0===n?void 0:n.id)?{inbound:Object.assign(Object.assign({},c(this,j_,"f").connectionStats),{bitrate:this.calculateInboundTracksBitrate()})}:{})}calculateInboundTracksBitrate(){if(void 0===c(this,B_,"f"))throw new Error("Peers is undefined");return c(this,B_,"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)}calculateOutboundTracksBitrate(){if(void 0===c(this,U_,"f"))throw new Error("Media is undefined");return c(this,U_,"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)}};L_=new WeakMap,x_=new WeakMap,F_=new WeakMap,j_=new WeakMap,U_=new WeakMap,B_=new WeakMap,W_=i([at(),s(0,dt(Hn.LoggerFactory)),o("design:paramtypes",[Function])],W_);var H_=W_;const q_=Array.from({length:256},((e,t)=>(t+256).toString(16).slice(1)));function z_(e=24){const t=new Uint8Array(e);crypto.getRandomValues(t);let r="";for(let e=0;e<t.length;e++)r+=q_[t[e]];return r}var G_,Y_,$_,J_;let K_=class{constructor(e,t,r,n,i,s,o,a,c,u,l,p,h,f,m,g,v,y,_,b){var E;this.state=e,this.myPeer=t,this.integrationsService=n,this.processorsCache=i,this.mediaEventHandler=s,this.channelEventsHandler=o,this.peerTrackFactory=a,this.peers=c,this.system=u,this.media=l,this.network=p,this.loadBalancerClient=h,this.socket=f,this.eventsQueue=m,this.clientEventEmitter=g,this.internalEventEmitter=v,this.statsHandler=y,this.transportsStatsProvider=_,this.webRtcIssueDetector=b,G_.set(this,void 0),Y_.set(this,void 0),this.rejoinRequested=!1,this.isReleasing=!1,$_.set(this,!1),J_.set(this,!1),this.mark=z_(),d(this,G_,r("Engine"),"f"),d(this,Y_,r,"f"),this.watchNetworkState(),this.watchDocumentUnload(),E=this.mark,window._sdkMarks||(window._sdkMarks=new Set),window._sdkMarks.add(E)}get isChannelJoined(){return this.state.isJoined}initialize(){return a(this,void 0,void 0,(function*(){var e,t,r,n;try{const{rtpCapabilities:i}=yield this.socket.request("router.getRtpCapabilities");this.integrationsService.init(),yield this.media.loadDevice(i),c(this,G_,"f").info("Supported capabilities",{codecs:jn(this.media.mediasoupDevice)});const[s,o]=yield Promise.all([this.network.createSendTransport(this.media.mediasoupDevice),this.network.createRecvTransport(this.media.mediasoupDevice),this.network.createSignalingTransport(this.media.mediasoupDevice)]);null===(e=this.webRtcIssueDetector)||void 0===e||e.handleNewPeerConnection(s.handler._pc,s.id),null===(t=this.webRtcIssueDetector)||void 0===t||t.handleNewPeerConnection(o.handler._pc,o.id),this.transportsStatsProvider.init({media:this.media,peers:this.peers,receiveTransportConnectionManager:new N_({transport:o,statsHandler:this.statsHandler}),sendTransportConnectionManager:new N_({transport:s,statsHandler:this.statsHandler})}),c(this,G_,"f").debug("initialize()",{sendTransportId:null===(r=this.network.sendTransport)||void 0===r?void 0:r.id,recvTransportId:null===(n=this.network.receiveTransport)||void 0===n?void 0:n.id}),yield this.network.createSignalingConsumer()}catch(e){c(this,G_,"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 An("Device not supported",An.UNSUPPORTED_DEVICE_CODE);throw new Error("Error initialize engine")}}))}release(e){return a(this,void 0,void 0,(function*(){var t;if(!this.isReleasing){this.isReleasing=!0;try{this.state.isJoined=!1,this.network.peersLoaded=!1,this.state.reset(),this.myPeer.delete(),null===(t=this.webRtcIssueDetector)||void 0===t||t.stopWatchingNewPeerConnections(),yield this.peers.reset(),this.network.closeSendTransport(),this.network.closeReceiveTransport(),yield this.network.closeConnectionTransport(),yield this.media.unpublishTracks(),e||this.media.clearTracks(),this.processorsCache.reset(),this.integrationsService.reset(),this.network.closeAllDataChannels(),this.removeClientEventEmitterListeners(),this.network.reset(),this.socket.disconnect(),hr.clear(),this.transportsStatsProvider.clear(),this.statsHandler.clear(),c(this,G_,"f").debug("release()",{socketId:this.myPeerId})}catch(e){throw c(this,G_,"f").error("release()",{error:e}),new Error("Error release engine")}finally{this.isReleasing=!1}}}))}removeClientEventEmitterListeners(){Array.from(Object.values($r)).forEach((e=>this.internalEventEmitter.removeAllListeners(e)))}getPeers(){return this.peers.all()}get myPeerId(){return this.myPeer.id}confirmActivity(){return a(this,void 0,void 0,(function*(){this.network.checkSocketConnectionActivity(),yield this.socket.request(yr)}))}join(e){return a(this,void 0,void 0,(function*(){const t=()=>a(this,void 0,void 0,(function*(){this.watchClientEvents(),yield this.connectToSocketServerWithRetry(e),yield this.performJoin({appData:e.appData})}));try{c(this,G_,"f").debug("join()",{params:e}),this.state.isChannelJoining=!0,yield Wn(t,{maxRetries:4,minBackoffDelayMs:150,maxBackoffDelayMs:5e3,actionName:"joinWithRetry",logger:c(this,Y_,"f").call(this,"RetryJoinNode"),onError:()=>a(this,void 0,void 0,(function*(){yield this.release(!0)}))})}catch(e){throw c(this,G_,"f").error("join()",{error:e}),e}finally{this.state.isChannelJoining=!1,this.rejoinRequested=!1}}))}loadPeers(e){return a(this,void 0,void 0,(function*(){yield this.peers.load(e)}))}requestChannelStateSync(){Wn((()=>a(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>a(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)?(c(this,G_,"f").info("Channel state event received",{case:"Engine.requestChannelStateSync"}),e()):t(new Error("Channel state event not received"))}),5e3),i=()=>{clearTimeout(n),this.clientEventEmitter.off(Fr,i),e()};this.clientEventEmitter.on(Fr,i)}))))}))),{minBackoffDelayMs:0,maxBackoffDelayMs:0,maxRetries:10,actionName:"triggerChannelStateEventWithRetry",logger:c(this,G_,"f")}).catch((e=>{c(this,G_,"f").error("Failed to request channel state event",{case:"Engine.requestChannelStateSync",error:pr(e)})}))}setPeer(e,t=!0){return this.peers.add(e,t)}removePeer(e){return a(this,void 0,void 0,(function*(){yield this.peers.remove(e)}))}updateAppData(e){return a(this,void 0,void 0,(function*(){const t=this.myPeer.get();if(!t)throw new Error("Need join to channel first");try{On(e),yield this.network.updatePeerAppData({peerId:t.id,appData:e})}catch(e){throw c(this,G_,"f").error("updateAppData()",{error:e}),new Error("Can not update peer appData")}}))}createCameraVideoTrack(e){return a(this,void 0,void 0,(function*(){const t=tm.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 Wf&&(r.setLabel((null==e?void 0:e.isPreview)?zn.CameraPreview:zn.Camera),r.setEncoderConfig(t.encoderConfig),r.setTransformParams(tm.getVideoTrackTransformParams(r.mediaStreamTrack))),this.media.setTrack(r),c(this,G_,"f").debug("createCameraVideoTrack()",{trackParams:t}),r}catch(e){throw c(this,G_,"f").error("createCameraVideoTrack()",{error:e,trackParams:t}),new Error(`Can not create camera track: ${e.message}`)}}))}createMicrophoneAudioTrack(e){return a(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)?zn.MicrophonePreview:zn.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()!==zn.Microphone||c(this,J_,"f")||this.media.initDenoiser(t,e).catch((t=>{this.clientEventEmitter.emit(Gr,{cause:"Failed to initialize denoiser",error:t}),c(this,G_,"f").error("Failed to execute initDenoiser",{case:"Denoiser",options:e,error:pr(t)})})),this.media.setTrack(t),c(this,G_,"f").debug("createMicrophoneAudioTrack()",{options:e,trackLabel:t.getLabel()}),t}catch(t){throw c(this,G_,"f").error("createMicrophoneAudioTrack()",{error:t,options:e}),new Error(`Can not create microphone track: ${t.message}`)}}))}createScreenMediaTracks(e){return a(this,void 0,void 0,(function*(){const t=tm.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=>{c(this,G_,"f").error("Failed to unpublish screen track",{error:pr(e)})}))}),{once:!0}),r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof Wf){r.setLabel(zn.ScreenVideo),r.setEncoderConfig(t.encoderConfig);const e=tm.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(e),this.media.setTrack(r),void c(this,G_,"f").debug("createScreenMediaTrack()",{trackParams:t,transformParams:e,label:r.logCtx})}r.setLabel(zn.ScreenAudio),(null==e?void 0:e.audioEncoderConfig)&&r.setEncoderConfig(e.audioEncoderConfig),this.media.setTrack(r),c(this,G_,"f").debug("createScreenMediaTrack()",{trackParams:null==e?void 0:e.audio,encoderConfig:null==e?void 0:e.audioEncoderConfig})})),r}catch(e){throw c(this,G_,"f").error("createScreenMediaTrack()",{error:e,trackParams:t}),new Error(`Can not create screen media tracks: ${e.message}`)}}))}createCustomAudioTrack(e){if(!e.audioTrack)throw 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=>{c(this,G_,"f").error("Failed to unpublish custom audio track",{track:t,error:pr(e)})}))}),{once:!0}),t.setStopTrackOnPause(Boolean(e.stopTrackOnPause)),t.setLabel(zn.CustomAudio),e.audioEncoderConfig&&t.setEncoderConfig(e.audioEncoderConfig),this.media.setTrack(t),c(this,G_,"f").debug("createCustomAudioTrack()",{trackParams:e.audio,encoderConfig:e.audioEncoderConfig}),t}catch(t){throw c(this,G_,"f").error("createCustomAudioTrack()",{error:t,trackParams:e.audioTrack}),new Error(`Can not create custom media tracks: ${t.message}`)}}createCustomVideoTrack(e){const t=tm.getScreenVideoTrackParams(e);if(!e.videoTrack)throw 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=>{c(this,G_,"f").error("Failed to unpublish custom video track",{track:r,error:pr(e)})}))}),{once:!0}),r.mediaStreamTrack.contentHint="customVideo",r.setLabel(zn.CustomVideo),r.setEncoderConfig(t.encoderConfig);const n=tm.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(n),this.media.setTrack(r),c(this,G_,"f").debug("createCustomVideoTrack()",{trackParams:t,transformParams:n,label:r.logCtx}),r}catch(e){throw c(this,G_,"f").error("createCustomVideoTrack()",{error:e,trackParams:t}),new Error(`Failed to create custom video track: ${e.message}`)}}deleteTrack(e){return a(this,void 0,void 0,(function*(){yield this.media.deleteTrack(e)}))}transportsStats(){return this.transportsStatsProvider.getStats()}setLoadbalancerUrl(e){if(this.isChannelJoined||this.rejoinRequested||this.state.isChannelJoining)throw new Error("Method not available when joined channel");this.loadBalancerClient.setBaseUrl(e)}connectToSocketServerWithRetry(e){return a(this,void 0,void 0,(function*(){yield Wn((()=>a(this,void 0,void 0,(function*(){return yield this.connectToSocketServer(e)}))),{maxRetries:15,minBackoffDelayMs:150,maxBackoffDelayMs:5e3,actionName:"connectToSocketServer",logger:c(this,Y_,"f").call(this,"RetrySocketConnect"),abortOnError:e=>{var t;return"unauthorized"===(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.errorCode)}})}))}connectToSocketServer(e){return a(this,void 0,void 0,(function*(){const t=e.isP2pCall?qn.P2P:qn.Common,{webSocketUrl:r}=yield this.getAvailableNode({datacenterType:t,channelId:e.channelId,role:e.role});this.socket.connect(r,e.token);try{yield this.waitForSocketConnection()}catch(t){throw c(this,G_,"f").error("Failed to connect to socket server",{error:t,role:e.role,channelId:e.channelId,webSocketUrl:r}),this.socket.disconnect(),t}}))}getAvailableNode(e){return a(this,void 0,void 0,(function*(){try{return{webSocketUrl:(yield this.loadBalancerClient.getNode(e)).webSocketUrl}}catch(e){throw c(this,G_,"f").error("getAvailableNode()",{error:"No available nodes"}),e}}))}waitForSocketConnection(){return a(this,void 0,void 0,(function*(){yield new Promise(((e,t)=>{const r=n=>{const{error:i,state:s}=n,o=()=>this.socket.observer.removeListener(Yn.State,r),a=[Yn.Disconnected,Yn.Reconnecting].includes(s);return i?(o(),void t(i)):this.state.isChannelJoining&&a?(o(),void t(new Error(`Not expected socket state for new connection: ${s}`))):void(this.state.isChannelJoining&&[Yn.Connected,Yn.Reconnected].includes(s)&&(o(),e()))};this.socket.observer.on(Yn.State,r)}))}))}performJoin(e){return a(this,void 0,void 0,(function*(){try{const{appId:t,channelId:r,peerId:n}=yield this.sendJoinChannelRequestWithRetry(e);this.myPeer.id=n,this.state.appId=t,this.state.channelId=r,yield this.initialize(),yield this.network.createAllDataChannels(),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)),hr.setPeerId(n),hr.setChannelId(r),hr.setAppId(t),yield Promise.all([this.network.waitForReceiveTransportConnected(),this.network.waitForChannelMessagesDataConsumerConnected()]),this.state.isJoined=!0,c(this,G_,"f").info("Successfully joined channel",{channelId:r})}catch(e){throw c(this,G_,"f").error("performJoin()",{error:e}),e}}))}sendJoinChannelRequestWithRetry(e){return a(this,void 0,void 0,(function*(){return yield Wn((()=>a(this,void 0,void 0,(function*(){return yield this.sendJoinChannelRequest(e)}))),{maxRetries:3,minBackoffDelayMs:300,actionName:"sendJoinChannelRequest",logger:c(this,Y_,"f").call(this,"RetryJoin")})}))}sendJoinChannelRequest(e){return a(this,void 0,void 0,(function*(){return yield this.socket.request(fr,e)}))}watchClientEvents(){this.internalEventEmitter.on($r.trackProduced,(e=>a(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.internalEventEmitter.on($r.trackUnproduced,(e=>a(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=>{c(this,G_,"f").debug("Failed to close peerTrack",{error:pr(e)})})),yield this.media.deleteTrack(e)})))),this.internalEventEmitter.on($r.trackPaused,(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=>{c(this,G_,"f").debug("Failed to pause peerTrack",{error:pr(e)})}))})),this.internalEventEmitter.on($r.trackResumed,(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=>{c(this,G_,"f").debug("Failed to resume peerTrack",{error:pr(e)})}))})),this.internalEventEmitter.on($r.trackClosed,(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=>{c(this,G_,"f").debug("Failed to close peerTrack",{error:pr(e)})}))})),this.internalEventEmitter.on($r.trackReopened,(e=>a(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.internalEventEmitter.on($r.trackFailed,(e=>{this.clientEventEmitter.safeEmit(Mr,{label:e.getLabel()})}))}createSelfPeerTrack(e){return a(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.rejoinRequested&&!this.state.isChannelJoining||(c(this,G_,"f").debug("Triggering channel rejoin required event",{reason:e}),this.rejoinRequested=!0,this.clientEventEmitter.emit(Dr))}watchNetworkState(){this.network.observer.on(Rn,(e=>{var t;if(this.isReleasing)return;const{code:r,error:n,state:i}=e,s="unauthorized"===(null===(t=null==n?void 0:n.data)||void 0===t?void 0:t.errorCode)&&this.isChannelJoined,o=r===Yn.NeedToJoinFirst&&this.isChannelJoined;if(s&&this.clientEventEmitter.safeEmit(Br),"server.disconnect"!==r||c(this,$_,"f")){if(o||s){const e=s?"unauthorized error":"invalid channel state";this.triggerRejoinEventIfAppropriate(e)}i===Yn.Disconnected&&this.isChannelJoined&&!c(this,$_,"f")&&c(this,G_,"f").info("connection lost",{channel:"socket"}),i===Yn.Reconnected&&this.isChannelJoined&&c(this,G_,"f").info("connection restored",{channel:"socket"}),i===Yn.BufferingStart&&(d(this,$_,!0,"f"),this.clientEventEmitter.safeEmit(Fr),this.waitForReconnectOrTriggerRejoinEventIfAppropriate()),[Yn.BufferingEnd,Yn.Reconnected].includes(i)&&this.network.isNetworkActive&&(d(this,$_,!1,"f"),this.clientEventEmitter.safeEmit(jr))}else this.clientEventEmitter.safeEmit(Ur)})),this.network.observer.on(In,(({state:e,direction:t})=>{if(!this.isReleasing&&(["disconnected","failed"].includes(e)&&this.isChannelJoined&&!c(this,$_,"f")&&(d(this,$_,!0,"f"),c(this,G_,"f").info("connection lost",{channel:"webrtc-transport",direction:t}),this.clientEventEmitter.safeEmit(Fr),this.waitForReconnectOrTriggerRejoinEventIfAppropriate()),"reconnected"===e&&this.isChannelJoined&&c(this,G_,"f").info("connection restored",{channel:"webrtc-transport",direction:t}),"reconnected"===e&&this.isChannelJoined&&c(this,$_,"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;d(this,$_,!1,"f"),this.clientEventEmitter.safeEmit(jr)}}))}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){c(this,G_,"f").error("Failed to add watchDocumentUnload listener",{channelId:this.state.channelId,error:pr(e)})}}waitForReconnectOrTriggerRejoinEventIfAppropriate(){c(this,G_,"f").info("Start waiting for seamless reconnect and check loadbalancer availability",{case:"waitForReconnectOrTriggerRejoinEventIfAppropriate"});let e=0;const t=setInterval((()=>a(this,void 0,void 0,(function*(){if(this.isReleasing||!this.state.isJoined)return clearInterval(t),void c(this,G_,"f").info("Stop waiting for seamless reconnect due to call end",{case:"waitForReconnectOrTriggerRejoinEventIfAppropriate"});try{if(!c(this,$_,"f"))return void clearInterval(t);if(!(yield this.loadBalancerClient.checkServiceAvailability(9e3)))return void(e=0);e+=1,e>6&&(clearInterval(t),this.triggerRejoinEventIfAppropriate("loadbalancer available"))}catch(e){c(this,G_,"f").error("Check failed",{error:pr(e),case:"waitForReconnectOrTriggerRejoinEventIfAppropriate"})}}))),1e4)}};G_=new WeakMap,Y_=new WeakMap,$_=new WeakMap,J_=new WeakMap,K_=i([at(),s(0,dt(Hn.CallState)),s(1,dt(Hn.MyPeer)),s(2,dt(Hn.LoggerFactory)),s(3,dt(Hn.IntegrationsService)),s(4,dt(Hn.ProcessorsCache)),s(5,dt(Hn.MediaEventHandler)),s(6,dt(Hn.ChannelEventHandler)),s(7,dt(Hn.PeerTrackFactory)),s(8,dt(Hn.Peers)),s(9,dt(Hn.System)),s(10,dt(Hn.Media)),s(11,dt(Hn.Network)),s(12,dt(Hn.LoadBalancerApiClient)),s(13,dt(Hn.SocketIO)),s(14,dt(Hn.EventsQueue)),s(15,dt(Hn.ClientEventEmitter)),s(16,dt(Hn.InternalEventEmitter)),s(17,dt(Hn.StatsHandler)),s(18,dt(Hn.TransportsStatsProvider)),s(19,dt(Hn.WebRTCIssueDetector)),o("design:paramtypes",[$n,js,Function,af,nf,Pm,ym,Function,Object,O_,tm,Aa,C_,la,xs,Tt,Tt,V_,H_,or])],K_);var Q_=K_;let Z_,X_=!1;const eb=()=>{try{return X_?null:window.localStorage}catch(e){return console.error("Get local storage error",{error:pr(e)}),e instanceof Error&&"SecurityError"===e.name&&(X_=!0),null}};function tb(e){const t=eb();if(!t)return null;try{const r=t.getItem(e);return r?JSON.parse(r):null}catch(e){return null}}const rb=()=>{if(Z_)return Z_;const e=tb("sdk_clientUniqueId");if(e)return Z_=e,e;const t=z_(12);return Z_=t,function(e,t){const r=eb();if(r)try{r.setItem(e,JSON.stringify(t))}catch(e){console.error(e)}}("sdk_clientUniqueId",t),t},nb=()=>{const e=tb("sdk_clientUniqueId");return e||(null!=Z_?Z_:rb())},ib=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 sb(e){return!e.response&&(!!e.code&&(!["ERR_CANCELED","ECONNABORTED"].includes(e.code)&&(e=>!ib.has(e&&e.code))(e)))}const ob=["get","head","options"],ab=ob.concat(["put","delete"]);function cb(e){return"ECONNABORTED"!==e.code&&(!e.response||429===e.response.status||e.response.status>=500&&e.response.status<=599)}function db(e){return!!e.config?.method&&(cb(e)&&-1!==ab.indexOf(e.config.method))}function ub(e){return sb(e)||db(e)}function lb(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 pb={retries:3,retryCondition:ub,retryDelay:function(e=0,t){return Math.max(0,lb(t))},shouldResetTimeout:!1,onRetry:()=>{},onMaxRetryTimesExceeded:()=>{},validateResponse:null};function hb(e,t,r=!1){const n=function(e,t){return{...pb,...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 fb=(e,t)=>{const r=e.interceptors.request.use((e=>(hb(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=hb(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}};fb.isNetworkError=sb,fb.isSafeRequestError=function(e){return!!e.config?.method&&(cb(e)&&-1!==ob.indexOf(e.config.method))},fb.isIdempotentRequestError=db,fb.isNetworkOrIdempotentRequestError=ub,fb.exponentialDelay=function(e=0,t,r=100){const n=2**e*r,i=Math.max(n,lb(t));return i+.2*i*Math.random()},fb.linearDelay=function(e=100){return(t=0,r)=>{const n=t*e;return Math.max(n,lb(r))}},fb.isRetryableError=cb;class mb{constructor(e){this.api=e,fb(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 a(this,void 0,void 0,(function*(){yield this.api.post("/log/batch",e)}))}}class gb{constructor(e){this.api=e,fb(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 a(this,void 0,void 0,(function*(){yield this.api.post("/analytics/network-metrics",e)}))}sendWIDMetrics(e){return a(this,void 0,void 0,(function*(){yield this.api.post("/analytics/wid-metrics",Object.assign({},e))}))}}let vb=class{constructor(){this.api=tv.create({baseURL:"https://moodhood-analytics.livedigital.space/v1",timeout:1e4,withCredentials:!0,paramsSerializer:e=>E_.stringify(e),headers:{"x-cl-id":nb()}}),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=i([at(),o("design:paramtypes",[])],vb);var yb=vb;const _b=new Error("request for lock canceled");var bb=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){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class Eb{constructor(e,t=_b){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=wb(this._queue,(e=>t<=e.priority));-1===s&&e<=this._value?this._dispatchItem(i):this._queue.splice(s+1,0,i)}))}runExclusive(e){return bb(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=wb(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 wb(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1}var Sb,Cb=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){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class Pb{constructor(e){this._semaphore=new Eb(1,e)}acquire(){return Cb(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 Tb=class{constructor(){Sb.set(this,new Map)}lock(e){return a(this,void 0,void 0,(function*(){let t=c(this,Sb,"f").get(e);return t||(t=new Pb,c(this,Sb,"f").set(e,t)),t.isLocked()&&(yield t.waitForUnlock()),yield t.acquire()}))}isLocked(e){const t=c(this,Sb,"f").get(e);return!!t&&t.isLocked()}waitForUnlock(e){return a(this,void 0,void 0,(function*(){const t=c(this,Sb,"f").get(e);(null==t?void 0:t.isLocked())?yield t.waitForUnlock():yield Promise.resolve()}))}};Sb=new WeakMap,Tb=i([at()],Tb);var kb=Tb,Rb={exports:{}},Ib=1e3,Db=60*Ib,Ab=60*Db,Ob=24*Ab,Nb=7*Ob,Mb=365.25*Ob,Lb=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*Mb;case"weeks":case"week":case"w":return r*Nb;case"days":case"day":case"d":return r*Ob;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Ab;case"minutes":case"minute":case"mins":case"min":case"m":return r*Db;case"seconds":case"second":case"secs":case"sec":case"s":return r*Ib;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>=Ob)return xb(e,t,Ob,"day");if(t>=Ab)return xb(e,t,Ab,"hour");if(t>=Db)return xb(e,t,Db,"minute");if(t>=Ib)return xb(e,t,Ib,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=Ob)return Math.round(e/Ob)+"d";if(t>=Ab)return Math.round(e/Ab)+"h";if(t>=Db)return Math.round(e/Db)+"m";if(t>=Ib)return Math.round(e/Ib)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function xb(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}var Fb=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=Lb,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=Fb(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Rb,Rb.exports);var jb,Ub,Bb=Rb.exports,Vb={},Wb={},Hb={},qb={exports:{}};
|
|
30
30
|
/**
|
|
31
31
|
* @license
|
|
32
32
|
* Lodash <https://lodash.com/>
|