@livedigital/client 3.54.1 → 3.54.2
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 +1 -1
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -26,7 +26,7 @@ MERCHANTABLITY OR NON-INFRINGEMENT.
|
|
|
26
26
|
|
|
27
27
|
See the Apache Version 2.0 License for specific language governing permissions
|
|
28
28
|
and limitations under the License.
|
|
29
|
-
***************************************************************************** */!function(e){!function(t){var r="object"==typeof globalThis?globalThis:"object"==typeof p?p:"object"==typeof self?self:"object"==typeof this?this:function(){try{return Function("return this;")()}catch(e){}}()||function(){try{return(0,eval)("(function() { return this; })()")}catch(e){}}(),n=i(e);function i(e,t){return function(r,n){Object.defineProperty(e,r,{configurable:!0,writable:!0,value:n}),t&&t(r,n)}}void 0!==r.Reflect&&(n=i(r.Reflect,n)),function(e,t){var r=Object.prototype.hasOwnProperty,n="function"==typeof Symbol,i=n&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",s=n&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",o="function"==typeof Object.create,a={__proto__:[]}instanceof Array,c=!o&&!a,d={create:o?function(){return le(Object.create(null))}:a?function(){return le({__proto__:null})}:function(){return le({})},has:c?function(e,t){return r.call(e,t)}:function(e,t){return t in e},get:c?function(e,t){return r.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},u=Object.getPrototypeOf(Function),l="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:ce(),p="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:de(),h="function"==typeof WeakMap?WeakMap:ue(),f=n?Symbol.for("@reflect-metadata:registry"):void 0,m=ie(),g=se(m);function v(e,t,r,n){if(F(r)){if(!G(e))throw new TypeError;if(!$(t))throw new TypeError;return R(e,t)}if(!G(e))throw new TypeError;if(!V(t))throw new TypeError;if(!V(n)&&!F(n)&&!j(n))throw new TypeError;return j(n)&&(n=void 0),k(e,t,r=z(r),n)}function y(e,t){function r(r,n){if(!V(r))throw new TypeError;if(!F(n)&&!J(n))throw new TypeError;M(e,t,r,n)}return r}function _(e,t,r,n){if(!V(r))throw new TypeError;return F(n)||(n=z(n)),M(e,t,r,n)}function b(e,t,r){if(!V(t))throw new TypeError;return F(r)||(r=z(r)),D(e,t,r)}function E(e,t,r){if(!V(t))throw new TypeError;return F(r)||(r=z(r)),I(e,t,r)}function w(e,t,r){if(!V(t))throw new TypeError;return F(r)||(r=z(r)),A(e,t,r)}function S(e,t,r){if(!V(t))throw new TypeError;return F(r)||(r=z(r)),O(e,t,r)}function C(e,t){if(!V(e))throw new TypeError;return F(t)||(t=z(t)),N(e,t)}function P(e,t){if(!V(e))throw new TypeError;return F(t)||(t=z(t)),L(e,t)}function T(e,t,r){if(!V(t))throw new TypeError;if(F(r)||(r=z(r)),!V(t))throw new TypeError;F(r)||(r=z(r));var n=ae(t,r,!1);return!F(n)&&n.OrdinaryDeleteMetadata(e,t,r)}function R(e,t){for(var r=e.length-1;r>=0;--r){var n=(0,e[r])(t);if(!F(n)&&!j(n)){if(!$(n))throw new TypeError;t=n}}return t}function k(e,t,r,n){for(var i=e.length-1;i>=0;--i){var s=(0,e[i])(t,r,n);if(!F(s)&&!j(s)){if(!V(s))throw new TypeError;n=s}}return n}function D(e,t,r){if(I(e,t,r))return!0;var n=re(t);return!j(n)&&D(e,n,r)}function I(e,t,r){var n=ae(t,r,!1);return!F(n)&&H(n.OrdinaryHasOwnMetadata(e,t,r))}function A(e,t,r){if(I(e,t,r))return O(e,t,r);var n=re(t);return j(n)?void 0:A(e,n,r)}function O(e,t,r){var n=ae(t,r,!1);if(!F(n))return n.OrdinaryGetOwnMetadata(e,t,r)}function M(e,t,r,n){ae(r,n,!0).OrdinaryDefineOwnMetadata(e,t,r,n)}function N(e,t){var r=L(e,t),n=re(e);if(null===n)return r;var i=N(n,t);if(i.length<=0)return r;if(r.length<=0)return i;for(var s=new p,o=[],a=0,c=r;a<c.length;a++){var d=c[a];s.has(d)||(s.add(d),o.push(d))}for(var u=0,l=i;u<l.length;u++){d=l[u];s.has(d)||(s.add(d),o.push(d))}return o}function L(e,t){var r=ae(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function x(e){if(null===e)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===e?1:6;default:return 6}}function F(e){return void 0===e}function j(e){return null===e}function U(e){return"symbol"==typeof e}function V(e){return"object"==typeof e?null!==e:"function"==typeof e}function B(e,t){switch(x(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var r=3===t?"string":5===t?"number":"default",n=K(e,i);if(void 0!==n){var s=n.call(e,r);if(V(s))throw new TypeError;return s}return W(e,"default"===r?"number":r)}function W(e,t){if("string"===t){var r=e.toString;if(Y(r))if(!V(i=r.call(e)))return i;if(Y(n=e.valueOf))if(!V(i=n.call(e)))return i}else{var n;if(Y(n=e.valueOf))if(!V(i=n.call(e)))return i;var i,s=e.toString;if(Y(s))if(!V(i=s.call(e)))return i}throw new TypeError}function H(e){return!!e}function q(e){return""+e}function z(e){var t=B(e,3);return U(t)?t:q(t)}function G(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function Y(e){return"function"==typeof e}function $(e){return"function"==typeof e}function J(e){switch(x(e)){case 3:case 4:return!0;default:return!1}}function Q(e,t){return e===t||e!=e&&t!=t}function K(e,t){var r=e[t];if(null!=r){if(!Y(r))throw new TypeError;return r}}function Z(e){var t=K(e,s);if(!Y(t))throw new TypeError;var r=t.call(e);if(!V(r))throw new TypeError;return r}function X(e){return e.value}function ee(e){var t=e.next();return!t.done&&t}function te(e){var t=e.return;t&&t.call(e)}function re(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===u)return t;if(t!==u)return t;var r=e.prototype,n=r&&Object.getPrototypeOf(r);if(null==n||n===Object.prototype)return t;var i=n.constructor;return"function"!=typeof i||i===e?t:i}function ne(){var e,r,n,i;F(f)||void 0===t.Reflect||f in t.Reflect||"function"!=typeof t.Reflect.defineMetadata||(e=oe(t.Reflect));var s=new h,o={registerProvider:a,getProvider:d,setProvider:m};return o;function a(t){if(!Object.isExtensible(o))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===t:break;case F(r):r=t;break;case r===t:break;case F(n):n=t;break;case n===t:break;default:void 0===i&&(i=new p),i.add(t)}}function c(t,s){if(!F(r)){if(r.isProviderFor(t,s))return r;if(!F(n)){if(n.isProviderFor(t,s))return r;if(!F(i))for(var o=Z(i);;){var a=ee(o);if(!a)return;var c=X(a);if(c.isProviderFor(t,s))return te(o),c}}}if(!F(e)&&e.isProviderFor(t,s))return e}function d(e,t){var r,n=s.get(e);return F(n)||(r=n.get(t)),F(r)?(F(r=c(e,t))||(F(n)&&(n=new l,s.set(e,n)),n.set(t,r)),r):r}function u(e){if(F(e))throw new TypeError;return r===e||n===e||!F(i)&&i.has(e)}function m(e,t,r){if(!u(r))throw new Error("Metadata provider not registered.");var n=d(e,t);if(n!==r){if(!F(n))return!1;var i=s.get(e);F(i)&&(i=new l,s.set(e,i)),i.set(t,r)}return!0}}function ie(){var e;return!F(f)&&V(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[f]),F(e)&&(e=ne()),!F(f)&&V(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,f,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function se(e){var t=new h,r={isProviderFor:function(e,r){var n=t.get(e);return!F(n)&&n.has(r)},OrdinaryDefineOwnMetadata:o,OrdinaryHasOwnMetadata:i,OrdinaryGetOwnMetadata:s,OrdinaryOwnMetadataKeys:a,OrdinaryDeleteMetadata:c};return m.registerProvider(r),r;function n(n,i,s){var o=t.get(n),a=!1;if(F(o)){if(!s)return;o=new l,t.set(n,o),a=!0}var c=o.get(i);if(F(c)){if(!s)return;if(c=new l,o.set(i,c),!e.setProvider(n,i,r))throw o.delete(i),a&&t.delete(n),new Error("Wrong provider for target.")}return c}function i(e,t,r){var i=n(t,r,!1);return!F(i)&&H(i.has(e))}function s(e,t,r){var i=n(t,r,!1);if(!F(i))return i.get(e)}function o(e,t,r,i){n(r,i,!0).set(e,t)}function a(e,t){var r=[],i=n(e,t,!1);if(F(i))return r;for(var s=Z(i.keys()),o=0;;){var a=ee(s);if(!a)return r.length=o,r;var c=X(a);try{r[o]=c}catch(e){try{te(s)}finally{throw e}}o++}}function c(e,r,i){var s=n(r,i,!1);if(F(s))return!1;if(!s.delete(e))return!1;if(0===s.size){var o=t.get(r);F(o)||(o.delete(i),0===o.size&&t.delete(o))}return!0}}function oe(e){var t=e.defineMetadata,r=e.hasOwnMetadata,n=e.getOwnMetadata,i=e.getOwnMetadataKeys,s=e.deleteMetadata,o=new h,a={isProviderFor:function(e,t){var r=o.get(e);return!(F(r)||!r.has(t))||!!i(e,t).length&&(F(r)&&(r=new p,o.set(e,r)),r.add(t),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:n,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:s};return a}function ae(e,t,r){var n=m.getProvider(e,t);if(!F(n))return n;if(r){if(m.setProvider(e,t,g))return g;throw new Error("Illegal state.")}}function ce(){var e={},t=[],r=function(){function e(e,t,r){this._index=0,this._keys=e,this._values=t,this._selector=r}return e.prototype["@@iterator"]=function(){return this},e.prototype[s]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var r=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:r,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}(),n=function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var r=this._find(e,!0);return this._values[r]=t,this},t.prototype.delete=function(t){var r=this._find(t,!1);if(r>=0){for(var n=this._keys.length,i=r+1;i<n;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,Q(t,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new r(this._keys,this._values,i)},t.prototype.values=function(){return new r(this._keys,this._values,o)},t.prototype.entries=function(){return new r(this._keys,this._values,a)},t.prototype["@@iterator"]=function(){return this.entries()},t.prototype[s]=function(){return this.entries()},t.prototype._find=function(e,t){if(!Q(this._cacheKey,e)){this._cacheIndex=-1;for(var r=0;r<this._keys.length;r++)if(Q(this._keys[r],e)){this._cacheIndex=r;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();return n;function i(e,t){return e}function o(e,t){return t}function a(e,t){return[e,t]}}function de(){return function(){function e(){this._map=new l}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[s]=function(){return this.keys()},e}()}function ue(){var e=16,t=d.create(),n=i();return function(){function e(){this._key=i()}return e.prototype.has=function(e){var t=s(e,!1);return void 0!==t&&d.has(t,this._key)},e.prototype.get=function(e){var t=s(e,!1);return void 0!==t?d.get(t,this._key):void 0},e.prototype.set=function(e,t){return s(e,!0)[this._key]=t,this},e.prototype.delete=function(e){var t=s(e,!1);return void 0!==t&&delete t[this._key]},e.prototype.clear=function(){this._key=i()},e}();function i(){var e;do{e="@@WeakMap@@"+c()}while(d.has(t,e));return t[e]=!0,e}function s(e,t){if(!r.call(e,n)){if(!t)return;Object.defineProperty(e,n,{value:d.create()})}return e[n]}function o(e,t){for(var r=0;r<t;++r)e[r]=255*Math.random()|0;return e}function a(e){if("function"==typeof Uint8Array){var t=new Uint8Array(e);return"undefined"!=typeof crypto?crypto.getRandomValues(t):"undefined"!=typeof msCrypto?msCrypto.getRandomValues(t):o(t,e),t}return o(new Array(e),e)}function c(){var t=a(e);t[6]=79&t[6]|64,t[8]=191&t[8]|128;for(var r="",n=0;n<e;++n){var i=t[n];4!==n&&6!==n&&8!==n||(r+="-"),i<16&&(r+="0"),r+=i.toString(16).toLowerCase()}return r}}function le(e){return e.__=void 0,delete e.__,e}e("decorate",v),e("metadata",y),e("defineMetadata",_),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)}()}(l||(l={}));var m=["inject","multi_inject","name","unmanaged","named","optional"],g="Request",v="Singleton",y="Transient",_="ConstantValue",b="Constructor",E="DynamicValue",w="Factory",S="Function",C="Instance",P="Invalid",T="Provider",R="ClassProperty",k="ConstructorArgument",D="Variable",I=0;function A(){return I++}var O=function(){function e(e,t){this.id=A(),this.activated=!1,this.serviceIdentifier=e,this.scope=t,this.type=P,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===v&&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}(),M="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.",L=function(e,t){return"onDeactivation() error in class "+e+": "+t},x=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}(),F=0,j=1;function U(e){return e instanceof RangeError||"Maximum call stack size exceeded"===e.message}function V(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=q(e.implementationType)),n=n+"\n "+t,e.constraint.metaData&&(n=n+" - "+e.constraint.metaData)}))),n}function W(e,t){return null!==e.parentRequest&&(e.parentRequest.serviceIdentifier===t||W(e.parentRequest,t))}function H(e){e.childRequests.forEach((function(e){if(W(e,e.serviceIdentifier)){var t=function(e){return function e(t,r){void 0===r&&(r=[]);var n=V(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)}H(e)}))}function q(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 z=function(){function e(e){this.id=A(),this.container=e}return e.prototype.addPlan=function(e){this.plan=e},e.prototype.setCurrentRequest=function(e){this.currentRequest=e},e}(),G=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}(),Y=function(e,t){this.parentContext=e,this.rootRequest=t},$=function(){function e(e){this._cb=e}return e.prototype.unwrap=function(){return this._cb()},e}(),J=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}(),Q=function(){function e(e,t,r,n){this.id=A(),this.type=e,this.serviceIdentifier=r;var i="symbol"==typeof t?function(e){return e.toString().slice(7,-1)}(t):t;this.name=new J(i||""),this.identifier=t,this.metadata=new Array;var s=null;"string"==typeof n?s=new G("named",n):n instanceof G&&(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 m.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 m.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 Z(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=X(o,e,t,r,n);null!==a&&s.push(a)}return s}(n,t,s,o,c||d?a.length:r.length),l=te(e,r,t);return K(K([],u,!0),l,!0)}function X(e,t,r,n,i){var s=i[e.toString()]||[],o=ne(s),a=!0!==o.unmanaged,c=n[e],d=o.inject||o.multiInject;if((c=d||c)instanceof $&&(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 Q(k,o.targetName,c);return u.metadata=s,u}return null}function ee(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 te(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=ne(d),l=u.targetName||c,p=ee(u.inject,u.multiInject,c,r),h=new Q(R,l,p);h.metadata=d,i.push(h)}var f=Object.getPrototypeOf(t.prototype).constructor;if(f!==Object){var m=te(e,f,r);i=K(K([],i,!0),m,!0)}return i}function re(e,t){var r=Object.getPrototypeOf(t.prototype).constructor;if(r!==Object){var n=Z(e,q(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:re(e,r)}return 0}function ne(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 ie=function(){function e(e,t,r,n,i){this.id=A(),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 se(e){return e._bindingDictionary}function oe(e,t,r,n,i){var s=ce(r.container,i.serviceIdentifier),o=[];return s.length===F&&r.container.options.autoBindInjectable&&"function"==typeof i.serviceIdentifier&&e.getConstructorMetadata(i.serviceIdentifier).compilerGeneratedMetadata&&(r.container.bind(i.serviceIdentifier).toSelf(),s=ce(r.container,i.serviceIdentifier)),o=t?s:s.filter((function(e){var t=new ie(e.serviceIdentifier,r,n,e,i);return e.constraint(t)})),function(e,t,r,n){switch(t.length){case F:if(r.isOptional())return t;var i=V(e),s=M;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,ce),new Error(s);case j:return t;default:if(r.isArray())return t;s="Ambiguous match found for serviceIdentifier: "+(i=V(e));throw s+=B(n,i,ce),new Error(s)}}(i.serviceIdentifier,o,i,r.container),o}function ae(e,t,r,n,i,s){var o,a;if(null===i){o=oe(e,t,n,null,s),a=new ie(r,n,null,o,s);var c=new Y(n,a);n.addPlan(c)}else o=oe(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===C&&null!==t.implementationType){var i=function(e,t){return Z(e,q(t),t,!1)}(e,t.implementationType);if(!n.container.options.skipBaseClassChecks){var o=re(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."}(q(t.implementationType));throw new Error(c)}}i.forEach((function(t){ae(e,!1,t.serviceIdentifier,n,r,t)}))}}))}function ce(e,t){var r=[],n=se(e);return n.hasKey(t)?r=n.get(t):null!==e.parent&&(r=ce(e.parent,t)),r}function de(e,t,r,n,i,s,o,a){void 0===a&&(a=!1);var c=new z(t),d=function(e,t,r,n,i,s){var o=new G(e?"multi_inject":"inject",r),a=new Q(t,n,r,o);if(void 0!==i){var c=new G(i,s);a.metadata.push(c)}return a}(r,n,i,"",s,o);try{return ae(e,a,i,c,null,d),c}catch(e){throw U(e)&&H(c.plan.rootRequest),e}}function ue(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&"function"==typeof e.then}function le(e){return!!ue(e)||Array.isArray(e)&&e.some(ue)}var pe,he=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},fe=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])}}},me=function(e,t,r){e.has(t.id)||e.set(t.id,r)},ge=function(e,t){e.cache=t,e.activated=!0,ue(t)&&ve(e,t)},ve=function(e,t){return he(void 0,void 0,void 0,(function(){var r,n;return fe(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"}(pe||(pe={}));var ye=function(){return ye=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},ye.apply(this,arguments)},_e=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},be=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])}}},Ee=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 we(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=le(n)),e}),{constructorInjections:[],propertyInjections:[],propertyRequests:[],isAsync:!1})}(t,r),s=ye(ye({},i),{constr:e});n=i.isAsync?function(e){return _e(this,void 0,void 0,(function(){var t,r;return be(this,(function(n){switch(n.label){case 0:return[4,Ce(e.constructorInjections)];case 1:return t=n.sent(),[4,Ce(e.propertyInjections)];case 2:return r=n.sent(),[2,Se(ye(ye({},e),{constructorInjections:t,propertyInjections:r}))]}}))}))}(s):Se(s)}else n=new e;return n}function Se(e){var t,r=new((t=e.constr).bind.apply(t,Ee([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 Ce(e){return _e(this,void 0,void 0,(function(){var t,r,n,i;return be(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 Pe(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 ue(r)?r.then((function(){return t})):t}function Te(e,t){e.scope!==v&&function(e,t){var r="Class cannot be instantiated in "+(e.scope===g?"request":"transient")+" scope.";if("function"==typeof e.onDeactivation)throw new Error(L(t.name,r));if(Reflect.hasMetadata("pre_destroy",t))throw new Error("@preDestroy error in class "+t.name+": "+r)}(e,t)}var Re=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},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])}}},De=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 De(e)(t)}));if(!t.target.isOptional()||0!==r.length){var o=r[0];return Me(e,t,o)}}},Ie=function(e,t){var r=function(e){switch(e.type){case w:return{factory:e.factory,factoryType:pe.Factory};case T:return{factory:e.provider,factoryType:pe.Provider};case E:return{factory:e.dynamicValue,factoryType:pe.DynamicValue};default:throw new Error("Unexpected factory type "+e.type)}}(e);return function(e,t){try{return e()}catch(e){throw U(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}))},Ae=function(e,t,r){var n,i=t.childRequests;switch(function(e){var t=null;switch(e.type){case _:case S:t=e.cache;break;case b:case C:t=e.implementationType;break;case E:t=e.dynamicValue;break;case T:t=e.provider;break;case w:t=e.factory}if(null===t){var r=V(e.serviceIdentifier);throw new Error("Invalid binding type: "+r)}}(r),r.type){case _:case S:n=r.cache;break;case b:n=r.implementationType;break;case C:n=function(e,t,r,n){Te(e,t);var i=we(t,r,n);return ue(i)?i.then((function(e){return Pe(t,e)})):Pe(t,i)}(r,r.implementationType,i,De(e));break;default:n=Ie(r,t.parentContext)}return n},Oe=function(e,t,r){var n=function(e,t){return t.scope===v&&t.activated?t.cache:t.scope===g&&e.has(t.id)?e.get(t.id):null}(e,t);return null!==n||function(e,t,r){t.scope===v&&ge(t,r),t.scope===g&&me(e,t,r)}(e,t,n=r()),n},Me=function(e,t,r){return Oe(e,r,(function(){var n=Ae(e,t,r);return n=ue(n)?n.then((function(e){return Ne(t,r,e)})):Ne(t,r,n)}))};function Ne(e,t,r){var n,i=Le(e.parentContext,t,r),s=Ue(e.parentContext.container),o=s.next();do{n=o.value;var a=e.parentContext,c=e.serviceIdentifier,d=je(n,c);i=ue(i)?Fe(d,a,i):xe(d,a,i),o=s.next()}while(!0!==o.done&&!se(n).hasKey(e.serviceIdentifier));return i}var Le=function(e,t,r){return"function"==typeof t.onActivation?t.onActivation(e,r):r},xe=function(e,t,r){for(var n=e.next();!n.done;){if(ue(r=n.value(t,r)))return Fe(e,t,r);n=e.next()}return r},Fe=function(e,t,r){return Re(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]}}))}))},je=function(e,t){var r=e._activations;return r.hasKey(t)?r.get(t).values():[].values()},Ue=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 Ve=function(e,t){var r=e.parentRequest;return null!==r&&(!!t(r)||Ve(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 G(e,t),r}},We=Be("named"),He=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}},qe=function(){function e(e){this._binding=e}return e.prototype.when=function(e){return this._binding.constraint=e,new ze(this._binding)},e.prototype.whenTargetNamed=function(e){return this._binding.constraint=We(e),new ze(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 ze(this._binding)},e.prototype.whenTargetTagged=function(e,t){return this._binding.constraint=Be(e)(t),new ze(this._binding)},e.prototype.whenInjectedInto=function(e){return this._binding.constraint=function(t){return null!==t&&He(e)(t.parentRequest)},new ze(this._binding)},e.prototype.whenParentNamed=function(e){return this._binding.constraint=function(t){return null!==t&&We(e)(t.parentRequest)},new ze(this._binding)},e.prototype.whenParentTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&Be(e)(t)(r.parentRequest)},new ze(this._binding)},e.prototype.whenAnyAncestorIs=function(e){return this._binding.constraint=function(t){return null!==t&&Ve(t,He(e))},new ze(this._binding)},e.prototype.whenNoAncestorIs=function(e){return this._binding.constraint=function(t){return null!==t&&!Ve(t,He(e))},new ze(this._binding)},e.prototype.whenAnyAncestorNamed=function(e){return this._binding.constraint=function(t){return null!==t&&Ve(t,We(e))},new ze(this._binding)},e.prototype.whenNoAncestorNamed=function(e){return this._binding.constraint=function(t){return null!==t&&!Ve(t,We(e))},new ze(this._binding)},e.prototype.whenAnyAncestorTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&Ve(r,Be(e)(t))},new ze(this._binding)},e.prototype.whenNoAncestorTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&!Ve(r,Be(e)(t))},new ze(this._binding)},e.prototype.whenAnyAncestorMatches=function(e){return this._binding.constraint=function(t){return null!==t&&Ve(t,e)},new ze(this._binding)},e.prototype.whenNoAncestorMatches=function(e){return this._binding.constraint=function(t){return null!==t&&!Ve(t,e)},new ze(this._binding)},e}(),ze=function(){function e(e){this._binding=e}return e.prototype.onActivation=function(e){return this._binding.onActivation=e,new qe(this._binding)},e.prototype.onDeactivation=function(e){return this._binding.onDeactivation=e,new qe(this._binding)},e}(),Ge=function(){function e(e){this._binding=e,this._bindingWhenSyntax=new qe(this._binding),this._bindingOnSyntax=new ze(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}(),Ye=function(){function e(e){this._binding=e}return e.prototype.inRequestScope=function(){return this._binding.scope=g,new Ge(this._binding)},e.prototype.inSingletonScope=function(){return this._binding.scope=v,new Ge(this._binding)},e.prototype.inTransientScope=function(){return this._binding.scope=y,new Ge(this._binding)},e}(),$e=function(){function e(e){this._binding=e,this._bindingWhenSyntax=new qe(this._binding),this._bindingOnSyntax=new ze(this._binding),this._bindingInSyntax=new Ye(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}(),Je=function(){function e(e){this._binding=e}return e.prototype.to=function(e){return this._binding.type=C,this._binding.implementationType=e,new $e(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=_,this._binding.cache=e,this._binding.dynamicValue=null,this._binding.implementationType=null,this._binding.scope=v,new Ge(this._binding)},e.prototype.toDynamicValue=function(e){return this._binding.type=E,this._binding.cache=null,this._binding.dynamicValue=e,this._binding.implementationType=null,new $e(this._binding)},e.prototype.toConstructor=function(e){return this._binding.type=b,this._binding.implementationType=e,this._binding.scope=v,new Ge(this._binding)},e.prototype.toFactory=function(e){return this._binding.type=w,this._binding.factory=e,this._binding.scope=v,new Ge(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=S,this._binding.scope=v,t},e.prototype.toAutoFactory=function(e){return this._binding.type=w,this._binding.factory=function(t){return function(){return t.container.get(e)}},this._binding.scope=v,new Ge(this._binding)},e.prototype.toAutoNamedFactory=function(e){return this._binding.type=w,this._binding.factory=function(t){return function(r){return t.container.getNamed(e,r)}},new Ge(this._binding)},e.prototype.toProvider=function(e){return this._binding.type=T,this._binding.provider=e,this._binding.scope=v,new Ge(this._binding)},e.prototype.toService=function(e){this.toDynamicValue((function(t){return t.container.get(e)}))},e}(),Qe=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}(),Ze=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}(),Xe=function(){return Xe=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},Xe.apply(this,arguments)},et=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},tt=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])}}},rt=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))},nt=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=y;else if(t.defaultScope!==v&&t.defaultScope!==y&&t.defaultScope!==g)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=A(),this._bindingDictionary=new Ke,this._snapshots=[],this._middleware=null,this._activations=new Ke,this._deactivations=new Ke,this.parent=null,this._metadataReader=new x,this._moduleActivationStore=new Ze}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=rt([t,r],n,!0).map((function(e){return se(e)})),a=se(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 et(this,void 0,void 0,(function(){var t,r,n,i,s;return tt(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 et(this,void 0,void 0,(function(){var t,r,n,i;return tt(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||y,r=new O(e,t);return this._bindingDictionary.add(e,r),new Je(r)},e.prototype.rebind=function(e){return this.unbind(e),this.bind(e)},e.prototype.rebindAsync=function(e){return et(this,void 0,void 0,(function(){return tt(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 et(this,void 0,void 0,(function(){var t;return tt(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 et(this,void 0,void 0,(function(){var e,t=this;return tt(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 Q(D,"",t,new G(r,n)),s=new z(e);return new ie(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(Qe.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 et(this,void 0,void 0,(function(){var t;return tt(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 et(this,void 0,void 0,(function(){var n;return tt(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(ue(i))return this._handleDeactivationError(i.then((function(){return r._propagateContainerDeactivationThenBindingAndPreDestroyAsync(e,t,n)})),n)}var s=this._propagateContainerDeactivationThenBindingAndPreDestroy(e,t,n);if(ue(s))return this._handleDeactivationError(s,n)}catch(e){if(e instanceof Error)throw new Error(L(n.name,e.message))}},e.prototype._handleDeactivationError=function(e,t){return et(this,void 0,void 0,(function(){var r;return tt(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(L(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(ue(i))return i.then((function(){return r._deactivateContainerAsync(e,t)}));n=t.next()}},e.prototype._deactivateContainerAsync=function(e,t){return et(this,void 0,void 0,(function(){var r;return tt(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=Xe(Xe({},e),{contextInterceptor:function(e){return e},targetType:D});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(le(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=de(e._metadataReader,e,t.isMultiInject,t.targetType,t.serviceIdentifier,t.key,t.value,t.avoidConstraints);return function(e){return De(e.plan.rootRequest.requestScope)(e.plan.rootRequest)}(r=t.contextInterceptor(r))}},e.prototype._deactivateIfSingleton=function(e){var t=this;if(e.activated)return ue(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(ue(this._deactivateIfSingleton(n)))throw new Error("Attempting to unbind dependency with asynchronous destruction (@preDestroy or onDeactivation)")}},e.prototype._deactivateSingletonsAsync=function(e){return et(this,void 0,void 0,(function(){var t=this;return tt(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 et(this,void 0,void 0,(function(){return tt(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: "+V(e))}},e.prototype._bindingDeactivationAndPreDestroy=function(e,t,r){var n=this;if("function"==typeof e.onDeactivation){var i=e.onDeactivation(t);if(ue(i))return i.then((function(){return n._preDestroy(r,t)}))}return this._preDestroy(r,t)},e.prototype._bindingDeactivationAndPreDestroyAsync=function(e,t,r){return et(this,void 0,void 0,(function(){return tt(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 it(e,t,r,n){!function(e){if(void 0!==e)throw new Error(N)}(t),ot("inversify:tagged",e,r.toString(),n)}function st(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 ot(e,t,r,n){var i=st(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 at(e){return function(t,r,n){"number"==typeof n?it(t,r,n,e):function(e,t,r){if(void 0!==e.prototype)throw new Error(N);ot("inversify:tagged_props",e.constructor,t,r)}(t,r,e)}}function ct(){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 dt,ut=(dt="inject",function(e){return function(t,r,n){if(void 0===e){var i="function"==typeof t?t.name:t.constructor.name;throw new Error("@inject called with undefined this could mean that the class "+i+" has a circular dependency problem. You can use a LazyServiceIdentifier to overcome this limitation.")}return at(new G(dt,e))(t,r,n)}});const lt=3,pt=4,ht=6,ft=7;var mt;!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"}(mt||(mt={}));var gt;const 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,d;gt.set(this,void 0),u(this,gt,{denoiser:null!==(t=e.denoiser)&&void 0!==t?t:"rnnoise",asdk:Object.assign(Object.assign({},vt),e.asdk),signalingServerUrl:null!==(r=e.signalingServerUrl)&&void 0!==r?r:String("https://signaling-api.livedigital.space/v1"),logLevel:null!==(n=e.logLevel)&&void 0!==n?n:lt,sendAnalytics:null!==(i=e.sendAnalytics)&&void 0!==i&&i,onLogMessage:null!==(s=e.onLogMessage)&&void 0!==s?s:_t,onIssues:null!==(o=e.onIssues)&&void 0!==o?o:_t,disableWid:null!==(a=e.disableWid)&&void 0!==a&&a,effectsSDKParams:Object.assign(Object.assign({},yt),e.effectsSDKParams),onNetworkScoresUpdated:null!==(c=e.onNetworkScoresUpdated)&&void 0!==c?c:_t,getStatsInterval:null!==(d=e.getStatsInterval)&&void 0!==d?d:5e3,staticFilesPath:e.staticFilesPath||window.location.origin},"f")}get(e){return d(this,gt,"f")[e]}set(e,t){d(this,gt,"f")[e]=t}};gt=new WeakMap,bt=s([ct(),a("design:paramtypes",[Object])],bt);var Et=bt;class wt extends e.EventEmitter{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}}Error;const St=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0}],Ct=({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]=Ct({from:e[r],seen:t.slice(),forceEnumerable:n}):i[r]=s);for(const{property:t,enumerable:r}of St)"string"==typeof e[t]&&Object.defineProperty(i,t,{value:e[t],enumerable:!!n||r,configurable:!0,writable:!0});return i};var Pt=e=>"object"==typeof e&&null!==e?Ct({from:e,seen:[],forceEnumerable:!0}):"function"==typeof e?`[Function: ${e.name||"anonymous"}]`:e;class Tt extends Error{constructor(e,t){var r;if(t instanceof Tt)return super(t.message),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this.errorCode=t.errorCode,void(this.cause=t.cause);const n=Pt(t),i=null!==(r=(e=>{if("string"==typeof e)return e;if(e instanceof Error)return e.message;if(e&&"object"==typeof e&&"message"in e){const t=e.message;return"string"==typeof t?t:void 0}})(n))&&void 0!==r?r:"Operation failed";super(i),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this.errorCode=e,this.cause=Pt(n)}}var Rt,kt,Dt,It;function At(){}function Ot(){Ot.init.call(this)}function Mt(e){return void 0===e._maxListeners?Ot.defaultMaxListeners:e._maxListeners}function Nt(e,t,r){if(t)e.call(r);else for(var n=e.length,i=Wt(e,n),s=0;s<n;++s)i[s].call(r)}function Lt(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,s=Wt(e,i),o=0;o<i;++o)s[o].call(r,n)}function xt(e,t,r,n,i){if(t)e.call(r,n,i);else for(var s=e.length,o=Wt(e,s),a=0;a<s;++a)o[a].call(r,n,i)}function Ft(e,t,r,n,i,s){if(t)e.call(r,n,i,s);else for(var o=e.length,a=Wt(e,o),c=0;c<o;++c)a[c].call(r,n,i,s)}function jt(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,s=Wt(e,i),o=0;o<i;++o)s[o].apply(r,n)}function Ut(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 At,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=Mt(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 Vt(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 Bt(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 Wt(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}At.prototype=Object.create(null),Ot.EventEmitter=Ot,Ot.usingDomains=!1,Ot.prototype.domain=void 0,Ot.prototype._events=void 0,Ot.prototype._maxListeners=void 0,Ot.defaultMaxListeners=10,Ot.init=function(){this.domain=null,Ot.usingDomains&&(void 0).active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new At,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Ot.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},Ot.prototype.getMaxListeners=function(){return Mt(this)},Ot.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:Nt(r,u,this);break;case 2:Lt(r,u,this,arguments[1]);break;case 3:xt(r,u,this,arguments[1],arguments[2]);break;case 4:Ft(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];jt(r,u,this,i)}return!0},Ot.prototype.addListener=function(e,t){return Ut(this,e,t,!1)},Ot.prototype.on=Ot.prototype.addListener,Ot.prototype.prependListener=function(e,t){return Ut(this,e,t,!0)},Ot.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,Vt(this,e,t)),this},Ot.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,Vt(this,e,t)),this},Ot.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 At:(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 At,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},Ot.prototype.off=function(e,t){return this.removeListener(e,t)},Ot.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new At,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new At: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 At,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},Ot.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):[]},Ot.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Bt.call(e,t)},Ot.prototype.listenerCount=Bt,Ot.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class Ht extends Ot{}!function(e){e.Issue="issue",e.NetworkScoresUpdated="network-scores-updated",e.StatsParsingFinished="stats-parsing-finished"}(Rt||(Rt={})),function(e){e.Network="network",e.CPU="cpu",e.Server="server",e.Stream="stream"}(kt||(kt={})),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"}(Dt||(Dt={})),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"}(It||(It={}));class qt extends Ot{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(qt.STATS_REPORTS_PARSED,{timeTaken:r,reportItems:t}),t.forEach((e=>{this.emit(qt.STATS_REPORT_READY_EVENT,e)}))}}const zt=(()=>{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 Gt{#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,zt({taskId:t,delayMs:35e3,callback:()=>delete this.#e[t]}),{outbound:r,inbound:i,connectionId:t,statsSamples:{inboundStatsSample:s,outboundStatsSample:n}}}calculateOutboundScore(e){const t=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!t.length)return;const r=this.#e[e.connection.id];if(!r)return;const n=[...r.remote?.audio.inbound||[],...r.remote?.video.inbound||[]],{packetsSent:i}=e.connection,s=r.connection.packetsSent,o=t.reduce(((e,t)=>{const r=n.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=1e3*c/t.length,u=i-s,l=o.packetsLost-o.lastPacketsLost,p=u&&l?Math.round(100*l/(u+l)):0;return{mos:this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:p}),stats:{avgJitter:d,rtt:a,packetsLoss:p}}}calculateInboundScore(e){const t=[...e.audio?.inbound,...e.video?.inbound];if(!t.length)return;const r=this.#e[e.connection.id];if(!r)return;const n=[...r.video?.inbound,...r.audio?.inbound],{packetsReceived:i}=e.connection,s=r.connection.packetsReceived,o=t.reduce(((e,t)=>{const r=n.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=1e3*c/t.length,u=i-s,l=o.packetsLost-o.lastPacketsLost,p=u&&l?Math.round(100*l/(u+l)):0;return{mos:this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:p}),stats:{avgJitter:d,rtt:a,packetsLoss:p}}}calculateMOS({avgJitter:e,rtt:t,packetsLoss:r}){const n=t+2*e+10;let i=n<160?93.2-n/40:93.2-(n-120)/10;i-=2.5*r;const s=1+.035*i+7e-6*i*(i-60)*(100-i);return Math.max(0,Math.min(5,s))}}class Yt{#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)&&zt({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 $t extends Yt{#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:kt.Network,reason:Dt.OutboundNetworkThroughput}),t):t}}class Jt extends Yt{#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=1e3*d/r.length,p=u/r.length,h=s-o,f=a.packetsLost-a.lastPacketsLost,m=h&&f?Math.round(100*f/(h+f)):0,g=m>this.#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:kt.Network,reason:Dt.InboundNetworkQuality,iceCandidate:e.connection.local.id}),b&&t.push({statsSample:S,type:kt.Server,reason:Dt.ServerIssue,iceCandidate:e.connection.remote.id}),E&&t.push({statsSample:S,type:kt.Network,reason:Dt.InboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),w&&t.push({statsSample:S,type:kt.Network,reason:Dt.NetworkMediaSyncFailure,iceCandidate:e.connection.local.id}),t}}class Qt extends Yt{#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:kt.Network,reason:Dt.NetworkMediaSyncFailure,ssrc:e.ssrc})})),r):r}}class Kt extends Yt{#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=1e3*d/r.length,l=s-o,p=a.packetsLost-a.lastPacketsLost,h=l&&p?Math.round(100*p/(l+p)):0,f=h>this.#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:kt.Network,reason:Dt.OutboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),g&&t.push({statsSample:v,type:kt.Network,reason:Dt.OutboundNetworkQuality,iceCandidate:e.connection.local.id}),t}}class Zt extends Yt{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:kt.CPU,reason:Dt.EncoderCPUThrottling,ssrc:e.ssrc}),"bandwidth"===e.qualityLimitationReason&&r.push({statsSample:i,type:kt.Network,reason:Dt.OutboundNetworkThroughput,ssrc:e.ssrc}))})),r):r}}class Xt extends Yt{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:kt.Stream,reason:Dt.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 er=e=>e.reduce(((e,t)=>e+t),0)/e.length,tr=(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)(er(e),e);return Math.sqrt(t)})(n)>r},rr=(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 nr extends Yt{#l;#p;#h;constructor(e={}){super(),this.#l=e.avgFreezeDurationThresholdMs??1e3,this.#p=e.frozenDurationThresholdPct??30,this.#h=e.minMosQuality??It.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(rr(t.ssrc,[r[r.length-1],e]))return;if(tr(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:kt.Stream,reason:Dt.FrozenVideoTrack,statsSample:{ssrcs:n.map((e=>e.ssrc))}}),this.deleteLastProcessedStats(e.connection.id)),t}}class ir extends Yt{#f;#m;#h;constructor(e={}){super(e),this.#f=e.volatilityThreshold??8,this.#m=e.affectedStreamsPercentThreshold??30,this.#h=e.minMosQuality??It.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(rr(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(tr(e.ssrc,r))return;const n=(e=>{if(0===e.length)throw new Error("Cannot calculate volatility for empty array");const t=er(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:kt.CPU,reason:Dt.DecoderCPUThrottling,statsSample:{affectedStreamsPercent:i,throtthedStreams:n}}),this.deleteLastProcessedStats(e.connection.id)),t}}class sr extends Yt{#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,kt.Stream,Dt.MissingAudioStreamData)),t.push(...this.detectMissingData(i,kt.Stream,Dt.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)}}const or=e=>"closed"===e.iceConnectionState||"closed"===e.connectionState,ar=(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 cr{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(!or(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 dr{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(!or(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()}),zt({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=ar(e,r,"bytesReceived"),e.packetRate=ar(e,r,"packetsReceived")})),e.audio.outbound.forEach((e=>{const r=t.audio.outbound.find((({id:t})=>t===e.id));e.bitrate=ar(e,r,"bytesSent"),e.packetRate=ar(e,r,"packetsSent")})),e.video.inbound.forEach((e=>{const r=t.video.inbound.find((({id:t})=>t===e.id));e.bitrate=ar(e,r,"bytesReceived"),e.packetRate=ar(e,r,"packetsReceived")})),e.video.outbound.forEach((e=>{const r=t.video.outbound.find((({id:t})=>t===e.id));e.bitrate=ar(e,r,"bytesSent"),e.packetRate=ar(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 ur{eventEmitter;#_=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;autoAddPeerConnections;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new Ht,e.onIssues&&this.eventEmitter.on(Rt.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(Rt.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new Zt,new Jt,new Kt,new Qt,new $t,new Xt,new nr,new ir,new sr],this.networkScoresCalculator=e.networkScoresCalculator??new Gt,this.compositeStatsParser=e.compositeStatsParser??new cr({statsParser:new dr({ignoreSSRCList:e.ignoreSSRCList,logger:this.logger})}),this.statsReporter=e.statsReporter??new qt({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.autoAddPeerConnections=e.autoAddPeerConnections??!0,this.autoAddPeerConnections&&this.wrapRTCPeerConnection(),this.statsReporter.on(qt.STATS_REPORT_READY_EVENT,(e=>{const t=this.calculateNetworkScores(e.stats);this.detectIssues({data:e.stats},t)})),this.statsReporter.on(qt.STATS_REPORTS_PARSED,(t=>{const r={timeTaken:t.timeTaken,ts:Date.now()};e.onStats&&e.onStats(t.reportItems),this.eventEmitter.emit(Rt.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(Rt.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(Rt.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}}var lr,pr,hr,fr,mr;let gr=class{constructor(){lr.set(this,void 0),pr.set(this,void 0),hr.set(this,void 0),fr.set(this,void 0),mr.set(this,void 0)}get meta(){return{peerId:d(this,lr,"f"),channelId:d(this,pr,"f"),appId:d(this,hr,"f"),datacenterName:d(this,fr,"f"),nodeId:d(this,mr,"f")}}setPeerId(e){u(this,lr,e,"f")}setChannelId(e){u(this,pr,e,"f")}setAppId(e){u(this,hr,e,"f")}setDatacenterName(e){u(this,fr,e,"f")}setNodeId(e){u(this,mr,e,"f")}clear(){u(this,lr,void 0,"f"),u(this,pr,void 0,"f"),u(this,hr,void 0,"f"),u(this,fr,void 0,"f")}};lr=new WeakMap,pr=new WeakMap,hr=new WeakMap,fr=new WeakMap,mr=new WeakMap,gr=s([ct()],gr);const vr="peer.updateAppData",yr="channel-event",_r="peer-joined",br="peer-left",Er="channel-activity-confirmation-required",wr="channel-activity-confirmation-acquired",Sr="channel-activity-confirmation-expired",Cr="channel-rejoin-required",Pr="devices-list-updated",Tr="transport-connection-timeout",Rr="track-force-closed",kr="track-failed",Dr="active-speaker-changed",Ir="channel-state-inconsistent",Ar="connection-lost",Or="connection-restored",Mr="denoiser-initializing",Nr="channel-state-synced",Lr="denoiser-enabled",xr="denoiser-disabled",Fr="denoiser-fallback",jr="denoiser-failed",Ur="volume-changed",Vr="track-produced",Br="track-unproduced",Wr="track-paused",Hr="track-resumed",qr="track-closed",zr="track-reopened",Gr="track-failed",Yr="media-published",$r="media-unpublished",Jr="publisher-paused",Qr="publisher-resumed",Kr="track-start",Zr="track-end",Xr="track-paused",en="track-resumed",tn="track-failed",rn="app-data-updated",nn="produce-permissions-changed",sn="groups-changed",on="peer.newProducer",an="producer.close",cn="producer.setMaxSpatialLayer",dn="producer.requestMaxSpatialLayer",un="consumer.close",ln="consumer.pause",pn="consumer.resume",hn="consumer.changeConsumerPreferredLayers",fn="transport.connectionTimeout",mn="transport-state";var gn;!function(e){e.CloseProducer="CloseProducer",e.Mute="Mute",e.Resume="Resume",e.Join="Join",e.Release="Release"}(gn||(gn={}));class vn extends Error{constructor(e,t,r){super(null!=e?e:"Unexpected Livedigital SDK error"),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this.errorCode=null!=t?t:"unknown_error",this.meta=r}}class yn extends vn{constructor(e,t,r){super(null!=e?e:yn.DEFAULT_MESSAGE,null!=t?t:"need_joined_to_channel",r)}}yn.DEFAULT_MESSAGE="Peer must join the channel before performing this request";class _n extends vn{constructor(e,t,r){super(null!=e?e:_n.DEFAULT_MESSAGE,null!=t?t:"unsupported_error",r)}}_n.UNSUPPORTED_DEVICE_CODE="unsupported_device_error",_n.UNSUPPORTED_OPERATION_CODE="unsupported_operation_error",_n.DEFAULT_MESSAGE="Unsupported operation";const bn=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")};var En={exports:{}},wn=h(En.exports=function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=90)}({17:function(e,t,r){t.__esModule=!0,t.default=void 0;var n=r(18),i=function(){function e(){}return e.getFirstMatch=function(e,t){var r=t.match(e);return r&&r.length>0&&r[1]||""},e.getSecondMatch=function(e,t){var r=t.match(e);return r&&r.length>1&&r[2]||""},e.matchAndReturnConst=function(e,t,r){if(e.test(t))return r},e.getWindowsVersionName=function(e){switch(e){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},e.getMacOSVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),10===t[0])switch(t[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}},e.getAndroidVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0},e.getVersionPrecision=function(e){return e.split(".").length},e.compareVersions=function(t,r,n){void 0===n&&(n=!1);var i=e.getVersionPrecision(t),s=e.getVersionPrecision(r),o=Math.max(i,s),a=0,c=e.map([t,r],(function(t){var r=o-e.getVersionPrecision(t),n=t+new Array(r+1).join(".0");return e.map(n.split("."),(function(e){return new Array(20-e.length).join("0")+e})).reverse()}));for(n&&(a=o-Math.min(i,s)),o-=1;o>=a;){if(c[0][o]>c[1][o])return 1;if(c[0][o]===c[1][o]){if(o===a)return 0;o-=1}else if(c[0][o]<c[1][o])return-1}},e.map=function(e,t){var r,n=[];if(Array.prototype.map)return Array.prototype.map.call(e,t);for(r=0;r<e.length;r+=1)n.push(t(e[r]));return n},e.find=function(e,t){var r,n;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(r=0,n=e.length;r<n;r+=1){var i=e[r];if(t(i,r))return i}},e.assign=function(e){for(var t,r,n=e,i=arguments.length,s=new Array(i>1?i-1:0),o=1;o<i;o++)s[o-1]=arguments[o];if(Object.assign)return Object.assign.apply(Object,[e].concat(s));var a=function(){var e=s[t];"object"==typeof e&&null!==e&&Object.keys(e).forEach((function(t){n[t]=e[t]}))};for(t=0,r=s.length;t<r;t+=1)a();return e},e.getBrowserAlias=function(e){return n.BROWSER_ALIASES_MAP[e]},e.getBrowserTypeByAlias=function(e){return n.BROWSER_MAP[e]||""},e}();t.default=i,e.exports=t.default},18:function(e,t,r){t.__esModule=!0,t.ENGINE_MAP=t.OS_MAP=t.PLATFORMS_MAP=t.BROWSER_MAP=t.BROWSER_ALIASES_MAP=void 0,t.BROWSER_ALIASES_MAP={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},t.BROWSER_MAP={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},t.PLATFORMS_MAP={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},t.OS_MAP={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},t.ENGINE_MAP={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"}},90:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(91))&&n.__esModule?n:{default:n},s=r(18);function o(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}var a=function(){function e(){}var t,r,n;return e.getParser=function(e,t){if(void 0===t&&(t=!1),"string"!=typeof e)throw new Error("UserAgent should be a string");return new i.default(e,t)},e.parse=function(e){return new i.default(e).getResult()},t=e,n=[{key:"BROWSER_MAP",get:function(){return s.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return s.ENGINE_MAP}},{key:"OS_MAP",get:function(){return s.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return s.PLATFORMS_MAP}}],(r=null)&&o(t.prototype,r),n&&o(t,n),e}();t.default=a,e.exports=t.default},91:function(e,t,r){t.__esModule=!0,t.default=void 0;var n=c(r(92)),i=c(r(93)),s=c(r(94)),o=c(r(95)),a=c(r(17));function c(e){return e&&e.__esModule?e:{default:e}}var d=function(){function e(e,t){if(void 0===t&&(t=!1),null==e||""===e)throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},!0!==t&&this.parse()}var t=e.prototype;return t.getUA=function(){return this._ua},t.test=function(e){return e.test(this._ua)},t.parseBrowser=function(){var e=this;this.parsedResult.browser={};var t=a.default.find(n.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.browser=t.describe(this.getUA())),this.parsedResult.browser},t.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},t.getBrowserName=function(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},t.getBrowserVersion=function(){return this.getBrowser().version},t.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},t.parseOS=function(){var e=this;this.parsedResult.os={};var t=a.default.find(i.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os},t.getOSName=function(e){var t=this.getOS().name;return e?String(t).toLowerCase()||"":t||""},t.getOSVersion=function(){return this.getOS().version},t.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},t.getPlatformType=function(e){void 0===e&&(e=!1);var t=this.getPlatform().type;return e?String(t).toLowerCase()||"":t||""},t.parsePlatform=function(){var e=this;this.parsedResult.platform={};var t=a.default.find(s.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform},t.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},t.getEngineName=function(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},t.parseEngine=function(){var e=this;this.parsedResult.engine={};var t=a.default.find(o.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine},t.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},t.getResult=function(){return a.default.assign({},this.parsedResult)},t.satisfies=function(e){var t=this,r={},n=0,i={},s=0;if(Object.keys(e).forEach((function(t){var o=e[t];"string"==typeof o?(i[t]=o,s+=1):"object"==typeof o&&(r[t]=o,n+=1)})),n>0){var o=Object.keys(r),c=a.default.find(o,(function(e){return t.isOS(e)}));if(c){var d=this.satisfies(r[c]);if(void 0!==d)return d}var u=a.default.find(o,(function(e){return t.isPlatform(e)}));if(u){var l=this.satisfies(r[u]);if(void 0!==l)return l}}if(s>0){var p=Object.keys(i),h=a.default.find(p,(function(e){return t.isBrowser(e,!0)}));if(void 0!==h)return this.compareVersion(i[h])}},t.isBrowser=function(e,t){void 0===t&&(t=!1);var r=this.getBrowserName().toLowerCase(),n=e.toLowerCase(),i=a.default.getBrowserTypeByAlias(n);return t&&i&&(n=i.toLowerCase()),n===r},t.compareVersion=function(e){var t=[0],r=e,n=!1,i=this.getBrowserVersion();if("string"==typeof i)return">"===e[0]||"<"===e[0]?(r=e.substr(1),"="===e[1]?(n=!0,r=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?r=e.substr(1):"~"===e[0]&&(n=!0,r=e.substr(1)),t.indexOf(a.default.compareVersions(i,r,n))>-1},t.isOS=function(e){return this.getOSName(!0)===String(e).toLowerCase()},t.isPlatform=function(e){return this.getPlatformType(!0)===String(e).toLowerCase()},t.isEngine=function(e){return this.getEngineName(!0)===String(e).toLowerCase()},t.is=function(e,t){return void 0===t&&(t=!1),this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)},t.some=function(e){var t=this;return void 0===e&&(e=[]),e.some((function(e){return t.is(e)}))},e}();t.default=d,e.exports=t.default},92:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=/version\/(\d+(\.?_?\d+)+)/i,o=[{test:[/googlebot/i],describe:function(e){var t={name:"Googlebot"},r=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/opera/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opr\/|opios/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/SamsungBrowser/i],describe:function(e){var t={name:"Samsung Internet for Android"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Whale/i],describe:function(e){var t={name:"NAVER Whale Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MZBrowser/i],describe:function(e){var t={name:"MZ Browser"},r=i.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/focus/i],describe:function(e){var t={name:"Focus"},r=i.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/swing/i],describe:function(e){var t={name:"Swing"},r=i.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/coast/i],describe:function(e){var t={name:"Opera Coast"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(e){var t={name:"Opera Touch"},r=i.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/yabrowser/i],describe:function(e){var t={name:"Yandex Browser"},r=i.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/ucbrowser/i],describe:function(e){var t={name:"UC Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Maxthon|mxios/i],describe:function(e){var t={name:"Maxthon"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/epiphany/i],describe:function(e){var t={name:"Epiphany"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/puffin/i],describe:function(e){var t={name:"Puffin"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sleipnir/i],describe:function(e){var t={name:"Sleipnir"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/k-meleon/i],describe:function(e){var t={name:"K-Meleon"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/micromessenger/i],describe:function(e){var t={name:"WeChat"},r=i.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/qqbrowser/i],describe:function(e){var t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},r=i.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/msie|trident/i],describe:function(e){var t={name:"Internet Explorer"},r=i.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/\sedg\//i],describe:function(e){var t={name:"Microsoft Edge"},r=i.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/edg([ea]|ios)/i],describe:function(e){var t={name:"Microsoft Edge"},r=i.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/vivaldi/i],describe:function(e){var t={name:"Vivaldi"},r=i.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/seamonkey/i],describe:function(e){var t={name:"SeaMonkey"},r=i.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sailfish/i],describe:function(e){var t={name:"Sailfish"},r=i.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return r&&(t.version=r),t}},{test:[/silk/i],describe:function(e){var t={name:"Amazon Silk"},r=i.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/phantom/i],describe:function(e){var t={name:"PhantomJS"},r=i.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/slimerjs/i],describe:function(e){var t={name:"SlimerJS"},r=i.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t={name:"BlackBerry"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t={name:"WebOS Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/bada/i],describe:function(e){var t={name:"Bada"},r=i.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/tizen/i],describe:function(e){var t={name:"Tizen"},r=i.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/qupzilla/i],describe:function(e){var t={name:"QupZilla"},r=i.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/firefox|iceweasel|fxios/i],describe:function(e){var t={name:"Firefox"},r=i.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/electron/i],describe:function(e){var t={name:"Electron"},r=i.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MiuiBrowser/i],describe:function(e){var t={name:"Miui"},r=i.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/chromium/i],describe:function(e){var t={name:"Chromium"},r=i.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/chrome|crios|crmo/i],describe:function(e){var t={name:"Chrome"},r=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/GSA/i],describe:function(e){var t={name:"Google Search"},r=i.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t={name:"Android Browser"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/playstation 4/i],describe:function(e){var t={name:"PlayStation 4"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/safari|applewebkit/i],describe:function(e){var t={name:"Safari"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/.*/i],describe:function(e){var t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:i.default.getFirstMatch(t,e),version:i.default.getSecondMatch(t,e)}}}];t.default=o,e.exports=t.default},93:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18),o=[{test:[/Roku\/DVP/],describe:function(e){var t=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:s.OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe:function(e){var t=i.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe:function(e){var t=i.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),r=i.default.getWindowsVersionName(t);return{name:s.OS_MAP.Windows,version:t,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e){var t={name:s.OS_MAP.iOS},r=i.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return r&&(t.version=r),t}},{test:[/macintosh/i],describe:function(e){var t=i.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),r=i.default.getMacOSVersionName(t),n={name:s.OS_MAP.MacOS,version:t};return r&&(n.versionName=r),n}},{test:[/(ipod|iphone|ipad)/i],describe:function(e){var t=i.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:s.OS_MAP.iOS,version:t}}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t=i.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),r=i.default.getAndroidVersionName(t),n={name:s.OS_MAP.Android,version:t};return r&&(n.versionName=r),n}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t=i.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),r={name:s.OS_MAP.WebOS};return t&&t.length&&(r.version=t),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t=i.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||i.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||i.default.getFirstMatch(/\bbb(\d+)/i,e);return{name:s.OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe:function(e){var t=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe:function(e){var t=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:function(){return{name:s.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:s.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e){var t=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.PlayStation4,version:t}}}];t.default=o,e.exports=t.default},94:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18),o=[{test:[/googlebot/i],describe:function(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe:function(e){var t=i.default.getFirstMatch(/(can-l01)/i,e)&&"Nova",r={type:s.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(r.model=t),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet}}},{test:function(e){var t=e.test(/ipod|iphone/i),r=e.test(/like (ipod|iphone)/i);return t&&!r},describe:function(e){var t=i.default.getFirstMatch(/(ipod|iphone)/i,e);return{type:s.PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"blackberry"===e.getBrowserName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e){return"bada"===e.getBrowserName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"windows phone"===e.getBrowserName()},describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(e){var t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(!0)&&t>=3},describe:function(){return{type:s.PLATFORMS_MAP.tablet}}},{test:function(e){return"android"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"macos"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e){return"windows"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.desktop}}},{test:function(e){return"linux"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.desktop}}},{test:function(e){return"playstation 4"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.tv}}},{test:function(e){return"roku"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.tv}}}];t.default=o,e.exports=t.default},95:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18),o=[{test:function(e){return"microsoft edge"===e.getBrowserName(!0)},describe:function(e){if(/\sedg\//i.test(e))return{name:s.ENGINE_MAP.Blink};var t=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:s.ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe:function(e){var t={name:s.ENGINE_MAP.Trident},r=i.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){return e.test(/presto/i)},describe:function(e){var t={name:s.ENGINE_MAP.Presto},r=i.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=e.test(/gecko/i),r=e.test(/like gecko/i);return t&&!r},describe:function(e){var t={name:s.ENGINE_MAP.Gecko},r=i.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:s.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e){var t={name:s.ENGINE_MAP.WebKit},r=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}}];t.default=o,e.exports=t.default}}));function Sn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Cn(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=Sn(n)&&Sn(s);(o&&!Cn(n,s)||!o&&n!==s)&&(i=!1)})),i}function Pn(e,t,r=!1){let n=null;return function(...i){return c(this,void 0,void 0,(function*(){const s=r&&!n;"number"==typeof n&&clearTimeout(n),n=setTimeout((()=>c(this,void 0,void 0,(function*(){n=null,r||(yield e.apply(this,i))}))),t),s&&(yield e.apply(this,i))}))}}function Tn(e,t){return c(this,void 0,void 0,(function*(){try{return yield e()}catch(e){return void(null==t||t(e))}}))}const Rn=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:[]},kn=e=>["video/vp9","vp9"].includes(e.toLowerCase()),Dn=Array.from({length:256},((e,t)=>(t+256).toString(16).slice(1)));function In(e=24){const t=new Uint8Array(e);crypto.getRandomValues(t);let r="";for(let e=0;e<t.length;e++)r+=Dn[t[e]];return r}class An{sleepMs(e){return c(this,void 0,void 0,(function*(){yield new Promise((t=>setTimeout(t,e)))}))}now(){return new Date(Date.now())}}const On=new An,Mn=(e,...t)=>c(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:Pt(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 On.sleepMs(Math.min(e,null!==(s=t.maxBackoffDelayMs)&&void 0!==s?s:e))}}}throw null!=c?c:new Error("retryAsync logic failed")}));var Nn,Ln,xn;!function(e){e.Config="Config",e.Engine="Engine",e.System="System",e.Media="Media",e.Network="Network",e.MediaEventHandler="MediaEventHandler",e.ChannelEventHandler="ChannelEventHandler",e.ChannelAudioObserverEventHandler="ChannelAudioObserverEventHandler",e.ChannelAudioObserverMissingProducerRestorer="ChannelAudioObserverMissingProducerRestorer",e.ChannelStateSynchronizer="ChannelStateSynchronizer",e.ChannelStateSyncEventHandler="ChannelStateSyncEventHandler",e.CompositeStatsParser="CompositeStatsParser",e.PeriodicStatsReporter="PeriodicStatsReporter",e.WIDIgnoreSsrcList="WIDIgnoreSsrcList",e.WebRTCIssueDetector="WebRTCIssueDetector",e.WIDStatsAdapter="WIDStatsAdapter",e.ScoresCalculator="ScoresCalculator",e.LoggerFactory="LoggerFactory",e.MediaStreamTrackManager="MediaStreamTrackManager",e.EventsQueue="EventsQueue",e.ClientEventEmitter="ClientEventEmitter",e.Peers="Peers",e.CallState="CallState",e.RemotePeerTracks="RemotePeerTracks",e.MyPeer="MyPeer",e.InternalEventEmitter="InternalEventEmitter",e.PeerTrackFactory="PeerTrackFactory",e.PeerFactory="PeerFactory",e.PeerConsumerFactory="PeerConsumerFactory",e.AudioTrackFactory="AudioTrackFactory",e.VideoTrackFactory="VideoTrackFactory",e.AudioTrackProcessorFactory="AudioTrackProcessorFactory",e.IntegrationsService="IntegrationsService",e.ProcessorsCache="ProcessorsCache",e.StatsHandler="StatsHandler",e.DataChannelsManager="DataChannelsManager",e.WIDHandler="WIDHandler",e.AnalyticsApiClient="AnalyticsApiClient",e.TransportsStatsProvider="TransportsStatsProvider",e.LocalMutex="LocalMutex",e.PeersStorage="PeersStorage",e.SignalingApiClient="SignalingApiClient",e.DatachannelHeartbeater="DatachannelHeartbeater",e.SignalingHeartbeater="SignalingHeartbeater",e.PendingClosureProducerStorage="PendingClosureProducerStorage",e.ProducerCloseManager="ProducerCloseManager",e.NetworkTransportPolicyManager="NetworkTransportPolicyManager",e.ClientMetaProvider="ClientMetaProvider"}(Nn||(Nn={})),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"}(Ln||(Ln={})),function(e){e.NotFoundError="NotFoundError",e.NoDevices="NoDevices",e.DeviceIsBusy="DeviceIsBusy",e.NotAllowedError="NotAllowedError",e.RequestDevicesUnknownError="RequestDevicesUnknownError"}(xn||(xn={}));let Fn=class{constructor(){this.isJoined=!1,this.isChannelJoining=!1}reset(){this.appId=void 0,this.channelId=void 0,this.isJoined=!1,this.isChannelJoining=!1}};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 Un(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)}}Fn=s([ct()],Fn);function Vn(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?Hn(n,i):Wn(n,i)}function Bn(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()+qn(s)+qn(i)}function Wn(e,t){return{lo:0|e,hi:0|t}}function Hn(e,t){return t=~t,e?e=1+~e:t+=1,Wn(e,t)}const qn=e=>{const t=String(e);return"0000000".slice(t.length)+t};function zn(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 Gn(){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 Yn=$n();function $n(){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()),Jn(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),Qn(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),Jn(e),Vn(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),Qn(e),Vn(e)),dec:(e,t)=>function(e,t){let r=Wn(e,t);const n=2147483648&r.hi;n&&(r=Hn(r.lo,r.hi));const i=Bn(r.lo,r.hi);return n?"-"+i:i}(e,t),uDec:(e,t)=>Bn(e,t)}}function Jn(e){if(!/^-?[0-9]+$/.test(e))throw new Error("invalid int64: "+e)}function Qn(e){if(!/^[0-9]+$/.test(e))throw new Error("invalid uint64: "+e)}const Kn=Symbol.for("@bufbuild/protobuf/text-encoding");function Zn(){if(null==globalThis[Kn]){const e=new globalThis.TextEncoder,t=new globalThis.TextDecoder;globalThis[Kn]={encodeUtf8:t=>e.encode(t),decodeUtf8:e=>t.decode(e),checkUtf8(e){try{return encodeURIComponent(e),!0}catch(e){return!1}}}}return globalThis[Kn]}var Xn;!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"}(Xn||(Xn={}));const ei=34028234663852886e22,ti=-34028234663852886e22;class ri{constructor(e=Zn().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(si(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return ii(e),zn(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>ei||e<ti))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){si(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){ii(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return ii(e),zn(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),r=new DataView(t.buffer),n=Yn.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=Yn.uEnc(e);return r.setInt32(0,n.lo,!0),r.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=Yn.enc(e);return Un(t.lo,t.hi,this.buf),this}sint64(e){const t=Yn.enc(e),r=t.hi>>31;return Un(t.lo<<1^r,(t.hi<<1|t.lo>>>31)^r,this.buf),this}uint64(e){const t=Yn.uEnc(e);return Un(t.lo,t.hi,this.buf),this}}class ni{constructor(e,t=Zn().decodeUtf8){this.decodeUtf8=t,this.varint64=jn,this.uint32=Gn,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 Xn.Varint:for(;128&this.buf[this.pos++];);break;case Xn.Bit64:this.pos+=4;case Xn.Bit32:this.pos+=4;break;case Xn.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Xn.StartGroup:for(;;){const[e,r]=this.tag();if(r===Xn.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 Yn.dec(...this.varint64())}uint64(){return Yn.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),r=-(1&e);return e=(e>>>1|(1&t)<<31)^r,t=t>>>1^r,Yn.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 Yn.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Yn.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 ii(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 si(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 oi={encode:(e,t=new ri)=>(0!==e.time&&t.uint32(8).int64(e.time),t),decode(e,t){const r=e instanceof ni?e:new ni(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=ai(r.int64());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON(e){return{time:(t=e.time,null!=t?globalThis.Number(e.time):0)};var t},toJSON(e){const t={};return 0!==e.time&&(t.time=Math.round(e.time)),t},create:e=>oi.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 ai(e){const t=globalThis.Number(e.toString());if(t>globalThis.Number.MAX_SAFE_INTEGER)throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");if(t<globalThis.Number.MIN_SAFE_INTEGER)throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");return t}var ci;function di(e){switch(e){case 0:case"NULL_VALUE":return ci.NULL_VALUE;default:return ci.UNRECOGNIZED}}!function(e){e[e.NULL_VALUE=0]="NULL_VALUE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(ci||(ci={}));const ui={encode:(e,t=new ri)=>(Object.entries(e.fields).forEach((([e,r])=>{void 0!==r&&li.encode({key:e,value:r},t.uint32(10).fork()).join()})),t),decode(e,t){const r=e instanceof ni?e:new ni(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=li.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:fi(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=>ui.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 li={encode:(e,t=new ri)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&pi.encode(pi.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof ni?e:new ni(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=pi.unwrap(pi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:mi(e.key)?globalThis.String(e.key):"",value:mi(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=>li.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 pi={encode:(e,t=new ri)=>(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&&ui.encode(ui.wrap(e.structValue),t.uint32(42).fork()).join(),void 0!==e.listValue&&hi.encode(hi.wrap(e.listValue),t.uint32(50).fork()).join(),t),decode(e,t){const r=e instanceof ni?e:new ni(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=ui.unwrap(ui.decode(r,r.uint32()));continue;case 6:if(50!==e)break;i.listValue=hi.unwrap(hi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({nullValue:mi(e.nullValue)?di(e.nullValue):void 0,numberValue:mi(e.numberValue)?globalThis.Number(e.numberValue):void 0,stringValue:mi(e.stringValue)?globalThis.String(e.stringValue):void 0,boolValue:mi(e.boolValue)?globalThis.Boolean(e.boolValue):void 0,structValue:fi(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 ci.NULL_VALUE:return"NULL_VALUE";case ci.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=>pi.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=ci.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 hi={encode(e,t=new ri){for(const r of e.values)pi.encode(pi.wrap(r),t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof ni?e:new ni(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(pi.unwrap(pi.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=>hi.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 fi(e){return"object"==typeof e&&null!==e}function mi(e){return null!=e}const gi={encode:(e,t=new ri)=>(Object.entries(e.event).forEach((([e,r])=>{void 0!==r&&vi.encode({key:e,value:r},t.uint32(10).fork()).join()})),t),decode(e,t){const r=e instanceof ni?e:new ni(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=vi.decode(r,r.uint32());void 0!==t.value&&(i.event[t.key]=t.value);continue}}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON(e){return{event:(t=e.event,"object"==typeof t&&null!==t?Object.entries(e.event).reduce(((e,[t,r])=>(e[t]=r,e)),{}):{})};var t},toJSON(e){const t={};if(e.event){const r=Object.entries(e.event);r.length>0&&(t.event={},r.forEach((([e,r])=>{t.event[e]=r})))}return t},create:e=>gi.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 vi={encode:(e,t=new ri)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&pi.encode(pi.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof ni?e:new ni(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=pi.unwrap(pi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:yi(e.key)?globalThis.String(e.key):"",value:yi(null==e?void 0:e.value)?e.value:void 0}),toJSON(e){const t={};return""!==e.key&&(t.key=e.key),void 0!==e.value&&(t.value=e.value),t},create:e=>vi.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 yi(e){return null!=e}var _i,bi;function Ei(e){switch(e){case 0:case"PEER_GROUP_UNSPECIFIED":return _i.PEER_GROUP_UNSPECIFIED;case 1:case"PEER_GROUP_MODERATOR":return _i.PEER_GROUP_MODERATOR;case 2:case"PEER_GROUP_USER":return _i.PEER_GROUP_USER;default:return _i.UNRECOGNIZED}}function wi(e){switch(e){case _i.PEER_GROUP_UNSPECIFIED:return"PEER_GROUP_UNSPECIFIED";case _i.PEER_GROUP_MODERATOR:return"PEER_GROUP_MODERATOR";case _i.PEER_GROUP_USER:return"PEER_GROUP_USER";case _i.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function Si(e){switch(e){case 0:case"PRODUCER_LABEL_UNSPECIFIED":return bi.PRODUCER_LABEL_UNSPECIFIED;case 1:case"PRODUCER_LABEL_CAMERA":return bi.PRODUCER_LABEL_CAMERA;case 2:case"PRODUCER_LABEL_MICROPHONE":return bi.PRODUCER_LABEL_MICROPHONE;case 3:case"PRODUCER_LABEL_SCREEN_VIDEO":return bi.PRODUCER_LABEL_SCREEN_VIDEO;case 4:case"PRODUCER_LABEL_SCREEN_AUDIO":return bi.PRODUCER_LABEL_SCREEN_AUDIO;case 5:case"PRODUCER_LABEL_CUSTOM_VIDEO":return bi.PRODUCER_LABEL_CUSTOM_VIDEO;case 6:case"PRODUCER_LABEL_CUSTOM_AUDIO":return bi.PRODUCER_LABEL_CUSTOM_AUDIO;case 7:case"PRODUCER_LABEL_UNKNOWN":return bi.PRODUCER_LABEL_UNKNOWN;default:return bi.UNRECOGNIZED}}function Ci(e){switch(e){case bi.PRODUCER_LABEL_UNSPECIFIED:return"PRODUCER_LABEL_UNSPECIFIED";case bi.PRODUCER_LABEL_CAMERA:return"PRODUCER_LABEL_CAMERA";case bi.PRODUCER_LABEL_MICROPHONE:return"PRODUCER_LABEL_MICROPHONE";case bi.PRODUCER_LABEL_SCREEN_VIDEO:return"PRODUCER_LABEL_SCREEN_VIDEO";case bi.PRODUCER_LABEL_SCREEN_AUDIO:return"PRODUCER_LABEL_SCREEN_AUDIO";case bi.PRODUCER_LABEL_CUSTOM_VIDEO:return"PRODUCER_LABEL_CUSTOM_VIDEO";case bi.PRODUCER_LABEL_CUSTOM_AUDIO:return"PRODUCER_LABEL_CUSTOM_AUDIO";case bi.PRODUCER_LABEL_UNKNOWN:return"PRODUCER_LABEL_UNKNOWN";case bi.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"}(_i||(_i={})),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"}(bi||(bi={}));const Pi={encode(e,t=new ri){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 ni?e:new ni(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=>Ei(e))):[],producePermissions:globalThis.Array.isArray(null==e?void 0:e.producePermissions)?e.producePermissions.map((e=>Si(e))):[],changedProducePermissions:globalThis.Array.isArray(null==e?void 0:e.changedProducePermissions)?e.changedProducePermissions.map((e=>Si(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=>wi(e)))),(null===(r=e.producePermissions)||void 0===r?void 0:r.length)&&(i.producePermissions=e.producePermissions.map((e=>Ci(e)))),(null===(n=e.changedProducePermissions)||void 0===n?void 0:n.length)&&(i.changedProducePermissions=e.changedProducePermissions.map((e=>Ci(e)))),i},create:e=>Pi.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 Ti={encode:(e,t=new ri)=>(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 ni?e:new ni(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=Ri(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:ki(e.seconds)?globalThis.Number(e.seconds):0,nanos:ki(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=>Ti.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 Ri(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 ki(e){return null!=e}var Di;function Ii(e){switch(e){case 0:case"PRODUCER_KIND_UNSPECIFIED":return Di.PRODUCER_KIND_UNSPECIFIED;case 1:case"PRODUCER_KIND_AUDIO":return Di.PRODUCER_KIND_AUDIO;case 2:case"PRODUCER_KIND_VIDEO":return Di.PRODUCER_KIND_VIDEO;default:return Di.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"}(Di||(Di={}));const Ai={encode(e,t=new ri){""!==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)pi.encode(pi.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 ni?e:new ni(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(pi.unwrap(pi.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:Oi(e.id)?globalThis.String(e.id):"",kind:Oi(e.kind)?Ii(e.kind):0,label:Oi(e.label)?Si(e.label):0,peerId:Oi(e.peerId)?globalThis.String(e.peerId):"",paused:!!Oi(e.paused)&&globalThis.Boolean(e.paused),encodings:globalThis.Array.isArray(null==e?void 0:e.encodings)?[...e.encodings]:[],maxSpatialLayer:Oi(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 Di.PRODUCER_KIND_UNSPECIFIED:return"PRODUCER_KIND_UNSPECIFIED";case Di.PRODUCER_KIND_AUDIO:return"PRODUCER_KIND_AUDIO";case Di.PRODUCER_KIND_VIDEO:return"PRODUCER_KIND_VIDEO";case Di.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.kind)),0!==e.label&&(r.label=Ci(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=>Ai.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 Oi(e){return null!=e}var Mi;function Ni(e){switch(e){case 0:case"PEER_ROLE_UNSPECIFIED":return Mi.PEER_ROLE_UNSPECIFIED;case 1:case"PEER_ROLE_HOST":return Mi.PEER_ROLE_HOST;case 2:case"PEER_ROLE_AUDIENCE":return Mi.PEER_ROLE_AUDIENCE;default:return Mi.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"}(Mi||(Mi={}));const Li={encode(e,t=new ri){""!==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)Ai.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&&xi.encode({key:e,value:r},t.uint32(66).fork()).join()})),0!==e.role&&t.uint32(72).int32(e.role),void 0!==e.loginDate&&Ti.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 ni?e:new ni(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(Ai.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=xi.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=Fi(Ti.decode(r,r.uint32()));continue;case 11:if(88===e){i.groups.push(r.int32());continue}if(90===e){const e=r.uint32()+r.pos;for(;r.pos<e;)i.groups.push(r.int32());continue}break;case 12:if(96===e){i.producePermissions.push(r.int32());continue}if(98===e){const e=r.uint32()+r.pos;for(;r.pos<e;)i.producePermissions.push(r.int32());continue}}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON(e){return{id:Ui(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=>Ai.fromJSON(e))):[],uid:Ui(e.uid)?globalThis.String(e.uid):"",appId:Ui(e.appId)?globalThis.String(e.appId):"",appData:(t=e.appData,"object"==typeof t&&null!==t?Object.entries(e.appData).reduce(((e,[t,r])=>(e[t]=r,e)),{}):{}),role:Ui(e.role)?Ni(e.role):0,loginDate:Ui(e.loginDate)?ji(e.loginDate):void 0,groups:globalThis.Array.isArray(null==e?void 0:e.groups)?e.groups.map((e=>Ei(e))):[],producePermissions:globalThis.Array.isArray(null==e?void 0:e.producePermissions)?e.producePermissions.map((e=>Si(e))):[]};var t},toJSON(e){var t,r,n,i;const s={};if(""!==e.id&&(s.id=e.id),(null===(t=e.channelIds)||void 0===t?void 0:t.length)&&(s.channelIds=e.channelIds),(null===(r=e.producers)||void 0===r?void 0:r.length)&&(s.producers=e.producers.map((e=>Ai.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 Mi.PEER_ROLE_UNSPECIFIED:return"PEER_ROLE_UNSPECIFIED";case Mi.PEER_ROLE_HOST:return"PEER_ROLE_HOST";case Mi.PEER_ROLE_AUDIENCE:return"PEER_ROLE_AUDIENCE";case Mi.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=>wi(e)))),(null===(i=e.producePermissions)||void 0===i?void 0:i.length)&&(s.producePermissions=e.producePermissions.map((e=>Ci(e)))),s},create:e=>Li.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=>Ai.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 xi={encode:(e,t=new ri)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&pi.encode(pi.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof ni?e:new ni(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=pi.unwrap(pi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:Ui(e.key)?globalThis.String(e.key):"",value:Ui(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=>xi.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 Fi(e){let t=1e3*(e.seconds||0);return t+=(e.nanos||0)/1e6,new globalThis.Date(t)}function ji(e){return e instanceof globalThis.Date?e:"string"==typeof e?new globalThis.Date(e):Fi(Ti.fromJSON(e))}function Ui(e){return null!=e}const Vi={encode(e,t=new ri){for(const r of e.peers)Li.encode(r,t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof ni?e:new ni(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(Li.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=>Li.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=>Li.toJSON(e)))),r},create:e=>Vi.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=>Li.fromPartial(e))))||[],r}};const Bi={encode:(e,t=new ri)=>(""!==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 ni?e:new ni(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:qi(e.id)?globalThis.String(e.id):"",paused:!!qi(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=>Bi.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 Wi={encode(e,t=new ri){""!==e.id&&t.uint32(10).string(e.id);for(const r of e.producers)Bi.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 ni?e:new ni(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(Bi.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:qi(e.id)?globalThis.String(e.id):"",producers:globalThis.Array.isArray(null==e?void 0:e.producers)?e.producers.map((e=>Bi.fromJSON(e))):[],appDataHash:qi(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=>Bi.toJSON(e)))),void 0!==e.appDataHash&&(r.appDataHash=e.appDataHash),r},create:e=>Wi.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=>Bi.fromPartial(e))))||[],i.appDataHash=null!==(n=e.appDataHash)&&void 0!==n?n:void 0,i}};const Hi={encode(e,t=new ri){for(const r of e.peers)Wi.encode(r,t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof ni?e:new ni(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(Wi.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=>Wi.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=>Wi.toJSON(e)))),r},create:e=>Hi.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=>Wi.fromPartial(e))))||[],r}};function qi(e){return null!=e}var zi;function Gi(e){switch(e){case 0:case"CHANNEL_EVENT_TYPE_UNSPECIFIED":return zi.CHANNEL_EVENT_TYPE_UNSPECIFIED;case 1:case"CHANNEL_EVENT_TYPE_CHANNEL_STATE":return zi.CHANNEL_EVENT_TYPE_CHANNEL_STATE;case 2:case"CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT":return zi.CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT;case 3:case"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED":return zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED;case 4:case"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED":return zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED;case 5:case"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED":return zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED;case 6:case"CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED":return zi.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED;case 7:case"CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED":return zi.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED;case 8:case"CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT":return zi.CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT;case 14:case"CHANNEL_EVENT_TYPE_PEER_JOINED":return zi.CHANNEL_EVENT_TYPE_PEER_JOINED;case 15:case"CHANNEL_EVENT_TYPE_PEER_LEFT":return zi.CHANNEL_EVENT_TYPE_PEER_LEFT;case 16:case"CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED":return zi.CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED;case 17:case"CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED":return zi.CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED;case 18:case"CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED":return zi.CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED;default:return zi.UNRECOGNIZED}}function Yi(e){switch(e){case zi.CHANNEL_EVENT_TYPE_UNSPECIFIED:return"CHANNEL_EVENT_TYPE_UNSPECIFIED";case zi.CHANNEL_EVENT_TYPE_CHANNEL_STATE:return"CHANNEL_EVENT_TYPE_CHANNEL_STATE";case zi.CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT:return"CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT";case zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED:return"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED";case zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED:return"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED";case zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED:return"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED";case zi.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED:return"CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED";case zi.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED:return"CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED";case zi.CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT:return"CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT";case zi.CHANNEL_EVENT_TYPE_PEER_JOINED:return"CHANNEL_EVENT_TYPE_PEER_JOINED";case zi.CHANNEL_EVENT_TYPE_PEER_LEFT:return"CHANNEL_EVENT_TYPE_PEER_LEFT";case zi.CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED:return"CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED";case zi.CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED:return"CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED";case zi.CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED:return"CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED";case zi.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"}(zi||(zi={}));const $i={encode:(e,t=new ri)=>(0!==e.eventType&&t.uint32(8).int32(e.eventType),void 0!==e.channelState&&Vi.encode(e.channelState,t.uint32(18).fork()).join(),void 0!==e.channelStateShort&&Hi.encode(e.channelStateShort,t.uint32(26).fork()).join(),void 0!==e.channelActivityConfirmationTime&&oi.encode(e.channelActivityConfirmationTime,t.uint32(34).fork()).join(),void 0!==e.channelManagementEvent&&gi.encode(e.channelManagementEvent,t.uint32(42).fork()).join(),void 0!==e.channelProducePermissions&&Pi.encode(e.channelProducePermissions,t.uint32(50).fork()).join(),void 0!==e.peer&&Li.encode(e.peer,t.uint32(58).fork()).join(),t),decode(e,t){const r=e instanceof ni?e:new ni(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=Vi.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.channelStateShort=Hi.decode(r,r.uint32());continue;case 4:if(34!==e)break;i.channelActivityConfirmationTime=oi.decode(r,r.uint32());continue;case 5:if(42!==e)break;i.channelManagementEvent=gi.decode(r,r.uint32());continue;case 6:if(50!==e)break;i.channelProducePermissions=Pi.decode(r,r.uint32());continue;case 7:if(58!==e)break;i.peer=Li.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({eventType:Ji(e.eventType)?Gi(e.eventType):0,channelState:Ji(e.channelState)?Vi.fromJSON(e.channelState):void 0,channelStateShort:Ji(e.channelStateShort)?Hi.fromJSON(e.channelStateShort):void 0,channelActivityConfirmationTime:Ji(e.channelActivityConfirmationTime)?oi.fromJSON(e.channelActivityConfirmationTime):void 0,channelManagementEvent:Ji(e.channelManagementEvent)?gi.fromJSON(e.channelManagementEvent):void 0,channelProducePermissions:Ji(e.channelProducePermissions)?Pi.fromJSON(e.channelProducePermissions):void 0,peer:Ji(e.peer)?Li.fromJSON(e.peer):void 0}),toJSON(e){const t={};return 0!==e.eventType&&(t.eventType=Yi(e.eventType)),void 0!==e.channelState&&(t.channelState=Vi.toJSON(e.channelState)),void 0!==e.channelStateShort&&(t.channelStateShort=Hi.toJSON(e.channelStateShort)),void 0!==e.channelActivityConfirmationTime&&(t.channelActivityConfirmationTime=oi.toJSON(e.channelActivityConfirmationTime)),void 0!==e.channelManagementEvent&&(t.channelManagementEvent=gi.toJSON(e.channelManagementEvent)),void 0!==e.channelProducePermissions&&(t.channelProducePermissions=Pi.toJSON(e.channelProducePermissions)),void 0!==e.peer&&(t.peer=Li.toJSON(e.peer)),t},create:e=>$i.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?Vi.fromPartial(e.channelState):void 0,r.channelStateShort=void 0!==e.channelStateShort&&null!==e.channelStateShort?Hi.fromPartial(e.channelStateShort):void 0,r.channelActivityConfirmationTime=void 0!==e.channelActivityConfirmationTime&&null!==e.channelActivityConfirmationTime?oi.fromPartial(e.channelActivityConfirmationTime):void 0,r.channelManagementEvent=void 0!==e.channelManagementEvent&&null!==e.channelManagementEvent?gi.fromPartial(e.channelManagementEvent):void 0,r.channelProducePermissions=void 0!==e.channelProducePermissions&&null!==e.channelProducePermissions?Pi.fromPartial(e.channelProducePermissions):void 0,r.peer=void 0!==e.peer&&null!==e.peer?Li.fromPartial(e.peer):void 0,r}};function Ji(e){return null!=e}const Qi={encode:(e,t=new ri)=>(""!==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 ni?e:new ni(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:Ki(e.id)?globalThis.String(e.id):"",peerId:Ki(e.peerId)?globalThis.String(e.peerId):"",producerPeerId:Ki(e.producerPeerId)?globalThis.String(e.producerPeerId):"",spatialLayer:Ki(e.spatialLayer)?globalThis.Number(e.spatialLayer):void 0,temporalLayer:Ki(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=>Qi.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 Ki(e){return null!=e}const Zi={encode:(e,t=new ri)=>(""!==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 ni?e:new ni(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:Xi(e.producerId)?globalThis.String(e.producerId):"",spatialLayer:Xi(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=>Zi.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 Xi(e){return null!=e}var es,ts;function rs(e){switch(e){case 0:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED":return es.TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED;case 1:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS":return es.TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS;case 2:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE":return es.TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE;default:return es.UNRECOGNIZED}}function ns(e){switch(e){case 0:case"TRANSPORT_DIRECTION_UNSPECIFIED":return ts.TRANSPORT_DIRECTION_UNSPECIFIED;case 1:case"TRANSPORT_DIRECTION_SEND":return ts.TRANSPORT_DIRECTION_SEND;case 2:case"TRANSPORT_DIRECTION_RECEIVE":return ts.TRANSPORT_DIRECTION_RECEIVE;default:return ts.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"}(es||(es={})),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"}(ts||(ts={}));const is={encode:(e,t=new ri)=>(""!==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 ni?e:new ni(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:ss(e.transportId)?globalThis.String(e.transportId):"",timeout:ss(e.timeout)?globalThis.Number(e.timeout):0,direction:ss(e.direction)?ns(e.direction):0,reason:ss(e.reason)?rs(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 ts.TRANSPORT_DIRECTION_UNSPECIFIED:return"TRANSPORT_DIRECTION_UNSPECIFIED";case ts.TRANSPORT_DIRECTION_SEND:return"TRANSPORT_DIRECTION_SEND";case ts.TRANSPORT_DIRECTION_RECEIVE:return"TRANSPORT_DIRECTION_RECEIVE";case ts.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.direction)),0!==e.reason&&(t.reason=function(e){switch(e){case es.TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED";case es.TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS";case es.TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE";case es.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.reason)),t},create:e=>is.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 ss(e){return null!=e}var os;function as(e){switch(e){case 0:case"MEDIA_EVENT_TYPE_UNSPECIFIED":return os.MEDIA_EVENT_TYPE_UNSPECIFIED;case 1:case"MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT":return os.MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT;case 2:case"MEDIA_EVENT_TYPE_PRODUCER_CREATED":return os.MEDIA_EVENT_TYPE_PRODUCER_CREATED;case 3:case"MEDIA_EVENT_TYPE_PRODUCER_PAUSED":return os.MEDIA_EVENT_TYPE_PRODUCER_PAUSED;case 4:case"MEDIA_EVENT_TYPE_PRODUCER_RESUMED":return os.MEDIA_EVENT_TYPE_PRODUCER_RESUMED;case 5:case"MEDIA_EVENT_TYPE_PRODUCER_CLOSED":return os.MEDIA_EVENT_TYPE_PRODUCER_CLOSED;case 6:case"MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED":return os.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED;case 7:case"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED":return os.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED;case 8:case"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED":return os.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED;case 9:case"MEDIA_EVENT_TYPE_CONSUMER_CLOSED":return os.MEDIA_EVENT_TYPE_CONSUMER_CLOSED;case 10:case"MEDIA_EVENT_TYPE_CONSUMER_PAUSED":return os.MEDIA_EVENT_TYPE_CONSUMER_PAUSED;case 11:case"MEDIA_EVENT_TYPE_CONSUMER_RESUMED":return os.MEDIA_EVENT_TYPE_CONSUMER_RESUMED;case 12:case"MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED":return os.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED;default:return os.UNRECOGNIZED}}function cs(e){switch(e){case os.MEDIA_EVENT_TYPE_UNSPECIFIED:return"MEDIA_EVENT_TYPE_UNSPECIFIED";case os.MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT:return"MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT";case os.MEDIA_EVENT_TYPE_PRODUCER_CREATED:return"MEDIA_EVENT_TYPE_PRODUCER_CREATED";case os.MEDIA_EVENT_TYPE_PRODUCER_PAUSED:return"MEDIA_EVENT_TYPE_PRODUCER_PAUSED";case os.MEDIA_EVENT_TYPE_PRODUCER_RESUMED:return"MEDIA_EVENT_TYPE_PRODUCER_RESUMED";case os.MEDIA_EVENT_TYPE_PRODUCER_CLOSED:return"MEDIA_EVENT_TYPE_PRODUCER_CLOSED";case os.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED:return"MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED";case os.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED:return"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED";case os.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED:return"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED";case os.MEDIA_EVENT_TYPE_CONSUMER_CLOSED:return"MEDIA_EVENT_TYPE_CONSUMER_CLOSED";case os.MEDIA_EVENT_TYPE_CONSUMER_PAUSED:return"MEDIA_EVENT_TYPE_CONSUMER_PAUSED";case os.MEDIA_EVENT_TYPE_CONSUMER_RESUMED:return"MEDIA_EVENT_TYPE_CONSUMER_RESUMED";case os.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED:return"MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED";case os.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"}(os||(os={}));const ds={encode:(e,t=new ri)=>(0!==e.eventType&&t.uint32(8).int32(e.eventType),void 0!==e.producer&&Ai.encode(e.producer,t.uint32(18).fork()).join(),void 0!==e.consumer&&Qi.encode(e.consumer,t.uint32(26).fork()).join(),void 0!==e.producerSpatialLayerRequest&&Zi.encode(e.producerSpatialLayerRequest,t.uint32(34).fork()).join(),void 0!==e.transportConnectionTimeout&&is.encode(e.transportConnectionTimeout,t.uint32(42).fork()).join(),t),decode(e,t){const r=e instanceof ni?e:new ni(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=Ai.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.consumer=Qi.decode(r,r.uint32());continue;case 4:if(34!==e)break;i.producerSpatialLayerRequest=Zi.decode(r,r.uint32());continue;case 5:if(42!==e)break;i.transportConnectionTimeout=is.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({eventType:us(e.eventType)?as(e.eventType):0,producer:us(e.producer)?Ai.fromJSON(e.producer):void 0,consumer:us(e.consumer)?Qi.fromJSON(e.consumer):void 0,producerSpatialLayerRequest:us(e.producerSpatialLayerRequest)?Zi.fromJSON(e.producerSpatialLayerRequest):void 0,transportConnectionTimeout:us(e.transportConnectionTimeout)?is.fromJSON(e.transportConnectionTimeout):void 0}),toJSON(e){const t={};return 0!==e.eventType&&(t.eventType=cs(e.eventType)),void 0!==e.producer&&(t.producer=Ai.toJSON(e.producer)),void 0!==e.consumer&&(t.consumer=Qi.toJSON(e.consumer)),void 0!==e.producerSpatialLayerRequest&&(t.producerSpatialLayerRequest=Zi.toJSON(e.producerSpatialLayerRequest)),void 0!==e.transportConnectionTimeout&&(t.transportConnectionTimeout=is.toJSON(e.transportConnectionTimeout)),t},create:e=>ds.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?Ai.fromPartial(e.producer):void 0,r.consumer=void 0!==e.consumer&&null!==e.consumer?Qi.fromPartial(e.consumer):void 0,r.producerSpatialLayerRequest=void 0!==e.producerSpatialLayerRequest&&null!==e.producerSpatialLayerRequest?Zi.fromPartial(e.producerSpatialLayerRequest):void 0,r.transportConnectionTimeout=void 0!==e.transportConnectionTimeout&&null!==e.transportConnectionTimeout?is.fromPartial(e.transportConnectionTimeout):void 0,r}};function us(e){return null!=e}const ls={encode:(e,t=new ri)=>(0!==e.id&&t.uint32(8).int32(e.id),void 0!==e.channelEvent&&$i.encode(e.channelEvent,t.uint32(18).fork()).join(),void 0!==e.mediaEvent&&ds.encode(e.mediaEvent,t.uint32(26).fork()).join(),t),decode(e,t){const r=e instanceof ni?e:new ni(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=$i.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.mediaEvent=ds.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({id:ps(e.id)?globalThis.Number(e.id):0,channelEvent:ps(e.channelEvent)?$i.fromJSON(e.channelEvent):void 0,mediaEvent:ps(e.mediaEvent)?ds.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=$i.toJSON(e.channelEvent)),void 0!==e.mediaEvent&&(t.mediaEvent=ds.toJSON(e.mediaEvent)),t},create:e=>ls.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?$i.fromPartial(e.channelEvent):void 0,r.mediaEvent=void 0!==e.mediaEvent&&null!==e.mediaEvent?ds.fromPartial(e.mediaEvent):void 0,r}};function ps(e){return null!=e}var hs,fs,ms,gs,vs,ys,_s,bs;let Es=class{constructor(e){hs.set(this,[]),fs.set(this,!1),ms.set(this,!1),gs.set(this,void 0),vs.set(this,void 0),ys.set(this,new Map),_s.set(this,void 0),bs.set(this,new Set),u(this,_s,e("EventsQueue"),"f")}setMediaEventHandler(e){u(this,gs,e,"f"),d(this,_s,"f").info("Media event handler set",{case:"EventsQueue"})}setChannelEventHandler(e){u(this,vs,e,"f"),d(this,_s,"f").info("Channel event handler set",{case:"EventsQueue"})}subscribe(e){u(this,bs,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=ls.decode(n);i.id&&(d(this,bs,"f").has(i.id)&&d(this,_s,"f").warn("Received duplicate message",{case:"EventsQueue",lastReceivedMsgId:t,currentReceivedMsgId:i.id}),i.id>t+1&&d(this,_s,"f").warn("Received out of order message",{case:"EventsQueue",lastReceivedMsgId:t,currentReceivedMsgId:i.id})),d(this,bs,"f").add(i.id),t=i.id,this.push(i)}catch(e){d(this,_s,"f").error("Failed to parse channel message",{error:Pt(e),case:"EventsQueue"})}},n=()=>{e.removeListener("message",r),e.removeListener("close",n)};e.on("close",n),e.on("message",r),d(this,_s,"f").info("Subscribed to data channel",{case:"EventsQueue"})}push(e){d(this,hs,"f").push(e),this.process()}process(){return c(this,void 0,void 0,(function*(){if(!d(this,fs,"f")&&!d(this,ms,"f")){for(u(this,ms,!0,"f");!d(this,fs,"f")&&d(this,hs,"f").length>0;){const e=d(this,hs,"f").shift();if(e)try{if(e.channelEvent&&d(this,vs,"f")){d(this,_s,"f").debug("Handle channel event",{case:"EventsQueue",id:e.id,type:Yi(e.channelEvent.eventType),event:e.channelEvent}),yield d(this,vs,"f").call(this,e.channelEvent);continue}if(e.mediaEvent&&d(this,gs,"f")){d(this,_s,"f").debug("Handle media event",{case:"EventsQueue",id:e.id,type:cs(e.mediaEvent.eventType),event:e.mediaEvent}),yield d(this,gs,"f").call(this,e.mediaEvent);continue}d(this,_s,"f").warn("Received unknown message",{message:e,case:"EventsQueue"})}catch(t){d(this,_s,"f").error("Failed to handle event",{case:"EventsQueue",id:e.id,error:Pt(t)})}}u(this,ms,!1,"f"),!d(this,fs,"f")&&d(this,hs,"f").length>0&&queueMicrotask((()=>{this.process()}))}}))}processMessageChunk(e){const t=new Uint8Array(e);if(t.length<12)return void d(this,_s,"f").warn("Chunk too small",{case:"EventsQueue",bytesLength:t.length});const{msgId:r,index:n,total:i}=this.parseMessageChunkHeader(t),s=t.slice(12);d(this,ys,"f").has(r)||d(this,ys,"f").set(r,{msgId:r,total:i,received:[]});const o=d(this,ys,"f").get(r);if(o)return o.received[n]=s,o.msgId=r,o;d(this,_s,"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 d(this,ys,"f").delete(e.msgId),t}pause(){u(this,fs,!0,"f")}size(){return d(this,hs,"f").length}resume(){u(this,fs,!1,"f"),this.process()}isMessageReceived(e){return d(this,bs,"f").has(e)}};hs=new WeakMap,fs=new WeakMap,ms=new WeakMap,gs=new WeakMap,vs=new WeakMap,ys=new WeakMap,_s=new WeakMap,bs=new WeakMap,Es=s([ct(),o(0,ut(Nn.LoggerFactory)),a("design:paramtypes",[Function])],Es);var ws=Es;function Ss(e){return{id:e.id,appId:e.appId,role:e.role,groups:e.groups,producePermissions:e.producePermissions}}let Cs=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)}};Cs=s([ct()],Cs);const Ps=["no media section found for reuseMid","Duplicate a=msid lines detected"];class Ts extends vn{constructor(e,t,r){super(null!=e?e:Ts.DEFAULT_MESSAGE,null!=t?t:"already_connected",r)}}Ts.DEFAULT_MESSAGE="Peer is already connected";const Rs=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 ks(e){return!e.response&&(!!e.code&&(!["ERR_CANCELED","ECONNABORTED"].includes(e.code)&&(e=>!Rs.has(e&&e.code))(e)))}const Ds=["get","head","options"],Is=Ds.concat(["put","delete"]);function As(e){return"ECONNABORTED"!==e.code&&(!e.response||429===e.response.status||e.response.status>=500&&e.response.status<=599)}function Os(e){return!!e.config?.method&&(As(e)&&-1!==Is.indexOf(e.config.method))}function Ms(e){return ks(e)||Os(e)}function Ns(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 Ls={retries:3,retryCondition:Ms,retryDelay:function(e=0,t){return Math.max(0,Ns(t))},shouldResetTimeout:!1,onRetry:()=>{},onMaxRetryTimesExceeded:()=>{},validateResponse:null};function xs(e,t,r=!1){const n=function(e,t){return{...Ls,...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 Fs=(e,t)=>{const r=e.interceptors.request.use((e=>(xs(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=xs(n,t);return r.response&&i.validateResponse?.(r.response)?r.response:await async function(e,t){const{retries:r,retryCondition:n}=e,i=(e.retryCount||0)<r&&n(t);if("object"==typeof i)try{return!1!==await i}catch(e){return!1}return i}(i,r)?async function(e,t,r,n){t.retryCount+=1;const{retryDelay:i,shouldResetTimeout:s,onRetry:o}=t,a=i(t.retryCount,r);if(function(e,t){e.defaults.agent===t.agent&&delete t.agent,e.defaults.httpAgent===t.httpAgent&&delete t.httpAgent,e.defaults.httpsAgent===t.httpsAgent&&delete t.httpsAgent}(e,n),!s&&n.timeout&&t.lastRequestTime){const e=Date.now()-t.lastRequestTime,i=n.timeout-e-a;if(i<=0)return Promise.reject(r);n.timeout=i}return n.transformRequest=[e=>e],await o(t.retryCount,r,n),n.signal?.aborted?Promise.resolve(e(n)):new Promise((t=>{const r=()=>{clearTimeout(i),t(e(n))},i=setTimeout((()=>{t(e(n)),n.signal?.removeEventListener&&n.signal.removeEventListener("abort",r)}),a);n.signal?.addEventListener&&n.signal.addEventListener("abort",r,{once:!0})}))}(e,i,r,n):(await async function(e,t){e.retryCount>=e.retries&&await e.onMaxRetryTimesExceeded(t,e.retryCount)}(i,r),Promise.reject(r))}));return{requestInterceptorId:r,responseInterceptorId:n}};function js(e,t){return function(){return e.apply(t,arguments)}}Fs.isNetworkError=ks,Fs.isSafeRequestError=function(e){return!!e.config?.method&&(As(e)&&-1!==Ds.indexOf(e.config.method))},Fs.isIdempotentRequestError=Os,Fs.isNetworkOrIdempotentRequestError=Ms,Fs.exponentialDelay=function(e=0,t,r=100){const n=2**e*r,i=Math.max(n,Ns(t));return i+.2*i*Math.random()},Fs.linearDelay=function(e=100){return(t=0,r)=>{const n=t*e;return Math.max(n,Ns(r))}},Fs.isRetryableError=As;const{toString:Us}=Object.prototype,{getPrototypeOf:Vs}=Object,{iterator:Bs,toStringTag:Ws}=Symbol,Hs=(qs=Object.create(null),e=>{const t=Us.call(e);return qs[t]||(qs[t]=t.slice(8,-1).toLowerCase())});var qs;const zs=e=>(e=e.toLowerCase(),t=>Hs(t)===e),Gs=e=>t=>typeof t===e,{isArray:Ys}=Array,$s=Gs("undefined");const Js=zs("ArrayBuffer");const Qs=Gs("string"),Ks=Gs("function"),Zs=Gs("number"),Xs=e=>null!==e&&"object"==typeof e,eo=e=>{if("object"!==Hs(e))return!1;const t=Vs(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Ws in e||Bs in e)},to=zs("Date"),ro=zs("File"),no=zs("Blob"),io=zs("FileList"),so=zs("URLSearchParams"),[oo,ao,co,uo]=["ReadableStream","Request","Response","Headers"].map(zs);function lo(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,i;if("object"!=typeof e&&(e=[e]),Ys(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{const i=r?Object.getOwnPropertyNames(e):Object.keys(e),s=i.length;let o;for(n=0;n<s;n++)o=i[n],t.call(null,e[o],o,e)}}function po(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,i=r.length;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}const ho="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,fo=e=>!$s(e)&&e!==ho;const mo=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Vs(Uint8Array)),go=zs("HTMLFormElement"),vo=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),yo=zs("RegExp"),_o=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};lo(r,((r,i)=>{let s;!1!==(s=t(r,i,e))&&(n[i]=s||r)})),Object.defineProperties(e,n)};const bo=zs("AsyncFunction"),Eo=(wo="function"==typeof setImmediate,So=Ks(ho.postMessage),wo?setImmediate:So?(Co=`axios@${Math.random()}`,Po=[],ho.addEventListener("message",(({source:e,data:t})=>{e===ho&&t===Co&&Po.length&&Po.shift()()}),!1),e=>{Po.push(e),ho.postMessage(Co,"*")}):e=>setTimeout(e));var wo,So,Co,Po;const To="undefined"!=typeof queueMicrotask?queueMicrotask.bind(ho):"undefined"!=typeof process&&process.nextTick||Eo;var Ro={isArray:Ys,isArrayBuffer:Js,isBuffer:function(e){return null!==e&&!$s(e)&&null!==e.constructor&&!$s(e.constructor)&&Ks(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Ks(e.append)&&("formdata"===(t=Hs(e))||"object"===t&&Ks(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Js(e.buffer),t},isString:Qs,isNumber:Zs,isBoolean:e=>!0===e||!1===e,isObject:Xs,isPlainObject:eo,isReadableStream:oo,isRequest:ao,isResponse:co,isHeaders:uo,isUndefined:$s,isDate:to,isFile:ro,isBlob:no,isRegExp:yo,isFunction:Ks,isStream:e=>Xs(e)&&Ks(e.pipe),isURLSearchParams:so,isTypedArray:mo,isFileList:io,forEach:lo,merge:function e(){const{caseless:t}=fo(this)&&this||{},r={},n=(n,i)=>{const s=t&&po(r,i)||i;eo(r[s])&&eo(n)?r[s]=e(r[s],n):eo(n)?r[s]=e({},n):Ys(n)?r[s]=n.slice():r[s]=n};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&lo(arguments[e],n);return r},extend:(e,t,r,{allOwnKeys:n}={})=>(lo(t,((t,n)=>{r&&Ks(t)?e[n]=js(t,r):e[n]=t}),{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let i,s,o;const a={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),s=i.length;s-- >0;)o=i[s],n&&!n(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==r&&Vs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:Hs,kindOfTest:zs,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(Ys(e))return e;let t=e.length;if(!Zs(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Bs]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:go,hasOwnProperty:vo,hasOwnProp:vo,reduceDescriptors:_o,freezeMethods:e=>{_o(e,((t,r)=>{if(Ks(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];Ks(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach((e=>{r[e]=!0}))};return Ys(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:po,global:ho,isContextDefined:fo,isSpecCompliantForm:function(e){return!!(e&&Ks(e.append)&&"FormData"===e[Ws]&&e[Bs])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(Xs(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const i=Ys(e)?[]:{};return lo(e,((e,t)=>{const s=r(e,n+1);!$s(s)&&(i[t]=s)})),t[n]=void 0,i}}return e};return r(e,0)},isAsyncFn:bo,isThenable:e=>e&&(Xs(e)||Ks(e))&&Ks(e.then)&&Ks(e.catch),setImmediate:Eo,asap:To,isIterable:e=>null!=e&&Ks(e[Bs])};function ko(e,t,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}Ro.inherits(ko,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:Ro.toJSONObject(this.config),code:this.code,status:this.status}}});const Do=ko.prototype,Io={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{Io[e]={value:e}})),Object.defineProperties(ko,Io),Object.defineProperty(Do,"isAxiosError",{value:!0}),ko.from=(e,t,r,n,i,s)=>{const o=Object.create(Do);return Ro.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),ko.call(o,e.message,t,r,n,i),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function Ao(e){return Ro.isPlainObject(e)||Ro.isArray(e)}function Oo(e){return Ro.endsWith(e,"[]")?e.slice(0,-2):e}function Mo(e,t,r){return e?e.concat(t).map((function(e,t){return e=Oo(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const No=Ro.toFlatObject(Ro,{},null,(function(e){return/^is[A-Z]/.test(e)}));function Lo(e,t,r){if(!Ro.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=Ro.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!Ro.isUndefined(t[e])}))).metaTokens,i=r.visitor||d,s=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&Ro.isSpecCompliantForm(t);if(!Ro.isFunction(i))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(Ro.isDate(e))return e.toISOString();if(Ro.isBoolean(e))return e.toString();if(!a&&Ro.isBlob(e))throw new ko("Blob is not supported. Use a Buffer instead.");return Ro.isArrayBuffer(e)||Ro.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,r,i){let a=e;if(e&&!i&&"object"==typeof e)if(Ro.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(Ro.isArray(e)&&function(e){return Ro.isArray(e)&&!e.some(Ao)}(e)||(Ro.isFileList(e)||Ro.endsWith(r,"[]"))&&(a=Ro.toArray(e)))return r=Oo(r),a.forEach((function(e,n){!Ro.isUndefined(e)&&null!==e&&t.append(!0===o?Mo([r],n,s):null===o?r:r+"[]",c(e))})),!1;return!!Ao(e)||(t.append(Mo(i,r,s),c(e)),!1)}const u=[],l=Object.assign(No,{defaultVisitor:d,convertValue:c,isVisitable:Ao});if(!Ro.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!Ro.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+n.join("."));u.push(r),Ro.forEach(r,(function(r,s){!0===(!(Ro.isUndefined(r)||null===r)&&i.call(t,r,Ro.isString(s)?s.trim():s,n,l))&&e(r,n?n.concat(s):[s])})),u.pop()}}(e),t}function xo(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function Fo(e,t){this._pairs=[],e&&Lo(e,this,t)}const jo=Fo.prototype;function Uo(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Vo(e,t,r){if(!t)return e;const n=r&&r.encode||Uo;Ro.isFunction(r)&&(r={serialize:r});const i=r&&r.serialize;let s;if(s=i?i(t,r):Ro.isURLSearchParams(t)?t.toString():new Fo(t,r).toString(n),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}jo.append=function(e,t){this._pairs.push([e,t])},jo.toString=function(e){const t=e?function(t){return e.call(this,t,xo)}:xo;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var Bo=class{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){Ro.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},Wo={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ho={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Fo,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const qo="undefined"!=typeof window&&"undefined"!=typeof document,zo="object"==typeof navigator&&navigator||void 0,Go=qo&&(!zo||["ReactNative","NativeScript","NS"].indexOf(zo.product)<0),Yo="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,$o=qo&&window.location.href||"http://localhost";var Jo={...Object.freeze({__proto__:null,hasBrowserEnv:qo,hasStandardBrowserWebWorkerEnv:Yo,hasStandardBrowserEnv:Go,navigator:zo,origin:$o}),...Ho};function Qo(e){function t(e,r,n,i){let s=e[i++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=i>=e.length;if(s=!s&&Ro.isArray(n)?n.length:s,a)return Ro.hasOwnProp(n,s)?n[s]=[n[s],r]:n[s]=r,!o;n[s]&&Ro.isObject(n[s])||(n[s]=[]);return t(e,r,n[s],i)&&Ro.isArray(n[s])&&(n[s]=function(e){const t={},r=Object.keys(e);let n;const i=r.length;let s;for(n=0;n<i;n++)s=r[n],t[s]=e[s];return t}(n[s])),!o}if(Ro.isFormData(e)&&Ro.isFunction(e.entries)){const r={};return Ro.forEachEntry(e,((e,n)=>{t(function(e){return Ro.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null}const Ko={transitional:Wo,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,i=Ro.isObject(e);i&&Ro.isHTMLForm(e)&&(e=new FormData(e));if(Ro.isFormData(e))return n?JSON.stringify(Qo(e)):e;if(Ro.isArrayBuffer(e)||Ro.isBuffer(e)||Ro.isStream(e)||Ro.isFile(e)||Ro.isBlob(e)||Ro.isReadableStream(e))return e;if(Ro.isArrayBufferView(e))return e.buffer;if(Ro.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Lo(e,new Jo.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return Jo.isNode&&Ro.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=Ro.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Lo(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return i||n?(t.setContentType("application/json",!1),function(e,t,r){if(Ro.isString(e))try{return(t||JSON.parse)(e),Ro.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Ko.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(Ro.isResponse(e)||Ro.isReadableStream(e))return e;if(e&&Ro.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw ko.from(e,ko.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Jo.classes.FormData,Blob:Jo.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Ro.forEach(["delete","get","head","post","put","patch"],(e=>{Ko.headers[e]={}}));var Zo=Ko;const Xo=Ro.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const ea=Symbol("internals");function ta(e){return e&&String(e).trim().toLowerCase()}function ra(e){return!1===e||null==e?e:Ro.isArray(e)?e.map(ra):String(e)}function na(e,t,r,n,i){return Ro.isFunction(n)?n.call(this,t,r):(i&&(t=r),Ro.isString(t)?Ro.isString(n)?-1!==t.indexOf(n):Ro.isRegExp(n)?n.test(t):void 0:void 0)}class ia{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function i(e,t,r){const i=ta(t);if(!i)throw new Error("header name must be a non-empty string");const s=Ro.findKey(n,i);(!s||void 0===n[s]||!0===r||void 0===r&&!1!==n[s])&&(n[s||t]=ra(e))}const s=(e,t)=>Ro.forEach(e,((e,r)=>i(e,r,t)));if(Ro.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(Ro.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let r,n,i;return e&&e.split("\n").forEach((function(e){i=e.indexOf(":"),r=e.substring(0,i).trim().toLowerCase(),n=e.substring(i+1).trim(),!r||t[r]&&Xo[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t);else if(Ro.isObject(e)&&Ro.isIterable(e)){let r,n,i={};for(const t of e){if(!Ro.isArray(t))throw TypeError("Object iterator must return a key-value pair");i[n=t[0]]=(r=i[n])?Ro.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}s(i,t)}else null!=e&&i(t,e,r);return this}get(e,t){if(e=ta(e)){const r=Ro.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(Ro.isFunction(t))return t.call(this,e,r);if(Ro.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=ta(e)){const r=Ro.findKey(this,e);return!(!r||void 0===this[r]||t&&!na(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function i(e){if(e=ta(e)){const i=Ro.findKey(r,e);!i||t&&!na(0,r[i],i,t)||(delete r[i],n=!0)}}return Ro.isArray(e)?e.forEach(i):i(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const i=t[r];e&&!na(0,this[i],i,e,!0)||(delete this[i],n=!0)}return n}normalize(e){const t=this,r={};return Ro.forEach(this,((n,i)=>{const s=Ro.findKey(r,i);if(s)return t[s]=ra(n),void delete t[i];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(i):String(i).trim();o!==i&&delete t[i],t[o]=ra(n),r[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return Ro.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&Ro.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[ea]=this[ea]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=ta(e);t[n]||(!function(e,t){const r=Ro.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,i){return this[n].call(this,t,e,r,i)},configurable:!0})}))}(r,e),t[n]=!0)}return Ro.isArray(e)?e.forEach(n):n(e),this}}ia.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),Ro.reduceDescriptors(ia.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),Ro.freezeMethods(ia);var sa=ia;function oa(e,t){const r=this||Zo,n=t||r,i=sa.from(n.headers);let s=n.data;return Ro.forEach(e,(function(e){s=e.call(r,s,i.normalize(),t?t.status:void 0)})),i.normalize(),s}function aa(e){return!(!e||!e.__CANCEL__)}function ca(e,t,r){ko.call(this,null==e?"canceled":e,ko.ERR_CANCELED,t,r),this.name="CanceledError"}function da(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new ko("Request failed with status code "+r.status,[ko.ERR_BAD_REQUEST,ko.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}Ro.inherits(ca,ko,{__CANCEL__:!0});const ua=(e,t,r=3)=>{let n=0;const i=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let i,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=n[o];i||(i=c),r[s]=a,n[s]=c;let u=o,l=0;for(;u!==s;)l+=r[u++],u%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-i<t)return;const p=d&&c-d;return p?Math.round(1e3*l/p):void 0}}(50,250);return function(e,t){let r,n,i=0,s=1e3/t;const o=(t,s=Date.now())=>{i=s,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-i;a>=s?o(e,t):(r=e,n||(n=setTimeout((()=>{n=null,o(r)}),s-a)))},()=>r&&o(r)]}((r=>{const s=r.loaded,o=r.lengthComputable?r.total:void 0,a=s-n,c=i(a);n=s;e({loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:r,lengthComputable:null!=o,[t?"download":"upload"]:!0})}),r)},la=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},pa=e=>(...t)=>Ro.asap((()=>e(...t)));var ha=Jo.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,Jo.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(Jo.origin),Jo.navigator&&/(msie|trident)/i.test(Jo.navigator.userAgent)):()=>!0,fa=Jo.hasStandardBrowserEnv?{write(e,t,r,n,i,s){const o=[e+"="+encodeURIComponent(t)];Ro.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),Ro.isString(n)&&o.push("path="+n),Ro.isString(i)&&o.push("domain="+i),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function ma(e,t,r){let n=!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t);return e&&(n||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const ga=e=>e instanceof sa?{...e}:e;function va(e,t){t=t||{};const r={};function n(e,t,r,n){return Ro.isPlainObject(e)&&Ro.isPlainObject(t)?Ro.merge.call({caseless:n},e,t):Ro.isPlainObject(t)?Ro.merge({},t):Ro.isArray(t)?t.slice():t}function i(e,t,r,i){return Ro.isUndefined(t)?Ro.isUndefined(e)?void 0:n(void 0,e,0,i):n(e,t,0,i)}function s(e,t){if(!Ro.isUndefined(t))return n(void 0,t)}function o(e,t){return Ro.isUndefined(t)?Ro.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,i,s){return s in t?n(r,i):s in e?n(void 0,r):void 0}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,r)=>i(ga(e),ga(t),0,!0)};return Ro.forEach(Object.keys(Object.assign({},e,t)),(function(n){const s=c[n]||i,o=s(e[n],t[n],n);Ro.isUndefined(o)&&s!==a||(r[n]=o)})),r}var ya=e=>{const t=va({},e);let r,{data:n,withXSRFToken:i,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=sa.from(a),t.url=Vo(ma(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),Ro.isFormData(n))if(Jo.hasStandardBrowserEnv||Jo.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map((e=>e.trim())).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(Jo.hasStandardBrowserEnv&&(i&&Ro.isFunction(i)&&(i=i(t)),i||!1!==i&&ha(t.url))){const e=s&&o&&fa.read(o);e&&a.set(s,e)}return t};var _a="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){const n=ya(e);let i=n.data;const s=sa.from(n.headers).normalize();let o,a,c,d,u,{responseType:l,onUploadProgress:p,onDownloadProgress:h}=n;function f(){d&&d(),u&&u(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let m=new XMLHttpRequest;function g(){if(!m)return;const n=sa.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());da((function(e){t(e),f()}),(function(e){r(e),f()}),{data:l&&"text"!==l&&"json"!==l?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:n,config:e,request:m}),m=null}m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout,"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(g)},m.onabort=function(){m&&(r(new ko("Request aborted",ko.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ko("Network Error",ko.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const i=n.transitional||Wo;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new ko(t,i.clarifyTimeoutError?ko.ETIMEDOUT:ko.ECONNABORTED,e,m)),m=null},void 0===i&&s.setContentType(null),"setRequestHeader"in m&&Ro.forEach(s.toJSON(),(function(e,t){m.setRequestHeader(t,e)})),Ro.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),l&&"json"!==l&&(m.responseType=n.responseType),h&&([c,u]=ua(h,!0),m.addEventListener("progress",c)),p&&m.upload&&([a,d]=ua(p),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",d)),(n.cancelToken||n.signal)&&(o=t=>{m&&(r(!t||t.type?new ca(null,e,m):t),m.abort(),m=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));const v=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);v&&-1===Jo.protocols.indexOf(v)?r(new ko("Unsupported protocol "+v+":",ko.ERR_BAD_REQUEST,e)):m.send(i||null)}))};var ba=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const i=function(e){if(!r){r=!0,o();const t=e instanceof Error?e:this.reason;n.abort(t instanceof ko?t:new ca(t instanceof Error?t.message:t))}};let s=t&&setTimeout((()=>{s=null,i(new ko(`timeout ${t} of ms exceeded`,ko.ETIMEDOUT))}),t);const o=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)})),e=null)};e.forEach((e=>e.addEventListener("abort",i)));const{signal:a}=n;return a.unsubscribe=()=>Ro.asap(o),a}};const Ea=function*(e,t){let r=e.byteLength;if(!t||r<t)return void(yield e);let n,i=0;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},wa=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},Sa=(e,t,r,n)=>{const i=async function*(e,t){for await(const r of wa(e))yield*Ea(r,t)}(e,t);let s,o=0,a=e=>{s||(s=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await i.next();if(t)return a(),void e.close();let s=n.byteLength;if(r){let e=o+=s;r(e)}e.enqueue(new Uint8Array(n))}catch(e){throw a(e),e}},cancel:e=>(a(e),i.return())},{highWaterMark:2})},Ca="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Pa=Ca&&"function"==typeof ReadableStream,Ta=Ca&&("function"==typeof TextEncoder?(Ra=new TextEncoder,e=>Ra.encode(e)):async e=>new Uint8Array(await new Response(e).arrayBuffer()));var Ra;const ka=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},Da=Pa&&ka((()=>{let e=!1;const t=new Request(Jo.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),Ia=Pa&&ka((()=>Ro.isReadableStream(new Response("").body))),Aa={stream:Ia&&(e=>e.body)};var Oa;Ca&&(Oa=new Response,["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!Aa[e]&&(Aa[e]=Ro.isFunction(Oa[e])?t=>t[e]():(t,r)=>{throw new ko(`Response type '${e}' is not supported`,ko.ERR_NOT_SUPPORT,r)})})));const Ma=async(e,t)=>{const r=Ro.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(Ro.isBlob(e))return e.size;if(Ro.isSpecCompliantForm(e)){const t=new Request(Jo.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return Ro.isArrayBufferView(e)||Ro.isArrayBuffer(e)?e.byteLength:(Ro.isURLSearchParams(e)&&(e+=""),Ro.isString(e)?(await Ta(e)).byteLength:void 0)})(t):r};var Na=Ca&&(async e=>{let{url:t,method:r,data:n,signal:i,cancelToken:s,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:d,headers:u,withCredentials:l="same-origin",fetchOptions:p}=ya(e);d=d?(d+"").toLowerCase():"text";let h,f=ba([i,s&&s.toAbortSignal()],o);const m=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let g;try{if(c&&Da&&"get"!==r&&"head"!==r&&0!==(g=await Ma(u,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if(Ro.isFormData(n)&&(e=r.headers.get("content-type"))&&u.setContentType(e),r.body){const[e,t]=la(g,ua(pa(c)));n=Sa(r.body,65536,e,t)}}Ro.isString(l)||(l=l?"include":"omit");const i="credentials"in Request.prototype;h=new Request(t,{...p,signal:f,method:r.toUpperCase(),headers:u.normalize().toJSON(),body:n,duplex:"half",credentials:i?l:void 0});let s=await fetch(h,p);const o=Ia&&("stream"===d||"response"===d);if(Ia&&(a||o&&m)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=s[t]}));const t=Ro.toFiniteNumber(s.headers.get("content-length")),[r,n]=a&&la(t,ua(pa(a),!0))||[];s=new Response(Sa(s.body,65536,r,(()=>{n&&n(),m&&m()})),e)}d=d||"text";let v=await Aa[Ro.findKey(Aa,d)||"text"](s,e);return!o&&m&&m(),await new Promise(((t,r)=>{da(t,r,{data:v,headers:sa.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:h})}))}catch(t){if(m&&m(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new ko("Network Error",ko.ERR_NETWORK,e,h),{cause:t.cause||t});throw ko.from(t,t&&t.code,e,h)}});const La={http:null,xhr:_a,fetch:Na};Ro.forEach(La,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));const xa=e=>`- ${e}`,Fa=e=>Ro.isFunction(e)||null===e||!1===e;var ja=e=>{e=Ro.isArray(e)?e:[e];const{length:t}=e;let r,n;const i={};for(let s=0;s<t;s++){let t;if(r=e[s],n=r,!Fa(r)&&(n=La[(t=String(r)).toLowerCase()],void 0===n))throw new ko(`Unknown adapter '${t}'`);if(n)break;i[t||"#"+s]=n}if(!n){const e=Object.entries(i).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new ko("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(xa).join("\n"):" "+xa(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n};function Ua(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new ca(null,e)}function Va(e){Ua(e),e.headers=sa.from(e.headers),e.data=oa.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return ja(e.adapter||Zo.adapter)(e).then((function(t){return Ua(e),t.data=oa.call(e,e.transformResponse,t),t.headers=sa.from(t.headers),t}),(function(t){return aa(t)||(Ua(e),t&&t.response&&(t.response.data=oa.call(e,e.transformResponse,t.response),t.response.headers=sa.from(t.response.headers))),Promise.reject(t)}))}const Ba={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Ba[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const Wa={};Ba.transitional=function(e,t,r){function n(e,t){return"[Axios v1.10.0] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,i,s)=>{if(!1===e)throw new ko(n(i," has been removed"+(t?" in "+t:"")),ko.ERR_DEPRECATED);return t&&!Wa[i]&&(Wa[i]=!0,console.warn(n(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,i,s)}},Ba.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};var Ha={assertOptions:function(e,t,r){if("object"!=typeof e)throw new ko("options must be an object",ko.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let i=n.length;for(;i-- >0;){const s=n[i],o=t[s];if(o){const t=e[s],r=void 0===t||o(t,s,e);if(!0!==r)throw new ko("option "+s+" must be "+r,ko.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new ko("Unknown option "+s,ko.ERR_BAD_OPTION)}},validators:Ba};const qa=Ha.validators;class za{constructor(e){this.defaults=e||{},this.interceptors={request:new Bo,response:new Bo}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const r=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=va(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:i}=t;void 0!==r&&Ha.assertOptions(r,{silentJSONParsing:qa.transitional(qa.boolean),forcedJSONParsing:qa.transitional(qa.boolean),clarifyTimeoutError:qa.transitional(qa.boolean)},!1),null!=n&&(Ro.isFunction(n)?t.paramsSerializer={serialize:n}:Ha.assertOptions(n,{encode:qa.function,serialize:qa.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Ha.assertOptions(t,{baseUrl:qa.spelling("baseURL"),withXsrfToken:qa.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=i&&Ro.merge(i.common,i[t.method]);i&&Ro.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete i[e]})),t.headers=sa.concat(s,i);const o=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))}));const c=[];let d;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let u,l=0;if(!a){const e=[Va.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),u=e.length,d=Promise.resolve(t);l<u;)d=d.then(e[l++],e[l++]);return d}u=o.length;let p=t;for(l=0;l<u;){const e=o[l++],t=o[l++];try{p=e(p)}catch(e){t.call(this,e);break}}try{d=Va.call(this,p)}catch(e){return Promise.reject(e)}for(l=0,u=c.length;l<u;)d=d.then(c[l++],c[l++]);return d}getUri(e){return Vo(ma((e=va(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}}Ro.forEach(["delete","get","head","options"],(function(e){za.prototype[e]=function(t,r){return this.request(va(r||{},{method:e,url:t,data:(r||{}).data}))}})),Ro.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,i){return this.request(va(i||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}za.prototype[e]=t(),za.prototype[e+"Form"]=t(!0)}));var Ga=za;class Ya{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,i){r.reason||(r.reason=new ca(e,n,i),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;const t=new Ya((function(t){e=t}));return{token:t,cancel:e}}}var $a=Ya;const Ja={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Ja).forEach((([e,t])=>{Ja[t]=e}));var Qa=Ja;const Ka=function e(t){const r=new Ga(t),n=js(Ga.prototype.request,r);return Ro.extend(n,Ga.prototype,r,{allOwnKeys:!0}),Ro.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(va(t,r))},n}(Zo);Ka.Axios=Ga,Ka.CanceledError=ca,Ka.CancelToken=$a,Ka.isCancel=aa,Ka.VERSION="1.10.0",Ka.toFormData=Lo,Ka.AxiosError=ko,Ka.Cancel=Ka.CanceledError,Ka.all=function(e){return Promise.all(e)},Ka.spread=function(e){return function(t){return e.apply(null,t)}},Ka.isAxiosError=function(e){return Ro.isObject(e)&&!0===e.isAxiosError},Ka.mergeConfig=va,Ka.AxiosHeaders=sa,Ka.formToJSON=e=>Qo(Ro.isHTMLForm(e)?new FormData(e):e),Ka.getAdapter=ja,Ka.HttpStatusCode=Qa,Ka.default=Ka;var Za=Ka;class Xa extends vn{constructor(e,t,r){super(null!=e?e:Xa.DEFAULT_MESSAGE,null!=t?t:"already_created",r)}}Xa.DEFAULT_MESSAGE="Resource has already been created";class ec extends vn{constructor(e,t,r){super(null!=e?e:ec.DEFAULT_MESSAGE,null!=t?t:"forbidden",r)}}ec.DEFAULT_MESSAGE="Forbidden";class tc extends vn{constructor(e,t,r){super(null!=e?e:tc.DEFAULT_MESSAGE,null!=t?t:"invalid_request",r)}}tc.DEFAULT_MESSAGE="Invalid request";class rc extends vn{constructor(e,t,r){super(null!=e?e:rc.DEFAULT_MESSAGE,null!=t?t:"not_found",r)}}rc.DEFAULT_MESSAGE="Requested resource was not found";class nc extends vn{constructor(e,t,r){super(null!=e?e:nc.DEFAULT_MESSAGE,null!=t?t:"something_went_wrong",r)}}nc.DEFAULT_MESSAGE="Request failed";class ic extends vn{constructor(e,t,r){super(null!=e?e:ic.DEFAULT_MESSAGE,null!=t?t:"timeout",r)}}ic.DEFAULT_MESSAGE="Request timed out";class sc extends vn{constructor(e,t,r){super(null!=e?e:sc.DEFAULT_MESSAGE,null!=t?t:"too_many_requests",r)}}sc.DEFAULT_MESSAGE="Too many requests";class oc extends vn{constructor(e,t,r){super(null!=e?e:oc.DEFAULT_MESSAGE,null!=t?t:"unauthorized",r)}}oc.DEFAULT_MESSAGE="Unauthorized";const ac=e=>(t,r,n)=>new e(t,r,n),cc={check_access_fail:ac(ec),join_room_fail:ac(tc),need_joined_to_channel:ac(yn),forbidden:ac(ec),not_found:ac(rc),invalid_request:ac(tc),invalid_payload:ac(tc),already_created:ac(Xa),too_many_requests:ac(sc),something_went_wrong:ac(nc),di_error:ac(tc),resources_lock_error:ac(tc),already_connected:ac(Ts),timeout:ac(ic),unauthorized:ac(oc)},dc=e=>{if(!(e=>"object"==typeof e&&null!==e&&!Array.isArray(e))(e))return!1;const{error:t,errorCode:r}=e;return!(void 0!==t&&"string"!=typeof t||void 0!==r&&"string"!=typeof r)},uc=(e,t)=>{var r,n,i,s;const o={};return t&&Object.keys(t).length>0&&(o.response=t),"number"==typeof(null===(r=e.response)||void 0===r?void 0:r.status)&&(o.status=e.response.status),(null===(n=e.response)||void 0===n?void 0:n.statusText)&&(o.statusText=e.response.statusText),e.code&&(o.axiosCode=e.code),(null===(i=e.config)||void 0===i?void 0:i.url)&&(o.url=e.config.url),(null===(s=e.config)||void 0===s?void 0:s.method)&&(o.method=e.config.method),Object.keys(o).length>0?o:void 0};var lc;!function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"}(lc||(lc={}));const pc=["/ping","/ice-parameters"];let hc=class extends class extends class{constructor(e={}){var{securityWorker:t,secure:r,format:n}=e,s=i(e,["securityWorker","secure","format"]);this.securityData=null,this.setSecurityData=e=>{this.securityData=e},this.request=e=>c(this,void 0,void 0,(function*(){var{secure:t,path:r,type:n,query:s,format:o,body:a}=e,c=i(e,["secure","path","type","query","format","body"]);const d=("boolean"==typeof t?t:this.secure)&&this.securityWorker&&(yield this.securityWorker(this.securityData))||{},u=this.mergeRequestParams(c,d),l=o||this.format||void 0;return n===lc.FormData&&a&&null!==a&&"object"==typeof a&&(a=this.createFormData(a)),n===lc.Text&&a&&null!==a&&"string"!=typeof a&&(a=JSON.stringify(a)),this.instance.request(Object.assign(Object.assign({},u),{headers:Object.assign(Object.assign({},u.headers||{}),n&&n!==lc.FormData?{"Content-Type":n}:{}),params:s,responseType:l,data:a,url:r}))})),this.instance=Za.create(Object.assign(Object.assign({},s),{baseURL:s.baseURL||"signaling.livedigital.space/v1"})),this.secure=r,this.format=n,this.securityWorker=t}mergeRequestParams(e,t){const r=e.method||t&&t.method;return Object.assign(Object.assign(Object.assign(Object.assign({},this.instance.defaults),e),t||{}),{headers:Object.assign(Object.assign(Object.assign({},r&&this.instance.defaults.headers[r.toLowerCase()]||{}),e.headers||{}),t&&t.headers||{})})}stringifyFormItem(e){return"object"==typeof e&&null!==e?JSON.stringify(e):`${e}`}createFormData(e){return Object.keys(e||{}).reduce(((t,r)=>{const n=e[r],i=n instanceof Array?n:[n];for(const e of i){const n=e instanceof Blob||e instanceof File;t.append(r,n?e:this.stringifyFormItem(e))}return t}),new FormData)}}{constructor(){super(...arguments),this.peers={getPeers:(e,t={})=>this.request(Object.assign({path:"/peers",method:"GET",query:e,secure:!0,format:"json"},t)),registerPeer:(e,t={})=>this.request(Object.assign({path:"/peers",method:"POST",body:e,secure:!0,type:lc.Json,format:"json"},t)),disconnectPeer:(e={})=>this.request(Object.assign({path:"/peers",method:"DELETE",secure:!0},e)),changePeerProducePermissions:(e,t,r={})=>this.request(Object.assign({path:`/peers/${e}/produce-permissions`,method:"PUT",body:t,secure:!0,type:lc.Json},r)),addPeerProducePermissions:(e,t,r={})=>this.request(Object.assign({path:`/peers/${e}/produce-permissions/${t}`,method:"POST",secure:!0},r)),removePeerProducePermissions:(e,t,r={})=>this.request(Object.assign({path:`/peers/${e}/produce-permissions/${t}`,method:"DELETE",secure:!0},r))},this.router={getRtpCapabilities:(e={})=>this.request(Object.assign({path:"/router/rtp-capabilities",method:"GET",secure:!0,format:"json"},e))},this.channel={confirmChannelActivity:(e={})=>this.request(Object.assign({path:"/channel/activity",method:"PATCH",secure:!0},e)),triggerChannelStateEvent:(e,t={})=>this.request(Object.assign({path:"/channel/peers-state-message-id",method:"GET",query:e,secure:!0,format:"json"},t))},this.ping={pingPeer:(e={})=>this.request(Object.assign({path:"/ping",method:"POST",secure:!0},e))},this.appData={updateSelfPeerAppData:(e,t={})=>this.request(Object.assign({path:"/app-data",method:"PUT",body:e,secure:!0,type:lc.Json},t))},this.producer={getGeneralDataProducer:(e={})=>this.request(Object.assign({path:"/producer/general-data",method:"GET",secure:!0,format:"json"},e)),getAudioObserverProducer:(e={})=>this.request(Object.assign({path:"/producer/audio-observer",method:"GET",secure:!0,format:"json"},e)),getChannelStateSyncDataProducer:(e={})=>this.request(Object.assign({path:"/producer/channel-state-sync-data",method:"GET",secure:!0,format:"json"},e)),closeProducer:(e,t={})=>this.request(Object.assign({path:`/producer/${e}`,method:"DELETE",secure:!0},t)),pauseProducer:(e,t={})=>this.request(Object.assign({path:`/producer/${e}/actions/pause`,method:"POST",secure:!0},t)),resumeProducer:(e,t={})=>this.request(Object.assign({path:`/producer/${e}/actions/resume`,method:"POST",secure:!0},t)),requestProducerMaxSpatialLayer:(e,t,r={})=>this.request(Object.assign({path:`/producer/${e}/max-spatial-layer`,method:"POST",body:t,secure:!0,type:lc.Json},r)),setProducerMaxSpatialLayer:(e,t,r={})=>this.request(Object.assign({path:`/producer/${e}/max-spatial-layer`,method:"PUT",body:t,secure:!0,type:lc.Json},r))},this.consumer={createConsumer:(e,t={})=>this.request(Object.assign({path:"/consumer",method:"POST",body:e,secure:!0,type:lc.Json,format:"json"},t)),closeConsumer:(e,t={})=>this.request(Object.assign({path:`/consumer/${e}`,method:"DELETE",secure:!0},t)),pauseConsumer:(e,t={})=>this.request(Object.assign({path:`/consumer/${e}/actions/pause`,method:"POST",secure:!0},t)),resumeConsumer:(e,t={})=>this.request(Object.assign({path:`/consumer/${e}/actions/resume`,method:"POST",secure:!0},t)),updateConsumerPreferredLayers:(e,t,r={})=>this.request(Object.assign({path:`/consumer/${e}/preferred-layers`,method:"PUT",body:t,secure:!0,type:lc.Json},r)),requestConsumerKeyFrame:(e,t={})=>this.request(Object.assign({path:`/consumer/${e}/key-frame`,method:"POST",secure:!0},t))},this.dataConsumer={createDataConsumer:(e,t={})=>this.request(Object.assign({path:"/data-consumer",method:"POST",body:e,secure:!0,type:lc.Json,format:"json"},t))},this.transport={createTransport:(e,t={})=>this.request(Object.assign({path:"/transport",method:"POST",body:e,secure:!0,type:lc.Json,format:"json"},t)),getTransportIceParameters:(e,t={})=>this.request(Object.assign({path:`/transport/${e}/ice-parameters`,method:"GET",secure:!0,format:"json"},t)),connectTransport:(e,t,r={})=>this.request(Object.assign({path:`/transport/${e}/connect`,method:"PUT",body:t,secure:!0,type:lc.Json},r)),produceMediaToTransport:(e,t,r={})=>this.request(Object.assign({path:`/transport/${e}/media-producer`,method:"PUT",body:t,secure:!0,type:lc.Json,format:"json"},r)),produceDataToTransport:(e,t,r={})=>this.request(Object.assign({path:`/transport/${e}/data-producer`,method:"PUT",body:t,secure:!0,type:lc.Json,format:"json"},r)),closeTransport:(e,t={})=>this.request(Object.assign({path:`/transport/${e}`,method:"DELETE",secure:!0},t))}}}{constructor(e){super({baseURL:String("https://signaling-api.livedigital.space/v1"),securityWorker:e=>{if(!e)return;const t={};return e.token&&(t.Authorization=`Bearer ${e.token}`),e.peerApiVersion&&(t["x-peer-api-version"]=String(e.peerApiVersion)),e.datacenterType&&(t["x-datacenter-type"]=e.datacenterType),{headers:t}}}),this.config=e,this.errorListeners=new Set,this.abortController=new AbortController,this.instance.interceptors.request.use((e=>(!e.signal&&this.abortController&&(e.signal=this.abortController.signal),e))),Fs(this.instance,{retries:3,shouldResetTimeout:!0,retryDelay:e=>Math.min(300*Math.pow(2,e-1),2e3)+300*Math.random(),retryCondition:e=>{var t;return"ERR_CANCELED"!==e.code&&(!(e=>"string"==typeof e&&pc.some((t=>e.includes(t))))(null===(t=e.config)||void 0===t?void 0:t.url)&&(Fs.isNetworkError(e)||"ECONNABORTED"===e.code&&!e.response))}}),this.instance.interceptors.response.use((e=>e),(e=>{const t=(e=>{var t,r;if(!Za.isAxiosError(e))return e instanceof Error?e:new nc;const n=e;if(!n.response){const e=uc(n),r=n.message||nc.DEFAULT_MESSAGE,i=null!==(t=n.code)&&void 0!==t?t:"network_error";return new nc(r,i,e)}const i=dc(n.response.data)?n.response.data:void 0,s="string"==typeof(null==i?void 0:i.errorCode)?i.errorCode:void 0,o="string"==typeof(null==i?void 0:i.error)?i.error:void 0,a=(o&&o.trim().length>0?o:n.message)||nc.DEFAULT_MESSAGE,c=uc(n,i);if(s){const e=cc[s];return e?e(a,s,c):new nc(a,s,c)}const d=null!==(r=n.code)&&void 0!==r?r:"number"==typeof n.response.status?`http_${n.response.status}`:"something_went_wrong";return new nc(a,d,c)})(e);throw this.notifyErrorListeners(t),t})),this.instance.defaults.timeout=7e3;const t=this.config.get("signalingServerUrl");t&&(this.instance.defaults.baseURL=t)}abortPendingRequests(e){this.abortController.abort(e),this.abortController=new AbortController}addErrorListener(e){return this.errorListeners.add(e),()=>{this.errorListeners.delete(e)}}notifyErrorListeners(e){this.errorListeners.forEach((t=>{try{t(e)}catch(e){}}))}};hc=s([ct(),o(0,ut(Nn.Config)),a("design:paramtypes",[Et])],hc);var fc,mc,gc,vc,yc,_c,bc=hc;let Ec=class{constructor(e){fc.set(this,void 0),mc.set(this,void 0),gc.set(this,void 0),vc.set(this,[]),yc.set(this,void 0),_c.set(this,new Uint8Array(0)),u(this,yc,e("DatachannelHeartbeater"),"f")}init(e,t){u(this,gc,e,"f"),u(this,mc,t,"f"),this.subscribeToDataProducerEvents(t),this.startHeartbeatInterval()}dispose(){this.stopHeartbeatInterval(),this.cleanupDataProducerEvents(),u(this,mc,void 0,"f"),u(this,gc,void 0,"f")}startHeartbeatInterval(){d(this,fc,"f")||(u(this,fc,setInterval((()=>{this.sendHeartbeat()}),5e3),"f"),d(this,yc,"f").debug("Datachannel heartbeat interval started"))}stopHeartbeatInterval(){d(this,fc,"f")&&(clearInterval(d(this,fc,"f")),u(this,fc,void 0,"f"),d(this,yc,"f").debug("Datachannel heartbeat interval stopped"))}canSendHeartbeat(){return!(!d(this,mc,"f")||!d(this,gc,"f"))&&(!d(this,mc,"f").closed&&"connected"===d(this,gc,"f").connectionState&&"open"===d(this,mc,"f").readyState)}subscribeToDataProducerEvents(e){this.cleanupDataProducerEvents();const t=t=>{d(this,yc,"f").debug(`Heartbeat data producer ${t}`,{readyState:e.readyState,closed:e.closed})},r=()=>t("open"),n=()=>t("close"),i=()=>t("transport closed");e.on("open",r),e.on("close",n),e.on("transportclose",i),u(this,vc,[()=>e.off("open",r),()=>e.off("close",n),()=>e.off("transportclose",i)],"f")}cleanupDataProducerEvents(){d(this,vc,"f").forEach((e=>e())),u(this,vc,[],"f")}sendHeartbeat(){if(d(this,mc,"f")&&this.canSendHeartbeat())try{d(this,mc,"f").send(d(this,_c,"f"))}catch(e){d(this,yc,"f").debug("Failed to send datachannel heartbeat",{error:Pt(e)})}}};fc=new WeakMap,mc=new WeakMap,gc=new WeakMap,vc=new WeakMap,yc=new WeakMap,_c=new WeakMap,Ec=s([ct(),o(0,ut(Nn.LoggerFactory)),a("design:paramtypes",[Function])],Ec);var wc,Sc=Ec;class Cc extends vn{constructor(e,t,r){super(null!=e?e:Cc.DEFAULT_MESSAGE,null!=t?t:"invalid_payload",r)}}Cc.DEFAULT_MESSAGE="Invalid payload",function(e){e.DominantSpeaker="dominant-speaker",e.PeersVolumes="peers-volumes",e.Silence="silence"}(wc||(wc={}));let Pc=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()}};Pc=s([ct()],Pc);var Tc=Pc;const Rc=[{scaleResolutionDownBy:4,maxBitrate:15e4,maxFramerate:12},{scaleResolutionDownBy:2,maxBitrate:35e4,maxFramerate:18},{scaleResolutionDownBy:1,maxBitrate:9e5,maxFramerate:24}],kc=[{maxBitrate:1e6,dtx:!0}],Dc=[{maxBitrate:4e4,dtx:!0}];var Ic;let Ac=class{constructor(e,t){this.peersStorage=e,Ic.set(this,void 0),u(this,Ic,t("ChannelAudioObserverMissingProducerRestorer"),"f")}handlePeerVolume(e){const{peerId:t,producerId:r}=e,n=this.peersStorage.get(t);if(!n)return;if(n.producers.has(r))return;const i={id:r,kind:"audio",peerId:t,label:Ln.Microphone,paused:!1,encodings:Dc,maxSpatialLayer:0};n.observer.safeEmit(on,i),d(this,Ic,"f").warn("Recovered missing audio producer from audio observer volume",{peerId:t,producerId:r})}};Ic=new WeakMap,Ac=s([ct(),o(0,ut(Nn.PeersStorage)),o(1,ut(Nn.LoggerFactory)),a("design:paramtypes",[Tc,Function])],Ac);var Oc,Mc,Nc,Lc,xc,Fc=Ac;let jc=xc=class{constructor(e,t,r,n){this.peersStorage=e,this.clientEventEmitter=t,this.channelAudioObserverMissingProducerRestorer=r,Oc.set(this,void 0),Mc.set(this,void 0),Nc.set(this,void 0),Lc.set(this,void 0),u(this,Oc,n("ChannelAudioObserverEventHandler"),"f"),this.watchPeersLeave()}handle(e){try{const t=JSON.parse(e);switch(xc.validateEventPayload(t),t.event){case wc.DominantSpeaker:this.handleDominantSpeaker(t);break;case wc.PeersVolumes:this.handlePeerVolumes(t);break;case wc.Silence:this.handleSilence()}}catch(t){d(this,Oc,"f").warn("Failed to handle audio observer event",{error:Pt(t),eventData:e})}}handleDominantSpeaker(e){const{peerId:t}=e.data,r=this.peersStorage.get(t);u(this,Nc,r,"f"),u(this,Lc,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&&!d(this,Nc,"f")&&s.id===(null===(t=d(this,Lc,"f"))||void 0===t?void 0:t.id)&&(u(this,Nc,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))),u(this,Nc,void 0,"f"),this.setActiveSpeaker(void 0)}watchPeersLeave(){this.clientEventEmitter.on(br,(e=>{var t;e===(null===(t=d(this,Nc,"f"))||void 0===t?void 0:t.id)&&this.setActiveSpeaker(void 0)}))}setActiveSpeaker(e){d(this,Mc,"f")!==(null==e?void 0:e.id)&&(u(this,Mc,null==e?void 0:e.id,"f"),this.clientEventEmitter.safeEmit(Dr,{peer:e}))}static validateEventPayload(e){switch(e.event){case wc.Silence:break;case wc.DominantSpeaker:{e.data||xc.throwInvalidPayload();const{peerId:t,producerId:r,trackLabel:n}=e.data;"string"==typeof t&&"string"==typeof r&&n===Ln.Microphone||xc.throwInvalidPayload();break}case wc.PeersVolumes:Array.isArray(e.volumes)||xc.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===Ln.Microphone||xc.throwInvalidPayload()}));break;default:xc.throwInvalidPayload()}}static throwInvalidPayload(){throw new Cc("invalid_channel_audio_observer_payload")}};Oc=new WeakMap,Mc=new WeakMap,Nc=new WeakMap,Lc=new WeakMap,jc=xc=s([ct(),o(0,ut(Nn.PeersStorage)),o(1,ut(Nn.ClientEventEmitter)),o(2,ut(Nn.ChannelAudioObserverMissingProducerRestorer)),o(3,ut(Nn.LoggerFactory)),a("design:paramtypes",[Tc,wt,Fc,Function])],jc);var Uc,Vc,Bc,Wc=jc;let Hc=class{constructor(e,t,r,n,i){this.state=e,this.myPeer=r,this.signalingApiClient=n,this.channelAudioObserverEventHandler=i,Uc.set(this,void 0),Vc.set(this,void 0),Bc.set(this,void 0),u(this,Uc,t("DataChannels"),"f")}get channelMessagesDataConsumer(){return d(this,Bc,"f")}createAudioObserver(e){return c(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();u(this,Vc,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=d(this,Vc,"f"))||void 0===e||e.removeListener("message",n),null===(t=d(this,Vc,"f"))||void 0===t||t.removeListener("close",i)};d(this,Vc,"f").on("close",i),d(this,Vc,"f").on("message",n),d(this,Uc,"f").debug("Successfully create audio observer",r)}catch(e){d(this,Uc,"f").error("Failed to create audio observer",Object.assign(Object.assign({},r),{error:Pt(e)}))}}))}createChannelMessagesDataConsumer(e){return c(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");u(this,Bc,yield this.createDataConsumer({producerId:t,appId:this.state.appId,channelId:this.state.channelId,ordered:!0,transport:e}),"f"),d(this,Uc,"f").debug("Successfully created channel messages data consumer",Object.assign(Object.assign({},r),{producerId:t}))}catch(e){throw d(this,Uc,"f").error("Failed to create channel messages data consumer",Object.assign(Object.assign({},r),{error:e})),e}}))}closeAudioObserver(){var e;null===(e=d(this,Vc,"f"))||void 0===e||e.close()}closeChannelMessagesDataConsumer(){var e;null===(e=d(this,Bc,"f"))||void 0===e||e.close()}createDataProducer(e,t){return c(this,void 0,void 0,(function*(){const{data:r}=yield this.signalingApiClient.transport.produceDataToTransport(e,{label:t});return r}))}createDataConsumer(e){return c(this,arguments,void 0,(function*({producerId:e,appId:t,channelId:r,ordered:n,transport:i}){if(!i)throw d(this,Uc,"f").error("createDataConsumer()",{reason:"missing receive transport"}),new Error("Failed to create data consumer due to missing receive transport");d(this,Uc,"f").debug("createDataConsumer()",{producerId:e});const s=(yield this.signalingApiClient.dataConsumer.createDataConsumer({ordered:n,dataProducerId:e,transportId:i.id,appData:{peerId:this.myPeer.id,producerId:e,appId:t,channelId:r}})).data,o=yield i.consumeData(s);return d(this,Uc,"f").debug("Data consumer created",{consumerId:o.id}),o}))}getAudioObserverProducer(){return c(this,void 0,void 0,(function*(){const{data:e}=yield this.signalingApiClient.producer.getAudioObserverProducer();return e}))}};Uc=new WeakMap,Vc=new WeakMap,Bc=new WeakMap,Hc=s([ct(),o(0,ut(Nn.CallState)),o(1,ut(Nn.LoggerFactory)),o(2,ut(Nn.MyPeer)),o(3,ut(Nn.SignalingApiClient)),o(4,ut(Nn.ChannelAudioObserverEventHandler)),a("design:paramtypes",[Fn,Function,Cs,bc,Wc])],Hc);var qc,zc,Gc=Hc;let Yc=class{constructor(e,t){this.signalingApiClient=t,qc.set(this,void 0),zc.set(this,void 0),u(this,zc,e("SignalingHeartbeater"),"f")}start(){d(this,qc,"f")||(u(this,qc,setInterval((()=>c(this,void 0,void 0,(function*(){yield this.sendHeartbeat()}))),15e3),"f"),d(this,zc,"f").debug("Signaling heartbeat interval started"))}dispose(){d(this,qc,"f")&&(clearInterval(d(this,qc,"f")),u(this,qc,void 0,"f"),d(this,zc,"f").debug("Signaling heartbeat interval stopped"))}sendHeartbeat(){return c(this,void 0,void 0,(function*(){try{yield this.signalingApiClient.ping.pingPeer()}catch(e){d(this,zc,"f").debug("Failed to send signaling heartbeat",{error:Pt(e)})}}))}};qc=new WeakMap,zc=new WeakMap,Yc=s([ct(),o(0,ut(Nn.LoggerFactory)),o(1,ut(Nn.SignalingApiClient)),a("design:paramtypes",[Function,bc])],Yc);var $c,Jc,Qc,Kc=Yc;let Zc=class{constructor(e,t,r,n,i,s,o,a){this.state=e,this.myPeer=t,this.clientEventEmitter=n,this.dataChannelsManager=i,this.signalingApiClient=s,this.datachannelHeartbeater=o,this.signalingHeartbeater=a,$c.set(this,new Map),Jc.set(this,void 0),Qc.set(this,void 0),this.peersLoaded=!1,u(this,Qc,r("Network"),"f"),u(this,Jc,new wt,"f")}get isNetworkActive(){var e,t,r,n;return["connected","new"].includes(null!==(t=null===(e=this.receiveTransport)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"")&&["connected","new"].includes(null!==(n=null===(r=this.sendTransport)||void 0===r?void 0:r.connectionState)&&void 0!==n?n:"")}get observer(){return d(this,Jc,"f")}removeEventListeners(){const{sendTransport:e,receiveTransport:t,signalingTransport:r}=this;if(e){["connect","produce","connectionstatechange"].forEach((t=>e.removeAllListeners(t)))}if(t){["connect","produce","connectionstatechange"].forEach((e=>t.removeAllListeners(e)))}if(r){["connect","produce","producedata","connectionstatechange"].forEach((e=>r.removeAllListeners(e)))}}reset(){this.datachannelHeartbeater.dispose(),this.signalingHeartbeater.dispose(),this.heartbeatDataProducer=void 0,this.peersLoaded=!1,this.stopRestartIceAttempts(),this.removeEventListeners(),this.closeAllDataChannels(),this.closeSendTransport(),this.closeReceiveTransport(),this.closeConnectionTransport()}closeRemoteProducer(e){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.closeProducer(e)}))}closeSendTransport(){this.sendTransport?(this.closeTransport(this.sendTransport),this.sendTransport=void 0):d(this,Qc,"f").debug("closeSendTransport()",{message:"No available send transport"})}closeReceiveTransport(){this.receiveTransport?(this.closeTransport(this.receiveTransport),this.receiveTransport=void 0):d(this,Qc,"f").debug("closeReceiveTransport()",{message:"No available receive transport"})}closeConnectionTransport(){this.signalingTransport?(this.closeTransport(this.signalingTransport),this.signalingTransport=void 0):d(this,Qc,"f").debug("closeConnectionTransport()",{message:"No available connection transport"})}closeTransport(e){try{e.close(),d(this,Qc,"f").debug("closeTransport()",{transportId:e.id,direction:e.direction})}catch(t){d(this,Qc,"f").error("closeTransport()",{error:t,transportId:e.id,direction:e.direction})}}createSendTransport(e){return c(this,void 0,void 0,(function*(){if(this.sendTransport)throw d(this,Qc,"f").warn("createSendTransport()",{message:"Send transport already exists"}),new vn("Send transport already exists","already_exists");const{data:t}=yield this.signalingApiClient.transport.createTransport({localDirection:"send"}),r=e.createSendTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return d(this,Qc,"f").debug("createSendTransport()",{transportId:r.id,direction:r.direction}),this.sendTransport=r,this.subscribeCommonTransportEvents(r),r}))}createRecvTransport(e){return c(this,void 0,void 0,(function*(){if(this.receiveTransport)throw d(this,Qc,"f").warn("createReceiveTransport()",{message:"Receive transport already exists"}),new vn("Receive transport already exists","already_exists");const{data:t}=yield this.signalingApiClient.transport.createTransport({localDirection:"receive"}),r=e.createRecvTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return d(this,Qc,"f").debug("createReceiveTransport()",{transportId:r.id,direction:r.direction}),this.receiveTransport=r,this.subscribeCommonTransportEvents(r),r}))}createSignalingTransport(e){return c(this,void 0,void 0,(function*(){if(this.signalingTransport)throw d(this,Qc,"f").warn("createConnectionTransport()",{message:"Connection transport already exists"}),new vn("Connection transport already exists","already_exists");const{data:t}=yield this.signalingApiClient.transport.createTransport({localDirection:"receive",tcpOnly:!0}),r=e.createSendTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return d(this,Qc,"f").debug("createConnectionTransport()",{transportId:r.id,direction:r.direction,tcpOnly:!0}),this.signalingTransport=r,this.subscribeCommonTransportEvents(r),r}))}getIceParameters(e){return c(this,void 0,void 0,(function*(){const{data:{iceParameters:t}}=yield this.signalingApiClient.transport.getTransportIceParameters(e.id);return t}))}restartIce(e){return c(this,void 0,void 0,(function*(){try{const t=yield this.getIceParameters(e);yield e.restartIce({iceParameters:t}),d(this,Qc,"f").info("restartIce completed",{iceParameters:t})}catch(e){d(this,Qc,"f").error("restartIce error",{error:e})}}))}createConsumer(e){return c(this,arguments,void 0,(function*({producerId:e,rtpCapabilities:t,producerPeerId:r}){const n=this.receiveTransport;if(!n)throw d(this,Qc,"f").error("createConsumer()",{reason:"missing receive transport"}),new Error("Failed to create consumer due to missing receive transport");d(this,Qc,"f").debug("createConsumer()",{producerId:e});const i=yield this.signalingApiClient.consumer.createConsumer({producerId:e,transportId:n.id,rtpCapabilities:t,producerPeerId:r,forceCloseExisting:!0}).then((({data:e})=>this.toRemoteConsumerOptions(e))).catch((t=>{throw d(this,Qc,"f").error("Failed to get consumer options",{producerId:e,producerPeerId:r,error:Pt(t)}),new Error("Failed to create consumer due to error while fetching consumer options")})),s=yield n.consume(i).catch((t=>{throw t instanceof Error&&Ps.some((e=>t.message.includes(e)))&&(d(this,Qc,"f").error("createConsumer() reached irrecoverable mediasoup state",{producerId:e,producerPeerId:r,error:Pt(t)}),this.signalingApiClient.abortPendingRequests("channel-rejoin"),this.clientEventEmitter.safeEmit(Cr)),t})),{producerPaused:o}=i;return o&&"audio"!==s.kind&&s.pause(),d(this,Qc,"f").debug("Consumer created",{consumerId:s.id,label:s.appData.label,isProducerPaused:o}),{consumer:s,isProducerPaused:o}}))}initializeHeartbeats(){return c(this,void 0,void 0,(function*(){this.signalingHeartbeater.start();const e=this.sendTransport;if(!e)throw d(this,Qc,"f").error("createHeartbeatProducer()",{reason:"missing send transport"}),new Error("Failed to create data producer");const t=yield e.produceData({label:"heart-beater",protocol:"heartbeat"});this.heartbeatDataProducer=t,t.once("transportclose",(()=>{var e;null===(e=this.heartbeatDataProducer)||void 0===e||e.close(),this.heartbeatDataProducer=void 0,this.datachannelHeartbeater.dispose()})),this.datachannelHeartbeater.init(e,t)}))}createKeepAliveConsumer(){return c(this,void 0,void 0,(function*(){const e=this.signalingTransport;if(!e)return void d(this,Qc,"f").error("createKeepAliveConsumer()",{reason:"missing signaling transport"});const t=yield e.produceData({label:"consumers-scores",protocol:"keepalive"});t.once("open",(()=>{t.send(new Uint8Array(0))})),t.once("transportclose",(()=>{t.close()}))}))}get channelMessagesDataConsumer(){return this.dataChannelsManager.channelMessagesDataConsumer}closeRemoteConsumer(e){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.closeConsumer(e)}))}resumeRemoteConsumer(e){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.resumeConsumer(e)}))}pauseRemoteProducer(e){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.pauseProducer(e)}))}resumeRemoteProducer(e){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.resumeProducer(e)}))}pauseRemoteConsumer(e){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.pauseConsumer(e)}))}updatePeerAppData(e){return c(this,arguments,void 0,(function*({appData:e}){yield this.signalingApiClient.appData.updateSelfPeerAppData({appData:e})}))}setProducerMaxSpatialLayer(e,t){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.setProducerMaxSpatialLayer(e,{maxSpatialLayer:t})}))}requestProducerMaxSpatialLayer(e,t){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.requestProducerMaxSpatialLayer(e,{spatialLayer:t})}))}changePeerProducePermissions(e,t){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.peers.changePeerProducePermissions(e,{producePermissions:null==t?void 0:t.map((e=>e))})}))}addPeerProducePermission(e,t){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.peers.addPeerProducePermissions(e,t)}))}removePeerProducePermission(e,t){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.peers.removePeerProducePermissions(e,t)}))}updateConsumerPreferredLayers(e,t,r){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.updateConsumerPreferredLayers(e,{spatialLayer:t,temporalLayer:r})}))}requestConsumerKeyFrame(e){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.requestConsumerKeyFrame(e)}))}ping(){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.ping.pingPeer()}))}getTransportsStateInfo(){return c(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 c(this,void 0,void 0,(function*(){var t;const{data:r}=yield this.signalingApiClient.peers.getPeers({role:e});this.peersLoaded=!0;return{peers:(null!==(t=r.items)&&void 0!==t?t:[]).map((e=>this.mapPeerResponse(e)))}}))}createAllDataChannels(){return c(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(e){return c(this,arguments,void 0,(function*({onReceiveTransportFailed:e}){if(!this.receiveTransport)throw new Error("receiveTransport is not initialized");if("connected"===(yield this.waitForTransportTerminalState(this.receiveTransport)))return;yield e();const t=yield this.waitForTransportTerminalState(this.receiveTransport);if("connected"!==t)throw new Error(`receiveTransport connection failed after relay escalation: ${t}`)}))}triggerChannelStateEvent(e){return c(this,void 0,void 0,(function*(){const{data:t}=yield this.signalingApiClient.channel.triggerChannelStateEvent({role:e});if("number"!=typeof t.messageId)throw new Error("Invalid channel state event response");return t.messageId}))}waitForChannelMessagesDataConsumerConnected(){return c(this,void 0,void 0,(function*(){if(!this.dataChannelsManager.channelMessagesDataConsumer)throw new Error("channelMessagesDataConsumer is not initialized");yield this.waitForDataConsumerConnected(this.dataChannelsManager.channelMessagesDataConsumer)}))}waitForTransportTerminalState(e){return c(this,arguments,void 0,(function*(e,t=6e4){if("connected"===e.connectionState)return e.connectionState;if("failed"===e.connectionState)return e.connectionState;if("closed"===e.connectionState)throw new Error(`receiveTransport connection failed: ${e.connectionState}`);return yield new Promise(((r,n)=>{const i=setTimeout((()=>{s(),r(e.connectionState)}),t),s=()=>{clearTimeout(i),e.off("connectionstatechange",o)},o=()=>{["connected","failed"].includes(e.connectionState)?(s(),r(e.connectionState)):"closed"===e.connectionState&&(s(),n(new Error(`receiveTransport connection failed: ${e.connectionState}`)))};e.on("connectionstatechange",o)}))}))}waitForDataConsumerConnected(e){return c(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 c(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 d(this,Qc,"f").warn("getParsedTransportStats()",{error:e})}else d(this,Qc,"f").debug("getParsedTransportStats()",{message:"Transport is missing"})}))}logTransportDetails(e){return c(this,void 0,void 0,(function*(){var t,r,n,i;let s;try{s=yield e.getStats()}catch(t){return void d(this,Qc,"f").error("Failed to log detailed WebRTC transport stats",{error:Pt(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:[],[,c]=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==c?void 0:c.localCandidateId)&&void 0!==n?n:"-")),l=s.get(String(null!==(i=null==c?void 0:c.remoteCandidateId)&&void 0!==i?i:"-")),p={hasNominatedPair:!!c,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==c?void 0:c.totalRoundTripTime)&&(null==c?void 0:c.responsesReceived)&&(p.pairRoundTripTime=Math.round(c.totalRoundTripTime/c.responsesReceived*1e3)),d(this,Qc,"f").info("Detailed WebRTC transport stats",p)}catch(t){d(this,Qc,"f").error("Failed to log detailed WebRTC transport stats",{error:Pt(t),transportId:e.id,reason:"-"})}}))}stopRestartIceAttempts(){Array.from(d(this,$c,"f").values()).forEach((e=>clearInterval(e)))}toRemoteConsumerOptions(e){const{producerPaused:t}=e,r=i(e,["producerPaused"]);return Object.assign(Object.assign({},r),{producerPaused:t})}mapPeerResponse(e){var t,r,n,i,s,o,a,c;return{id:e.id,channelIds:null!==(t=e.channelIds)&&void 0!==t?t:[],groups:null!==(r=e.groups)&&void 0!==r?r:[],producePermissions:null!==(n=e.producePermissions)&&void 0!==n?n:[],appId:null!==(s=null!==(i=e.appId)&&void 0!==i?i:this.state.appId)&&void 0!==s?s:"",producers:(null!==(o=e.producers)&&void 0!==o?o:[]).map((e=>this.mapProducer(e))),uid:e.uid,appData:null!==(a=e.appData)&&void 0!==a?a:{},role:null!==(c=e.role)&&void 0!==c?c:"audience",loginDate:e.loginDate?new Date(e.loginDate):new Date}}mapProducer(e){var t;return{id:e.id,kind:e.kind,peerId:e.peerId,label:e.label,paused:null!==(t=e.paused)&&void 0!==t&&t,encodings:[],maxSpatialLayer:0}}connectTransport(e,t){return c(this,void 0,void 0,(function*(){try{yield this.signalingApiClient.transport.connectTransport(e,{dtlsParameters:t})}catch(t){if(t instanceof Ts)return void d(this,Qc,"f").warn("connectTransport() transport already connected",{transportId:e});throw t}}))}subscribeCommonTransportEvents(e){e.on("connect",((t,r,n)=>c(this,[t,r,n],void 0,(function*({dtlsParameters:t},r,n){try{yield this.connectTransport(e.id,t),r(),d(this,Qc,"f").debug(`${e.direction}Transport.connect()`,{transportId:e.id,dtlsRole:t.role}),setTimeout((()=>c(this,void 0,void 0,(function*(){return yield this.logTransportDetails(e)}))),2e3),setTimeout((()=>c(this,void 0,void 0,(function*(){return yield this.checkTransportState(e)}))),15e3)}catch(t){d(this,Qc,"f").error(`${e.direction}Transport.on('connect')`,{error:t}),n(t)}})))),e.on("produce",((t,r,n)=>c(this,void 0,void 0,(function*(){try{const{data:n}=yield this.signalingApiClient.transport.produceMediaToTransport(e.id,{kind:t.kind,rtpParameters:t.rtpParameters,appData:t.appData,forceCloseExisting:!0}),i=n.id;r({id:i}),d(this,Qc,"f").debug(`${e.direction}Transport.produce()`,{producerId:i,transportId:e.id,kind:t.kind})}catch(r){d(this,Qc,"f").error(`${e.direction}Transport.produce()`,{error:Pt(r),transportId:e.id,kind:t.kind}),n(r)}})))),e.on("producedata",((t,r,n)=>c(this,void 0,void 0,(function*(){try{const{data:n}=yield this.signalingApiClient.transport.produceDataToTransport(e.id,{label:t.label,sctpStreamParameters:t.sctpStreamParameters,appData:t.appData});r({id:n.id}),d(this,Qc,"f").debug(`${e.direction}Transport.produceData()`,{producerId:n.id,transportId:e.id,sctpStreamParameters:t.sctpStreamParameters,label:t.label})}catch(r){d(this,Qc,"f").error(`${e.direction}Transport.produceData()`,{error:Pt(r),transportId:e.id,sctpStreamParameters:t.sctpStreamParameters,label:t.label}),n(r)}})))),e.on("connectionstatechange",(t=>{if(d(this,Qc,"f").info(`${e.direction}Transport.state`,{state:t}),["closed","connected"].includes(t))return d(this,Jc,"f").safeEmit(mn,{state:t,direction:e.direction}),d(this,$c,"f").has(e.id)&&(d(this,Qc,"f").debug("Stop receiveTransport.restartIce() retries",{recvTransportId:e.id}),clearInterval(d(this,$c,"f").get(e.id)),d(this,$c,"f").delete(e.id),"connected"===t&&d(this,Jc,"f").safeEmit(mn,{state:"reconnected",direction:e.direction})),void("connected"===t&&setTimeout((()=>{this.logTransportDetails(e).catch((e=>{d(this,Qc,"f").debug("Failed to log transport details",{error:Pt(e)})}))}),1500));if(d(this,Jc,"f").safeEmit(mn,{state:t,direction:e.direction}),["disconnected","failed"].includes(t)){if(d(this,$c,"f").has(e.id))return;"failed"===t&&(d(this,Qc,"f").debug(`${e.id} transport.restartIce()`,{transportId:e.id,direction:e.direction}),this.restartIce(e).catch((t=>{d(this,Qc,"f").debug("Failed to execute restartIce",{error:Pt(t),transportId:e.id,direction:e.direction})}))),d(this,$c,"f").set(e.id,setInterval((()=>{this.restartIce(e).catch((t=>{d(this,Qc,"f").debug("Failed to execute restartIce",{error:Pt(t),transportId:e.id,direction:e.direction})})),d(this,Qc,"f").debug(`${e.id} transport.restartIce() attempt`,{recvTransportId:e.id,transportId:e.id,direction:e.direction})}),1500))}})),e.on("icegatheringstatechange",(t=>{d(this,Qc,"f").info("icegatheringstatechange",{state:t,transportId:e.id,transportDirection:e.direction})}))}checkTransportState(e){return c(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(Tr,{direction:r,reason:"ice"}),void d(this,Qc,"f").warn(fn,{reason:"ice",transportId:e.id,direction:r});"connected"!==t.dtlsState&&(this.clientEventEmitter.emit(Tr,{direction:r,reason:"dtls"}),d(this,Qc,"f").warn(fn,{reason:"dtls",transportId:e.id,direction:r}))}catch(t){d(this,Qc,"f").error("checkTransportState()",{error:Pt(t),transportId:e.id,direction:e.direction})}}))}};$c=new WeakMap,Jc=new WeakMap,Qc=new WeakMap,Zc=s([ct(),o(0,ut(Nn.CallState)),o(1,ut(Nn.MyPeer)),o(2,ut(Nn.LoggerFactory)),o(3,ut(Nn.ClientEventEmitter)),o(4,ut(Nn.DataChannelsManager)),o(5,ut(Nn.SignalingApiClient)),o(6,ut(Nn.DatachannelHeartbeater)),o(7,ut(Nn.SignalingHeartbeater)),a("design:paramtypes",[Fn,Cs,Function,wt,Gc,bc,Sc,Kc])],Zc);var Xc=Zc;let ed=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 c(this,void 0,void 0,(function*(){const t=this.get(e);t&&(yield t.reset(),this.delete(e),this.clientEventEmitter.safeEmit(br,e))}))}all(){return this.peersStorage.all()}hosts(){return this.peersStorage.hosts()}audience(){return this.peersStorage.audience()}reset(){return c(this,void 0,void 0,(function*(){yield Promise.all(this.peersStorage.all().map((e=>c(this,void 0,void 0,(function*(){return yield e.reset()}))))),this.peersStorage.clear()}))}load(e){return c(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(_r,n),n}isModerator(e){if(void 0===e)return!1;const t=this.get(e);return!!t&&t.isModerator}};function td(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 rd(e,t,r,n){var i=td(td(td(e,r),function(e){return Object.prototype.toString.call(e)}(t)),typeof t);if(null===t)return td(i,"null");if(void 0===t)return td(i,"undefined");if("object"==typeof t||"function"==typeof t){if(-1!==n.indexOf(t))return td(i,"[Circular]"+r);n.push(t);var s=function(e,t,r){return Object.keys(t).sort().reduce((function(e,n){return rd(e,t[n],n,r)}),e)}(i,t,n);if(!("valueOf"in t)||"function"!=typeof t.valueOf)return s;try{return td(s,String(t.valueOf()))}catch(e){return td(s,"[valueOf exception]"+(e.stack||e.message))}}return td(i,t.toString())}ed=s([ct(),o(0,ut(Nn.MyPeer)),o(1,ut(Nn.Network)),o(2,ut(Nn.PeerFactory)),o(3,ut(Nn.ClientEventEmitter)),o(4,ut(Nn.PeersStorage)),a("design:paramtypes",[Cs,Xc,Function,wt,Tc])],ed);var nd=function(e){return function(e,t){for(;e.length<t;)e="0"+e;return e}(rd(0,e,"",[]).toString(16),8)};class id{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 sd{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 id({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 od,ad,cd,dd,ud,ld,pd;!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"}(od||(od={}));let hd=class{constructor(e,t,r,n,i,s,o){var a;this.network=t,this.callState=r,this.peersStorage=n,this.clientEventEmitter=i,this.signalingApiClient=s,this.webRtcIssueDetector=o,ad.set(this,void 0),cd.set(this,void 0),dd.set(this,[]),ud.set(this,!1),ld.set(this,{inbound:4.3,outbound:4.3}),pd.set(this,(new Date).getTime()-15e3),u(this,cd,null===(a=this.webRtcIssueDetector)||void 0===a?void 0:a.eventEmitter,"f"),u(this,ad,e("ChannelStateSyncEventHandler"),"f"),this.debouncedHandleChannelStateEvent=Pn(this.handleChannelStateEvent.bind(this),3e3),this.listenNetworkScoresUpdatedEvents()}handleChannelStateShort(e){return c(this,void 0,void 0,(function*(){try{yield this.debouncedHandleChannelStateEvent(e)}catch(e){d(this,ad,"f").error("handleChannelStateSyncEvent()",{error:Pt(e)})}}))}handleChannelStateEvent(e){return c(this,void 0,void 0,(function*(){if(d(this,ud,"f"))d(this,ad,"f").warn("Channel state event is already being handled, skipping new event",{case:"handleChannelStateEvent"});else{u(this,ud,!0,"f");try{yield this.collectProbableInconsistencyCases(e);const t=this.getConfirmedInconsistencyResult();if(!(null==t?void 0:t.hasInconsistencyCases()))return;if(this.isRestoreStateRequestToEarly())return void d(this,ad,"f").info("Inconsistency detected, but restore skipped",Object.assign({},t));this.handleConfirmedInconsistencyResult(t)}finally{u(this,ud,!1,"f")}}}))}getLastInconsistencyCheckResult(){return d(this,dd,"f")[d(this,dd,"f").length-1]}handleConfirmedInconsistencyResult(e){e.missingPeers.forEach((e=>{this.clientEventEmitter.safeEmit(Ir,{peerId:e,peersLoaded:this.network.peersLoaded,sdkInstances:Array.from(window._sdkMarks||[]).length,type:od.MissingPeer})})),e.missingProducers.forEach((e=>{this.clientEventEmitter.safeEmit(Ir,{producerId:e,type:od.MissingProducer})})),e.producersWithInconsistentState.forEach((e=>{this.clientEventEmitter.safeEmit(Ir,{producerId:e,type:od.IncorrectProducerState})})),e.peersWithInconsistentAppData.forEach((e=>{this.clientEventEmitter.safeEmit(Ir,{peerId:e,type:od.IncorrectAppData})}))}getConfirmedInconsistencyResult(){const e=this.getLastInconsistencyCheckResult();if(!e)return;return new id({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 c(this,void 0,void 0,(function*(){const t=new sd({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(){u(this,dd,[],"f")}rotateLastProbableInconsistencyCheckResults(e){4===d(this,dd,"f").length&&d(this,dd,"f").shift(),d(this,dd,"f").push(e)}isReachedMaxCheckRetries(e,t,r=4){let n=0;return d(this,dd,"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:nd(e.appData),producers:e.getProducers().map((e=>({id:e.id,paused:e.paused,stateChangedAt:e.getStateChangedAt()}))),consumers:e.getConsumersState()})))}}getIsConnectionActive(){return c(this,void 0,void 0,(function*(){try{return!!this.network.isNetworkActive&&(yield this.signalingApiClient.ping.pingPeer(),!0)}catch(e){return!1}}))}listenNetworkScoresUpdatedEvents(){d(this,cd,"f")&&d(this,cd,"f").on(Rt.NetworkScoresUpdated,(e=>{e.inbound&&(d(this,ld,"f").inbound=e.inbound),e.outbound&&(d(this,ld,"f").outbound=e.outbound)}))}isBadNetworkScore(){const{inbound:e,outbound:t}=d(this,ld,"f");return e<=2.6||t<=2.6}compareCheckedAndRestoredResults(e,t){return new id({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()-d(this,pd,"f")<=15e3}};ad=new WeakMap,cd=new WeakMap,dd=new WeakMap,ud=new WeakMap,ld=new WeakMap,pd=new WeakMap,hd=s([ct(),o(0,ut(Nn.LoggerFactory)),o(1,ut(Nn.Network)),o(2,ut(Nn.CallState)),o(3,ut(Nn.PeersStorage)),o(4,ut(Nn.ClientEventEmitter)),o(5,ut(Nn.SignalingApiClient)),o(6,ut(Nn.WebRTCIssueDetector)),a("design:paramtypes",[Function,Xc,Fn,Tc,wt,bc,ur])],hd);var fd=hd,md={},gd={exports:{}},vd=1e3,yd=6e4,_d=60*yd,bd=24*_d,Ed=function(e,t){t=t||{};var r=typeof e;if("string"===r&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return 6048e5*r;case"days":case"day":case"d":return r*bd;case"hours":case"hour":case"hrs":case"hr":case"h":return r*_d;case"minutes":case"minute":case"mins":case"min":case"m":return r*yd;case"seconds":case"second":case"secs":case"sec":case"s":return 1e3*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(e);if("number"===r&&isFinite(e))return t.long?function(e){var t=Math.abs(e);if(t>=bd)return wd(e,t,bd,"day");if(t>=_d)return wd(e,t,_d,"hour");if(t>=yd)return wd(e,t,yd,"minute");if(t>=1e3)return wd(e,t,1e3,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=bd)return Math.round(e/bd)+"d";if(t>=_d)return Math.round(e/_d)+"h";if(t>=yd)return Math.round(e/yd)+"m";if(t>=vd)return Math.round(e/vd)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function wd(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}var Sd=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=Ed,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=Sd(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(gd,gd.exports);var Cd={};Object.defineProperty(Cd,"__esModule",{value:!0});var Pd={},Td={};Object.defineProperty(Td,"__esModule",{value:!0}),Td.Logger=void 0;const Rd=gd.exports,kd="mediasoup-client";Td.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Rd.default)(`${kd}:${e}`),this._warn=(0,Rd.default)(`${kd}:WARN:${e}`),this._error=(0,Rd.default)(`${kd}:ERROR:${e}`)):(this._debug=(0,Rd.default)(kd),this._warn=(0,Rd.default)(`${kd}:WARN`),this._error=(0,Rd.default)(`${kd}: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,Id={},Ad={exports:{}},Od="object"==typeof Reflect?Reflect:null,Md=Od&&"function"==typeof Od.apply?Od.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};Dd=Od&&"function"==typeof Od.ownKeys?Od.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var Nd=Number.isNaN||function(e){return e!=e};function Ld(){Ld.init.call(this)}Ad.exports=Ld,Ad.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))}zd(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&zd(e,"error",t,r)}(e,i,{once:!0})}))},Ld.EventEmitter=Ld,Ld.prototype._events=void 0,Ld.prototype._eventsCount=0,Ld.prototype._maxListeners=void 0;var xd=10;function Fd(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function jd(e){return void 0===e._maxListeners?Ld.defaultMaxListeners:e._maxListeners}function Ud(e,t,r,n){var i,s,o,a;if(Fd(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=jd(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 Vd(){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 Bd(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=Vd.bind(n);return i.listener=r,n.wrapFn=i,i}function Wd(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):qd(i,i.length)}function Hd(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 qd(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function zd(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(Ld,"defaultMaxListeners",{enumerable:!0,get:function(){return xd},set:function(e){if("number"!=typeof e||e<0||Nd(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");xd=e}}),Ld.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},Ld.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||Nd(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},Ld.prototype.getMaxListeners=function(){return jd(this)},Ld.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)Md(a,this,t);else{var c=a.length,d=qd(a,c);for(r=0;r<c;++r)Md(d[r],this,t)}return!0},Ld.prototype.addListener=function(e,t){return Ud(this,e,t,!1)},Ld.prototype.on=Ld.prototype.addListener,Ld.prototype.prependListener=function(e,t){return Ud(this,e,t,!0)},Ld.prototype.once=function(e,t){return Fd(t),this.on(e,Bd(this,e,t)),this},Ld.prototype.prependOnceListener=function(e,t){return Fd(t),this.prependListener(e,Bd(this,e,t)),this},Ld.prototype.removeListener=function(e,t){var r,n,i,s,o;if(Fd(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},Ld.prototype.off=Ld.prototype.removeListener,Ld.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},Ld.prototype.listeners=function(e){return Wd(this,e,!0)},Ld.prototype.rawListeners=function(e){return Wd(this,e,!1)},Ld.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Hd.call(e,t)},Ld.prototype.listenerCount=Hd,Ld.prototype.eventNames=function(){return this._eventsCount>0?Dd(this._events):[]},Object.defineProperty(Id,"__esModule",{value:!0}),Id.EnhancedEventEmitter=void 0;const Gd=Ad.exports,Yd=new Td.Logger("EnhancedEventEmitter");class $d extends Gd.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){Yd.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)}}Id.EnhancedEventEmitter=$d;var Jd={};Object.defineProperty(Jd,"__esModule",{value:!0}),Jd.InvalidStateError=Jd.UnsupportedError=void 0;class Qd extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Qd):this.stack=new Error(e).stack}}Jd.UnsupportedError=Qd;class Kd extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Kd):this.stack=new Error(e).stack}}Jd.InvalidStateError=Kd;var Zd={};Object.defineProperty(Zd,"__esModule",{value:!0}),Zd.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))},Zd.generateRandomNumber=function(){return Math.round(1e7*Math.random())},Zd.deepFreeze=function e(t){const r=Reflect.ownKeys(t);for(const n of r){const r=t[n];(r&&"object"==typeof r||"function"==typeof r)&&e(r)}return Object.freeze(t)};var Xd={},eu={},tu={},ru={exports:{}};var nu=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=Ed,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=nu(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(ru,ru.exports),Object.defineProperty(tu,"__esModule",{value:!0}),tu.Logger=void 0;const iu=ru.exports,su="h264-profile-level-id";tu.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,iu.default)(`${su}:${e}`),this._warn=(0,iu.default)(`${su}:WARN:${e}`),this._error=(0,iu.default)(`${su}:ERROR:${e}`)):(this._debug=(0,iu.default)(su),this._warn=(0,iu.default)(`${su}:WARN`),this._error=(0,iu.default)(`${su}: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(eu,"__esModule",{value:!0}),eu.ProfileLevelId=eu.Level=eu.Profile=void 0,eu.parseProfileLevelId=mu,eu.profileLevelIdToString=gu,eu.profileToString=function(e){switch(e){case au.ConstrainedBaseline:return"ConstrainedBaseline";case au.Baseline:return"Baseline";case au.Main:return"Main";case au.ConstrainedHigh:return"ConstrainedHigh";case au.High:return"High";case au.PredictiveHigh444:return"PredictiveHigh444";default:return void ou.warn(`profileToString() | unrecognized profile ${e}`)}},eu.levelToString=function(e){switch(e){case cu.L1_b:return"1b";case cu.L1:return"1";case cu.L1_1:return"1.1";case cu.L1_2:return"1.2";case cu.L1_3:return"1.3";case cu.L2:return"2";case cu.L2_1:return"2.1";case cu.L2_2:return"2.2";case cu.L3:return"3";case cu.L3_1:return"3.1";case cu.L3_2:return"3.2";case cu.L4:return"4";case cu.L4_1:return"4.1";case cu.L4_2:return"4.2";case cu.L5:return"5";case cu.L5_1:return"5.1";case cu.L5_2:return"5.2";default:return void ou.warn(`levelToString() | unrecognized level ${e}`)}},eu.parseSdpProfileLevelId=vu,eu.isSameProfile=function(e={},t={}){const r=vu(e),n=vu(t);return Boolean(r&&n&&r.profile===n.profile)},eu.isSameProfileAndLevel=function(e={},t={}){const r=vu(e),n=vu(t);return Boolean(r&&n&&r.profile===n.profile&&r.level==n.level)},eu.generateProfileLevelIdStringForAnswer=function(e={},t={}){if(!e["profile-level-id"]&&!t["profile-level-id"])return void ou.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");const r=vu(e),n=vu(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=_u(e)&&_u(t),s=r.level,o=n.level,a=function(e,t){return function(e,t){if(e===cu.L1_b)return t!==cu.L1&&t!==cu.L1_b;if(t===cu.L1_b)return e!==cu.L1;return e<t}(e,t)?e:t}(s,o),c=i?s:a;return ou.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${r.profile}, level:${c}]`),gu(new du(r.profile,c))},eu.supportedLevel=function(e,t){for(let r=fu.length-1;r>=0;--r){const n=fu[r];if(256*n.max_macroblock_frame_size<=e&&n.max_macroblocks_per_second<=t*n.max_macroblock_frame_size)return ou.debug(`supportedLevel() | result [max_frame_pixel_count:${e}, max_fps:${t}, level:${n.level}]`),n.level}return void ou.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${e}, max_fps:${t}]`)};const ou=new tu.Logger;var au,cu;!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"}(au||(eu.Profile=au={})),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"}(cu||(eu.Level=cu={}));class du{profile;level;constructor(e,t){this.profile=e,this.level=t}}eu.ProfileLevelId=du;const uu=new du(au.ConstrainedBaseline,cu.L3_1);class lu{mask;masked_value;constructor(e){this.mask=~yu("x",e),this.masked_value=yu("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}}class pu{profile_idc;profile_iop;profile;constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}}const hu=[new pu(66,new lu("x1xx0000"),au.ConstrainedBaseline),new pu(77,new lu("1xxx0000"),au.ConstrainedBaseline),new pu(88,new lu("11xx0000"),au.ConstrainedBaseline),new pu(66,new lu("x0xx0000"),au.Baseline),new pu(88,new lu("10xx0000"),au.Baseline),new pu(77,new lu("0x0x0000"),au.Main),new pu(100,new lu("00000000"),au.High),new pu(100,new lu("00001100"),au.ConstrainedHigh),new pu(244,new lu("00000000"),au.PredictiveHigh444)],fu=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:cu.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:cu.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:cu.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:cu.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:cu.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:cu.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:cu.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:cu.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:cu.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:cu.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:cu.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:cu.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:cu.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:cu.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:cu.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:cu.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:cu.L5_2}];function mu(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 cu.L1_1:s=0!=(16&n)?cu.L1_b:cu.L1_1;break;case cu.L1:case cu.L1_2:case cu.L1_3:case cu.L2:case cu.L2_1:case cu.L2_2:case cu.L3:case cu.L3_1:case cu.L3_2:case cu.L4:case cu.L4_1:case cu.L4_2:case cu.L5:case cu.L5_1:case cu.L5_2:s=r;break;default:return void ou.warn(`parseProfileLevelId() | unrecognized level_idc [str:${e}, level_idc:${r}]`)}for(const t of hu)if(i===t.profile_idc&&t.profile_iop.isMatch(n))return ou.debug(`parseProfileLevelId() | result [str:${e}, profile:${t.profile}, level:${s}]`),new du(t.profile,s);ou.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${e}, profile_idc:${i}, profile_iop:${n}]`)}function gu(e){if(e.level==cu.L1_b)switch(e.profile){case au.ConstrainedBaseline:return"42f00b";case au.Baseline:return"42100b";case au.Main:return"4d100b";default:return void ou.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${e.profile}`)}let t;switch(e.profile){case au.ConstrainedBaseline:t="42e0";break;case au.Baseline:t="4200";break;case au.Main:t="4d00";break;case au.ConstrainedHigh:t="640c";break;case au.High:t="6400";break;case au.PredictiveHigh444:t="f400";break;default:return void ou.warn(`profileLevelIdToString() | unrecognized profile ${e.profile}`)}let r=e.level.toString(16);return 1===r.length&&(r=`0${r}`),`${t}${r}`}function vu(e={}){const t=e["profile-level-id"];return t?mu(t):uu}function yu(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 _u(e={}){const t=e["level-asymmetry-allowed"];return!0===t||1===t||"1"===t}Object.defineProperty(Xd,"__esModule",{value:!0}),Xd.validateAndNormalizeRtpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(e.codecs&&!Array.isArray(e.codecs))throw new TypeError("caps.codecs is not an array");e.codecs||(e.codecs=[]);for(const t of e.codecs)Su(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)Pu(t)},Xd.validateAndNormalizeRtpParameters=wu,Xd.validateAndNormalizeSctpStreamParameters=function(e){if("object"!=typeof e)throw new TypeError("params is not an object");if("number"!=typeof e.streamId)throw new TypeError("missing params.streamId");let t=!1;"boolean"==typeof e.ordered?t=!0:e.ordered=!0;if(e.maxPacketLifeTime&&"number"!=typeof e.maxPacketLifeTime)throw new TypeError("invalid params.maxPacketLifeTime");if(e.maxRetransmits&&"number"!=typeof e.maxRetransmits)throw new TypeError("invalid params.maxRetransmits");if(e.maxPacketLifeTime&&e.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(t&&e.ordered&&(e.maxPacketLifeTime||e.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");t||!e.maxPacketLifeTime&&!e.maxRetransmits||(e.ordered=!1);if(e.label&&"string"!=typeof e.label)throw new TypeError("invalid params.label");if(e.protocol&&"string"!=typeof e.protocol)throw new TypeError("invalid params.protocol")},Xd.validateSctpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(!e.numStreams||"object"!=typeof e.numStreams)throw new TypeError("missing caps.numStreams");!function(e){if("object"!=typeof e)throw new TypeError("numStreams is not an object");if("number"!=typeof e.OS)throw new TypeError("missing numStreams.OS");if("number"!=typeof e.MIS)throw new TypeError("missing numStreams.MIS")}(e.numStreams)},Xd.getExtendedRtpCapabilities=function(e,t,r){const n={codecs:[],headerExtensions:[]};if(r)for(const r of e.codecs??[]){if(Iu(r))continue;const e=(t.codecs??[]).find((e=>Au(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:Mu(r,e)};n.codecs.push(i)}else for(const r of t.codecs??[]){if(Iu(r))continue;const t=(e.codecs??[]).find((e=>Au(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:Mu(t,r)};n.codecs.push(i)}for(const r of n.codecs){const n=e.codecs.find((e=>Iu(e)&&e.parameters?.apt===r.localPayloadType)),i=t.codecs.find((e=>Iu(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=>Ou(e,r)));if(!t)continue;const i={kind:r.kind,uri:r.uri,sendId:t.preferredId,recvId:r.preferredId,encrypt:t.preferredEncrypt??!1,direction:"sendrecv"};switch(r.direction){case"sendrecv":i.direction="sendrecv";break;case"recvonly":i.direction="sendonly";break;case"sendonly":i.direction="recvonly";break;case"inactive":i.direction="inactive"}n.headerExtensions.push(i)}return n},Xd.getRecvRtpCapabilities=function(e){return Du({direction:"recvonly",extendedRtpCapabilities:e})},Xd.getSendRtpCapabilities=function(e){return Du({direction:"sendonly",extendedRtpCapabilities:e})},Xd.getSendingRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const n of t.codecs){if(n.kind!==e)continue;const t={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.localParameters,rtcpFeedback:n.rtcpFeedback};if(r.codecs.push(t),n.localRtxPayloadType){const e={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const n of t.headerExtensions){if(n.kind&&n.kind!==e||"sendrecv"!==n.direction&&"sendonly"!==n.direction)continue;const t={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};r.headerExtensions.push(t)}return r},Xd.getSendingRemoteRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const n of t.codecs){if(n.kind!==e)continue;const t={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.remoteParameters,rtcpFeedback:n.rtcpFeedback};if(r.codecs.push(t),n.localRtxPayloadType){const e={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const n of t.headerExtensions){if(n.kind&&n.kind!==e||"sendrecv"!==n.direction&&"sendonly"!==n.direction)continue;const t={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};r.headerExtensions.push(t)}if(r.headerExtensions.some((e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.uri)))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"goog-remb"!==e.type));else if(r.headerExtensions.some((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.uri)))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"transport-cc"!==e.type));else for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"transport-cc"!==e.type&&"goog-remb"!==e.type));return r},Xd.reduceCodecs=function(e,t){const r=[];if(t){for(let n=0;n<e.length;++n)if(Au(e[n],t,{strict:!0})){r.push(e[n]),Iu(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]),Iu(e[1])&&r.push(e[1]);return r},Xd.generateProbatorRtpParameters=function(e){wu(e=Eu.clone(e));const t={mid:"probator",codecs:[],headerExtensions:[],encodings:[{ssrc:1234}],rtcp:{cname:"probator"}};return t.codecs.push(e.codecs[0]),t.codecs[0].payloadType=127,t.headerExtensions=e.headerExtensions,t},Xd.canSend=function(e,t){return(t.codecs??[]).some((t=>t.kind===e))},Xd.canReceive=function(e,t){if(wu(e),0===e.codecs.length)return!1;const r=e.codecs[0];return(t.codecs??[]).some((e=>e.preferredPayloadType===r.payloadType))};const bu=eu,Eu=Zd;function wu(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)Tu(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)Ru(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)ku(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 Su(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)Cu(t)}function Cu(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 Pu(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 Tu(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)Cu(t)}function Ru(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 ku(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 Du({direction:e,extendedRtpCapabilities:t}){const r={codecs:[],headerExtensions:[]};for(const e of t.codecs){const t={kind:e.kind,mimeType:e.mimeType,preferredPayloadType:e.remotePayloadType,clockRate:e.clockRate,channels:e.channels,parameters:e.localParameters,rtcpFeedback:e.rtcpFeedback};if(r.codecs.push(t),!e.remoteRtxPayloadType)continue;const n={kind:e.kind,mimeType:`${e.kind}/rtx`,preferredPayloadType:e.remoteRtxPayloadType,clockRate:e.clockRate,parameters:{apt:e.remotePayloadType},rtcpFeedback:[]};r.codecs.push(n)}for(const n of t.headerExtensions){if("sendrecv"!==n.direction&&n.direction!==e)continue;const t={kind:n.kind,uri:n.uri,preferredId:n.recvId,preferredEncrypt:n.encrypt??!1,direction:n.direction};r.headerExtensions.push(t)}return r}function Iu(e){return!!e&&/.+\/rtx$/i.test(e.mimeType)}function Au(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(!bu.isSameProfile(e.parameters,t.parameters))return!1;let r;try{r=bu.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 Ou(e,t){return(!e.kind||!t.kind||e.kind===t.kind)&&e.uri===t.uri}function Mu(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 Nu={},Lu={},xu={},Fu={};Object.defineProperty(Fu,"__esModule",{value:!0}),Fu.Logger=void 0;const ju=gd.exports,Uu="awaitqueue";Fu.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=ju(`awaitqueue:${e}`),this._warn=ju(`awaitqueue:WARN:${e}`),this._error=ju(`awaitqueue:ERROR:${e}`)):(this._debug=ju(Uu),this._warn=ju("awaitqueue:WARN"),this._error=ju("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 Vu={};Object.defineProperty(Vu,"__esModule",{value:!0}),Vu.AwaitQueueRemovedTaskError=Vu.AwaitQueueStoppedError=void 0;class Bu extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Bu)}}Vu.AwaitQueueStoppedError=Bu;class Wu extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Wu)}}Vu.AwaitQueueRemovedTaskError=Wu,Object.defineProperty(xu,"__esModule",{value:!0}),xu.AwaitQueue=void 0;const Hu=Vu,qu=new Fu.Logger("AwaitQueue");xu.AwaitQueue=class{pendingTasks=new Map;nextTaskId=0;constructor(){qu.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t,r){if(t=t??e.name,qu.debug(`push() [name:${t}, options:%o]`,r),"function"!=typeof e)throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch(e){}return new Promise(((n,i)=>{if(t&&r?.removeOngoingTasksWithSameName)for(const e of this.pendingTasks.values())e.name===t&&e.reject(new Hu.AwaitQueueRemovedTaskError,{canExecuteNextTask:!1});const s={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:e=>{if(s.completed)return;s.completed=!0,this.pendingTasks.delete(s.id),qu.debug(`resolving task [name:${s.name}]`),n(e);const[t]=this.pendingTasks.values();t&&!t.executedAt&&this.execute(t)},reject:(e,{canExecuteNextTask:t})=>{if(!s.completed&&(s.completed=!0,this.pendingTasks.delete(s.id),qu.debug(`rejecting task [name:${s.name}]: %s`,String(e)),i(e),t)){const[e]=this.pendingTasks.values();e&&!e.executedAt&&this.execute(e)}}};this.pendingTasks.set(s.id,s),1===this.pendingTasks.size&&this.execute(s)}))}stop(){qu.debug("stop()");for(const e of this.pendingTasks.values())qu.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Hu.AwaitQueueStoppedError,{canExecuteNextTask:!1})}remove(e){qu.debug(`remove() [taskIdx:${e}]`);const t=Array.from(this.pendingTasks.values())[e];t?t.reject(new Hu.AwaitQueueRemovedTaskError,{canExecuteNextTask:!0}):qu.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(qu.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const t=await e.task();e.resolve(t)}catch(t){e.reject(t,{canExecuteNextTask:!0})}}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AwaitQueueRemovedTaskError=e.AwaitQueueStoppedError=e.AwaitQueue=void 0;var t=xu;Object.defineProperty(e,"AwaitQueue",{enumerable:!0,get:function(){return t.AwaitQueue}});var r=Vu;Object.defineProperty(e,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return r.AwaitQueueStoppedError}}),Object.defineProperty(e,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return r.AwaitQueueRemovedTaskError}})}(Lu);var zu={};Object.defineProperty(zu,"__esModule",{value:!0}),zu.Producer=void 0;const Gu=Id,Yu=Jd,$u=new Td.Logger("Producer");class Ju extends Gu.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new Gu.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:r,track:n,rtpParameters:i,stopTracks:s,disableTrackOnPause:o,zeroRtpOnPause:a,appData:c}){super(),$u.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||($u.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||($u.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Yu.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){$u.debug("pause()"),this._closed?$u.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(){$u.debug("resume()"),this._closed?$u.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($u.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch(e){}throw new Yu.InvalidStateError("closed")}if("ended"===e?.readyState)throw new Yu.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()):$u.debug("replaceTrack() | same track, ignored")}async setMaxSpatialLayer(e){if(this._closed)throw new Yu.InvalidStateError("closed");if("video"!==this._kind)throw new Yu.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 Yu.InvalidStateError("closed");if("object"!=typeof e)throw new TypeError("invalid params");await new Promise(((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)}))}onTrackEnded(){$u.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){}}}zu.Producer=Ju;var Qu={};Object.defineProperty(Qu,"__esModule",{value:!0}),Qu.Consumer=void 0;const Ku=Id,Zu=Jd,Xu=new Td.Logger("Consumer");class el extends Ku.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new Ku.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:r,rtpReceiver:n,track:i,rtpParameters:s,appData:o}){super(),Xu.debug("constructor()"),this._id=e,this._localId=t,this._producerId=r,this._rtpReceiver=n,this._track=i,this._rtpParameters=s,this._paused=!i.enabled,this._appData=o??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get producerId(){return this._producerId}get closed(){return this._closed}get kind(){return this._track.kind}get rtpReceiver(){return this._rtpReceiver}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Xu.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Xu.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Zu.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){Xu.debug("pause()"),this._closed?Xu.error("pause() | Consumer closed"):this._paused?Xu.debug("pause() | Consumer is already paused"):(this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause"))}resume(){Xu.debug("resume()"),this._closed?Xu.error("resume() | Consumer closed"):this._paused?(this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")):Xu.debug("resume() | Consumer is already resumed")}onTrackEnded(){Xu.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){try{this._track.removeEventListener("ended",this.onTrackEnded),this._track.stop()}catch(e){}}}Qu.Consumer=el;var tl={};Object.defineProperty(tl,"__esModule",{value:!0}),tl.DataProducer=void 0;const rl=Id,nl=Jd,il=new Td.Logger("DataProducer");class sl extends rl.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new rl.EnhancedEventEmitter;constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:n}){super(),il.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||(il.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(il.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(il.debug("send()"),this._closed)throw new nl.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(il.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?il.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):il.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(il.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))})),this._dataChannel.addEventListener("message",(()=>{this._closed||il.warn('DataChannel "message" event in a DataProducer, message discarded')})),this._dataChannel.addEventListener("bufferedamountlow",(()=>{this._closed||this.safeEmit("bufferedamountlow")}))}}tl.DataProducer=sl;var ol={};Object.defineProperty(ol,"__esModule",{value:!0}),ol.DataConsumer=void 0;const al=Id,cl=new Td.Logger("DataConsumer");class dl extends al.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new al.EnhancedEventEmitter;constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:n,appData:i}){super(),cl.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||(cl.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(cl.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(cl.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?cl.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):cl.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(cl.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)}))}}ol.DataConsumer=dl,Object.defineProperty(Nu,"__esModule",{value:!0}),Nu.Transport=void 0;const ul=Lu,ll=Id,pl=Jd,hl=Zd,fl=Xd,ml=zu,gl=Qu,vl=tl,yl=ol,_l=new Td.Logger("Transport");class bl{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class El extends ll.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 ul.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new ll.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(),_l.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=hl.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){_l.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 pl.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(_l.debug("restartIce()"),this._closed)throw new pl.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(_l.debug("updateIceServers()"),this._closed)throw new pl.InvalidStateError("closed");if(!Array.isArray(e))throw new TypeError("missing iceServers");return this._awaitQueue.push((async()=>this._handler.updateIceServers(e)),"transport.updateIceServers()")}async produce({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s,stopTracks:o=!0,disableTrackOnPause:a=!0,zeroRtpOnPause:c=!1,onRtpSender:d,appData:u={}}={}){if(_l.debug("produce() [track:%o]",e),this._closed)throw new pl.InvalidStateError("closed");if(!e)throw new TypeError("missing track");if("send"!==this._direction)throw new pl.UnsupportedError("not a sending Transport");if(!this._canProduceByKind[e.kind])throw new pl.UnsupportedError(`cannot produce ${e.kind}`);if("ended"===e.readyState)throw new pl.InvalidStateError("track ended");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("produce"))throw new TypeError('no "produce" listener set into this transport');if(u&&"object"!=typeof u)throw new TypeError("if given, appData must be an object");return this._awaitQueue.push((async()=>{let l;if(r&&!Array.isArray(r))throw TypeError("encodings must be an array");0===r?.length?l=void 0:r&&(l=r.map((e=>{const t={active:!0};return!1===e.active&&(t.active=!1),"boolean"==typeof e.dtx&&(t.dtx=e.dtx),"string"==typeof e.scalabilityMode&&(t.scalabilityMode=e.scalabilityMode),"number"==typeof e.scaleResolutionDownBy&&(t.scaleResolutionDownBy=e.scaleResolutionDownBy),"number"==typeof e.maxBitrate&&(t.maxBitrate=e.maxBitrate),"number"==typeof e.maxFramerate&&(t.maxFramerate=e.maxFramerate),"boolean"==typeof e.adaptivePtime&&(t.adaptivePtime=e.adaptivePtime),"string"==typeof e.priority&&(t.priority=e.priority),"string"==typeof e.networkPriority&&(t.networkPriority=e.networkPriority),t})));const{localId:p,rtpParameters:h,rtpSender:f}=await this._handler.send({track:e,streamId:t,encodings:l,codecOptions:n,headerExtensionOptions:i,codec:s,onRtpSender:d});try{fl.validateAndNormalizeRtpParameters(h);const{id:t}=await new Promise(((t,r)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:h,appData:u},t,r)})),r=new ml.Producer({id:t,localId:p,rtpSender:f,track:e,rtpParameters:h,stopTracks:o,disableTrackOnPause:a,zeroRtpOnPause:c,appData:u});return this._producers.set(r.id,r),this.handleProducer(r),this._observer.safeEmit("newproducer",r),r}catch(e){throw this._handler.stopSending(p).catch((()=>{})),e}}),"transport.produce()").catch((t=>{if(o)try{e.stop()}catch(e){}throw t}))}async consume({id:e,producerId:t,kind:r,rtpParameters:n,streamId:i,onRtpReceiver:s,appData:o={}}){if(_l.debug("consume()"),this._closed)throw new pl.InvalidStateError("closed");if("recv"!==this._direction)throw new pl.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=hl.clone(n);if(!fl.canReceive(a,this._recvRtpCapabilities))throw new pl.UnsupportedError("cannot consume this Producer");const c=new bl({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(_l.debug("produceData()"),this._closed)throw new pl.InvalidStateError("closed");if("send"!==this._direction)throw new pl.UnsupportedError("not a sending Transport");if(!this._maxSctpMessageSize)throw new pl.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});fl.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 vl.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(_l.debug("consumeData()"),this._closed)throw new pl.InvalidStateError("closed");if("recv"!==this._direction)throw new pl.UnsupportedError("not a receiving Transport");if(!this._maxSctpMessageSize)throw new pl.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=hl.clone(r);return fl.validateAndNormalizeSctpStreamParameters(o),this._awaitQueue.push((async()=>{const{dataChannel:r}=await this._handler.receiveDataChannel({sctpStreamParameters:o,label:n,protocol:i}),a=new yl.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 _l.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 gl.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=fl.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:e}]),_l.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(e){_l.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 _l.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){_l.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 _l.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){_l.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 _l.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){_l.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 pl.InvalidStateError("closed")):this.safeEmit("connect",{dtlsParameters:e},t,r)})),e.on("@icegatheringstatechange",(e=>{e!==this._iceGatheringState&&(_l.debug("ICE gathering state changed to %s",e),this._iceGatheringState=e,this._closed||this.safeEmit("icegatheringstatechange",e))})),e.on("@icecandidateerror",(e=>{_l.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&&(_l.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=>_l.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 pl.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 pl.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)}))}}Nu.Transport=El;var wl={},Sl={},Cl={},Pl={exports:{}},Tl=Pl.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{push:"msid",reg:/^msid:([\w-]+)(?: ([\w-]+))?/,names:["id","appdata"],format:"msid:%s %s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Tl).forEach((function(e){Tl[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=Pl.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}}))}))}}(Cl);var Rl=Pl.exports,kl=/%[sdv%]/g,Dl=function(e){var t=1,r=arguments,n=r.length;return e.replace(kl,(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""}}))},Il=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 Dl.apply(null,n)},Al=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Ol=["i","c","b","a"],Ml=Cl,Nl=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||Al,n=t.innerOrder||Ol,i=[];return r.forEach((function(t){Rl[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(Il(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(Il(t,r,e))}))}))})),e.media.forEach((function(e){i.push(Il("m",Rl.m[0],e)),n.forEach((function(t){Rl[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(Il(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(Il(t,r,e))}))}))}))})),i.join("\r\n")+"\r\n"},Ll=Pl.exports;Sl.grammar=Ll,Sl.write=Nl,Sl.parse=Ml.parse,Sl.parseParams=Ml.parseParams,Sl.parseFmtpConfig=Ml.parseFmtpConfig,Sl.parsePayloads=Ml.parsePayloads,Sl.parseRemoteCandidates=Ml.parseRemoteCandidates,Sl.parseImageAttributes=Ml.parseImageAttributes,Sl.parseSimulcastStreamList=Ml.parseSimulcastStreamList;var xl={};Object.defineProperty(xl,"__esModule",{value:!0}),xl.parse=function(e){const t=Fl.exec(e??"");return t?{spatialLayers:Number(t[1]),temporalLayers:Number(t[2])}:{spatialLayers:1,temporalLayers:1}};const Fl=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");var jl={},Ul={};Object.defineProperty(Ul,"__esModule",{value:!0}),Ul.OfferMediaSection=Ul.AnswerMediaSection=Ul.MediaSection=void 0;const Vl=Sl,Bl=Zd;class Wl{_mediaObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r}){if(this._mediaObject={type:"",port:0,protocol:"",payloads:"",rtp:[],fmtp:[]},e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(const e of t){const t={foundation:e.foundation,component:1,ip:e.address??e.ip,port:e.port,priority:e.priority,transport:e.protocol,type:e.type};e.tcpType&&(t.tcptype=e.tcpType),this._mediaObject.candidates.push(t)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}r&&this.setDtlsRole(r.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return 0===this._mediaObject.port}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause()}close(){this.disable(),this._mediaObject.port=0,delete this._mediaObject.candidates,delete this._mediaObject.endOfCandidates,delete this._mediaObject.iceUfrag,delete this._mediaObject.icePwd,delete this._mediaObject.iceOptions,this._mediaObject.rtp=[],this._mediaObject.fmtp=[],delete this._mediaObject.rtcp,delete this._mediaObject.rtcpFb,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}}Ul.MediaSection=Wl;Ul.AnswerMediaSection=class extends Wl{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:Hl(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r=Bl.clone(e.parameters)??{};let n=Bl.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=Vl.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 Hl(e){const t=new RegExp("^(audio|video)/(.+)","i").exec(e.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}Ul.OfferMediaSection=class extends Wl{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,mid:s,kind:o,offerRtpParameters:a,streamId:c,trackId:d}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(s),this._mediaObject.type=o,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.protocol=n?"UDP/DTLS/SCTP":"UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",o){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=[{id:c,appdata:d}];for(const e of a.codecs){const t={payload:e.payloadType,codec:Hl(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(jl,"__esModule",{value:!0}),jl.RemoteSdp=void 0;const ql=Sl,zl=Ul,Gl=md,Yl=["av1","h264"],$l=new Td.Logger("RemoteSdp");jl.RemoteSdp=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i}){if(this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=r,this._sctpParameters=n,this._plainRtpParameters=i,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:`mediasoup-client-v${Gl.version}`},name:"-",timing:{start:0,stop:0},media:[]},this._sdpObject.iceOptions="ice2",e?.iceLite&&(this._sdpObject.icelite="ice-lite"),r){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};const e=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:r.fingerprints[e-1].algorithm,hash:r.fingerprints[e-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){$l.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){$l.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(const t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){$l.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 zl.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=>Yl.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 zl.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?($l.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 zl.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 zl.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++,ql.write(this._sdpObject)}addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this.regenerateBundleMids()}replaceMediaSection(e,t){if("string"==typeof t){const r=this._midToIndex.get(t);if(void 0===r)throw new Error(`no media section found for reuseMid '${t}'`);const n=this._mediaSections[r];this._mediaSections[r]=e,this._midToIndex.delete(n.mid),this._midToIndex.set(e.mid,r),this._sdpObject.media[r]=e.getObject(),this.regenerateBundleMids()}else{const t=this._midToIndex.get(e.mid);if(void 0===t)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[t]=e,this._sdpObject.media[t]=e.getObject()}}findMediaSection(e){const t=this._midToIndex.get(e);if(void 0===t)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter((e=>!e.closed)).map((e=>e.mid)).join(" "))}};var Jl={};Object.defineProperty(Jl,"__esModule",{value:!0}),Jl.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=Ql.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())}},Jl.extractDtlsParameters=function({sdpObject:e}){let t,r=e.setup,n=e.fingerprint;if(!r||!n){const t=(e.media??[]).find((e=>0!==e.port));t&&(r=r??t.setup,n=n??t.fingerprint)}if(!r)throw new Error("no a=setup found at SDP session or media level");if(!n)throw new Error("no a=fingerprint found at SDP session or media level");switch(r){case"active":t="client";break;case"passive":t="server";break;case"actpass":t="auto"}return{role:t,fingerprints:[{algorithm:n.type,value:n.hash}]}},Jl.getCname=function({offerMediaObject:e}){const t=(e.ssrcs??[]).find((e=>"cname"===e.attribute));if(!t)return"";return t.value},Jl.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=Ql.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]}`}},Jl.addHeaderExtension=function({offerMediaObject:e,headerExtensionUri:t,headerExtensionId:r}){e.ext||(e.ext=[]);e.ext.push({uri:t,value:r})};const Ql=Sl;var Kl={};Object.defineProperty(Kl,"__esModule",{value:!0}),Kl.getRtpEncodings=function({offerMediaObject:e,codecs:t}){const r=new Set;for(const t of e.ssrcs??[]){const e=t.id;e&&r.add(e)}if(0===r.size)throw new Error("no a=ssrc lines found");const n=new Map;for(const t of e.ssrcGroups??[]){if("FID"!==t.semantics)continue;const e=t.ssrcs.split(/\s+/),i=Number(e[0]),s=Number(e[1]);r.has(i)&&(r.delete(i),r.delete(s),n.set(i,s))}for(const e of r)n.set(e,void 0);const i=[];for(const[e,r]of n){const n={ssrc:e};r&&t.length>1&&(n.rtx={ssrc:r}),i.push(n)}return i},Kl.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 Zl={};Object.defineProperty(Zl,"__esModule",{value:!0}),Zl.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"}))},Zl.addHeaderExtensionSupport=function(e,t){let r;const n=e.headerExtensions?.find((e=>e.uri===t.uri));if(n){if(n.kind===t.kind)return;r=n.preferredId}e.headerExtensions||(e.headerExtensions=[]);if(void 0===r){r=1;const t=new Set(e.headerExtensions.map((e=>e.preferredId)));for(;t.has(r);)++r}const i={kind:t.kind,uri:t.uri,preferredId:r,preferredEncrypt:!1,direction:t.direction};e.headerExtensions.push(i)},Zl.getMsidStreamIdAndTrackId=function(e){if(!e||"string"!=typeof e)return{msidStreamId:void 0,msidTrackId:void 0};const[t,r]=e.trim().split(/\s+/);if(!t)return{msidStreamId:void 0,msidTrackId:void 0};return{msidStreamId:t,msidTrackId:r}},Object.defineProperty(wl,"__esModule",{value:!0}),wl.Chrome111=void 0;const Xl=Sl,ep=Id,tp=Xd,rp=Jd,np=xl,ip=jl,sp=Jl,op=Kl,ap=Zl,cp=new Td.Logger("Chrome111"),dp={OS:1024,MIS:1024};class up extends ep.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 up(e),getNativeRtpCapabilities:async({direction:e})=>{cp.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e,sendEncodings:[{scalabilityMode:"L3T3"}]});const r=await t.createOffer();try{t.close()}catch(e){}t=void 0;const n=Xl.parse(r.sdp);return up.getLocalRtpCapabilities(n)}catch(e){try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(cp.debug("getNativeSctpCapabilities()"),{numStreams:dp})}}static getLocalRtpCapabilities(e,t=[]){const r=sp.extractRtpCapabilities({sdpObject:e});tp.validateAndNormalizeRtpCapabilities(r),ap.addNackSupportForOpus(r);for(const e of t)ap.addHeaderExtensionSupport(r,e);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),cp.debug("constructor()"),this._direction=e,this._remoteSdp=new ip.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):(cp.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Chrome111"}close(){if(cp.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(),cp.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),cp.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});cp.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};cp.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};cp.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();cp.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s,onRtpSender:o}){if(this.assertNotClosed(),this.assertSendDirection(),cp.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1){let e=1;for(const t of r){const r=t.scalabilityMode?(0,np.parse)(t.scalabilityMode).temporalLayers:3;r>e&&(e=r)}r.forEach(((t,r)=>{t.rid=`r${r}`,t.scalabilityMode=`L1T${e}`}))}const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});o&&o(c.sender);let d=await this._pc.createOffer(),u=Xl.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const l=[];l.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});const p=up.getLocalRtpCapabilities(u,l),h=this._getSendExtendedRtpCapabilities(p),f=tp.getSendingRtpParameters(e.kind,h);f.codecs=tp.reduceCodecs(f.codecs,s);const m=tp.getSendingRemoteRtpParameters(e.kind,h);if(m.codecs=tp.reduceCodecs(m.codecs,s),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u}),i?.absCaptureTime){const e=u.media[a.idx];sp.addHeaderExtension({offerMediaObject:e,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"===e.uri)).id}),d={type:"offer",sdp:Xl.write(u)}}cp.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const g=c.mid;f.mid=g,u=Xl.parse(this._pc.localDescription.sdp);const v=u.media[a.idx];if(f.rtcp.cname=sp.getCname({offerMediaObject:v}),f.msid=`${t??this._sendStream.id} ${e.id}`,r)if(1===r.length){const e=op.getRtpEncodings({offerMediaObject:v,codecs:f.codecs});Object.assign(e[0],r[0]),f.encodings=e}else f.encodings=r;else f.encodings=op.getRtpEncodings({offerMediaObject:v,codecs:f.codecs});this._remoteSdp.send({offerMediaObject:v,reuseMid:a.reuseMid,offerRtpParameters:f,answerRtpParameters:m,codecOptions:n});const y={type:"answer",sdp:this._remoteSdp.getSdp()};return cp.debug("send() | calling pc.setRemoteDescription() [answer:%o]",y),await this._pc.setRemoteDescription(y),this._mapMidTransceiver.set(g,c),{localId:g,rtpParameters:f,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),cp.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();cp.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};cp.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),cp.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();cp.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};cp.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),cp.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();cp.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};cp.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?cp.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):cp.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(),cp.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();cp.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};cp.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),cp.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();cp.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};cp.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};cp.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%dp.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Xl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),cp.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()};cp.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;cp.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=ap.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};cp.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=Xl.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));sp.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Xl.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),cp.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){cp.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()};cp.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();cp.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){cp.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()};cp.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();cp.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){cp.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()};cp.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();cp.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};cp.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()};cp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Xl.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}cp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Xl.parse(this._pc.localDescription.sdp));const r=sp.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 rp.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')}}wl.Chrome111=up;var lp={};Object.defineProperty(lp,"__esModule",{value:!0}),lp.Chrome74=void 0;const pp=Sl,hp=Id,fp=Xd,mp=Jd,gp=xl,vp=jl,yp=Jl,_p=Kl,bp=Zl,Ep=new Td.Logger("Chrome74"),wp={OS:1024,MIS:1024};class Sp extends hp.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 Sp(e),getNativeRtpCapabilities:async({direction:e})=>{Ep.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});const r=await t.createOffer();try{t.close()}catch(e){}t=void 0;const n=pp.parse(r.sdp);return Sp.getLocalRtpCapabilities(n)}catch(e){try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(Ep.debug("getNativeSctpCapabilities()"),{numStreams:wp})}}static getLocalRtpCapabilities(e,t=[]){const r=yp.extractRtpCapabilities({sdpObject:e});fp.validateAndNormalizeRtpCapabilities(r),bp.addNackSupportForOpus(r);for(const e of t)bp.addHeaderExtensionSupport(r,e);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Ep.debug("constructor()"),this._direction=e,this._remoteSdp=new vp.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):(Ep.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Chrome74"}close(){if(Ep.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(),Ep.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Ep.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Ep.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Ep.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Ep.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Ep.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s}){this.assertNotClosed(),this.assertSendDirection(),Ep.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach(((e,t)=>{e.rid=`r${t}`}));const o=this._remoteSdp.getNextMediaSectionIdx(),a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});let c=await this._pc.createOffer(),d=pp.parse(c.sdp);d.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const u=[];u.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});const l=Sp.getLocalRtpCapabilities(d,u),p=this._getSendExtendedRtpCapabilities(l),h=fp.getSendingRtpParameters(e.kind,p);h.codecs=fp.reduceCodecs(h.codecs,s);const f=fp.getSendingRemoteRtpParameters(e.kind,p);f.codecs=fp.reduceCodecs(f.codecs,s),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:d});let m=!1;const g=(0,gp.parse)((r??[{}])[0].scalabilityMode);let v;1===r?.length&&g.spatialLayers>1&&"video/vp9"===h.codecs[0].mimeType.toLowerCase()&&(Ep.debug("send() | enabling legacy simulcast for VP9 SVC"),m=!0,d=pp.parse(c.sdp),v=d.media[o.idx],_p.addLegacySimulcast({offerMediaObject:v,numStreams:g.spatialLayers}),c={type:"offer",sdp:pp.write(d)}),Ep.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),i?.absCaptureTime&&(v=d.media[o.idx],yp.addHeaderExtension({offerMediaObject:v,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:f.headerExtensions.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"===e.uri)).id}),c={type:"offer",sdp:pp.write(d)}),await this._pc.setLocalDescription(c);const y=a.mid;if(h.mid=y,d=pp.parse(this._pc.localDescription.sdp),v=d.media[o.idx],h.rtcp.cname=yp.getCname({offerMediaObject:v}),h.msid=`${t??this._sendStream.id} ${e.id}`,r)if(1===r.length){let e=_p.getRtpEncodings({offerMediaObject:v,codecs:h.codecs});Object.assign(e[0],r[0]),m&&(e=[e[0]]),h.encodings=e}else h.encodings=r;else h.encodings=_p.getRtpEncodings({offerMediaObject:v,codecs:h.codecs});if(h.encodings.length>1&&("video/vp8"===h.codecs[0].mimeType.toLowerCase()||"video/h264"===h.codecs[0].mimeType.toLowerCase()))for(const e of h.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${g.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:v,reuseMid:o.reuseMid,offerRtpParameters:h,answerRtpParameters:f,codecOptions:n});const _={type:"answer",sdp:this._remoteSdp.getSdp()};return Ep.debug("send() | calling pc.setRemoteDescription() [answer:%o]",_),await this._pc.setRemoteDescription(_),this._mapMidTransceiver.set(y,a),{localId:y,rtpParameters:h,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),Ep.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();Ep.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Ep.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Ep.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();Ep.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Ep.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Ep.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();Ep.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Ep.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Ep.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Ep.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(),Ep.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();Ep.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Ep.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Ep.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();Ep.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Ep.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};Ep.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%wp.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=pp.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Ep.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()};Ep.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;Ep.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=bp.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Ep.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer();const s=pp.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));yp.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:pp.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Ep.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){Ep.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()};Ep.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Ep.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){Ep.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()};Ep.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Ep.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){Ep.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()};Ep.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Ep.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};Ep.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()};Ep.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=pp.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Ep.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=pp.parse(this._pc.localDescription.sdp));const r=yp.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 mp.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')}}lp.Chrome74=Sp;var Cp={};Object.defineProperty(Cp,"__esModule",{value:!0}),Cp.Firefox120=void 0;const Pp=Sl,Tp=Id,Rp=Jd,kp=Xd,Dp=xl,Ip=jl,Ap=Jl,Op=Kl,Mp=Zl,Np=new Td.Logger("Firefox120"),Lp={OS:16,MIS:2048};class xp extends Tp.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 xp(e),getNativeRtpCapabilities:async({direction:e})=>{Np.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});const r=document.createElement("canvas");r.getContext("2d");const n=r.captureStream().getVideoTracks()[0];try{t.addTransceiver("audio",{direction:e}),t.addTransceiver(n,{direction:e,sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});const i=await t.createOffer();try{r.remove()}catch(e){}try{n.stop()}catch(e){}try{t.close()}catch(e){}t=void 0;const s=Pp.parse(i.sdp);return xp.getLocalRtpCapabilities(s)}catch(e){try{r.remove()}catch(e){}try{n.stop()}catch(e){}try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(Np.debug("getNativeSctpCapabilities()"),{numStreams:Lp})}}static getLocalRtpCapabilities(e){const t=Ap.extractRtpCapabilities({sdpObject:e});return kp.validateAndNormalizeRtpCapabilities(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Np.debug("constructor()"),this._direction=e,this._remoteSdp=new Ip.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):(Np.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Firefox120"}close(){if(Np.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 Rp.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),Np.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Np.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Np.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Np.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Np.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,codec:i,onRtpSender:s}){this.assertNotClosed(),this.assertSendDirection(),Np.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach(((e,t)=>{e.rid=`r${t}`}));const o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});s&&s(o.sender);const a=await this._pc.createOffer();let c=Pp.parse(a.sdp);c.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const d=xp.getLocalRtpCapabilities(c),u=this._getSendExtendedRtpCapabilities(d),l=kp.getSendingRtpParameters(e.kind,u);l.codecs=kp.reduceCodecs(l.codecs,i);const p=kp.getSendingRemoteRtpParameters(e.kind,u);p.codecs=kp.reduceCodecs(p.codecs,i),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:c});const h=(0,Dp.parse)((r??[{}])[0].scalabilityMode);Np.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const f=o.mid;l.mid=f,c=Pp.parse(this._pc.localDescription.sdp);const m=c.media[c.media.length-1];if(l.rtcp.cname=Ap.getCname({offerMediaObject:m}),l.msid=`${t??this._sendStream.id} ${e.id}`,r)if(1===r.length){const e=Op.getRtpEncodings({offerMediaObject:m,codecs:l.codecs});Object.assign(e[0],r[0]),l.encodings=e}else l.encodings=r;else l.encodings=Op.getRtpEncodings({offerMediaObject:m,codecs:l.codecs});if(l.encodings.length>1&&("video/vp8"===l.codecs[0].mimeType.toLowerCase()||"video/h264"===l.codecs[0].mimeType.toLowerCase()))for(const e of l.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${h.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:m,offerRtpParameters:l,answerRtpParameters:p,codecOptions:n});const g={type:"answer",sdp:this._remoteSdp.getSdp()};return Np.debug("send() | calling pc.setRemoteDescription() [answer:%o]",g),await this._pc.setRemoteDescription(g),this._mapMidTransceiver.set(f,o),{localId:f,rtpParameters:l,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),Np.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();Np.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Np.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Np.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();Np.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Np.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Np.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();Np.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Np.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Np.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Np.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(),Np.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();Np.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Np.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Np.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();Np.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Np.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};Np.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Lp.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Pp.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),Np.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()};Np.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;Np.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=Mp.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Np.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=Pp.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));Ap.applyCodecParameters({offerRtpParameters:n,answerMediaObject:a}),i={type:"answer",sdp:Pp.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),Np.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){Np.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()};Np.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Np.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){Np.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()};Np.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Np.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){Np.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()};Np.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Np.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};Np.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()};Np.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Pp.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}Np.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=Pp.parse(this._pc.localDescription.sdp));const r=Ap.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 Rp.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')}}Cp.Firefox120=xp;var Fp={};Object.defineProperty(Fp,"__esModule",{value:!0}),Fp.Safari12=void 0;const jp=Sl,Up=Id,Vp=Xd,Bp=Jd,Wp=xl,Hp=jl,qp=Jl,zp=Kl,Gp=Zl,Yp=new Td.Logger("Safari12"),$p={OS:1024,MIS:1024};class Jp extends Up.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 Jp(e),getNativeRtpCapabilities:async({direction:e})=>{Yp.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});const r=await t.createOffer();try{t.close()}catch(e){}t=void 0;const n=jp.parse(r.sdp);return Jp.getLocalRtpCapabilities(n)}catch(e){try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(Yp.debug("getNativeSctpCapabilities()"),{numStreams:$p})}}static getLocalRtpCapabilities(e,t=[]){const r=qp.extractRtpCapabilities({sdpObject:e});Vp.validateAndNormalizeRtpCapabilities(r),Gp.addNackSupportForOpus(r);for(const e of t)Gp.addHeaderExtensionSupport(r,e);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Yp.debug("constructor()"),this._direction=e,this._remoteSdp=new Hp.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):(Yp.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Safari12"}close(){if(Yp.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(),Yp.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Yp.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Yp.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Yp.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Yp.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Yp.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s,onRtpSender:o}){this.assertNotClosed(),this.assertSendDirection(),Yp.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});o&&o(c.sender);let d=await this._pc.createOffer(),u=jp.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const l=[];l.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});const p=Jp.getLocalRtpCapabilities(u,l),h=this._getSendExtendedRtpCapabilities(p),f=Vp.getSendingRtpParameters(e.kind,h);f.codecs=Vp.reduceCodecs(f.codecs,s);const m=Vp.getSendingRemoteRtpParameters(e.kind,h);let g;m.codecs=Vp.reduceCodecs(m.codecs,s),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});const v=(0,Wp.parse)((r??[{}])[0].scalabilityMode);r&&r.length>1&&(Yp.debug("send() | enabling legacy simulcast"),u=jp.parse(d.sdp),g=u.media[a.idx],zp.addLegacySimulcast({offerMediaObject:g,numStreams:r.length}),d={type:"offer",sdp:jp.write(u)}),i?.absCaptureTime&&(g=u.media[a.idx],qp.addHeaderExtension({offerMediaObject:g,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"===e.uri)).id}),d={type:"offer",sdp:jp.write(u)}),Yp.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const y=c.mid;if(f.mid=y,u=jp.parse(this._pc.localDescription.sdp),g=u.media[a.idx],f.rtcp.cname=qp.getCname({offerMediaObject:g}),f.msid=`${t??this._sendStream.id} ${e.id}`,f.encodings=zp.getRtpEncodings({offerMediaObject:g,codecs:f.codecs}),r)for(let e=0;e<f.encodings.length;++e)r[e]&&Object.assign(f.encodings[e],r[e]);if(f.encodings.length>1&&("video/vp8"===f.codecs[0].mimeType.toLowerCase()||"video/h264"===f.codecs[0].mimeType.toLowerCase()))for(const e of f.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${v.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:g,reuseMid:a.reuseMid,offerRtpParameters:f,answerRtpParameters:m,codecOptions:n});const _={type:"answer",sdp:this._remoteSdp.getSdp()};return Yp.debug("send() | calling pc.setRemoteDescription() [answer:%o]",_),await this._pc.setRemoteDescription(_),this._mapMidTransceiver.set(y,c),{localId:y,rtpParameters:f,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Yp.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();Yp.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Yp.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Yp.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();Yp.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Yp.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Yp.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();Yp.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Yp.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Yp.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Yp.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(),Yp.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();Yp.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Yp.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Yp.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();Yp.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Yp.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};Yp.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%$p.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=jp.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Yp.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()};Yp.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;Yp.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=Gp.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Yp.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=jp.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));qp.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:jp.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Yp.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){Yp.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()};Yp.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Yp.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){Yp.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()};Yp.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Yp.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){Yp.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()};Yp.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Yp.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};Yp.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()};Yp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=jp.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Yp.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=jp.parse(this._pc.localDescription.sdp));const r=qp.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 Bp.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')}}Fp.Safari12=Jp;var Qp={};Object.defineProperty(Qp,"__esModule",{value:!0}),Qp.ReactNative106=void 0;const Kp=Sl,Zp=Id,Xp=Xd,eh=Jd,th=xl,rh=jl,nh=Jl,ih=Kl,sh=Zl,oh=new Td.Logger("ReactNative106"),ah={OS:1024,MIS:1024};class ch extends Zp.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 ch(e),getNativeRtpCapabilities:async({direction:e})=>{oh.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});const r=await t.createOffer();try{t.close()}catch(e){}t=void 0;const n=Kp.parse(r.sdp);return ch.getLocalRtpCapabilities(n)}catch(e){try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(oh.debug("getNativeSctpCapabilities()"),{numStreams:ah})}}static getLocalRtpCapabilities(e,t=[]){const r=nh.extractRtpCapabilities({sdpObject:e});Xp.validateAndNormalizeRtpCapabilities(r),sh.addNackSupportForOpus(r);for(const e of t)sh.addHeaderExtensionSupport(r,e);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),oh.debug("constructor()"),this._direction=e,this._remoteSdp=new rh.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):(oh.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"ReactNative106"}close(){if(oh.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(),oh.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),oh.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});oh.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};oh.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};oh.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();oh.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s,onRtpSender:o}){this.assertNotClosed(),this.assertSendDirection(),oh.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach(((e,t)=>{e.rid=`r${t}`}));const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});o&&o(c.sender);let d=await this._pc.createOffer(),u=Kp.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const l=[];l.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});const p=ch.getLocalRtpCapabilities(u,l),h=this._getSendExtendedRtpCapabilities(p),f=Xp.getSendingRtpParameters(e.kind,h);f.codecs=Xp.reduceCodecs(f.codecs,s);const m=Xp.getSendingRemoteRtpParameters(e.kind,h);m.codecs=Xp.reduceCodecs(m.codecs,s),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let g=!1;const v=(0,th.parse)((r??[{}])[0].scalabilityMode);let y;1===r?.length&&v.spatialLayers>1&&"video/vp9"===f.codecs[0].mimeType.toLowerCase()&&(oh.debug("send() | enabling legacy simulcast for VP9 SVC"),g=!0,u=Kp.parse(d.sdp),y=u.media[a.idx],ih.addLegacySimulcast({offerMediaObject:y,numStreams:v.spatialLayers}),d={type:"offer",sdp:Kp.write(u)}),i?.absCaptureTime&&(y=u.media[a.idx],nh.addHeaderExtension({offerMediaObject:y,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"===e.uri)).id}),d={type:"offer",sdp:Kp.write(u)}),oh.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);let _=c.mid??void 0;if(_||oh.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),f.mid=_,u=Kp.parse(this._pc.localDescription.sdp),y=u.media[a.idx],f.rtcp.cname=nh.getCname({offerMediaObject:y}),f.msid=`${t??this._sendStream.id} ${e.id}`,r)if(1===r.length){let e=ih.getRtpEncodings({offerMediaObject:y,codecs:f.codecs});Object.assign(e[0],r[0]),g&&(e=[e[0]]),f.encodings=e}else f.encodings=r;else f.encodings=ih.getRtpEncodings({offerMediaObject:y,codecs:f.codecs});if(f.encodings.length>1&&("video/vp8"===f.codecs[0].mimeType.toLowerCase()||"video/h264"===f.codecs[0].mimeType.toLowerCase()))for(const e of f.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${v.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:y,reuseMid:a.reuseMid,offerRtpParameters:f,answerRtpParameters:m,codecOptions:n});const b={type:"answer",sdp:this._remoteSdp.getSdp()};return oh.debug("send() | calling pc.setRemoteDescription() [answer:%o]",b),await this._pc.setRemoteDescription(b),_||(_=c.mid,f.mid=_),this._mapMidTransceiver.set(_,c),{localId:_,rtpParameters:f,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;oh.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();oh.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};oh.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),oh.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();oh.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};oh.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),oh.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();oh.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};oh.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?oh.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):oh.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(),oh.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();oh.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};oh.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),oh.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();oh.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};oh.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};oh.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%ah.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Kp.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),oh.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()};oh.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;oh.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=sh.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};oh.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=Kp.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));nh.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Kp.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),oh.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){oh.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()};oh.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();oh.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){oh.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()};oh.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();oh.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){oh.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()};oh.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();oh.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};oh.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()};oh.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Kp.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}oh.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=Kp.parse(this._pc.localDescription.sdp));const r=nh.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 eh.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')}}Qp.ReactNative106=ch,Object.defineProperty(Pd,"__esModule",{value:!0}),Pd.Device=void 0,Pd.detectDevice=bh,Pd.detectDeviceAsync=Eh;const dh=Id,uh=Jd,lh=Zd,ph=Xd,hh=Nu,fh=wl,mh=lp,gh=Cp,vh=Fp,yh=Qp,_h=new Td.Logger("Device");function bh(e,t){return _h.debug("detectDevice()"),e||"object"!=typeof navigator||(e=navigator.userAgent),t||"object"!=typeof navigator||(t=navigator.userAgentData),Sh(e,t)}async function Eh(e,t){return _h.debug("detectDeviceAsync()"),e||"object"!=typeof navigator||(e=navigator.userAgent),t||"object"!=typeof navigator||(t=navigator.userAgentData),Sh(e,t)}class wh{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new dh.EnhancedEventEmitter;static async factory({handlerName:e,handlerFactory:t}={}){if(_h.debug("factory()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!e&&!t&&!(e=await Eh()))throw new uh.UnsupportedError("device not supported");return new wh({handlerName:e,handlerFactory:t})}constructor({handlerName:e,handlerFactory:t}={}){if(_h.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)_h.debug("constructor() | handler given: %s",e);else{if(!(e=bh()))throw new uh.UnsupportedError("device not supported");_h.debug("constructor() | detected handler: %s",e)}switch(e){case"Chrome111":this._handlerFactory=fh.Chrome111.createFactory();break;case"Chrome74":this._handlerFactory=mh.Chrome74.createFactory();break;case"Firefox120":this._handlerFactory=gh.Firefox120.createFactory();break;case"Safari12":this._handlerFactory=vh.Safari12.createFactory();break;case"ReactNative106":this._handlerFactory=yh.ReactNative106.createFactory();break;default:throw new TypeError(`unknown handlerName "${e}"`)}}this._handlerName=this._handlerFactory.name}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){return this.recvRtpCapabilities}get recvRtpCapabilities(){if(!this._loaded)throw new uh.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sendRtpCapabilities(){if(!this._loaded)throw new uh.InvalidStateError("not loaded");return this._sendRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new uh.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e,preferLocalCodecsOrder:t=!1}){if(_h.debug("load() [routerRtpCapabilities:%o]",e),this._loaded)throw new uh.InvalidStateError("already loaded");const r=lh.clone(e);ph.validateAndNormalizeRtpCapabilities(r);const{getNativeRtpCapabilities:n,getNativeSctpCapabilities:i}=this._handlerFactory,s=lh.clone(await n({direction:"recvonly"}));_h.debug("load() | got native receiving RTP capabilities:%o",s),ph.validateAndNormalizeRtpCapabilities(s);const o=lh.clone(await n({direction:"sendonly"}));_h.debug("load() | got native sending RTP capabilities:%o",o),ph.validateAndNormalizeRtpCapabilities(o),this._getSendExtendedRtpCapabilities=e=>lh.clone(ph.getExtendedRtpCapabilities(e,r,t));const a=ph.getExtendedRtpCapabilities(s,r,!1);this._recvRtpCapabilities=ph.getRecvRtpCapabilities(a),_h.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),ph.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities);const c=ph.getExtendedRtpCapabilities(o,r,t);this._sendRtpCapabilities=ph.getSendRtpCapabilities(c),_h.debug("load() | got sending RTP capabilities:%o",this._sendRtpCapabilities),ph.validateAndNormalizeRtpCapabilities(this._sendRtpCapabilities),this._canProduceByKind.audio=ph.canSend("audio",this._sendRtpCapabilities),this._canProduceByKind.video=ph.canSend("video",this._sendRtpCapabilities),this._sctpCapabilities=await i(),ph.validateSctpCapabilities(this._sctpCapabilities),_h.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),_h.debug("load() succeeded"),this._loaded=!0}canProduce(e){if(!this._loaded)throw new uh.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 _h.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 _h.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 uh.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 hh.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 Sh(e,t){_h.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',e,t);const r=function(e,t){if(_h.debug("getChromiumMajorVersion()"),Ch(e,t))return void _h.debug("getChromiumMajorVersion() | this is iOS => undefined");if(Ph())return void _h.debug("getChromiumMajorVersion() | this is React-Native => undefined");if(t){const e=(t.brands??[]).find((e=>"Chromium"===e.brand));if(e){const t=Number(e.version);return _h.debug(`getChromiumMajorVersion() | Chromium major version based on NavigatorUAData => ${t}`),t}}const r=e?.match(/\b(?:Chrome|Chromium)\/(\w+)/i);if(r?.[1]){const e=Number(r[1]);return _h.debug(`getChromiumMajorVersion() | Chromium major version based on User-Agent => ${e}`),e}return void _h.debug("getChromiumMajorVersion() | this is not Chromium => undefined")}(e,t);if(r)return r>=111?(_h.debug("detectDeviceImpl() | using Chrome111 handler"),"Chrome111"):r>=74?(_h.debug("detectDeviceImpl() | using Chrome74 handler"),"Chrome74"):void _h.warn("detectDeviceImpl() | unsupported Chromium based browser/version");const n=function(e){if(_h.debug("getFirefoxMajorVersion()"),Ch(e))return void _h.debug("getFirefoxMajorVersion() | this is iOS => undefined");if(Ph())return void _h.debug("getFirefoxMajorVersion() | this is React-Native => undefined");const t=e?.match(/\bFirefox\/(\w+)/i);if(t?.[1]){const e=Number(t[1]);return _h.debug(`getFirefoxMajorVersion() | Firefox major version based on User-Agent => ${e}`),e}return void _h.debug("getFirefoxMajorVersion() | this is not Firefox => undefined")}(e);if(n)return n>=120?(_h.debug("detectDeviceImpl() | using Firefox120 handler"),"Firefox120"):void _h.warn("detectDeviceImpl() | unsupported Firefox browser/version");const i=function(e){if(_h.debug("getMacOSWebKitMajorVersion()"),Ch(e))return void _h.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");if(Ph())return void _h.debug("getMacOSWebKitMajorVersion() | this is React-Native => undefined");if(!e||!/\bSafari\b/i.test(e)||/\bChrome\b/i.test(e)||/\bChromium\b/i.test(e)||/\bFirefox\b/i.test(e))return void _h.debug("getMacOSWebKitMajorVersion() | this is not Safari => undefined");const t=e.match(/AppleWebKit\/(\w+)/i);if(t?.[1]){const e=Number(t[1]);return _h.debug(`getMacOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${e}`),e}return void _h.debug("getMacOSWebKitMajorVersion() | this is not WebKit => undefined")}(e);if(i)return i>=605?(_h.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12"):void _h.warn("detectDeviceImpl() | unsupported desktop Safari browser/version");const s=function(e){if(_h.debug("getIOSWebKitMajorVersion()"),!Ch(e))return void _h.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");if(Ph())return void _h.debug("getIOSWebKitMajorVersion() | this is React-Native => undefined");const t=e?.match(/AppleWebKit\/(\w+)/i);if(t?.[1]){const e=Number(t[1]);return _h.debug(`getIOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${e}`),e}return void _h.debug("getIOSWebKitMajorVersion() | this is not WebKit => undefined")}(e);return s?s>=605?(_h.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12"):void _h.warn("detectDeviceImpl() | unsupported iOS Safari based browser/version"):Ph()?"undefined"!=typeof RTCPeerConnection&&"undefined"!=typeof RTCRtpTransceiver?(_h.debug("detectDeviceImpl() | using ReactNative106 handler"),"ReactNative106"):void _h.warn("detectDeviceImpl() | unsupported react-native-webrtc version without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?"):void _h.warn('detectDeviceImpl() | device not supported [userAgent:"%s", userAgentData:%o]',e,t)}function Ch(e,t){return _h.debug("isIOS()"),"iOS"===t?.platform?(_h.debug("isIOS() | this is iOS based on NavigatorUAData.platform => true"),!0):t?.platform?(_h.debug("isIOS() | this is not iOS based on NavigatorUAData.platform => false"),!1):e&&/iPad|iPhone|iPod/.test(e)?(_h.debug("isIOS() | this is iOS based on User-Agent => true"),!0):"object"==typeof navigator&&"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1?(_h.debug("isIOS() | this is iPadOS 13+ based on User-Agent => true"),!0):(_h.debug("isIOS() | this is not iOS => false"),!1)}function Ph(){return _h.debug("isReactNative()"),"object"==typeof navigator&&"ReactNative"===navigator.product?(_h.debug("isReactNative() | this is React-Native based on navigator.product"),!0):(_h.debug("isReactNative() | this is not React-Native => false"),!1)}Pd.Device=wh;for(var Th,Rh={},kh={},Dh={},Ih=256,Ah=[];Ih--;)Ah[Ih]=(Ih+256).toString(16).substring(1);Dh.v4=function(){var e,t=0,r="";if(!Th||Ih+16>256){for(Th=Array(t=256);t--;)Th[t]=256*Math.random()|0;t=Ih=0}for(;t<16;t++)e=Th[Ih+t],r+=6==t?Ah[15&e|64]:8==t?Ah[63&e|128]:Ah[e],1&t&&t>1&&t<11&&(r+="-");return Ih++,r};var Oh={};Object.defineProperty(Oh,"__esModule",{value:!0}),Oh.FakeEventTarget=void 0;Oh.FakeEventTarget=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:"function"==typeof t?t:t.handleEvent,once:"object"==typeof r&&!0===r.once}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter((e=>e.callback!==("function"==typeof t?t:t.handleEvent))))}dispatchEvent(e){if(!e||"string"!=typeof e.type)throw new Error("invalid event object");const t=this.listeners[e.type];if(!t)return!0;for(const r of[...t]){try{r.callback.call(this,e)}catch(e){setTimeout((()=>{throw e}),0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}};var Mh={};Object.defineProperty(Mh,"__esModule",{value:!0}),Mh.FakeEvent=void 0;Mh.FakeEvent=class{NONE=0;CAPTURING_PHASE=1;AT_TARGET=2;BUBBLING_PHASE=3;type;bubbles;cancelable;defaultPrevented=!1;composed=!1;currentTarget=null;eventPhase=p.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 Nh={};Object.defineProperty(Nh,"__esModule",{value:!0}),Nh.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(kh,"__esModule",{value:!0}),kh.FakeMediaStreamTrack=void 0;const Lh=Dh,xh=Oh,Fh=Mh,jh=Nh;class Uh extends xh.FakeEventTarget{#b;#E;#w;#S;#C;#P;#T;#R;#k;#D;#I;#A=null;#O=null;#M=null;#N=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,Lh.v4)(),this.#E=e,this.#w=r??"",this.#T=n??"",this.#C=i??!0,this.#P=s??!1,this.#S=o??"live",this.#R=a??{},this.#k=c??{},this.#D=d??{},this.#I=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 Fh.FakeEvent("enabledchange"))}get muted(){return this.#P}get readyState(){return this.#S}get data(){return this.#I}set data(e){this.#I=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.#M}set onended(e){this.#M&&this.removeEventListener("ended",this.#M),this.#M=e,e&&this.addEventListener("ended",e)}get onenabledchange(){return this.#N}set onenabledchange(e){this.#N&&this.removeEventListener("enabledchange",this.#N),this.#N=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 Fh.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new Uh({id:e??(0,Lh.v4)(),kind:this.#E,label:this.#w,contentHint:this.#T,enabled:this.#C,muted:this.#P,readyState:this.#S,capabilities:(0,jh.clone)(this.#R),constraints:(0,jh.clone)(this.#k),settings:(0,jh.clone)(this.#D),data:t??(0,jh.clone)(this.#I)})}getCapabilities(){return this.#R}getConstraints(){return this.#k}async applyConstraints(e={}){return this.#k=e,Promise.resolve()}getSettings(){return this.#D}remoteStop(){"ended"!==this.#S&&(this.#S="ended",this.dispatchEvent(new Fh.FakeEvent("stopped")),this.dispatchEvent(new Fh.FakeEvent("ended")))}remoteMute(){this.#P||(this.#P=!0,this.dispatchEvent(new Fh.FakeEvent("mute")))}remoteUnmute(){this.#P&&(this.#P=!1,this.dispatchEvent(new Fh.FakeEvent("unmute")))}}kh.FakeMediaStreamTrack=Uh;var Vh={};Object.defineProperty(Vh,"__esModule",{value:!0}),Vh.FakeEventTarget=void 0;Vh.FakeEventTarget=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:"function"==typeof t?t:t.handleEvent,once:"object"==typeof r&&!0===r.once}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter((e=>e.callback!==("function"==typeof t?t:t.handleEvent))))}dispatchEvent(e){if(!e||"string"!=typeof e.type)throw new Error("invalid event object");const t=this.listeners[e.type];if(!t)return!0;for(const r of[...t]){try{r.callback.call(this,e)}catch(e){setTimeout((()=>{throw e}),0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}},Object.defineProperty(Rh,"__esModule",{value:!0}),Rh.FakeHandler=void 0;const Bh=kh,Wh=Id,Hh=Zd,qh=Xd,zh=Jd,Gh=Vh,Yh=new Td.Logger("FakeHandler");class $h extends Wh.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${Hh.generateRandomNumber()}`;_defaultSendStreamId=`${Hh.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:"FakeHandler",factory:t=>new $h(t,e),getNativeRtpCapabilities:async({direction:t})=>(Yh.debug("getNativeRtpCapabilities() [direction:%o]",t),$h.getLocalRtpCapabilities(e)),getNativeSctpCapabilities:async()=>(Yh.debug("getNativeSctpCapabilities()"),e.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(e){const t=e.generateNativeRtpCapabilities();return qh.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),Yh.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return"FakeHandler"}close(){Yh.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(),Yh.debug("updateIceServers()")}async restartIce(e){this.assertNotClosed(),Yh.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:e,streamId:t,encodings:r,codecOptions:n,codec:i}){this.assertNotClosed(),Yh.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});const s=$h.getLocalRtpCapabilities(this._fakeParameters),o=this._getSendExtendedRtpCapabilities(s),a=qh.getSendingRtpParameters(e.kind,o);a.codecs=qh.reduceCodecs(a.codecs,i);const c=a.codecs.some((e=>/.+\/rtx$/i.test(e.mimeType)));a.mid=`mid-${Hh.generateRandomNumber()}`,a.msid=`${t??"-"} ${e.id}`,r||(r=[{}]);for(const e of r)e.ssrc=Hh.generateRandomNumber(),c&&(e.rtx={ssrc:Hh.generateRandomNumber()});a.encodings=r,a.rtcp={cname:this._cname,reducedSize:!0,mux:!0},a.msid=`${t??this._defaultSendStreamId} ${e.id}`;const d=this._nextLocalId++;return this._tracks.set(d,e),{localId:String(d),rtpParameters:a}}async stopSending(e){if(Yh.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?Yh.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Yh.debug("replaceTrack() [localId:%s, no track]",e),this._tracks.delete(Number(e)),this._tracks.set(Number(e),t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),Yh.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),Yh.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"}),Yh.debug("sendDataChannel()");return{dataChannel:new Jh({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"}),Yh.debug("receive() [trackId:%s, kind:%s]",e,n);const i=this._nextLocalId++,s=new Bh.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)Yh.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"}),Yh.debug("receiveDataChannel()");return{dataChannel:new Jh({id:e.streamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:t,protocol:r})}}async setupTransport({localDtlsRole:e,localSdpObject:t}){const r=Hh.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 zh.InvalidStateError("method called in a closed handler")}}Rh.FakeHandler=$h;class Jh extends Gh.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(),Yh.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 zh.InvalidStateError("not open")}}var Qh={};Object.defineProperty(Qh,"__esModule",{value:!0}),Qh.generateRouterRtpCapabilities=function(){return Kh.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"}]})},Qh.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}]}},Qh.generateNativeSctpCapabilities=function(){return Kh.deepFreeze({numStreams:{OS:2048,MIS:2048}})},Qh.generateLocalDtlsParameters=function(){return Kh.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"})},Qh.generateTransportRemoteParameters=function(){return{id:Zh(),iceParameters:Kh.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:Kh.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:Kh.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:Kh.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}},Qh.generateProducerRemoteParameters=function(){return Kh.deepFreeze({id:Zh()})},Qh.generateConsumerRemoteParameters=function({id:e,codecMimeType:t}={}){switch(t){case"audio/opus":return{id:e??Zh(),producerId:Zh(),kind:"audio",rtpParameters:Kh.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??Zh(),producerId:Zh(),kind:"audio",rtpParameters:Kh.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??Zh(),producerId:Zh(),kind:"video",rtpParameters:Kh.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??Zh(),producerId:Zh(),kind:"video",rtpParameters:Kh.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}'`)}},Qh.generateDataProducerRemoteParameters=function(){return Kh.deepFreeze({id:Zh()})},Qh.generateDataConsumerRemoteParameters=function({id:e}={}){return{id:e??Zh(),dataProducerId:Zh(),sctpStreamParameters:Kh.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}};const Kh=Zd;function Zh(){return String(Kh.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=gd.exports;e.debug=t.default,e.types=Cd,e.version="3.18.7";var r=Pd;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=xl;Object.defineProperty(e,"parseScalabilityMode",{enumerable:!0,get:function(){return n.parse}}),e.ortc=Xd,e.enhancedEvents=Id;var i=Rh;Object.defineProperty(e,"FakeHandler",{enumerable:!0,get:function(){return i.FakeHandler}}),e.testFakeParameters=Qh}(md);const Xh={width:1280,height:720},ef=0,tf=2,rf=0;function nf(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 sf(e,t){e.onreadystatechange=function(){"complete"!=this.readyState&&"loaded"!=this.readyState||(this.onreadystatechange=null,t(null,e))}}const of=new An,af=e=>c(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?nf:sf)(i,r),i.onload||nf(i,r),n.appendChild(i)}(e,((e,n)=>{e?r(e):t(n)}))}))})),cf=(e,...t)=>c(void 0,[e,...t],void 0,(function*(e,t=3,r=500){let n=0;for(;n<t;)try{return void(yield af(e))}catch(e){if(n+=1,!(n<t))throw e;yield of.sleepMs(r)}}));var df;let uf=class{constructor(){df.set(this,new Map)}add(e,t,r){const n=this.getKey(e,t);if(d(this,df,"f").has(n))throw new Error("Attempt to rewrite cached track processor");d(this,df,"f").set(n,r)}get(e,t){return d(this,df,"f").get(this.getKey(e,t))}has(e,t){return d(this,df,"f").has(this.getKey(e,t))}getKey(e,t){return`${e}:${t}`}reset(){for(const e of d(this,df,"f").values())try{e.stopProcessing(),e.release()}catch(e){}d(this,df,"f").clear()}};var lf,pf;df=new WeakMap,uf=s([ct()],uf);let hf=class{constructor(e,t,r,n){this.config=e,this.processorsCache=t,this.audioTrackProcessorFactory=r,lf.set(this,new Map),pf.set(this,void 0),u(this,pf,n("IntegrationsService"),"f")}init(){const e=this.config.get("denoiser");if("asdk"===e){d(this,pf,"f").info("Start integration of ASDK",{denoiser:e});const t={integrated:!1,initPromise:this.integrateASDK()};d(this,lf,"f").set("asdk",t)}else{d(this,pf,"f").info("Start integration of RNNoise",{denoiser:e});const t={integrated:!1,initPromise:this.integrateRNNoise()};d(this,lf,"f").set("rnnoise",t)}}integrateASDK(){return c(this,void 0,void 0,(function*(){const e=this.config.get("asdk"),r=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 t.URL(n,r).href}yield(n=o,i=s,c(void 0,void 0,void 0,(function*(){try{yield cf(n)}catch(e){if(!i)throw e;yield cf(i)}})))}var n,i;if(!window.atsvb)throw d(this,pf,"f").info("Audio Effects SDK is not loaded, skipping initialization",{case:"initAudioSDK"}),new Error("windows.atsvb is still missing");const s=this.audioTrackProcessorFactory({trackLabel:Ln.Microphone});yield s.init(),this.processorsCache.add("asdk",Ln.Microphone,s);const o=d(this,lf,"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=d(this,lf,"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=d(this,lf,"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 c(this,void 0,void 0,(function*(){const e=yield function(e){return c(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:Ln.Microphone,noiseSuppressor:e});this.processorsCache.add("rnnoise",Ln.Microphone,t);const r=d(this,lf,"f").get("rnnoise");if(!r)throw Error("IntegrationContext is missing for RNNoise");r.integrated=!0}))}reset(){d(this,lf,"f").clear()}};var ff,mf,gf,vf,yf,_f,bf,Ef,wf;lf=new WeakMap,pf=new WeakMap,hf=s([ct(),o(0,ut(Nn.Config)),o(1,ut(Nn.ProcessorsCache)),o(2,ut(Nn.AudioTrackProcessorFactory)),o(3,ut(Nn.LoggerFactory)),a("design:paramtypes",[Et,uf,Function,Function])],hf),function(e){e.INFO="info",e.WARNING="warning",e.ERROR="error"}(Ef||(Ef={})),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"}(wf||(wf={}));class Sf{constructor(e){ff.set(this,void 0),mf.set(this,void 0),gf.set(this,{lowLighter:!1,colorCorrector:!1,faceDetector:!1,segmentation:!1}),vf.set(this,null),yf.set(this,void 0),_f.set(this,!1),bf.set(this,void 0);const{loggerFactory:t}=e;if(u(this,mf,t("EffectsSDKTrackProcessor"),"f"),u(this,bf,e.onModelsLoaded,"f"),!e.customerId)throw new Error("Customer ID must be provided");u(this,ff,new window.tsvb(e.customerId),"f"),d(this,ff,"f").onError(this.tsvbErrorHandler.bind(this)),d(this,ff,"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`}};d(this,ff,"f").config(o)}init(){return c(this,void 0,void 0,(function*(){yield d(this,ff,"f").preload(),yield d(this,ff,"f").cache(),u(this,_f,!0,"f")}))}awaitReady(){return c(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:n}=e,s=i(e,["emitter","type"]),o=null!=r?r:"N/A emitter";n===Ef.ERROR&&d(this,mf,"f").error(o,Object.assign({error:Pt(e)},s)),n===Ef.WARNING&&d(this,mf,"f").warn(o,Object.assign({},s)),n===Ef.INFO&&d(this,mf,"f").info(o,Object.assign({},s)),r===wf.ML_INFERENCE&&(s.message.toLocaleLowerCase().includes("init lowlighter")&&(d(this,gf,"f").lowLighter=!0),s.message.toLocaleLowerCase().includes("init colorcorrector")&&(d(this,gf,"f").colorCorrector=!0),s.message.toLocaleLowerCase().includes("init facedetector")&&(d(this,gf,"f").faceDetector=!0),s.message.toLocaleLowerCase().includes("init segmentation")&&(d(this,gf,"f").segmentation=!0),this.isModelsLoaded&&(null===(t=d(this,bf,"f"))||void 0===t||t.call(this)))}get isModelsLoaded(){return d(this,gf,"f").colorCorrector&&d(this,gf,"f").faceDetector&&d(this,gf,"f").lowLighter&&d(this,gf,"f").segmentation}get modelsLoadProgress(){return Object.values(d(this,gf,"f")).filter(Boolean).length/Object.keys(d(this,gf,"f")).length}get isReady(){return d(this,_f,"f")}setOnLoadModels(e){u(this,bf,e,"f"),this.isModelsLoaded&&d(this,bf,"f").call(this)}onReady(){u(this,_f,!0,"f"),d(this,mf,"f").debug("onReady()",{description:"ESDK is ready"}),this.updateEffects(d(this,yf,"f"))}processTrack(e){var t,r,n;if(d(this,vf,"f")===e||"ended"===e.readyState)return null!==(r=null===(t=d(this,ff,"f").getStream())||void 0===t?void 0:t.getVideoTracks()[0])&&void 0!==r?r:e;this.stopProcessing();try{d(this,ff,"f").useStream(new MediaStream([e]));const t=null===(n=d(this,ff,"f").getStream())||void 0===n?void 0:n.getVideoTracks()[0];return t?(u(this,vf,e,"f"),t):e}catch(t){throw d(this,mf,"f").error("processTrack()",{error:t,track:e}),new Error("Can not process this track")}}stopProcessing(){try{d(this,ff,"f").clear(),d(this,ff,"f").stop()}catch(e){d(this,mf,"f").error("stopProcessing()",{error:e})}finally{u(this,vf,null,"f")}}updateEffects(e){var t,r,n,i,s,o,a,c,l,p,h,f,m,g,v,y,_,b,E,w,S,C;if(u(this,yf,e,"f"),!d(this,_f,"f"))return void d(this,mf,"f").warn("updateEffects()",{description:"Esdk not ready"});if(!d(this,yf,"f")||0===Object.keys(d(this,yf,"f")).length)return void d(this,ff,"f").stop();let P=0;if((null===(t=d(this,yf,"f"))||void 0===t?void 0:t.blur)&&!(null===(r=d(this,yf,"f"))||void 0===r?void 0:r.backgroundColor)?(d(this,ff,"f").setBlur(d(this,yf,"f").blur),P+=1):d(this,ff,"f").clearBlur(),void 0!==(null===(n=d(this,yf,"f"))||void 0===n?void 0:n.background)?(d(this,ff,"f").setBackground(d(this,yf,"f").background),P+=1):void 0!==(null===(i=d(this,yf,"f"))||void 0===i?void 0:i.backgroundColor)?(d(this,ff,"f").setBackgroundColor(null===(s=d(this,yf,"f"))||void 0===s?void 0:s.backgroundColor),d(this,ff,"f").setBackground("color"),P+=1):d(this,ff,"f").clearBackground(),(null===(o=d(this,yf,"f"))||void 0===o?void 0:o.beautification)?(d(this,ff,"f").enableBeautification(),d(this,ff,"f").setBeautificationLevel(d(this,yf,"f").beautification),P+=1):d(this,ff,"f").disableBeautification(),(null===(a=d(this,yf,"f"))||void 0===a?void 0:a.lowLightEffect)?(d(this,ff,"f").enableLowLightEffect(),d(this,ff,"f").setLowLightEffectPower(d(this,yf,"f").lowLightEffect),P+=1):d(this,ff,"f").disableLowLightEffect(),(null===(c=d(this,yf,"f"))||void 0===c?void 0:c.colorCorrector)?(d(this,ff,"f").enableColorCorrector(),d(this,ff,"f").setColorCorrectorPower(d(this,yf,"f").colorCorrector),P+=1):d(this,ff,"f").disableColorCorrector(),(null===(l=d(this,yf,"f"))||void 0===l?void 0:l.smartZoom)?(d(this,ff,"f").enableSmartZoom(),d(this,ff,"f").setFaceArea(d(this,yf,"f").smartZoom),P+=1):d(this,ff,"f").disableSmartZoom(),(null===(p=d(this,yf,"f"))||void 0===p?void 0:p.layout)?(d(this,ff,"f").setLayout(d(this,yf,"f").layout),P+=1):d(this,ff,"f").setLayout("center"),(null===(h=d(this,yf,"f"))||void 0===h?void 0:h.colorFilter)&&(null===(f=d(this,yf,"f"))||void 0===f?void 0:f.colorFilter.power)&&(null===(m=d(this,yf,"f"))||void 0===m?void 0:m.colorFilter.url)?(d(this,ff,"f").setColorFilterConfig({lut:d(this,yf,"f").colorFilter.url,power:d(this,yf,"f").colorFilter.power}),d(this,ff,"f").enableColorFilter(),P+=1):d(this,ff,"f").disableColorFilter(),null===(g=d(this,yf,"f"))||void 0===g?void 0:g.lowerThird){const e=d(this,ff,"f").createComponent({component:d(this,yf,"f").lowerThird.type,options:null!==(v=d(this,yf,"f").lowerThird.options)&&void 0!==v?v:{}});null===(b=null===(_=null===(y=d(this,ff,"f").components)||void 0===y?void 0:y.lowerThird)||void 0===_?void 0:_.hideLowerThird)||void 0===b||b.call(_),d(this,ff,"f").addComponent(e,"lowerThird"),d(this,ff,"f").components.lowerThird.showLowerThird(),P+=1}else null===(S=null===(w=null===(E=d(this,ff,"f").components)||void 0===E?void 0:E.lowerThird)||void 0===w?void 0:w.hideLowerThird)||void 0===S||S.call(w);(null===(C=d(this,yf,"f"))||void 0===C?void 0:C.sharpness)?(d(this,ff,"f").setSharpnessEffectConfig(d(this,yf,"f").sharpness),P+=1):d(this,ff,"f").disableSharpnessEffect(),P>2?d(this,ff,"f").enableFrameSkipping():d(this,ff,"f").disableFrameSkipping(),d(this,ff,"f").run()}}ff=new WeakMap,mf=new WeakMap,gf=new WeakMap,vf=new WeakMap,yf=new WeakMap,_f=new WeakMap,bf=new WeakMap;const Cf=e=>"rtx"!==e.mimeType;let Pf,Tf=!1;const Rf=()=>{try{return Tf?null:window.localStorage}catch(e){return console.error("Get local storage error",{error:Pt(e)}),e instanceof Error&&"SecurityError"===e.name&&(Tf=!0),null}};function kf(e){const t=Rf();if(!t)return null;try{const r=t.getItem(e);return r?JSON.parse(r):null}catch(e){return null}}const Df=()=>{if(Pf)return Pf;const e=kf("sdk_clientUniqueId");if(e)return Pf=e,e;const t=In(12);return Pf=t,function(e,t){const r=Rf();if(r)try{r.setItem(e,JSON.stringify(t))}catch(e){console.error(e)}}("sdk_clientUniqueId",t),t},If=()=>{const e=kf("sdk_clientUniqueId");return e||(null!=Pf?Pf:Df())};var Af,Of,Mf;class Nf{constructor({track:e}){Af.set(this,1e4),Of.set(this,0),Mf.set(this,void 0),this.startCleanupTimer(),e.addEventListener("ended",(()=>{clearInterval(d(this,Mf,"f")),u(this,Mf,void 0,"f")}),{once:!0})}touchLastReceivedStatsTimestamp(){u(this,Of,Date.now(),"f")}startCleanupTimer(){u(this,Mf,setInterval((()=>{d(this,Of,"f")>0&&Date.now()-d(this,Of,"f")>=d(this,Af,"f")&&this.cleanupStats()}),d(this,Af,"f")),"f")}}var Lf,xf,Ff,jf,Uf,Vf,Bf,Wf,Hf,qf,zf,Gf,Yf,$f,Jf,Qf,Kf,Zf,Xf,em,tm,rm,nm;Af=new WeakMap,Of=new WeakMap,Mf=new WeakMap;class im extends Nf{constructor({track:e,statsHandler:t,widStatsAdapter:r,scoresCalculator:n,isStaticContent:i}){super({track:e}),Lf.set(this,void 0),xf.set(this,void 0),Ff.set(this,void 0),jf.set(this,void 0),Uf.set(this,void 0),Vf.set(this,void 0),Bf.set(this,void 0),this.handleWebRTCStats(e,t),u(this,Vf,r,"f"),u(this,Uf,n,"f"),u(this,Bf,i,"f")}get videoWebRTCStats(){var e,t,r,n,i;return null!==(r=null===(t=null===(e=d(this,Lf,"f"))||void 0===e?void 0:e.find((e=>e.outbound.active)))||void 0===t?void 0:t.outbound)&&void 0!==r?r:null===(i=null===(n=d(this,Lf,"f"))||void 0===n?void 0:n[0])||void 0===i?void 0:i.outbound}get audioWebRTCStats(){var e;return null===(e=d(this,xf,"f"))||void 0===e?void 0:e.outbound}get scores(){return{Qv:d(this,Ff,"f"),Qa:d(this,jf,"f")}}handleWebRTCStats(e,t){e.addEventListener("ended",(()=>{t.removeOutboundVideoHandler(e.id),t.removeOutboundAudioHandler(e.id)}),{once:!0}),"video"!==e.kind?t.addOutboundAudioHandler(e.id,this.setAudioWebRTCStats.bind(this)):t.addOutboundVideoHandler(e.id,this.setVideoWebRTCStats.bind(this))}setVideoWebRTCStats(e){this.touchLastReceivedStatsTimestamp();const t=e.filter((e=>e.outbound.active)),r=[];t.forEach((e=>{var t;const n=null===(t=d(this,Lf,"f"))||void 0===t?void 0:t.find((t=>t.outbound.ssrc===e.outbound.ssrc)),i=d(this,Vf,"f").adaptOutboundVideoStats({stats:e.outbound,remoteInboundStats:e.remoteInbound,prevStats:n,isStaticContent:d(this,Bf,"f")});r.push(d(this,Uf,"f").calculateVideoMOS(i))})),u(this,Ff,r.length>0?Math.min(...r):void 0,"f"),u(this,Lf,e,"f")}setAudioWebRTCStats(e){var t,r;this.touchLastReceivedStatsTimestamp();const n=d(this,xf,"f")?{outbound:d(this,xf,"f").outbound,remoteInbound:d(this,xf,"f").remoteInbound}:void 0,i=d(this,Vf,"f").adaptOutboundAudioStats({stats:e.outbound,remoteInboundStats:e.remoteInbound,fec:null===(t=kf("qosOutboundFec"))||void 0===t||t,dtx:null===(r=kf("qosOutboundDtx"))||void 0===r||r,prevStats:n});u(this,jf,d(this,Uf,"f").calculateAudioMOS(i),"f"),u(this,xf,e,"f")}cleanupStats(){u(this,Lf,void 0,"f"),u(this,xf,void 0,"f"),u(this,Ff,void 0,"f"),u(this,jf,void 0,"f")}}Lf=new WeakMap,xf=new WeakMap,Ff=new WeakMap,jf=new WeakMap,Uf=new WeakMap,Vf=new WeakMap,Bf=new WeakMap;class sm{constructor(e){Wf.set(this,void 0),Hf.set(this,void 0),this.encoderConfig={},this.label=Ln.Unknown,qf.set(this,void 0),zf.set(this,void 0),Gf.set(this,void 0),Yf.set(this,void 0),$f.set(this,void 0),Jf.set(this,void 0),Qf.set(this,void 0),Kf.set(this,void 0),Zf.set(this,!0),Xf.set(this,void 0),em.set(this,void 0),tm.set(this,void 0),rm.set(this,void 0),nm.set(this,void 0);const{mediaStreamTrack:t,internalEventEmitter:r,constraints:n,mediaStreamTrackManager:i,media:s,myPeer:o,network:a,producerCloseManager:c,mutex:d,loggerFactory:l,loggerNamespace:p,statsHandler:h,widStatsAdapter:f,scoresCalculator:m}=e;u(this,Wf,t,"f"),u(this,$f,r,"f"),u(this,Jf,n,"f"),u(this,Qf,i,"f"),u(this,Kf,new wt,"f"),this.logger=l(p),u(this,Xf,d,"f"),u(this,zf,s,"f"),u(this,qf,o,"f"),u(this,Gf,a,"f"),u(this,Yf,c,"f"),u(this,tm,h,"f"),u(this,rm,f,"f"),u(this,nm,m,"f"),u(this,em,new im({track:t,statsHandler:h,widStatsAdapter:f,scoresCalculator:m}),"f")}get videoWebRTCStats(){return d(this,em,"f").videoWebRTCStats}get audioWebRTCStats(){return d(this,em,"f").audioWebRTCStats}get connectionScores(){return d(this,em,"f").scores}get logCtx(){return{label:this.getLabel(),id:this.id,kind:this.kind,producerId:this.producerId,paused:this.isPaused,published:this.isPublished}}get observer(){return d(this,Kf,"f")}get mediaStreamTrack(){return d(this,Wf,"f")}get originalTrack(){return d(this,Hf,"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 d(this,$f,"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||u(this,Zf,e,"f")}getProducer(){return this.producer}setOriginalTrack(){u(this,Hf,this.mediaStreamTrack,"f")}closeProducer(){return c(this,arguments,void 0,(function*(e=!0){const t=yield d(this,Xf,"f").lock(gn.CloseProducer);if(!this.producer)return void t();const{producerId:r}=this;r&&(yield d(this,Yf,"f").close(this.getLabel(),r)),this.producer.close(),this.producer=void 0,e&&this.stopMediaStreamTrack(),t()}))}setPriority(e){return c(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(){d(this,Hf,"f")&&(d(this,Hf,"f").stop(),u(this,Hf,void 0,"f"))}produce(e){return c(this,arguments,void 0,(function*({encodings:e,codecOptions:t,preferredCodec:r,transformParams:n,keyFrameRequestDelay:i}){var s,o,a,c,u;if(!d(this,qf,"f").canPublish)throw this.logger.error("produce()",{message:"Not enough access to produce"}),new Tt("not_enough_access",new Error("Not enough access to produce"));if(this.producer)throw new Tt("track_already_produced",new Error("Track already produced"));try{yield d(this,Yf,"f").ensureNoPending(this.getLabel()),yield d(this,Gf,"f").ping();const{rtpCapabilities:{codecs:l}}=d(this,zf,"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(d(this,qf,"f").id),label:this.getLabel(),maxSpatialLayer:h,encodings:f,codecOptions:t,preferredCodec:r,codec:p,keyFrameRequestDelay:i},g=yield null===(s=d(this,Gf,"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)!==d(this,Wf,"f").id&&(this.logger.info("Producer initialized with old track, updating",{oldTrackId:null===(u=null===(c=this.producer)||void 0===c?void 0:c.track)||void 0===u?void 0:u.id,newTrackId:d(this,Wf,"f").id}),yield this.replaceTrack(d(this,Wf,"f"))),"video"===this.kind&&(e&&v&&p&&kn(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 d(this,Gf,"f").setProducerMaxSpatialLayer(g.id,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 Tt("track_publish_failed",e)}}))}publish(){return c(this,void 0,void 0,(function*(){yield this.produce({}),this.internalEventEmitter.emit(Vr,this)}))}unpublish(){return c(this,arguments,void 0,(function*(e=!0){try{e&&this.stopMediaStreamTrack(),this.internalEventEmitter.emit(Br,this),this.producer&&(yield this.closeProducer()),this.logger.debug("unpublish()",{track:this.logCtx})}catch(e){this.logger.error("unpublish()",{error:e})}}))}pauseRemoteProducer(e){return c(this,void 0,void 0,(function*(){yield d(this,Gf,"f").pauseRemoteProducer(e)}))}resumeRemoteProducer(e){return c(this,void 0,void 0,(function*(){yield d(this,Gf,"f").resumeRemoteProducer(e)}))}mute(e){return c(this,void 0,void 0,(function*(){const t=yield d(this,Xf,"f").lock(gn.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}),d(this,Zf,"f"))return null==e||e(),d(this,Wf,"f").stop(),this.stopOriginalTrack(),this.internalEventEmitter.emit(qr,this),void(yield this.pauseRemoteProducer(this.producer.id));yield this.pauseRemoteProducer(this.producer.id),this.internalEventEmitter.emit(Wr,this)}catch(e){throw this.logger.error("pause()",{error:e,track:this.logCtx}),yield d(this,zf,"f").deleteTrack(this),this.internalEventEmitter.emit(Gr,this),new Tt("track_pause_failed",e)}finally{t()}}))}resume(){return c(this,void 0,void 0,(function*(){const e=yield d(this,Xf,"f").lock(gn.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}),d(this,Zf,"f"))return yield this.reopenMediaStreamTrack(),yield this.resumeProducer(),void this.internalEventEmitter.emit(zr,this);yield this.resumeProducer(),this.internalEventEmitter.emit(Hr,this)}catch(e){throw this.logger.error("resume()",{error:e,track:this.logCtx}),new Tt("track_resume_failed",e)}finally{e()}}))}getInfo(){return c(this,void 0,void 0,(function*(){const{width:e,height:t,frameRate:r,aspectRatio:n}=d(this,Wf,"f").getSettings();return{trackId:d(this,Wf,"f").id,readyState:d(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 c(this,void 0,void 0,(function*(){var e,t,r,n,i;try{return{producerId:null===(e=this.producer)||void 0===e?void 0:e.id,codec:null===(t=this.producer)||void 0===t?void 0:t.rtpParameters.codecs.find((e=>Cf(e))),dtlsState:null===(i=null===(n=null===(r=this.producer)||void 0===r?void 0:r.rtpSender)||void 0===n?void 0:n.transport)||void 0===i?void 0:i.state,rtcStats:yield this.getOutboundRTPStreamStats()}}catch(e){return void this.logger.debug("getStats()",{error:e})}}))}replaceTrack(e){return c(this,void 0,void 0,(function*(){var t;try{u(this,Wf,e,"f"),this.internalEventEmitter.emit(zr,this),this.observer.safeEmit("track-changed",{track:e}),yield null===(t=this.producer)||void 0===t?void 0:t.replaceTrack({track:e}),u(this,em,new im({track:e,statsHandler:d(this,tm,"f"),widStatsAdapter:d(this,rm,"f"),scoresCalculator:d(this,nm,"f")}),"f")}catch(e){this.logger.warn("replaceTrack()",{error:e})}}))}resumeProducer(){return c(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 c(this,void 0,void 0,(function*(){var e;const t=yield d(this,Qf,"f").createMediaStreamTrack({label:this.label,constraints:d(this,Jf,"f")});u(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&&kn(r.mimeType)?[t[n]||t[0]]:t}getOutboundRTPStreamStats(){return c(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>{const r=(...n)=>c(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((()=>c(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:Pt(e)})}))}))}))}}var om,am,cm,dm;Wf=new WeakMap,Hf=new WeakMap,qf=new WeakMap,zf=new WeakMap,Gf=new WeakMap,Yf=new WeakMap,$f=new WeakMap,Jf=new WeakMap,Qf=new WeakMap,Kf=new WeakMap,Zf=new WeakMap,Xf=new WeakMap,em=new WeakMap,tm=new WeakMap,rm=new WeakMap,nm=new WeakMap;class um extends sm{constructor(e){super(e),this.transformParams={},om.set(this,void 0),am.set(this,void 0),cm.set(this,!1),dm.set(this,(()=>{})),u(this,am,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(d(this,om,"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()===Ln.ScreenVideo?"vp8":"h264")}getEncodings(){var e;return null!==(e=this.getEncoderConfig().encodings)&&void 0!==e?e:Rc}setTransformParams(e){this.transformParams=e}setMaxSpatialLayer(e){return c(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 c(this,void 0,void 0,(function*(){if(!d(this,cm,"f")){u(this,cm,!0,"f");try{if(d(this,om,"f"))return this.logger.debug("enableEffects()",{description:"Track is already processed"}),void u(this,cm,!1,"f");if("ended"===this.mediaStreamTrack.readyState)return void this.logger.warn("Track already ended",{case:"enableEffects"});const{media:e}=d(this,am,"f");if(!e.effectsSDKInitialized)return void this.logger.warn("Effects SDK not initialized",{case:"enableEffects"});const t=Date.now();u(this,om,yield e.createEffectsSDKTrackProcessor(this.getLabel()),"f"),this.setOriginalTrack();const r=d(this,om,"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:Pt(e)}),this.disableEffects().catch((e=>{this.logger.warn("Failed to this.disableEffects() in catch{}",{track:this.logCtx,error:Pt(e)})})),d(this,dm,"f").call(this,e)}finally{u(this,cm,!1,"f")}}}))}disableEffects(){return c(this,arguments,void 0,(function*(e=!0){var t;try{if(!d(this,om,"f"))return void this.logger.debug("disableEffects()",{description:"Track is not processed"});if(null===(t=d(this,om,"f"))||void 0===t||t.stopProcessing(),u(this,om,void 0,"f"),this.logger.info("disableEffects()",{track:this.logCtx}),!e)return;if(!this.originalTrack)return void this.logger.warn("disableEffects()",{description:"Original track missing"});yield this.replaceTrack(this.originalTrack)}catch(e){this.logger.warn("disableEffects()",{track:this.logCtx,error:e})}}))}publish(){return c(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(Vr,this)}))}adjustEncodingPresetToCurrentMaxSpatialLayer(e){return c(this,void 0,void 0,(function*(){var t;if(!kn(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 c(this,void 0,void 0,(function*(){var t;try{!this.isEffectsProcessing&&Object.keys(e).length>0&&(yield this.enableEffects()),null===(t=d(this,om,"f"))||void 0===t||t.updateEffects(e)}catch(e){d(this,dm,"f").call(this,e)}}))}resetEffects(){var e;null===(e=d(this,om,"f"))||void 0===e||e.updateEffects({})}setOnLoadModels(e){var t;null===(t=d(this,om,"f"))||void 0===t||t.setOnLoadModels(e)}get modelsLoadProgress(){var e,t;return null!==(t=null===(e=d(this,om,"f"))||void 0===e?void 0:e.modelsLoadProgress)&&void 0!==t?t:0}pause(){return c(this,void 0,void 0,(function*(){yield this.mute((()=>{var e;d(this,om,"f")&&(null===(e=d(this,om,"f"))||void 0===e||e.stopProcessing(),u(this,om,void 0,"f"))}))}))}setOnEffectError(e){u(this,dm,e,"f")}}var lm,pm;om=new WeakMap,am=new WeakMap,cm=new WeakMap,dm=new WeakMap;let hm=pm=class{constructor(e){lm.set(this,void 0),u(this,lm,e("MediaStreamTrackManager"),"f")}createMediaStreamTrack(e){return c(this,arguments,void 0,(function*({label:e,constraints:t}){if(pm.isDisplayMedia(e)){const[e]=yield this.createDisplayMediaTracks(t);return e}const[r]=yield this.createUserMediaTracks(t);return r}))}static isDisplayMedia(e){return[Ln.ScreenVideo,Ln.ScreenAudio].includes(e)}createUserMediaTracks(e){return c(this,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.getUserMedia(e);return d(this,lm,"f").debug("createUserMediaTracks() stream created",{streamId:t.id}),t.getTracks()}))}createDisplayMediaTracks(e){return c(this,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.getDisplayMedia(e);return d(this,lm,"f").debug("getDisplayMediaTracks() stream created",{streamId:t.id}),t.getTracks()}))}};lm=new WeakMap,hm=pm=s([ct(),o(0,ut(Nn.LoggerFactory)),a("design:paramtypes",[Function])],hm);var fm,mm,gm,vm,ym,_m,bm,Em=hm;let wm=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.signalingApiClient=c,this.isDeviceLoaded=!1,this.tracks=new Map,fm.set(this,void 0),mm.set(this,null),gm.set(this,!1),vm.set(this,new Map),ym.set(this,!1),_m.set(this,!1),bm.set(this,void 0);const d=this.config.get("effectsSDKParams");u(this,bm,this.config.get("denoiser"),"f"),u(this,fm,this.loggerFactory("Media"),"f"),u(this,mm,null!=d?d:null,"f")}get mediasoupDevice(){var e;return null!==(e=this.device)&&void 0!==e||(this.device=this.createDevice()),this.device}get effectsSDKInitialized(){return d(this,gm,"f")}get effectsSDKParams(){return d(this,mm,"f")}getTrack(e){return this.tracks.get(e)}loadDevice(e){return c(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()}`));d(this,fm,"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"})),d(this,fm,"f").debug("createTrack() track created",{trackId:n.id,kind:n.kind}),n}))}createUserMediaTracks(e){return c(this,void 0,void 0,(function*(){const t=yield this.mediaStreamTrackManager.createUserMediaTracks(e);return this.createTracks({constraints:e,mediaStreamTracks:t})}))}createDisplayMediaTracks(e){return c(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 c(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(!1))}catch(e){d(this,fm,"f").warn("deleteTrack()",Object.assign({error:e},t))}try{this.tracks.delete(e.getLabel()),e.stopMediaStreamTrack(),yield e.closeProducer()}catch(e){d(this,fm,"f").error("deleteTrack()",{error:e})}finally{d(this,fm,"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){d(this,fm,"f").warn("clearTracks()",{error:e})}finally{this.tracks.clear()}}unpublishTracks(){return c(this,void 0,void 0,(function*(){try{yield Promise.all(this.publishedTracks().map((e=>c(this,void 0,void 0,(function*(){return yield e.unpublish(!1)})))))}catch(e){d(this,fm,"f").warn("unpublishTracks()",{error:e})}}))}setTrack(e){this.tracks.set(e.getLabel(),e)}initEffectsSDK(){return c(this,void 0,void 0,(function*(){if(d(this,gm,"f"))return!0;if(!d(this,mm,"f"))throw d(this,fm,"f").error("Effects SDK config params not provided",{case:"initEffectsSDK"}),new Tt("effects_sdk_config_missing",new Error("Effects SDK config not provided"));const e=(e,t)=>c(this,void 0,void 0,(function*(){if(!window.tsvb)return d(this,fm,"f").info("Effects SDK not loaded, skipping initialization",{case:"initEffectsSDK"}),void e(!1);d(this,fm,"f").info("Effects SDK initializing",{case:"initEffectsSDK"});try{d(this,vm,"f").set(Ln.Camera,yield this.createEffectsSDKTrackProcessor(Ln.Camera)),d(this,vm,"f").set(Ln.CameraPreview,yield this.createEffectsSDKTrackProcessor(Ln.CameraPreview)),u(this,gm,!0,"f"),d(this,fm,"f").info("Effects SDK initialized",{case:"initEffectsSDK"}),e(!0)}catch(e){d(this,fm,"f").error("Failed to initialize Effects SDK",{error:e,case:"initEffectsSDK"}),t(e)}}));return yield new Promise(((t,r)=>{if(!window.tsvb)return d(this,fm,"f").info("Effects SDK tsvb-web.js is not ready, waiting",{case:"initEffectsSDK"}),void window.addEventListener("load",(()=>c(this,void 0,void 0,(function*(){return yield e(t,r)}))));e(t,r).catch((e=>{d(this,fm,"f").error("Failed to execute init() in initEffectsSDK",{error:Pt(e)})}))}))}))}initDenoiser(e,t){return c(this,void 0,void 0,(function*(){if(!d(this,ym,"f"))try{u(this,ym,!0,"f"),this.clientEventEmitter.emit(Mr,!0);try{yield this.integrationsService.audio.waitForInitialization}catch(e){"asdk"===d(this,bm,"f")&&(u(this,_m,!0,"f"),u(this,bm,"rnnoise","f"),this.config.set("denoiser",d(this,bm,"f")),d(this,fm,"f").debug("Set config to rnnoise denoiser",{case:"Denoiser",error:Pt(e),type:this.config.get("denoiser")}),this.clientEventEmitter.emit(Fr),this.integrationsService.init(),yield this.integrationsService.audio.waitForInitialization)}d(this,fm,"f").debug("Denoiser initialized, activating",{case:"Denoiser",type:this.integrationsService.audio.type,trackLabel:e.getLabel()});const r=e,n=this.processorsCache.get(d(this,bm,"f"),Ln.Microphone);if(!n)return void d(this,fm,"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(Mr,!0),this.fallbackToRNoise(e,{reason:r,options:t,error:n}).catch((t=>{d(this,fm,"f").error("Failed to fallback to RNNoise through onError",{case:"Denoiser",type:d(this,bm,"f"),error:Pt(t),label:e.getLabel()})})).then((()=>{this.clientEventEmitter.emit(Mr,!1)})).catch((()=>{}))})),r.setTrackProcessor(n),d(this,fm,"f").debug("Denoiser trackProcessor set, check if activation is needed",{case:"Denoiser",type:d(this,bm,"f"),shouldEnableDenoiser:null==t?void 0:t.noiseSuppression,trackLabel:e.getLabel()}),(null==t?void 0:t.noiseSuppression)&&(yield e.enableNoiseSuppression())}catch(r){if(d(this,fm,"f").warn("Failed to start noise suppression, featured original track",{case:"Denoiser",type:d(this,bm,"f"),error:Pt(r),label:e.getLabel()}),"asdk"===d(this,bm,"f"))try{d(this,fm,"f").warn("Fallback to RNNoise",{error:Pt(r)}),yield this.fallbackToRNoise(e,{options:t,reason:"ASDK init error",error:r})}catch(t){d(this,fm,"f").error("Failed to fallback to RNNoise through catch",{case:"Denoiser",type:d(this,bm,"f"),error:Pt(t),label:e.getLabel()})}}finally{this.clientEventEmitter.emit(Mr,!1),u(this,ym,!1,"f")}}))}fallbackToRNoise(e,t){return c(this,void 0,void 0,(function*(){var r;if(d(this,_m,"f"))return;if(u(this,_m,!0,"f"),"rnnoise"===d(this,bm,"f"))return;this.clientEventEmitter.emit(Fr),d(this,fm,"f").info("Fallback to RNNoise",{reason:null==t?void 0:t.reason,error:Pt(null==t?void 0:t.error),case:"Denoiser"});const n=e;yield n.disableNoiseSuppression(),n.unsetTrackProcessor(),u(this,bm,"rnnoise","f"),this.config.set("denoiser",d(this,bm,"f")),d(this,fm,"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(d(this,bm,"f"),Ln.Microphone);i?(n.setTrackProcessor(i),(null===(r=null==t?void 0:t.options)||void 0===r?void 0:r.noiseSuppression)&&(yield n.enableNoiseSuppression())):d(this,fm,"f").error("No cached trackProcessor found",{case:"Denoiser",trackLabel:e.getLabel(),type:this.integrationsService.audio.type})}))}createEffectsSDKTrackProcessor(e){return c(this,void 0,void 0,(function*(){var t,r,n;if(e){const t=d(this,vm,"f").get(e);if(t)return t}if(!d(this,mm,"f"))throw d(this,fm,"f").error("Effects SDK config params not provided",{case:"initEffectsSDK"}),new Tt("effects_sdk_config_missing",new Error("Effects SDK config not provided"));const i=new Sf({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(),d(this,fm,"f").info("Track effects processor initialized",{trackLabel:e}),i}))}handleProducerSetMaxSpatialLayer(e){return c(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 d(this,fm,"f").warn("producerRequestMaxSpatialLayer()",{message:"Producer not found"});if(!(r instanceof um))return void d(this,fm,"f").warn("producerRequestMaxSpatialLayer()",{message:"Wrong producer kind"});const n=null!=t?t:ef,i=r.getMaxSpatialLayer();i!==n?(r.getEncodings().length>1&&(yield r.setMaxSpatialLayer(n)),yield this.signalingApiClient.producer.setProducerMaxSpatialLayer(e,{maxSpatialLayer:n}),yield r.adjustEncodingPresetToCurrentMaxSpatialLayer(n)):d(this,fm,"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:Xh.width,height:null!==(r=n.height)&&void 0!==r?r:Xh.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:Xh.width},height:{max:Xh.height}},encoderConfig:null!==(r=null==e?void 0:e.videoEncoderConfig)&&void 0!==r?r:{encodings:kc}}}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:Xh.width},height:{max:Xh.height}},encoderConfig:null!==(r=null==e?void 0:e.encoderConfig)&&void 0!==r?r:{encodings:Rc}}}createDevice(){this.normalizeUserAgentBrands();const e=(e=>{const t=null!=e?e:null===navigator||void 0===navigator?void 0:navigator.userAgent;if(!t)return;const r=wn.getParser(t);return r.satisfies({"yandex browser":">=25"})&&"iOS"===r.getOSName()?void 0:r.satisfies({"yandex browser":">=23.7"})?"Chrome111":r.satisfies({"yandex browser":">=22"})?"Chrome74":r.satisfies({"Samsung Internet for Android":">=17"})?"Chrome111":void 0})();return d(this,fm,"f").debug("Creating a media device",{handlerName:null!=e?e:"not specified"}),new md.Device({handlerName:e})}normalizeUserAgentBrands(){const{normalized:e,error:t}=(()=>{const e="undefined"!=typeof navigator?navigator.userAgentData:void 0;if(!(null==e?void 0:e.brands)||Array.isArray(e.brands))return{normalized:!1};try{return e.brands=Array.from(e.brands),{normalized:!0}}catch(t){return e.brands=[],{normalized:!0,error:t}}})();t?d(this,fm,"f").warn("Tried to reform brands property in navigator, but failed",{error:Pt(t)}):e&&d(this,fm,"f").info("Reform brands property in navigator",{})}};fm=new WeakMap,mm=new WeakMap,gm=new WeakMap,vm=new WeakMap,ym=new WeakMap,_m=new WeakMap,bm=new WeakMap,wm=s([ct(),o(0,ut(Nn.Config)),o(1,ut(Nn.LoggerFactory)),o(2,ut(Nn.AudioTrackFactory)),o(3,ut(Nn.ClientEventEmitter)),o(4,ut(Nn.IntegrationsService)),o(5,ut(Nn.ProcessorsCache)),o(6,ut(Nn.VideoTrackFactory)),o(7,ut(Nn.MediaStreamTrackManager)),o(8,ut(Nn.SignalingApiClient)),a("design:paramtypes",[Et,Function,Function,wt,hf,uf,Function,Em,bc])],wm);var Sm=wm;const Cm={[Di.PRODUCER_KIND_VIDEO]:"video",[Di.PRODUCER_KIND_AUDIO]:"audio"},Pm={[Mi.PEER_ROLE_HOST]:"host",[Mi.PEER_ROLE_AUDIENCE]:"audience"},Tm={[bi.PRODUCER_LABEL_CAMERA]:Ln.Camera,[bi.PRODUCER_LABEL_MICROPHONE]:Ln.Microphone,[bi.PRODUCER_LABEL_SCREEN_VIDEO]:Ln.ScreenVideo,[bi.PRODUCER_LABEL_SCREEN_AUDIO]:Ln.ScreenAudio,[bi.PRODUCER_LABEL_CUSTOM_VIDEO]:Ln.CustomVideo,[bi.PRODUCER_LABEL_CUSTOM_AUDIO]:Ln.CustomAudio,[bi.PRODUCER_LABEL_UNKNOWN]:Ln.Unknown,[bi.PRODUCER_LABEL_UNSPECIFIED]:Ln.Unknown},Rm={[_i.PEER_GROUP_MODERATOR]:"moderator",[_i.PEER_GROUP_USER]:"user"},km=e=>{const t=Cm[e];if(!t)throw new Error(`Unknown producer kind: ${e}`);return t},Dm=e=>{const t=Rm[e];if(!t)throw new Error(`Unknown peer group: ${e}`);return t},Im=e=>{const t=Tm[e];if(!t)throw new Error(`Unknown producer label: ${e}`);return t},Am=e=>{const t=Pm[e];if(!t)throw new Error(`Unknown peer role: ${e}`);return t},Om=e=>({id:e.id,channelIds:e.channelIds,groups:e.groups.map(Dm),producePermissions:e.producePermissions.map(Im),appId:e.appId,producers:e.producers.map(Mm),uid:e.uid,appData:e.appData,role:Am(e.role),loginDate:e.loginDate}),Mm=e=>{var t;return{id:e.id,kind:km(e.kind),label:Im(e.label),peerId:e.peerId,paused:e.paused,encodings:e.encodings,maxSpatialLayer:null!==(t=e.maxSpatialLayer)&&void 0!==t?t:0}},Nm=e=>{switch(e){case"moderator":return _i.PEER_GROUP_MODERATOR;case"user":return _i.PEER_GROUP_USER;default:return _i.PEER_GROUP_UNSPECIFIED}};var Lm;let xm=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,Lm.set(this,void 0),u(this,Lm,o("ChannelStateSyncEventHandler"),"f"),this.debouncedTriggerChannelStateEvent=Pn(this.triggerChannelStateEvent.bind(this),3e3),this.watchNetworkState()}handleChannelStateEvent(e){return c(this,void 0,void 0,(function*(){this.network.peersLoaded?yield this.restoreState(e):this.loadChannelState(e),this.clientEventEmitter.emit(Nr)}))}watchNetworkState(){this.clientEventEmitter.on(Or,(()=>{this.debouncedTriggerChannelStateEvent()}))}triggerChannelStateEvent(){return c(this,void 0,void 0,(function*(){const e=()=>c(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>c(this,void 0,void 0,(function*(){const r=yield this.network.triggerChannelStateEvent("host"),n=setTimeout((()=>{this.eventsQueue.isMessageReceived(r)?(d(this,Lm,"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(Ar,i),e()};this.clientEventEmitter.on(Ar,i)}))))}));try{yield Mn(e,{maxRetries:5,actionName:"triggerChannelStateEventWithRetry",logger:d(this,Lm,"f")})}catch(e){d(this,Lm,"f").warn("Failed to trigger channel state event",{case:"ChannelStateSynchronizer.triggerChannelStateEvent",error:Pt(e)})}}))}loadChannelState(e){d(this,Lm,"f").info("Loading channel state",{case:"loadChannelState"});try{const t=this.peers.hosts().map((e=>e.shortData)),r=e.peers.filter((e=>e.role===Mi.PEER_ROLE_HOST));this.setMissingPeers(t,r),this.restoreLocalPeersState(r),this.network.peersLoaded=!0}catch(e){d(this,Lm,"f").error("Failed to load channel state",{case:"loadState",error:Pt(e)})}}restoreState(e){return c(this,void 0,void 0,(function*(){const{peers:t}=e,r={missingPeers:[],removedPeers:[],missingProducers:[],removedProducers:[],fixedProducersState:[],fixedConsumersState:[],restoredAppDataPeers:[]};try{if(!this.network.isNetworkActive)return d(this,Lm,"f").info("Connection inactive, skipping restore local state",{case:"restoreLocalState"}),r;d(this,Lm,"f").info("Restoring local state",{case:"restoreLocalState"});const e=this.peers.hosts().map((e=>e.shortData)),n=t.filter((e=>e.role===Mi.PEER_ROLE_HOST)),{removedProducers:i,fixedProducersState:s}=yield this.restoreRemoteProducersState(n);r.fixedProducersState.push(...s),r.removedProducers.push(...i),r.removedPeers.push(...this.removeUnnecessaryPeers(e,n)),r.missingPeers.push(...this.setMissingPeers(e,n));const o=this.restoreLocalPeersState(n);return r.missingProducers.push(...o.missingProducers),r.removedProducers.push(...o.removedProducers),r.restoredAppDataPeers.push(...o.restoredAppDataPeers),r.fixedProducersState.push(...o.fixedProducersState),r.fixedConsumersState.push(...o.fixedConsumersState),r}catch(e){return d(this,Lm,"f").info("Failed to restore local state",{case:"restoreLocalState",error:Pt(e)}),r}}))}restoreRemoteProducersState(e){return c(this,void 0,void 0,(function*(){const t={removedProducers:[],fixedProducersState:[]},r=this.myPeer.get(),n=e.find((e=>e.id===this.myPeer.id));if(!r||!n)return t;const i=new Map;this.media.getAllTracks().forEach((e=>{e.producerId&&i.set(e.producerId,e)}));const s=new Set(i.keys()),o=n.producers.filter((e=>!s.has(e.id)));yield Promise.all(o.map((e=>c(this,void 0,void 0,(function*(){yield this.network.closeRemoteProducer(e.id),r.producers.delete(e.id),t.removedProducers.push(e.id),d(this,Lm,"f").info("Unnecessary local producer closed",{case:"restoreLocalState",removedProducerId:e.id,removedProducerPeerId:e.peerId})})))));const a=[];for(const e of n.producers){const t=i.get(e.id);t&&(t.isPaused!==e.paused&&a.push({cp:e,localTrack:t}))}return yield Promise.all(a.map((e=>c(this,[e],void 0,(function*({cp:e,localTrack:r}){r.isPaused?yield this.network.pauseRemoteProducer(e.id):yield this.network.resumeRemoteProducer(e.id),t.fixedProducersState.push(e.id),e.paused=r.isPaused,d(this,Lm,"f").info("Remote producer state repaired",{case:"restoreLocalState",removedProducerId:e.id,removedProducerPeerId:e.peerId,paused:r.isPaused})}))))),t}))}removeUnnecessaryPeers(e,t){const r=[];return e.filter((e=>!t.find((t=>t.id===e.id)))).forEach((e=>{this.peers.remove(e.id).catch((e=>{d(this,Lm,"f").error("Failed to remove peer",{error:Pt(e)})})),r.push(e.id),d(this,Lm,"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(Om(t));r.push(n.id),d(this,Lm,"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 d(this,Lm,"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)})),d(this,Lm,"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(an,t),r.push(t.id),d(this,Lm,"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(on,Mm(t)),r.missingProducers.push(t.id),void d(this,Lm,"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?Jr:Qr;e.observer.safeEmit(n,{producerId:i.id,kind:i.kind,label:i.label,paused:i.paused}),r.fixedProducersState.push(t.id),d(this,Lm,"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?ln:pn;e.observer.safeEmit(s,n),r.fixedConsumersState.push(n),d(this,Lm,"f").info("Consumer state fixed",{case:"restoreLocalState",consumerId:n,consumerProducerId:t.id,consumerProducerPeerId:t.peerId})}})),r}restoreAppData(e,t){return!Cn(e.appData,t.appData)&&(e.observer.emit(vr,t.appData),d(this,Lm,"f").info("Application data restored",{case:"restoreLocalState",peerId:e.id,appData:t.appData}),!0)}};Lm=new WeakMap,xm=s([ct(),o(0,ut(Nn.Network)),o(1,ut(Nn.Media)),o(2,ut(Nn.MyPeer)),o(3,ut(Nn.EventsQueue)),o(4,ut(Nn.ClientEventEmitter)),o(5,ut(Nn.Peers)),o(6,ut(Nn.LoggerFactory)),a("design:paramtypes",[Xc,Sm,Cs,ws,wt,ed,Function])],xm);var Fm,jm=xm;let Um=class{constructor(e,t,r,n,i){this.peers=e,this.clientEventEmitter=t,this.channelStateSyncEventHandler=n,this.channelStateSynchronizer=i,Fm.set(this,void 0),u(this,Fm,r("ChannelEvents"),"f")}handleChannelEvent(e){return c(this,void 0,void 0,(function*(){switch(e.eventType){case zi.CHANNEL_EVENT_TYPE_CHANNEL_STATE:yield this.handleChannelState(e);break;case zi.CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT:this.handleChannelStateShort(e);break;case zi.CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT:this.handleChannelManagementEvent(e);break;case zi.CHANNEL_EVENT_TYPE_PEER_JOINED:this.handlePeerJoined(e);break;case zi.CHANNEL_EVENT_TYPE_PEER_LEFT:this.handlePeerLeft(e);break;case zi.CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED:this.handlePeerAppDataChanged(e);break;case zi.CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED:this.handlePeerGroupsChanged(e);break;case zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED:this.handleChannelActivityConfirmationAcquired();break;case zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED:this.handleChannelActivityConfirmationExpired();break;case zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED:this.handleChannelActivityConfirmationRequired(e);break;case zi.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED:this.handleChannelProducePermissionsChanged(e);break;case zi.CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED:this.handlePeerProducePermissionsChanged(e);break;case zi.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(yr,t),d(this,Fm,"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(Om(e.peer));d(this,Fm,"f").debug("Peer joined to the channel",{peer:Ss(t)})}handlePeerLeft(e){if(!e.peer)throw new Error("Missing peer in PEER_LEFT event");this.peers.remove(e.peer.id).catch((e=>{d(this,Fm,"f").debug("Failed to remove peer",{error:Pt(e)})})),d(this,Fm,"f").debug("Peer left the channel",{peerId:e.peer.id})}handleChannelState(e){return c(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){d(this,Fm,"f").error("Failed to restore channel state",{case:"restoreLocalState",error:Pt(e)})}}))}handleChannelStateShort(e){if(!e.channelStateShort)throw new Error("Missing channelStateShort in CHANNEL_STATE_SHORT event");this.channelStateSyncEventHandler.handleChannelStateShort(e.channelStateShort).catch((e=>{d(this,Fm,"f").error("Failed to handle channel state short event",{error:Pt(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(Dm))}handleChannelActivityConfirmationExpired(){this.clientEventEmitter.safeEmit(Sr),d(this,Fm,"f").info("Notify the channel that it has disconnected due to the activity confirmation expiring",{})}handleChannelActivityConfirmationAcquired(){this.clientEventEmitter.safeEmit(wr),d(this,Fm,"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(Er,t),d(this,Fm,"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(Nm(e)))))),n=e.channelProducePermissions.producePermissions.map(Im),i=e.channelProducePermissions.changedProducePermissions.map(Im);r.forEach((e=>{const t=Array.from(new Set([...e.producePermissions,...i])).filter((e=>!i.includes(e)||n.includes(e)));e.handleProducePermissionsChange(t)})),d(this,Fm,"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(Im);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(Nm(e)))))),n=e.channelProducePermissions.producePermissions.map(Im);r.forEach((e=>{const t=e.producePermissions.filter((e=>!n.includes(e)));e.handleProducePermissionsChange(t)})),d(this,Fm,"f").info("Peers deleted produce permissions",{groups:t,producePermissions:n})}};Fm=new WeakMap,Um=s([ct(),o(0,ut(Nn.Peers)),o(1,ut(Nn.ClientEventEmitter)),o(2,ut(Nn.LoggerFactory)),o(3,ut(Nn.ChannelStateSyncEventHandler)),o(4,ut(Nn.ChannelStateSynchronizer)),a("design:paramtypes",[ed,wt,Function,fd,jm])],Um);var Vm=Um,Bm={},Wm=p&&p.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(Bm,"__esModule",{value:!0});var Hm,qm,zm=Bm.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 Wm(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 Wm(this,void 0,void 0,(function*(){const e=this.pendingTasks[0];e&&(yield this.executeTask(e),this.pendingTasks.shift(),this.next())}))}executeTask(e){return Wm(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 Gm=class{constructor(e,t,r,n,i){this.media=e,this.internalEventEmitter=t,this.peersStorage=r,this.clientEventEmitter=n,Hm.set(this,new zm),qm.set(this,void 0),u(this,qm,i("MediaEvents"),"f")}handleMediaEvent(e){var t;switch(e.eventType){case os.MEDIA_EVENT_TYPE_PRODUCER_CREATED:this.handleProducerCreated(e);break;case os.MEDIA_EVENT_TYPE_PRODUCER_CLOSED:this.handleProducerClosed(e);break;case os.MEDIA_EVENT_TYPE_PRODUCER_PAUSED:this.handleProducerPaused(e);break;case os.MEDIA_EVENT_TYPE_PRODUCER_RESUMED:this.handleProducerResumed(e);break;case os.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED:this.handleProducerMaxSpatialLayerChanged(e);break;case os.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED:this.handleProducerRequestMaxSpatialLayer(e).catch((e=>{d(this,qm,"f").error("Failed to handle producer max spatial layer requested event",{error:Pt(e)})}));break;case os.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED:this.handleProducerForciblyClosed(e).catch((e=>{d(this,qm,"f").error("Failed to handle producer forcibly closed event",{error:Pt(e)})}));break;case os.MEDIA_EVENT_TYPE_CONSUMER_CLOSED:d(this,qm,"f").debug("Close consumer event received, skip",{consumerId:null===(t=e.consumer)||void 0===t?void 0:t.id});break;case os.MEDIA_EVENT_TYPE_CONSUMER_RESUMED:this.handleConsumerResumed(e);break;case os.MEDIA_EVENT_TYPE_CONSUMER_PAUSED:this.handleConsumerPaused(e);break;case os.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED:this.handleConsumerPreferredLayersChanged(e);break;case os.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(on,Mm(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(an,Mm(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(Jr,{producerId:r.id,kind:r.kind,label:r.label,paused:r.paused})):t.observer.safeEmit(on,Object.assign(Object.assign({},Mm(e.producer)),{paused:!0})):d(this,qm,"f").warn("Peer not found for producer paused event",{peerId:e.producer.peerId})}handleProducerResumed(e){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_RESUMED");const t=this.peersStorage.get(e.producer.peerId),r=null==t?void 0:t.producers.get(e.producer.id);t?r?(r.setPaused(!1),t.observer.safeEmit(Qr,{producerId:r.id,kind:r.kind,label:r.label,paused:r.paused})):t.observer.safeEmit(on,Object.assign(Object.assign({},Mm(e.producer)),{paused:!1})):d(this,qm,"f").warn("Peer not found for producer resumed event",{peerId:e.producer.peerId})}handleProducerMaxSpatialLayerChanged(e){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED");if(void 0===e.producer.maxSpatialLayer)return;const t=this.peersStorage.get(e.producer.peerId);null==t||t.observer.safeEmit(cn,{peerId:e.producer.peerId,producerId:e.producer.id,spatialLayer:e.producer.maxSpatialLayer})}handleProducerRequestMaxSpatialLayer(e){return c(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 d(this,Hm,"f").push((()=>c(this,void 0,void 0,(function*(){yield this.media.handleProducerSetMaxSpatialLayer({producerId:t,spatialLayer:r})}))),dn)}))}handleProducerForciblyClosed(e){return c(this,void 0,void 0,(function*(){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED");const t=Im(e.producer.label),r=this.media.getTrack(t);if(!r)return;r.stopMediaStreamTrack(),this.internalEventEmitter.safeEmit(qr,r);const n={label:t};this.clientEventEmitter.emit(Rr,n),yield this.media.deleteTrack(r)}))}handleConsumerResumed(e){if(!e.consumer)throw new Error("Missing consumer in MEDIA_EVENT_TYPE_CONSUMER_RESUMED");const t=this.peersStorage.get(e.consumer.producerPeerId);null==t||t.observer.safeEmit(pn,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(ln,e.consumer.id)}handleConsumerPreferredLayersChanged(e){var t;if(!e.consumer)throw new Error("Missing consumer in MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED");if(void 0===e.consumer.spatialLayer)return;const r=e.consumer.producerPeerId||e.consumer.peerId,n=this.peersStorage.get(r);null==n||n.observer.safeEmit(hn,{consumerId:e.consumer.id,spatialLayer:e.consumer.spatialLayer,temporalLayer:null!==(t=e.consumer.temporalLayer)&&void 0!==t?t:rf})}handleTransportConnectionTimeout(e){if(!e.transportConnectionTimeout)throw new Error("Missing transportConnectionTimeout in MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT");d(this,qm,"f").warn("Transport connection timed out",{transportId:e.transportConnectionTimeout.transportId,direction:e.transportConnectionTimeout.direction,timeout:e.transportConnectionTimeout.timeout,reason:e.transportConnectionTimeout.reason})}};Hm=new WeakMap,qm=new WeakMap,Gm=s([ct(),o(0,ut(Nn.Media)),o(1,ut(Nn.InternalEventEmitter)),o(2,ut(Nn.PeersStorage)),o(3,ut(Nn.ClientEventEmitter)),o(4,ut(Nn.LoggerFactory)),a("design:paramtypes",[Sm,wt,Tc,wt,Function])],Gm);var Ym,$m=Gm;let Jm=class{constructor(){Ym.set(this,new Map)}set(e,t){d(this,Ym,"f").set(e,{label:e,producerId:t})}get(e){return d(this,Ym,"f").get(e)}has(e){return d(this,Ym,"f").has(e)}delete(e){d(this,Ym,"f").delete(e)}entries(){return Array.from(d(this,Ym,"f").values())}};Ym=new WeakMap,Jm=s([ct()],Jm);var Qm,Km=Jm;let Zm=class{constructor(e,t,r){this.network=e,this.storage=t,Qm.set(this,void 0),u(this,Qm,r("ProducerCloseManager"),"f")}close(e,t){return c(this,void 0,void 0,(function*(){try{const r=yield this.sendCloseRequest(t);if(this.storage.delete(e),!r)return;d(this,Qm,"f").info("Remote producer closed",{label:e,producerId:t})}catch(r){this.storage.set(e,t),d(this,Qm,"f").warn("Failed to close remote producer, queued for retry",{label:e,producerId:t,error:Pt(r)})}}))}ensureNoPending(e){return c(this,void 0,void 0,(function*(){const t=this.storage.get(e);t&&(yield this.flushEntry(t))}))}flushPending(){return c(this,void 0,void 0,(function*(){const e=this.storage.entries();for(const t of e)try{yield this.flushEntry(t)}catch(e){}}))}flushEntry(e){return c(this,void 0,void 0,(function*(){try{yield Mn((()=>c(this,void 0,void 0,(function*(){yield this.sendCloseRequest(e.producerId)}))),{maxRetries:5,minBackoffDelayMs:200,maxBackoffDelayMs:1e3,actionName:"closeRemoteProducer",logger:d(this,Qm,"f")}),this.storage.delete(e.label),d(this,Qm,"f").info("Pending remote producer closed",{label:e.label,producerId:e.producerId})}catch(t){throw d(this,Qm,"f").warn("Failed to close pending remote producer",{label:e.label,producerId:e.producerId,error:Pt(t)}),t}}))}sendCloseRequest(e){return c(this,void 0,void 0,(function*(){try{return yield this.network.closeRemoteProducer(e),!0}catch(t){if(t instanceof rc)return d(this,Qm,"f").debug("Remote producer maybe already closed",{producerId:e}),!1;throw t}}))}};Qm=new WeakMap,Zm=s([ct(),o(0,ut(Nn.Network)),o(1,ut(Nn.PendingClosureProducerStorage)),o(2,ut(Nn.LoggerFactory)),a("design:paramtypes",[Function,Km,Function])],Zm);var Xm,eg,tg,rg,ng,ig,sg=Zm;const og=["send","recv"];let ag=ig=class{constructor(e,t){this.network=e,this.loggerFactory=t,Xm.set(this,!1),eg.set(this,new Map),tg.set(this,new Set),rg.set(this,new Map),ng.set(this,void 0),this.handleTransportState=({state:e,direction:t})=>{if(!d(this,Xm,"f"))return;if(d(this,tg,"f").has(t))return;if(d(this,rg,"f").has(t))return;if(!["disconnected","failed"].includes(e))return;const r=this.recordDisconnectAndGetCount(t);r&&(r<=3||(d(this,ng,"f").warn("transport instability detected. Escalating to relay",{direction:t,disconnectCount:r}),this.escalateDirectionToRelay(t).catch((e=>{d(this,ng,"f").warn("Failed to apply relay policy",{direction:t,error:Pt(e)})}))))},u(this,ng,this.loggerFactory("NetworkTransportPolicyManager"),"f")}startMonitoring(){d(this,Xm,"f")||(this.refreshDirectionRelayState(),d(this,eg,"f").clear(),u(this,Xm,!0,"f"),this.network.observer.on(mn,this.handleTransportState))}stopMonitoring(){d(this,Xm,"f")&&(this.network.observer.off(mn,this.handleTransportState),u(this,Xm,!1,"f"),d(this,eg,"f").clear())}changeIceTransportPolicy(e){return c(this,void 0,void 0,(function*(){yield Promise.all(d(this,rg,"f").values()),yield Promise.all(og.map((t=>c(this,void 0,void 0,(function*(){return yield this.applyRelayPolicy(t,e)}))))),d(this,eg,"f").clear(),"all"!==e?this.stopMonitoring():d(this,tg,"f").clear()}))}recordDisconnectAndGetCount(e){var t;const r=Date.now(),n=null!==(t=d(this,eg,"f").get(e))&&void 0!==t?t:[],i=n[n.length-1];if(ig.isDuplicateDisconnect(i,r))return;const s=ig.getDisconnectsInWindow(n,r);return s.push(r),d(this,eg,"f").set(e,s),s.length}applyRelayPolicy(e,t){return c(this,void 0,void 0,(function*(){const r=this.getTransportByDirection(e);if(!r)return;const n=ig.getPeerConnection(r);n&&(n.setConfiguration(Object.assign(Object.assign({},n.getConfiguration()),{iceTransportPolicy:t})),yield this.network.restartIce(r),"relay"===t?d(this,tg,"f").add(e):d(this,tg,"f").delete(e))}))}escalateDirectionToRelay(e){return c(this,void 0,void 0,(function*(){if(d(this,tg,"f").has(e))return;const t=d(this,rg,"f").get(e);if(t)return void(yield t);const r=(()=>c(this,void 0,void 0,(function*(){yield this.applyRelayPolicy(e,"relay"),d(this,eg,"f").delete(e)})))();d(this,rg,"f").set(e,r);try{yield r}finally{d(this,rg,"f").delete(e)}}))}refreshDirectionRelayState(){og.forEach((e=>{const t=this.getTransportByDirection(e),r=ig.getPeerConnection(t);"relay"!==(null==r?void 0:r.getConfiguration().iceTransportPolicy)?d(this,tg,"f").delete(e):d(this,tg,"f").add(e)}))}getTransportByDirection(e){return"send"===e?this.network.sendTransport:this.network.receiveTransport}static getPeerConnection(e){var t;return null===(t=null==e?void 0:e.handler)||void 0===t?void 0:t._pc}static getDisconnectsInWindow(e,t){const r=t-3e4;return e.filter((e=>e>=r))}static isDuplicateDisconnect(e,t){return"number"==typeof e&&t-e<400}};Xm=new WeakMap,eg=new WeakMap,tg=new WeakMap,rg=new WeakMap,ng=new WeakMap,ag=ig=s([ct(),o(0,ut(Nn.Network)),o(1,ut(Nn.LoggerFactory)),a("design:paramtypes",[Xc,Function])],ag);var cg=ag;const dg=new Error("request for lock canceled");var ug=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class lg{constructor(e,t=dg){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=pg(this._queue,(e=>t<=e.priority));-1===s&&e<=this._value?this._dispatchItem(i):this._queue.splice(s+1,0,i)}))}runExclusive(e){return ug(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=pg(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 pg(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1}var hg,fg=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class mg{constructor(e){this._semaphore=new lg(1,e)}acquire(){return fg(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 gg=class{constructor(){hg.set(this,new Map)}lock(e){return c(this,void 0,void 0,(function*(){let t=d(this,hg,"f").get(e);return t||(t=new mg,d(this,hg,"f").set(e,t)),t.isLocked()&&(yield t.waitForUnlock()),yield t.acquire()}))}isLocked(e){const t=d(this,hg,"f").get(e);return!!t&&t.isLocked()}waitForUnlock(e){return c(this,void 0,void 0,(function*(){const t=d(this,hg,"f").get(e);(null==t?void 0:t.isLocked())?yield t.waitForUnlock():yield Promise.resolve()}))}};hg=new WeakMap,gg=s([ct()],gg);var vg,yg=gg;let _g=class{constructor(e,t){this.clientEventEmitter=e,this.isEnableVideoDevicesLock=!1,this.isEnableAudioDevicesLock=!1,this.isDevicesDetected=!1,this.availableVideoDevices=[],this.availableAudioDevices=[],vg.set(this,void 0),u(this,vg,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 c(this,arguments,void 0,(function*(e={video:!0,audio:!0}){try{return(yield navigator.mediaDevices.getUserMedia(e)).getTracks()}catch(t){d(this,vg,"f").error("getUserMedia()",{error:t,constraints:e});const r=t instanceof Error?t.name:void 0;if("NotAllowedError"===r)throw new Error(xn.NotAllowedError);if("NotReadableError"===r)throw new Error(xn.DeviceIsBusy);if("NotFoundError"===r)throw new Error(xn.NotFoundError);throw new Error(xn.RequestDevicesUnknownError)}}))}hasAvailableMediaDevicesList(){return c(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 c(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 d(this,vg,"f").info("Devices list updated",{videoDevices:t.map(n),audioDevices:r.map(n)}),e}))}detectDevices(e){return c(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(xn.NoDevices)}))}deviceChangeHandler(){return c(this,void 0,void 0,(function*(){if(!this.isDevicesDetected)return;yield this.refreshAvailableMediaDevicesList();const e={audio:this.availableAudioDevices,video:this.availableVideoDevices};this.clientEventEmitter.safeEmit(Pr,e)}))}listenDevices(){navigator.mediaDevices.addEventListener("devicechange",this.deviceChangeHandler)}assertHasAccessToMediaDevices(){return c(this,arguments,void 0,(function*(e={video:!0,audio:!0}){(yield this.requestMediaDevicesAccess(e)).forEach((e=>e.stop()))}))}tryToAccessDevices(){return c(this,void 0,void 0,(function*(){try{(yield this.requestMediaDevicesAccess()).forEach((e=>e.stop()))}catch(t){const r=(e=>{if(e instanceof Error)return e.message;if("string"==typeof e)return e;if(e&&"object"==typeof e&&"message"in e){const t=e.message;return"string"==typeof t?t:void 0}})(t);if(!r||(e=r,![xn.NotFoundError,xn.NotAllowedError,xn.DeviceIsBusy].includes(e)))throw t;r!==xn.DeviceIsBusy&&(yield this.assertHasAccessToMediaDevices({audio:!0}),yield this.assertHasAccessToMediaDevices({video:!0}))}var e}))}};vg=new WeakMap,_g=s([ct(),o(0,ut(Nn.ClientEventEmitter)),o(1,ut(Nn.LoggerFactory)),a("design:paramtypes",[wt,Function])],_g);var bg,Eg=_g;class wg{constructor({transport:e,statsHandler:t}){bg.set(this,void 0),this.handleWebRTCStats(e,t)}get connectionStats(){return d(this,bg,"f")}handleWebRTCStats(e,t){t.addConnectionHandler(e.id,this.setConnectionStats.bind(this)),e.observer.once("close",(()=>{t.removeConnectionHandler(e.id)}))}setConnectionStats(e){u(this,bg,e,"f")}}bg=new WeakMap;function Sg(e,t){return t.find((t=>t.ssrc===e))}function Cg(e,t,r){return Math.max(t,Math.min(e,r))}function Pg(e,t=2){return Number(e.toFixed(t))}function Tg(e){return Cg(Pg(e),1,5)}function Rg(e,t){if(0===e.length)throw new Error("Cannot compute percentile of empty array");if(1===e.length)return e[0];const r=t*(e.length-1),n=Math.floor(r),i=Math.ceil(r),s=r-n;return Pg(e[n]+s*(e[i]-e[n]))}var kg,Dg,Ig,Ag,Og;let Mg=class{constructor(){kg.set(this,new Map),Dg.set(this,new Map),Ig.set(this,new Map),Ag.set(this,new Map),Og.set(this,new Map)}handle(e){e.forEach((({id:e,stats:t})=>{var r;null===(r=d(this,kg,"f").get(e))||void 0===r||r(t.connection),t.video.inbound.forEach((e=>{var r;return null===(r=d(this,Dg,"f").get(e.trackIdentifier))||void 0===r?void 0:r({inbound:e,connection:t.connection})})),t.audio.inbound.forEach((e=>{var r;return null===(r=d(this,Ig,"f").get(e.trackIdentifier))||void 0===r?void 0:r({inbound:e,connection:t.connection})}));const n=new Map;t.video.outbound.forEach((e=>{const r=Sg(e.ssrc,t.remote.video.inbound);if(!r)return;const i={outbound:e,remoteInbound:r,connection:t.connection},s=n.get(e.mid);s?s.push(i):n.set(e.mid,[i])})),n.forEach((e=>{var t,r;const n=null===(t=e.find((e=>e.outbound.track.trackIdentifier)))||void 0===t?void 0:t.outbound.track.trackIdentifier;n&&(null===(r=d(this,Ag,"f").get(n))||void 0===r||r(e))})),t.audio.outbound.forEach((e=>{var r;const n=Sg(e.ssrc,t.remote.audio.inbound);n&&(null===(r=d(this,Og,"f").get(e.track.trackIdentifier))||void 0===r||r({outbound:e,remoteInbound:n,connection:t.connection}))}))}))}addConnectionHandler(e,t){d(this,kg,"f").set(e,t)}addInboundVideoHandler(e,t){d(this,Dg,"f").set(e,t)}addInboundAudioHandler(e,t){d(this,Ig,"f").set(e,t)}addOutboundVideoHandler(e,t){d(this,Ag,"f").set(e,t)}addOutboundAudioHandler(e,t){d(this,Og,"f").set(e,t)}removeConnectionHandler(e){d(this,kg,"f").delete(e)}removeInboundVideoHandler(e){d(this,Dg,"f").delete(e)}removeInboundAudioHandler(e){d(this,Ig,"f").delete(e)}removeOutboundVideoHandler(e){d(this,Ag,"f").delete(e)}removeOutboundAudioHandler(e){d(this,Og,"f").delete(e)}clear(){d(this,kg,"f").clear(),d(this,Dg,"f").clear(),d(this,Ig,"f").clear(),d(this,Ag,"f").clear(),d(this,Og,"f").clear()}};kg=new WeakMap,Dg=new WeakMap,Ig=new WeakMap,Ag=new WeakMap,Og=new WeakMap,Mg=s([ct()],Mg);var Ng,Lg,xg,Fg,jg,Ug,Vg,Bg,Wg=Mg;let Hg=class{constructor(e,t){var r;Ng.set(this,!1),Lg.set(this,void 0),xg.set(this,void 0),Fg.set(this,void 0),jg.set(this,void 0),Ug.set(this,void 0),Vg.set(this,void 0),Bg.set(this,.5),u(this,Lg,e("IntegrationsService"),"f"),u(this,Vg,t,"f"),u(this,Bg,null!==(r=kf("qosQPercentile"))&&void 0!==r?r:d(this,Bg,"f"),"f")}init({sendTransportConnectionManager:e,receiveTransportConnectionManager:t,media:r,peers:n}){u(this,xg,e,"f"),u(this,Fg,t,"f"),u(this,jg,r,"f"),u(this,Ug,n,"f"),u(this,Ng,!0,"f")}getStats(){try{return this.doGetStats()}catch(e){return d(this,Lg,"f").error("Failed to get stats",{error:Pt(e)}),{}}}clear(){u(this,xg,void 0,"f"),u(this,Fg,void 0,"f"),u(this,jg,void 0,"f"),u(this,Ug,void 0,"f")}doGetStats(){var e,t,r,n;if(!d(this,Ng,"f"))throw new Error("TransportsStatsProvider is not initialized");const i={};if(null===(t=null===(e=d(this,xg,"f"))||void 0===e?void 0:e.connectionStats)||void 0===t?void 0:t.id){const e=this.calculateOutboundTracksResultQValues();i.outbound=Object.assign(Object.assign({},d(this,xg,"f").connectionStats),{bitrate:this.calculateOutboundTracksBitrate(),Qav:e.Qav,Qa:e.Qa,Qv:e.Qv})}if(null===(n=null===(r=d(this,Fg,"f"))||void 0===r?void 0:r.connectionStats)||void 0===n?void 0:n.id){const e=this.calculateInboundTracksResultQValues();i.inbound=Object.assign(Object.assign({},d(this,Fg,"f").connectionStats),{bitrate:this.calculateInboundTracksBitrate(),Qav:e.Qav,Qa:e.Qa,Qv:e.Qv})}return i}calculateInboundTracksBitrate(){if(void 0===d(this,Ug,"f"))throw new Error("Peers is undefined");return d(this,Ug,"f").hosts().reduce(((e,t)=>{if(t.isMe)return e;return e+Array.from(t.tracks.values()).reduce(((e,t)=>{var r,n;const i="video"===t.kind?null===(r=t.videoWebRTCStats)||void 0===r?void 0:r.bitrate:null===(n=t.audioWebRTCStats)||void 0===n?void 0:n.bitrate;return e+(null!=i?i:0)}),0)}),0)}calculateInboundTracksResultQValues(){if(void 0===d(this,Ug,"f"))throw new Error("Peers prop is not defined");const e=[],t=[],r=[];for(const n of d(this,Ug,"f").hosts()){if(n.isMe)continue;const{Qa:i,Qv:s}=this.getWorstQValues(Array.from(n.tracks.values()));void 0!==i&&t.push(i),void 0!==s&&r.push(s);const o=void 0===i||void 0===s?null!=i?i:s:d(this,Vg,"f").calculateAVCompositeMOS(i,s);void 0!==o&&e.push(o)}const n=(e,t)=>e-t;return e.sort(n),t.sort(n),r.sort(n),{Qav:e.length>0?Rg(e,d(this,Bg,"f")):void 0,Qa:t.length>0?Rg(t,d(this,Bg,"f")):void 0,Qv:r.length>0?Rg(r,d(this,Bg,"f")):void 0}}calculateOutboundTracksResultQValues(){var e;if(void 0===d(this,jg,"f"))throw new Error("Media prop is not defined");const t=d(this,jg,"f").getAllTracks().filter((e=>e.isPublished)),{Qa:r,Qv:n}=this.getWorstQValues(t);let i;return void 0!==r&&void 0!==n&&(i=d(this,Vg,"f").calculateAVCompositeMOS(r,n)),{Qav:null!==(e=null!=i?i:r)&&void 0!==e?e:n,Qa:r,Qv:n}}calculateOutboundTracksBitrate(){if(void 0===d(this,jg,"f"))throw new Error("Media is undefined");return d(this,jg,"f").getAllTracks().reduce(((e,t)=>{var r,n;if(!t.isPublished)return e;const i="video"===t.kind?null===(r=t.videoWebRTCStats)||void 0===r?void 0:r.bitrate:null===(n=t.audioWebRTCStats)||void 0===n?void 0:n.bitrate;return e+(null!=i?i:0)}),0)}getWorstQValues(e){let t,r;for(const n of e){const{Qa:e,Qv:i}=n.connectionScores;void 0!==e&&(void 0===t||e<t)&&(t=e),void 0!==i&&(void 0===r||i<r)&&(r=i)}return{Qa:t,Qv:r}}};Ng=new WeakMap,Lg=new WeakMap,xg=new WeakMap,Fg=new WeakMap,jg=new WeakMap,Ug=new WeakMap,Vg=new WeakMap,Bg=new WeakMap,Hg=s([ct(),o(0,ut(Nn.LoggerFactory)),o(1,ut(Nn.ScoresCalculator)),a("design:paramtypes",[Function,Function])],Hg);var qg=Hg;const zg={vp8:40,vp9:40,h264:25},Gg={mobile:[.1558,1.0348,-.0181,-.4048],pc:[.1526,.8788,.0086,-.2242],tv:[.1496,1.0267,-.0248,-.3477]},Yg={video:{codecFactors:{vp9:1.2,vp8:1,h264:1}},defaults:{audio:{ssrc:-1,packetLoss:0,bufferDelay:50,roundTripTime:50,fec:!0,bitrate:0,dtx:!1},video:{ssrc:-1,packetLoss:0,bufferDelay:0,roundTripTime:50,codec:"vp8",width:640,height:480,expectedWidth:640,expectedHeight:480,frameRate:20,expectedFrameRate:20,bitrate:0}}};let $g=class{constructor(e){this.config=this.mergeConfig(e)}calculateAudioMOS(e){const t=this.normalizeAudioStats(e),r=20+t.bufferDelay+t.roundTripTime/2,n=t.packetLoss;let i=0;i=t.dtx?8:t.bitrate>0?Cg(55-4.6*Math.log(t.bitrate),0,30):6;const s=Cg(100-(i+(100-i)*n/(n+(t.fec?20:10)))-(.03*r+(r>150?.1*(r-150):0)),0,100);return Tg(1+.035*s+s*(s-60)*(100-s)*7/1e6)}calculateVideoMOS(e){var t,r,n,i,s,o;const a=this.normalizeVideoStats(e),c=a.expectedWidth*a.expectedHeight;if(!a.frameRate||!c||void 0===a.bitrate)return 1;const d=a.codec&&null!==(n=null===(r=null===(t=this.config.video)||void 0===t?void 0:t.codecFactors)||void 0===r?void 0:r[a.codec.toLowerCase()])&&void 0!==n?n:1,u=a.bufferDelay+a.roundTripTime/2,l=d*a.bitrate/c/a.frameRate,p=Cg(.56*Math.log(l)+5.36,1,5),h=!0===a.decreaseOutboundPenalty&&"none"===a.qualityLimitationReason,f=null!==(o=zg[null!==(s=null===(i=a.codec)||void 0===i?void 0:i.toLowerCase())&&void 0!==s?s:""])&&void 0!==o?o:40,m=void 0!==a.averageQP&&a.averageQP<f;return Tg((h||!0===a.isStaticContent||m?Math.max(p,4):p)-(a.expectedFrameRate>0?1.9*Math.log(a.expectedFrameRate/a.frameRate):0)-.002*u)}calculateAVCompositeMOS(e,t,r){const[n,i,s,o]=Gg[null!=r?r:"pc"];return Tg(n*e+i*t+s*e*t+o)}mergeConfig(e){var t;return e?{video:{codecFactors:Object.assign(Object.assign({},Yg.video.codecFactors),null===(t=e.video)||void 0===t?void 0:t.codecFactors)}}:Yg}normalizeAudioStats(e){return Object.assign(Object.assign({},Yg.defaults.audio),e)}normalizeVideoStats(e){const t=Object.assign(Object.assign({},Yg.defaults.video),e);return void 0!==e.width&&void 0===e.expectedWidth&&(t.expectedWidth=e.width),void 0!==e.height&&void 0===e.expectedHeight&&(t.expectedHeight=e.height),void 0!==e.frameRate&&void 0===e.expectedFrameRate&&(t.expectedFrameRate=e.frameRate),t}};var Jg,Qg,Kg;$g=s([ct(),a("design:paramtypes",[Object])],$g);let Zg=class{constructor(e,t,r,n,i,s,o,a,c,d,l,p,h,f,m,g,v,y,_,b,E,w,S,C,P){var T;this.state=e,this.myPeer=t,this.integrationsService=n,this.processorsCache=i,this.mediaEventHandler=s,this.channelEventsHandler=o,this.peerTrackFactory=a,this.peers=c,this.peersStorage=d,this.system=l,this.media=p,this.network=h,this.networkTransportPolicyManager=f,this.producerCloseManager=m,this.signalingApiClient=g,this.eventsQueue=v,this.clientEventEmitter=y,this.internalEventEmitter=_,this.statsHandler=b,this.transportsStatsProvider=E,this.localMutex=w,this.scoresCalculatorInstance=S,this.clientMetaProvider=C,this.webRtcIssueDetector=P,Jg.set(this,void 0),this.rejoinRequested=!1,this.isReleasing=!1,Qg.set(this,!1),Kg.set(this,!1),this.mark=In(),this.handleSignalingError=e=>{this.isReleasing||!this.isChannelJoined||this.state.isChannelJoining||e instanceof yn&&this.triggerRejoinEventIfAppropriate(e.errorCode)},u(this,Jg,r("Engine"),"f"),this.watchNetworkState(),this.watchDocumentUnload(),this.watchInternalEvents(),this.signalingApiClient.addErrorListener(this.handleSignalingError),T=this.mark,window._sdkMarks||(window._sdkMarks=new Set),window._sdkMarks.add(T)}get isChannelJoined(){return this.state.isJoined}get scoresCalculator(){return this.scoresCalculatorInstance}initialize(){return c(this,void 0,void 0,(function*(){var e,t,r,n;try{const{data:i}=yield this.signalingApiClient.router.getRtpCapabilities(),{rtpCapabilities:s}=i;this.integrationsService.init(),yield this.media.loadDevice(s),d(this,Jg,"f").info("Supported capabilities",{codecs:Rn(this.media.mediasoupDevice)});const[o,a]=yield Promise.all([this.network.createSendTransport(this.media.mediasoupDevice),this.network.createRecvTransport(this.media.mediasoupDevice)]);null===(e=this.webRtcIssueDetector)||void 0===e||e.handleNewPeerConnection(o.handler._pc,o.id),null===(t=this.webRtcIssueDetector)||void 0===t||t.handleNewPeerConnection(a.handler._pc,a.id),this.transportsStatsProvider.init({media:this.media,peers:this.peers,receiveTransportConnectionManager:new wg({transport:a,statsHandler:this.statsHandler}),sendTransportConnectionManager:new wg({transport:o,statsHandler:this.statsHandler})}),yield this.network.initializeHeartbeats();const{isChromiumBased:c}=(e=>{var t;const r=null!=e?e:"undefined"!=typeof navigator?navigator.userAgent:void 0;if(!r)return{isMobile:!1,isChromiumBased:!1};const n=wn.getParser(r),i=n.getPlatformType(!0),s="mobile"===i||"tablet"===i,o=n.getEngineName().toLowerCase(),a=null!==(t=n.satisfies({chrome:">=0",chromium:">=0","chromium webview":">=0",edge:">=0",opera:">=0","opera coast":">=0","samsung internet for android":">=0","yandex browser":">=0",electron:">=0"}))&&void 0!==t&&t;return{isMobile:s,isChromiumBased:"blink"===o||a&&"webkit"!==o}})();c||(yield this.network.createSignalingTransport(this.media.mediasoupDevice),yield this.network.createKeepAliveConsumer()),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)),d(this,Jg,"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})}catch(e){d(this,Jg,"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 _n("Device not supported",_n.UNSUPPORTED_DEVICE_CODE);if(e instanceof vn)throw e;throw new Tt("initialize_engine_error",e)}}))}release(e){return c(this,void 0,void 0,(function*(){var t;if(this.isReleasing)return;const r=this.myPeer.get(),n={case:"release",applicationId:this.state.appId,channelId:this.state.channelId,peerId:null!==(t=null==r?void 0:r.id)&&void 0!==t?t:this.myPeerId,peerRole:null==r?void 0:r.role,isJoined:this.state.isJoined,isChannelJoining:this.state.isChannelJoining,rejoinRequested:this.rejoinRequested};this.isReleasing=!0;const i=yield this.localMutex.lock(gn.Release);try{this.signalingApiClient.abortPendingRequests("release"),e||this.media.clearTracks(),yield Promise.all([Tn((()=>c(this,void 0,void 0,(function*(){return yield this.peers.reset()})))),Tn((()=>c(this,void 0,void 0,(function*(){return yield this.media.unpublishTracks()})))),Tn((()=>c(this,void 0,void 0,(function*(){return yield this.signalingApiClient.peers.disconnectPeer()}))))]),this.cleanup(),d(this,Jg,"f").debug("release()",n)}catch(e){d(this,Jg,"f").error("Failed to release",Object.assign(Object.assign({},n),{error:Pt(e)}))}finally{this.isReleasing=!1,i()}}))}getPeers(){return this.peers.all()}get myPeerId(){return this.myPeer.id}confirmActivity(){return c(this,void 0,void 0,(function*(){try{yield this.signalingApiClient.channel.confirmChannelActivity()}catch(e){throw new Tt("confirm_activity_failed",e)}}))}join(e){return c(this,void 0,void 0,(function*(){if(this.isChannelJoined)throw new Tt("method_not_available_when_joined");const t=yield this.localMutex.lock(gn.Join);try{d(this,Jg,"f").debug("join()",{params:e}),this.state.isChannelJoining=!0,this.signalingApiClient.abortPendingRequests("join"),this.signalingApiClient.setSecurityData({token:e.token,peerApiVersion:8,datacenterType:e.isP2pCall?"p2p":"common"});const{data:r,headers:n}=yield this.signalingApiClient.peers.registerPeer({appData:e.appData}),{appId:i,channelId:s,peerId:o}=r,a=String(n["x-datacenter-name"]),u=String(n["x-node-id"]);this.myPeer.id=o,this.state.appId=i,this.state.channelId=s,this.clientMetaProvider.setPeerId(o),this.clientMetaProvider.setChannelId(s),this.clientMetaProvider.setAppId(i),this.clientMetaProvider.setDatacenterName(a),this.clientMetaProvider.setNodeId(u),yield this.initialize(),yield this.network.waitForReceiveTransportConnected({onReceiveTransportFailed:()=>c(this,void 0,void 0,(function*(){yield this.networkTransportPolicyManager.escalateDirectionToRelay("recv")}))}),yield this.network.waitForChannelMessagesDataConsumerConnected(),this.state.isJoined=!0,this.networkTransportPolicyManager.startMonitoring(),d(this,Jg,"f").info("Successfully joined channel",{channelId:s,datacenterName:a})}catch(e){throw this.signalingApiClient.abortPendingRequests("join"),yield this.release(),d(this,Jg,"f").error("join()",{error:e}),new Tt("join_failed",e)}finally{this.state.isChannelJoining=!1,this.rejoinRequested=!1,t()}}))}loadPeers(e){return c(this,void 0,void 0,(function*(){try{yield this.peers.load(e)}catch(e){throw new Tt("load_peers_failed",e)}}))}requestChannelStateSync(){Mn((()=>c(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>c(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)?(d(this,Jg,"f").info("Channel state event received",{case:"Engine.requestChannelStateSync"}),e()):t(new Tt("channel_state_event_not_received",new Error("Channel state event not received")))}),5e3),i=()=>{clearTimeout(n),this.clientEventEmitter.off(Ar,i),e()};this.clientEventEmitter.on(Ar,i)}))))}))),{minBackoffDelayMs:0,maxBackoffDelayMs:0,maxRetries:10,actionName:"triggerChannelStateEventWithRetry",logger:d(this,Jg,"f")}).catch((e=>{d(this,Jg,"f").error("Failed to request channel state event",{case:"Engine.requestChannelStateSync",error:Pt(e)})}))}updateAppData(e){return c(this,void 0,void 0,(function*(){const t=this.myPeer.get();if(!t)throw new Tt("need_joined_to_channel",new Error("Need join to channel first"));try{bn(e)}catch(e){throw d(this,Jg,"f").error("updateAppData() validation failed",{error:e}),new Tt("invalid_app_data",e)}try{yield this.network.updatePeerAppData({peerId:t.id,appData:e})}catch(e){throw d(this,Jg,"f").error("updateAppData()",{error:e}),new Tt("update_app_data_failed",e)}}))}createCameraVideoTrack(e){return c(this,void 0,void 0,(function*(){const t=Sm.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 um&&(r.setLabel((null==e?void 0:e.isPreview)?Ln.CameraPreview:Ln.Camera),r.setEncoderConfig(t.encoderConfig),r.setTransformParams(Sm.getVideoTrackTransformParams(r.mediaStreamTrack))),this.media.setTrack(r),d(this,Jg,"f").debug("createCameraVideoTrack()",{trackParams:t}),r}catch(e){throw d(this,Jg,"f").error("createCameraVideoTrack()",{error:e,trackParams:t}),new Tt("create_camera_track_failed",e)}}))}createMicrophoneAudioTrack(e){return c(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)?Ln.MicrophonePreview:Ln.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()!==Ln.Microphone||d(this,Kg,"f")||this.media.initDenoiser(t,e).catch((t=>{this.clientEventEmitter.emit(jr,{cause:"Failed to initialize denoiser",error:t}),d(this,Jg,"f").error("Failed to execute initDenoiser",{case:"Denoiser",options:e,error:Pt(t)})})),this.media.setTrack(t),d(this,Jg,"f").debug("createMicrophoneAudioTrack()",{options:e,trackLabel:t.getLabel()}),t}catch(t){throw d(this,Jg,"f").error("createMicrophoneAudioTrack()",{error:t,options:e}),new Tt("create_microphone_track_failed",t)}}))}createScreenMediaTracks(e){return c(this,void 0,void 0,(function*(){const t=Sm.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=>{d(this,Jg,"f").error("Failed to unpublish screen track",{error:Pt(e)})}))}),{once:!0}),r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof um){r.setLabel(Ln.ScreenVideo),r.setEncoderConfig(t.encoderConfig);const e=Sm.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(e),this.media.setTrack(r),void d(this,Jg,"f").debug("createScreenMediaTrack()",{trackParams:t,transformParams:e,label:r.logCtx})}r.setLabel(Ln.ScreenAudio),(null==e?void 0:e.audioEncoderConfig)&&r.setEncoderConfig(e.audioEncoderConfig),this.media.setTrack(r),d(this,Jg,"f").debug("createScreenMediaTrack()",{trackParams:null==e?void 0:e.audio,encoderConfig:null==e?void 0:e.audioEncoderConfig})})),r}catch(e){throw d(this,Jg,"f").error("createScreenMediaTrack()",{error:e,trackParams:t}),new Tt("create_screen_tracks_failed",e)}}))}createCustomAudioTrack(e){if(!e.audioTrack)throw new Tt("missing_audio_track",new Error("options.audioTrack is required"));try{const t=this.media.createCustomMediaTrack(e.audioTrack,{audio:e.audio});return t.mediaStreamTrack.addEventListener("ended",(()=>{t.unpublish().catch((e=>{d(this,Jg,"f").error("Failed to unpublish custom audio track",{track:t,error:Pt(e)})}))}),{once:!0}),t.setStopTrackOnPause(Boolean(e.stopTrackOnPause)),t.setLabel(Ln.CustomAudio),e.audioEncoderConfig&&t.setEncoderConfig(e.audioEncoderConfig),this.media.setTrack(t),d(this,Jg,"f").debug("createCustomAudioTrack()",{trackParams:e.audio,encoderConfig:e.audioEncoderConfig}),t}catch(t){throw d(this,Jg,"f").error("createCustomAudioTrack()",{error:t,trackParams:e.audioTrack}),new Tt("create_custom_audio_track_failed",t)}}createCustomVideoTrack(e){const t=Sm.getScreenVideoTrackParams(e);if(!e.videoTrack)throw new Tt("missing_video_track",new Error("options.videoTrack is required"));try{const r=this.media.createCustomMediaTrack(e.videoTrack,{video:e.video});r.mediaStreamTrack.addEventListener("ended",(()=>{r.unpublish().catch((e=>{d(this,Jg,"f").error("Failed to unpublish custom video track",{track:r,error:Pt(e)})}))}),{once:!0}),r.mediaStreamTrack.contentHint="customVideo",r.setLabel(Ln.CustomVideo),r.setEncoderConfig(t.encoderConfig);const n=Sm.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(n),this.media.setTrack(r),d(this,Jg,"f").debug("createCustomVideoTrack()",{trackParams:t,transformParams:n,label:r.logCtx}),r}catch(e){throw d(this,Jg,"f").error("createCustomVideoTrack()",{error:e,trackParams:t}),new Tt("create_custom_video_track_failed",e)}}deleteTrack(e){return c(this,void 0,void 0,(function*(){try{yield this.media.deleteTrack(e)}catch(e){throw new Tt("delete_track_failed",e)}}))}transportsStats(){return this.transportsStatsProvider.getStats()}setSignalingServerUrl(e){if(this.isChannelJoined||this.rejoinRequested||this.state.isChannelJoining)throw new Tt("method_not_available_when_joined",new Error("Method not available when joined channel"));this.signalingApiClient.instance.defaults.baseURL=e}cleanup(){var e;this.signalingApiClient.abortPendingRequests("cleanup"),this.rejoinRequested=!1,u(this,Qg,!1,"f"),this.networkTransportPolicyManager.stopMonitoring(),this.state.reset(),this.network.reset(),this.peersStorage.clear(),this.transportsStatsProvider.clear(),this.statsHandler.clear(),this.integrationsService.reset(),null===(e=this.webRtcIssueDetector)||void 0===e||e.stopWatchingNewPeerConnections(),this.processorsCache.reset(),this.clientMetaProvider.clear()}watchInternalEvents(){this.internalEventEmitter.on(Vr,(e=>c(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.internalEventEmitter.on(Br,(e=>c(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=>{d(this,Jg,"f").debug("Failed to close peerTrack",{error:Pt(e)})})),yield this.media.deleteTrack(e)})))),this.internalEventEmitter.on(Wr,(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=>{d(this,Jg,"f").debug("Failed to pause peerTrack",{error:Pt(e)})}))})),this.internalEventEmitter.on(Hr,(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=>{d(this,Jg,"f").debug("Failed to resume peerTrack",{error:Pt(e)})}))})),this.internalEventEmitter.on(qr,(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=>{d(this,Jg,"f").debug("Failed to close peerTrack",{error:Pt(e)})}))})),this.internalEventEmitter.on(zr,(e=>c(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.internalEventEmitter.on(Gr,(e=>{this.clientEventEmitter.safeEmit(kr,{label:e.getLabel()})}))}createSelfPeerTrack(e){return c(this,void 0,void 0,(function*(){var t;if(!this.myPeer.id)return;const r=this.peers.get(this.myPeer.id);if(!r)return;yield null===(t=r.tracks.get(e.getLabel()))||void 0===t?void 0:t.close();const n=this.peerTrackFactory({label:e.getLabel(),mediaStreamTrack:e.mediaStreamTrack,muted:!1,paused:e.isPaused,onClose:()=>{},peerEventEmitter:r.observer});r.tracks.set(n.label,n)}))}triggerRejoinEventIfAppropriate(e){!this.isChannelJoined||this.isReleasing||this.state.isChannelJoining||this.rejoinRequested||(d(this,Jg,"f").debug("Triggering channel rejoin required event",{reason:e}),this.signalingApiClient.abortPendingRequests("channel-rejoin"),this.rejoinRequested=!0,this.clientEventEmitter.emit(Cr))}watchNetworkState(){this.network.observer.on(mn,(({state:e,direction:t})=>{if(!this.isReleasing&&(["disconnected","failed"].includes(e)&&this.isChannelJoined&&!d(this,Qg,"f")&&(u(this,Qg,!0,"f"),d(this,Jg,"f").info("connection lost",{channel:"webrtc-transport",direction:t}),this.clientEventEmitter.safeEmit(Ar)),"reconnected"===e&&this.isChannelJoined&&d(this,Jg,"f").info("connection restored",{channel:"webrtc-transport",direction:t}),"reconnected"===e&&this.isChannelJoined&&d(this,Qg,"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;u(this,Qg,!1,"f"),this.clientEventEmitter.safeEmit(Or),this.producerCloseManager.flushPending().catch((e=>{d(this,Jg,"f").warn("Failed to flush pending remote producers",{error:Pt(e)})}))}}))}watchDocumentUnload(){try{window.addEventListener("unload",(()=>{var e,t;null===(e=this.network.sendTransport)||void 0===e||e.close(),null===(t=this.network.receiveTransport)||void 0===t||t.close()}))}catch(e){d(this,Jg,"f").error("Failed to add watchDocumentUnload listener",{channelId:this.state.channelId,error:Pt(e)})}}};Jg=new WeakMap,Qg=new WeakMap,Kg=new WeakMap,Zg=s([ct(),o(0,ut(Nn.CallState)),o(1,ut(Nn.MyPeer)),o(2,ut(Nn.LoggerFactory)),o(3,ut(Nn.IntegrationsService)),o(4,ut(Nn.ProcessorsCache)),o(5,ut(Nn.MediaEventHandler)),o(6,ut(Nn.ChannelEventHandler)),o(7,ut(Nn.PeerTrackFactory)),o(8,ut(Nn.Peers)),o(9,ut(Nn.PeersStorage)),o(10,ut(Nn.System)),o(11,ut(Nn.Media)),o(12,ut(Nn.Network)),o(13,ut(Nn.NetworkTransportPolicyManager)),o(14,ut(Nn.ProducerCloseManager)),o(15,ut(Nn.SignalingApiClient)),o(16,ut(Nn.EventsQueue)),o(17,ut(Nn.ClientEventEmitter)),o(18,ut(Nn.InternalEventEmitter)),o(19,ut(Nn.StatsHandler)),o(20,ut(Nn.TransportsStatsProvider)),o(21,ut(Nn.LocalMutex)),o(22,ut(Nn.ScoresCalculator)),o(23,ut(Nn.ClientMetaProvider)),o(24,ut(Nn.WebRTCIssueDetector)),a("design:paramtypes",[Fn,Cs,Function,hf,uf,$m,Vm,Function,Object,Tc,Eg,Sm,Xc,cg,sg,bc,ws,wt,wt,Wg,qg,yg,$g,gr,ur])],Zg);var Xg=Zg,ev="undefined"!=typeof Symbol&&Symbol,tv=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},rv="Function.prototype.bind called on incompatible ",nv=Array.prototype.slice,iv=Object.prototype.toString,sv=function(e){var t=this;if("function"!=typeof t||"[object Function]"!==iv.call(t))throw new TypeError(rv+t);for(var r,n=nv.call(arguments,1),i=function(){if(this instanceof r){var i=t.apply(this,n.concat(nv.call(arguments)));return Object(i)===i?i:this}return t.apply(e,n.concat(nv.call(arguments)))},s=Math.max(0,t.length-n.length),o=[],a=0;a<s;a++)o.push("$"+a);if(r=Function("binder","return function ("+o.join(",")+"){ return binder.apply(this,arguments); }")(i),t.prototype){var c=function(){};c.prototype=t.prototype,r.prototype=new c,c.prototype=null}return r},ov=Function.prototype.bind||sv,av="Function.prototype.bind called on incompatible ",cv=Array.prototype.slice,dv=Object.prototype.toString,uv=function(e){var t=this;if("function"!=typeof t||"[object Function]"!==dv.call(t))throw new TypeError(av+t);for(var r,n=cv.call(arguments,1),i=function(){if(this instanceof r){var i=t.apply(this,n.concat(cv.call(arguments)));return Object(i)===i?i:this}return t.apply(e,n.concat(cv.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},lv=(Function.prototype.bind||uv).call(Function.call,Object.prototype.hasOwnProperty),pv=SyntaxError,hv=Function,fv=TypeError,mv=function(e){try{return hv('"use strict"; return ('+e+").constructor;")()}catch(e){}},gv=Object.getOwnPropertyDescriptor;if(gv)try{gv({},"")}catch(kt){gv=null}var vv=function(){throw new fv},yv=gv?function(){try{return vv}catch(e){try{return gv(arguments,"callee").get}catch(e){return vv}}}():vv,_v="function"==typeof ev&&"function"==typeof Symbol&&"symbol"==typeof ev("foo")&&"symbol"==typeof Symbol("bar")&&tv(),bv=Object.getPrototypeOf||function(e){return e.__proto__},Ev={},wv="undefined"==typeof Uint8Array?undefined:bv(Uint8Array),Sv={"%AggregateError%":"undefined"==typeof AggregateError?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":_v?bv([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":Ev,"%AsyncGenerator%":Ev,"%AsyncGeneratorFunction%":Ev,"%AsyncIteratorPrototype%":Ev,"%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%":hv,"%GeneratorFunction%":Ev,"%Int8Array%":"undefined"==typeof Int8Array?undefined:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":_v?bv(bv([][Symbol.iterator]())):undefined,"%JSON%":"object"==typeof JSON?JSON:undefined,"%Map%":"undefined"==typeof Map?undefined:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&_v?bv((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&&_v?bv((new Set)[Symbol.iterator]()):undefined,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":_v?bv(""[Symbol.iterator]()):undefined,"%Symbol%":_v?Symbol:undefined,"%SyntaxError%":pv,"%ThrowTypeError%":yv,"%TypedArray%":wv,"%TypeError%":fv,"%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},Cv=function e(t){var r;if("%AsyncFunction%"===t)r=mv("async function () {}");else if("%GeneratorFunction%"===t)r=mv("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=mv("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&(r=bv(i.prototype))}return Sv[t]=r,r},Pv={"%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"]},Tv=ov,Rv=lv,kv=Tv.call(Function.call,Array.prototype.concat),Dv=Tv.call(Function.apply,Array.prototype.splice),Iv=Tv.call(Function.call,String.prototype.replace),Av=Tv.call(Function.call,String.prototype.slice),Ov=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Mv=/\\(\\)?/g,Nv=function(e){var t=Av(e,0,1),r=Av(e,-1);if("%"===t&&"%"!==r)throw new pv("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new pv("invalid intrinsic syntax, expected opening `%`");var n=[];return Iv(e,Ov,(function(e,t,r,i){n[n.length]=r?Iv(i,Mv,"$1"):t||e})),n},Lv=function(e,t){var r,n=e;if(Rv(Pv,n)&&(n="%"+(r=Pv[n])[0]+"%"),Rv(Sv,n)){var i=Sv[n];if(i===Ev&&(i=Cv(n)),void 0===i&&!t)throw new fv("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:i}}throw new pv("intrinsic "+e+" does not exist!")},xv=function(e,t){if("string"!=typeof e||0===e.length)throw new fv("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new fv('"allowMissing" argument must be a boolean');var r=Nv(e),n=r.length>0?r[0]:"",i=Lv("%"+n+"%",t),s=i.name,o=i.value,a=!1,c=i.alias;c&&(n=c[0],Dv(r,kv([0,1],c)));for(var d=1,u=!0;d<r.length;d+=1){var l=r[d],p=Av(l,0,1),h=Av(l,-1);if(('"'===p||"'"===p||"`"===p||'"'===h||"'"===h||"`"===h)&&p!==h)throw new pv("property names with quotes must have matching quotes");if("constructor"!==l&&u||(a=!0),Rv(Sv,s="%"+(n+="."+l)+"%"))o=Sv[s];else if(null!=o){if(!(l in o)){if(!t)throw new fv("base intrinsic for "+e+" exists, but the property is not available.");return}if(gv&&d+1>=r.length){var f=gv(o,l);o=(u=!!f)&&"get"in f&&!("originalValue"in f.get)?f.get:o[l]}else u=Rv(o,l),o=o[l];u&&!a&&(Sv[s]=o)}}return o},Fv={exports:{}};!function(e){var t=ov,r=xv,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}(Fv);var jv=xv,Uv=Fv.exports,Vv=Uv(jv("String.prototype.indexOf")),Bv=f(Object.freeze({__proto__:null,default:{}})),Wv="function"==typeof Map&&Map.prototype,Hv=Object.getOwnPropertyDescriptor&&Wv?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,qv=Wv&&Hv&&"function"==typeof Hv.get?Hv.get:null,zv=Wv&&Map.prototype.forEach,Gv="function"==typeof Set&&Set.prototype,Yv=Object.getOwnPropertyDescriptor&&Gv?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,$v=Gv&&Yv&&"function"==typeof Yv.get?Yv.get:null,Jv=Gv&&Set.prototype.forEach,Qv="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,Kv="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,Zv="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,Xv=Boolean.prototype.valueOf,ey=Object.prototype.toString,ty=Function.prototype.toString,ry=String.prototype.match,ny="function"==typeof BigInt?BigInt.prototype.valueOf:null,iy=Object.getOwnPropertySymbols,sy="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,oy="function"==typeof Symbol&&"object"==typeof Symbol.iterator,ay=Object.prototype.propertyIsEnumerable,cy=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null),dy=Bv.custom,uy=dy&&my(dy)?dy:null,ly="function"==typeof Symbol&&void 0!==Symbol.toStringTag?Symbol.toStringTag:null;function py(e,t,r){var n="double"===(r.quoteStyle||t)?'"':"'";return n+e+n}function hy(e){return String(e).replace(/"/g,""")}function fy(e){return!("[object Array]"!==yy(e)||ly&&"object"==typeof e&&ly in e)}function my(e){if(oy)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!sy)return!1;try{return sy.call(e),!0}catch(e){}return!1}var gy=Object.prototype.hasOwnProperty||function(e){return e in this};function vy(e,t){return gy.call(e,t)}function yy(e){return ey.call(e)}function _y(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 by(e,t){if(e.length>t.maxStringLength){var r=e.length-t.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return by(e.slice(0,t.maxStringLength),t)+n}return py(e.replace(/(['\\])/g,"\\$1").replace(/[\x00-\x1f]/g,Ey),"single",t)}function Ey(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 wy(e){return"Object("+e+")"}function Sy(e){return e+" { ? }"}function Cy(e,t,r,n){return e+" ("+t+") {"+(n?Py(r,n):r.join(", "))+"}"}function Py(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+e.join(","+r)+"\n"+t.prev}function Ty(e,t){var r=fy(e),n=[];if(r){n.length=e.length;for(var i=0;i<e.length;i++)n[i]=vy(e,i)?t(e[i],e):""}var s,o="function"==typeof iy?iy(e):[];if(oy){s={};for(var a=0;a<o.length;a++)s["$"+o[a]]=o[a]}for(var c in e)vy(e,c)&&(r&&String(Number(c))===c&&c<e.length||oy&&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 iy)for(var d=0;d<o.length;d++)ay.call(e,o[d])&&n.push("["+t(o[d])+"]: "+t(e[o[d]],e));return n}var Ry=xv,ky=function(e,t){var r=jv(e,!!t);return"function"==typeof r&&Vv(e,".prototype.")>-1?Uv(r):r},Dy=function e(t,r,n,i){var s=r||{};if(vy(s,"quoteStyle")&&"single"!==s.quoteStyle&&"double"!==s.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(vy(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=!vy(s,"customInspect")||s.customInspect;if("boolean"!=typeof o&&"symbol"!==o)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(vy(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 by(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 fy(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(_y(i,t)>=0)return"[Circular]";function d(t,r,o){if(r&&(i=i.slice()).push(r),o){var a={depth:s.depth};return vy(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=ry.call(ty.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),l=Ty(t,d);return"[Function"+(u?": "+u:" (anonymous)")+"]"+(l.length>0?" { "+l.join(", ")+" }":"")}if(my(t)){var p=oy?String(t).replace(/^(Symbol\(.*\))_[^)]*$/,"$1"):sy.call(t);return"object"!=typeof t||oy?p:wy(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+"="+py(hy(f[m].value),"double",s);return h+=">",t.childNodes&&t.childNodes.length&&(h+="..."),h+="</"+String(t.nodeName).toLowerCase()+">"}if(fy(t)){if(0===t.length)return"[]";var g=Ty(t,d);return c&&!function(e){for(var t=0;t<e.length;t++)if(_y(e[t],"\n")>=0)return!1;return!0}(g)?"["+Py(g,c)+"]":"[ "+g.join(", ")+" ]"}if(function(e){return!("[object Error]"!==yy(e)||ly&&"object"==typeof e&&ly in e)}(t)){var v=Ty(t,d);return 0===v.length?"["+String(t)+"]":"{ ["+String(t)+"] "+v.join(", ")+" }"}if("object"==typeof t&&o){if(uy&&"function"==typeof t[uy])return t[uy]();if("symbol"!==o&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!qv||!e||"object"!=typeof e)return!1;try{qv.call(e);try{$v.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var y=[];return zv.call(t,(function(e,r){y.push(d(r,t,!0)+" => "+d(e,t))})),Cy("Map",qv.call(t),y,c)}if(function(e){if(!$v||!e||"object"!=typeof e)return!1;try{$v.call(e);try{qv.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var _=[];return Jv.call(t,(function(e){_.push(d(e,t))})),Cy("Set",$v.call(t),_,c)}if(function(e){if(!Qv||!e||"object"!=typeof e)return!1;try{Qv.call(e,Qv);try{Kv.call(e,Kv)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Sy("WeakMap");if(function(e){if(!Kv||!e||"object"!=typeof e)return!1;try{Kv.call(e,Kv);try{Qv.call(e,Qv)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Sy("WeakSet");if(function(e){if(!Zv||!e||"object"!=typeof e)return!1;try{return Zv.call(e),!0}catch(e){}return!1}(t))return Sy("WeakRef");if(function(e){return!("[object Number]"!==yy(e)||ly&&"object"==typeof e&&ly in e)}(t))return wy(d(Number(t)));if(function(e){if(!e||"object"!=typeof e||!ny)return!1;try{return ny.call(e),!0}catch(e){}return!1}(t))return wy(d(ny.call(t)));if(function(e){return!("[object Boolean]"!==yy(e)||ly&&"object"==typeof e&&ly in e)}(t))return wy(Xv.call(t));if(function(e){return!("[object String]"!==yy(e)||ly&&"object"==typeof e&&ly in e)}(t))return wy(d(String(t)));if(!function(e){return!("[object Date]"!==yy(e)||ly&&"object"==typeof e&&ly in e)}(t)&&!function(e){return!("[object RegExp]"!==yy(e)||ly&&"object"==typeof e&&ly in e)}(t)){var b=Ty(t,d),E=cy?cy(t)===Object.prototype:t instanceof Object||t.constructor===Object,w=t instanceof Object?"":"null prototype",S=!E&&ly&&Object(t)===t&&ly in t?yy(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+"{"+Py(b,c)+"}":C+"{ "+b.join(", ")+" }"}return String(t)},Iy=Ry("%TypeError%"),Ay=Ry("%WeakMap%",!0),Oy=Ry("%Map%",!0),My=ky("WeakMap.prototype.get",!0),Ny=ky("WeakMap.prototype.set",!0),Ly=ky("WeakMap.prototype.has",!0),xy=ky("Map.prototype.get",!0),Fy=ky("Map.prototype.set",!0),jy=ky("Map.prototype.has",!0),Uy=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},Vy=String.prototype.replace,By=/%20/g,Wy="RFC3986",Hy={default:Wy,formatters:{RFC1738:function(e){return Vy.call(e,By,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:Wy},qy=Hy,zy=Object.prototype.hasOwnProperty,Gy=Array.isArray,Yy=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),$y=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},Jy={arrayToObject:$y,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(Gy(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===qy.RFC1738&&(40===c||41===c)?o+=s.charAt(a):c<128?o+=Yy[c]:c<2048?o+=Yy[192|c>>6]+Yy[128|63&c]:c<55296||c>=57344?o+=Yy[224|c>>12]+Yy[128|c>>6&63]+Yy[128|63&c]:(a+=1,c=65536+((1023&c)<<10|1023&s.charCodeAt(a)),o+=Yy[240|c>>18]+Yy[128|c>>12&63]+Yy[128|c>>6&63]+Yy[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(Gy(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(Gy(t))t.push(r);else{if(!t||"object"!=typeof t)return[t,r];(n&&(n.plainObjects||n.allowPrototypes)||!zy.call(Object.prototype,r))&&(t[r]=!0)}return t}if(!t||"object"!=typeof t)return[t].concat(r);var i=t;return Gy(t)&&!Gy(r)&&(i=$y(t,n)),Gy(t)&&Gy(r)?(r.forEach((function(r,i){if(zy.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 zy.call(t,i)?t[i]=e(t[i],s,n):t[i]=s,t}),i)}},Qy=function(){var e,t,r,n={assert:function(e){if(!n.has(e))throw new Iy("Side channel does not contain "+Dy(e))},get:function(n){if(Ay&&n&&("object"==typeof n||"function"==typeof n)){if(e)return My(e,n)}else if(Oy){if(t)return xy(t,n)}else if(r)return function(e,t){var r=Uy(e,t);return r&&r.value}(r,n)},has:function(n){if(Ay&&n&&("object"==typeof n||"function"==typeof n)){if(e)return Ly(e,n)}else if(Oy){if(t)return jy(t,n)}else if(r)return function(e,t){return!!Uy(e,t)}(r,n);return!1},set:function(n,i){Ay&&n&&("object"==typeof n||"function"==typeof n)?(e||(e=new Ay),Ny(e,n,i)):Oy?(t||(t=new Oy),Fy(t,n,i)):(r||(r={key:{},next:null}),function(e,t,r){var n=Uy(e,t);n?n.value=r:e.next={key:t,next:e.next,value:r}}(r,n,i))}};return n},Ky=Jy,Zy=Hy,Xy=Object.prototype.hasOwnProperty,e_={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},t_=Array.isArray,r_=String.prototype.split,n_=Array.prototype.push,i_=function(e,t){n_.apply(e,t_(t)?t:[t])},s_=Date.prototype.toISOString,o_=Zy.default,a_={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:Ky.encode,encodeValuesOnly:!1,format:o_,formatter:Zy.formatters[o_],indices:!1,serializeDate:function(e){return s_.call(e)},skipNulls:!1,strictNullHandling:!1},c_={},d_=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(c_))&&!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(c_)&&(_=0)}if("function"==typeof c?v=c(r,v):v instanceof Date?v=l(v):"comma"===n&&t_(v)&&(v=Ky.maybeMap(v,(function(e){return e instanceof Date?l(e):e}))),null===v){if(s)return a&&!f?a(r,a_.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)||Ky.isBuffer(v)){if(a){var w=f?r:a(r,a_.encoder,m,"key",p);if("comma"===n&&f){for(var S=r_.call(String(v),","),C="",P=0;P<S.length;++P)C+=(0===P?"":",")+h(a(S[P],a_.encoder,m,"value",p));return[h(w)+(i&&t_(v)&&1===S.length?"[]":"")+"="+C]}return[h(w)+"="+h(a(v,a_.encoder,m,"value",p))]}return[h(r)+"="+h(String(v))]}var T,R=[];if(void 0===v)return R;if("comma"===n&&t_(v))T=[{value:v.length>0?v.join(",")||null:void 0}];else if(t_(c))T=c;else{var k=Object.keys(v);T=d?k.sort(d):k}for(var D=i&&t_(v)&&1===v.length?r+"[]":r,I=0;I<T.length;++I){var A=T[I],O="object"==typeof A&&void 0!==A.value?A.value:v[A];if(!o||null!==O){var M=t_(v)?"function"==typeof n?n(D,A):D:D+(u?"."+A:"["+A+"]");g.set(t,_);var N=Qy();N.set(c_,g),i_(R,e(O,M,n,i,s,o,a,c,d,u,l,p,h,f,m,N))}}return R},u_=Jy,l_=Object.prototype.hasOwnProperty,p_=Array.isArray,h_={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:u_.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},f_=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},m_=function(e,t){return e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1?e.split(","):e},g_=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&&l_.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&&l_.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:m_(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)}},v_=function(e,t){var r,n=e,i=function(e){if(!e)return a_;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||a_.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=Zy.default;if(void 0!==e.format){if(!Xy.call(Zy.formatters,e.format))throw new TypeError("Unknown format option provided.");r=e.format}var n=Zy.formatters[r],i=a_.filter;return("function"==typeof e.filter||t_(e.filter))&&(i=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:a_.addQueryPrefix,allowDots:void 0===e.allowDots?a_.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:a_.charsetSentinel,delimiter:void 0===e.delimiter?a_.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:a_.encode,encoder:"function"==typeof e.encoder?e.encoder:a_.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:a_.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:a_.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:a_.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:a_.strictNullHandling}}(t);"function"==typeof i.filter?n=(0,i.filter)("",n):t_(i.filter)&&(r=i.filter);var s,o=[];if("object"!=typeof n||null===n)return"";s=t&&t.arrayFormat in e_?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var a=e_[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=Qy(),u=0;u<r.length;++u){var l=r[u];i.skipNulls&&null===n[l]||i_(o,d_(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:""},y_=function(e,t){var r=function(e){if(!e)return h_;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?h_.charset:e.charset;return{allowDots:void 0===e.allowDots?h_.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:h_.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:h_.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:h_.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:h_.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:h_.comma,decoder:"function"==typeof e.decoder?e.decoder:h_.decoder,delimiter:"string"==typeof e.delimiter||u_.isRegExp(e.delimiter)?e.delimiter:h_.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:h_.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:h_.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:h_.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:h_.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:h_.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,h_.decoder,c,"key"),u=t.strictNullHandling?null:""):(d=t.decoder(l.slice(0,h),h_.decoder,c,"key"),u=u_.maybeMap(m_(l.slice(h+1),t),(function(e){return t.decoder(e,h_.decoder,c,"value")}))),u&&t.interpretNumericEntities&&"iso-8859-1"===c&&(u=f_(u)),l.indexOf("[]=")>-1&&(u=p_(u)?[u]:u),l_.call(n,d)?n[d]=u_.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=g_(a,n[a],r,"string"==typeof e);i=u_.merge(i,c,r)}return!0===r.allowSparse?i:u_.compact(i)},__={formats:Hy,parse:y_,stringify:v_};class b_{constructor(e){this.api=e,Fs(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 c(this,void 0,void 0,(function*(){yield this.api.post("/log/batch",e)}))}}class E_{constructor(e){this.api=e,Fs(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 c(this,void 0,void 0,(function*(){yield this.api.post("/analytics/network-metrics",e)}))}sendWIDMetrics(e){return c(this,void 0,void 0,(function*(){yield this.api.post("/analytics/wid-metrics",Object.assign({},e))}))}}let w_=class{constructor(){this.api=Za.create({baseURL:"https://moodhood-analytics.livedigital.space/v1",timeout:1e4,withCredentials:!0,paramsSerializer:e=>__.stringify(e),headers:{"x-cl-id":If()}}),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 b_(this.api),this.metricsApi=new E_(this.api)}get log(){return this.logApi}get metrics(){return this.metricsApi}};w_=s([ct(),a("design:paramtypes",[])],w_);var S_=w_,C_={exports:{}},P_=1e3,T_=60*P_,R_=60*T_,k_=24*R_,D_=7*k_,I_=365.25*k_,A_=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*I_;case"weeks":case"week":case"w":return r*D_;case"days":case"day":case"d":return r*k_;case"hours":case"hour":case"hrs":case"hr":case"h":return r*R_;case"minutes":case"minute":case"mins":case"min":case"m":return r*T_;case"seconds":case"second":case"secs":case"sec":case"s":return r*P_;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>=k_)return O_(e,t,k_,"day");if(t>=R_)return O_(e,t,R_,"hour");if(t>=T_)return O_(e,t,T_,"minute");if(t>=P_)return O_(e,t,P_,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=k_)return Math.round(e/k_)+"d";if(t>=R_)return Math.round(e/R_)+"h";if(t>=T_)return Math.round(e/T_)+"m";if(t>=P_)return Math.round(e/P_)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function O_(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}var M_=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=A_,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=M_(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(C_,C_.exports);var N_=C_.exports,L_={},x_={},F_={},j_={exports:{}};
|
|
29
|
+
***************************************************************************** */!function(e){!function(t){var r="object"==typeof globalThis?globalThis:"object"==typeof p?p:"object"==typeof self?self:"object"==typeof this?this:function(){try{return Function("return this;")()}catch(e){}}()||function(){try{return(0,eval)("(function() { return this; })()")}catch(e){}}(),n=i(e);function i(e,t){return function(r,n){Object.defineProperty(e,r,{configurable:!0,writable:!0,value:n}),t&&t(r,n)}}void 0!==r.Reflect&&(n=i(r.Reflect,n)),function(e,t){var r=Object.prototype.hasOwnProperty,n="function"==typeof Symbol,i=n&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",s=n&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",o="function"==typeof Object.create,a={__proto__:[]}instanceof Array,c=!o&&!a,d={create:o?function(){return le(Object.create(null))}:a?function(){return le({__proto__:null})}:function(){return le({})},has:c?function(e,t){return r.call(e,t)}:function(e,t){return t in e},get:c?function(e,t){return r.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},u=Object.getPrototypeOf(Function),l="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:ce(),p="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:de(),h="function"==typeof WeakMap?WeakMap:ue(),f=n?Symbol.for("@reflect-metadata:registry"):void 0,m=ie(),g=se(m);function v(e,t,r,n){if(F(r)){if(!G(e))throw new TypeError;if(!$(t))throw new TypeError;return R(e,t)}if(!G(e))throw new TypeError;if(!V(t))throw new TypeError;if(!V(n)&&!F(n)&&!j(n))throw new TypeError;return j(n)&&(n=void 0),k(e,t,r=z(r),n)}function y(e,t){function r(r,n){if(!V(r))throw new TypeError;if(!F(n)&&!J(n))throw new TypeError;M(e,t,r,n)}return r}function _(e,t,r,n){if(!V(r))throw new TypeError;return F(n)||(n=z(n)),M(e,t,r,n)}function b(e,t,r){if(!V(t))throw new TypeError;return F(r)||(r=z(r)),D(e,t,r)}function E(e,t,r){if(!V(t))throw new TypeError;return F(r)||(r=z(r)),I(e,t,r)}function w(e,t,r){if(!V(t))throw new TypeError;return F(r)||(r=z(r)),A(e,t,r)}function S(e,t,r){if(!V(t))throw new TypeError;return F(r)||(r=z(r)),O(e,t,r)}function C(e,t){if(!V(e))throw new TypeError;return F(t)||(t=z(t)),N(e,t)}function P(e,t){if(!V(e))throw new TypeError;return F(t)||(t=z(t)),L(e,t)}function T(e,t,r){if(!V(t))throw new TypeError;if(F(r)||(r=z(r)),!V(t))throw new TypeError;F(r)||(r=z(r));var n=ae(t,r,!1);return!F(n)&&n.OrdinaryDeleteMetadata(e,t,r)}function R(e,t){for(var r=e.length-1;r>=0;--r){var n=(0,e[r])(t);if(!F(n)&&!j(n)){if(!$(n))throw new TypeError;t=n}}return t}function k(e,t,r,n){for(var i=e.length-1;i>=0;--i){var s=(0,e[i])(t,r,n);if(!F(s)&&!j(s)){if(!V(s))throw new TypeError;n=s}}return n}function D(e,t,r){if(I(e,t,r))return!0;var n=re(t);return!j(n)&&D(e,n,r)}function I(e,t,r){var n=ae(t,r,!1);return!F(n)&&H(n.OrdinaryHasOwnMetadata(e,t,r))}function A(e,t,r){if(I(e,t,r))return O(e,t,r);var n=re(t);return j(n)?void 0:A(e,n,r)}function O(e,t,r){var n=ae(t,r,!1);if(!F(n))return n.OrdinaryGetOwnMetadata(e,t,r)}function M(e,t,r,n){ae(r,n,!0).OrdinaryDefineOwnMetadata(e,t,r,n)}function N(e,t){var r=L(e,t),n=re(e);if(null===n)return r;var i=N(n,t);if(i.length<=0)return r;if(r.length<=0)return i;for(var s=new p,o=[],a=0,c=r;a<c.length;a++){var d=c[a];s.has(d)||(s.add(d),o.push(d))}for(var u=0,l=i;u<l.length;u++){d=l[u];s.has(d)||(s.add(d),o.push(d))}return o}function L(e,t){var r=ae(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function x(e){if(null===e)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===e?1:6;default:return 6}}function F(e){return void 0===e}function j(e){return null===e}function U(e){return"symbol"==typeof e}function V(e){return"object"==typeof e?null!==e:"function"==typeof e}function B(e,t){switch(x(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var r=3===t?"string":5===t?"number":"default",n=K(e,i);if(void 0!==n){var s=n.call(e,r);if(V(s))throw new TypeError;return s}return W(e,"default"===r?"number":r)}function W(e,t){if("string"===t){var r=e.toString;if(Y(r))if(!V(i=r.call(e)))return i;if(Y(n=e.valueOf))if(!V(i=n.call(e)))return i}else{var n;if(Y(n=e.valueOf))if(!V(i=n.call(e)))return i;var i,s=e.toString;if(Y(s))if(!V(i=s.call(e)))return i}throw new TypeError}function H(e){return!!e}function q(e){return""+e}function z(e){var t=B(e,3);return U(t)?t:q(t)}function G(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function Y(e){return"function"==typeof e}function $(e){return"function"==typeof e}function J(e){switch(x(e)){case 3:case 4:return!0;default:return!1}}function Q(e,t){return e===t||e!=e&&t!=t}function K(e,t){var r=e[t];if(null!=r){if(!Y(r))throw new TypeError;return r}}function Z(e){var t=K(e,s);if(!Y(t))throw new TypeError;var r=t.call(e);if(!V(r))throw new TypeError;return r}function X(e){return e.value}function ee(e){var t=e.next();return!t.done&&t}function te(e){var t=e.return;t&&t.call(e)}function re(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===u)return t;if(t!==u)return t;var r=e.prototype,n=r&&Object.getPrototypeOf(r);if(null==n||n===Object.prototype)return t;var i=n.constructor;return"function"!=typeof i||i===e?t:i}function ne(){var e,r,n,i;F(f)||void 0===t.Reflect||f in t.Reflect||"function"!=typeof t.Reflect.defineMetadata||(e=oe(t.Reflect));var s=new h,o={registerProvider:a,getProvider:d,setProvider:m};return o;function a(t){if(!Object.isExtensible(o))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===t:break;case F(r):r=t;break;case r===t:break;case F(n):n=t;break;case n===t:break;default:void 0===i&&(i=new p),i.add(t)}}function c(t,s){if(!F(r)){if(r.isProviderFor(t,s))return r;if(!F(n)){if(n.isProviderFor(t,s))return r;if(!F(i))for(var o=Z(i);;){var a=ee(o);if(!a)return;var c=X(a);if(c.isProviderFor(t,s))return te(o),c}}}if(!F(e)&&e.isProviderFor(t,s))return e}function d(e,t){var r,n=s.get(e);return F(n)||(r=n.get(t)),F(r)?(F(r=c(e,t))||(F(n)&&(n=new l,s.set(e,n)),n.set(t,r)),r):r}function u(e){if(F(e))throw new TypeError;return r===e||n===e||!F(i)&&i.has(e)}function m(e,t,r){if(!u(r))throw new Error("Metadata provider not registered.");var n=d(e,t);if(n!==r){if(!F(n))return!1;var i=s.get(e);F(i)&&(i=new l,s.set(e,i)),i.set(t,r)}return!0}}function ie(){var e;return!F(f)&&V(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[f]),F(e)&&(e=ne()),!F(f)&&V(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,f,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function se(e){var t=new h,r={isProviderFor:function(e,r){var n=t.get(e);return!F(n)&&n.has(r)},OrdinaryDefineOwnMetadata:o,OrdinaryHasOwnMetadata:i,OrdinaryGetOwnMetadata:s,OrdinaryOwnMetadataKeys:a,OrdinaryDeleteMetadata:c};return m.registerProvider(r),r;function n(n,i,s){var o=t.get(n),a=!1;if(F(o)){if(!s)return;o=new l,t.set(n,o),a=!0}var c=o.get(i);if(F(c)){if(!s)return;if(c=new l,o.set(i,c),!e.setProvider(n,i,r))throw o.delete(i),a&&t.delete(n),new Error("Wrong provider for target.")}return c}function i(e,t,r){var i=n(t,r,!1);return!F(i)&&H(i.has(e))}function s(e,t,r){var i=n(t,r,!1);if(!F(i))return i.get(e)}function o(e,t,r,i){n(r,i,!0).set(e,t)}function a(e,t){var r=[],i=n(e,t,!1);if(F(i))return r;for(var s=Z(i.keys()),o=0;;){var a=ee(s);if(!a)return r.length=o,r;var c=X(a);try{r[o]=c}catch(e){try{te(s)}finally{throw e}}o++}}function c(e,r,i){var s=n(r,i,!1);if(F(s))return!1;if(!s.delete(e))return!1;if(0===s.size){var o=t.get(r);F(o)||(o.delete(i),0===o.size&&t.delete(o))}return!0}}function oe(e){var t=e.defineMetadata,r=e.hasOwnMetadata,n=e.getOwnMetadata,i=e.getOwnMetadataKeys,s=e.deleteMetadata,o=new h,a={isProviderFor:function(e,t){var r=o.get(e);return!(F(r)||!r.has(t))||!!i(e,t).length&&(F(r)&&(r=new p,o.set(e,r)),r.add(t),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:n,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:s};return a}function ae(e,t,r){var n=m.getProvider(e,t);if(!F(n))return n;if(r){if(m.setProvider(e,t,g))return g;throw new Error("Illegal state.")}}function ce(){var e={},t=[],r=function(){function e(e,t,r){this._index=0,this._keys=e,this._values=t,this._selector=r}return e.prototype["@@iterator"]=function(){return this},e.prototype[s]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var r=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:r,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}(),n=function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var r=this._find(e,!0);return this._values[r]=t,this},t.prototype.delete=function(t){var r=this._find(t,!1);if(r>=0){for(var n=this._keys.length,i=r+1;i<n;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,Q(t,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new r(this._keys,this._values,i)},t.prototype.values=function(){return new r(this._keys,this._values,o)},t.prototype.entries=function(){return new r(this._keys,this._values,a)},t.prototype["@@iterator"]=function(){return this.entries()},t.prototype[s]=function(){return this.entries()},t.prototype._find=function(e,t){if(!Q(this._cacheKey,e)){this._cacheIndex=-1;for(var r=0;r<this._keys.length;r++)if(Q(this._keys[r],e)){this._cacheIndex=r;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();return n;function i(e,t){return e}function o(e,t){return t}function a(e,t){return[e,t]}}function de(){return function(){function e(){this._map=new l}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[s]=function(){return this.keys()},e}()}function ue(){var e=16,t=d.create(),n=i();return function(){function e(){this._key=i()}return e.prototype.has=function(e){var t=s(e,!1);return void 0!==t&&d.has(t,this._key)},e.prototype.get=function(e){var t=s(e,!1);return void 0!==t?d.get(t,this._key):void 0},e.prototype.set=function(e,t){return s(e,!0)[this._key]=t,this},e.prototype.delete=function(e){var t=s(e,!1);return void 0!==t&&delete t[this._key]},e.prototype.clear=function(){this._key=i()},e}();function i(){var e;do{e="@@WeakMap@@"+c()}while(d.has(t,e));return t[e]=!0,e}function s(e,t){if(!r.call(e,n)){if(!t)return;Object.defineProperty(e,n,{value:d.create()})}return e[n]}function o(e,t){for(var r=0;r<t;++r)e[r]=255*Math.random()|0;return e}function a(e){if("function"==typeof Uint8Array){var t=new Uint8Array(e);return"undefined"!=typeof crypto?crypto.getRandomValues(t):"undefined"!=typeof msCrypto?msCrypto.getRandomValues(t):o(t,e),t}return o(new Array(e),e)}function c(){var t=a(e);t[6]=79&t[6]|64,t[8]=191&t[8]|128;for(var r="",n=0;n<e;++n){var i=t[n];4!==n&&6!==n&&8!==n||(r+="-"),i<16&&(r+="0"),r+=i.toString(16).toLowerCase()}return r}}function le(e){return e.__=void 0,delete e.__,e}e("decorate",v),e("metadata",y),e("defineMetadata",_),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)}()}(l||(l={}));var m=["inject","multi_inject","name","unmanaged","named","optional"],g="Request",v="Singleton",y="Transient",_="ConstantValue",b="Constructor",E="DynamicValue",w="Factory",S="Function",C="Instance",P="Invalid",T="Provider",R="ClassProperty",k="ConstructorArgument",D="Variable",I=0;function A(){return I++}var O=function(){function e(e,t){this.id=A(),this.activated=!1,this.serviceIdentifier=e,this.scope=t,this.type=P,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===v&&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}(),M="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.",L=function(e,t){return"onDeactivation() error in class "+e+": "+t},x=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}(),F=0,j=1;function U(e){return e instanceof RangeError||"Maximum call stack size exceeded"===e.message}function V(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=q(e.implementationType)),n=n+"\n "+t,e.constraint.metaData&&(n=n+" - "+e.constraint.metaData)}))),n}function W(e,t){return null!==e.parentRequest&&(e.parentRequest.serviceIdentifier===t||W(e.parentRequest,t))}function H(e){e.childRequests.forEach((function(e){if(W(e,e.serviceIdentifier)){var t=function(e){return function e(t,r){void 0===r&&(r=[]);var n=V(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)}H(e)}))}function q(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 z=function(){function e(e){this.id=A(),this.container=e}return e.prototype.addPlan=function(e){this.plan=e},e.prototype.setCurrentRequest=function(e){this.currentRequest=e},e}(),G=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}(),Y=function(e,t){this.parentContext=e,this.rootRequest=t},$=function(){function e(e){this._cb=e}return e.prototype.unwrap=function(){return this._cb()},e}(),J=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}(),Q=function(){function e(e,t,r,n){this.id=A(),this.type=e,this.serviceIdentifier=r;var i="symbol"==typeof t?function(e){return e.toString().slice(7,-1)}(t):t;this.name=new J(i||""),this.identifier=t,this.metadata=new Array;var s=null;"string"==typeof n?s=new G("named",n):n instanceof G&&(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 m.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 m.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 Z(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=X(o,e,t,r,n);null!==a&&s.push(a)}return s}(n,t,s,o,c||d?a.length:r.length),l=te(e,r,t);return K(K([],u,!0),l,!0)}function X(e,t,r,n,i){var s=i[e.toString()]||[],o=ne(s),a=!0!==o.unmanaged,c=n[e],d=o.inject||o.multiInject;if((c=d||c)instanceof $&&(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 Q(k,o.targetName,c);return u.metadata=s,u}return null}function ee(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 te(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=ne(d),l=u.targetName||c,p=ee(u.inject,u.multiInject,c,r),h=new Q(R,l,p);h.metadata=d,i.push(h)}var f=Object.getPrototypeOf(t.prototype).constructor;if(f!==Object){var m=te(e,f,r);i=K(K([],i,!0),m,!0)}return i}function re(e,t){var r=Object.getPrototypeOf(t.prototype).constructor;if(r!==Object){var n=Z(e,q(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:re(e,r)}return 0}function ne(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 ie=function(){function e(e,t,r,n,i){this.id=A(),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 se(e){return e._bindingDictionary}function oe(e,t,r,n,i){var s=ce(r.container,i.serviceIdentifier),o=[];return s.length===F&&r.container.options.autoBindInjectable&&"function"==typeof i.serviceIdentifier&&e.getConstructorMetadata(i.serviceIdentifier).compilerGeneratedMetadata&&(r.container.bind(i.serviceIdentifier).toSelf(),s=ce(r.container,i.serviceIdentifier)),o=t?s:s.filter((function(e){var t=new ie(e.serviceIdentifier,r,n,e,i);return e.constraint(t)})),function(e,t,r,n){switch(t.length){case F:if(r.isOptional())return t;var i=V(e),s=M;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,ce),new Error(s);case j:return t;default:if(r.isArray())return t;s="Ambiguous match found for serviceIdentifier: "+(i=V(e));throw s+=B(n,i,ce),new Error(s)}}(i.serviceIdentifier,o,i,r.container),o}function ae(e,t,r,n,i,s){var o,a;if(null===i){o=oe(e,t,n,null,s),a=new ie(r,n,null,o,s);var c=new Y(n,a);n.addPlan(c)}else o=oe(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===C&&null!==t.implementationType){var i=function(e,t){return Z(e,q(t),t,!1)}(e,t.implementationType);if(!n.container.options.skipBaseClassChecks){var o=re(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."}(q(t.implementationType));throw new Error(c)}}i.forEach((function(t){ae(e,!1,t.serviceIdentifier,n,r,t)}))}}))}function ce(e,t){var r=[],n=se(e);return n.hasKey(t)?r=n.get(t):null!==e.parent&&(r=ce(e.parent,t)),r}function de(e,t,r,n,i,s,o,a){void 0===a&&(a=!1);var c=new z(t),d=function(e,t,r,n,i,s){var o=new G(e?"multi_inject":"inject",r),a=new Q(t,n,r,o);if(void 0!==i){var c=new G(i,s);a.metadata.push(c)}return a}(r,n,i,"",s,o);try{return ae(e,a,i,c,null,d),c}catch(e){throw U(e)&&H(c.plan.rootRequest),e}}function ue(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&"function"==typeof e.then}function le(e){return!!ue(e)||Array.isArray(e)&&e.some(ue)}var pe,he=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},fe=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])}}},me=function(e,t,r){e.has(t.id)||e.set(t.id,r)},ge=function(e,t){e.cache=t,e.activated=!0,ue(t)&&ve(e,t)},ve=function(e,t){return he(void 0,void 0,void 0,(function(){var r,n;return fe(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"}(pe||(pe={}));var ye=function(){return ye=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},ye.apply(this,arguments)},_e=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},be=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])}}},Ee=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 we(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=le(n)),e}),{constructorInjections:[],propertyInjections:[],propertyRequests:[],isAsync:!1})}(t,r),s=ye(ye({},i),{constr:e});n=i.isAsync?function(e){return _e(this,void 0,void 0,(function(){var t,r;return be(this,(function(n){switch(n.label){case 0:return[4,Ce(e.constructorInjections)];case 1:return t=n.sent(),[4,Ce(e.propertyInjections)];case 2:return r=n.sent(),[2,Se(ye(ye({},e),{constructorInjections:t,propertyInjections:r}))]}}))}))}(s):Se(s)}else n=new e;return n}function Se(e){var t,r=new((t=e.constr).bind.apply(t,Ee([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 Ce(e){return _e(this,void 0,void 0,(function(){var t,r,n,i;return be(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 Pe(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 ue(r)?r.then((function(){return t})):t}function Te(e,t){e.scope!==v&&function(e,t){var r="Class cannot be instantiated in "+(e.scope===g?"request":"transient")+" scope.";if("function"==typeof e.onDeactivation)throw new Error(L(t.name,r));if(Reflect.hasMetadata("pre_destroy",t))throw new Error("@preDestroy error in class "+t.name+": "+r)}(e,t)}var Re=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},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])}}},De=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 De(e)(t)}));if(!t.target.isOptional()||0!==r.length){var o=r[0];return Me(e,t,o)}}},Ie=function(e,t){var r=function(e){switch(e.type){case w:return{factory:e.factory,factoryType:pe.Factory};case T:return{factory:e.provider,factoryType:pe.Provider};case E:return{factory:e.dynamicValue,factoryType:pe.DynamicValue};default:throw new Error("Unexpected factory type "+e.type)}}(e);return function(e,t){try{return e()}catch(e){throw U(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}))},Ae=function(e,t,r){var n,i=t.childRequests;switch(function(e){var t=null;switch(e.type){case _:case S:t=e.cache;break;case b:case C:t=e.implementationType;break;case E:t=e.dynamicValue;break;case T:t=e.provider;break;case w:t=e.factory}if(null===t){var r=V(e.serviceIdentifier);throw new Error("Invalid binding type: "+r)}}(r),r.type){case _:case S:n=r.cache;break;case b:n=r.implementationType;break;case C:n=function(e,t,r,n){Te(e,t);var i=we(t,r,n);return ue(i)?i.then((function(e){return Pe(t,e)})):Pe(t,i)}(r,r.implementationType,i,De(e));break;default:n=Ie(r,t.parentContext)}return n},Oe=function(e,t,r){var n=function(e,t){return t.scope===v&&t.activated?t.cache:t.scope===g&&e.has(t.id)?e.get(t.id):null}(e,t);return null!==n||function(e,t,r){t.scope===v&&ge(t,r),t.scope===g&&me(e,t,r)}(e,t,n=r()),n},Me=function(e,t,r){return Oe(e,r,(function(){var n=Ae(e,t,r);return n=ue(n)?n.then((function(e){return Ne(t,r,e)})):Ne(t,r,n)}))};function Ne(e,t,r){var n,i=Le(e.parentContext,t,r),s=Ue(e.parentContext.container),o=s.next();do{n=o.value;var a=e.parentContext,c=e.serviceIdentifier,d=je(n,c);i=ue(i)?Fe(d,a,i):xe(d,a,i),o=s.next()}while(!0!==o.done&&!se(n).hasKey(e.serviceIdentifier));return i}var Le=function(e,t,r){return"function"==typeof t.onActivation?t.onActivation(e,r):r},xe=function(e,t,r){for(var n=e.next();!n.done;){if(ue(r=n.value(t,r)))return Fe(e,t,r);n=e.next()}return r},Fe=function(e,t,r){return Re(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]}}))}))},je=function(e,t){var r=e._activations;return r.hasKey(t)?r.get(t).values():[].values()},Ue=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 Ve=function(e,t){var r=e.parentRequest;return null!==r&&(!!t(r)||Ve(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 G(e,t),r}},We=Be("named"),He=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}},qe=function(){function e(e){this._binding=e}return e.prototype.when=function(e){return this._binding.constraint=e,new ze(this._binding)},e.prototype.whenTargetNamed=function(e){return this._binding.constraint=We(e),new ze(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 ze(this._binding)},e.prototype.whenTargetTagged=function(e,t){return this._binding.constraint=Be(e)(t),new ze(this._binding)},e.prototype.whenInjectedInto=function(e){return this._binding.constraint=function(t){return null!==t&&He(e)(t.parentRequest)},new ze(this._binding)},e.prototype.whenParentNamed=function(e){return this._binding.constraint=function(t){return null!==t&&We(e)(t.parentRequest)},new ze(this._binding)},e.prototype.whenParentTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&Be(e)(t)(r.parentRequest)},new ze(this._binding)},e.prototype.whenAnyAncestorIs=function(e){return this._binding.constraint=function(t){return null!==t&&Ve(t,He(e))},new ze(this._binding)},e.prototype.whenNoAncestorIs=function(e){return this._binding.constraint=function(t){return null!==t&&!Ve(t,He(e))},new ze(this._binding)},e.prototype.whenAnyAncestorNamed=function(e){return this._binding.constraint=function(t){return null!==t&&Ve(t,We(e))},new ze(this._binding)},e.prototype.whenNoAncestorNamed=function(e){return this._binding.constraint=function(t){return null!==t&&!Ve(t,We(e))},new ze(this._binding)},e.prototype.whenAnyAncestorTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&Ve(r,Be(e)(t))},new ze(this._binding)},e.prototype.whenNoAncestorTagged=function(e,t){return this._binding.constraint=function(r){return null!==r&&!Ve(r,Be(e)(t))},new ze(this._binding)},e.prototype.whenAnyAncestorMatches=function(e){return this._binding.constraint=function(t){return null!==t&&Ve(t,e)},new ze(this._binding)},e.prototype.whenNoAncestorMatches=function(e){return this._binding.constraint=function(t){return null!==t&&!Ve(t,e)},new ze(this._binding)},e}(),ze=function(){function e(e){this._binding=e}return e.prototype.onActivation=function(e){return this._binding.onActivation=e,new qe(this._binding)},e.prototype.onDeactivation=function(e){return this._binding.onDeactivation=e,new qe(this._binding)},e}(),Ge=function(){function e(e){this._binding=e,this._bindingWhenSyntax=new qe(this._binding),this._bindingOnSyntax=new ze(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}(),Ye=function(){function e(e){this._binding=e}return e.prototype.inRequestScope=function(){return this._binding.scope=g,new Ge(this._binding)},e.prototype.inSingletonScope=function(){return this._binding.scope=v,new Ge(this._binding)},e.prototype.inTransientScope=function(){return this._binding.scope=y,new Ge(this._binding)},e}(),$e=function(){function e(e){this._binding=e,this._bindingWhenSyntax=new qe(this._binding),this._bindingOnSyntax=new ze(this._binding),this._bindingInSyntax=new Ye(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}(),Je=function(){function e(e){this._binding=e}return e.prototype.to=function(e){return this._binding.type=C,this._binding.implementationType=e,new $e(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=_,this._binding.cache=e,this._binding.dynamicValue=null,this._binding.implementationType=null,this._binding.scope=v,new Ge(this._binding)},e.prototype.toDynamicValue=function(e){return this._binding.type=E,this._binding.cache=null,this._binding.dynamicValue=e,this._binding.implementationType=null,new $e(this._binding)},e.prototype.toConstructor=function(e){return this._binding.type=b,this._binding.implementationType=e,this._binding.scope=v,new Ge(this._binding)},e.prototype.toFactory=function(e){return this._binding.type=w,this._binding.factory=e,this._binding.scope=v,new Ge(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=S,this._binding.scope=v,t},e.prototype.toAutoFactory=function(e){return this._binding.type=w,this._binding.factory=function(t){return function(){return t.container.get(e)}},this._binding.scope=v,new Ge(this._binding)},e.prototype.toAutoNamedFactory=function(e){return this._binding.type=w,this._binding.factory=function(t){return function(r){return t.container.getNamed(e,r)}},new Ge(this._binding)},e.prototype.toProvider=function(e){return this._binding.type=T,this._binding.provider=e,this._binding.scope=v,new Ge(this._binding)},e.prototype.toService=function(e){this.toDynamicValue((function(t){return t.container.get(e)}))},e}(),Qe=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}(),Ze=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}(),Xe=function(){return Xe=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},Xe.apply(this,arguments)},et=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))},tt=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])}}},rt=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))},nt=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=y;else if(t.defaultScope!==v&&t.defaultScope!==y&&t.defaultScope!==g)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=A(),this._bindingDictionary=new Ke,this._snapshots=[],this._middleware=null,this._activations=new Ke,this._deactivations=new Ke,this.parent=null,this._metadataReader=new x,this._moduleActivationStore=new Ze}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=rt([t,r],n,!0).map((function(e){return se(e)})),a=se(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 et(this,void 0,void 0,(function(){var t,r,n,i,s;return tt(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 et(this,void 0,void 0,(function(){var t,r,n,i;return tt(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||y,r=new O(e,t);return this._bindingDictionary.add(e,r),new Je(r)},e.prototype.rebind=function(e){return this.unbind(e),this.bind(e)},e.prototype.rebindAsync=function(e){return et(this,void 0,void 0,(function(){return tt(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 et(this,void 0,void 0,(function(){var t;return tt(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 et(this,void 0,void 0,(function(){var e,t=this;return tt(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 Q(D,"",t,new G(r,n)),s=new z(e);return new ie(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(Qe.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 et(this,void 0,void 0,(function(){var t;return tt(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 et(this,void 0,void 0,(function(){var n;return tt(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(ue(i))return this._handleDeactivationError(i.then((function(){return r._propagateContainerDeactivationThenBindingAndPreDestroyAsync(e,t,n)})),n)}var s=this._propagateContainerDeactivationThenBindingAndPreDestroy(e,t,n);if(ue(s))return this._handleDeactivationError(s,n)}catch(e){if(e instanceof Error)throw new Error(L(n.name,e.message))}},e.prototype._handleDeactivationError=function(e,t){return et(this,void 0,void 0,(function(){var r;return tt(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(L(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(ue(i))return i.then((function(){return r._deactivateContainerAsync(e,t)}));n=t.next()}},e.prototype._deactivateContainerAsync=function(e,t){return et(this,void 0,void 0,(function(){var r;return tt(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=Xe(Xe({},e),{contextInterceptor:function(e){return e},targetType:D});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(le(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=de(e._metadataReader,e,t.isMultiInject,t.targetType,t.serviceIdentifier,t.key,t.value,t.avoidConstraints);return function(e){return De(e.plan.rootRequest.requestScope)(e.plan.rootRequest)}(r=t.contextInterceptor(r))}},e.prototype._deactivateIfSingleton=function(e){var t=this;if(e.activated)return ue(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(ue(this._deactivateIfSingleton(n)))throw new Error("Attempting to unbind dependency with asynchronous destruction (@preDestroy or onDeactivation)")}},e.prototype._deactivateSingletonsAsync=function(e){return et(this,void 0,void 0,(function(){var t=this;return tt(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 et(this,void 0,void 0,(function(){return tt(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: "+V(e))}},e.prototype._bindingDeactivationAndPreDestroy=function(e,t,r){var n=this;if("function"==typeof e.onDeactivation){var i=e.onDeactivation(t);if(ue(i))return i.then((function(){return n._preDestroy(r,t)}))}return this._preDestroy(r,t)},e.prototype._bindingDeactivationAndPreDestroyAsync=function(e,t,r){return et(this,void 0,void 0,(function(){return tt(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 it(e,t,r,n){!function(e){if(void 0!==e)throw new Error(N)}(t),ot("inversify:tagged",e,r.toString(),n)}function st(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 ot(e,t,r,n){var i=st(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 at(e){return function(t,r,n){"number"==typeof n?it(t,r,n,e):function(e,t,r){if(void 0!==e.prototype)throw new Error(N);ot("inversify:tagged_props",e.constructor,t,r)}(t,r,e)}}function ct(){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 dt,ut=(dt="inject",function(e){return function(t,r,n){if(void 0===e){var i="function"==typeof t?t.name:t.constructor.name;throw new Error("@inject called with undefined this could mean that the class "+i+" has a circular dependency problem. You can use a LazyServiceIdentifier to overcome this limitation.")}return at(new G(dt,e))(t,r,n)}});const lt=3,pt=4,ht=6,ft=7;var mt;!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"}(mt||(mt={}));var gt;const 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,d;gt.set(this,void 0),u(this,gt,{denoiser:null!==(t=e.denoiser)&&void 0!==t?t:"rnnoise",asdk:Object.assign(Object.assign({},vt),e.asdk),signalingServerUrl:null!==(r=e.signalingServerUrl)&&void 0!==r?r:String("https://signaling-api.livedigital.space/v1"),logLevel:null!==(n=e.logLevel)&&void 0!==n?n:lt,sendAnalytics:null!==(i=e.sendAnalytics)&&void 0!==i&&i,onLogMessage:null!==(s=e.onLogMessage)&&void 0!==s?s:_t,onIssues:null!==(o=e.onIssues)&&void 0!==o?o:_t,disableWid:null!==(a=e.disableWid)&&void 0!==a&&a,effectsSDKParams:Object.assign(Object.assign({},yt),e.effectsSDKParams),onNetworkScoresUpdated:null!==(c=e.onNetworkScoresUpdated)&&void 0!==c?c:_t,getStatsInterval:null!==(d=e.getStatsInterval)&&void 0!==d?d:5e3,staticFilesPath:e.staticFilesPath||window.location.origin},"f")}get(e){return d(this,gt,"f")[e]}set(e,t){d(this,gt,"f")[e]=t}};gt=new WeakMap,bt=s([ct(),a("design:paramtypes",[Object])],bt);var Et=bt;class wt extends e.EventEmitter{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}}Error;const St=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0}],Ct=({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]=Ct({from:e[r],seen:t.slice(),forceEnumerable:n}):i[r]=s);for(const{property:t,enumerable:r}of St)"string"==typeof e[t]&&Object.defineProperty(i,t,{value:e[t],enumerable:!!n||r,configurable:!0,writable:!0});return i};var Pt=e=>"object"==typeof e&&null!==e?Ct({from:e,seen:[],forceEnumerable:!0}):"function"==typeof e?`[Function: ${e.name||"anonymous"}]`:e;class Tt extends Error{constructor(e,t){var r;if(t instanceof Tt)return super(t.message),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this.errorCode=t.errorCode,void(this.cause=t.cause);const n=Pt(t),i=null!==(r=(e=>{if("string"==typeof e)return e;if(e instanceof Error)return e.message;if(e&&"object"==typeof e&&"message"in e){const t=e.message;return"string"==typeof t?t:void 0}})(n))&&void 0!==r?r:"Operation failed";super(i),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this.errorCode=e,this.cause=Pt(n)}}var Rt,kt,Dt,It;function At(){}function Ot(){Ot.init.call(this)}function Mt(e){return void 0===e._maxListeners?Ot.defaultMaxListeners:e._maxListeners}function Nt(e,t,r){if(t)e.call(r);else for(var n=e.length,i=Wt(e,n),s=0;s<n;++s)i[s].call(r)}function Lt(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,s=Wt(e,i),o=0;o<i;++o)s[o].call(r,n)}function xt(e,t,r,n,i){if(t)e.call(r,n,i);else for(var s=e.length,o=Wt(e,s),a=0;a<s;++a)o[a].call(r,n,i)}function Ft(e,t,r,n,i,s){if(t)e.call(r,n,i,s);else for(var o=e.length,a=Wt(e,o),c=0;c<o;++c)a[c].call(r,n,i,s)}function jt(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,s=Wt(e,i),o=0;o<i;++o)s[o].apply(r,n)}function Ut(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 At,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=Mt(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 Vt(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 Bt(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 Wt(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}At.prototype=Object.create(null),Ot.EventEmitter=Ot,Ot.usingDomains=!1,Ot.prototype.domain=void 0,Ot.prototype._events=void 0,Ot.prototype._maxListeners=void 0,Ot.defaultMaxListeners=10,Ot.init=function(){this.domain=null,Ot.usingDomains&&(void 0).active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new At,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Ot.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},Ot.prototype.getMaxListeners=function(){return Mt(this)},Ot.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:Nt(r,u,this);break;case 2:Lt(r,u,this,arguments[1]);break;case 3:xt(r,u,this,arguments[1],arguments[2]);break;case 4:Ft(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];jt(r,u,this,i)}return!0},Ot.prototype.addListener=function(e,t){return Ut(this,e,t,!1)},Ot.prototype.on=Ot.prototype.addListener,Ot.prototype.prependListener=function(e,t){return Ut(this,e,t,!0)},Ot.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,Vt(this,e,t)),this},Ot.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,Vt(this,e,t)),this},Ot.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 At:(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 At,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},Ot.prototype.off=function(e,t){return this.removeListener(e,t)},Ot.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new At,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new At: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 At,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},Ot.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):[]},Ot.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Bt.call(e,t)},Ot.prototype.listenerCount=Bt,Ot.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class Ht extends Ot{}!function(e){e.Issue="issue",e.NetworkScoresUpdated="network-scores-updated",e.StatsParsingFinished="stats-parsing-finished"}(Rt||(Rt={})),function(e){e.Network="network",e.CPU="cpu",e.Server="server",e.Stream="stream"}(kt||(kt={})),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"}(Dt||(Dt={})),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"}(It||(It={}));class qt extends Ot{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(qt.STATS_REPORTS_PARSED,{timeTaken:r,reportItems:t}),t.forEach((e=>{this.emit(qt.STATS_REPORT_READY_EVENT,e)}))}}const zt=()=>{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 Gt{#e={};#t=zt();calculate(e){const{connection:{id:t}}=e,{mos:r,stats:n}=this.calculateOutboundScore(e)||{},{mos:i,stats:s}=this.calculateInboundScore(e)||{};return this.#e[t]=e,this.#t({taskId:t,delayMs:35e3,callback:()=>delete this.#e[t]}),{outbound:r,inbound:i,connectionId:t,statsSamples:{inboundStatsSample:s,outboundStatsSample:n}}}calculateOutboundScore(e){const t=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!t.length)return;const r=this.#e[e.connection.id];if(!r)return;const n=[...r.remote?.audio.inbound||[],...r.remote?.video.inbound||[]],{packetsSent:i}=e.connection,s=r.connection.packetsSent,o=t.reduce(((e,t)=>{const r=n.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=1e3*c/t.length,u=i-s,l=o.packetsLost-o.lastPacketsLost,p=u&&l?Math.round(100*l/(u+l)):0;return{mos:this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:p}),stats:{avgJitter:d,rtt:a,packetsLoss:p}}}calculateInboundScore(e){const t=[...e.audio?.inbound,...e.video?.inbound];if(!t.length)return;const r=this.#e[e.connection.id];if(!r)return;const n=[...r.video?.inbound,...r.audio?.inbound],{packetsReceived:i}=e.connection,s=r.connection.packetsReceived,o=t.reduce(((e,t)=>{const r=n.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=1e3*c/t.length,u=i-s,l=o.packetsLost-o.lastPacketsLost,p=u&&l?Math.round(100*l/(u+l)):0;return{mos:this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:p}),stats:{avgJitter:d,rtt:a,packetsLoss:p}}}calculateMOS({avgJitter:e,rtt:t,packetsLoss:r}){const n=t+2*e+10;let i=n<160?93.2-n/40:93.2-(n-120)/10;i-=2.5*r;const s=1+.035*i+7e-6*i*(i-60)*(100-i);return Math.max(0,Math.min(5,s))}}class Yt{#r=new Map;#n;#i;#t=zt();constructor(e={}){this.#n=e.statsCleanupTtlMs??35e3,this.#i=e.maxParsedStatsStorageSize??5}detect(e,t){const r={...e,networkScores:{...t,statsSamples:t?.statsSamples||{}}},n=this.performDetection(r);return this.setLastProcessedStats(e.connection.id,r),this.performPrevStatsCleanup({connectionId:e.connection.id}),n}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:r}=e;this.#r.has(t)&&this.#t({taskId:t,delayMs:this.#n,callback:()=>{this.deleteLastProcessedStats(t),"function"==typeof r&&r()}})}setLastProcessedStats(e,t){if(!e||t.connection.id!==e)return;const r=this.#r.get(e)??[];r.push(t),r.length>this.#i&&r.shift(),this.#r.set(e,r)}getLastProcessedStats(e){const t=this.#r.get(e);return t?.[t.length-1]}getAllLastProcessedStats(e){return this.#r.get(e)??[]}deleteLastProcessedStats(e){this.#r.delete(e)}}class $t extends Yt{#s;constructor(e={}){super(e),this.#s=e.availableOutgoingBitrateThreshold??1e5}performDetection(e){const t=[],{availableOutgoingBitrate:r}=e.connection;if(void 0===r)return t;const n=e.audio.outbound.reduce(((e,t)=>e+t.targetBitrate),0),i=e.video.outbound.reduce(((e,t)=>e+t.bitrate),0);if(!n&&!i)return t;const s={availableOutgoingBitrate:r,videoStreamsTotalBitrate:i,audioStreamsTotalTargetBitrate:n};return n>r||i>0&&r<this.#s?(t.push({statsSample:s,type:kt.Network,reason:Dt.OutboundNetworkThroughput}),t):t}}class Jt extends Yt{#o;#a;#c;#d;constructor(e={}){super(e),this.#o=e.highPacketLossThresholdPct??5,this.#a=e.highJitterThreshold??200,this.#c=e.highJitterBufferDelayThresholdMs??500,this.#d=e.highRttThresholdMs??250}performDetection(e){return this.processData(e)}processData(e){const t=[],r=[...e.audio?.inbound,...e.video?.inbound];if(!r.length)return t;const n=this.getLastProcessedStats(e.connection.id);if(!n)return t;const i=[...n.video?.inbound,...n.audio?.inbound],{packetsReceived:s}=e.connection,o=n.connection.packetsReceived,a=r.reduce(((e,t)=>{const r=i.find((e=>e.ssrc===t.ssrc)),n=r?.jitterBufferDelay||0,s=r?.jitterBufferEmittedCount||0,o=t.jitterBufferDelay-n,a=t.jitterBufferEmittedCount-s,c=o&&a?1e3*o/a:0;return{sumJitter:e.sumJitter+t.jitter,sumJitterBufferDelayMs:e.sumJitterBufferDelayMs+c,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,sumJitterBufferDelayMs:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:d,sumJitterBufferDelayMs:u}=a,l=1e3*d/r.length,p=u/r.length,h=s-o,f=a.packetsLost-a.lastPacketsLost,m=h&&f?Math.round(100*f/(h+f)):0,g=m>this.#o,v=l>=this.#a,y=c>=this.#d,_=p>this.#c,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:kt.Network,reason:Dt.InboundNetworkQuality,iceCandidate:e.connection.local.id}),b&&t.push({statsSample:S,type:kt.Server,reason:Dt.ServerIssue,iceCandidate:e.connection.remote.id}),E&&t.push({statsSample:S,type:kt.Network,reason:Dt.InboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),w&&t.push({statsSample:S,type:kt.Network,reason:Dt.NetworkMediaSyncFailure,iceCandidate:e.connection.local.id}),t}}class Qt extends Yt{#u;constructor(e={}){super(e),this.#u=e.correctedSamplesThresholdPct??5}performDetection(e){return this.processData(e)}processData(e){const t=e.audio.inbound,r=[],n=this.getLastProcessedStats(e.connection.id)?.audio.inbound;return n?(t.forEach((e=>{const t=n.find((t=>t.ssrc===e.ssrc));if(!t)return;const i=e.track.insertedSamplesForDeceleration+e.track.removedSamplesForAcceleration,s=t.track.insertedSamplesForDeceleration+t.track.removedSamplesForAcceleration;if(i===s)return;const o=e.track.totalSamplesReceived-t.track.totalSamplesReceived;if(0===o)return;const a=i-s,c=Math.round(100*a/o),d={correctedSamplesPct:c};c>this.#u&&r.push({statsSample:d,type:kt.Network,reason:Dt.NetworkMediaSyncFailure,ssrc:e.ssrc})})),r):r}}class Kt extends Yt{#o;#a;constructor(e={}){super(e),this.#o=e.highPacketLossThresholdPct??5,this.#a=e.highJitterThreshold??200}performDetection(e){return this.processData(e)}processData(e){const t=[],r=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!r.length)return t;const n=this.getLastProcessedStats(e.connection.id);if(!n)return t;const i=[...n.remote?.audio.inbound||[],...n.remote?.video.inbound||[]],{packetsSent:s}=e.connection,o=n.connection.packetsSent,a=r.reduce(((e,t)=>{const r=i.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:d}=a,u=1e3*d/r.length,l=s-o,p=a.packetsLost-a.lastPacketsLost,h=l&&p?Math.round(100*p/(l+p)):0,f=h>this.#o,m=u>=this.#a,g=m||f,v={rtt:c,avgJitter:u,packetLossPct:h};return f&&m&&t.push({statsSample:v,type:kt.Network,reason:Dt.OutboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),g&&t.push({statsSample:v,type:kt.Network,reason:Dt.OutboundNetworkQuality,iceCandidate:e.connection.local.id}),t}}class Zt extends Yt{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:kt.CPU,reason:Dt.EncoderCPUThrottling,ssrc:e.ssrc}),"bandwidth"===e.qualityLimitationReason&&r.push({statsSample:i,type:kt.Network,reason:Dt.OutboundNetworkThroughput,ssrc:e.ssrc}))})),r):r}}class Xt extends Yt{UNKNOWN_DECODER="unknown";#l={};performDetection(e){return this.processData(e)}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:r}=e;super.performPrevStatsCleanup({...e,cleanupCallback:()=>{delete this.#l[t],"function"==typeof r&&r()}})}processData(e){const t=[],{id:r}=e.connection,n=this.getLastProcessedStats(r)?.video.inbound;return e.video.inbound.forEach((e=>{const{decoderImplementation:i,ssrc:s}=e,o=n?.find((e=>e.ssrc===s));if(o)if(i===this.UNKNOWN_DECODER){if(!this.hadLastDecoderWithIssue(r,s)){this.setLastDecoderWithIssue(r,s,this.UNKNOWN_DECODER);const n={mimeType:e.mimeType,decoderImplementation:i};t.push({ssrc:s,statsSample:n,type:kt.Stream,reason:Dt.UnknownVideoDecoderIssue,trackIdentifier:e.track.trackIdentifier})}}else this.setLastDecoderWithIssue(r,s,void 0)})),t}setLastDecoderWithIssue(e,t,r){const n=this.#l[e]??{};void 0===r?delete n[t]:n[t]=r,this.#l[e]=n}hadLastDecoderWithIssue(e,t){const r=this.#l[e];return(r&&r[t])===this.UNKNOWN_DECODER}}const er=e=>e.reduce(((e,t)=>e+t),0)/e.length,tr=(e,t,r=30)=>{const n=[];for(let r=1;r<t.length;r+=1){const i=t[r]?.video?.inbound.find((t=>t.ssrc===e));if(!i)continue;const s=t[r-1]?.video?.inbound?.find((t=>t.ssrc===e));if(!i||!s)continue;const o=i.timestamp-s.timestamp,a=i.framesDecoded-s.framesDecoded;if(a>0){const e=o/a;n.push(e)}}return!(n.length<=1)&&(e=>{const t=((e,t)=>t.reduce(((t,r)=>t+(r-e)**2),0)/t.length)(er(e),e);return Math.sqrt(t)})(n)>r},rr=(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 nr extends Yt{#p;#h;#f;constructor(e={}){super(),this.#p=e.avgFreezeDurationThresholdMs??1e3,this.#h=e.frozenDurationThresholdPct??30,this.#f=e.minMosQuality??It.BAD}performDetection(e){const t=e.networkScores.inbound;return void 0!==t&&t<=this.#f?[]:this.processData(e)}processData(e){const t=[],r=this.getAllLastProcessedStats(e.connection.id);if(0===r.length)return[];const n=e.video.inbound.map((t=>{const n=r[r.length-1].video.inbound.find((e=>e.ssrc===t.ssrc));if(!n)return;if(rr(t.ssrc,[r[r.length-1],e]))return;if(tr(t.ssrc,r))return;const i=t.freezeCount-(n.freezeCount??0),s=1e3*(t.totalFreezesDuration-(n.totalFreezesDuration??0)),o=i>0?s/i:0,a=s/(t.timestamp-n.timestamp)*100;return a>this.#h||o>this.#p?{ssrc:t.ssrc,avgFreezeDurationMs:o,frozenDurationPct:a}:void 0})).filter((e=>void 0!==e));return n.length>0&&(t.push({type:kt.Stream,reason:Dt.FrozenVideoTrack,statsSample:{ssrcs:n.map((e=>e.ssrc))}}),this.deleteLastProcessedStats(e.connection.id)),t}}class ir extends Yt{#m;#g;#f;constructor(e={}){super(e),this.#m=e.volatilityThreshold??8,this.#g=e.affectedStreamsPercentThreshold??30,this.#f=e.minMosQuality??It.BAD}performDetection(e){return[...this.getAllLastProcessedStats(e.connection.id),e].find((e=>void 0!==e.networkScores.inbound&&e.networkScores.inbound<=this.#f))?[]:this.processData(e)}processData(e){const t=[],r=[...this.getAllLastProcessedStats(e.connection.id),e],n=e.video.inbound.map((e=>{if(r.length<5)return;if(rr(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(tr(e.ssrc,r))return;const n=(e=>{if(0===e.length)throw new Error("Cannot calculate volatility for empty array");const t=er(e);return 0===t?0:e.reduce(((e,r)=>e+Math.abs(r-t)),0)/e.length*100/t})(t);return n>this.#m?{ssrc:e.ssrc,allFps:t,volatility:n}:void 0})).filter((e=>Boolean(e)));if(0===n.length)return t;const i=n.length/(e.video.inbound.length/100);return i>this.#g&&(t.push({type:kt.CPU,reason:Dt.DecoderCPUThrottling,statsSample:{affectedStreamsPercent:i,throtthedStreams:n}}),this.deleteLastProcessedStats(e.connection.id)),t}}class sr extends Yt{#v=new Map;#y;#_;constructor(e={}){super(),this.#y=e.timeoutMs??15e3,this.#_=e.steps??3}performDetection(e){return this.processData(e)}processData(e){const t=[],r=[...this.getAllLastProcessedStats(e.connection.id),e];if(r.length<this.#_)return t;const n=r.slice(-this.#_),i=n.map((e=>e.video.inbound)),s=n.map((e=>e.audio.inbound));return t.push(...this.detectMissingData(s,kt.Stream,Dt.MissingAudioStreamData)),t.push(...this.detectMissingData(i,kt.Stream,Dt.MissingVideoStreamData)),new Set(this.#v.keys()).forEach((e=>{const t=this.#v.get(e);t&&Date.now()-t>this.#y&&this.removeMarkedIssue(e)})),t}detectMissingData(e,t,r){const n=[],i=e.pop(),s=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.#v.get(e);return(!r||t-r>this.#y)&&(this.#v.set(e,t),!0)}removeMarkedIssue(e){this.#v.delete(e)}}const or=e=>"closed"===e.iceConnectionState||"closed"===e.connectionState,ar=(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 cr{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(!or(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 dr{prevStats=new Map;scheduleTask=zt();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(!or(e.pc))return this.getConnectionStats(e);this.logger.debug("Skip stats parsing. Connection is closed.",{connection:e})}async getConnectionStats(e){const{pc:t,id:r}=e;try{const n=Date.now(),i=t.getReceivers().filter((e=>e.track?.enabled)),s=t.getSenders().filter((e=>e.track?.enabled)),o=await Promise.all(i.map((e=>e.getStats()))),a=await Promise.all(s.map((e=>e.getStats())));return{id:r,stats:this.mapReportsStats([...o,...a],e),timeTaken:Date.now()-n}}catch(e){return void this.logger.error("Failed to get stats for PC",{id:r,pc:t,error:e})}}mapReportsStats(e,t){const r={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{},remote:{video:{inbound:[],outbound:[]},audio:{inbound:[],outbound:[]}}};e.forEach((e=>{e.forEach((t=>{this.allowedReportTypes.has(t.type)&&this.updateMappedStatsWithReportItemData(t,r,e)}))}));const{id:n}=t,i=this.prevStats.get(n);return i&&this.propagateStatsWithRateValues(r,i.stats),this.prevStats.set(n,{stats:r,ts:Date.now()}),this.scheduleTask({taskId:n,delayMs:35e3,callback:()=>this.prevStats.delete(n)}),r}updateMappedStatsWithReportItemData(e,t,r){const n=e.type;if("candidate-pair"===n&&"succeeded"===e.state&&e.nominated)return void(t.connection=this.prepareConnectionStats(e,r));const i=this.getMediaType(e);if(!i)return;const s=e.ssrc;if(!s||!this.ignoreSSRCList.includes(s))if("outbound-rtp"!==n)if("inbound-rtp"!==n)"remote-outbound-rtp"!==n?"remote-inbound-rtp"===n&&(this.mapConnectionStatsIfNecessary(t,e,r),t.remote[i].inbound.push({...e})):t.remote[i].outbound.push({...e});else{const n=r.get(e.trackId)||r.get(e.mediaSourceId)||{};this.mapConnectionStatsIfNecessary(t,e,r);const s={...e,track:{...n}};t[i].inbound.push(s)}else{const n=r.get(e.trackId)||r.get(e.mediaSourceId)||{},s={...e,track:{...n}};t[i].outbound.push(s)}}getMediaType(e){const t=e.mediaType||e.kind;if(!["audio","video"].includes(t)){const{id:t}=e;if(!t)return;return String(t).includes("Video")?"video":String(t).includes("Audio")?"audio":void 0}return t}propagateStatsWithRateValues(e,t){e.audio.inbound.forEach((e=>{const r=t.audio.inbound.find((({id:t})=>t===e.id));e.bitrate=ar(e,r,"bytesReceived"),e.packetRate=ar(e,r,"packetsReceived")})),e.audio.outbound.forEach((e=>{const r=t.audio.outbound.find((({id:t})=>t===e.id));e.bitrate=ar(e,r,"bytesSent"),e.packetRate=ar(e,r,"packetsSent")})),e.video.inbound.forEach((e=>{const r=t.video.inbound.find((({id:t})=>t===e.id));e.bitrate=ar(e,r,"bytesReceived"),e.packetRate=ar(e,r,"packetsReceived")})),e.video.outbound.forEach((e=>{const r=t.video.outbound.find((({id:t})=>t===e.id));e.bitrate=ar(e,r,"bytesSent"),e.packetRate=ar(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 ur{eventEmitter;#b=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;autoAddPeerConnections;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new Ht,e.onIssues&&this.eventEmitter.on(Rt.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(Rt.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new Zt,new Jt,new Kt,new Qt,new $t,new Xt,new nr,new ir,new sr],this.networkScoresCalculator=e.networkScoresCalculator??new Gt,this.compositeStatsParser=e.compositeStatsParser??new cr({statsParser:new dr({ignoreSSRCList:e.ignoreSSRCList,logger:this.logger})}),this.statsReporter=e.statsReporter??new qt({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.autoAddPeerConnections=e.autoAddPeerConnections??!0,this.autoAddPeerConnections&&this.wrapRTCPeerConnection(),this.statsReporter.on(qt.STATS_REPORT_READY_EVENT,(e=>{const t=this.calculateNetworkScores(e.stats);this.detectIssues({data:e.stats},t)})),this.statsReporter.on(qt.STATS_REPORTS_PARSED,(t=>{const r={timeTaken:t.timeTaken,ts:Date.now()};e.onStats&&e.onStats(t.reportItems),this.eventEmitter.emit(Rt.StatsParsingFinished,r)}))}watchNewPeerConnections(){if(!this.autoAddPeerConnections)throw new Error("Auto add peer connections was disabled in the constructor.");this.#b?this.logger.warn("WebRTCIssueDetector is already started. Skip processing"):(this.logger.info("Start watching peer connections"),this.#b=!0,this.statsReporter.startReporting())}stopWatchingNewPeerConnections(){this.#b?(this.logger.info("Stop watching peer connections"),this.#b=!1,this.statsReporter.stopReporting()):this.logger.warn("WebRTCIssueDetector is already stopped. Skip processing")}handleNewPeerConnection(e,t){this.#b||!this.autoAddPeerConnections?(this.#b||!1!==this.autoAddPeerConnections||(this.logger.info("Starting stats reporting for new peer connection"),this.#b=!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(Rt.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(Rt.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}}var lr,pr,hr,fr,mr;let gr=class{constructor(){lr.set(this,void 0),pr.set(this,void 0),hr.set(this,void 0),fr.set(this,void 0),mr.set(this,void 0)}get meta(){return{peerId:d(this,lr,"f"),channelId:d(this,pr,"f"),appId:d(this,hr,"f"),datacenterName:d(this,fr,"f"),nodeId:d(this,mr,"f")}}setPeerId(e){u(this,lr,e,"f")}setChannelId(e){u(this,pr,e,"f")}setAppId(e){u(this,hr,e,"f")}setDatacenterName(e){u(this,fr,e,"f")}setNodeId(e){u(this,mr,e,"f")}clear(){u(this,lr,void 0,"f"),u(this,pr,void 0,"f"),u(this,hr,void 0,"f"),u(this,fr,void 0,"f")}};lr=new WeakMap,pr=new WeakMap,hr=new WeakMap,fr=new WeakMap,mr=new WeakMap,gr=s([ct()],gr);const vr="peer.updateAppData",yr="channel-event",_r="peer-joined",br="peer-left",Er="channel-activity-confirmation-required",wr="channel-activity-confirmation-acquired",Sr="channel-activity-confirmation-expired",Cr="channel-rejoin-required",Pr="devices-list-updated",Tr="transport-connection-timeout",Rr="track-force-closed",kr="track-failed",Dr="active-speaker-changed",Ir="channel-state-inconsistent",Ar="connection-lost",Or="connection-restored",Mr="denoiser-initializing",Nr="channel-state-synced",Lr="denoiser-enabled",xr="denoiser-disabled",Fr="denoiser-fallback",jr="denoiser-failed",Ur="volume-changed",Vr="track-produced",Br="track-unproduced",Wr="track-paused",Hr="track-resumed",qr="track-closed",zr="track-reopened",Gr="track-failed",Yr="media-published",$r="media-unpublished",Jr="publisher-paused",Qr="publisher-resumed",Kr="track-start",Zr="track-end",Xr="track-paused",en="track-resumed",tn="track-failed",rn="app-data-updated",nn="produce-permissions-changed",sn="groups-changed",on="peer.newProducer",an="producer.close",cn="producer.setMaxSpatialLayer",dn="producer.requestMaxSpatialLayer",un="consumer.close",ln="consumer.pause",pn="consumer.resume",hn="consumer.changeConsumerPreferredLayers",fn="transport.connectionTimeout",mn="transport-state";var gn;!function(e){e.CloseProducer="CloseProducer",e.Mute="Mute",e.Resume="Resume",e.Join="Join",e.Release="Release"}(gn||(gn={}));class vn extends Error{constructor(e,t,r){super(null!=e?e:"Unexpected Livedigital SDK error"),Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this.errorCode=null!=t?t:"unknown_error",this.meta=r}}class yn extends vn{constructor(e,t,r){super(null!=e?e:yn.DEFAULT_MESSAGE,null!=t?t:"need_joined_to_channel",r)}}yn.DEFAULT_MESSAGE="Peer must join the channel before performing this request";class _n extends vn{constructor(e,t,r){super(null!=e?e:_n.DEFAULT_MESSAGE,null!=t?t:"unsupported_error",r)}}_n.UNSUPPORTED_DEVICE_CODE="unsupported_device_error",_n.UNSUPPORTED_OPERATION_CODE="unsupported_operation_error",_n.DEFAULT_MESSAGE="Unsupported operation";const bn=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")};var En={exports:{}},wn=h(En.exports=function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=90)}({17:function(e,t,r){t.__esModule=!0,t.default=void 0;var n=r(18),i=function(){function e(){}return e.getFirstMatch=function(e,t){var r=t.match(e);return r&&r.length>0&&r[1]||""},e.getSecondMatch=function(e,t){var r=t.match(e);return r&&r.length>1&&r[2]||""},e.matchAndReturnConst=function(e,t,r){if(e.test(t))return r},e.getWindowsVersionName=function(e){switch(e){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},e.getMacOSVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),10===t[0])switch(t[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}},e.getAndroidVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0},e.getVersionPrecision=function(e){return e.split(".").length},e.compareVersions=function(t,r,n){void 0===n&&(n=!1);var i=e.getVersionPrecision(t),s=e.getVersionPrecision(r),o=Math.max(i,s),a=0,c=e.map([t,r],(function(t){var r=o-e.getVersionPrecision(t),n=t+new Array(r+1).join(".0");return e.map(n.split("."),(function(e){return new Array(20-e.length).join("0")+e})).reverse()}));for(n&&(a=o-Math.min(i,s)),o-=1;o>=a;){if(c[0][o]>c[1][o])return 1;if(c[0][o]===c[1][o]){if(o===a)return 0;o-=1}else if(c[0][o]<c[1][o])return-1}},e.map=function(e,t){var r,n=[];if(Array.prototype.map)return Array.prototype.map.call(e,t);for(r=0;r<e.length;r+=1)n.push(t(e[r]));return n},e.find=function(e,t){var r,n;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(r=0,n=e.length;r<n;r+=1){var i=e[r];if(t(i,r))return i}},e.assign=function(e){for(var t,r,n=e,i=arguments.length,s=new Array(i>1?i-1:0),o=1;o<i;o++)s[o-1]=arguments[o];if(Object.assign)return Object.assign.apply(Object,[e].concat(s));var a=function(){var e=s[t];"object"==typeof e&&null!==e&&Object.keys(e).forEach((function(t){n[t]=e[t]}))};for(t=0,r=s.length;t<r;t+=1)a();return e},e.getBrowserAlias=function(e){return n.BROWSER_ALIASES_MAP[e]},e.getBrowserTypeByAlias=function(e){return n.BROWSER_MAP[e]||""},e}();t.default=i,e.exports=t.default},18:function(e,t,r){t.__esModule=!0,t.ENGINE_MAP=t.OS_MAP=t.PLATFORMS_MAP=t.BROWSER_MAP=t.BROWSER_ALIASES_MAP=void 0,t.BROWSER_ALIASES_MAP={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},t.BROWSER_MAP={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},t.PLATFORMS_MAP={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},t.OS_MAP={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},t.ENGINE_MAP={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"}},90:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(91))&&n.__esModule?n:{default:n},s=r(18);function o(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}var a=function(){function e(){}var t,r,n;return e.getParser=function(e,t){if(void 0===t&&(t=!1),"string"!=typeof e)throw new Error("UserAgent should be a string");return new i.default(e,t)},e.parse=function(e){return new i.default(e).getResult()},t=e,n=[{key:"BROWSER_MAP",get:function(){return s.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return s.ENGINE_MAP}},{key:"OS_MAP",get:function(){return s.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return s.PLATFORMS_MAP}}],(r=null)&&o(t.prototype,r),n&&o(t,n),e}();t.default=a,e.exports=t.default},91:function(e,t,r){t.__esModule=!0,t.default=void 0;var n=c(r(92)),i=c(r(93)),s=c(r(94)),o=c(r(95)),a=c(r(17));function c(e){return e&&e.__esModule?e:{default:e}}var d=function(){function e(e,t){if(void 0===t&&(t=!1),null==e||""===e)throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},!0!==t&&this.parse()}var t=e.prototype;return t.getUA=function(){return this._ua},t.test=function(e){return e.test(this._ua)},t.parseBrowser=function(){var e=this;this.parsedResult.browser={};var t=a.default.find(n.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.browser=t.describe(this.getUA())),this.parsedResult.browser},t.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},t.getBrowserName=function(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},t.getBrowserVersion=function(){return this.getBrowser().version},t.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},t.parseOS=function(){var e=this;this.parsedResult.os={};var t=a.default.find(i.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os},t.getOSName=function(e){var t=this.getOS().name;return e?String(t).toLowerCase()||"":t||""},t.getOSVersion=function(){return this.getOS().version},t.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},t.getPlatformType=function(e){void 0===e&&(e=!1);var t=this.getPlatform().type;return e?String(t).toLowerCase()||"":t||""},t.parsePlatform=function(){var e=this;this.parsedResult.platform={};var t=a.default.find(s.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform},t.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},t.getEngineName=function(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},t.parseEngine=function(){var e=this;this.parsedResult.engine={};var t=a.default.find(o.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine},t.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},t.getResult=function(){return a.default.assign({},this.parsedResult)},t.satisfies=function(e){var t=this,r={},n=0,i={},s=0;if(Object.keys(e).forEach((function(t){var o=e[t];"string"==typeof o?(i[t]=o,s+=1):"object"==typeof o&&(r[t]=o,n+=1)})),n>0){var o=Object.keys(r),c=a.default.find(o,(function(e){return t.isOS(e)}));if(c){var d=this.satisfies(r[c]);if(void 0!==d)return d}var u=a.default.find(o,(function(e){return t.isPlatform(e)}));if(u){var l=this.satisfies(r[u]);if(void 0!==l)return l}}if(s>0){var p=Object.keys(i),h=a.default.find(p,(function(e){return t.isBrowser(e,!0)}));if(void 0!==h)return this.compareVersion(i[h])}},t.isBrowser=function(e,t){void 0===t&&(t=!1);var r=this.getBrowserName().toLowerCase(),n=e.toLowerCase(),i=a.default.getBrowserTypeByAlias(n);return t&&i&&(n=i.toLowerCase()),n===r},t.compareVersion=function(e){var t=[0],r=e,n=!1,i=this.getBrowserVersion();if("string"==typeof i)return">"===e[0]||"<"===e[0]?(r=e.substr(1),"="===e[1]?(n=!0,r=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?r=e.substr(1):"~"===e[0]&&(n=!0,r=e.substr(1)),t.indexOf(a.default.compareVersions(i,r,n))>-1},t.isOS=function(e){return this.getOSName(!0)===String(e).toLowerCase()},t.isPlatform=function(e){return this.getPlatformType(!0)===String(e).toLowerCase()},t.isEngine=function(e){return this.getEngineName(!0)===String(e).toLowerCase()},t.is=function(e,t){return void 0===t&&(t=!1),this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)},t.some=function(e){var t=this;return void 0===e&&(e=[]),e.some((function(e){return t.is(e)}))},e}();t.default=d,e.exports=t.default},92:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=/version\/(\d+(\.?_?\d+)+)/i,o=[{test:[/googlebot/i],describe:function(e){var t={name:"Googlebot"},r=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/opera/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opr\/|opios/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/SamsungBrowser/i],describe:function(e){var t={name:"Samsung Internet for Android"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Whale/i],describe:function(e){var t={name:"NAVER Whale Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MZBrowser/i],describe:function(e){var t={name:"MZ Browser"},r=i.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/focus/i],describe:function(e){var t={name:"Focus"},r=i.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/swing/i],describe:function(e){var t={name:"Swing"},r=i.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/coast/i],describe:function(e){var t={name:"Opera Coast"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(e){var t={name:"Opera Touch"},r=i.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/yabrowser/i],describe:function(e){var t={name:"Yandex Browser"},r=i.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/ucbrowser/i],describe:function(e){var t={name:"UC Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Maxthon|mxios/i],describe:function(e){var t={name:"Maxthon"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/epiphany/i],describe:function(e){var t={name:"Epiphany"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/puffin/i],describe:function(e){var t={name:"Puffin"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sleipnir/i],describe:function(e){var t={name:"Sleipnir"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/k-meleon/i],describe:function(e){var t={name:"K-Meleon"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/micromessenger/i],describe:function(e){var t={name:"WeChat"},r=i.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/qqbrowser/i],describe:function(e){var t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},r=i.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/msie|trident/i],describe:function(e){var t={name:"Internet Explorer"},r=i.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/\sedg\//i],describe:function(e){var t={name:"Microsoft Edge"},r=i.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/edg([ea]|ios)/i],describe:function(e){var t={name:"Microsoft Edge"},r=i.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/vivaldi/i],describe:function(e){var t={name:"Vivaldi"},r=i.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/seamonkey/i],describe:function(e){var t={name:"SeaMonkey"},r=i.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sailfish/i],describe:function(e){var t={name:"Sailfish"},r=i.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return r&&(t.version=r),t}},{test:[/silk/i],describe:function(e){var t={name:"Amazon Silk"},r=i.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/phantom/i],describe:function(e){var t={name:"PhantomJS"},r=i.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/slimerjs/i],describe:function(e){var t={name:"SlimerJS"},r=i.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t={name:"BlackBerry"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t={name:"WebOS Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/bada/i],describe:function(e){var t={name:"Bada"},r=i.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/tizen/i],describe:function(e){var t={name:"Tizen"},r=i.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/qupzilla/i],describe:function(e){var t={name:"QupZilla"},r=i.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/firefox|iceweasel|fxios/i],describe:function(e){var t={name:"Firefox"},r=i.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/electron/i],describe:function(e){var t={name:"Electron"},r=i.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MiuiBrowser/i],describe:function(e){var t={name:"Miui"},r=i.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/chromium/i],describe:function(e){var t={name:"Chromium"},r=i.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/chrome|crios|crmo/i],describe:function(e){var t={name:"Chrome"},r=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/GSA/i],describe:function(e){var t={name:"Google Search"},r=i.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t={name:"Android Browser"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/playstation 4/i],describe:function(e){var t={name:"PlayStation 4"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/safari|applewebkit/i],describe:function(e){var t={name:"Safari"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/.*/i],describe:function(e){var t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:i.default.getFirstMatch(t,e),version:i.default.getSecondMatch(t,e)}}}];t.default=o,e.exports=t.default},93:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18),o=[{test:[/Roku\/DVP/],describe:function(e){var t=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:s.OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe:function(e){var t=i.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe:function(e){var t=i.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),r=i.default.getWindowsVersionName(t);return{name:s.OS_MAP.Windows,version:t,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e){var t={name:s.OS_MAP.iOS},r=i.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return r&&(t.version=r),t}},{test:[/macintosh/i],describe:function(e){var t=i.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),r=i.default.getMacOSVersionName(t),n={name:s.OS_MAP.MacOS,version:t};return r&&(n.versionName=r),n}},{test:[/(ipod|iphone|ipad)/i],describe:function(e){var t=i.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:s.OS_MAP.iOS,version:t}}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t=i.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),r=i.default.getAndroidVersionName(t),n={name:s.OS_MAP.Android,version:t};return r&&(n.versionName=r),n}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t=i.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),r={name:s.OS_MAP.WebOS};return t&&t.length&&(r.version=t),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t=i.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||i.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||i.default.getFirstMatch(/\bbb(\d+)/i,e);return{name:s.OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe:function(e){var t=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe:function(e){var t=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:function(){return{name:s.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:s.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e){var t=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.PlayStation4,version:t}}}];t.default=o,e.exports=t.default},94:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18),o=[{test:[/googlebot/i],describe:function(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe:function(e){var t=i.default.getFirstMatch(/(can-l01)/i,e)&&"Nova",r={type:s.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(r.model=t),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet}}},{test:function(e){var t=e.test(/ipod|iphone/i),r=e.test(/like (ipod|iphone)/i);return t&&!r},describe:function(e){var t=i.default.getFirstMatch(/(ipod|iphone)/i,e);return{type:s.PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"blackberry"===e.getBrowserName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e){return"bada"===e.getBrowserName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"windows phone"===e.getBrowserName()},describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(e){var t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(!0)&&t>=3},describe:function(){return{type:s.PLATFORMS_MAP.tablet}}},{test:function(e){return"android"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"macos"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e){return"windows"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.desktop}}},{test:function(e){return"linux"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.desktop}}},{test:function(e){return"playstation 4"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.tv}}},{test:function(e){return"roku"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.tv}}}];t.default=o,e.exports=t.default},95:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18),o=[{test:function(e){return"microsoft edge"===e.getBrowserName(!0)},describe:function(e){if(/\sedg\//i.test(e))return{name:s.ENGINE_MAP.Blink};var t=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:s.ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe:function(e){var t={name:s.ENGINE_MAP.Trident},r=i.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){return e.test(/presto/i)},describe:function(e){var t={name:s.ENGINE_MAP.Presto},r=i.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=e.test(/gecko/i),r=e.test(/like gecko/i);return t&&!r},describe:function(e){var t={name:s.ENGINE_MAP.Gecko},r=i.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:s.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e){var t={name:s.ENGINE_MAP.WebKit},r=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}}];t.default=o,e.exports=t.default}}));function Sn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Cn(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=Sn(n)&&Sn(s);(o&&!Cn(n,s)||!o&&n!==s)&&(i=!1)})),i}function Pn(e,t,r=!1){let n=null;return function(...i){return c(this,void 0,void 0,(function*(){const s=r&&!n;"number"==typeof n&&clearTimeout(n),n=setTimeout((()=>c(this,void 0,void 0,(function*(){n=null,r||(yield e.apply(this,i))}))),t),s&&(yield e.apply(this,i))}))}}function Tn(e,t){return c(this,void 0,void 0,(function*(){try{return yield e()}catch(e){return void(null==t||t(e))}}))}const Rn=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:[]},kn=e=>["video/vp9","vp9"].includes(e.toLowerCase()),Dn=Array.from({length:256},((e,t)=>(t+256).toString(16).slice(1)));function In(e=24){const t=new Uint8Array(e);crypto.getRandomValues(t);let r="";for(let e=0;e<t.length;e++)r+=Dn[t[e]];return r}class An{sleepMs(e){return c(this,void 0,void 0,(function*(){yield new Promise((t=>setTimeout(t,e)))}))}now(){return new Date(Date.now())}}const On=new An,Mn=(e,...t)=>c(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:Pt(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 On.sleepMs(Math.min(e,null!==(s=t.maxBackoffDelayMs)&&void 0!==s?s:e))}}}throw null!=c?c:new Error("retryAsync logic failed")}));var Nn,Ln,xn;!function(e){e.Config="Config",e.Engine="Engine",e.System="System",e.Media="Media",e.Network="Network",e.MediaEventHandler="MediaEventHandler",e.ChannelEventHandler="ChannelEventHandler",e.ChannelAudioObserverEventHandler="ChannelAudioObserverEventHandler",e.ChannelAudioObserverMissingProducerRestorer="ChannelAudioObserverMissingProducerRestorer",e.ChannelStateSynchronizer="ChannelStateSynchronizer",e.ChannelStateSyncEventHandler="ChannelStateSyncEventHandler",e.CompositeStatsParser="CompositeStatsParser",e.PeriodicStatsReporter="PeriodicStatsReporter",e.WIDIgnoreSsrcList="WIDIgnoreSsrcList",e.WebRTCIssueDetector="WebRTCIssueDetector",e.WIDStatsAdapter="WIDStatsAdapter",e.ScoresCalculator="ScoresCalculator",e.LoggerFactory="LoggerFactory",e.MediaStreamTrackManager="MediaStreamTrackManager",e.EventsQueue="EventsQueue",e.ClientEventEmitter="ClientEventEmitter",e.Peers="Peers",e.CallState="CallState",e.RemotePeerTracks="RemotePeerTracks",e.MyPeer="MyPeer",e.InternalEventEmitter="InternalEventEmitter",e.PeerTrackFactory="PeerTrackFactory",e.PeerFactory="PeerFactory",e.PeerConsumerFactory="PeerConsumerFactory",e.AudioTrackFactory="AudioTrackFactory",e.VideoTrackFactory="VideoTrackFactory",e.AudioTrackProcessorFactory="AudioTrackProcessorFactory",e.IntegrationsService="IntegrationsService",e.ProcessorsCache="ProcessorsCache",e.StatsHandler="StatsHandler",e.DataChannelsManager="DataChannelsManager",e.WIDHandler="WIDHandler",e.AnalyticsApiClient="AnalyticsApiClient",e.TransportsStatsProvider="TransportsStatsProvider",e.LocalMutex="LocalMutex",e.PeersStorage="PeersStorage",e.SignalingApiClient="SignalingApiClient",e.DatachannelHeartbeater="DatachannelHeartbeater",e.SignalingHeartbeater="SignalingHeartbeater",e.PendingClosureProducerStorage="PendingClosureProducerStorage",e.ProducerCloseManager="ProducerCloseManager",e.NetworkTransportPolicyManager="NetworkTransportPolicyManager",e.ClientMetaProvider="ClientMetaProvider"}(Nn||(Nn={})),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"}(Ln||(Ln={})),function(e){e.NotFoundError="NotFoundError",e.NoDevices="NoDevices",e.DeviceIsBusy="DeviceIsBusy",e.NotAllowedError="NotAllowedError",e.RequestDevicesUnknownError="RequestDevicesUnknownError"}(xn||(xn={}));let Fn=class{constructor(){this.isJoined=!1,this.isChannelJoining=!1}reset(){this.appId=void 0,this.channelId=void 0,this.isJoined=!1,this.isChannelJoining=!1}};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 Un(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)}}Fn=s([ct()],Fn);function Vn(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?Hn(n,i):Wn(n,i)}function Bn(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()+qn(s)+qn(i)}function Wn(e,t){return{lo:0|e,hi:0|t}}function Hn(e,t){return t=~t,e?e=1+~e:t+=1,Wn(e,t)}const qn=e=>{const t=String(e);return"0000000".slice(t.length)+t};function zn(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 Gn(){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 Yn=$n();function $n(){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()),Jn(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),Qn(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),Jn(e),Vn(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),Qn(e),Vn(e)),dec:(e,t)=>function(e,t){let r=Wn(e,t);const n=2147483648&r.hi;n&&(r=Hn(r.lo,r.hi));const i=Bn(r.lo,r.hi);return n?"-"+i:i}(e,t),uDec:(e,t)=>Bn(e,t)}}function Jn(e){if(!/^-?[0-9]+$/.test(e))throw new Error("invalid int64: "+e)}function Qn(e){if(!/^[0-9]+$/.test(e))throw new Error("invalid uint64: "+e)}const Kn=Symbol.for("@bufbuild/protobuf/text-encoding");function Zn(){if(null==globalThis[Kn]){const e=new globalThis.TextEncoder,t=new globalThis.TextDecoder;globalThis[Kn]={encodeUtf8:t=>e.encode(t),decodeUtf8:e=>t.decode(e),checkUtf8(e){try{return encodeURIComponent(e),!0}catch(e){return!1}}}}return globalThis[Kn]}var Xn;!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"}(Xn||(Xn={}));const ei=34028234663852886e22,ti=-34028234663852886e22;class ri{constructor(e=Zn().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(si(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return ii(e),zn(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>ei||e<ti))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){si(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){ii(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return ii(e),zn(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),r=new DataView(t.buffer),n=Yn.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=Yn.uEnc(e);return r.setInt32(0,n.lo,!0),r.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=Yn.enc(e);return Un(t.lo,t.hi,this.buf),this}sint64(e){const t=Yn.enc(e),r=t.hi>>31;return Un(t.lo<<1^r,(t.hi<<1|t.lo>>>31)^r,this.buf),this}uint64(e){const t=Yn.uEnc(e);return Un(t.lo,t.hi,this.buf),this}}class ni{constructor(e,t=Zn().decodeUtf8){this.decodeUtf8=t,this.varint64=jn,this.uint32=Gn,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 Xn.Varint:for(;128&this.buf[this.pos++];);break;case Xn.Bit64:this.pos+=4;case Xn.Bit32:this.pos+=4;break;case Xn.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Xn.StartGroup:for(;;){const[e,r]=this.tag();if(r===Xn.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 Yn.dec(...this.varint64())}uint64(){return Yn.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),r=-(1&e);return e=(e>>>1|(1&t)<<31)^r,t=t>>>1^r,Yn.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 Yn.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Yn.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 ii(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 si(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 oi={encode:(e,t=new ri)=>(0!==e.time&&t.uint32(8).int64(e.time),t),decode(e,t){const r=e instanceof ni?e:new ni(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=ai(r.int64());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON(e){return{time:(t=e.time,null!=t?globalThis.Number(e.time):0)};var t},toJSON(e){const t={};return 0!==e.time&&(t.time=Math.round(e.time)),t},create:e=>oi.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 ai(e){const t=globalThis.Number(e.toString());if(t>globalThis.Number.MAX_SAFE_INTEGER)throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");if(t<globalThis.Number.MIN_SAFE_INTEGER)throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");return t}var ci;function di(e){switch(e){case 0:case"NULL_VALUE":return ci.NULL_VALUE;default:return ci.UNRECOGNIZED}}!function(e){e[e.NULL_VALUE=0]="NULL_VALUE",e[e.UNRECOGNIZED=-1]="UNRECOGNIZED"}(ci||(ci={}));const ui={encode:(e,t=new ri)=>(Object.entries(e.fields).forEach((([e,r])=>{void 0!==r&&li.encode({key:e,value:r},t.uint32(10).fork()).join()})),t),decode(e,t){const r=e instanceof ni?e:new ni(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=li.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:fi(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=>ui.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 li={encode:(e,t=new ri)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&pi.encode(pi.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof ni?e:new ni(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=pi.unwrap(pi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:mi(e.key)?globalThis.String(e.key):"",value:mi(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=>li.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 pi={encode:(e,t=new ri)=>(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&&ui.encode(ui.wrap(e.structValue),t.uint32(42).fork()).join(),void 0!==e.listValue&&hi.encode(hi.wrap(e.listValue),t.uint32(50).fork()).join(),t),decode(e,t){const r=e instanceof ni?e:new ni(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=ui.unwrap(ui.decode(r,r.uint32()));continue;case 6:if(50!==e)break;i.listValue=hi.unwrap(hi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({nullValue:mi(e.nullValue)?di(e.nullValue):void 0,numberValue:mi(e.numberValue)?globalThis.Number(e.numberValue):void 0,stringValue:mi(e.stringValue)?globalThis.String(e.stringValue):void 0,boolValue:mi(e.boolValue)?globalThis.Boolean(e.boolValue):void 0,structValue:fi(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 ci.NULL_VALUE:return"NULL_VALUE";case ci.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=>pi.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=ci.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 hi={encode(e,t=new ri){for(const r of e.values)pi.encode(pi.wrap(r),t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof ni?e:new ni(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(pi.unwrap(pi.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=>hi.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 fi(e){return"object"==typeof e&&null!==e}function mi(e){return null!=e}const gi={encode:(e,t=new ri)=>(Object.entries(e.event).forEach((([e,r])=>{void 0!==r&&vi.encode({key:e,value:r},t.uint32(10).fork()).join()})),t),decode(e,t){const r=e instanceof ni?e:new ni(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=vi.decode(r,r.uint32());void 0!==t.value&&(i.event[t.key]=t.value);continue}}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON(e){return{event:(t=e.event,"object"==typeof t&&null!==t?Object.entries(e.event).reduce(((e,[t,r])=>(e[t]=r,e)),{}):{})};var t},toJSON(e){const t={};if(e.event){const r=Object.entries(e.event);r.length>0&&(t.event={},r.forEach((([e,r])=>{t.event[e]=r})))}return t},create:e=>gi.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 vi={encode:(e,t=new ri)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&pi.encode(pi.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof ni?e:new ni(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=pi.unwrap(pi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:yi(e.key)?globalThis.String(e.key):"",value:yi(null==e?void 0:e.value)?e.value:void 0}),toJSON(e){const t={};return""!==e.key&&(t.key=e.key),void 0!==e.value&&(t.value=e.value),t},create:e=>vi.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 yi(e){return null!=e}var _i,bi;function Ei(e){switch(e){case 0:case"PEER_GROUP_UNSPECIFIED":return _i.PEER_GROUP_UNSPECIFIED;case 1:case"PEER_GROUP_MODERATOR":return _i.PEER_GROUP_MODERATOR;case 2:case"PEER_GROUP_USER":return _i.PEER_GROUP_USER;default:return _i.UNRECOGNIZED}}function wi(e){switch(e){case _i.PEER_GROUP_UNSPECIFIED:return"PEER_GROUP_UNSPECIFIED";case _i.PEER_GROUP_MODERATOR:return"PEER_GROUP_MODERATOR";case _i.PEER_GROUP_USER:return"PEER_GROUP_USER";case _i.UNRECOGNIZED:default:return"UNRECOGNIZED"}}function Si(e){switch(e){case 0:case"PRODUCER_LABEL_UNSPECIFIED":return bi.PRODUCER_LABEL_UNSPECIFIED;case 1:case"PRODUCER_LABEL_CAMERA":return bi.PRODUCER_LABEL_CAMERA;case 2:case"PRODUCER_LABEL_MICROPHONE":return bi.PRODUCER_LABEL_MICROPHONE;case 3:case"PRODUCER_LABEL_SCREEN_VIDEO":return bi.PRODUCER_LABEL_SCREEN_VIDEO;case 4:case"PRODUCER_LABEL_SCREEN_AUDIO":return bi.PRODUCER_LABEL_SCREEN_AUDIO;case 5:case"PRODUCER_LABEL_CUSTOM_VIDEO":return bi.PRODUCER_LABEL_CUSTOM_VIDEO;case 6:case"PRODUCER_LABEL_CUSTOM_AUDIO":return bi.PRODUCER_LABEL_CUSTOM_AUDIO;case 7:case"PRODUCER_LABEL_UNKNOWN":return bi.PRODUCER_LABEL_UNKNOWN;default:return bi.UNRECOGNIZED}}function Ci(e){switch(e){case bi.PRODUCER_LABEL_UNSPECIFIED:return"PRODUCER_LABEL_UNSPECIFIED";case bi.PRODUCER_LABEL_CAMERA:return"PRODUCER_LABEL_CAMERA";case bi.PRODUCER_LABEL_MICROPHONE:return"PRODUCER_LABEL_MICROPHONE";case bi.PRODUCER_LABEL_SCREEN_VIDEO:return"PRODUCER_LABEL_SCREEN_VIDEO";case bi.PRODUCER_LABEL_SCREEN_AUDIO:return"PRODUCER_LABEL_SCREEN_AUDIO";case bi.PRODUCER_LABEL_CUSTOM_VIDEO:return"PRODUCER_LABEL_CUSTOM_VIDEO";case bi.PRODUCER_LABEL_CUSTOM_AUDIO:return"PRODUCER_LABEL_CUSTOM_AUDIO";case bi.PRODUCER_LABEL_UNKNOWN:return"PRODUCER_LABEL_UNKNOWN";case bi.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"}(_i||(_i={})),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"}(bi||(bi={}));const Pi={encode(e,t=new ri){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 ni?e:new ni(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=>Ei(e))):[],producePermissions:globalThis.Array.isArray(null==e?void 0:e.producePermissions)?e.producePermissions.map((e=>Si(e))):[],changedProducePermissions:globalThis.Array.isArray(null==e?void 0:e.changedProducePermissions)?e.changedProducePermissions.map((e=>Si(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=>wi(e)))),(null===(r=e.producePermissions)||void 0===r?void 0:r.length)&&(i.producePermissions=e.producePermissions.map((e=>Ci(e)))),(null===(n=e.changedProducePermissions)||void 0===n?void 0:n.length)&&(i.changedProducePermissions=e.changedProducePermissions.map((e=>Ci(e)))),i},create:e=>Pi.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 Ti={encode:(e,t=new ri)=>(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 ni?e:new ni(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=Ri(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:ki(e.seconds)?globalThis.Number(e.seconds):0,nanos:ki(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=>Ti.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 Ri(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 ki(e){return null!=e}var Di;function Ii(e){switch(e){case 0:case"PRODUCER_KIND_UNSPECIFIED":return Di.PRODUCER_KIND_UNSPECIFIED;case 1:case"PRODUCER_KIND_AUDIO":return Di.PRODUCER_KIND_AUDIO;case 2:case"PRODUCER_KIND_VIDEO":return Di.PRODUCER_KIND_VIDEO;default:return Di.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"}(Di||(Di={}));const Ai={encode(e,t=new ri){""!==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)pi.encode(pi.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 ni?e:new ni(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(pi.unwrap(pi.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:Oi(e.id)?globalThis.String(e.id):"",kind:Oi(e.kind)?Ii(e.kind):0,label:Oi(e.label)?Si(e.label):0,peerId:Oi(e.peerId)?globalThis.String(e.peerId):"",paused:!!Oi(e.paused)&&globalThis.Boolean(e.paused),encodings:globalThis.Array.isArray(null==e?void 0:e.encodings)?[...e.encodings]:[],maxSpatialLayer:Oi(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 Di.PRODUCER_KIND_UNSPECIFIED:return"PRODUCER_KIND_UNSPECIFIED";case Di.PRODUCER_KIND_AUDIO:return"PRODUCER_KIND_AUDIO";case Di.PRODUCER_KIND_VIDEO:return"PRODUCER_KIND_VIDEO";case Di.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.kind)),0!==e.label&&(r.label=Ci(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=>Ai.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 Oi(e){return null!=e}var Mi;function Ni(e){switch(e){case 0:case"PEER_ROLE_UNSPECIFIED":return Mi.PEER_ROLE_UNSPECIFIED;case 1:case"PEER_ROLE_HOST":return Mi.PEER_ROLE_HOST;case 2:case"PEER_ROLE_AUDIENCE":return Mi.PEER_ROLE_AUDIENCE;default:return Mi.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"}(Mi||(Mi={}));const Li={encode(e,t=new ri){""!==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)Ai.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&&xi.encode({key:e,value:r},t.uint32(66).fork()).join()})),0!==e.role&&t.uint32(72).int32(e.role),void 0!==e.loginDate&&Ti.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 ni?e:new ni(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(Ai.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=xi.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=Fi(Ti.decode(r,r.uint32()));continue;case 11:if(88===e){i.groups.push(r.int32());continue}if(90===e){const e=r.uint32()+r.pos;for(;r.pos<e;)i.groups.push(r.int32());continue}break;case 12:if(96===e){i.producePermissions.push(r.int32());continue}if(98===e){const e=r.uint32()+r.pos;for(;r.pos<e;)i.producePermissions.push(r.int32());continue}}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON(e){return{id:Ui(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=>Ai.fromJSON(e))):[],uid:Ui(e.uid)?globalThis.String(e.uid):"",appId:Ui(e.appId)?globalThis.String(e.appId):"",appData:(t=e.appData,"object"==typeof t&&null!==t?Object.entries(e.appData).reduce(((e,[t,r])=>(e[t]=r,e)),{}):{}),role:Ui(e.role)?Ni(e.role):0,loginDate:Ui(e.loginDate)?ji(e.loginDate):void 0,groups:globalThis.Array.isArray(null==e?void 0:e.groups)?e.groups.map((e=>Ei(e))):[],producePermissions:globalThis.Array.isArray(null==e?void 0:e.producePermissions)?e.producePermissions.map((e=>Si(e))):[]};var t},toJSON(e){var t,r,n,i;const s={};if(""!==e.id&&(s.id=e.id),(null===(t=e.channelIds)||void 0===t?void 0:t.length)&&(s.channelIds=e.channelIds),(null===(r=e.producers)||void 0===r?void 0:r.length)&&(s.producers=e.producers.map((e=>Ai.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 Mi.PEER_ROLE_UNSPECIFIED:return"PEER_ROLE_UNSPECIFIED";case Mi.PEER_ROLE_HOST:return"PEER_ROLE_HOST";case Mi.PEER_ROLE_AUDIENCE:return"PEER_ROLE_AUDIENCE";case Mi.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=>wi(e)))),(null===(i=e.producePermissions)||void 0===i?void 0:i.length)&&(s.producePermissions=e.producePermissions.map((e=>Ci(e)))),s},create:e=>Li.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=>Ai.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 xi={encode:(e,t=new ri)=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&pi.encode(pi.wrap(e.value),t.uint32(18).fork()).join(),t),decode(e,t){const r=e instanceof ni?e:new ni(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=pi.unwrap(pi.decode(r,r.uint32()));continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({key:Ui(e.key)?globalThis.String(e.key):"",value:Ui(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=>xi.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 Fi(e){let t=1e3*(e.seconds||0);return t+=(e.nanos||0)/1e6,new globalThis.Date(t)}function ji(e){return e instanceof globalThis.Date?e:"string"==typeof e?new globalThis.Date(e):Fi(Ti.fromJSON(e))}function Ui(e){return null!=e}const Vi={encode(e,t=new ri){for(const r of e.peers)Li.encode(r,t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof ni?e:new ni(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(Li.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=>Li.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=>Li.toJSON(e)))),r},create:e=>Vi.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=>Li.fromPartial(e))))||[],r}};const Bi={encode:(e,t=new ri)=>(""!==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 ni?e:new ni(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:qi(e.id)?globalThis.String(e.id):"",paused:!!qi(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=>Bi.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 Wi={encode(e,t=new ri){""!==e.id&&t.uint32(10).string(e.id);for(const r of e.producers)Bi.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 ni?e:new ni(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(Bi.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:qi(e.id)?globalThis.String(e.id):"",producers:globalThis.Array.isArray(null==e?void 0:e.producers)?e.producers.map((e=>Bi.fromJSON(e))):[],appDataHash:qi(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=>Bi.toJSON(e)))),void 0!==e.appDataHash&&(r.appDataHash=e.appDataHash),r},create:e=>Wi.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=>Bi.fromPartial(e))))||[],i.appDataHash=null!==(n=e.appDataHash)&&void 0!==n?n:void 0,i}};const Hi={encode(e,t=new ri){for(const r of e.peers)Wi.encode(r,t.uint32(10).fork()).join();return t},decode(e,t){const r=e instanceof ni?e:new ni(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(Wi.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=>Wi.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=>Wi.toJSON(e)))),r},create:e=>Hi.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=>Wi.fromPartial(e))))||[],r}};function qi(e){return null!=e}var zi;function Gi(e){switch(e){case 0:case"CHANNEL_EVENT_TYPE_UNSPECIFIED":return zi.CHANNEL_EVENT_TYPE_UNSPECIFIED;case 1:case"CHANNEL_EVENT_TYPE_CHANNEL_STATE":return zi.CHANNEL_EVENT_TYPE_CHANNEL_STATE;case 2:case"CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT":return zi.CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT;case 3:case"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED":return zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED;case 4:case"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED":return zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED;case 5:case"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED":return zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED;case 6:case"CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED":return zi.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED;case 7:case"CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED":return zi.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED;case 8:case"CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT":return zi.CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT;case 14:case"CHANNEL_EVENT_TYPE_PEER_JOINED":return zi.CHANNEL_EVENT_TYPE_PEER_JOINED;case 15:case"CHANNEL_EVENT_TYPE_PEER_LEFT":return zi.CHANNEL_EVENT_TYPE_PEER_LEFT;case 16:case"CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED":return zi.CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED;case 17:case"CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED":return zi.CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED;case 18:case"CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED":return zi.CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED;default:return zi.UNRECOGNIZED}}function Yi(e){switch(e){case zi.CHANNEL_EVENT_TYPE_UNSPECIFIED:return"CHANNEL_EVENT_TYPE_UNSPECIFIED";case zi.CHANNEL_EVENT_TYPE_CHANNEL_STATE:return"CHANNEL_EVENT_TYPE_CHANNEL_STATE";case zi.CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT:return"CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT";case zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED:return"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED";case zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED:return"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED";case zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED:return"CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED";case zi.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED:return"CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED";case zi.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED:return"CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_DELETED";case zi.CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT:return"CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT";case zi.CHANNEL_EVENT_TYPE_PEER_JOINED:return"CHANNEL_EVENT_TYPE_PEER_JOINED";case zi.CHANNEL_EVENT_TYPE_PEER_LEFT:return"CHANNEL_EVENT_TYPE_PEER_LEFT";case zi.CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED:return"CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED";case zi.CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED:return"CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED";case zi.CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED:return"CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED";case zi.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"}(zi||(zi={}));const $i={encode:(e,t=new ri)=>(0!==e.eventType&&t.uint32(8).int32(e.eventType),void 0!==e.channelState&&Vi.encode(e.channelState,t.uint32(18).fork()).join(),void 0!==e.channelStateShort&&Hi.encode(e.channelStateShort,t.uint32(26).fork()).join(),void 0!==e.channelActivityConfirmationTime&&oi.encode(e.channelActivityConfirmationTime,t.uint32(34).fork()).join(),void 0!==e.channelManagementEvent&&gi.encode(e.channelManagementEvent,t.uint32(42).fork()).join(),void 0!==e.channelProducePermissions&&Pi.encode(e.channelProducePermissions,t.uint32(50).fork()).join(),void 0!==e.peer&&Li.encode(e.peer,t.uint32(58).fork()).join(),t),decode(e,t){const r=e instanceof ni?e:new ni(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=Vi.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.channelStateShort=Hi.decode(r,r.uint32());continue;case 4:if(34!==e)break;i.channelActivityConfirmationTime=oi.decode(r,r.uint32());continue;case 5:if(42!==e)break;i.channelManagementEvent=gi.decode(r,r.uint32());continue;case 6:if(50!==e)break;i.channelProducePermissions=Pi.decode(r,r.uint32());continue;case 7:if(58!==e)break;i.peer=Li.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({eventType:Ji(e.eventType)?Gi(e.eventType):0,channelState:Ji(e.channelState)?Vi.fromJSON(e.channelState):void 0,channelStateShort:Ji(e.channelStateShort)?Hi.fromJSON(e.channelStateShort):void 0,channelActivityConfirmationTime:Ji(e.channelActivityConfirmationTime)?oi.fromJSON(e.channelActivityConfirmationTime):void 0,channelManagementEvent:Ji(e.channelManagementEvent)?gi.fromJSON(e.channelManagementEvent):void 0,channelProducePermissions:Ji(e.channelProducePermissions)?Pi.fromJSON(e.channelProducePermissions):void 0,peer:Ji(e.peer)?Li.fromJSON(e.peer):void 0}),toJSON(e){const t={};return 0!==e.eventType&&(t.eventType=Yi(e.eventType)),void 0!==e.channelState&&(t.channelState=Vi.toJSON(e.channelState)),void 0!==e.channelStateShort&&(t.channelStateShort=Hi.toJSON(e.channelStateShort)),void 0!==e.channelActivityConfirmationTime&&(t.channelActivityConfirmationTime=oi.toJSON(e.channelActivityConfirmationTime)),void 0!==e.channelManagementEvent&&(t.channelManagementEvent=gi.toJSON(e.channelManagementEvent)),void 0!==e.channelProducePermissions&&(t.channelProducePermissions=Pi.toJSON(e.channelProducePermissions)),void 0!==e.peer&&(t.peer=Li.toJSON(e.peer)),t},create:e=>$i.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?Vi.fromPartial(e.channelState):void 0,r.channelStateShort=void 0!==e.channelStateShort&&null!==e.channelStateShort?Hi.fromPartial(e.channelStateShort):void 0,r.channelActivityConfirmationTime=void 0!==e.channelActivityConfirmationTime&&null!==e.channelActivityConfirmationTime?oi.fromPartial(e.channelActivityConfirmationTime):void 0,r.channelManagementEvent=void 0!==e.channelManagementEvent&&null!==e.channelManagementEvent?gi.fromPartial(e.channelManagementEvent):void 0,r.channelProducePermissions=void 0!==e.channelProducePermissions&&null!==e.channelProducePermissions?Pi.fromPartial(e.channelProducePermissions):void 0,r.peer=void 0!==e.peer&&null!==e.peer?Li.fromPartial(e.peer):void 0,r}};function Ji(e){return null!=e}const Qi={encode:(e,t=new ri)=>(""!==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 ni?e:new ni(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:Ki(e.id)?globalThis.String(e.id):"",peerId:Ki(e.peerId)?globalThis.String(e.peerId):"",producerPeerId:Ki(e.producerPeerId)?globalThis.String(e.producerPeerId):"",spatialLayer:Ki(e.spatialLayer)?globalThis.Number(e.spatialLayer):void 0,temporalLayer:Ki(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=>Qi.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 Ki(e){return null!=e}const Zi={encode:(e,t=new ri)=>(""!==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 ni?e:new ni(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:Xi(e.producerId)?globalThis.String(e.producerId):"",spatialLayer:Xi(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=>Zi.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 Xi(e){return null!=e}var es,ts;function rs(e){switch(e){case 0:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED":return es.TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED;case 1:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS":return es.TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS;case 2:case"TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE":return es.TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE;default:return es.UNRECOGNIZED}}function ns(e){switch(e){case 0:case"TRANSPORT_DIRECTION_UNSPECIFIED":return ts.TRANSPORT_DIRECTION_UNSPECIFIED;case 1:case"TRANSPORT_DIRECTION_SEND":return ts.TRANSPORT_DIRECTION_SEND;case 2:case"TRANSPORT_DIRECTION_RECEIVE":return ts.TRANSPORT_DIRECTION_RECEIVE;default:return ts.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"}(es||(es={})),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"}(ts||(ts={}));const is={encode:(e,t=new ri)=>(""!==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 ni?e:new ni(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:ss(e.transportId)?globalThis.String(e.transportId):"",timeout:ss(e.timeout)?globalThis.Number(e.timeout):0,direction:ss(e.direction)?ns(e.direction):0,reason:ss(e.reason)?rs(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 ts.TRANSPORT_DIRECTION_UNSPECIFIED:return"TRANSPORT_DIRECTION_UNSPECIFIED";case ts.TRANSPORT_DIRECTION_SEND:return"TRANSPORT_DIRECTION_SEND";case ts.TRANSPORT_DIRECTION_RECEIVE:return"TRANSPORT_DIRECTION_RECEIVE";case ts.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.direction)),0!==e.reason&&(t.reason=function(e){switch(e){case es.TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_UNSPECIFIED";case es.TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_DTLS";case es.TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE:return"TRANSPORT_CONNECTION_TIMEOUT_REASON_ICE";case es.UNRECOGNIZED:default:return"UNRECOGNIZED"}}(e.reason)),t},create:e=>is.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 ss(e){return null!=e}var os;function as(e){switch(e){case 0:case"MEDIA_EVENT_TYPE_UNSPECIFIED":return os.MEDIA_EVENT_TYPE_UNSPECIFIED;case 1:case"MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT":return os.MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT;case 2:case"MEDIA_EVENT_TYPE_PRODUCER_CREATED":return os.MEDIA_EVENT_TYPE_PRODUCER_CREATED;case 3:case"MEDIA_EVENT_TYPE_PRODUCER_PAUSED":return os.MEDIA_EVENT_TYPE_PRODUCER_PAUSED;case 4:case"MEDIA_EVENT_TYPE_PRODUCER_RESUMED":return os.MEDIA_EVENT_TYPE_PRODUCER_RESUMED;case 5:case"MEDIA_EVENT_TYPE_PRODUCER_CLOSED":return os.MEDIA_EVENT_TYPE_PRODUCER_CLOSED;case 6:case"MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED":return os.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED;case 7:case"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED":return os.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED;case 8:case"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED":return os.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED;case 9:case"MEDIA_EVENT_TYPE_CONSUMER_CLOSED":return os.MEDIA_EVENT_TYPE_CONSUMER_CLOSED;case 10:case"MEDIA_EVENT_TYPE_CONSUMER_PAUSED":return os.MEDIA_EVENT_TYPE_CONSUMER_PAUSED;case 11:case"MEDIA_EVENT_TYPE_CONSUMER_RESUMED":return os.MEDIA_EVENT_TYPE_CONSUMER_RESUMED;case 12:case"MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED":return os.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED;default:return os.UNRECOGNIZED}}function cs(e){switch(e){case os.MEDIA_EVENT_TYPE_UNSPECIFIED:return"MEDIA_EVENT_TYPE_UNSPECIFIED";case os.MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT:return"MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT";case os.MEDIA_EVENT_TYPE_PRODUCER_CREATED:return"MEDIA_EVENT_TYPE_PRODUCER_CREATED";case os.MEDIA_EVENT_TYPE_PRODUCER_PAUSED:return"MEDIA_EVENT_TYPE_PRODUCER_PAUSED";case os.MEDIA_EVENT_TYPE_PRODUCER_RESUMED:return"MEDIA_EVENT_TYPE_PRODUCER_RESUMED";case os.MEDIA_EVENT_TYPE_PRODUCER_CLOSED:return"MEDIA_EVENT_TYPE_PRODUCER_CLOSED";case os.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED:return"MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED";case os.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED:return"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED";case os.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED:return"MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED";case os.MEDIA_EVENT_TYPE_CONSUMER_CLOSED:return"MEDIA_EVENT_TYPE_CONSUMER_CLOSED";case os.MEDIA_EVENT_TYPE_CONSUMER_PAUSED:return"MEDIA_EVENT_TYPE_CONSUMER_PAUSED";case os.MEDIA_EVENT_TYPE_CONSUMER_RESUMED:return"MEDIA_EVENT_TYPE_CONSUMER_RESUMED";case os.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED:return"MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED";case os.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"}(os||(os={}));const ds={encode:(e,t=new ri)=>(0!==e.eventType&&t.uint32(8).int32(e.eventType),void 0!==e.producer&&Ai.encode(e.producer,t.uint32(18).fork()).join(),void 0!==e.consumer&&Qi.encode(e.consumer,t.uint32(26).fork()).join(),void 0!==e.producerSpatialLayerRequest&&Zi.encode(e.producerSpatialLayerRequest,t.uint32(34).fork()).join(),void 0!==e.transportConnectionTimeout&&is.encode(e.transportConnectionTimeout,t.uint32(42).fork()).join(),t),decode(e,t){const r=e instanceof ni?e:new ni(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=Ai.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.consumer=Qi.decode(r,r.uint32());continue;case 4:if(34!==e)break;i.producerSpatialLayerRequest=Zi.decode(r,r.uint32());continue;case 5:if(42!==e)break;i.transportConnectionTimeout=is.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({eventType:us(e.eventType)?as(e.eventType):0,producer:us(e.producer)?Ai.fromJSON(e.producer):void 0,consumer:us(e.consumer)?Qi.fromJSON(e.consumer):void 0,producerSpatialLayerRequest:us(e.producerSpatialLayerRequest)?Zi.fromJSON(e.producerSpatialLayerRequest):void 0,transportConnectionTimeout:us(e.transportConnectionTimeout)?is.fromJSON(e.transportConnectionTimeout):void 0}),toJSON(e){const t={};return 0!==e.eventType&&(t.eventType=cs(e.eventType)),void 0!==e.producer&&(t.producer=Ai.toJSON(e.producer)),void 0!==e.consumer&&(t.consumer=Qi.toJSON(e.consumer)),void 0!==e.producerSpatialLayerRequest&&(t.producerSpatialLayerRequest=Zi.toJSON(e.producerSpatialLayerRequest)),void 0!==e.transportConnectionTimeout&&(t.transportConnectionTimeout=is.toJSON(e.transportConnectionTimeout)),t},create:e=>ds.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?Ai.fromPartial(e.producer):void 0,r.consumer=void 0!==e.consumer&&null!==e.consumer?Qi.fromPartial(e.consumer):void 0,r.producerSpatialLayerRequest=void 0!==e.producerSpatialLayerRequest&&null!==e.producerSpatialLayerRequest?Zi.fromPartial(e.producerSpatialLayerRequest):void 0,r.transportConnectionTimeout=void 0!==e.transportConnectionTimeout&&null!==e.transportConnectionTimeout?is.fromPartial(e.transportConnectionTimeout):void 0,r}};function us(e){return null!=e}const ls={encode:(e,t=new ri)=>(0!==e.id&&t.uint32(8).int32(e.id),void 0!==e.channelEvent&&$i.encode(e.channelEvent,t.uint32(18).fork()).join(),void 0!==e.mediaEvent&&ds.encode(e.mediaEvent,t.uint32(26).fork()).join(),t),decode(e,t){const r=e instanceof ni?e:new ni(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=$i.decode(r,r.uint32());continue;case 3:if(26!==e)break;i.mediaEvent=ds.decode(r,r.uint32());continue}if(4==(7&e)||0===e)break;r.skip(7&e)}return i},fromJSON:e=>({id:ps(e.id)?globalThis.Number(e.id):0,channelEvent:ps(e.channelEvent)?$i.fromJSON(e.channelEvent):void 0,mediaEvent:ps(e.mediaEvent)?ds.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=$i.toJSON(e.channelEvent)),void 0!==e.mediaEvent&&(t.mediaEvent=ds.toJSON(e.mediaEvent)),t},create:e=>ls.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?$i.fromPartial(e.channelEvent):void 0,r.mediaEvent=void 0!==e.mediaEvent&&null!==e.mediaEvent?ds.fromPartial(e.mediaEvent):void 0,r}};function ps(e){return null!=e}var hs,fs,ms,gs,vs,ys,_s,bs;let Es=class{constructor(e){hs.set(this,[]),fs.set(this,!1),ms.set(this,!1),gs.set(this,void 0),vs.set(this,void 0),ys.set(this,new Map),_s.set(this,void 0),bs.set(this,new Set),u(this,_s,e("EventsQueue"),"f")}setMediaEventHandler(e){u(this,gs,e,"f"),d(this,_s,"f").info("Media event handler set",{case:"EventsQueue"})}setChannelEventHandler(e){u(this,vs,e,"f"),d(this,_s,"f").info("Channel event handler set",{case:"EventsQueue"})}subscribe(e){u(this,bs,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=ls.decode(n);i.id&&(d(this,bs,"f").has(i.id)&&d(this,_s,"f").warn("Received duplicate message",{case:"EventsQueue",lastReceivedMsgId:t,currentReceivedMsgId:i.id}),i.id>t+1&&d(this,_s,"f").warn("Received out of order message",{case:"EventsQueue",lastReceivedMsgId:t,currentReceivedMsgId:i.id})),d(this,bs,"f").add(i.id),t=i.id,this.push(i)}catch(e){d(this,_s,"f").error("Failed to parse channel message",{error:Pt(e),case:"EventsQueue"})}},n=()=>{e.removeListener("message",r),e.removeListener("close",n)};e.on("close",n),e.on("message",r),d(this,_s,"f").info("Subscribed to data channel",{case:"EventsQueue"})}push(e){d(this,hs,"f").push(e),this.process()}process(){return c(this,void 0,void 0,(function*(){if(!d(this,fs,"f")&&!d(this,ms,"f")){for(u(this,ms,!0,"f");!d(this,fs,"f")&&d(this,hs,"f").length>0;){const e=d(this,hs,"f").shift();if(e)try{if(e.channelEvent&&d(this,vs,"f")){d(this,_s,"f").debug("Handle channel event",{case:"EventsQueue",id:e.id,type:Yi(e.channelEvent.eventType),event:e.channelEvent}),yield d(this,vs,"f").call(this,e.channelEvent);continue}if(e.mediaEvent&&d(this,gs,"f")){d(this,_s,"f").debug("Handle media event",{case:"EventsQueue",id:e.id,type:cs(e.mediaEvent.eventType),event:e.mediaEvent}),yield d(this,gs,"f").call(this,e.mediaEvent);continue}d(this,_s,"f").warn("Received unknown message",{message:e,case:"EventsQueue"})}catch(t){d(this,_s,"f").error("Failed to handle event",{case:"EventsQueue",id:e.id,error:Pt(t)})}}u(this,ms,!1,"f"),!d(this,fs,"f")&&d(this,hs,"f").length>0&&queueMicrotask((()=>{this.process()}))}}))}processMessageChunk(e){const t=new Uint8Array(e);if(t.length<12)return void d(this,_s,"f").warn("Chunk too small",{case:"EventsQueue",bytesLength:t.length});const{msgId:r,index:n,total:i}=this.parseMessageChunkHeader(t),s=t.slice(12);d(this,ys,"f").has(r)||d(this,ys,"f").set(r,{msgId:r,total:i,received:[]});const o=d(this,ys,"f").get(r);if(o)return o.received[n]=s,o.msgId=r,o;d(this,_s,"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 d(this,ys,"f").delete(e.msgId),t}pause(){u(this,fs,!0,"f")}size(){return d(this,hs,"f").length}resume(){u(this,fs,!1,"f"),this.process()}isMessageReceived(e){return d(this,bs,"f").has(e)}};hs=new WeakMap,fs=new WeakMap,ms=new WeakMap,gs=new WeakMap,vs=new WeakMap,ys=new WeakMap,_s=new WeakMap,bs=new WeakMap,Es=s([ct(),o(0,ut(Nn.LoggerFactory)),a("design:paramtypes",[Function])],Es);var ws=Es;function Ss(e){return{id:e.id,appId:e.appId,role:e.role,groups:e.groups,producePermissions:e.producePermissions}}let Cs=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)}};Cs=s([ct()],Cs);const Ps=["no media section found for reuseMid","Duplicate a=msid lines detected"];class Ts extends vn{constructor(e,t,r){super(null!=e?e:Ts.DEFAULT_MESSAGE,null!=t?t:"already_connected",r)}}Ts.DEFAULT_MESSAGE="Peer is already connected";const Rs=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 ks(e){return!e.response&&(!!e.code&&(!["ERR_CANCELED","ECONNABORTED"].includes(e.code)&&(e=>!Rs.has(e&&e.code))(e)))}const Ds=["get","head","options"],Is=Ds.concat(["put","delete"]);function As(e){return"ECONNABORTED"!==e.code&&(!e.response||429===e.response.status||e.response.status>=500&&e.response.status<=599)}function Os(e){return!!e.config?.method&&(As(e)&&-1!==Is.indexOf(e.config.method))}function Ms(e){return ks(e)||Os(e)}function Ns(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 Ls={retries:3,retryCondition:Ms,retryDelay:function(e=0,t){return Math.max(0,Ns(t))},shouldResetTimeout:!1,onRetry:()=>{},onMaxRetryTimesExceeded:()=>{},validateResponse:null};function xs(e,t,r=!1){const n=function(e,t){return{...Ls,...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 Fs=(e,t)=>{const r=e.interceptors.request.use((e=>(xs(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=xs(n,t);return r.response&&i.validateResponse?.(r.response)?r.response:await async function(e,t){const{retries:r,retryCondition:n}=e,i=(e.retryCount||0)<r&&n(t);if("object"==typeof i)try{return!1!==await i}catch(e){return!1}return i}(i,r)?async function(e,t,r,n){t.retryCount+=1;const{retryDelay:i,shouldResetTimeout:s,onRetry:o}=t,a=i(t.retryCount,r);if(function(e,t){e.defaults.agent===t.agent&&delete t.agent,e.defaults.httpAgent===t.httpAgent&&delete t.httpAgent,e.defaults.httpsAgent===t.httpsAgent&&delete t.httpsAgent}(e,n),!s&&n.timeout&&t.lastRequestTime){const e=Date.now()-t.lastRequestTime,i=n.timeout-e-a;if(i<=0)return Promise.reject(r);n.timeout=i}return n.transformRequest=[e=>e],await o(t.retryCount,r,n),n.signal?.aborted?Promise.resolve(e(n)):new Promise((t=>{const r=()=>{clearTimeout(i),t(e(n))},i=setTimeout((()=>{t(e(n)),n.signal?.removeEventListener&&n.signal.removeEventListener("abort",r)}),a);n.signal?.addEventListener&&n.signal.addEventListener("abort",r,{once:!0})}))}(e,i,r,n):(await async function(e,t){e.retryCount>=e.retries&&await e.onMaxRetryTimesExceeded(t,e.retryCount)}(i,r),Promise.reject(r))}));return{requestInterceptorId:r,responseInterceptorId:n}};function js(e,t){return function(){return e.apply(t,arguments)}}Fs.isNetworkError=ks,Fs.isSafeRequestError=function(e){return!!e.config?.method&&(As(e)&&-1!==Ds.indexOf(e.config.method))},Fs.isIdempotentRequestError=Os,Fs.isNetworkOrIdempotentRequestError=Ms,Fs.exponentialDelay=function(e=0,t,r=100){const n=2**e*r,i=Math.max(n,Ns(t));return i+.2*i*Math.random()},Fs.linearDelay=function(e=100){return(t=0,r)=>{const n=t*e;return Math.max(n,Ns(r))}},Fs.isRetryableError=As;const{toString:Us}=Object.prototype,{getPrototypeOf:Vs}=Object,{iterator:Bs,toStringTag:Ws}=Symbol,Hs=(qs=Object.create(null),e=>{const t=Us.call(e);return qs[t]||(qs[t]=t.slice(8,-1).toLowerCase())});var qs;const zs=e=>(e=e.toLowerCase(),t=>Hs(t)===e),Gs=e=>t=>typeof t===e,{isArray:Ys}=Array,$s=Gs("undefined");const Js=zs("ArrayBuffer");const Qs=Gs("string"),Ks=Gs("function"),Zs=Gs("number"),Xs=e=>null!==e&&"object"==typeof e,eo=e=>{if("object"!==Hs(e))return!1;const t=Vs(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Ws in e||Bs in e)},to=zs("Date"),ro=zs("File"),no=zs("Blob"),io=zs("FileList"),so=zs("URLSearchParams"),[oo,ao,co,uo]=["ReadableStream","Request","Response","Headers"].map(zs);function lo(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,i;if("object"!=typeof e&&(e=[e]),Ys(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{const i=r?Object.getOwnPropertyNames(e):Object.keys(e),s=i.length;let o;for(n=0;n<s;n++)o=i[n],t.call(null,e[o],o,e)}}function po(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,i=r.length;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}const ho="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,fo=e=>!$s(e)&&e!==ho;const mo=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Vs(Uint8Array)),go=zs("HTMLFormElement"),vo=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),yo=zs("RegExp"),_o=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};lo(r,((r,i)=>{let s;!1!==(s=t(r,i,e))&&(n[i]=s||r)})),Object.defineProperties(e,n)};const bo=zs("AsyncFunction"),Eo=(wo="function"==typeof setImmediate,So=Ks(ho.postMessage),wo?setImmediate:So?(Co=`axios@${Math.random()}`,Po=[],ho.addEventListener("message",(({source:e,data:t})=>{e===ho&&t===Co&&Po.length&&Po.shift()()}),!1),e=>{Po.push(e),ho.postMessage(Co,"*")}):e=>setTimeout(e));var wo,So,Co,Po;const To="undefined"!=typeof queueMicrotask?queueMicrotask.bind(ho):"undefined"!=typeof process&&process.nextTick||Eo;var Ro={isArray:Ys,isArrayBuffer:Js,isBuffer:function(e){return null!==e&&!$s(e)&&null!==e.constructor&&!$s(e.constructor)&&Ks(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Ks(e.append)&&("formdata"===(t=Hs(e))||"object"===t&&Ks(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Js(e.buffer),t},isString:Qs,isNumber:Zs,isBoolean:e=>!0===e||!1===e,isObject:Xs,isPlainObject:eo,isReadableStream:oo,isRequest:ao,isResponse:co,isHeaders:uo,isUndefined:$s,isDate:to,isFile:ro,isBlob:no,isRegExp:yo,isFunction:Ks,isStream:e=>Xs(e)&&Ks(e.pipe),isURLSearchParams:so,isTypedArray:mo,isFileList:io,forEach:lo,merge:function e(){const{caseless:t}=fo(this)&&this||{},r={},n=(n,i)=>{const s=t&&po(r,i)||i;eo(r[s])&&eo(n)?r[s]=e(r[s],n):eo(n)?r[s]=e({},n):Ys(n)?r[s]=n.slice():r[s]=n};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&lo(arguments[e],n);return r},extend:(e,t,r,{allOwnKeys:n}={})=>(lo(t,((t,n)=>{r&&Ks(t)?e[n]=js(t,r):e[n]=t}),{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let i,s,o;const a={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),s=i.length;s-- >0;)o=i[s],n&&!n(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==r&&Vs(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:Hs,kindOfTest:zs,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(Ys(e))return e;let t=e.length;if(!Zs(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Bs]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:go,hasOwnProperty:vo,hasOwnProp:vo,reduceDescriptors:_o,freezeMethods:e=>{_o(e,((t,r)=>{if(Ks(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];Ks(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach((e=>{r[e]=!0}))};return Ys(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:po,global:ho,isContextDefined:fo,isSpecCompliantForm:function(e){return!!(e&&Ks(e.append)&&"FormData"===e[Ws]&&e[Bs])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(Xs(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const i=Ys(e)?[]:{};return lo(e,((e,t)=>{const s=r(e,n+1);!$s(s)&&(i[t]=s)})),t[n]=void 0,i}}return e};return r(e,0)},isAsyncFn:bo,isThenable:e=>e&&(Xs(e)||Ks(e))&&Ks(e.then)&&Ks(e.catch),setImmediate:Eo,asap:To,isIterable:e=>null!=e&&Ks(e[Bs])};function ko(e,t,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}Ro.inherits(ko,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:Ro.toJSONObject(this.config),code:this.code,status:this.status}}});const Do=ko.prototype,Io={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{Io[e]={value:e}})),Object.defineProperties(ko,Io),Object.defineProperty(Do,"isAxiosError",{value:!0}),ko.from=(e,t,r,n,i,s)=>{const o=Object.create(Do);return Ro.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),ko.call(o,e.message,t,r,n,i),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function Ao(e){return Ro.isPlainObject(e)||Ro.isArray(e)}function Oo(e){return Ro.endsWith(e,"[]")?e.slice(0,-2):e}function Mo(e,t,r){return e?e.concat(t).map((function(e,t){return e=Oo(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const No=Ro.toFlatObject(Ro,{},null,(function(e){return/^is[A-Z]/.test(e)}));function Lo(e,t,r){if(!Ro.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=Ro.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!Ro.isUndefined(t[e])}))).metaTokens,i=r.visitor||d,s=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&Ro.isSpecCompliantForm(t);if(!Ro.isFunction(i))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(Ro.isDate(e))return e.toISOString();if(Ro.isBoolean(e))return e.toString();if(!a&&Ro.isBlob(e))throw new ko("Blob is not supported. Use a Buffer instead.");return Ro.isArrayBuffer(e)||Ro.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,r,i){let a=e;if(e&&!i&&"object"==typeof e)if(Ro.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(Ro.isArray(e)&&function(e){return Ro.isArray(e)&&!e.some(Ao)}(e)||(Ro.isFileList(e)||Ro.endsWith(r,"[]"))&&(a=Ro.toArray(e)))return r=Oo(r),a.forEach((function(e,n){!Ro.isUndefined(e)&&null!==e&&t.append(!0===o?Mo([r],n,s):null===o?r:r+"[]",c(e))})),!1;return!!Ao(e)||(t.append(Mo(i,r,s),c(e)),!1)}const u=[],l=Object.assign(No,{defaultVisitor:d,convertValue:c,isVisitable:Ao});if(!Ro.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!Ro.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+n.join("."));u.push(r),Ro.forEach(r,(function(r,s){!0===(!(Ro.isUndefined(r)||null===r)&&i.call(t,r,Ro.isString(s)?s.trim():s,n,l))&&e(r,n?n.concat(s):[s])})),u.pop()}}(e),t}function xo(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function Fo(e,t){this._pairs=[],e&&Lo(e,this,t)}const jo=Fo.prototype;function Uo(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Vo(e,t,r){if(!t)return e;const n=r&&r.encode||Uo;Ro.isFunction(r)&&(r={serialize:r});const i=r&&r.serialize;let s;if(s=i?i(t,r):Ro.isURLSearchParams(t)?t.toString():new Fo(t,r).toString(n),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}jo.append=function(e,t){this._pairs.push([e,t])},jo.toString=function(e){const t=e?function(t){return e.call(this,t,xo)}:xo;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var Bo=class{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){Ro.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},Wo={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ho={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Fo,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const qo="undefined"!=typeof window&&"undefined"!=typeof document,zo="object"==typeof navigator&&navigator||void 0,Go=qo&&(!zo||["ReactNative","NativeScript","NS"].indexOf(zo.product)<0),Yo="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,$o=qo&&window.location.href||"http://localhost";var Jo={...Object.freeze({__proto__:null,hasBrowserEnv:qo,hasStandardBrowserWebWorkerEnv:Yo,hasStandardBrowserEnv:Go,navigator:zo,origin:$o}),...Ho};function Qo(e){function t(e,r,n,i){let s=e[i++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=i>=e.length;if(s=!s&&Ro.isArray(n)?n.length:s,a)return Ro.hasOwnProp(n,s)?n[s]=[n[s],r]:n[s]=r,!o;n[s]&&Ro.isObject(n[s])||(n[s]=[]);return t(e,r,n[s],i)&&Ro.isArray(n[s])&&(n[s]=function(e){const t={},r=Object.keys(e);let n;const i=r.length;let s;for(n=0;n<i;n++)s=r[n],t[s]=e[s];return t}(n[s])),!o}if(Ro.isFormData(e)&&Ro.isFunction(e.entries)){const r={};return Ro.forEachEntry(e,((e,n)=>{t(function(e){return Ro.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null}const Ko={transitional:Wo,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,i=Ro.isObject(e);i&&Ro.isHTMLForm(e)&&(e=new FormData(e));if(Ro.isFormData(e))return n?JSON.stringify(Qo(e)):e;if(Ro.isArrayBuffer(e)||Ro.isBuffer(e)||Ro.isStream(e)||Ro.isFile(e)||Ro.isBlob(e)||Ro.isReadableStream(e))return e;if(Ro.isArrayBufferView(e))return e.buffer;if(Ro.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Lo(e,new Jo.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return Jo.isNode&&Ro.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=Ro.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Lo(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return i||n?(t.setContentType("application/json",!1),function(e,t,r){if(Ro.isString(e))try{return(t||JSON.parse)(e),Ro.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Ko.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(Ro.isResponse(e)||Ro.isReadableStream(e))return e;if(e&&Ro.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw ko.from(e,ko.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Jo.classes.FormData,Blob:Jo.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Ro.forEach(["delete","get","head","post","put","patch"],(e=>{Ko.headers[e]={}}));var Zo=Ko;const Xo=Ro.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const ea=Symbol("internals");function ta(e){return e&&String(e).trim().toLowerCase()}function ra(e){return!1===e||null==e?e:Ro.isArray(e)?e.map(ra):String(e)}function na(e,t,r,n,i){return Ro.isFunction(n)?n.call(this,t,r):(i&&(t=r),Ro.isString(t)?Ro.isString(n)?-1!==t.indexOf(n):Ro.isRegExp(n)?n.test(t):void 0:void 0)}class ia{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function i(e,t,r){const i=ta(t);if(!i)throw new Error("header name must be a non-empty string");const s=Ro.findKey(n,i);(!s||void 0===n[s]||!0===r||void 0===r&&!1!==n[s])&&(n[s||t]=ra(e))}const s=(e,t)=>Ro.forEach(e,((e,r)=>i(e,r,t)));if(Ro.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(Ro.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let r,n,i;return e&&e.split("\n").forEach((function(e){i=e.indexOf(":"),r=e.substring(0,i).trim().toLowerCase(),n=e.substring(i+1).trim(),!r||t[r]&&Xo[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t);else if(Ro.isObject(e)&&Ro.isIterable(e)){let r,n,i={};for(const t of e){if(!Ro.isArray(t))throw TypeError("Object iterator must return a key-value pair");i[n=t[0]]=(r=i[n])?Ro.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}s(i,t)}else null!=e&&i(t,e,r);return this}get(e,t){if(e=ta(e)){const r=Ro.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(Ro.isFunction(t))return t.call(this,e,r);if(Ro.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=ta(e)){const r=Ro.findKey(this,e);return!(!r||void 0===this[r]||t&&!na(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function i(e){if(e=ta(e)){const i=Ro.findKey(r,e);!i||t&&!na(0,r[i],i,t)||(delete r[i],n=!0)}}return Ro.isArray(e)?e.forEach(i):i(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const i=t[r];e&&!na(0,this[i],i,e,!0)||(delete this[i],n=!0)}return n}normalize(e){const t=this,r={};return Ro.forEach(this,((n,i)=>{const s=Ro.findKey(r,i);if(s)return t[s]=ra(n),void delete t[i];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(i):String(i).trim();o!==i&&delete t[i],t[o]=ra(n),r[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return Ro.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&Ro.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[ea]=this[ea]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=ta(e);t[n]||(!function(e,t){const r=Ro.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,i){return this[n].call(this,t,e,r,i)},configurable:!0})}))}(r,e),t[n]=!0)}return Ro.isArray(e)?e.forEach(n):n(e),this}}ia.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),Ro.reduceDescriptors(ia.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),Ro.freezeMethods(ia);var sa=ia;function oa(e,t){const r=this||Zo,n=t||r,i=sa.from(n.headers);let s=n.data;return Ro.forEach(e,(function(e){s=e.call(r,s,i.normalize(),t?t.status:void 0)})),i.normalize(),s}function aa(e){return!(!e||!e.__CANCEL__)}function ca(e,t,r){ko.call(this,null==e?"canceled":e,ko.ERR_CANCELED,t,r),this.name="CanceledError"}function da(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new ko("Request failed with status code "+r.status,[ko.ERR_BAD_REQUEST,ko.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}Ro.inherits(ca,ko,{__CANCEL__:!0});const ua=(e,t,r=3)=>{let n=0;const i=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let i,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=n[o];i||(i=c),r[s]=a,n[s]=c;let u=o,l=0;for(;u!==s;)l+=r[u++],u%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-i<t)return;const p=d&&c-d;return p?Math.round(1e3*l/p):void 0}}(50,250);return function(e,t){let r,n,i=0,s=1e3/t;const o=(t,s=Date.now())=>{i=s,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-i;a>=s?o(e,t):(r=e,n||(n=setTimeout((()=>{n=null,o(r)}),s-a)))},()=>r&&o(r)]}((r=>{const s=r.loaded,o=r.lengthComputable?r.total:void 0,a=s-n,c=i(a);n=s;e({loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:r,lengthComputable:null!=o,[t?"download":"upload"]:!0})}),r)},la=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},pa=e=>(...t)=>Ro.asap((()=>e(...t)));var ha=Jo.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,Jo.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(Jo.origin),Jo.navigator&&/(msie|trident)/i.test(Jo.navigator.userAgent)):()=>!0,fa=Jo.hasStandardBrowserEnv?{write(e,t,r,n,i,s){const o=[e+"="+encodeURIComponent(t)];Ro.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),Ro.isString(n)&&o.push("path="+n),Ro.isString(i)&&o.push("domain="+i),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function ma(e,t,r){let n=!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t);return e&&(n||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const ga=e=>e instanceof sa?{...e}:e;function va(e,t){t=t||{};const r={};function n(e,t,r,n){return Ro.isPlainObject(e)&&Ro.isPlainObject(t)?Ro.merge.call({caseless:n},e,t):Ro.isPlainObject(t)?Ro.merge({},t):Ro.isArray(t)?t.slice():t}function i(e,t,r,i){return Ro.isUndefined(t)?Ro.isUndefined(e)?void 0:n(void 0,e,0,i):n(e,t,0,i)}function s(e,t){if(!Ro.isUndefined(t))return n(void 0,t)}function o(e,t){return Ro.isUndefined(t)?Ro.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,i,s){return s in t?n(r,i):s in e?n(void 0,r):void 0}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,r)=>i(ga(e),ga(t),0,!0)};return Ro.forEach(Object.keys(Object.assign({},e,t)),(function(n){const s=c[n]||i,o=s(e[n],t[n],n);Ro.isUndefined(o)&&s!==a||(r[n]=o)})),r}var ya=e=>{const t=va({},e);let r,{data:n,withXSRFToken:i,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=sa.from(a),t.url=Vo(ma(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),Ro.isFormData(n))if(Jo.hasStandardBrowserEnv||Jo.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map((e=>e.trim())).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(Jo.hasStandardBrowserEnv&&(i&&Ro.isFunction(i)&&(i=i(t)),i||!1!==i&&ha(t.url))){const e=s&&o&&fa.read(o);e&&a.set(s,e)}return t};var _a="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){const n=ya(e);let i=n.data;const s=sa.from(n.headers).normalize();let o,a,c,d,u,{responseType:l,onUploadProgress:p,onDownloadProgress:h}=n;function f(){d&&d(),u&&u(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let m=new XMLHttpRequest;function g(){if(!m)return;const n=sa.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());da((function(e){t(e),f()}),(function(e){r(e),f()}),{data:l&&"text"!==l&&"json"!==l?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:n,config:e,request:m}),m=null}m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout,"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(g)},m.onabort=function(){m&&(r(new ko("Request aborted",ko.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ko("Network Error",ko.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const i=n.transitional||Wo;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new ko(t,i.clarifyTimeoutError?ko.ETIMEDOUT:ko.ECONNABORTED,e,m)),m=null},void 0===i&&s.setContentType(null),"setRequestHeader"in m&&Ro.forEach(s.toJSON(),(function(e,t){m.setRequestHeader(t,e)})),Ro.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),l&&"json"!==l&&(m.responseType=n.responseType),h&&([c,u]=ua(h,!0),m.addEventListener("progress",c)),p&&m.upload&&([a,d]=ua(p),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",d)),(n.cancelToken||n.signal)&&(o=t=>{m&&(r(!t||t.type?new ca(null,e,m):t),m.abort(),m=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));const v=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);v&&-1===Jo.protocols.indexOf(v)?r(new ko("Unsupported protocol "+v+":",ko.ERR_BAD_REQUEST,e)):m.send(i||null)}))};var ba=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const i=function(e){if(!r){r=!0,o();const t=e instanceof Error?e:this.reason;n.abort(t instanceof ko?t:new ca(t instanceof Error?t.message:t))}};let s=t&&setTimeout((()=>{s=null,i(new ko(`timeout ${t} of ms exceeded`,ko.ETIMEDOUT))}),t);const o=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)})),e=null)};e.forEach((e=>e.addEventListener("abort",i)));const{signal:a}=n;return a.unsubscribe=()=>Ro.asap(o),a}};const Ea=function*(e,t){let r=e.byteLength;if(!t||r<t)return void(yield e);let n,i=0;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},wa=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},Sa=(e,t,r,n)=>{const i=async function*(e,t){for await(const r of wa(e))yield*Ea(r,t)}(e,t);let s,o=0,a=e=>{s||(s=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await i.next();if(t)return a(),void e.close();let s=n.byteLength;if(r){let e=o+=s;r(e)}e.enqueue(new Uint8Array(n))}catch(e){throw a(e),e}},cancel:e=>(a(e),i.return())},{highWaterMark:2})},Ca="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Pa=Ca&&"function"==typeof ReadableStream,Ta=Ca&&("function"==typeof TextEncoder?(Ra=new TextEncoder,e=>Ra.encode(e)):async e=>new Uint8Array(await new Response(e).arrayBuffer()));var Ra;const ka=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},Da=Pa&&ka((()=>{let e=!1;const t=new Request(Jo.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),Ia=Pa&&ka((()=>Ro.isReadableStream(new Response("").body))),Aa={stream:Ia&&(e=>e.body)};var Oa;Ca&&(Oa=new Response,["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!Aa[e]&&(Aa[e]=Ro.isFunction(Oa[e])?t=>t[e]():(t,r)=>{throw new ko(`Response type '${e}' is not supported`,ko.ERR_NOT_SUPPORT,r)})})));const Ma=async(e,t)=>{const r=Ro.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(Ro.isBlob(e))return e.size;if(Ro.isSpecCompliantForm(e)){const t=new Request(Jo.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return Ro.isArrayBufferView(e)||Ro.isArrayBuffer(e)?e.byteLength:(Ro.isURLSearchParams(e)&&(e+=""),Ro.isString(e)?(await Ta(e)).byteLength:void 0)})(t):r};var Na=Ca&&(async e=>{let{url:t,method:r,data:n,signal:i,cancelToken:s,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:d,headers:u,withCredentials:l="same-origin",fetchOptions:p}=ya(e);d=d?(d+"").toLowerCase():"text";let h,f=ba([i,s&&s.toAbortSignal()],o);const m=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let g;try{if(c&&Da&&"get"!==r&&"head"!==r&&0!==(g=await Ma(u,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if(Ro.isFormData(n)&&(e=r.headers.get("content-type"))&&u.setContentType(e),r.body){const[e,t]=la(g,ua(pa(c)));n=Sa(r.body,65536,e,t)}}Ro.isString(l)||(l=l?"include":"omit");const i="credentials"in Request.prototype;h=new Request(t,{...p,signal:f,method:r.toUpperCase(),headers:u.normalize().toJSON(),body:n,duplex:"half",credentials:i?l:void 0});let s=await fetch(h,p);const o=Ia&&("stream"===d||"response"===d);if(Ia&&(a||o&&m)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=s[t]}));const t=Ro.toFiniteNumber(s.headers.get("content-length")),[r,n]=a&&la(t,ua(pa(a),!0))||[];s=new Response(Sa(s.body,65536,r,(()=>{n&&n(),m&&m()})),e)}d=d||"text";let v=await Aa[Ro.findKey(Aa,d)||"text"](s,e);return!o&&m&&m(),await new Promise(((t,r)=>{da(t,r,{data:v,headers:sa.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:h})}))}catch(t){if(m&&m(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new ko("Network Error",ko.ERR_NETWORK,e,h),{cause:t.cause||t});throw ko.from(t,t&&t.code,e,h)}});const La={http:null,xhr:_a,fetch:Na};Ro.forEach(La,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));const xa=e=>`- ${e}`,Fa=e=>Ro.isFunction(e)||null===e||!1===e;var ja=e=>{e=Ro.isArray(e)?e:[e];const{length:t}=e;let r,n;const i={};for(let s=0;s<t;s++){let t;if(r=e[s],n=r,!Fa(r)&&(n=La[(t=String(r)).toLowerCase()],void 0===n))throw new ko(`Unknown adapter '${t}'`);if(n)break;i[t||"#"+s]=n}if(!n){const e=Object.entries(i).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new ko("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(xa).join("\n"):" "+xa(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n};function Ua(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new ca(null,e)}function Va(e){Ua(e),e.headers=sa.from(e.headers),e.data=oa.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return ja(e.adapter||Zo.adapter)(e).then((function(t){return Ua(e),t.data=oa.call(e,e.transformResponse,t),t.headers=sa.from(t.headers),t}),(function(t){return aa(t)||(Ua(e),t&&t.response&&(t.response.data=oa.call(e,e.transformResponse,t.response),t.response.headers=sa.from(t.response.headers))),Promise.reject(t)}))}const Ba={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Ba[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const Wa={};Ba.transitional=function(e,t,r){function n(e,t){return"[Axios v1.10.0] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,i,s)=>{if(!1===e)throw new ko(n(i," has been removed"+(t?" in "+t:"")),ko.ERR_DEPRECATED);return t&&!Wa[i]&&(Wa[i]=!0,console.warn(n(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,i,s)}},Ba.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};var Ha={assertOptions:function(e,t,r){if("object"!=typeof e)throw new ko("options must be an object",ko.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let i=n.length;for(;i-- >0;){const s=n[i],o=t[s];if(o){const t=e[s],r=void 0===t||o(t,s,e);if(!0!==r)throw new ko("option "+s+" must be "+r,ko.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new ko("Unknown option "+s,ko.ERR_BAD_OPTION)}},validators:Ba};const qa=Ha.validators;class za{constructor(e){this.defaults=e||{},this.interceptors={request:new Bo,response:new Bo}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const r=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=va(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:i}=t;void 0!==r&&Ha.assertOptions(r,{silentJSONParsing:qa.transitional(qa.boolean),forcedJSONParsing:qa.transitional(qa.boolean),clarifyTimeoutError:qa.transitional(qa.boolean)},!1),null!=n&&(Ro.isFunction(n)?t.paramsSerializer={serialize:n}:Ha.assertOptions(n,{encode:qa.function,serialize:qa.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Ha.assertOptions(t,{baseUrl:qa.spelling("baseURL"),withXsrfToken:qa.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=i&&Ro.merge(i.common,i[t.method]);i&&Ro.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete i[e]})),t.headers=sa.concat(s,i);const o=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))}));const c=[];let d;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let u,l=0;if(!a){const e=[Va.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),u=e.length,d=Promise.resolve(t);l<u;)d=d.then(e[l++],e[l++]);return d}u=o.length;let p=t;for(l=0;l<u;){const e=o[l++],t=o[l++];try{p=e(p)}catch(e){t.call(this,e);break}}try{d=Va.call(this,p)}catch(e){return Promise.reject(e)}for(l=0,u=c.length;l<u;)d=d.then(c[l++],c[l++]);return d}getUri(e){return Vo(ma((e=va(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}}Ro.forEach(["delete","get","head","options"],(function(e){za.prototype[e]=function(t,r){return this.request(va(r||{},{method:e,url:t,data:(r||{}).data}))}})),Ro.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,i){return this.request(va(i||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}za.prototype[e]=t(),za.prototype[e+"Form"]=t(!0)}));var Ga=za;class Ya{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,i){r.reason||(r.reason=new ca(e,n,i),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;const t=new Ya((function(t){e=t}));return{token:t,cancel:e}}}var $a=Ya;const Ja={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Ja).forEach((([e,t])=>{Ja[t]=e}));var Qa=Ja;const Ka=function e(t){const r=new Ga(t),n=js(Ga.prototype.request,r);return Ro.extend(n,Ga.prototype,r,{allOwnKeys:!0}),Ro.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(va(t,r))},n}(Zo);Ka.Axios=Ga,Ka.CanceledError=ca,Ka.CancelToken=$a,Ka.isCancel=aa,Ka.VERSION="1.10.0",Ka.toFormData=Lo,Ka.AxiosError=ko,Ka.Cancel=Ka.CanceledError,Ka.all=function(e){return Promise.all(e)},Ka.spread=function(e){return function(t){return e.apply(null,t)}},Ka.isAxiosError=function(e){return Ro.isObject(e)&&!0===e.isAxiosError},Ka.mergeConfig=va,Ka.AxiosHeaders=sa,Ka.formToJSON=e=>Qo(Ro.isHTMLForm(e)?new FormData(e):e),Ka.getAdapter=ja,Ka.HttpStatusCode=Qa,Ka.default=Ka;var Za=Ka;class Xa extends vn{constructor(e,t,r){super(null!=e?e:Xa.DEFAULT_MESSAGE,null!=t?t:"already_created",r)}}Xa.DEFAULT_MESSAGE="Resource has already been created";class ec extends vn{constructor(e,t,r){super(null!=e?e:ec.DEFAULT_MESSAGE,null!=t?t:"forbidden",r)}}ec.DEFAULT_MESSAGE="Forbidden";class tc extends vn{constructor(e,t,r){super(null!=e?e:tc.DEFAULT_MESSAGE,null!=t?t:"invalid_request",r)}}tc.DEFAULT_MESSAGE="Invalid request";class rc extends vn{constructor(e,t,r){super(null!=e?e:rc.DEFAULT_MESSAGE,null!=t?t:"not_found",r)}}rc.DEFAULT_MESSAGE="Requested resource was not found";class nc extends vn{constructor(e,t,r){super(null!=e?e:nc.DEFAULT_MESSAGE,null!=t?t:"something_went_wrong",r)}}nc.DEFAULT_MESSAGE="Request failed";class ic extends vn{constructor(e,t,r){super(null!=e?e:ic.DEFAULT_MESSAGE,null!=t?t:"timeout",r)}}ic.DEFAULT_MESSAGE="Request timed out";class sc extends vn{constructor(e,t,r){super(null!=e?e:sc.DEFAULT_MESSAGE,null!=t?t:"too_many_requests",r)}}sc.DEFAULT_MESSAGE="Too many requests";class oc extends vn{constructor(e,t,r){super(null!=e?e:oc.DEFAULT_MESSAGE,null!=t?t:"unauthorized",r)}}oc.DEFAULT_MESSAGE="Unauthorized";const ac=e=>(t,r,n)=>new e(t,r,n),cc={check_access_fail:ac(ec),join_room_fail:ac(tc),need_joined_to_channel:ac(yn),forbidden:ac(ec),not_found:ac(rc),invalid_request:ac(tc),invalid_payload:ac(tc),already_created:ac(Xa),too_many_requests:ac(sc),something_went_wrong:ac(nc),di_error:ac(tc),resources_lock_error:ac(tc),already_connected:ac(Ts),timeout:ac(ic),unauthorized:ac(oc)},dc=e=>{if(!(e=>"object"==typeof e&&null!==e&&!Array.isArray(e))(e))return!1;const{error:t,errorCode:r}=e;return!(void 0!==t&&"string"!=typeof t||void 0!==r&&"string"!=typeof r)},uc=(e,t)=>{var r,n,i,s;const o={};return t&&Object.keys(t).length>0&&(o.response=t),"number"==typeof(null===(r=e.response)||void 0===r?void 0:r.status)&&(o.status=e.response.status),(null===(n=e.response)||void 0===n?void 0:n.statusText)&&(o.statusText=e.response.statusText),e.code&&(o.axiosCode=e.code),(null===(i=e.config)||void 0===i?void 0:i.url)&&(o.url=e.config.url),(null===(s=e.config)||void 0===s?void 0:s.method)&&(o.method=e.config.method),Object.keys(o).length>0?o:void 0};var lc;!function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"}(lc||(lc={}));const pc=["/ping","/ice-parameters"];let hc=class extends class extends class{constructor(e={}){var{securityWorker:t,secure:r,format:n}=e,s=i(e,["securityWorker","secure","format"]);this.securityData=null,this.setSecurityData=e=>{this.securityData=e},this.request=e=>c(this,void 0,void 0,(function*(){var{secure:t,path:r,type:n,query:s,format:o,body:a}=e,c=i(e,["secure","path","type","query","format","body"]);const d=("boolean"==typeof t?t:this.secure)&&this.securityWorker&&(yield this.securityWorker(this.securityData))||{},u=this.mergeRequestParams(c,d),l=o||this.format||void 0;return n===lc.FormData&&a&&null!==a&&"object"==typeof a&&(a=this.createFormData(a)),n===lc.Text&&a&&null!==a&&"string"!=typeof a&&(a=JSON.stringify(a)),this.instance.request(Object.assign(Object.assign({},u),{headers:Object.assign(Object.assign({},u.headers||{}),n&&n!==lc.FormData?{"Content-Type":n}:{}),params:s,responseType:l,data:a,url:r}))})),this.instance=Za.create(Object.assign(Object.assign({},s),{baseURL:s.baseURL||"signaling.livedigital.space/v1"})),this.secure=r,this.format=n,this.securityWorker=t}mergeRequestParams(e,t){const r=e.method||t&&t.method;return Object.assign(Object.assign(Object.assign(Object.assign({},this.instance.defaults),e),t||{}),{headers:Object.assign(Object.assign(Object.assign({},r&&this.instance.defaults.headers[r.toLowerCase()]||{}),e.headers||{}),t&&t.headers||{})})}stringifyFormItem(e){return"object"==typeof e&&null!==e?JSON.stringify(e):`${e}`}createFormData(e){return Object.keys(e||{}).reduce(((t,r)=>{const n=e[r],i=n instanceof Array?n:[n];for(const e of i){const n=e instanceof Blob||e instanceof File;t.append(r,n?e:this.stringifyFormItem(e))}return t}),new FormData)}}{constructor(){super(...arguments),this.peers={getPeers:(e,t={})=>this.request(Object.assign({path:"/peers",method:"GET",query:e,secure:!0,format:"json"},t)),registerPeer:(e,t={})=>this.request(Object.assign({path:"/peers",method:"POST",body:e,secure:!0,type:lc.Json,format:"json"},t)),disconnectPeer:(e={})=>this.request(Object.assign({path:"/peers",method:"DELETE",secure:!0},e)),changePeerProducePermissions:(e,t,r={})=>this.request(Object.assign({path:`/peers/${e}/produce-permissions`,method:"PUT",body:t,secure:!0,type:lc.Json},r)),addPeerProducePermissions:(e,t,r={})=>this.request(Object.assign({path:`/peers/${e}/produce-permissions/${t}`,method:"POST",secure:!0},r)),removePeerProducePermissions:(e,t,r={})=>this.request(Object.assign({path:`/peers/${e}/produce-permissions/${t}`,method:"DELETE",secure:!0},r))},this.router={getRtpCapabilities:(e={})=>this.request(Object.assign({path:"/router/rtp-capabilities",method:"GET",secure:!0,format:"json"},e))},this.channel={confirmChannelActivity:(e={})=>this.request(Object.assign({path:"/channel/activity",method:"PATCH",secure:!0},e)),triggerChannelStateEvent:(e,t={})=>this.request(Object.assign({path:"/channel/peers-state-message-id",method:"GET",query:e,secure:!0,format:"json"},t))},this.ping={pingPeer:(e={})=>this.request(Object.assign({path:"/ping",method:"POST",secure:!0},e))},this.appData={updateSelfPeerAppData:(e,t={})=>this.request(Object.assign({path:"/app-data",method:"PUT",body:e,secure:!0,type:lc.Json},t))},this.producer={getGeneralDataProducer:(e={})=>this.request(Object.assign({path:"/producer/general-data",method:"GET",secure:!0,format:"json"},e)),getAudioObserverProducer:(e={})=>this.request(Object.assign({path:"/producer/audio-observer",method:"GET",secure:!0,format:"json"},e)),getChannelStateSyncDataProducer:(e={})=>this.request(Object.assign({path:"/producer/channel-state-sync-data",method:"GET",secure:!0,format:"json"},e)),closeProducer:(e,t={})=>this.request(Object.assign({path:`/producer/${e}`,method:"DELETE",secure:!0},t)),pauseProducer:(e,t={})=>this.request(Object.assign({path:`/producer/${e}/actions/pause`,method:"POST",secure:!0},t)),resumeProducer:(e,t={})=>this.request(Object.assign({path:`/producer/${e}/actions/resume`,method:"POST",secure:!0},t)),requestProducerMaxSpatialLayer:(e,t,r={})=>this.request(Object.assign({path:`/producer/${e}/max-spatial-layer`,method:"POST",body:t,secure:!0,type:lc.Json},r)),setProducerMaxSpatialLayer:(e,t,r={})=>this.request(Object.assign({path:`/producer/${e}/max-spatial-layer`,method:"PUT",body:t,secure:!0,type:lc.Json},r))},this.consumer={createConsumer:(e,t={})=>this.request(Object.assign({path:"/consumer",method:"POST",body:e,secure:!0,type:lc.Json,format:"json"},t)),closeConsumer:(e,t={})=>this.request(Object.assign({path:`/consumer/${e}`,method:"DELETE",secure:!0},t)),pauseConsumer:(e,t={})=>this.request(Object.assign({path:`/consumer/${e}/actions/pause`,method:"POST",secure:!0},t)),resumeConsumer:(e,t={})=>this.request(Object.assign({path:`/consumer/${e}/actions/resume`,method:"POST",secure:!0},t)),updateConsumerPreferredLayers:(e,t,r={})=>this.request(Object.assign({path:`/consumer/${e}/preferred-layers`,method:"PUT",body:t,secure:!0,type:lc.Json},r)),requestConsumerKeyFrame:(e,t={})=>this.request(Object.assign({path:`/consumer/${e}/key-frame`,method:"POST",secure:!0},t))},this.dataConsumer={createDataConsumer:(e,t={})=>this.request(Object.assign({path:"/data-consumer",method:"POST",body:e,secure:!0,type:lc.Json,format:"json"},t))},this.transport={createTransport:(e,t={})=>this.request(Object.assign({path:"/transport",method:"POST",body:e,secure:!0,type:lc.Json,format:"json"},t)),getTransportIceParameters:(e,t={})=>this.request(Object.assign({path:`/transport/${e}/ice-parameters`,method:"GET",secure:!0,format:"json"},t)),connectTransport:(e,t,r={})=>this.request(Object.assign({path:`/transport/${e}/connect`,method:"PUT",body:t,secure:!0,type:lc.Json},r)),produceMediaToTransport:(e,t,r={})=>this.request(Object.assign({path:`/transport/${e}/media-producer`,method:"PUT",body:t,secure:!0,type:lc.Json,format:"json"},r)),produceDataToTransport:(e,t,r={})=>this.request(Object.assign({path:`/transport/${e}/data-producer`,method:"PUT",body:t,secure:!0,type:lc.Json,format:"json"},r)),closeTransport:(e,t={})=>this.request(Object.assign({path:`/transport/${e}`,method:"DELETE",secure:!0},t))}}}{constructor(e){super({baseURL:String("https://signaling-api.livedigital.space/v1"),securityWorker:e=>{if(!e)return;const t={};return e.token&&(t.Authorization=`Bearer ${e.token}`),e.peerApiVersion&&(t["x-peer-api-version"]=String(e.peerApiVersion)),e.datacenterType&&(t["x-datacenter-type"]=e.datacenterType),{headers:t}}}),this.config=e,this.errorListeners=new Set,this.abortController=new AbortController,this.instance.interceptors.request.use((e=>(!e.signal&&this.abortController&&(e.signal=this.abortController.signal),e))),Fs(this.instance,{retries:3,shouldResetTimeout:!0,retryDelay:e=>Math.min(300*Math.pow(2,e-1),2e3)+300*Math.random(),retryCondition:e=>{var t;return"ERR_CANCELED"!==e.code&&(!(e=>"string"==typeof e&&pc.some((t=>e.includes(t))))(null===(t=e.config)||void 0===t?void 0:t.url)&&(Fs.isNetworkError(e)||"ECONNABORTED"===e.code&&!e.response))}}),this.instance.interceptors.response.use((e=>e),(e=>{const t=(e=>{var t,r;if(!Za.isAxiosError(e))return e instanceof Error?e:new nc;const n=e;if(!n.response){const e=uc(n),r=n.message||nc.DEFAULT_MESSAGE,i=null!==(t=n.code)&&void 0!==t?t:"network_error";return new nc(r,i,e)}const i=dc(n.response.data)?n.response.data:void 0,s="string"==typeof(null==i?void 0:i.errorCode)?i.errorCode:void 0,o="string"==typeof(null==i?void 0:i.error)?i.error:void 0,a=(o&&o.trim().length>0?o:n.message)||nc.DEFAULT_MESSAGE,c=uc(n,i);if(s){const e=cc[s];return e?e(a,s,c):new nc(a,s,c)}const d=null!==(r=n.code)&&void 0!==r?r:"number"==typeof n.response.status?`http_${n.response.status}`:"something_went_wrong";return new nc(a,d,c)})(e);throw this.notifyErrorListeners(t),t})),this.instance.defaults.timeout=7e3;const t=this.config.get("signalingServerUrl");t&&(this.instance.defaults.baseURL=t)}abortPendingRequests(e){this.abortController.abort(e),this.abortController=new AbortController}addErrorListener(e){return this.errorListeners.add(e),()=>{this.errorListeners.delete(e)}}notifyErrorListeners(e){this.errorListeners.forEach((t=>{try{t(e)}catch(e){}}))}};hc=s([ct(),o(0,ut(Nn.Config)),a("design:paramtypes",[Et])],hc);var fc,mc,gc,vc,yc,_c,bc=hc;let Ec=class{constructor(e){fc.set(this,void 0),mc.set(this,void 0),gc.set(this,void 0),vc.set(this,[]),yc.set(this,void 0),_c.set(this,new Uint8Array(0)),u(this,yc,e("DatachannelHeartbeater"),"f")}init(e,t){u(this,gc,e,"f"),u(this,mc,t,"f"),this.subscribeToDataProducerEvents(t),this.startHeartbeatInterval()}dispose(){this.stopHeartbeatInterval(),this.cleanupDataProducerEvents(),u(this,mc,void 0,"f"),u(this,gc,void 0,"f")}startHeartbeatInterval(){d(this,fc,"f")||(u(this,fc,setInterval((()=>{this.sendHeartbeat()}),5e3),"f"),d(this,yc,"f").debug("Datachannel heartbeat interval started"))}stopHeartbeatInterval(){d(this,fc,"f")&&(clearInterval(d(this,fc,"f")),u(this,fc,void 0,"f"),d(this,yc,"f").debug("Datachannel heartbeat interval stopped"))}canSendHeartbeat(){return!(!d(this,mc,"f")||!d(this,gc,"f"))&&(!d(this,mc,"f").closed&&"connected"===d(this,gc,"f").connectionState&&"open"===d(this,mc,"f").readyState)}subscribeToDataProducerEvents(e){this.cleanupDataProducerEvents();const t=t=>{d(this,yc,"f").debug(`Heartbeat data producer ${t}`,{readyState:e.readyState,closed:e.closed})},r=()=>t("open"),n=()=>t("close"),i=()=>t("transport closed");e.on("open",r),e.on("close",n),e.on("transportclose",i),u(this,vc,[()=>e.off("open",r),()=>e.off("close",n),()=>e.off("transportclose",i)],"f")}cleanupDataProducerEvents(){d(this,vc,"f").forEach((e=>e())),u(this,vc,[],"f")}sendHeartbeat(){if(d(this,mc,"f")&&this.canSendHeartbeat())try{d(this,mc,"f").send(d(this,_c,"f"))}catch(e){d(this,yc,"f").debug("Failed to send datachannel heartbeat",{error:Pt(e)})}}};fc=new WeakMap,mc=new WeakMap,gc=new WeakMap,vc=new WeakMap,yc=new WeakMap,_c=new WeakMap,Ec=s([ct(),o(0,ut(Nn.LoggerFactory)),a("design:paramtypes",[Function])],Ec);var wc,Sc=Ec;class Cc extends vn{constructor(e,t,r){super(null!=e?e:Cc.DEFAULT_MESSAGE,null!=t?t:"invalid_payload",r)}}Cc.DEFAULT_MESSAGE="Invalid payload",function(e){e.DominantSpeaker="dominant-speaker",e.PeersVolumes="peers-volumes",e.Silence="silence"}(wc||(wc={}));let Pc=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()}};Pc=s([ct()],Pc);var Tc=Pc;const Rc=[{scaleResolutionDownBy:4,maxBitrate:15e4,maxFramerate:12},{scaleResolutionDownBy:2,maxBitrate:35e4,maxFramerate:18},{scaleResolutionDownBy:1,maxBitrate:9e5,maxFramerate:24}],kc=[{maxBitrate:1e6,dtx:!0}],Dc=[{maxBitrate:4e4,dtx:!0}];var Ic;let Ac=class{constructor(e,t){this.peersStorage=e,Ic.set(this,void 0),u(this,Ic,t("ChannelAudioObserverMissingProducerRestorer"),"f")}handlePeerVolume(e){const{peerId:t,producerId:r}=e,n=this.peersStorage.get(t);if(!n)return;if(n.producers.has(r))return;const i={id:r,kind:"audio",peerId:t,label:Ln.Microphone,paused:!1,encodings:Dc,maxSpatialLayer:0};n.observer.safeEmit(on,i),d(this,Ic,"f").warn("Recovered missing audio producer from audio observer volume",{peerId:t,producerId:r})}};Ic=new WeakMap,Ac=s([ct(),o(0,ut(Nn.PeersStorage)),o(1,ut(Nn.LoggerFactory)),a("design:paramtypes",[Tc,Function])],Ac);var Oc,Mc,Nc,Lc,xc,Fc=Ac;let jc=xc=class{constructor(e,t,r,n){this.peersStorage=e,this.clientEventEmitter=t,this.channelAudioObserverMissingProducerRestorer=r,Oc.set(this,void 0),Mc.set(this,void 0),Nc.set(this,void 0),Lc.set(this,void 0),u(this,Oc,n("ChannelAudioObserverEventHandler"),"f"),this.watchPeersLeave()}handle(e){try{const t=JSON.parse(e);switch(xc.validateEventPayload(t),t.event){case wc.DominantSpeaker:this.handleDominantSpeaker(t);break;case wc.PeersVolumes:this.handlePeerVolumes(t);break;case wc.Silence:this.handleSilence()}}catch(t){d(this,Oc,"f").warn("Failed to handle audio observer event",{error:Pt(t),eventData:e})}}handleDominantSpeaker(e){const{peerId:t}=e.data,r=this.peersStorage.get(t);u(this,Nc,r,"f"),u(this,Lc,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&&!d(this,Nc,"f")&&s.id===(null===(t=d(this,Lc,"f"))||void 0===t?void 0:t.id)&&(u(this,Nc,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))),u(this,Nc,void 0,"f"),this.setActiveSpeaker(void 0)}watchPeersLeave(){this.clientEventEmitter.on(br,(e=>{var t;e===(null===(t=d(this,Nc,"f"))||void 0===t?void 0:t.id)&&this.setActiveSpeaker(void 0)}))}setActiveSpeaker(e){d(this,Mc,"f")!==(null==e?void 0:e.id)&&(u(this,Mc,null==e?void 0:e.id,"f"),this.clientEventEmitter.safeEmit(Dr,{peer:e}))}static validateEventPayload(e){switch(e.event){case wc.Silence:break;case wc.DominantSpeaker:{e.data||xc.throwInvalidPayload();const{peerId:t,producerId:r,trackLabel:n}=e.data;"string"==typeof t&&"string"==typeof r&&n===Ln.Microphone||xc.throwInvalidPayload();break}case wc.PeersVolumes:Array.isArray(e.volumes)||xc.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===Ln.Microphone||xc.throwInvalidPayload()}));break;default:xc.throwInvalidPayload()}}static throwInvalidPayload(){throw new Cc("invalid_channel_audio_observer_payload")}};Oc=new WeakMap,Mc=new WeakMap,Nc=new WeakMap,Lc=new WeakMap,jc=xc=s([ct(),o(0,ut(Nn.PeersStorage)),o(1,ut(Nn.ClientEventEmitter)),o(2,ut(Nn.ChannelAudioObserverMissingProducerRestorer)),o(3,ut(Nn.LoggerFactory)),a("design:paramtypes",[Tc,wt,Fc,Function])],jc);var Uc,Vc,Bc,Wc=jc;let Hc=class{constructor(e,t,r,n,i){this.state=e,this.myPeer=r,this.signalingApiClient=n,this.channelAudioObserverEventHandler=i,Uc.set(this,void 0),Vc.set(this,void 0),Bc.set(this,void 0),u(this,Uc,t("DataChannels"),"f")}get channelMessagesDataConsumer(){return d(this,Bc,"f")}createAudioObserver(e){return c(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();u(this,Vc,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=d(this,Vc,"f"))||void 0===e||e.removeListener("message",n),null===(t=d(this,Vc,"f"))||void 0===t||t.removeListener("close",i)};d(this,Vc,"f").on("close",i),d(this,Vc,"f").on("message",n),d(this,Uc,"f").debug("Successfully create audio observer",r)}catch(e){d(this,Uc,"f").error("Failed to create audio observer",Object.assign(Object.assign({},r),{error:Pt(e)}))}}))}createChannelMessagesDataConsumer(e){return c(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");u(this,Bc,yield this.createDataConsumer({producerId:t,appId:this.state.appId,channelId:this.state.channelId,ordered:!0,transport:e}),"f"),d(this,Uc,"f").debug("Successfully created channel messages data consumer",Object.assign(Object.assign({},r),{producerId:t}))}catch(e){throw d(this,Uc,"f").error("Failed to create channel messages data consumer",Object.assign(Object.assign({},r),{error:e})),e}}))}closeAudioObserver(){var e;null===(e=d(this,Vc,"f"))||void 0===e||e.close()}closeChannelMessagesDataConsumer(){var e;null===(e=d(this,Bc,"f"))||void 0===e||e.close()}createDataProducer(e,t){return c(this,void 0,void 0,(function*(){const{data:r}=yield this.signalingApiClient.transport.produceDataToTransport(e,{label:t});return r}))}createDataConsumer(e){return c(this,arguments,void 0,(function*({producerId:e,appId:t,channelId:r,ordered:n,transport:i}){if(!i)throw d(this,Uc,"f").error("createDataConsumer()",{reason:"missing receive transport"}),new Error("Failed to create data consumer due to missing receive transport");d(this,Uc,"f").debug("createDataConsumer()",{producerId:e});const s=(yield this.signalingApiClient.dataConsumer.createDataConsumer({ordered:n,dataProducerId:e,transportId:i.id,appData:{peerId:this.myPeer.id,producerId:e,appId:t,channelId:r}})).data,o=yield i.consumeData(s);return d(this,Uc,"f").debug("Data consumer created",{consumerId:o.id}),o}))}getAudioObserverProducer(){return c(this,void 0,void 0,(function*(){const{data:e}=yield this.signalingApiClient.producer.getAudioObserverProducer();return e}))}};Uc=new WeakMap,Vc=new WeakMap,Bc=new WeakMap,Hc=s([ct(),o(0,ut(Nn.CallState)),o(1,ut(Nn.LoggerFactory)),o(2,ut(Nn.MyPeer)),o(3,ut(Nn.SignalingApiClient)),o(4,ut(Nn.ChannelAudioObserverEventHandler)),a("design:paramtypes",[Fn,Function,Cs,bc,Wc])],Hc);var qc,zc,Gc=Hc;let Yc=class{constructor(e,t){this.signalingApiClient=t,qc.set(this,void 0),zc.set(this,void 0),u(this,zc,e("SignalingHeartbeater"),"f")}start(){d(this,qc,"f")||(u(this,qc,setInterval((()=>c(this,void 0,void 0,(function*(){yield this.sendHeartbeat()}))),15e3),"f"),d(this,zc,"f").debug("Signaling heartbeat interval started"))}dispose(){d(this,qc,"f")&&(clearInterval(d(this,qc,"f")),u(this,qc,void 0,"f"),d(this,zc,"f").debug("Signaling heartbeat interval stopped"))}sendHeartbeat(){return c(this,void 0,void 0,(function*(){try{yield this.signalingApiClient.ping.pingPeer()}catch(e){d(this,zc,"f").debug("Failed to send signaling heartbeat",{error:Pt(e)})}}))}};qc=new WeakMap,zc=new WeakMap,Yc=s([ct(),o(0,ut(Nn.LoggerFactory)),o(1,ut(Nn.SignalingApiClient)),a("design:paramtypes",[Function,bc])],Yc);var $c,Jc,Qc,Kc=Yc;let Zc=class{constructor(e,t,r,n,i,s,o,a){this.state=e,this.myPeer=t,this.clientEventEmitter=n,this.dataChannelsManager=i,this.signalingApiClient=s,this.datachannelHeartbeater=o,this.signalingHeartbeater=a,$c.set(this,new Map),Jc.set(this,void 0),Qc.set(this,void 0),this.peersLoaded=!1,u(this,Qc,r("Network"),"f"),u(this,Jc,new wt,"f")}get isNetworkActive(){var e,t,r,n;return["connected","new"].includes(null!==(t=null===(e=this.receiveTransport)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"")&&["connected","new"].includes(null!==(n=null===(r=this.sendTransport)||void 0===r?void 0:r.connectionState)&&void 0!==n?n:"")}get observer(){return d(this,Jc,"f")}removeEventListeners(){const{sendTransport:e,receiveTransport:t,signalingTransport:r}=this;if(e){["connect","produce","connectionstatechange"].forEach((t=>e.removeAllListeners(t)))}if(t){["connect","produce","connectionstatechange"].forEach((e=>t.removeAllListeners(e)))}if(r){["connect","produce","producedata","connectionstatechange"].forEach((e=>r.removeAllListeners(e)))}}reset(){this.datachannelHeartbeater.dispose(),this.signalingHeartbeater.dispose(),this.heartbeatDataProducer=void 0,this.peersLoaded=!1,this.stopRestartIceAttempts(),this.removeEventListeners(),this.closeAllDataChannels(),this.closeSendTransport(),this.closeReceiveTransport(),this.closeConnectionTransport()}closeRemoteProducer(e){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.closeProducer(e)}))}closeSendTransport(){this.sendTransport?(this.closeTransport(this.sendTransport),this.sendTransport=void 0):d(this,Qc,"f").debug("closeSendTransport()",{message:"No available send transport"})}closeReceiveTransport(){this.receiveTransport?(this.closeTransport(this.receiveTransport),this.receiveTransport=void 0):d(this,Qc,"f").debug("closeReceiveTransport()",{message:"No available receive transport"})}closeConnectionTransport(){this.signalingTransport?(this.closeTransport(this.signalingTransport),this.signalingTransport=void 0):d(this,Qc,"f").debug("closeConnectionTransport()",{message:"No available connection transport"})}closeTransport(e){try{e.close(),d(this,Qc,"f").debug("closeTransport()",{transportId:e.id,direction:e.direction})}catch(t){d(this,Qc,"f").error("closeTransport()",{error:t,transportId:e.id,direction:e.direction})}}createSendTransport(e){return c(this,void 0,void 0,(function*(){if(this.sendTransport)throw d(this,Qc,"f").warn("createSendTransport()",{message:"Send transport already exists"}),new vn("Send transport already exists","already_exists");const{data:t}=yield this.signalingApiClient.transport.createTransport({localDirection:"send"}),r=e.createSendTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return d(this,Qc,"f").debug("createSendTransport()",{transportId:r.id,direction:r.direction}),this.sendTransport=r,this.subscribeCommonTransportEvents(r),r}))}createRecvTransport(e){return c(this,void 0,void 0,(function*(){if(this.receiveTransport)throw d(this,Qc,"f").warn("createReceiveTransport()",{message:"Receive transport already exists"}),new vn("Receive transport already exists","already_exists");const{data:t}=yield this.signalingApiClient.transport.createTransport({localDirection:"receive"}),r=e.createRecvTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return d(this,Qc,"f").debug("createReceiveTransport()",{transportId:r.id,direction:r.direction}),this.receiveTransport=r,this.subscribeCommonTransportEvents(r),r}))}createSignalingTransport(e){return c(this,void 0,void 0,(function*(){if(this.signalingTransport)throw d(this,Qc,"f").warn("createConnectionTransport()",{message:"Connection transport already exists"}),new vn("Connection transport already exists","already_exists");const{data:t}=yield this.signalingApiClient.transport.createTransport({localDirection:"receive",tcpOnly:!0}),r=e.createSendTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));return d(this,Qc,"f").debug("createConnectionTransport()",{transportId:r.id,direction:r.direction,tcpOnly:!0}),this.signalingTransport=r,this.subscribeCommonTransportEvents(r),r}))}getIceParameters(e){return c(this,void 0,void 0,(function*(){const{data:{iceParameters:t}}=yield this.signalingApiClient.transport.getTransportIceParameters(e.id);return t}))}restartIce(e){return c(this,void 0,void 0,(function*(){try{const t=yield this.getIceParameters(e);yield e.restartIce({iceParameters:t}),d(this,Qc,"f").info("restartIce completed",{iceParameters:t})}catch(e){d(this,Qc,"f").error("restartIce error",{error:e})}}))}createConsumer(e){return c(this,arguments,void 0,(function*({producerId:e,rtpCapabilities:t,producerPeerId:r}){const n=this.receiveTransport;if(!n)throw d(this,Qc,"f").error("createConsumer()",{reason:"missing receive transport"}),new Error("Failed to create consumer due to missing receive transport");d(this,Qc,"f").debug("createConsumer()",{producerId:e});const i=yield this.signalingApiClient.consumer.createConsumer({producerId:e,transportId:n.id,rtpCapabilities:t,producerPeerId:r,forceCloseExisting:!0}).then((({data:e})=>this.toRemoteConsumerOptions(e))).catch((t=>{throw d(this,Qc,"f").error("Failed to get consumer options",{producerId:e,producerPeerId:r,error:Pt(t)}),new Error("Failed to create consumer due to error while fetching consumer options")})),s=yield n.consume(i).catch((t=>{throw t instanceof Error&&Ps.some((e=>t.message.includes(e)))&&(d(this,Qc,"f").error("createConsumer() reached irrecoverable mediasoup state",{producerId:e,producerPeerId:r,error:Pt(t)}),this.signalingApiClient.abortPendingRequests("channel-rejoin"),this.clientEventEmitter.safeEmit(Cr)),t})),{producerPaused:o}=i;return o&&"audio"!==s.kind&&s.pause(),d(this,Qc,"f").debug("Consumer created",{consumerId:s.id,label:s.appData.label,isProducerPaused:o}),{consumer:s,isProducerPaused:o}}))}initializeHeartbeats(){return c(this,void 0,void 0,(function*(){this.signalingHeartbeater.start();const e=this.sendTransport;if(!e)throw d(this,Qc,"f").error("createHeartbeatProducer()",{reason:"missing send transport"}),new Error("Failed to create data producer");const t=yield e.produceData({label:"heart-beater",protocol:"heartbeat"});this.heartbeatDataProducer=t,t.once("transportclose",(()=>{var e;null===(e=this.heartbeatDataProducer)||void 0===e||e.close(),this.heartbeatDataProducer=void 0,this.datachannelHeartbeater.dispose()})),this.datachannelHeartbeater.init(e,t)}))}createKeepAliveConsumer(){return c(this,void 0,void 0,(function*(){const e=this.signalingTransport;if(!e)return void d(this,Qc,"f").error("createKeepAliveConsumer()",{reason:"missing signaling transport"});const t=yield e.produceData({label:"consumers-scores",protocol:"keepalive"});t.once("open",(()=>{t.send(new Uint8Array(0))})),t.once("transportclose",(()=>{t.close()}))}))}get channelMessagesDataConsumer(){return this.dataChannelsManager.channelMessagesDataConsumer}closeRemoteConsumer(e){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.closeConsumer(e)}))}resumeRemoteConsumer(e){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.resumeConsumer(e)}))}pauseRemoteProducer(e){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.pauseProducer(e)}))}resumeRemoteProducer(e){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.resumeProducer(e)}))}pauseRemoteConsumer(e){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.pauseConsumer(e)}))}updatePeerAppData(e){return c(this,arguments,void 0,(function*({appData:e}){yield this.signalingApiClient.appData.updateSelfPeerAppData({appData:e})}))}setProducerMaxSpatialLayer(e,t){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.setProducerMaxSpatialLayer(e,{maxSpatialLayer:t})}))}requestProducerMaxSpatialLayer(e,t){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.producer.requestProducerMaxSpatialLayer(e,{spatialLayer:t})}))}changePeerProducePermissions(e,t){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.peers.changePeerProducePermissions(e,{producePermissions:null==t?void 0:t.map((e=>e))})}))}addPeerProducePermission(e,t){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.peers.addPeerProducePermissions(e,t)}))}removePeerProducePermission(e,t){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.peers.removePeerProducePermissions(e,t)}))}updateConsumerPreferredLayers(e,t,r){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.updateConsumerPreferredLayers(e,{spatialLayer:t,temporalLayer:r})}))}requestConsumerKeyFrame(e){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.consumer.requestConsumerKeyFrame(e)}))}ping(){return c(this,void 0,void 0,(function*(){yield this.signalingApiClient.ping.pingPeer()}))}getTransportsStateInfo(){return c(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 c(this,void 0,void 0,(function*(){var t;const{data:r}=yield this.signalingApiClient.peers.getPeers({role:e});this.peersLoaded=!0;return{peers:(null!==(t=r.items)&&void 0!==t?t:[]).map((e=>this.mapPeerResponse(e)))}}))}createAllDataChannels(){return c(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(e){return c(this,arguments,void 0,(function*({onReceiveTransportFailed:e}){if(!this.receiveTransport)throw new Error("receiveTransport is not initialized");if("connected"===(yield this.waitForTransportTerminalState(this.receiveTransport)))return;yield e();const t=yield this.waitForTransportTerminalState(this.receiveTransport);if("connected"!==t)throw new Error(`receiveTransport connection failed after relay escalation: ${t}`)}))}triggerChannelStateEvent(e){return c(this,void 0,void 0,(function*(){const{data:t}=yield this.signalingApiClient.channel.triggerChannelStateEvent({role:e});if("number"!=typeof t.messageId)throw new Error("Invalid channel state event response");return t.messageId}))}waitForChannelMessagesDataConsumerConnected(){return c(this,void 0,void 0,(function*(){if(!this.dataChannelsManager.channelMessagesDataConsumer)throw new Error("channelMessagesDataConsumer is not initialized");yield this.waitForDataConsumerConnected(this.dataChannelsManager.channelMessagesDataConsumer)}))}waitForTransportTerminalState(e){return c(this,arguments,void 0,(function*(e,t=6e4){if("connected"===e.connectionState)return e.connectionState;if("failed"===e.connectionState)return e.connectionState;if("closed"===e.connectionState)throw new Error(`receiveTransport connection failed: ${e.connectionState}`);return yield new Promise(((r,n)=>{const i=setTimeout((()=>{s(),r(e.connectionState)}),t),s=()=>{clearTimeout(i),e.off("connectionstatechange",o)},o=()=>{["connected","failed"].includes(e.connectionState)?(s(),r(e.connectionState)):"closed"===e.connectionState&&(s(),n(new Error(`receiveTransport connection failed: ${e.connectionState}`)))};e.on("connectionstatechange",o)}))}))}waitForDataConsumerConnected(e){return c(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 c(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 d(this,Qc,"f").warn("getParsedTransportStats()",{error:e})}else d(this,Qc,"f").debug("getParsedTransportStats()",{message:"Transport is missing"})}))}logTransportDetails(e){return c(this,void 0,void 0,(function*(){var t,r,n,i;let s;try{s=yield e.getStats()}catch(t){return void d(this,Qc,"f").error("Failed to log detailed WebRTC transport stats",{error:Pt(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:[],[,c]=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==c?void 0:c.localCandidateId)&&void 0!==n?n:"-")),l=s.get(String(null!==(i=null==c?void 0:c.remoteCandidateId)&&void 0!==i?i:"-")),p={hasNominatedPair:!!c,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==c?void 0:c.totalRoundTripTime)&&(null==c?void 0:c.responsesReceived)&&(p.pairRoundTripTime=Math.round(c.totalRoundTripTime/c.responsesReceived*1e3)),d(this,Qc,"f").info("Detailed WebRTC transport stats",p)}catch(t){d(this,Qc,"f").error("Failed to log detailed WebRTC transport stats",{error:Pt(t),transportId:e.id,reason:"-"})}}))}stopRestartIceAttempts(){Array.from(d(this,$c,"f").values()).forEach((e=>clearInterval(e)))}toRemoteConsumerOptions(e){const{producerPaused:t}=e,r=i(e,["producerPaused"]);return Object.assign(Object.assign({},r),{producerPaused:t})}mapPeerResponse(e){var t,r,n,i,s,o,a,c;return{id:e.id,channelIds:null!==(t=e.channelIds)&&void 0!==t?t:[],groups:null!==(r=e.groups)&&void 0!==r?r:[],producePermissions:null!==(n=e.producePermissions)&&void 0!==n?n:[],appId:null!==(s=null!==(i=e.appId)&&void 0!==i?i:this.state.appId)&&void 0!==s?s:"",producers:(null!==(o=e.producers)&&void 0!==o?o:[]).map((e=>this.mapProducer(e))),uid:e.uid,appData:null!==(a=e.appData)&&void 0!==a?a:{},role:null!==(c=e.role)&&void 0!==c?c:"audience",loginDate:e.loginDate?new Date(e.loginDate):new Date}}mapProducer(e){var t;return{id:e.id,kind:e.kind,peerId:e.peerId,label:e.label,paused:null!==(t=e.paused)&&void 0!==t&&t,encodings:[],maxSpatialLayer:0}}connectTransport(e,t){return c(this,void 0,void 0,(function*(){try{yield this.signalingApiClient.transport.connectTransport(e,{dtlsParameters:t})}catch(t){if(t instanceof Ts)return void d(this,Qc,"f").warn("connectTransport() transport already connected",{transportId:e});throw t}}))}subscribeCommonTransportEvents(e){e.on("connect",((t,r,n)=>c(this,[t,r,n],void 0,(function*({dtlsParameters:t},r,n){try{yield this.connectTransport(e.id,t),r(),d(this,Qc,"f").debug(`${e.direction}Transport.connect()`,{transportId:e.id,dtlsRole:t.role}),setTimeout((()=>c(this,void 0,void 0,(function*(){return yield this.logTransportDetails(e)}))),2e3),setTimeout((()=>c(this,void 0,void 0,(function*(){return yield this.checkTransportState(e)}))),15e3)}catch(t){d(this,Qc,"f").error(`${e.direction}Transport.on('connect')`,{error:t}),n(t)}})))),e.on("produce",((t,r,n)=>c(this,void 0,void 0,(function*(){try{const{data:n}=yield this.signalingApiClient.transport.produceMediaToTransport(e.id,{kind:t.kind,rtpParameters:t.rtpParameters,appData:t.appData,forceCloseExisting:!0}),i=n.id;r({id:i}),d(this,Qc,"f").debug(`${e.direction}Transport.produce()`,{producerId:i,transportId:e.id,kind:t.kind})}catch(r){d(this,Qc,"f").error(`${e.direction}Transport.produce()`,{error:Pt(r),transportId:e.id,kind:t.kind}),n(r)}})))),e.on("producedata",((t,r,n)=>c(this,void 0,void 0,(function*(){try{const{data:n}=yield this.signalingApiClient.transport.produceDataToTransport(e.id,{label:t.label,sctpStreamParameters:t.sctpStreamParameters,appData:t.appData});r({id:n.id}),d(this,Qc,"f").debug(`${e.direction}Transport.produceData()`,{producerId:n.id,transportId:e.id,sctpStreamParameters:t.sctpStreamParameters,label:t.label})}catch(r){d(this,Qc,"f").error(`${e.direction}Transport.produceData()`,{error:Pt(r),transportId:e.id,sctpStreamParameters:t.sctpStreamParameters,label:t.label}),n(r)}})))),e.on("connectionstatechange",(t=>{if(d(this,Qc,"f").info(`${e.direction}Transport.state`,{state:t}),["closed","connected"].includes(t))return d(this,Jc,"f").safeEmit(mn,{state:t,direction:e.direction}),d(this,$c,"f").has(e.id)&&(d(this,Qc,"f").debug("Stop receiveTransport.restartIce() retries",{recvTransportId:e.id}),clearInterval(d(this,$c,"f").get(e.id)),d(this,$c,"f").delete(e.id),"connected"===t&&d(this,Jc,"f").safeEmit(mn,{state:"reconnected",direction:e.direction})),void("connected"===t&&setTimeout((()=>{this.logTransportDetails(e).catch((e=>{d(this,Qc,"f").debug("Failed to log transport details",{error:Pt(e)})}))}),1500));if(d(this,Jc,"f").safeEmit(mn,{state:t,direction:e.direction}),["disconnected","failed"].includes(t)){if(d(this,$c,"f").has(e.id))return;"failed"===t&&(d(this,Qc,"f").debug(`${e.id} transport.restartIce()`,{transportId:e.id,direction:e.direction}),this.restartIce(e).catch((t=>{d(this,Qc,"f").debug("Failed to execute restartIce",{error:Pt(t),transportId:e.id,direction:e.direction})}))),d(this,$c,"f").set(e.id,setInterval((()=>{this.restartIce(e).catch((t=>{d(this,Qc,"f").debug("Failed to execute restartIce",{error:Pt(t),transportId:e.id,direction:e.direction})})),d(this,Qc,"f").debug(`${e.id} transport.restartIce() attempt`,{recvTransportId:e.id,transportId:e.id,direction:e.direction})}),1500))}})),e.on("icegatheringstatechange",(t=>{d(this,Qc,"f").info("icegatheringstatechange",{state:t,transportId:e.id,transportDirection:e.direction})}))}checkTransportState(e){return c(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(Tr,{direction:r,reason:"ice"}),void d(this,Qc,"f").warn(fn,{reason:"ice",transportId:e.id,direction:r});"connected"!==t.dtlsState&&(this.clientEventEmitter.emit(Tr,{direction:r,reason:"dtls"}),d(this,Qc,"f").warn(fn,{reason:"dtls",transportId:e.id,direction:r}))}catch(t){d(this,Qc,"f").error("checkTransportState()",{error:Pt(t),transportId:e.id,direction:e.direction})}}))}};$c=new WeakMap,Jc=new WeakMap,Qc=new WeakMap,Zc=s([ct(),o(0,ut(Nn.CallState)),o(1,ut(Nn.MyPeer)),o(2,ut(Nn.LoggerFactory)),o(3,ut(Nn.ClientEventEmitter)),o(4,ut(Nn.DataChannelsManager)),o(5,ut(Nn.SignalingApiClient)),o(6,ut(Nn.DatachannelHeartbeater)),o(7,ut(Nn.SignalingHeartbeater)),a("design:paramtypes",[Fn,Cs,Function,wt,Gc,bc,Sc,Kc])],Zc);var Xc=Zc;let ed=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 c(this,void 0,void 0,(function*(){const t=this.get(e);t&&(yield t.reset(),this.delete(e),this.clientEventEmitter.safeEmit(br,e))}))}all(){return this.peersStorage.all()}hosts(){return this.peersStorage.hosts()}audience(){return this.peersStorage.audience()}reset(){return c(this,void 0,void 0,(function*(){yield Promise.all(this.peersStorage.all().map((e=>c(this,void 0,void 0,(function*(){return yield e.reset()}))))),this.peersStorage.clear()}))}load(e){return c(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(_r,n),n}isModerator(e){if(void 0===e)return!1;const t=this.get(e);return!!t&&t.isModerator}};function td(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 rd(e,t,r,n){var i=td(td(td(e,r),function(e){return Object.prototype.toString.call(e)}(t)),typeof t);if(null===t)return td(i,"null");if(void 0===t)return td(i,"undefined");if("object"==typeof t||"function"==typeof t){if(-1!==n.indexOf(t))return td(i,"[Circular]"+r);n.push(t);var s=function(e,t,r){return Object.keys(t).sort().reduce((function(e,n){return rd(e,t[n],n,r)}),e)}(i,t,n);if(!("valueOf"in t)||"function"!=typeof t.valueOf)return s;try{return td(s,String(t.valueOf()))}catch(e){return td(s,"[valueOf exception]"+(e.stack||e.message))}}return td(i,t.toString())}ed=s([ct(),o(0,ut(Nn.MyPeer)),o(1,ut(Nn.Network)),o(2,ut(Nn.PeerFactory)),o(3,ut(Nn.ClientEventEmitter)),o(4,ut(Nn.PeersStorage)),a("design:paramtypes",[Cs,Xc,Function,wt,Tc])],ed);var nd=function(e){return function(e,t){for(;e.length<t;)e="0"+e;return e}(rd(0,e,"",[]).toString(16),8)};class id{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 sd{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 id({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 od,ad,cd,dd,ud,ld,pd;!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"}(od||(od={}));let hd=class{constructor(e,t,r,n,i,s,o){var a;this.network=t,this.callState=r,this.peersStorage=n,this.clientEventEmitter=i,this.signalingApiClient=s,this.webRtcIssueDetector=o,ad.set(this,void 0),cd.set(this,void 0),dd.set(this,[]),ud.set(this,!1),ld.set(this,{inbound:4.3,outbound:4.3}),pd.set(this,(new Date).getTime()-15e3),u(this,cd,null===(a=this.webRtcIssueDetector)||void 0===a?void 0:a.eventEmitter,"f"),u(this,ad,e("ChannelStateSyncEventHandler"),"f"),this.debouncedHandleChannelStateEvent=Pn(this.handleChannelStateEvent.bind(this),3e3),this.listenNetworkScoresUpdatedEvents()}handleChannelStateShort(e){return c(this,void 0,void 0,(function*(){try{yield this.debouncedHandleChannelStateEvent(e)}catch(e){d(this,ad,"f").error("handleChannelStateSyncEvent()",{error:Pt(e)})}}))}handleChannelStateEvent(e){return c(this,void 0,void 0,(function*(){if(d(this,ud,"f"))d(this,ad,"f").warn("Channel state event is already being handled, skipping new event",{case:"handleChannelStateEvent"});else{u(this,ud,!0,"f");try{yield this.collectProbableInconsistencyCases(e);const t=this.getConfirmedInconsistencyResult();if(!(null==t?void 0:t.hasInconsistencyCases()))return;if(this.isRestoreStateRequestToEarly())return void d(this,ad,"f").info("Inconsistency detected, but restore skipped",Object.assign({},t));this.handleConfirmedInconsistencyResult(t)}finally{u(this,ud,!1,"f")}}}))}getLastInconsistencyCheckResult(){return d(this,dd,"f")[d(this,dd,"f").length-1]}handleConfirmedInconsistencyResult(e){e.missingPeers.forEach((e=>{this.clientEventEmitter.safeEmit(Ir,{peerId:e,peersLoaded:this.network.peersLoaded,sdkInstances:Array.from(window._sdkMarks||[]).length,type:od.MissingPeer})})),e.missingProducers.forEach((e=>{this.clientEventEmitter.safeEmit(Ir,{producerId:e,type:od.MissingProducer})})),e.producersWithInconsistentState.forEach((e=>{this.clientEventEmitter.safeEmit(Ir,{producerId:e,type:od.IncorrectProducerState})})),e.peersWithInconsistentAppData.forEach((e=>{this.clientEventEmitter.safeEmit(Ir,{peerId:e,type:od.IncorrectAppData})}))}getConfirmedInconsistencyResult(){const e=this.getLastInconsistencyCheckResult();if(!e)return;return new id({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 c(this,void 0,void 0,(function*(){const t=new sd({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(){u(this,dd,[],"f")}rotateLastProbableInconsistencyCheckResults(e){4===d(this,dd,"f").length&&d(this,dd,"f").shift(),d(this,dd,"f").push(e)}isReachedMaxCheckRetries(e,t,r=4){let n=0;return d(this,dd,"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:nd(e.appData),producers:e.getProducers().map((e=>({id:e.id,paused:e.paused,stateChangedAt:e.getStateChangedAt()}))),consumers:e.getConsumersState()})))}}getIsConnectionActive(){return c(this,void 0,void 0,(function*(){try{return!!this.network.isNetworkActive&&(yield this.signalingApiClient.ping.pingPeer(),!0)}catch(e){return!1}}))}listenNetworkScoresUpdatedEvents(){d(this,cd,"f")&&d(this,cd,"f").on(Rt.NetworkScoresUpdated,(e=>{e.inbound&&(d(this,ld,"f").inbound=e.inbound),e.outbound&&(d(this,ld,"f").outbound=e.outbound)}))}isBadNetworkScore(){const{inbound:e,outbound:t}=d(this,ld,"f");return e<=2.6||t<=2.6}compareCheckedAndRestoredResults(e,t){return new id({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()-d(this,pd,"f")<=15e3}};ad=new WeakMap,cd=new WeakMap,dd=new WeakMap,ud=new WeakMap,ld=new WeakMap,pd=new WeakMap,hd=s([ct(),o(0,ut(Nn.LoggerFactory)),o(1,ut(Nn.Network)),o(2,ut(Nn.CallState)),o(3,ut(Nn.PeersStorage)),o(4,ut(Nn.ClientEventEmitter)),o(5,ut(Nn.SignalingApiClient)),o(6,ut(Nn.WebRTCIssueDetector)),a("design:paramtypes",[Function,Xc,Fn,Tc,wt,bc,ur])],hd);var fd=hd,md={},gd={exports:{}},vd=1e3,yd=6e4,_d=60*yd,bd=24*_d,Ed=function(e,t){t=t||{};var r=typeof e;if("string"===r&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return 6048e5*r;case"days":case"day":case"d":return r*bd;case"hours":case"hour":case"hrs":case"hr":case"h":return r*_d;case"minutes":case"minute":case"mins":case"min":case"m":return r*yd;case"seconds":case"second":case"secs":case"sec":case"s":return 1e3*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(e);if("number"===r&&isFinite(e))return t.long?function(e){var t=Math.abs(e);if(t>=bd)return wd(e,t,bd,"day");if(t>=_d)return wd(e,t,_d,"hour");if(t>=yd)return wd(e,t,yd,"minute");if(t>=1e3)return wd(e,t,1e3,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=bd)return Math.round(e/bd)+"d";if(t>=_d)return Math.round(e/_d)+"h";if(t>=yd)return Math.round(e/yd)+"m";if(t>=vd)return Math.round(e/vd)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function wd(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}var Sd=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=Ed,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=Sd(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(gd,gd.exports);var Cd={};Object.defineProperty(Cd,"__esModule",{value:!0});var Pd={},Td={};Object.defineProperty(Td,"__esModule",{value:!0}),Td.Logger=void 0;const Rd=gd.exports,kd="mediasoup-client";Td.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Rd.default)(`${kd}:${e}`),this._warn=(0,Rd.default)(`${kd}:WARN:${e}`),this._error=(0,Rd.default)(`${kd}:ERROR:${e}`)):(this._debug=(0,Rd.default)(kd),this._warn=(0,Rd.default)(`${kd}:WARN`),this._error=(0,Rd.default)(`${kd}: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,Id={},Ad={exports:{}},Od="object"==typeof Reflect?Reflect:null,Md=Od&&"function"==typeof Od.apply?Od.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};Dd=Od&&"function"==typeof Od.ownKeys?Od.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var Nd=Number.isNaN||function(e){return e!=e};function Ld(){Ld.init.call(this)}Ad.exports=Ld,Ad.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))}zd(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&zd(e,"error",t,r)}(e,i,{once:!0})}))},Ld.EventEmitter=Ld,Ld.prototype._events=void 0,Ld.prototype._eventsCount=0,Ld.prototype._maxListeners=void 0;var xd=10;function Fd(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function jd(e){return void 0===e._maxListeners?Ld.defaultMaxListeners:e._maxListeners}function Ud(e,t,r,n){var i,s,o,a;if(Fd(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=jd(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 Vd(){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 Bd(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=Vd.bind(n);return i.listener=r,n.wrapFn=i,i}function Wd(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):qd(i,i.length)}function Hd(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 qd(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function zd(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(Ld,"defaultMaxListeners",{enumerable:!0,get:function(){return xd},set:function(e){if("number"!=typeof e||e<0||Nd(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");xd=e}}),Ld.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},Ld.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||Nd(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},Ld.prototype.getMaxListeners=function(){return jd(this)},Ld.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)Md(a,this,t);else{var c=a.length,d=qd(a,c);for(r=0;r<c;++r)Md(d[r],this,t)}return!0},Ld.prototype.addListener=function(e,t){return Ud(this,e,t,!1)},Ld.prototype.on=Ld.prototype.addListener,Ld.prototype.prependListener=function(e,t){return Ud(this,e,t,!0)},Ld.prototype.once=function(e,t){return Fd(t),this.on(e,Bd(this,e,t)),this},Ld.prototype.prependOnceListener=function(e,t){return Fd(t),this.prependListener(e,Bd(this,e,t)),this},Ld.prototype.removeListener=function(e,t){var r,n,i,s,o;if(Fd(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},Ld.prototype.off=Ld.prototype.removeListener,Ld.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},Ld.prototype.listeners=function(e){return Wd(this,e,!0)},Ld.prototype.rawListeners=function(e){return Wd(this,e,!1)},Ld.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Hd.call(e,t)},Ld.prototype.listenerCount=Hd,Ld.prototype.eventNames=function(){return this._eventsCount>0?Dd(this._events):[]},Object.defineProperty(Id,"__esModule",{value:!0}),Id.EnhancedEventEmitter=void 0;const Gd=Ad.exports,Yd=new Td.Logger("EnhancedEventEmitter");class $d extends Gd.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){Yd.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)}}Id.EnhancedEventEmitter=$d;var Jd={};Object.defineProperty(Jd,"__esModule",{value:!0}),Jd.InvalidStateError=Jd.UnsupportedError=void 0;class Qd extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Qd):this.stack=new Error(e).stack}}Jd.UnsupportedError=Qd;class Kd extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Kd):this.stack=new Error(e).stack}}Jd.InvalidStateError=Kd;var Zd={};Object.defineProperty(Zd,"__esModule",{value:!0}),Zd.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))},Zd.generateRandomNumber=function(){return Math.round(1e7*Math.random())},Zd.deepFreeze=function e(t){const r=Reflect.ownKeys(t);for(const n of r){const r=t[n];(r&&"object"==typeof r||"function"==typeof r)&&e(r)}return Object.freeze(t)};var Xd={},eu={},tu={},ru={exports:{}};var nu=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=Ed,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=nu(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(ru,ru.exports),Object.defineProperty(tu,"__esModule",{value:!0}),tu.Logger=void 0;const iu=ru.exports,su="h264-profile-level-id";tu.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,iu.default)(`${su}:${e}`),this._warn=(0,iu.default)(`${su}:WARN:${e}`),this._error=(0,iu.default)(`${su}:ERROR:${e}`)):(this._debug=(0,iu.default)(su),this._warn=(0,iu.default)(`${su}:WARN`),this._error=(0,iu.default)(`${su}: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(eu,"__esModule",{value:!0}),eu.ProfileLevelId=eu.Level=eu.Profile=void 0,eu.parseProfileLevelId=mu,eu.profileLevelIdToString=gu,eu.profileToString=function(e){switch(e){case au.ConstrainedBaseline:return"ConstrainedBaseline";case au.Baseline:return"Baseline";case au.Main:return"Main";case au.ConstrainedHigh:return"ConstrainedHigh";case au.High:return"High";case au.PredictiveHigh444:return"PredictiveHigh444";default:return void ou.warn(`profileToString() | unrecognized profile ${e}`)}},eu.levelToString=function(e){switch(e){case cu.L1_b:return"1b";case cu.L1:return"1";case cu.L1_1:return"1.1";case cu.L1_2:return"1.2";case cu.L1_3:return"1.3";case cu.L2:return"2";case cu.L2_1:return"2.1";case cu.L2_2:return"2.2";case cu.L3:return"3";case cu.L3_1:return"3.1";case cu.L3_2:return"3.2";case cu.L4:return"4";case cu.L4_1:return"4.1";case cu.L4_2:return"4.2";case cu.L5:return"5";case cu.L5_1:return"5.1";case cu.L5_2:return"5.2";default:return void ou.warn(`levelToString() | unrecognized level ${e}`)}},eu.parseSdpProfileLevelId=vu,eu.isSameProfile=function(e={},t={}){const r=vu(e),n=vu(t);return Boolean(r&&n&&r.profile===n.profile)},eu.isSameProfileAndLevel=function(e={},t={}){const r=vu(e),n=vu(t);return Boolean(r&&n&&r.profile===n.profile&&r.level==n.level)},eu.generateProfileLevelIdStringForAnswer=function(e={},t={}){if(!e["profile-level-id"]&&!t["profile-level-id"])return void ou.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");const r=vu(e),n=vu(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=_u(e)&&_u(t),s=r.level,o=n.level,a=function(e,t){return function(e,t){if(e===cu.L1_b)return t!==cu.L1&&t!==cu.L1_b;if(t===cu.L1_b)return e!==cu.L1;return e<t}(e,t)?e:t}(s,o),c=i?s:a;return ou.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${r.profile}, level:${c}]`),gu(new du(r.profile,c))},eu.supportedLevel=function(e,t){for(let r=fu.length-1;r>=0;--r){const n=fu[r];if(256*n.max_macroblock_frame_size<=e&&n.max_macroblocks_per_second<=t*n.max_macroblock_frame_size)return ou.debug(`supportedLevel() | result [max_frame_pixel_count:${e}, max_fps:${t}, level:${n.level}]`),n.level}return void ou.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${e}, max_fps:${t}]`)};const ou=new tu.Logger;var au,cu;!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"}(au||(eu.Profile=au={})),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"}(cu||(eu.Level=cu={}));class du{profile;level;constructor(e,t){this.profile=e,this.level=t}}eu.ProfileLevelId=du;const uu=new du(au.ConstrainedBaseline,cu.L3_1);class lu{mask;masked_value;constructor(e){this.mask=~yu("x",e),this.masked_value=yu("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}}class pu{profile_idc;profile_iop;profile;constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}}const hu=[new pu(66,new lu("x1xx0000"),au.ConstrainedBaseline),new pu(77,new lu("1xxx0000"),au.ConstrainedBaseline),new pu(88,new lu("11xx0000"),au.ConstrainedBaseline),new pu(66,new lu("x0xx0000"),au.Baseline),new pu(88,new lu("10xx0000"),au.Baseline),new pu(77,new lu("0x0x0000"),au.Main),new pu(100,new lu("00000000"),au.High),new pu(100,new lu("00001100"),au.ConstrainedHigh),new pu(244,new lu("00000000"),au.PredictiveHigh444)],fu=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:cu.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:cu.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:cu.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:cu.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:cu.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:cu.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:cu.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:cu.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:cu.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:cu.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:cu.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:cu.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:cu.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:cu.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:cu.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:cu.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:cu.L5_2}];function mu(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 cu.L1_1:s=0!=(16&n)?cu.L1_b:cu.L1_1;break;case cu.L1:case cu.L1_2:case cu.L1_3:case cu.L2:case cu.L2_1:case cu.L2_2:case cu.L3:case cu.L3_1:case cu.L3_2:case cu.L4:case cu.L4_1:case cu.L4_2:case cu.L5:case cu.L5_1:case cu.L5_2:s=r;break;default:return void ou.warn(`parseProfileLevelId() | unrecognized level_idc [str:${e}, level_idc:${r}]`)}for(const t of hu)if(i===t.profile_idc&&t.profile_iop.isMatch(n))return ou.debug(`parseProfileLevelId() | result [str:${e}, profile:${t.profile}, level:${s}]`),new du(t.profile,s);ou.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${e}, profile_idc:${i}, profile_iop:${n}]`)}function gu(e){if(e.level==cu.L1_b)switch(e.profile){case au.ConstrainedBaseline:return"42f00b";case au.Baseline:return"42100b";case au.Main:return"4d100b";default:return void ou.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${e.profile}`)}let t;switch(e.profile){case au.ConstrainedBaseline:t="42e0";break;case au.Baseline:t="4200";break;case au.Main:t="4d00";break;case au.ConstrainedHigh:t="640c";break;case au.High:t="6400";break;case au.PredictiveHigh444:t="f400";break;default:return void ou.warn(`profileLevelIdToString() | unrecognized profile ${e.profile}`)}let r=e.level.toString(16);return 1===r.length&&(r=`0${r}`),`${t}${r}`}function vu(e={}){const t=e["profile-level-id"];return t?mu(t):uu}function yu(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 _u(e={}){const t=e["level-asymmetry-allowed"];return!0===t||1===t||"1"===t}Object.defineProperty(Xd,"__esModule",{value:!0}),Xd.validateAndNormalizeRtpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(e.codecs&&!Array.isArray(e.codecs))throw new TypeError("caps.codecs is not an array");e.codecs||(e.codecs=[]);for(const t of e.codecs)Su(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)Pu(t)},Xd.validateAndNormalizeRtpParameters=wu,Xd.validateAndNormalizeSctpStreamParameters=function(e){if("object"!=typeof e)throw new TypeError("params is not an object");if("number"!=typeof e.streamId)throw new TypeError("missing params.streamId");let t=!1;"boolean"==typeof e.ordered?t=!0:e.ordered=!0;if(e.maxPacketLifeTime&&"number"!=typeof e.maxPacketLifeTime)throw new TypeError("invalid params.maxPacketLifeTime");if(e.maxRetransmits&&"number"!=typeof e.maxRetransmits)throw new TypeError("invalid params.maxRetransmits");if(e.maxPacketLifeTime&&e.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(t&&e.ordered&&(e.maxPacketLifeTime||e.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");t||!e.maxPacketLifeTime&&!e.maxRetransmits||(e.ordered=!1);if(e.label&&"string"!=typeof e.label)throw new TypeError("invalid params.label");if(e.protocol&&"string"!=typeof e.protocol)throw new TypeError("invalid params.protocol")},Xd.validateSctpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(!e.numStreams||"object"!=typeof e.numStreams)throw new TypeError("missing caps.numStreams");!function(e){if("object"!=typeof e)throw new TypeError("numStreams is not an object");if("number"!=typeof e.OS)throw new TypeError("missing numStreams.OS");if("number"!=typeof e.MIS)throw new TypeError("missing numStreams.MIS")}(e.numStreams)},Xd.getExtendedRtpCapabilities=function(e,t,r){const n={codecs:[],headerExtensions:[]};if(r)for(const r of e.codecs??[]){if(Iu(r))continue;const e=(t.codecs??[]).find((e=>Au(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:Mu(r,e)};n.codecs.push(i)}else for(const r of t.codecs??[]){if(Iu(r))continue;const t=(e.codecs??[]).find((e=>Au(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:Mu(t,r)};n.codecs.push(i)}for(const r of n.codecs){const n=e.codecs.find((e=>Iu(e)&&e.parameters?.apt===r.localPayloadType)),i=t.codecs.find((e=>Iu(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=>Ou(e,r)));if(!t)continue;const i={kind:r.kind,uri:r.uri,sendId:t.preferredId,recvId:r.preferredId,encrypt:t.preferredEncrypt??!1,direction:"sendrecv"};switch(r.direction){case"sendrecv":i.direction="sendrecv";break;case"recvonly":i.direction="sendonly";break;case"sendonly":i.direction="recvonly";break;case"inactive":i.direction="inactive"}n.headerExtensions.push(i)}return n},Xd.getRecvRtpCapabilities=function(e){return Du({direction:"recvonly",extendedRtpCapabilities:e})},Xd.getSendRtpCapabilities=function(e){return Du({direction:"sendonly",extendedRtpCapabilities:e})},Xd.getSendingRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const n of t.codecs){if(n.kind!==e)continue;const t={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.localParameters,rtcpFeedback:n.rtcpFeedback};if(r.codecs.push(t),n.localRtxPayloadType){const e={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const n of t.headerExtensions){if(n.kind&&n.kind!==e||"sendrecv"!==n.direction&&"sendonly"!==n.direction)continue;const t={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};r.headerExtensions.push(t)}return r},Xd.getSendingRemoteRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const n of t.codecs){if(n.kind!==e)continue;const t={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.remoteParameters,rtcpFeedback:n.rtcpFeedback};if(r.codecs.push(t),n.localRtxPayloadType){const e={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const n of t.headerExtensions){if(n.kind&&n.kind!==e||"sendrecv"!==n.direction&&"sendonly"!==n.direction)continue;const t={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};r.headerExtensions.push(t)}if(r.headerExtensions.some((e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.uri)))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"goog-remb"!==e.type));else if(r.headerExtensions.some((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.uri)))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"transport-cc"!==e.type));else for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter((e=>"transport-cc"!==e.type&&"goog-remb"!==e.type));return r},Xd.reduceCodecs=function(e,t){const r=[];if(t){for(let n=0;n<e.length;++n)if(Au(e[n],t,{strict:!0})){r.push(e[n]),Iu(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]),Iu(e[1])&&r.push(e[1]);return r},Xd.generateProbatorRtpParameters=function(e){wu(e=Eu.clone(e));const t={mid:"probator",codecs:[],headerExtensions:[],encodings:[{ssrc:1234}],rtcp:{cname:"probator"}};return t.codecs.push(e.codecs[0]),t.codecs[0].payloadType=127,t.headerExtensions=e.headerExtensions,t},Xd.canSend=function(e,t){return(t.codecs??[]).some((t=>t.kind===e))},Xd.canReceive=function(e,t){if(wu(e),0===e.codecs.length)return!1;const r=e.codecs[0];return(t.codecs??[]).some((e=>e.preferredPayloadType===r.payloadType))};const bu=eu,Eu=Zd;function wu(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)Tu(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)Ru(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)ku(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 Su(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)Cu(t)}function Cu(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 Pu(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 Tu(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)Cu(t)}function Ru(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 ku(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 Du({direction:e,extendedRtpCapabilities:t}){const r={codecs:[],headerExtensions:[]};for(const e of t.codecs){const t={kind:e.kind,mimeType:e.mimeType,preferredPayloadType:e.remotePayloadType,clockRate:e.clockRate,channels:e.channels,parameters:e.localParameters,rtcpFeedback:e.rtcpFeedback};if(r.codecs.push(t),!e.remoteRtxPayloadType)continue;const n={kind:e.kind,mimeType:`${e.kind}/rtx`,preferredPayloadType:e.remoteRtxPayloadType,clockRate:e.clockRate,parameters:{apt:e.remotePayloadType},rtcpFeedback:[]};r.codecs.push(n)}for(const n of t.headerExtensions){if("sendrecv"!==n.direction&&n.direction!==e)continue;const t={kind:n.kind,uri:n.uri,preferredId:n.recvId,preferredEncrypt:n.encrypt??!1,direction:n.direction};r.headerExtensions.push(t)}return r}function Iu(e){return!!e&&/.+\/rtx$/i.test(e.mimeType)}function Au(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(!bu.isSameProfile(e.parameters,t.parameters))return!1;let r;try{r=bu.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 Ou(e,t){return(!e.kind||!t.kind||e.kind===t.kind)&&e.uri===t.uri}function Mu(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 Nu={},Lu={},xu={},Fu={};Object.defineProperty(Fu,"__esModule",{value:!0}),Fu.Logger=void 0;const ju=gd.exports,Uu="awaitqueue";Fu.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=ju(`awaitqueue:${e}`),this._warn=ju(`awaitqueue:WARN:${e}`),this._error=ju(`awaitqueue:ERROR:${e}`)):(this._debug=ju(Uu),this._warn=ju("awaitqueue:WARN"),this._error=ju("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 Vu={};Object.defineProperty(Vu,"__esModule",{value:!0}),Vu.AwaitQueueRemovedTaskError=Vu.AwaitQueueStoppedError=void 0;class Bu extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Bu)}}Vu.AwaitQueueStoppedError=Bu;class Wu extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Wu)}}Vu.AwaitQueueRemovedTaskError=Wu,Object.defineProperty(xu,"__esModule",{value:!0}),xu.AwaitQueue=void 0;const Hu=Vu,qu=new Fu.Logger("AwaitQueue");xu.AwaitQueue=class{pendingTasks=new Map;nextTaskId=0;constructor(){qu.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t,r){if(t=t??e.name,qu.debug(`push() [name:${t}, options:%o]`,r),"function"!=typeof e)throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch(e){}return new Promise(((n,i)=>{if(t&&r?.removeOngoingTasksWithSameName)for(const e of this.pendingTasks.values())e.name===t&&e.reject(new Hu.AwaitQueueRemovedTaskError,{canExecuteNextTask:!1});const s={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:e=>{if(s.completed)return;s.completed=!0,this.pendingTasks.delete(s.id),qu.debug(`resolving task [name:${s.name}]`),n(e);const[t]=this.pendingTasks.values();t&&!t.executedAt&&this.execute(t)},reject:(e,{canExecuteNextTask:t})=>{if(!s.completed&&(s.completed=!0,this.pendingTasks.delete(s.id),qu.debug(`rejecting task [name:${s.name}]: %s`,String(e)),i(e),t)){const[e]=this.pendingTasks.values();e&&!e.executedAt&&this.execute(e)}}};this.pendingTasks.set(s.id,s),1===this.pendingTasks.size&&this.execute(s)}))}stop(){qu.debug("stop()");for(const e of this.pendingTasks.values())qu.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Hu.AwaitQueueStoppedError,{canExecuteNextTask:!1})}remove(e){qu.debug(`remove() [taskIdx:${e}]`);const t=Array.from(this.pendingTasks.values())[e];t?t.reject(new Hu.AwaitQueueRemovedTaskError,{canExecuteNextTask:!0}):qu.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(qu.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const t=await e.task();e.resolve(t)}catch(t){e.reject(t,{canExecuteNextTask:!0})}}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AwaitQueueRemovedTaskError=e.AwaitQueueStoppedError=e.AwaitQueue=void 0;var t=xu;Object.defineProperty(e,"AwaitQueue",{enumerable:!0,get:function(){return t.AwaitQueue}});var r=Vu;Object.defineProperty(e,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return r.AwaitQueueStoppedError}}),Object.defineProperty(e,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return r.AwaitQueueRemovedTaskError}})}(Lu);var zu={};Object.defineProperty(zu,"__esModule",{value:!0}),zu.Producer=void 0;const Gu=Id,Yu=Jd,$u=new Td.Logger("Producer");class Ju extends Gu.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new Gu.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:r,track:n,rtpParameters:i,stopTracks:s,disableTrackOnPause:o,zeroRtpOnPause:a,appData:c}){super(),$u.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||($u.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||($u.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Yu.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){$u.debug("pause()"),this._closed?$u.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(){$u.debug("resume()"),this._closed?$u.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($u.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch(e){}throw new Yu.InvalidStateError("closed")}if("ended"===e?.readyState)throw new Yu.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()):$u.debug("replaceTrack() | same track, ignored")}async setMaxSpatialLayer(e){if(this._closed)throw new Yu.InvalidStateError("closed");if("video"!==this._kind)throw new Yu.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 Yu.InvalidStateError("closed");if("object"!=typeof e)throw new TypeError("invalid params");await new Promise(((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)}))}onTrackEnded(){$u.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){}}}zu.Producer=Ju;var Qu={};Object.defineProperty(Qu,"__esModule",{value:!0}),Qu.Consumer=void 0;const Ku=Id,Zu=Jd,Xu=new Td.Logger("Consumer");class el extends Ku.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new Ku.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:r,rtpReceiver:n,track:i,rtpParameters:s,appData:o}){super(),Xu.debug("constructor()"),this._id=e,this._localId=t,this._producerId=r,this._rtpReceiver=n,this._track=i,this._rtpParameters=s,this._paused=!i.enabled,this._appData=o??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get producerId(){return this._producerId}get closed(){return this._closed}get kind(){return this._track.kind}get rtpReceiver(){return this._rtpReceiver}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Xu.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Xu.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Zu.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){Xu.debug("pause()"),this._closed?Xu.error("pause() | Consumer closed"):this._paused?Xu.debug("pause() | Consumer is already paused"):(this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause"))}resume(){Xu.debug("resume()"),this._closed?Xu.error("resume() | Consumer closed"):this._paused?(this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")):Xu.debug("resume() | Consumer is already resumed")}onTrackEnded(){Xu.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){try{this._track.removeEventListener("ended",this.onTrackEnded),this._track.stop()}catch(e){}}}Qu.Consumer=el;var tl={};Object.defineProperty(tl,"__esModule",{value:!0}),tl.DataProducer=void 0;const rl=Id,nl=Jd,il=new Td.Logger("DataProducer");class sl extends rl.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new rl.EnhancedEventEmitter;constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:n}){super(),il.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||(il.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(il.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(il.debug("send()"),this._closed)throw new nl.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(il.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?il.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):il.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(il.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))})),this._dataChannel.addEventListener("message",(()=>{this._closed||il.warn('DataChannel "message" event in a DataProducer, message discarded')})),this._dataChannel.addEventListener("bufferedamountlow",(()=>{this._closed||this.safeEmit("bufferedamountlow")}))}}tl.DataProducer=sl;var ol={};Object.defineProperty(ol,"__esModule",{value:!0}),ol.DataConsumer=void 0;const al=Id,cl=new Td.Logger("DataConsumer");class dl extends al.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new al.EnhancedEventEmitter;constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:n,appData:i}){super(),cl.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||(cl.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(cl.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(cl.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?cl.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):cl.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(cl.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)}))}}ol.DataConsumer=dl,Object.defineProperty(Nu,"__esModule",{value:!0}),Nu.Transport=void 0;const ul=Lu,ll=Id,pl=Jd,hl=Zd,fl=Xd,ml=zu,gl=Qu,vl=tl,yl=ol,_l=new Td.Logger("Transport");class bl{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class El extends ll.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 ul.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new ll.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(),_l.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=hl.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){_l.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 pl.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(_l.debug("restartIce()"),this._closed)throw new pl.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(_l.debug("updateIceServers()"),this._closed)throw new pl.InvalidStateError("closed");if(!Array.isArray(e))throw new TypeError("missing iceServers");return this._awaitQueue.push((async()=>this._handler.updateIceServers(e)),"transport.updateIceServers()")}async produce({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s,stopTracks:o=!0,disableTrackOnPause:a=!0,zeroRtpOnPause:c=!1,onRtpSender:d,appData:u={}}={}){if(_l.debug("produce() [track:%o]",e),this._closed)throw new pl.InvalidStateError("closed");if(!e)throw new TypeError("missing track");if("send"!==this._direction)throw new pl.UnsupportedError("not a sending Transport");if(!this._canProduceByKind[e.kind])throw new pl.UnsupportedError(`cannot produce ${e.kind}`);if("ended"===e.readyState)throw new pl.InvalidStateError("track ended");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("produce"))throw new TypeError('no "produce" listener set into this transport');if(u&&"object"!=typeof u)throw new TypeError("if given, appData must be an object");return this._awaitQueue.push((async()=>{let l;if(r&&!Array.isArray(r))throw TypeError("encodings must be an array");0===r?.length?l=void 0:r&&(l=r.map((e=>{const t={active:!0};return!1===e.active&&(t.active=!1),"boolean"==typeof e.dtx&&(t.dtx=e.dtx),"string"==typeof e.scalabilityMode&&(t.scalabilityMode=e.scalabilityMode),"number"==typeof e.scaleResolutionDownBy&&(t.scaleResolutionDownBy=e.scaleResolutionDownBy),"number"==typeof e.maxBitrate&&(t.maxBitrate=e.maxBitrate),"number"==typeof e.maxFramerate&&(t.maxFramerate=e.maxFramerate),"boolean"==typeof e.adaptivePtime&&(t.adaptivePtime=e.adaptivePtime),"string"==typeof e.priority&&(t.priority=e.priority),"string"==typeof e.networkPriority&&(t.networkPriority=e.networkPriority),t})));const{localId:p,rtpParameters:h,rtpSender:f}=await this._handler.send({track:e,streamId:t,encodings:l,codecOptions:n,headerExtensionOptions:i,codec:s,onRtpSender:d});try{fl.validateAndNormalizeRtpParameters(h);const{id:t}=await new Promise(((t,r)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:h,appData:u},t,r)})),r=new ml.Producer({id:t,localId:p,rtpSender:f,track:e,rtpParameters:h,stopTracks:o,disableTrackOnPause:a,zeroRtpOnPause:c,appData:u});return this._producers.set(r.id,r),this.handleProducer(r),this._observer.safeEmit("newproducer",r),r}catch(e){throw this._handler.stopSending(p).catch((()=>{})),e}}),"transport.produce()").catch((t=>{if(o)try{e.stop()}catch(e){}throw t}))}async consume({id:e,producerId:t,kind:r,rtpParameters:n,streamId:i,onRtpReceiver:s,appData:o={}}){if(_l.debug("consume()"),this._closed)throw new pl.InvalidStateError("closed");if("recv"!==this._direction)throw new pl.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=hl.clone(n);if(!fl.canReceive(a,this._recvRtpCapabilities))throw new pl.UnsupportedError("cannot consume this Producer");const c=new bl({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(_l.debug("produceData()"),this._closed)throw new pl.InvalidStateError("closed");if("send"!==this._direction)throw new pl.UnsupportedError("not a sending Transport");if(!this._maxSctpMessageSize)throw new pl.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});fl.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 vl.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(_l.debug("consumeData()"),this._closed)throw new pl.InvalidStateError("closed");if("recv"!==this._direction)throw new pl.UnsupportedError("not a receiving Transport");if(!this._maxSctpMessageSize)throw new pl.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=hl.clone(r);return fl.validateAndNormalizeSctpStreamParameters(o),this._awaitQueue.push((async()=>{const{dataChannel:r}=await this._handler.receiveDataChannel({sctpStreamParameters:o,label:n,protocol:i}),a=new yl.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 _l.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 gl.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=fl.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:e}]),_l.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(e){_l.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 _l.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){_l.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 _l.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){_l.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 _l.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){_l.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 pl.InvalidStateError("closed")):this.safeEmit("connect",{dtlsParameters:e},t,r)})),e.on("@icegatheringstatechange",(e=>{e!==this._iceGatheringState&&(_l.debug("ICE gathering state changed to %s",e),this._iceGatheringState=e,this._closed||this.safeEmit("icegatheringstatechange",e))})),e.on("@icecandidateerror",(e=>{_l.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&&(_l.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=>_l.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 pl.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 pl.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)}))}}Nu.Transport=El;var wl={},Sl={},Cl={},Pl={exports:{}},Tl=Pl.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{push:"msid",reg:/^msid:([\w-]+)(?: ([\w-]+))?/,names:["id","appdata"],format:"msid:%s %s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Tl).forEach((function(e){Tl[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=Pl.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}}))}))}}(Cl);var Rl=Pl.exports,kl=/%[sdv%]/g,Dl=function(e){var t=1,r=arguments,n=r.length;return e.replace(kl,(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""}}))},Il=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 Dl.apply(null,n)},Al=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Ol=["i","c","b","a"],Ml=Cl,Nl=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||Al,n=t.innerOrder||Ol,i=[];return r.forEach((function(t){Rl[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(Il(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(Il(t,r,e))}))}))})),e.media.forEach((function(e){i.push(Il("m",Rl.m[0],e)),n.forEach((function(t){Rl[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(Il(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(Il(t,r,e))}))}))}))})),i.join("\r\n")+"\r\n"},Ll=Pl.exports;Sl.grammar=Ll,Sl.write=Nl,Sl.parse=Ml.parse,Sl.parseParams=Ml.parseParams,Sl.parseFmtpConfig=Ml.parseFmtpConfig,Sl.parsePayloads=Ml.parsePayloads,Sl.parseRemoteCandidates=Ml.parseRemoteCandidates,Sl.parseImageAttributes=Ml.parseImageAttributes,Sl.parseSimulcastStreamList=Ml.parseSimulcastStreamList;var xl={};Object.defineProperty(xl,"__esModule",{value:!0}),xl.parse=function(e){const t=Fl.exec(e??"");return t?{spatialLayers:Number(t[1]),temporalLayers:Number(t[2])}:{spatialLayers:1,temporalLayers:1}};const Fl=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");var jl={},Ul={};Object.defineProperty(Ul,"__esModule",{value:!0}),Ul.OfferMediaSection=Ul.AnswerMediaSection=Ul.MediaSection=void 0;const Vl=Sl,Bl=Zd;class Wl{_mediaObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r}){if(this._mediaObject={type:"",port:0,protocol:"",payloads:"",rtp:[],fmtp:[]},e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(const e of t){const t={foundation:e.foundation,component:1,ip:e.address??e.ip,port:e.port,priority:e.priority,transport:e.protocol,type:e.type};e.tcpType&&(t.tcptype=e.tcpType),this._mediaObject.candidates.push(t)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}r&&this.setDtlsRole(r.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return 0===this._mediaObject.port}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause()}close(){this.disable(),this._mediaObject.port=0,delete this._mediaObject.candidates,delete this._mediaObject.endOfCandidates,delete this._mediaObject.iceUfrag,delete this._mediaObject.icePwd,delete this._mediaObject.iceOptions,this._mediaObject.rtp=[],this._mediaObject.fmtp=[],delete this._mediaObject.rtcp,delete this._mediaObject.rtcpFb,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}}Ul.MediaSection=Wl;Ul.AnswerMediaSection=class extends Wl{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:Hl(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r=Bl.clone(e.parameters)??{};let n=Bl.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=Vl.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 Hl(e){const t=new RegExp("^(audio|video)/(.+)","i").exec(e.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}Ul.OfferMediaSection=class extends Wl{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,mid:s,kind:o,offerRtpParameters:a,streamId:c,trackId:d}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(s),this._mediaObject.type=o,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.protocol=n?"UDP/DTLS/SCTP":"UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",o){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=[{id:c,appdata:d}];for(const e of a.codecs){const t={payload:e.payloadType,codec:Hl(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(jl,"__esModule",{value:!0}),jl.RemoteSdp=void 0;const ql=Sl,zl=Ul,Gl=md,Yl=["av1","h264"],$l=new Td.Logger("RemoteSdp");jl.RemoteSdp=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i}){if(this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=r,this._sctpParameters=n,this._plainRtpParameters=i,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:`mediasoup-client-v${Gl.version}`},name:"-",timing:{start:0,stop:0},media:[]},this._sdpObject.iceOptions="ice2",e?.iceLite&&(this._sdpObject.icelite="ice-lite"),r){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};const e=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:r.fingerprints[e-1].algorithm,hash:r.fingerprints[e-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){$l.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){$l.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(const t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){$l.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 zl.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=>Yl.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 zl.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?($l.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 zl.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 zl.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++,ql.write(this._sdpObject)}addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this.regenerateBundleMids()}replaceMediaSection(e,t){if("string"==typeof t){const r=this._midToIndex.get(t);if(void 0===r)throw new Error(`no media section found for reuseMid '${t}'`);const n=this._mediaSections[r];this._mediaSections[r]=e,this._midToIndex.delete(n.mid),this._midToIndex.set(e.mid,r),this._sdpObject.media[r]=e.getObject(),this.regenerateBundleMids()}else{const t=this._midToIndex.get(e.mid);if(void 0===t)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[t]=e,this._sdpObject.media[t]=e.getObject()}}findMediaSection(e){const t=this._midToIndex.get(e);if(void 0===t)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter((e=>!e.closed)).map((e=>e.mid)).join(" "))}};var Jl={};Object.defineProperty(Jl,"__esModule",{value:!0}),Jl.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=Ql.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())}},Jl.extractDtlsParameters=function({sdpObject:e}){let t,r=e.setup,n=e.fingerprint;if(!r||!n){const t=(e.media??[]).find((e=>0!==e.port));t&&(r=r??t.setup,n=n??t.fingerprint)}if(!r)throw new Error("no a=setup found at SDP session or media level");if(!n)throw new Error("no a=fingerprint found at SDP session or media level");switch(r){case"active":t="client";break;case"passive":t="server";break;case"actpass":t="auto"}return{role:t,fingerprints:[{algorithm:n.type,value:n.hash}]}},Jl.getCname=function({offerMediaObject:e}){const t=(e.ssrcs??[]).find((e=>"cname"===e.attribute));if(!t)return"";return t.value},Jl.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=Ql.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]}`}},Jl.addHeaderExtension=function({offerMediaObject:e,headerExtensionUri:t,headerExtensionId:r}){e.ext||(e.ext=[]);e.ext.push({uri:t,value:r})};const Ql=Sl;var Kl={};Object.defineProperty(Kl,"__esModule",{value:!0}),Kl.getRtpEncodings=function({offerMediaObject:e,codecs:t}){const r=new Set;for(const t of e.ssrcs??[]){const e=t.id;e&&r.add(e)}if(0===r.size)throw new Error("no a=ssrc lines found");const n=new Map;for(const t of e.ssrcGroups??[]){if("FID"!==t.semantics)continue;const e=t.ssrcs.split(/\s+/),i=Number(e[0]),s=Number(e[1]);r.has(i)&&(r.delete(i),r.delete(s),n.set(i,s))}for(const e of r)n.set(e,void 0);const i=[];for(const[e,r]of n){const n={ssrc:e};r&&t.length>1&&(n.rtx={ssrc:r}),i.push(n)}return i},Kl.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 Zl={};Object.defineProperty(Zl,"__esModule",{value:!0}),Zl.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"}))},Zl.addHeaderExtensionSupport=function(e,t){let r;const n=e.headerExtensions?.find((e=>e.uri===t.uri));if(n){if(n.kind===t.kind)return;r=n.preferredId}e.headerExtensions||(e.headerExtensions=[]);if(void 0===r){r=1;const t=new Set(e.headerExtensions.map((e=>e.preferredId)));for(;t.has(r);)++r}const i={kind:t.kind,uri:t.uri,preferredId:r,preferredEncrypt:!1,direction:t.direction};e.headerExtensions.push(i)},Zl.getMsidStreamIdAndTrackId=function(e){if(!e||"string"!=typeof e)return{msidStreamId:void 0,msidTrackId:void 0};const[t,r]=e.trim().split(/\s+/);if(!t)return{msidStreamId:void 0,msidTrackId:void 0};return{msidStreamId:t,msidTrackId:r}},Object.defineProperty(wl,"__esModule",{value:!0}),wl.Chrome111=void 0;const Xl=Sl,ep=Id,tp=Xd,rp=Jd,np=xl,ip=jl,sp=Jl,op=Kl,ap=Zl,cp=new Td.Logger("Chrome111"),dp={OS:1024,MIS:1024};class up extends ep.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 up(e),getNativeRtpCapabilities:async({direction:e})=>{cp.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e,sendEncodings:[{scalabilityMode:"L3T3"}]});const r=await t.createOffer();try{t.close()}catch(e){}t=void 0;const n=Xl.parse(r.sdp);return up.getLocalRtpCapabilities(n)}catch(e){try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(cp.debug("getNativeSctpCapabilities()"),{numStreams:dp})}}static getLocalRtpCapabilities(e,t=[]){const r=sp.extractRtpCapabilities({sdpObject:e});tp.validateAndNormalizeRtpCapabilities(r),ap.addNackSupportForOpus(r);for(const e of t)ap.addHeaderExtensionSupport(r,e);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),cp.debug("constructor()"),this._direction=e,this._remoteSdp=new ip.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):(cp.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Chrome111"}close(){if(cp.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(),cp.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),cp.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});cp.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};cp.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};cp.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();cp.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s,onRtpSender:o}){if(this.assertNotClosed(),this.assertSendDirection(),cp.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1){let e=1;for(const t of r){const r=t.scalabilityMode?(0,np.parse)(t.scalabilityMode).temporalLayers:3;r>e&&(e=r)}r.forEach(((t,r)=>{t.rid=`r${r}`,t.scalabilityMode=`L1T${e}`}))}const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});o&&o(c.sender);let d=await this._pc.createOffer(),u=Xl.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const l=[];l.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});const p=up.getLocalRtpCapabilities(u,l),h=this._getSendExtendedRtpCapabilities(p),f=tp.getSendingRtpParameters(e.kind,h);f.codecs=tp.reduceCodecs(f.codecs,s);const m=tp.getSendingRemoteRtpParameters(e.kind,h);if(m.codecs=tp.reduceCodecs(m.codecs,s),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u}),i?.absCaptureTime){const e=u.media[a.idx];sp.addHeaderExtension({offerMediaObject:e,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"===e.uri)).id}),d={type:"offer",sdp:Xl.write(u)}}cp.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const g=c.mid;f.mid=g,u=Xl.parse(this._pc.localDescription.sdp);const v=u.media[a.idx];if(f.rtcp.cname=sp.getCname({offerMediaObject:v}),f.msid=`${t??this._sendStream.id} ${e.id}`,r)if(1===r.length){const e=op.getRtpEncodings({offerMediaObject:v,codecs:f.codecs});Object.assign(e[0],r[0]),f.encodings=e}else f.encodings=r;else f.encodings=op.getRtpEncodings({offerMediaObject:v,codecs:f.codecs});this._remoteSdp.send({offerMediaObject:v,reuseMid:a.reuseMid,offerRtpParameters:f,answerRtpParameters:m,codecOptions:n});const y={type:"answer",sdp:this._remoteSdp.getSdp()};return cp.debug("send() | calling pc.setRemoteDescription() [answer:%o]",y),await this._pc.setRemoteDescription(y),this._mapMidTransceiver.set(g,c),{localId:g,rtpParameters:f,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),cp.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();cp.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};cp.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),cp.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();cp.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};cp.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),cp.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();cp.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};cp.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?cp.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):cp.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(),cp.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();cp.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};cp.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),cp.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();cp.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};cp.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};cp.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%dp.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Xl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),cp.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()};cp.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;cp.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=ap.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};cp.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=Xl.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));sp.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Xl.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),cp.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){cp.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()};cp.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();cp.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){cp.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()};cp.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();cp.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){cp.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()};cp.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();cp.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};cp.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()};cp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Xl.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}cp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Xl.parse(this._pc.localDescription.sdp));const r=sp.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 rp.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')}}wl.Chrome111=up;var lp={};Object.defineProperty(lp,"__esModule",{value:!0}),lp.Chrome74=void 0;const pp=Sl,hp=Id,fp=Xd,mp=Jd,gp=xl,vp=jl,yp=Jl,_p=Kl,bp=Zl,Ep=new Td.Logger("Chrome74"),wp={OS:1024,MIS:1024};class Sp extends hp.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 Sp(e),getNativeRtpCapabilities:async({direction:e})=>{Ep.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});const r=await t.createOffer();try{t.close()}catch(e){}t=void 0;const n=pp.parse(r.sdp);return Sp.getLocalRtpCapabilities(n)}catch(e){try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(Ep.debug("getNativeSctpCapabilities()"),{numStreams:wp})}}static getLocalRtpCapabilities(e,t=[]){const r=yp.extractRtpCapabilities({sdpObject:e});fp.validateAndNormalizeRtpCapabilities(r),bp.addNackSupportForOpus(r);for(const e of t)bp.addHeaderExtensionSupport(r,e);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Ep.debug("constructor()"),this._direction=e,this._remoteSdp=new vp.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):(Ep.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Chrome74"}close(){if(Ep.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(),Ep.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Ep.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Ep.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Ep.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Ep.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Ep.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s}){this.assertNotClosed(),this.assertSendDirection(),Ep.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach(((e,t)=>{e.rid=`r${t}`}));const o=this._remoteSdp.getNextMediaSectionIdx(),a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});let c=await this._pc.createOffer(),d=pp.parse(c.sdp);d.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const u=[];u.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});const l=Sp.getLocalRtpCapabilities(d,u),p=this._getSendExtendedRtpCapabilities(l),h=fp.getSendingRtpParameters(e.kind,p);h.codecs=fp.reduceCodecs(h.codecs,s);const f=fp.getSendingRemoteRtpParameters(e.kind,p);f.codecs=fp.reduceCodecs(f.codecs,s),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:d});let m=!1;const g=(0,gp.parse)((r??[{}])[0].scalabilityMode);let v;1===r?.length&&g.spatialLayers>1&&"video/vp9"===h.codecs[0].mimeType.toLowerCase()&&(Ep.debug("send() | enabling legacy simulcast for VP9 SVC"),m=!0,d=pp.parse(c.sdp),v=d.media[o.idx],_p.addLegacySimulcast({offerMediaObject:v,numStreams:g.spatialLayers}),c={type:"offer",sdp:pp.write(d)}),Ep.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),i?.absCaptureTime&&(v=d.media[o.idx],yp.addHeaderExtension({offerMediaObject:v,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:f.headerExtensions.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"===e.uri)).id}),c={type:"offer",sdp:pp.write(d)}),await this._pc.setLocalDescription(c);const y=a.mid;if(h.mid=y,d=pp.parse(this._pc.localDescription.sdp),v=d.media[o.idx],h.rtcp.cname=yp.getCname({offerMediaObject:v}),h.msid=`${t??this._sendStream.id} ${e.id}`,r)if(1===r.length){let e=_p.getRtpEncodings({offerMediaObject:v,codecs:h.codecs});Object.assign(e[0],r[0]),m&&(e=[e[0]]),h.encodings=e}else h.encodings=r;else h.encodings=_p.getRtpEncodings({offerMediaObject:v,codecs:h.codecs});if(h.encodings.length>1&&("video/vp8"===h.codecs[0].mimeType.toLowerCase()||"video/h264"===h.codecs[0].mimeType.toLowerCase()))for(const e of h.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${g.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:v,reuseMid:o.reuseMid,offerRtpParameters:h,answerRtpParameters:f,codecOptions:n});const _={type:"answer",sdp:this._remoteSdp.getSdp()};return Ep.debug("send() | calling pc.setRemoteDescription() [answer:%o]",_),await this._pc.setRemoteDescription(_),this._mapMidTransceiver.set(y,a),{localId:y,rtpParameters:h,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),Ep.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();Ep.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Ep.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Ep.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();Ep.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Ep.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Ep.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();Ep.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Ep.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Ep.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Ep.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(),Ep.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();Ep.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Ep.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Ep.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();Ep.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Ep.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};Ep.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%wp.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=pp.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Ep.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()};Ep.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;Ep.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=bp.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Ep.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer();const s=pp.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));yp.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:pp.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Ep.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){Ep.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()};Ep.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Ep.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){Ep.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()};Ep.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Ep.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){Ep.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()};Ep.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Ep.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};Ep.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()};Ep.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=pp.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Ep.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=pp.parse(this._pc.localDescription.sdp));const r=yp.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 mp.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')}}lp.Chrome74=Sp;var Cp={};Object.defineProperty(Cp,"__esModule",{value:!0}),Cp.Firefox120=void 0;const Pp=Sl,Tp=Id,Rp=Jd,kp=Xd,Dp=xl,Ip=jl,Ap=Jl,Op=Kl,Mp=Zl,Np=new Td.Logger("Firefox120"),Lp={OS:16,MIS:2048};class xp extends Tp.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 xp(e),getNativeRtpCapabilities:async({direction:e})=>{Np.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});const r=document.createElement("canvas");r.getContext("2d");const n=r.captureStream().getVideoTracks()[0];try{t.addTransceiver("audio",{direction:e}),t.addTransceiver(n,{direction:e,sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});const i=await t.createOffer();try{r.remove()}catch(e){}try{n.stop()}catch(e){}try{t.close()}catch(e){}t=void 0;const s=Pp.parse(i.sdp);return xp.getLocalRtpCapabilities(s)}catch(e){try{r.remove()}catch(e){}try{n.stop()}catch(e){}try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(Np.debug("getNativeSctpCapabilities()"),{numStreams:Lp})}}static getLocalRtpCapabilities(e){const t=Ap.extractRtpCapabilities({sdpObject:e});return kp.validateAndNormalizeRtpCapabilities(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Np.debug("constructor()"),this._direction=e,this._remoteSdp=new Ip.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):(Np.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Firefox120"}close(){if(Np.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 Rp.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),Np.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Np.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Np.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Np.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Np.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,codec:i,onRtpSender:s}){this.assertNotClosed(),this.assertSendDirection(),Np.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach(((e,t)=>{e.rid=`r${t}`}));const o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});s&&s(o.sender);const a=await this._pc.createOffer();let c=Pp.parse(a.sdp);c.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const d=xp.getLocalRtpCapabilities(c),u=this._getSendExtendedRtpCapabilities(d),l=kp.getSendingRtpParameters(e.kind,u);l.codecs=kp.reduceCodecs(l.codecs,i);const p=kp.getSendingRemoteRtpParameters(e.kind,u);p.codecs=kp.reduceCodecs(p.codecs,i),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:c});const h=(0,Dp.parse)((r??[{}])[0].scalabilityMode);Np.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const f=o.mid;l.mid=f,c=Pp.parse(this._pc.localDescription.sdp);const m=c.media[c.media.length-1];if(l.rtcp.cname=Ap.getCname({offerMediaObject:m}),l.msid=`${t??this._sendStream.id} ${e.id}`,r)if(1===r.length){const e=Op.getRtpEncodings({offerMediaObject:m,codecs:l.codecs});Object.assign(e[0],r[0]),l.encodings=e}else l.encodings=r;else l.encodings=Op.getRtpEncodings({offerMediaObject:m,codecs:l.codecs});if(l.encodings.length>1&&("video/vp8"===l.codecs[0].mimeType.toLowerCase()||"video/h264"===l.codecs[0].mimeType.toLowerCase()))for(const e of l.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${h.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:m,offerRtpParameters:l,answerRtpParameters:p,codecOptions:n});const g={type:"answer",sdp:this._remoteSdp.getSdp()};return Np.debug("send() | calling pc.setRemoteDescription() [answer:%o]",g),await this._pc.setRemoteDescription(g),this._mapMidTransceiver.set(f,o),{localId:f,rtpParameters:l,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),Np.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();Np.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Np.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Np.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();Np.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Np.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Np.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();Np.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Np.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Np.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Np.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(),Np.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();Np.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Np.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Np.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();Np.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Np.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};Np.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Lp.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Pp.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),Np.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()};Np.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;Np.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=Mp.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Np.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=Pp.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));Ap.applyCodecParameters({offerRtpParameters:n,answerMediaObject:a}),i={type:"answer",sdp:Pp.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),Np.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){Np.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()};Np.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Np.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){Np.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()};Np.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Np.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){Np.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()};Np.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Np.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};Np.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()};Np.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Pp.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}Np.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=Pp.parse(this._pc.localDescription.sdp));const r=Ap.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 Rp.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')}}Cp.Firefox120=xp;var Fp={};Object.defineProperty(Fp,"__esModule",{value:!0}),Fp.Safari12=void 0;const jp=Sl,Up=Id,Vp=Xd,Bp=Jd,Wp=xl,Hp=jl,qp=Jl,zp=Kl,Gp=Zl,Yp=new Td.Logger("Safari12"),$p={OS:1024,MIS:1024};class Jp extends Up.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 Jp(e),getNativeRtpCapabilities:async({direction:e})=>{Yp.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});const r=await t.createOffer();try{t.close()}catch(e){}t=void 0;const n=jp.parse(r.sdp);return Jp.getLocalRtpCapabilities(n)}catch(e){try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(Yp.debug("getNativeSctpCapabilities()"),{numStreams:$p})}}static getLocalRtpCapabilities(e,t=[]){const r=qp.extractRtpCapabilities({sdpObject:e});Vp.validateAndNormalizeRtpCapabilities(r),Gp.addNackSupportForOpus(r);for(const e of t)Gp.addHeaderExtensionSupport(r,e);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Yp.debug("constructor()"),this._direction=e,this._remoteSdp=new Hp.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):(Yp.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"Safari12"}close(){if(Yp.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(),Yp.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Yp.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Yp.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Yp.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Yp.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Yp.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s,onRtpSender:o}){this.assertNotClosed(),this.assertSendDirection(),Yp.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});o&&o(c.sender);let d=await this._pc.createOffer(),u=jp.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const l=[];l.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});const p=Jp.getLocalRtpCapabilities(u,l),h=this._getSendExtendedRtpCapabilities(p),f=Vp.getSendingRtpParameters(e.kind,h);f.codecs=Vp.reduceCodecs(f.codecs,s);const m=Vp.getSendingRemoteRtpParameters(e.kind,h);let g;m.codecs=Vp.reduceCodecs(m.codecs,s),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});const v=(0,Wp.parse)((r??[{}])[0].scalabilityMode);r&&r.length>1&&(Yp.debug("send() | enabling legacy simulcast"),u=jp.parse(d.sdp),g=u.media[a.idx],zp.addLegacySimulcast({offerMediaObject:g,numStreams:r.length}),d={type:"offer",sdp:jp.write(u)}),i?.absCaptureTime&&(g=u.media[a.idx],qp.addHeaderExtension({offerMediaObject:g,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"===e.uri)).id}),d={type:"offer",sdp:jp.write(u)}),Yp.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const y=c.mid;if(f.mid=y,u=jp.parse(this._pc.localDescription.sdp),g=u.media[a.idx],f.rtcp.cname=qp.getCname({offerMediaObject:g}),f.msid=`${t??this._sendStream.id} ${e.id}`,f.encodings=zp.getRtpEncodings({offerMediaObject:g,codecs:f.codecs}),r)for(let e=0;e<f.encodings.length;++e)r[e]&&Object.assign(f.encodings[e],r[e]);if(f.encodings.length>1&&("video/vp8"===f.codecs[0].mimeType.toLowerCase()||"video/h264"===f.codecs[0].mimeType.toLowerCase()))for(const e of f.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${v.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:g,reuseMid:a.reuseMid,offerRtpParameters:f,answerRtpParameters:m,codecOptions:n});const _={type:"answer",sdp:this._remoteSdp.getSdp()};return Yp.debug("send() | calling pc.setRemoteDescription() [answer:%o]",_),await this._pc.setRemoteDescription(_),this._mapMidTransceiver.set(y,c),{localId:y,rtpParameters:f,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Yp.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();Yp.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Yp.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Yp.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();Yp.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Yp.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Yp.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();Yp.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Yp.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Yp.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Yp.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(),Yp.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();Yp.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Yp.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Yp.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();Yp.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Yp.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};Yp.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%$p.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=jp.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Yp.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()};Yp.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;Yp.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=Gp.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Yp.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=jp.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));qp.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:jp.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Yp.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){Yp.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()};Yp.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Yp.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){Yp.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()};Yp.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Yp.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){Yp.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()};Yp.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Yp.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};Yp.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()};Yp.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=jp.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Yp.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=jp.parse(this._pc.localDescription.sdp));const r=qp.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 Bp.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')}}Fp.Safari12=Jp;var Qp={};Object.defineProperty(Qp,"__esModule",{value:!0}),Qp.ReactNative106=void 0;const Kp=Sl,Zp=Id,Xp=Xd,eh=Jd,th=xl,rh=jl,nh=Jl,ih=Kl,sh=Zl,oh=new Td.Logger("ReactNative106"),ah={OS:1024,MIS:1024};class ch extends Zp.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 ch(e),getNativeRtpCapabilities:async({direction:e})=>{oh.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});const r=await t.createOffer();try{t.close()}catch(e){}t=void 0;const n=Kp.parse(r.sdp);return ch.getLocalRtpCapabilities(n)}catch(e){try{t?.close()}catch(e){}throw t=void 0,e}},getNativeSctpCapabilities:async()=>(oh.debug("getNativeSctpCapabilities()"),{numStreams:ah})}}static getLocalRtpCapabilities(e,t=[]){const r=nh.extractRtpCapabilities({sdpObject:e});Xp.validateAndNormalizeRtpCapabilities(r),sh.addNackSupportForOpus(r);for(const e of t)sh.addHeaderExtensionSupport(r,e);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),oh.debug("constructor()"),this._direction=e,this._remoteSdp=new rh.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):(oh.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return"ReactNative106"}close(){if(oh.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(),oh.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),oh.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});oh.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};oh.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};oh.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();oh.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:n,headerExtensionOptions:i,codec:s,onRtpSender:o}){this.assertNotClosed(),this.assertSendDirection(),oh.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach(((e,t)=>{e.rid=`r${t}`}));const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});o&&o(c.sender);let d=await this._pc.createOffer(),u=Kp.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const l=[];l.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});const p=ch.getLocalRtpCapabilities(u,l),h=this._getSendExtendedRtpCapabilities(p),f=Xp.getSendingRtpParameters(e.kind,h);f.codecs=Xp.reduceCodecs(f.codecs,s);const m=Xp.getSendingRemoteRtpParameters(e.kind,h);m.codecs=Xp.reduceCodecs(m.codecs,s),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let g=!1;const v=(0,th.parse)((r??[{}])[0].scalabilityMode);let y;1===r?.length&&v.spatialLayers>1&&"video/vp9"===f.codecs[0].mimeType.toLowerCase()&&(oh.debug("send() | enabling legacy simulcast for VP9 SVC"),g=!0,u=Kp.parse(d.sdp),y=u.media[a.idx],ih.addLegacySimulcast({offerMediaObject:y,numStreams:v.spatialLayers}),d={type:"offer",sdp:Kp.write(u)}),i?.absCaptureTime&&(y=u.media[a.idx],nh.addHeaderExtension({offerMediaObject:y,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"===e.uri)).id}),d={type:"offer",sdp:Kp.write(u)}),oh.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);let _=c.mid??void 0;if(_||oh.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),f.mid=_,u=Kp.parse(this._pc.localDescription.sdp),y=u.media[a.idx],f.rtcp.cname=nh.getCname({offerMediaObject:y}),f.msid=`${t??this._sendStream.id} ${e.id}`,r)if(1===r.length){let e=ih.getRtpEncodings({offerMediaObject:y,codecs:f.codecs});Object.assign(e[0],r[0]),g&&(e=[e[0]]),f.encodings=e}else f.encodings=r;else f.encodings=ih.getRtpEncodings({offerMediaObject:y,codecs:f.codecs});if(f.encodings.length>1&&("video/vp8"===f.codecs[0].mimeType.toLowerCase()||"video/h264"===f.codecs[0].mimeType.toLowerCase()))for(const e of f.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${v.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:y,reuseMid:a.reuseMid,offerRtpParameters:f,answerRtpParameters:m,codecOptions:n});const b={type:"answer",sdp:this._remoteSdp.getSdp()};return oh.debug("send() | calling pc.setRemoteDescription() [answer:%o]",b),await this._pc.setRemoteDescription(b),_||(_=c.mid,f.mid=_),this._mapMidTransceiver.set(_,c),{localId:_,rtpParameters:f,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;oh.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();oh.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};oh.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),oh.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();oh.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};oh.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),oh.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();oh.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};oh.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?oh.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):oh.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(),oh.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();oh.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};oh.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),oh.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();oh.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};oh.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};oh.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%ah.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Kp.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),oh.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()};oh.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;oh.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o);const{msidStreamId:a}=sh.getMsidStreamIdAndTrackId(i.msid);this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??a??i.rtcp?.cname??"-",trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};oh.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=Kp.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));nh.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Kp.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),oh.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){oh.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()};oh.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();oh.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){oh.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()};oh.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();oh.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){oh.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()};oh.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();oh.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};oh.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()};oh.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Kp.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}oh.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=Kp.parse(this._pc.localDescription.sdp));const r=nh.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 eh.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')}}Qp.ReactNative106=ch,Object.defineProperty(Pd,"__esModule",{value:!0}),Pd.Device=void 0,Pd.detectDevice=bh,Pd.detectDeviceAsync=Eh;const dh=Id,uh=Jd,lh=Zd,ph=Xd,hh=Nu,fh=wl,mh=lp,gh=Cp,vh=Fp,yh=Qp,_h=new Td.Logger("Device");function bh(e,t){return _h.debug("detectDevice()"),e||"object"!=typeof navigator||(e=navigator.userAgent),t||"object"!=typeof navigator||(t=navigator.userAgentData),Sh(e,t)}async function Eh(e,t){return _h.debug("detectDeviceAsync()"),e||"object"!=typeof navigator||(e=navigator.userAgent),t||"object"!=typeof navigator||(t=navigator.userAgentData),Sh(e,t)}class wh{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new dh.EnhancedEventEmitter;static async factory({handlerName:e,handlerFactory:t}={}){if(_h.debug("factory()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!e&&!t&&!(e=await Eh()))throw new uh.UnsupportedError("device not supported");return new wh({handlerName:e,handlerFactory:t})}constructor({handlerName:e,handlerFactory:t}={}){if(_h.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)_h.debug("constructor() | handler given: %s",e);else{if(!(e=bh()))throw new uh.UnsupportedError("device not supported");_h.debug("constructor() | detected handler: %s",e)}switch(e){case"Chrome111":this._handlerFactory=fh.Chrome111.createFactory();break;case"Chrome74":this._handlerFactory=mh.Chrome74.createFactory();break;case"Firefox120":this._handlerFactory=gh.Firefox120.createFactory();break;case"Safari12":this._handlerFactory=vh.Safari12.createFactory();break;case"ReactNative106":this._handlerFactory=yh.ReactNative106.createFactory();break;default:throw new TypeError(`unknown handlerName "${e}"`)}}this._handlerName=this._handlerFactory.name}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){return this.recvRtpCapabilities}get recvRtpCapabilities(){if(!this._loaded)throw new uh.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sendRtpCapabilities(){if(!this._loaded)throw new uh.InvalidStateError("not loaded");return this._sendRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new uh.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e,preferLocalCodecsOrder:t=!1}){if(_h.debug("load() [routerRtpCapabilities:%o]",e),this._loaded)throw new uh.InvalidStateError("already loaded");const r=lh.clone(e);ph.validateAndNormalizeRtpCapabilities(r);const{getNativeRtpCapabilities:n,getNativeSctpCapabilities:i}=this._handlerFactory,s=lh.clone(await n({direction:"recvonly"}));_h.debug("load() | got native receiving RTP capabilities:%o",s),ph.validateAndNormalizeRtpCapabilities(s);const o=lh.clone(await n({direction:"sendonly"}));_h.debug("load() | got native sending RTP capabilities:%o",o),ph.validateAndNormalizeRtpCapabilities(o),this._getSendExtendedRtpCapabilities=e=>lh.clone(ph.getExtendedRtpCapabilities(e,r,t));const a=ph.getExtendedRtpCapabilities(s,r,!1);this._recvRtpCapabilities=ph.getRecvRtpCapabilities(a),_h.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),ph.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities);const c=ph.getExtendedRtpCapabilities(o,r,t);this._sendRtpCapabilities=ph.getSendRtpCapabilities(c),_h.debug("load() | got sending RTP capabilities:%o",this._sendRtpCapabilities),ph.validateAndNormalizeRtpCapabilities(this._sendRtpCapabilities),this._canProduceByKind.audio=ph.canSend("audio",this._sendRtpCapabilities),this._canProduceByKind.video=ph.canSend("video",this._sendRtpCapabilities),this._sctpCapabilities=await i(),ph.validateSctpCapabilities(this._sctpCapabilities),_h.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),_h.debug("load() succeeded"),this._loaded=!0}canProduce(e){if(!this._loaded)throw new uh.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 _h.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 _h.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 uh.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 hh.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 Sh(e,t){_h.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',e,t);const r=function(e,t){if(_h.debug("getChromiumMajorVersion()"),Ch(e,t))return void _h.debug("getChromiumMajorVersion() | this is iOS => undefined");if(Ph())return void _h.debug("getChromiumMajorVersion() | this is React-Native => undefined");if(t){const e=(t.brands??[]).find((e=>"Chromium"===e.brand));if(e){const t=Number(e.version);return _h.debug(`getChromiumMajorVersion() | Chromium major version based on NavigatorUAData => ${t}`),t}}const r=e?.match(/\b(?:Chrome|Chromium)\/(\w+)/i);if(r?.[1]){const e=Number(r[1]);return _h.debug(`getChromiumMajorVersion() | Chromium major version based on User-Agent => ${e}`),e}return void _h.debug("getChromiumMajorVersion() | this is not Chromium => undefined")}(e,t);if(r)return r>=111?(_h.debug("detectDeviceImpl() | using Chrome111 handler"),"Chrome111"):r>=74?(_h.debug("detectDeviceImpl() | using Chrome74 handler"),"Chrome74"):void _h.warn("detectDeviceImpl() | unsupported Chromium based browser/version");const n=function(e){if(_h.debug("getFirefoxMajorVersion()"),Ch(e))return void _h.debug("getFirefoxMajorVersion() | this is iOS => undefined");if(Ph())return void _h.debug("getFirefoxMajorVersion() | this is React-Native => undefined");const t=e?.match(/\bFirefox\/(\w+)/i);if(t?.[1]){const e=Number(t[1]);return _h.debug(`getFirefoxMajorVersion() | Firefox major version based on User-Agent => ${e}`),e}return void _h.debug("getFirefoxMajorVersion() | this is not Firefox => undefined")}(e);if(n)return n>=120?(_h.debug("detectDeviceImpl() | using Firefox120 handler"),"Firefox120"):void _h.warn("detectDeviceImpl() | unsupported Firefox browser/version");const i=function(e){if(_h.debug("getMacOSWebKitMajorVersion()"),Ch(e))return void _h.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");if(Ph())return void _h.debug("getMacOSWebKitMajorVersion() | this is React-Native => undefined");if(!e||!/\bSafari\b/i.test(e)||/\bChrome\b/i.test(e)||/\bChromium\b/i.test(e)||/\bFirefox\b/i.test(e))return void _h.debug("getMacOSWebKitMajorVersion() | this is not Safari => undefined");const t=e.match(/AppleWebKit\/(\w+)/i);if(t?.[1]){const e=Number(t[1]);return _h.debug(`getMacOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${e}`),e}return void _h.debug("getMacOSWebKitMajorVersion() | this is not WebKit => undefined")}(e);if(i)return i>=605?(_h.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12"):void _h.warn("detectDeviceImpl() | unsupported desktop Safari browser/version");const s=function(e){if(_h.debug("getIOSWebKitMajorVersion()"),!Ch(e))return void _h.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");if(Ph())return void _h.debug("getIOSWebKitMajorVersion() | this is React-Native => undefined");const t=e?.match(/AppleWebKit\/(\w+)/i);if(t?.[1]){const e=Number(t[1]);return _h.debug(`getIOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${e}`),e}return void _h.debug("getIOSWebKitMajorVersion() | this is not WebKit => undefined")}(e);return s?s>=605?(_h.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12"):void _h.warn("detectDeviceImpl() | unsupported iOS Safari based browser/version"):Ph()?"undefined"!=typeof RTCPeerConnection&&"undefined"!=typeof RTCRtpTransceiver?(_h.debug("detectDeviceImpl() | using ReactNative106 handler"),"ReactNative106"):void _h.warn("detectDeviceImpl() | unsupported react-native-webrtc version without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?"):void _h.warn('detectDeviceImpl() | device not supported [userAgent:"%s", userAgentData:%o]',e,t)}function Ch(e,t){return _h.debug("isIOS()"),"iOS"===t?.platform?(_h.debug("isIOS() | this is iOS based on NavigatorUAData.platform => true"),!0):t?.platform?(_h.debug("isIOS() | this is not iOS based on NavigatorUAData.platform => false"),!1):e&&/iPad|iPhone|iPod/.test(e)?(_h.debug("isIOS() | this is iOS based on User-Agent => true"),!0):"object"==typeof navigator&&"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1?(_h.debug("isIOS() | this is iPadOS 13+ based on User-Agent => true"),!0):(_h.debug("isIOS() | this is not iOS => false"),!1)}function Ph(){return _h.debug("isReactNative()"),"object"==typeof navigator&&"ReactNative"===navigator.product?(_h.debug("isReactNative() | this is React-Native based on navigator.product"),!0):(_h.debug("isReactNative() | this is not React-Native => false"),!1)}Pd.Device=wh;for(var Th,Rh={},kh={},Dh={},Ih=256,Ah=[];Ih--;)Ah[Ih]=(Ih+256).toString(16).substring(1);Dh.v4=function(){var e,t=0,r="";if(!Th||Ih+16>256){for(Th=Array(t=256);t--;)Th[t]=256*Math.random()|0;t=Ih=0}for(;t<16;t++)e=Th[Ih+t],r+=6==t?Ah[15&e|64]:8==t?Ah[63&e|128]:Ah[e],1&t&&t>1&&t<11&&(r+="-");return Ih++,r};var Oh={};Object.defineProperty(Oh,"__esModule",{value:!0}),Oh.FakeEventTarget=void 0;Oh.FakeEventTarget=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:"function"==typeof t?t:t.handleEvent,once:"object"==typeof r&&!0===r.once}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter((e=>e.callback!==("function"==typeof t?t:t.handleEvent))))}dispatchEvent(e){if(!e||"string"!=typeof e.type)throw new Error("invalid event object");const t=this.listeners[e.type];if(!t)return!0;for(const r of[...t]){try{r.callback.call(this,e)}catch(e){setTimeout((()=>{throw e}),0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}};var Mh={};Object.defineProperty(Mh,"__esModule",{value:!0}),Mh.FakeEvent=void 0;Mh.FakeEvent=class{NONE=0;CAPTURING_PHASE=1;AT_TARGET=2;BUBBLING_PHASE=3;type;bubbles;cancelable;defaultPrevented=!1;composed=!1;currentTarget=null;eventPhase=p.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 Nh={};Object.defineProperty(Nh,"__esModule",{value:!0}),Nh.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(kh,"__esModule",{value:!0}),kh.FakeMediaStreamTrack=void 0;const Lh=Dh,xh=Oh,Fh=Mh,jh=Nh;class Uh extends xh.FakeEventTarget{#E;#w;#S;#C;#P;#T;#R;#k;#D;#I;#A;#O=null;#M=null;#N=null;#L=null;#x=null;constructor({kind:e,id:t,label:r,contentHint:n,enabled:i,muted:s,readyState:o,capabilities:a,constraints:c,settings:d,data:u}){super(),this.#E=t??(0,Lh.v4)(),this.#w=e,this.#S=r??"",this.#R=n??"",this.#P=i??!0,this.#T=s??!1,this.#C=o??"live",this.#k=a??{},this.#D=c??{},this.#I=d??{},this.#A=u??{}}get id(){return this.#E}get kind(){return this.#w}get label(){return this.#S}get contentHint(){return this.#R}set contentHint(e){this.#R=e}get enabled(){return this.#P}set enabled(e){const t=this.#P!==e;this.#P=e,t&&this.dispatchEvent(new Fh.FakeEvent("enabledchange"))}get muted(){return this.#T}get readyState(){return this.#C}get data(){return this.#A}set data(e){this.#A=e}get onmute(){return this.#O}set onmute(e){this.#O&&this.removeEventListener("mute",this.#O),this.#O=e,e&&this.addEventListener("mute",e)}get onunmute(){return this.#M}set onunmute(e){this.#M&&this.removeEventListener("unmute",this.#M),this.#M=e,e&&this.addEventListener("unmute",e)}get onended(){return this.#N}set onended(e){this.#N&&this.removeEventListener("ended",this.#N),this.#N=e,e&&this.addEventListener("ended",e)}get onenabledchange(){return this.#L}set onenabledchange(e){this.#L&&this.removeEventListener("enabledchange",this.#L),this.#L=e,e&&this.addEventListener("enabledchange",e)}get onstopped(){return this.#x}set onstopped(e){this.#x&&this.removeEventListener("stopped",this.#x),this.#x=e,e&&this.addEventListener("stopped",e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}stop(){"ended"!==this.#C&&(this.#C="ended",this.dispatchEvent(new Fh.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new Uh({id:e??(0,Lh.v4)(),kind:this.#w,label:this.#S,contentHint:this.#R,enabled:this.#P,muted:this.#T,readyState:this.#C,capabilities:(0,jh.clone)(this.#k),constraints:(0,jh.clone)(this.#D),settings:(0,jh.clone)(this.#I),data:t??(0,jh.clone)(this.#A)})}getCapabilities(){return this.#k}getConstraints(){return this.#D}async applyConstraints(e={}){return this.#D=e,Promise.resolve()}getSettings(){return this.#I}remoteStop(){"ended"!==this.#C&&(this.#C="ended",this.dispatchEvent(new Fh.FakeEvent("stopped")),this.dispatchEvent(new Fh.FakeEvent("ended")))}remoteMute(){this.#T||(this.#T=!0,this.dispatchEvent(new Fh.FakeEvent("mute")))}remoteUnmute(){this.#T&&(this.#T=!1,this.dispatchEvent(new Fh.FakeEvent("unmute")))}}kh.FakeMediaStreamTrack=Uh;var Vh={};Object.defineProperty(Vh,"__esModule",{value:!0}),Vh.FakeEventTarget=void 0;Vh.FakeEventTarget=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:"function"==typeof t?t:t.handleEvent,once:"object"==typeof r&&!0===r.once}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter((e=>e.callback!==("function"==typeof t?t:t.handleEvent))))}dispatchEvent(e){if(!e||"string"!=typeof e.type)throw new Error("invalid event object");const t=this.listeners[e.type];if(!t)return!0;for(const r of[...t]){try{r.callback.call(this,e)}catch(e){setTimeout((()=>{throw e}),0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}},Object.defineProperty(Rh,"__esModule",{value:!0}),Rh.FakeHandler=void 0;const Bh=kh,Wh=Id,Hh=Zd,qh=Xd,zh=Jd,Gh=Vh,Yh=new Td.Logger("FakeHandler");class $h extends Wh.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${Hh.generateRandomNumber()}`;_defaultSendStreamId=`${Hh.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:"FakeHandler",factory:t=>new $h(t,e),getNativeRtpCapabilities:async({direction:t})=>(Yh.debug("getNativeRtpCapabilities() [direction:%o]",t),$h.getLocalRtpCapabilities(e)),getNativeSctpCapabilities:async()=>(Yh.debug("getNativeSctpCapabilities()"),e.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(e){const t=e.generateNativeRtpCapabilities();return qh.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),Yh.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return"FakeHandler"}close(){Yh.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(),Yh.debug("updateIceServers()")}async restartIce(e){this.assertNotClosed(),Yh.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:e,streamId:t,encodings:r,codecOptions:n,codec:i}){this.assertNotClosed(),Yh.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});const s=$h.getLocalRtpCapabilities(this._fakeParameters),o=this._getSendExtendedRtpCapabilities(s),a=qh.getSendingRtpParameters(e.kind,o);a.codecs=qh.reduceCodecs(a.codecs,i);const c=a.codecs.some((e=>/.+\/rtx$/i.test(e.mimeType)));a.mid=`mid-${Hh.generateRandomNumber()}`,a.msid=`${t??"-"} ${e.id}`,r||(r=[{}]);for(const e of r)e.ssrc=Hh.generateRandomNumber(),c&&(e.rtx={ssrc:Hh.generateRandomNumber()});a.encodings=r,a.rtcp={cname:this._cname,reducedSize:!0,mux:!0},a.msid=`${t??this._defaultSendStreamId} ${e.id}`;const d=this._nextLocalId++;return this._tracks.set(d,e),{localId:String(d),rtpParameters:a}}async stopSending(e){if(Yh.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?Yh.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Yh.debug("replaceTrack() [localId:%s, no track]",e),this._tracks.delete(Number(e)),this._tracks.set(Number(e),t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),Yh.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),Yh.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"}),Yh.debug("sendDataChannel()");return{dataChannel:new Jh({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"}),Yh.debug("receive() [trackId:%s, kind:%s]",e,n);const i=this._nextLocalId++,s=new Bh.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)Yh.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"}),Yh.debug("receiveDataChannel()");return{dataChannel:new Jh({id:e.streamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:t,protocol:r})}}async setupTransport({localDtlsRole:e,localSdpObject:t}){const r=Hh.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 zh.InvalidStateError("method called in a closed handler")}}Rh.FakeHandler=$h;class Jh extends Gh.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(),Yh.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 zh.InvalidStateError("not open")}}var Qh={};Object.defineProperty(Qh,"__esModule",{value:!0}),Qh.generateRouterRtpCapabilities=function(){return Kh.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"}]})},Qh.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}]}},Qh.generateNativeSctpCapabilities=function(){return Kh.deepFreeze({numStreams:{OS:2048,MIS:2048}})},Qh.generateLocalDtlsParameters=function(){return Kh.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"})},Qh.generateTransportRemoteParameters=function(){return{id:Zh(),iceParameters:Kh.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:Kh.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:Kh.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:Kh.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}},Qh.generateProducerRemoteParameters=function(){return Kh.deepFreeze({id:Zh()})},Qh.generateConsumerRemoteParameters=function({id:e,codecMimeType:t}={}){switch(t){case"audio/opus":return{id:e??Zh(),producerId:Zh(),kind:"audio",rtpParameters:Kh.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??Zh(),producerId:Zh(),kind:"audio",rtpParameters:Kh.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??Zh(),producerId:Zh(),kind:"video",rtpParameters:Kh.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??Zh(),producerId:Zh(),kind:"video",rtpParameters:Kh.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}'`)}},Qh.generateDataProducerRemoteParameters=function(){return Kh.deepFreeze({id:Zh()})},Qh.generateDataConsumerRemoteParameters=function({id:e}={}){return{id:e??Zh(),dataProducerId:Zh(),sctpStreamParameters:Kh.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}};const Kh=Zd;function Zh(){return String(Kh.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=gd.exports;e.debug=t.default,e.types=Cd,e.version="3.18.7";var r=Pd;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=xl;Object.defineProperty(e,"parseScalabilityMode",{enumerable:!0,get:function(){return n.parse}}),e.ortc=Xd,e.enhancedEvents=Id;var i=Rh;Object.defineProperty(e,"FakeHandler",{enumerable:!0,get:function(){return i.FakeHandler}}),e.testFakeParameters=Qh}(md);const Xh={width:1280,height:720},ef=0,tf=2,rf=0;function nf(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 sf(e,t){e.onreadystatechange=function(){"complete"!=this.readyState&&"loaded"!=this.readyState||(this.onreadystatechange=null,t(null,e))}}const of=new An,af=e=>c(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?nf:sf)(i,r),i.onload||nf(i,r),n.appendChild(i)}(e,((e,n)=>{e?r(e):t(n)}))}))})),cf=(e,...t)=>c(void 0,[e,...t],void 0,(function*(e,t=3,r=500){let n=0;for(;n<t;)try{return void(yield af(e))}catch(e){if(n+=1,!(n<t))throw e;yield of.sleepMs(r)}}));var df;let uf=class{constructor(){df.set(this,new Map)}add(e,t,r){const n=this.getKey(e,t);if(d(this,df,"f").has(n))throw new Error("Attempt to rewrite cached track processor");d(this,df,"f").set(n,r)}get(e,t){return d(this,df,"f").get(this.getKey(e,t))}has(e,t){return d(this,df,"f").has(this.getKey(e,t))}getKey(e,t){return`${e}:${t}`}reset(){for(const e of d(this,df,"f").values())try{e.stopProcessing(),e.release()}catch(e){}d(this,df,"f").clear()}};var lf,pf;df=new WeakMap,uf=s([ct()],uf);let hf=class{constructor(e,t,r,n){this.config=e,this.processorsCache=t,this.audioTrackProcessorFactory=r,lf.set(this,new Map),pf.set(this,void 0),u(this,pf,n("IntegrationsService"),"f")}init(){const e=this.config.get("denoiser");if("asdk"===e){d(this,pf,"f").info("Start integration of ASDK",{denoiser:e});const t={integrated:!1,initPromise:this.integrateASDK()};d(this,lf,"f").set("asdk",t)}else{d(this,pf,"f").info("Start integration of RNNoise",{denoiser:e});const t={integrated:!1,initPromise:this.integrateRNNoise()};d(this,lf,"f").set("rnnoise",t)}}integrateASDK(){return c(this,void 0,void 0,(function*(){const e=this.config.get("asdk"),r=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 t.URL(n,r).href}yield(n=o,i=s,c(void 0,void 0,void 0,(function*(){try{yield cf(n)}catch(e){if(!i)throw e;yield cf(i)}})))}var n,i;if(!window.atsvb)throw d(this,pf,"f").info("Audio Effects SDK is not loaded, skipping initialization",{case:"initAudioSDK"}),new Error("windows.atsvb is still missing");const s=this.audioTrackProcessorFactory({trackLabel:Ln.Microphone});yield s.init(),this.processorsCache.add("asdk",Ln.Microphone,s);const o=d(this,lf,"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=d(this,lf,"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=d(this,lf,"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 c(this,void 0,void 0,(function*(){const e=yield function(e){return c(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:Ln.Microphone,noiseSuppressor:e});this.processorsCache.add("rnnoise",Ln.Microphone,t);const r=d(this,lf,"f").get("rnnoise");if(!r)throw Error("IntegrationContext is missing for RNNoise");r.integrated=!0}))}reset(){d(this,lf,"f").clear()}};var ff,mf,gf,vf,yf,_f,bf,Ef,wf;lf=new WeakMap,pf=new WeakMap,hf=s([ct(),o(0,ut(Nn.Config)),o(1,ut(Nn.ProcessorsCache)),o(2,ut(Nn.AudioTrackProcessorFactory)),o(3,ut(Nn.LoggerFactory)),a("design:paramtypes",[Et,uf,Function,Function])],hf),function(e){e.INFO="info",e.WARNING="warning",e.ERROR="error"}(Ef||(Ef={})),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"}(wf||(wf={}));class Sf{constructor(e){ff.set(this,void 0),mf.set(this,void 0),gf.set(this,{lowLighter:!1,colorCorrector:!1,faceDetector:!1,segmentation:!1}),vf.set(this,null),yf.set(this,void 0),_f.set(this,!1),bf.set(this,void 0);const{loggerFactory:t}=e;if(u(this,mf,t("EffectsSDKTrackProcessor"),"f"),u(this,bf,e.onModelsLoaded,"f"),!e.customerId)throw new Error("Customer ID must be provided");u(this,ff,new window.tsvb(e.customerId),"f"),d(this,ff,"f").onError(this.tsvbErrorHandler.bind(this)),d(this,ff,"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`}};d(this,ff,"f").config(o)}init(){return c(this,void 0,void 0,(function*(){yield d(this,ff,"f").preload(),yield d(this,ff,"f").cache(),u(this,_f,!0,"f")}))}awaitReady(){return c(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:n}=e,s=i(e,["emitter","type"]),o=null!=r?r:"N/A emitter";n===Ef.ERROR&&d(this,mf,"f").error(o,Object.assign({error:Pt(e)},s)),n===Ef.WARNING&&d(this,mf,"f").warn(o,Object.assign({},s)),n===Ef.INFO&&d(this,mf,"f").info(o,Object.assign({},s)),r===wf.ML_INFERENCE&&(s.message.toLocaleLowerCase().includes("init lowlighter")&&(d(this,gf,"f").lowLighter=!0),s.message.toLocaleLowerCase().includes("init colorcorrector")&&(d(this,gf,"f").colorCorrector=!0),s.message.toLocaleLowerCase().includes("init facedetector")&&(d(this,gf,"f").faceDetector=!0),s.message.toLocaleLowerCase().includes("init segmentation")&&(d(this,gf,"f").segmentation=!0),this.isModelsLoaded&&(null===(t=d(this,bf,"f"))||void 0===t||t.call(this)))}get isModelsLoaded(){return d(this,gf,"f").colorCorrector&&d(this,gf,"f").faceDetector&&d(this,gf,"f").lowLighter&&d(this,gf,"f").segmentation}get modelsLoadProgress(){return Object.values(d(this,gf,"f")).filter(Boolean).length/Object.keys(d(this,gf,"f")).length}get isReady(){return d(this,_f,"f")}setOnLoadModels(e){u(this,bf,e,"f"),this.isModelsLoaded&&d(this,bf,"f").call(this)}onReady(){u(this,_f,!0,"f"),d(this,mf,"f").debug("onReady()",{description:"ESDK is ready"}),this.updateEffects(d(this,yf,"f"))}processTrack(e){var t,r,n;if(d(this,vf,"f")===e||"ended"===e.readyState)return null!==(r=null===(t=d(this,ff,"f").getStream())||void 0===t?void 0:t.getVideoTracks()[0])&&void 0!==r?r:e;this.stopProcessing();try{d(this,ff,"f").useStream(new MediaStream([e]));const t=null===(n=d(this,ff,"f").getStream())||void 0===n?void 0:n.getVideoTracks()[0];return t?(u(this,vf,e,"f"),t):e}catch(t){throw d(this,mf,"f").error("processTrack()",{error:t,track:e}),new Error("Can not process this track")}}stopProcessing(){try{d(this,ff,"f").clear(),d(this,ff,"f").stop()}catch(e){d(this,mf,"f").error("stopProcessing()",{error:e})}finally{u(this,vf,null,"f")}}updateEffects(e){var t,r,n,i,s,o,a,c,l,p,h,f,m,g,v,y,_,b,E,w,S,C;if(u(this,yf,e,"f"),!d(this,_f,"f"))return void d(this,mf,"f").warn("updateEffects()",{description:"Esdk not ready"});if(!d(this,yf,"f")||0===Object.keys(d(this,yf,"f")).length)return void d(this,ff,"f").stop();let P=0;if((null===(t=d(this,yf,"f"))||void 0===t?void 0:t.blur)&&!(null===(r=d(this,yf,"f"))||void 0===r?void 0:r.backgroundColor)?(d(this,ff,"f").setBlur(d(this,yf,"f").blur),P+=1):d(this,ff,"f").clearBlur(),void 0!==(null===(n=d(this,yf,"f"))||void 0===n?void 0:n.background)?(d(this,ff,"f").setBackground(d(this,yf,"f").background),P+=1):void 0!==(null===(i=d(this,yf,"f"))||void 0===i?void 0:i.backgroundColor)?(d(this,ff,"f").setBackgroundColor(null===(s=d(this,yf,"f"))||void 0===s?void 0:s.backgroundColor),d(this,ff,"f").setBackground("color"),P+=1):d(this,ff,"f").clearBackground(),(null===(o=d(this,yf,"f"))||void 0===o?void 0:o.beautification)?(d(this,ff,"f").enableBeautification(),d(this,ff,"f").setBeautificationLevel(d(this,yf,"f").beautification),P+=1):d(this,ff,"f").disableBeautification(),(null===(a=d(this,yf,"f"))||void 0===a?void 0:a.lowLightEffect)?(d(this,ff,"f").enableLowLightEffect(),d(this,ff,"f").setLowLightEffectPower(d(this,yf,"f").lowLightEffect),P+=1):d(this,ff,"f").disableLowLightEffect(),(null===(c=d(this,yf,"f"))||void 0===c?void 0:c.colorCorrector)?(d(this,ff,"f").enableColorCorrector(),d(this,ff,"f").setColorCorrectorPower(d(this,yf,"f").colorCorrector),P+=1):d(this,ff,"f").disableColorCorrector(),(null===(l=d(this,yf,"f"))||void 0===l?void 0:l.smartZoom)?(d(this,ff,"f").enableSmartZoom(),d(this,ff,"f").setFaceArea(d(this,yf,"f").smartZoom),P+=1):d(this,ff,"f").disableSmartZoom(),(null===(p=d(this,yf,"f"))||void 0===p?void 0:p.layout)?(d(this,ff,"f").setLayout(d(this,yf,"f").layout),P+=1):d(this,ff,"f").setLayout("center"),(null===(h=d(this,yf,"f"))||void 0===h?void 0:h.colorFilter)&&(null===(f=d(this,yf,"f"))||void 0===f?void 0:f.colorFilter.power)&&(null===(m=d(this,yf,"f"))||void 0===m?void 0:m.colorFilter.url)?(d(this,ff,"f").setColorFilterConfig({lut:d(this,yf,"f").colorFilter.url,power:d(this,yf,"f").colorFilter.power}),d(this,ff,"f").enableColorFilter(),P+=1):d(this,ff,"f").disableColorFilter(),null===(g=d(this,yf,"f"))||void 0===g?void 0:g.lowerThird){const e=d(this,ff,"f").createComponent({component:d(this,yf,"f").lowerThird.type,options:null!==(v=d(this,yf,"f").lowerThird.options)&&void 0!==v?v:{}});null===(b=null===(_=null===(y=d(this,ff,"f").components)||void 0===y?void 0:y.lowerThird)||void 0===_?void 0:_.hideLowerThird)||void 0===b||b.call(_),d(this,ff,"f").addComponent(e,"lowerThird"),d(this,ff,"f").components.lowerThird.showLowerThird(),P+=1}else null===(S=null===(w=null===(E=d(this,ff,"f").components)||void 0===E?void 0:E.lowerThird)||void 0===w?void 0:w.hideLowerThird)||void 0===S||S.call(w);(null===(C=d(this,yf,"f"))||void 0===C?void 0:C.sharpness)?(d(this,ff,"f").setSharpnessEffectConfig(d(this,yf,"f").sharpness),P+=1):d(this,ff,"f").disableSharpnessEffect(),P>2?d(this,ff,"f").enableFrameSkipping():d(this,ff,"f").disableFrameSkipping(),d(this,ff,"f").run()}}ff=new WeakMap,mf=new WeakMap,gf=new WeakMap,vf=new WeakMap,yf=new WeakMap,_f=new WeakMap,bf=new WeakMap;const Cf=e=>"rtx"!==e.mimeType;let Pf,Tf=!1;const Rf=()=>{try{return Tf?null:window.localStorage}catch(e){return console.error("Get local storage error",{error:Pt(e)}),e instanceof Error&&"SecurityError"===e.name&&(Tf=!0),null}};function kf(e){const t=Rf();if(!t)return null;try{const r=t.getItem(e);return r?JSON.parse(r):null}catch(e){return null}}const Df=()=>{if(Pf)return Pf;const e=kf("sdk_clientUniqueId");if(e)return Pf=e,e;const t=In(12);return Pf=t,function(e,t){const r=Rf();if(r)try{r.setItem(e,JSON.stringify(t))}catch(e){console.error(e)}}("sdk_clientUniqueId",t),t},If=()=>{const e=kf("sdk_clientUniqueId");return e||(null!=Pf?Pf:Df())};var Af,Of,Mf;class Nf{constructor({track:e}){Af.set(this,1e4),Of.set(this,0),Mf.set(this,void 0),this.startCleanupTimer(),e.addEventListener("ended",(()=>{clearInterval(d(this,Mf,"f")),u(this,Mf,void 0,"f")}),{once:!0})}touchLastReceivedStatsTimestamp(){u(this,Of,Date.now(),"f")}startCleanupTimer(){u(this,Mf,setInterval((()=>{d(this,Of,"f")>0&&Date.now()-d(this,Of,"f")>=d(this,Af,"f")&&this.cleanupStats()}),d(this,Af,"f")),"f")}}var Lf,xf,Ff,jf,Uf,Vf,Bf,Wf,Hf,qf,zf,Gf,Yf,$f,Jf,Qf,Kf,Zf,Xf,em,tm,rm,nm;Af=new WeakMap,Of=new WeakMap,Mf=new WeakMap;class im extends Nf{constructor({track:e,statsHandler:t,widStatsAdapter:r,scoresCalculator:n,isStaticContent:i}){super({track:e}),Lf.set(this,void 0),xf.set(this,void 0),Ff.set(this,void 0),jf.set(this,void 0),Uf.set(this,void 0),Vf.set(this,void 0),Bf.set(this,void 0),this.handleWebRTCStats(e,t),u(this,Vf,r,"f"),u(this,Uf,n,"f"),u(this,Bf,i,"f")}get videoWebRTCStats(){var e,t,r,n,i;return null!==(r=null===(t=null===(e=d(this,Lf,"f"))||void 0===e?void 0:e.find((e=>e.outbound.active)))||void 0===t?void 0:t.outbound)&&void 0!==r?r:null===(i=null===(n=d(this,Lf,"f"))||void 0===n?void 0:n[0])||void 0===i?void 0:i.outbound}get audioWebRTCStats(){var e;return null===(e=d(this,xf,"f"))||void 0===e?void 0:e.outbound}get scores(){return{Qv:d(this,Ff,"f"),Qa:d(this,jf,"f")}}handleWebRTCStats(e,t){e.addEventListener("ended",(()=>{t.removeOutboundVideoHandler(e.id),t.removeOutboundAudioHandler(e.id)}),{once:!0}),"video"!==e.kind?t.addOutboundAudioHandler(e.id,this.setAudioWebRTCStats.bind(this)):t.addOutboundVideoHandler(e.id,this.setVideoWebRTCStats.bind(this))}setVideoWebRTCStats(e){this.touchLastReceivedStatsTimestamp();const t=e.filter((e=>e.outbound.active)),r=[];t.forEach((e=>{var t;const n=null===(t=d(this,Lf,"f"))||void 0===t?void 0:t.find((t=>t.outbound.ssrc===e.outbound.ssrc)),i=d(this,Vf,"f").adaptOutboundVideoStats({stats:e.outbound,remoteInboundStats:e.remoteInbound,prevStats:n,isStaticContent:d(this,Bf,"f")});r.push(d(this,Uf,"f").calculateVideoMOS(i))})),u(this,Ff,r.length>0?Math.min(...r):void 0,"f"),u(this,Lf,e,"f")}setAudioWebRTCStats(e){var t,r;this.touchLastReceivedStatsTimestamp();const n=d(this,xf,"f")?{outbound:d(this,xf,"f").outbound,remoteInbound:d(this,xf,"f").remoteInbound}:void 0,i=d(this,Vf,"f").adaptOutboundAudioStats({stats:e.outbound,remoteInboundStats:e.remoteInbound,fec:null===(t=kf("qosOutboundFec"))||void 0===t||t,dtx:null===(r=kf("qosOutboundDtx"))||void 0===r||r,prevStats:n});u(this,jf,d(this,Uf,"f").calculateAudioMOS(i),"f"),u(this,xf,e,"f")}cleanupStats(){u(this,Lf,void 0,"f"),u(this,xf,void 0,"f"),u(this,Ff,void 0,"f"),u(this,jf,void 0,"f")}}Lf=new WeakMap,xf=new WeakMap,Ff=new WeakMap,jf=new WeakMap,Uf=new WeakMap,Vf=new WeakMap,Bf=new WeakMap;class sm{constructor(e){Wf.set(this,void 0),Hf.set(this,void 0),this.encoderConfig={},this.label=Ln.Unknown,qf.set(this,void 0),zf.set(this,void 0),Gf.set(this,void 0),Yf.set(this,void 0),$f.set(this,void 0),Jf.set(this,void 0),Qf.set(this,void 0),Kf.set(this,void 0),Zf.set(this,!0),Xf.set(this,void 0),em.set(this,void 0),tm.set(this,void 0),rm.set(this,void 0),nm.set(this,void 0);const{mediaStreamTrack:t,internalEventEmitter:r,constraints:n,mediaStreamTrackManager:i,media:s,myPeer:o,network:a,producerCloseManager:c,mutex:d,loggerFactory:l,loggerNamespace:p,statsHandler:h,widStatsAdapter:f,scoresCalculator:m}=e;u(this,Wf,t,"f"),u(this,$f,r,"f"),u(this,Jf,n,"f"),u(this,Qf,i,"f"),u(this,Kf,new wt,"f"),this.logger=l(p),u(this,Xf,d,"f"),u(this,zf,s,"f"),u(this,qf,o,"f"),u(this,Gf,a,"f"),u(this,Yf,c,"f"),u(this,tm,h,"f"),u(this,rm,f,"f"),u(this,nm,m,"f"),u(this,em,new im({track:t,statsHandler:h,widStatsAdapter:f,scoresCalculator:m}),"f")}get videoWebRTCStats(){return d(this,em,"f").videoWebRTCStats}get audioWebRTCStats(){return d(this,em,"f").audioWebRTCStats}get connectionScores(){return d(this,em,"f").scores}get logCtx(){return{label:this.getLabel(),id:this.id,kind:this.kind,producerId:this.producerId,paused:this.isPaused,published:this.isPublished}}get observer(){return d(this,Kf,"f")}get mediaStreamTrack(){return d(this,Wf,"f")}get originalTrack(){return d(this,Hf,"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 d(this,$f,"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||u(this,Zf,e,"f")}getProducer(){return this.producer}setOriginalTrack(){u(this,Hf,this.mediaStreamTrack,"f")}closeProducer(){return c(this,arguments,void 0,(function*(e=!0){const t=yield d(this,Xf,"f").lock(gn.CloseProducer);if(!this.producer)return void t();const{producerId:r}=this;r&&(yield d(this,Yf,"f").close(this.getLabel(),r)),this.producer.close(),this.producer=void 0,e&&this.stopMediaStreamTrack(),t()}))}setPriority(e){return c(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(){d(this,Hf,"f")&&(d(this,Hf,"f").stop(),u(this,Hf,void 0,"f"))}produce(e){return c(this,arguments,void 0,(function*({encodings:e,codecOptions:t,preferredCodec:r,transformParams:n,keyFrameRequestDelay:i}){var s,o,a,c,u;if(!d(this,qf,"f").canPublish)throw this.logger.error("produce()",{message:"Not enough access to produce"}),new Tt("not_enough_access",new Error("Not enough access to produce"));if(this.producer)throw new Tt("track_already_produced",new Error("Track already produced"));try{yield d(this,Yf,"f").ensureNoPending(this.getLabel()),yield d(this,Gf,"f").ping();const{rtpCapabilities:{codecs:l}}=d(this,zf,"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(d(this,qf,"f").id),label:this.getLabel(),maxSpatialLayer:h,encodings:f,codecOptions:t,preferredCodec:r,codec:p,keyFrameRequestDelay:i},g=yield null===(s=d(this,Gf,"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)!==d(this,Wf,"f").id&&(this.logger.info("Producer initialized with old track, updating",{oldTrackId:null===(u=null===(c=this.producer)||void 0===c?void 0:c.track)||void 0===u?void 0:u.id,newTrackId:d(this,Wf,"f").id}),yield this.replaceTrack(d(this,Wf,"f"))),"video"===this.kind&&(e&&v&&p&&kn(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 d(this,Gf,"f").setProducerMaxSpatialLayer(g.id,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 Tt("track_publish_failed",e)}}))}publish(){return c(this,void 0,void 0,(function*(){yield this.produce({}),this.internalEventEmitter.emit(Vr,this)}))}unpublish(){return c(this,arguments,void 0,(function*(e=!0){try{e&&this.stopMediaStreamTrack(),this.internalEventEmitter.emit(Br,this),this.producer&&(yield this.closeProducer()),this.logger.debug("unpublish()",{track:this.logCtx})}catch(e){this.logger.error("unpublish()",{error:e})}}))}pauseRemoteProducer(e){return c(this,void 0,void 0,(function*(){yield d(this,Gf,"f").pauseRemoteProducer(e)}))}resumeRemoteProducer(e){return c(this,void 0,void 0,(function*(){yield d(this,Gf,"f").resumeRemoteProducer(e)}))}mute(e){return c(this,void 0,void 0,(function*(){const t=yield d(this,Xf,"f").lock(gn.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}),d(this,Zf,"f"))return null==e||e(),d(this,Wf,"f").stop(),this.stopOriginalTrack(),this.internalEventEmitter.emit(qr,this),void(yield this.pauseRemoteProducer(this.producer.id));yield this.pauseRemoteProducer(this.producer.id),this.internalEventEmitter.emit(Wr,this)}catch(e){throw this.logger.error("pause()",{error:e,track:this.logCtx}),yield d(this,zf,"f").deleteTrack(this),this.internalEventEmitter.emit(Gr,this),new Tt("track_pause_failed",e)}finally{t()}}))}resume(){return c(this,void 0,void 0,(function*(){const e=yield d(this,Xf,"f").lock(gn.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}),d(this,Zf,"f"))return yield this.reopenMediaStreamTrack(),yield this.resumeProducer(),void this.internalEventEmitter.emit(zr,this);yield this.resumeProducer(),this.internalEventEmitter.emit(Hr,this)}catch(e){throw this.logger.error("resume()",{error:e,track:this.logCtx}),new Tt("track_resume_failed",e)}finally{e()}}))}getInfo(){return c(this,void 0,void 0,(function*(){const{width:e,height:t,frameRate:r,aspectRatio:n}=d(this,Wf,"f").getSettings();return{trackId:d(this,Wf,"f").id,readyState:d(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 c(this,void 0,void 0,(function*(){var e,t,r,n,i;try{return{producerId:null===(e=this.producer)||void 0===e?void 0:e.id,codec:null===(t=this.producer)||void 0===t?void 0:t.rtpParameters.codecs.find((e=>Cf(e))),dtlsState:null===(i=null===(n=null===(r=this.producer)||void 0===r?void 0:r.rtpSender)||void 0===n?void 0:n.transport)||void 0===i?void 0:i.state,rtcStats:yield this.getOutboundRTPStreamStats()}}catch(e){return void this.logger.debug("getStats()",{error:e})}}))}replaceTrack(e){return c(this,void 0,void 0,(function*(){var t;try{u(this,Wf,e,"f"),this.internalEventEmitter.emit(zr,this),this.observer.safeEmit("track-changed",{track:e}),yield null===(t=this.producer)||void 0===t?void 0:t.replaceTrack({track:e}),u(this,em,new im({track:e,statsHandler:d(this,tm,"f"),widStatsAdapter:d(this,rm,"f"),scoresCalculator:d(this,nm,"f")}),"f")}catch(e){this.logger.warn("replaceTrack()",{error:e})}}))}resumeProducer(){return c(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 c(this,void 0,void 0,(function*(){var e;const t=yield d(this,Qf,"f").createMediaStreamTrack({label:this.label,constraints:d(this,Jf,"f")});u(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&&kn(r.mimeType)?[t[n]||t[0]]:t}getOutboundRTPStreamStats(){return c(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>{const r=(...n)=>c(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((()=>c(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:Pt(e)})}))}))}))}}var om,am,cm,dm;Wf=new WeakMap,Hf=new WeakMap,qf=new WeakMap,zf=new WeakMap,Gf=new WeakMap,Yf=new WeakMap,$f=new WeakMap,Jf=new WeakMap,Qf=new WeakMap,Kf=new WeakMap,Zf=new WeakMap,Xf=new WeakMap,em=new WeakMap,tm=new WeakMap,rm=new WeakMap,nm=new WeakMap;class um extends sm{constructor(e){super(e),this.transformParams={},om.set(this,void 0),am.set(this,void 0),cm.set(this,!1),dm.set(this,(()=>{})),u(this,am,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(d(this,om,"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()===Ln.ScreenVideo?"vp8":"h264")}getEncodings(){var e;return null!==(e=this.getEncoderConfig().encodings)&&void 0!==e?e:Rc}setTransformParams(e){this.transformParams=e}setMaxSpatialLayer(e){return c(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 c(this,void 0,void 0,(function*(){if(!d(this,cm,"f")){u(this,cm,!0,"f");try{if(d(this,om,"f"))return this.logger.debug("enableEffects()",{description:"Track is already processed"}),void u(this,cm,!1,"f");if("ended"===this.mediaStreamTrack.readyState)return void this.logger.warn("Track already ended",{case:"enableEffects"});const{media:e}=d(this,am,"f");if(!e.effectsSDKInitialized)return void this.logger.warn("Effects SDK not initialized",{case:"enableEffects"});const t=Date.now();u(this,om,yield e.createEffectsSDKTrackProcessor(this.getLabel()),"f"),this.setOriginalTrack();const r=d(this,om,"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:Pt(e)}),this.disableEffects().catch((e=>{this.logger.warn("Failed to this.disableEffects() in catch{}",{track:this.logCtx,error:Pt(e)})})),d(this,dm,"f").call(this,e)}finally{u(this,cm,!1,"f")}}}))}disableEffects(){return c(this,arguments,void 0,(function*(e=!0){var t;try{if(!d(this,om,"f"))return void this.logger.debug("disableEffects()",{description:"Track is not processed"});if(null===(t=d(this,om,"f"))||void 0===t||t.stopProcessing(),u(this,om,void 0,"f"),this.logger.info("disableEffects()",{track:this.logCtx}),!e)return;if(!this.originalTrack)return void this.logger.warn("disableEffects()",{description:"Original track missing"});yield this.replaceTrack(this.originalTrack)}catch(e){this.logger.warn("disableEffects()",{track:this.logCtx,error:e})}}))}publish(){return c(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(Vr,this)}))}adjustEncodingPresetToCurrentMaxSpatialLayer(e){return c(this,void 0,void 0,(function*(){var t;if(!kn(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 c(this,void 0,void 0,(function*(){var t;try{!this.isEffectsProcessing&&Object.keys(e).length>0&&(yield this.enableEffects()),null===(t=d(this,om,"f"))||void 0===t||t.updateEffects(e)}catch(e){d(this,dm,"f").call(this,e)}}))}resetEffects(){var e;null===(e=d(this,om,"f"))||void 0===e||e.updateEffects({})}setOnLoadModels(e){var t;null===(t=d(this,om,"f"))||void 0===t||t.setOnLoadModels(e)}get modelsLoadProgress(){var e,t;return null!==(t=null===(e=d(this,om,"f"))||void 0===e?void 0:e.modelsLoadProgress)&&void 0!==t?t:0}pause(){return c(this,void 0,void 0,(function*(){yield this.mute((()=>{var e;d(this,om,"f")&&(null===(e=d(this,om,"f"))||void 0===e||e.stopProcessing(),u(this,om,void 0,"f"))}))}))}setOnEffectError(e){u(this,dm,e,"f")}}var lm,pm;om=new WeakMap,am=new WeakMap,cm=new WeakMap,dm=new WeakMap;let hm=pm=class{constructor(e){lm.set(this,void 0),u(this,lm,e("MediaStreamTrackManager"),"f")}createMediaStreamTrack(e){return c(this,arguments,void 0,(function*({label:e,constraints:t}){if(pm.isDisplayMedia(e)){const[e]=yield this.createDisplayMediaTracks(t);return e}const[r]=yield this.createUserMediaTracks(t);return r}))}static isDisplayMedia(e){return[Ln.ScreenVideo,Ln.ScreenAudio].includes(e)}createUserMediaTracks(e){return c(this,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.getUserMedia(e);return d(this,lm,"f").debug("createUserMediaTracks() stream created",{streamId:t.id}),t.getTracks()}))}createDisplayMediaTracks(e){return c(this,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.getDisplayMedia(e);return d(this,lm,"f").debug("getDisplayMediaTracks() stream created",{streamId:t.id}),t.getTracks()}))}};lm=new WeakMap,hm=pm=s([ct(),o(0,ut(Nn.LoggerFactory)),a("design:paramtypes",[Function])],hm);var fm,mm,gm,vm,ym,_m,bm,Em=hm;let wm=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.signalingApiClient=c,this.isDeviceLoaded=!1,this.tracks=new Map,fm.set(this,void 0),mm.set(this,null),gm.set(this,!1),vm.set(this,new Map),ym.set(this,!1),_m.set(this,!1),bm.set(this,void 0);const d=this.config.get("effectsSDKParams");u(this,bm,this.config.get("denoiser"),"f"),u(this,fm,this.loggerFactory("Media"),"f"),u(this,mm,null!=d?d:null,"f")}get mediasoupDevice(){var e;return null!==(e=this.device)&&void 0!==e||(this.device=this.createDevice()),this.device}get effectsSDKInitialized(){return d(this,gm,"f")}get effectsSDKParams(){return d(this,mm,"f")}getTrack(e){return this.tracks.get(e)}loadDevice(e){return c(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()}`));d(this,fm,"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"})),d(this,fm,"f").debug("createTrack() track created",{trackId:n.id,kind:n.kind}),n}))}createUserMediaTracks(e){return c(this,void 0,void 0,(function*(){const t=yield this.mediaStreamTrackManager.createUserMediaTracks(e);return this.createTracks({constraints:e,mediaStreamTracks:t})}))}createDisplayMediaTracks(e){return c(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 c(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(!1))}catch(e){d(this,fm,"f").warn("deleteTrack()",Object.assign({error:e},t))}try{this.tracks.delete(e.getLabel()),e.stopMediaStreamTrack(),yield e.closeProducer()}catch(e){d(this,fm,"f").error("deleteTrack()",{error:e})}finally{d(this,fm,"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){d(this,fm,"f").warn("clearTracks()",{error:e})}finally{this.tracks.clear()}}unpublishTracks(){return c(this,void 0,void 0,(function*(){try{yield Promise.all(this.publishedTracks().map((e=>c(this,void 0,void 0,(function*(){return yield e.unpublish(!1)})))))}catch(e){d(this,fm,"f").warn("unpublishTracks()",{error:e})}}))}setTrack(e){this.tracks.set(e.getLabel(),e)}initEffectsSDK(){return c(this,void 0,void 0,(function*(){if(d(this,gm,"f"))return!0;if(!d(this,mm,"f"))throw d(this,fm,"f").error("Effects SDK config params not provided",{case:"initEffectsSDK"}),new Tt("effects_sdk_config_missing",new Error("Effects SDK config not provided"));const e=(e,t)=>c(this,void 0,void 0,(function*(){if(!window.tsvb)return d(this,fm,"f").info("Effects SDK not loaded, skipping initialization",{case:"initEffectsSDK"}),void e(!1);d(this,fm,"f").info("Effects SDK initializing",{case:"initEffectsSDK"});try{d(this,vm,"f").set(Ln.Camera,yield this.createEffectsSDKTrackProcessor(Ln.Camera)),d(this,vm,"f").set(Ln.CameraPreview,yield this.createEffectsSDKTrackProcessor(Ln.CameraPreview)),u(this,gm,!0,"f"),d(this,fm,"f").info("Effects SDK initialized",{case:"initEffectsSDK"}),e(!0)}catch(e){d(this,fm,"f").error("Failed to initialize Effects SDK",{error:e,case:"initEffectsSDK"}),t(e)}}));return yield new Promise(((t,r)=>{if(!window.tsvb)return d(this,fm,"f").info("Effects SDK tsvb-web.js is not ready, waiting",{case:"initEffectsSDK"}),void window.addEventListener("load",(()=>c(this,void 0,void 0,(function*(){return yield e(t,r)}))));e(t,r).catch((e=>{d(this,fm,"f").error("Failed to execute init() in initEffectsSDK",{error:Pt(e)})}))}))}))}initDenoiser(e,t){return c(this,void 0,void 0,(function*(){if(!d(this,ym,"f"))try{u(this,ym,!0,"f"),this.clientEventEmitter.emit(Mr,!0);try{yield this.integrationsService.audio.waitForInitialization}catch(e){"asdk"===d(this,bm,"f")&&(u(this,_m,!0,"f"),u(this,bm,"rnnoise","f"),this.config.set("denoiser",d(this,bm,"f")),d(this,fm,"f").debug("Set config to rnnoise denoiser",{case:"Denoiser",error:Pt(e),type:this.config.get("denoiser")}),this.clientEventEmitter.emit(Fr),this.integrationsService.init(),yield this.integrationsService.audio.waitForInitialization)}d(this,fm,"f").debug("Denoiser initialized, activating",{case:"Denoiser",type:this.integrationsService.audio.type,trackLabel:e.getLabel()});const r=e,n=this.processorsCache.get(d(this,bm,"f"),Ln.Microphone);if(!n)return void d(this,fm,"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(Mr,!0),this.fallbackToRNoise(e,{reason:r,options:t,error:n}).catch((t=>{d(this,fm,"f").error("Failed to fallback to RNNoise through onError",{case:"Denoiser",type:d(this,bm,"f"),error:Pt(t),label:e.getLabel()})})).then((()=>{this.clientEventEmitter.emit(Mr,!1)})).catch((()=>{}))})),r.setTrackProcessor(n),d(this,fm,"f").debug("Denoiser trackProcessor set, check if activation is needed",{case:"Denoiser",type:d(this,bm,"f"),shouldEnableDenoiser:null==t?void 0:t.noiseSuppression,trackLabel:e.getLabel()}),(null==t?void 0:t.noiseSuppression)&&(yield e.enableNoiseSuppression())}catch(r){if(d(this,fm,"f").warn("Failed to start noise suppression, featured original track",{case:"Denoiser",type:d(this,bm,"f"),error:Pt(r),label:e.getLabel()}),"asdk"===d(this,bm,"f"))try{d(this,fm,"f").warn("Fallback to RNNoise",{error:Pt(r)}),yield this.fallbackToRNoise(e,{options:t,reason:"ASDK init error",error:r})}catch(t){d(this,fm,"f").error("Failed to fallback to RNNoise through catch",{case:"Denoiser",type:d(this,bm,"f"),error:Pt(t),label:e.getLabel()})}}finally{this.clientEventEmitter.emit(Mr,!1),u(this,ym,!1,"f")}}))}fallbackToRNoise(e,t){return c(this,void 0,void 0,(function*(){var r;if(d(this,_m,"f"))return;if(u(this,_m,!0,"f"),"rnnoise"===d(this,bm,"f"))return;this.clientEventEmitter.emit(Fr),d(this,fm,"f").info("Fallback to RNNoise",{reason:null==t?void 0:t.reason,error:Pt(null==t?void 0:t.error),case:"Denoiser"});const n=e;yield n.disableNoiseSuppression(),n.unsetTrackProcessor(),u(this,bm,"rnnoise","f"),this.config.set("denoiser",d(this,bm,"f")),d(this,fm,"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(d(this,bm,"f"),Ln.Microphone);i?(n.setTrackProcessor(i),(null===(r=null==t?void 0:t.options)||void 0===r?void 0:r.noiseSuppression)&&(yield n.enableNoiseSuppression())):d(this,fm,"f").error("No cached trackProcessor found",{case:"Denoiser",trackLabel:e.getLabel(),type:this.integrationsService.audio.type})}))}createEffectsSDKTrackProcessor(e){return c(this,void 0,void 0,(function*(){var t,r,n;if(e){const t=d(this,vm,"f").get(e);if(t)return t}if(!d(this,mm,"f"))throw d(this,fm,"f").error("Effects SDK config params not provided",{case:"initEffectsSDK"}),new Tt("effects_sdk_config_missing",new Error("Effects SDK config not provided"));const i=new Sf({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(),d(this,fm,"f").info("Track effects processor initialized",{trackLabel:e}),i}))}handleProducerSetMaxSpatialLayer(e){return c(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 d(this,fm,"f").warn("producerRequestMaxSpatialLayer()",{message:"Producer not found"});if(!(r instanceof um))return void d(this,fm,"f").warn("producerRequestMaxSpatialLayer()",{message:"Wrong producer kind"});const n=null!=t?t:ef,i=r.getMaxSpatialLayer();i!==n?(r.getEncodings().length>1&&(yield r.setMaxSpatialLayer(n)),yield this.signalingApiClient.producer.setProducerMaxSpatialLayer(e,{maxSpatialLayer:n}),yield r.adjustEncodingPresetToCurrentMaxSpatialLayer(n)):d(this,fm,"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:Xh.width,height:null!==(r=n.height)&&void 0!==r?r:Xh.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:Xh.width},height:{max:Xh.height}},encoderConfig:null!==(r=null==e?void 0:e.videoEncoderConfig)&&void 0!==r?r:{encodings:kc}}}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:Xh.width},height:{max:Xh.height}},encoderConfig:null!==(r=null==e?void 0:e.encoderConfig)&&void 0!==r?r:{encodings:Rc}}}createDevice(){this.normalizeUserAgentBrands();const e=(e=>{const t=null!=e?e:null===navigator||void 0===navigator?void 0:navigator.userAgent;if(!t)return;const r=wn.getParser(t);return r.satisfies({"yandex browser":">=25"})&&"iOS"===r.getOSName()?void 0:r.satisfies({"yandex browser":">=23.7"})?"Chrome111":r.satisfies({"yandex browser":">=22"})?"Chrome74":r.satisfies({"Samsung Internet for Android":">=17"})?"Chrome111":void 0})();return d(this,fm,"f").debug("Creating a media device",{handlerName:null!=e?e:"not specified"}),new md.Device({handlerName:e})}normalizeUserAgentBrands(){const{normalized:e,error:t}=(()=>{const e="undefined"!=typeof navigator?navigator.userAgentData:void 0;if(!(null==e?void 0:e.brands)||Array.isArray(e.brands))return{normalized:!1};try{return e.brands=Array.from(e.brands),{normalized:!0}}catch(t){return e.brands=[],{normalized:!0,error:t}}})();t?d(this,fm,"f").warn("Tried to reform brands property in navigator, but failed",{error:Pt(t)}):e&&d(this,fm,"f").info("Reform brands property in navigator",{})}};fm=new WeakMap,mm=new WeakMap,gm=new WeakMap,vm=new WeakMap,ym=new WeakMap,_m=new WeakMap,bm=new WeakMap,wm=s([ct(),o(0,ut(Nn.Config)),o(1,ut(Nn.LoggerFactory)),o(2,ut(Nn.AudioTrackFactory)),o(3,ut(Nn.ClientEventEmitter)),o(4,ut(Nn.IntegrationsService)),o(5,ut(Nn.ProcessorsCache)),o(6,ut(Nn.VideoTrackFactory)),o(7,ut(Nn.MediaStreamTrackManager)),o(8,ut(Nn.SignalingApiClient)),a("design:paramtypes",[Et,Function,Function,wt,hf,uf,Function,Em,bc])],wm);var Sm=wm;const Cm={[Di.PRODUCER_KIND_VIDEO]:"video",[Di.PRODUCER_KIND_AUDIO]:"audio"},Pm={[Mi.PEER_ROLE_HOST]:"host",[Mi.PEER_ROLE_AUDIENCE]:"audience"},Tm={[bi.PRODUCER_LABEL_CAMERA]:Ln.Camera,[bi.PRODUCER_LABEL_MICROPHONE]:Ln.Microphone,[bi.PRODUCER_LABEL_SCREEN_VIDEO]:Ln.ScreenVideo,[bi.PRODUCER_LABEL_SCREEN_AUDIO]:Ln.ScreenAudio,[bi.PRODUCER_LABEL_CUSTOM_VIDEO]:Ln.CustomVideo,[bi.PRODUCER_LABEL_CUSTOM_AUDIO]:Ln.CustomAudio,[bi.PRODUCER_LABEL_UNKNOWN]:Ln.Unknown,[bi.PRODUCER_LABEL_UNSPECIFIED]:Ln.Unknown},Rm={[_i.PEER_GROUP_MODERATOR]:"moderator",[_i.PEER_GROUP_USER]:"user"},km=e=>{const t=Cm[e];if(!t)throw new Error(`Unknown producer kind: ${e}`);return t},Dm=e=>{const t=Rm[e];if(!t)throw new Error(`Unknown peer group: ${e}`);return t},Im=e=>{const t=Tm[e];if(!t)throw new Error(`Unknown producer label: ${e}`);return t},Am=e=>{const t=Pm[e];if(!t)throw new Error(`Unknown peer role: ${e}`);return t},Om=e=>({id:e.id,channelIds:e.channelIds,groups:e.groups.map(Dm),producePermissions:e.producePermissions.map(Im),appId:e.appId,producers:e.producers.map(Mm),uid:e.uid,appData:e.appData,role:Am(e.role),loginDate:e.loginDate}),Mm=e=>{var t;return{id:e.id,kind:km(e.kind),label:Im(e.label),peerId:e.peerId,paused:e.paused,encodings:e.encodings,maxSpatialLayer:null!==(t=e.maxSpatialLayer)&&void 0!==t?t:0}},Nm=e=>{switch(e){case"moderator":return _i.PEER_GROUP_MODERATOR;case"user":return _i.PEER_GROUP_USER;default:return _i.PEER_GROUP_UNSPECIFIED}};var Lm;let xm=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,Lm.set(this,void 0),u(this,Lm,o("ChannelStateSyncEventHandler"),"f"),this.debouncedTriggerChannelStateEvent=Pn(this.triggerChannelStateEvent.bind(this),3e3),this.watchNetworkState()}handleChannelStateEvent(e){return c(this,void 0,void 0,(function*(){this.network.peersLoaded?yield this.restoreState(e):this.loadChannelState(e),this.clientEventEmitter.emit(Nr)}))}watchNetworkState(){this.clientEventEmitter.on(Or,(()=>{this.debouncedTriggerChannelStateEvent()}))}triggerChannelStateEvent(){return c(this,void 0,void 0,(function*(){const e=()=>c(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>c(this,void 0,void 0,(function*(){const r=yield this.network.triggerChannelStateEvent("host"),n=setTimeout((()=>{this.eventsQueue.isMessageReceived(r)?(d(this,Lm,"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(Ar,i),e()};this.clientEventEmitter.on(Ar,i)}))))}));try{yield Mn(e,{maxRetries:5,actionName:"triggerChannelStateEventWithRetry",logger:d(this,Lm,"f")})}catch(e){d(this,Lm,"f").warn("Failed to trigger channel state event",{case:"ChannelStateSynchronizer.triggerChannelStateEvent",error:Pt(e)})}}))}loadChannelState(e){d(this,Lm,"f").info("Loading channel state",{case:"loadChannelState"});try{const t=this.peers.hosts().map((e=>e.shortData)),r=e.peers.filter((e=>e.role===Mi.PEER_ROLE_HOST));this.setMissingPeers(t,r),this.restoreLocalPeersState(r),this.network.peersLoaded=!0}catch(e){d(this,Lm,"f").error("Failed to load channel state",{case:"loadState",error:Pt(e)})}}restoreState(e){return c(this,void 0,void 0,(function*(){const{peers:t}=e,r={missingPeers:[],removedPeers:[],missingProducers:[],removedProducers:[],fixedProducersState:[],fixedConsumersState:[],restoredAppDataPeers:[]};try{if(!this.network.isNetworkActive)return d(this,Lm,"f").info("Connection inactive, skipping restore local state",{case:"restoreLocalState"}),r;d(this,Lm,"f").info("Restoring local state",{case:"restoreLocalState"});const e=this.peers.hosts().map((e=>e.shortData)),n=t.filter((e=>e.role===Mi.PEER_ROLE_HOST)),{removedProducers:i,fixedProducersState:s}=yield this.restoreRemoteProducersState(n);r.fixedProducersState.push(...s),r.removedProducers.push(...i),r.removedPeers.push(...this.removeUnnecessaryPeers(e,n)),r.missingPeers.push(...this.setMissingPeers(e,n));const o=this.restoreLocalPeersState(n);return r.missingProducers.push(...o.missingProducers),r.removedProducers.push(...o.removedProducers),r.restoredAppDataPeers.push(...o.restoredAppDataPeers),r.fixedProducersState.push(...o.fixedProducersState),r.fixedConsumersState.push(...o.fixedConsumersState),r}catch(e){return d(this,Lm,"f").info("Failed to restore local state",{case:"restoreLocalState",error:Pt(e)}),r}}))}restoreRemoteProducersState(e){return c(this,void 0,void 0,(function*(){const t={removedProducers:[],fixedProducersState:[]},r=this.myPeer.get(),n=e.find((e=>e.id===this.myPeer.id));if(!r||!n)return t;const i=new Map;this.media.getAllTracks().forEach((e=>{e.producerId&&i.set(e.producerId,e)}));const s=new Set(i.keys()),o=n.producers.filter((e=>!s.has(e.id)));yield Promise.all(o.map((e=>c(this,void 0,void 0,(function*(){yield this.network.closeRemoteProducer(e.id),r.producers.delete(e.id),t.removedProducers.push(e.id),d(this,Lm,"f").info("Unnecessary local producer closed",{case:"restoreLocalState",removedProducerId:e.id,removedProducerPeerId:e.peerId})})))));const a=[];for(const e of n.producers){const t=i.get(e.id);t&&(t.isPaused!==e.paused&&a.push({cp:e,localTrack:t}))}return yield Promise.all(a.map((e=>c(this,[e],void 0,(function*({cp:e,localTrack:r}){r.isPaused?yield this.network.pauseRemoteProducer(e.id):yield this.network.resumeRemoteProducer(e.id),t.fixedProducersState.push(e.id),e.paused=r.isPaused,d(this,Lm,"f").info("Remote producer state repaired",{case:"restoreLocalState",removedProducerId:e.id,removedProducerPeerId:e.peerId,paused:r.isPaused})}))))),t}))}removeUnnecessaryPeers(e,t){const r=[];return e.filter((e=>!t.find((t=>t.id===e.id)))).forEach((e=>{this.peers.remove(e.id).catch((e=>{d(this,Lm,"f").error("Failed to remove peer",{error:Pt(e)})})),r.push(e.id),d(this,Lm,"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(Om(t));r.push(n.id),d(this,Lm,"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 d(this,Lm,"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)})),d(this,Lm,"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(an,t),r.push(t.id),d(this,Lm,"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(on,Mm(t)),r.missingProducers.push(t.id),void d(this,Lm,"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?Jr:Qr;e.observer.safeEmit(n,{producerId:i.id,kind:i.kind,label:i.label,paused:i.paused}),r.fixedProducersState.push(t.id),d(this,Lm,"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?ln:pn;e.observer.safeEmit(s,n),r.fixedConsumersState.push(n),d(this,Lm,"f").info("Consumer state fixed",{case:"restoreLocalState",consumerId:n,consumerProducerId:t.id,consumerProducerPeerId:t.peerId})}})),r}restoreAppData(e,t){return!Cn(e.appData,t.appData)&&(e.observer.emit(vr,t.appData),d(this,Lm,"f").info("Application data restored",{case:"restoreLocalState",peerId:e.id,appData:t.appData}),!0)}};Lm=new WeakMap,xm=s([ct(),o(0,ut(Nn.Network)),o(1,ut(Nn.Media)),o(2,ut(Nn.MyPeer)),o(3,ut(Nn.EventsQueue)),o(4,ut(Nn.ClientEventEmitter)),o(5,ut(Nn.Peers)),o(6,ut(Nn.LoggerFactory)),a("design:paramtypes",[Xc,Sm,Cs,ws,wt,ed,Function])],xm);var Fm,jm=xm;let Um=class{constructor(e,t,r,n,i){this.peers=e,this.clientEventEmitter=t,this.channelStateSyncEventHandler=n,this.channelStateSynchronizer=i,Fm.set(this,void 0),u(this,Fm,r("ChannelEvents"),"f")}handleChannelEvent(e){return c(this,void 0,void 0,(function*(){switch(e.eventType){case zi.CHANNEL_EVENT_TYPE_CHANNEL_STATE:yield this.handleChannelState(e);break;case zi.CHANNEL_EVENT_TYPE_CHANNEL_STATE_SHORT:this.handleChannelStateShort(e);break;case zi.CHANNEL_EVENT_TYPE_CHANNEL_MANAGEMENT_EVENT:this.handleChannelManagementEvent(e);break;case zi.CHANNEL_EVENT_TYPE_PEER_JOINED:this.handlePeerJoined(e);break;case zi.CHANNEL_EVENT_TYPE_PEER_LEFT:this.handlePeerLeft(e);break;case zi.CHANNEL_EVENT_TYPE_PEER_APP_DATA_CHANGED:this.handlePeerAppDataChanged(e);break;case zi.CHANNEL_EVENT_TYPE_PEER_GROUP_CHANGED:this.handlePeerGroupsChanged(e);break;case zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_ACQUIRED:this.handleChannelActivityConfirmationAcquired();break;case zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_EXPIRED:this.handleChannelActivityConfirmationExpired();break;case zi.CHANNEL_EVENT_TYPE_CHANNEL_ACTIVITY_CONFIRMATION_REQUIRED:this.handleChannelActivityConfirmationRequired(e);break;case zi.CHANNEL_EVENT_TYPE_CHANNEL_PRODUCE_PERMISSIONS_CHANGED:this.handleChannelProducePermissionsChanged(e);break;case zi.CHANNEL_EVENT_TYPE_PEER_PRODUCE_PERMISSIONS_CHANGED:this.handlePeerProducePermissionsChanged(e);break;case zi.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(yr,t),d(this,Fm,"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(Om(e.peer));d(this,Fm,"f").debug("Peer joined to the channel",{peer:Ss(t)})}handlePeerLeft(e){if(!e.peer)throw new Error("Missing peer in PEER_LEFT event");this.peers.remove(e.peer.id).catch((e=>{d(this,Fm,"f").debug("Failed to remove peer",{error:Pt(e)})})),d(this,Fm,"f").debug("Peer left the channel",{peerId:e.peer.id})}handleChannelState(e){return c(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){d(this,Fm,"f").error("Failed to restore channel state",{case:"restoreLocalState",error:Pt(e)})}}))}handleChannelStateShort(e){if(!e.channelStateShort)throw new Error("Missing channelStateShort in CHANNEL_STATE_SHORT event");this.channelStateSyncEventHandler.handleChannelStateShort(e.channelStateShort).catch((e=>{d(this,Fm,"f").error("Failed to handle channel state short event",{error:Pt(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(Dm))}handleChannelActivityConfirmationExpired(){this.clientEventEmitter.safeEmit(Sr),d(this,Fm,"f").info("Notify the channel that it has disconnected due to the activity confirmation expiring",{})}handleChannelActivityConfirmationAcquired(){this.clientEventEmitter.safeEmit(wr),d(this,Fm,"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(Er,t),d(this,Fm,"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(Nm(e)))))),n=e.channelProducePermissions.producePermissions.map(Im),i=e.channelProducePermissions.changedProducePermissions.map(Im);r.forEach((e=>{const t=Array.from(new Set([...e.producePermissions,...i])).filter((e=>!i.includes(e)||n.includes(e)));e.handleProducePermissionsChange(t)})),d(this,Fm,"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(Im);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(Nm(e)))))),n=e.channelProducePermissions.producePermissions.map(Im);r.forEach((e=>{const t=e.producePermissions.filter((e=>!n.includes(e)));e.handleProducePermissionsChange(t)})),d(this,Fm,"f").info("Peers deleted produce permissions",{groups:t,producePermissions:n})}};Fm=new WeakMap,Um=s([ct(),o(0,ut(Nn.Peers)),o(1,ut(Nn.ClientEventEmitter)),o(2,ut(Nn.LoggerFactory)),o(3,ut(Nn.ChannelStateSyncEventHandler)),o(4,ut(Nn.ChannelStateSynchronizer)),a("design:paramtypes",[ed,wt,Function,fd,jm])],Um);var Vm=Um,Bm={},Wm=p&&p.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(Bm,"__esModule",{value:!0});var Hm,qm,zm=Bm.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 Wm(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 Wm(this,void 0,void 0,(function*(){const e=this.pendingTasks[0];e&&(yield this.executeTask(e),this.pendingTasks.shift(),this.next())}))}executeTask(e){return Wm(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 Gm=class{constructor(e,t,r,n,i){this.media=e,this.internalEventEmitter=t,this.peersStorage=r,this.clientEventEmitter=n,Hm.set(this,new zm),qm.set(this,void 0),u(this,qm,i("MediaEvents"),"f")}handleMediaEvent(e){var t;switch(e.eventType){case os.MEDIA_EVENT_TYPE_PRODUCER_CREATED:this.handleProducerCreated(e);break;case os.MEDIA_EVENT_TYPE_PRODUCER_CLOSED:this.handleProducerClosed(e);break;case os.MEDIA_EVENT_TYPE_PRODUCER_PAUSED:this.handleProducerPaused(e);break;case os.MEDIA_EVENT_TYPE_PRODUCER_RESUMED:this.handleProducerResumed(e);break;case os.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED:this.handleProducerMaxSpatialLayerChanged(e);break;case os.MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_REQUESTED:this.handleProducerRequestMaxSpatialLayer(e).catch((e=>{d(this,qm,"f").error("Failed to handle producer max spatial layer requested event",{error:Pt(e)})}));break;case os.MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED:this.handleProducerForciblyClosed(e).catch((e=>{d(this,qm,"f").error("Failed to handle producer forcibly closed event",{error:Pt(e)})}));break;case os.MEDIA_EVENT_TYPE_CONSUMER_CLOSED:d(this,qm,"f").debug("Close consumer event received, skip",{consumerId:null===(t=e.consumer)||void 0===t?void 0:t.id});break;case os.MEDIA_EVENT_TYPE_CONSUMER_RESUMED:this.handleConsumerResumed(e);break;case os.MEDIA_EVENT_TYPE_CONSUMER_PAUSED:this.handleConsumerPaused(e);break;case os.MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED:this.handleConsumerPreferredLayersChanged(e);break;case os.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(on,Mm(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(an,Mm(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(Jr,{producerId:r.id,kind:r.kind,label:r.label,paused:r.paused})):t.observer.safeEmit(on,Object.assign(Object.assign({},Mm(e.producer)),{paused:!0})):d(this,qm,"f").warn("Peer not found for producer paused event",{peerId:e.producer.peerId})}handleProducerResumed(e){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_RESUMED");const t=this.peersStorage.get(e.producer.peerId),r=null==t?void 0:t.producers.get(e.producer.id);t?r?(r.setPaused(!1),t.observer.safeEmit(Qr,{producerId:r.id,kind:r.kind,label:r.label,paused:r.paused})):t.observer.safeEmit(on,Object.assign(Object.assign({},Mm(e.producer)),{paused:!1})):d(this,qm,"f").warn("Peer not found for producer resumed event",{peerId:e.producer.peerId})}handleProducerMaxSpatialLayerChanged(e){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_MAX_SPATIAL_LAYER_CHANGED");if(void 0===e.producer.maxSpatialLayer)return;const t=this.peersStorage.get(e.producer.peerId);null==t||t.observer.safeEmit(cn,{peerId:e.producer.peerId,producerId:e.producer.id,spatialLayer:e.producer.maxSpatialLayer})}handleProducerRequestMaxSpatialLayer(e){return c(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 d(this,Hm,"f").push((()=>c(this,void 0,void 0,(function*(){yield this.media.handleProducerSetMaxSpatialLayer({producerId:t,spatialLayer:r})}))),dn)}))}handleProducerForciblyClosed(e){return c(this,void 0,void 0,(function*(){if(!e.producer)throw new Error("Missing producer in MEDIA_EVENT_TYPE_PRODUCER_FORCIBLY_CLOSED");const t=Im(e.producer.label),r=this.media.getTrack(t);if(!r)return;r.stopMediaStreamTrack(),this.internalEventEmitter.safeEmit(qr,r);const n={label:t};this.clientEventEmitter.emit(Rr,n),yield this.media.deleteTrack(r)}))}handleConsumerResumed(e){if(!e.consumer)throw new Error("Missing consumer in MEDIA_EVENT_TYPE_CONSUMER_RESUMED");const t=this.peersStorage.get(e.consumer.producerPeerId);null==t||t.observer.safeEmit(pn,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(ln,e.consumer.id)}handleConsumerPreferredLayersChanged(e){var t;if(!e.consumer)throw new Error("Missing consumer in MEDIA_EVENT_TYPE_CONSUMER_PREFERRED_LAYERS_CHANGED");if(void 0===e.consumer.spatialLayer)return;const r=e.consumer.producerPeerId||e.consumer.peerId,n=this.peersStorage.get(r);null==n||n.observer.safeEmit(hn,{consumerId:e.consumer.id,spatialLayer:e.consumer.spatialLayer,temporalLayer:null!==(t=e.consumer.temporalLayer)&&void 0!==t?t:rf})}handleTransportConnectionTimeout(e){if(!e.transportConnectionTimeout)throw new Error("Missing transportConnectionTimeout in MEDIA_EVENT_TYPE_TRANSPORT_CONNECTION_TIMEOUT");d(this,qm,"f").warn("Transport connection timed out",{transportId:e.transportConnectionTimeout.transportId,direction:e.transportConnectionTimeout.direction,timeout:e.transportConnectionTimeout.timeout,reason:e.transportConnectionTimeout.reason})}};Hm=new WeakMap,qm=new WeakMap,Gm=s([ct(),o(0,ut(Nn.Media)),o(1,ut(Nn.InternalEventEmitter)),o(2,ut(Nn.PeersStorage)),o(3,ut(Nn.ClientEventEmitter)),o(4,ut(Nn.LoggerFactory)),a("design:paramtypes",[Sm,wt,Tc,wt,Function])],Gm);var Ym,$m=Gm;let Jm=class{constructor(){Ym.set(this,new Map)}set(e,t){d(this,Ym,"f").set(e,{label:e,producerId:t})}get(e){return d(this,Ym,"f").get(e)}has(e){return d(this,Ym,"f").has(e)}delete(e){d(this,Ym,"f").delete(e)}entries(){return Array.from(d(this,Ym,"f").values())}};Ym=new WeakMap,Jm=s([ct()],Jm);var Qm,Km=Jm;let Zm=class{constructor(e,t,r){this.network=e,this.storage=t,Qm.set(this,void 0),u(this,Qm,r("ProducerCloseManager"),"f")}close(e,t){return c(this,void 0,void 0,(function*(){try{const r=yield this.sendCloseRequest(t);if(this.storage.delete(e),!r)return;d(this,Qm,"f").info("Remote producer closed",{label:e,producerId:t})}catch(r){this.storage.set(e,t),d(this,Qm,"f").warn("Failed to close remote producer, queued for retry",{label:e,producerId:t,error:Pt(r)})}}))}ensureNoPending(e){return c(this,void 0,void 0,(function*(){const t=this.storage.get(e);t&&(yield this.flushEntry(t))}))}flushPending(){return c(this,void 0,void 0,(function*(){const e=this.storage.entries();for(const t of e)try{yield this.flushEntry(t)}catch(e){}}))}flushEntry(e){return c(this,void 0,void 0,(function*(){try{yield Mn((()=>c(this,void 0,void 0,(function*(){yield this.sendCloseRequest(e.producerId)}))),{maxRetries:5,minBackoffDelayMs:200,maxBackoffDelayMs:1e3,actionName:"closeRemoteProducer",logger:d(this,Qm,"f")}),this.storage.delete(e.label),d(this,Qm,"f").info("Pending remote producer closed",{label:e.label,producerId:e.producerId})}catch(t){throw d(this,Qm,"f").warn("Failed to close pending remote producer",{label:e.label,producerId:e.producerId,error:Pt(t)}),t}}))}sendCloseRequest(e){return c(this,void 0,void 0,(function*(){try{return yield this.network.closeRemoteProducer(e),!0}catch(t){if(t instanceof rc)return d(this,Qm,"f").debug("Remote producer maybe already closed",{producerId:e}),!1;throw t}}))}};Qm=new WeakMap,Zm=s([ct(),o(0,ut(Nn.Network)),o(1,ut(Nn.PendingClosureProducerStorage)),o(2,ut(Nn.LoggerFactory)),a("design:paramtypes",[Function,Km,Function])],Zm);var Xm,eg,tg,rg,ng,ig,sg=Zm;const og=["send","recv"];let ag=ig=class{constructor(e,t){this.network=e,this.loggerFactory=t,Xm.set(this,!1),eg.set(this,new Map),tg.set(this,new Set),rg.set(this,new Map),ng.set(this,void 0),this.handleTransportState=({state:e,direction:t})=>{if(!d(this,Xm,"f"))return;if(d(this,tg,"f").has(t))return;if(d(this,rg,"f").has(t))return;if(!["disconnected","failed"].includes(e))return;const r=this.recordDisconnectAndGetCount(t);r&&(r<=3||(d(this,ng,"f").warn("transport instability detected. Escalating to relay",{direction:t,disconnectCount:r}),this.escalateDirectionToRelay(t).catch((e=>{d(this,ng,"f").warn("Failed to apply relay policy",{direction:t,error:Pt(e)})}))))},u(this,ng,this.loggerFactory("NetworkTransportPolicyManager"),"f")}startMonitoring(){d(this,Xm,"f")||(this.refreshDirectionRelayState(),d(this,eg,"f").clear(),u(this,Xm,!0,"f"),this.network.observer.on(mn,this.handleTransportState))}stopMonitoring(){d(this,Xm,"f")&&(this.network.observer.off(mn,this.handleTransportState),u(this,Xm,!1,"f"),d(this,eg,"f").clear())}changeIceTransportPolicy(e){return c(this,void 0,void 0,(function*(){yield Promise.all(d(this,rg,"f").values()),yield Promise.all(og.map((t=>c(this,void 0,void 0,(function*(){return yield this.applyRelayPolicy(t,e)}))))),d(this,eg,"f").clear(),"all"!==e?this.stopMonitoring():d(this,tg,"f").clear()}))}recordDisconnectAndGetCount(e){var t;const r=Date.now(),n=null!==(t=d(this,eg,"f").get(e))&&void 0!==t?t:[],i=n[n.length-1];if(ig.isDuplicateDisconnect(i,r))return;const s=ig.getDisconnectsInWindow(n,r);return s.push(r),d(this,eg,"f").set(e,s),s.length}applyRelayPolicy(e,t){return c(this,void 0,void 0,(function*(){const r=this.getTransportByDirection(e);if(!r)return;const n=ig.getPeerConnection(r);n&&(n.setConfiguration(Object.assign(Object.assign({},n.getConfiguration()),{iceTransportPolicy:t})),yield this.network.restartIce(r),"relay"===t?d(this,tg,"f").add(e):d(this,tg,"f").delete(e))}))}escalateDirectionToRelay(e){return c(this,void 0,void 0,(function*(){if(d(this,tg,"f").has(e))return;const t=d(this,rg,"f").get(e);if(t)return void(yield t);const r=(()=>c(this,void 0,void 0,(function*(){yield this.applyRelayPolicy(e,"relay"),d(this,eg,"f").delete(e)})))();d(this,rg,"f").set(e,r);try{yield r}finally{d(this,rg,"f").delete(e)}}))}refreshDirectionRelayState(){og.forEach((e=>{const t=this.getTransportByDirection(e),r=ig.getPeerConnection(t);"relay"!==(null==r?void 0:r.getConfiguration().iceTransportPolicy)?d(this,tg,"f").delete(e):d(this,tg,"f").add(e)}))}getTransportByDirection(e){return"send"===e?this.network.sendTransport:this.network.receiveTransport}static getPeerConnection(e){var t;return null===(t=null==e?void 0:e.handler)||void 0===t?void 0:t._pc}static getDisconnectsInWindow(e,t){const r=t-3e4;return e.filter((e=>e>=r))}static isDuplicateDisconnect(e,t){return"number"==typeof e&&t-e<400}};Xm=new WeakMap,eg=new WeakMap,tg=new WeakMap,rg=new WeakMap,ng=new WeakMap,ag=ig=s([ct(),o(0,ut(Nn.Network)),o(1,ut(Nn.LoggerFactory)),a("design:paramtypes",[Xc,Function])],ag);var cg=ag;const dg=new Error("request for lock canceled");var ug=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class lg{constructor(e,t=dg){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=pg(this._queue,(e=>t<=e.priority));-1===s&&e<=this._value?this._dispatchItem(i):this._queue.splice(s+1,0,i)}))}runExclusive(e){return ug(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=pg(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 pg(e,t){for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1}var hg,fg=function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class mg{constructor(e){this._semaphore=new lg(1,e)}acquire(){return fg(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 gg=class{constructor(){hg.set(this,new Map)}lock(e){return c(this,void 0,void 0,(function*(){let t=d(this,hg,"f").get(e);return t||(t=new mg,d(this,hg,"f").set(e,t)),t.isLocked()&&(yield t.waitForUnlock()),yield t.acquire()}))}isLocked(e){const t=d(this,hg,"f").get(e);return!!t&&t.isLocked()}waitForUnlock(e){return c(this,void 0,void 0,(function*(){const t=d(this,hg,"f").get(e);(null==t?void 0:t.isLocked())?yield t.waitForUnlock():yield Promise.resolve()}))}};hg=new WeakMap,gg=s([ct()],gg);var vg,yg=gg;let _g=class{constructor(e,t){this.clientEventEmitter=e,this.isEnableVideoDevicesLock=!1,this.isEnableAudioDevicesLock=!1,this.isDevicesDetected=!1,this.availableVideoDevices=[],this.availableAudioDevices=[],vg.set(this,void 0),u(this,vg,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 c(this,arguments,void 0,(function*(e={video:!0,audio:!0}){try{return(yield navigator.mediaDevices.getUserMedia(e)).getTracks()}catch(t){d(this,vg,"f").error("getUserMedia()",{error:t,constraints:e});const r=t instanceof Error?t.name:void 0;if("NotAllowedError"===r)throw new Error(xn.NotAllowedError);if("NotReadableError"===r)throw new Error(xn.DeviceIsBusy);if("NotFoundError"===r)throw new Error(xn.NotFoundError);throw new Error(xn.RequestDevicesUnknownError)}}))}hasAvailableMediaDevicesList(){return c(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 c(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 d(this,vg,"f").info("Devices list updated",{videoDevices:t.map(n),audioDevices:r.map(n)}),e}))}detectDevices(e){return c(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(xn.NoDevices)}))}deviceChangeHandler(){return c(this,void 0,void 0,(function*(){if(!this.isDevicesDetected)return;yield this.refreshAvailableMediaDevicesList();const e={audio:this.availableAudioDevices,video:this.availableVideoDevices};this.clientEventEmitter.safeEmit(Pr,e)}))}listenDevices(){navigator.mediaDevices.addEventListener("devicechange",this.deviceChangeHandler)}assertHasAccessToMediaDevices(){return c(this,arguments,void 0,(function*(e={video:!0,audio:!0}){(yield this.requestMediaDevicesAccess(e)).forEach((e=>e.stop()))}))}tryToAccessDevices(){return c(this,void 0,void 0,(function*(){try{(yield this.requestMediaDevicesAccess()).forEach((e=>e.stop()))}catch(t){const r=(e=>{if(e instanceof Error)return e.message;if("string"==typeof e)return e;if(e&&"object"==typeof e&&"message"in e){const t=e.message;return"string"==typeof t?t:void 0}})(t);if(!r||(e=r,![xn.NotFoundError,xn.NotAllowedError,xn.DeviceIsBusy].includes(e)))throw t;r!==xn.DeviceIsBusy&&(yield this.assertHasAccessToMediaDevices({audio:!0}),yield this.assertHasAccessToMediaDevices({video:!0}))}var e}))}};vg=new WeakMap,_g=s([ct(),o(0,ut(Nn.ClientEventEmitter)),o(1,ut(Nn.LoggerFactory)),a("design:paramtypes",[wt,Function])],_g);var bg,Eg=_g;class wg{constructor({transport:e,statsHandler:t}){bg.set(this,void 0),this.handleWebRTCStats(e,t)}get connectionStats(){return d(this,bg,"f")}handleWebRTCStats(e,t){t.addConnectionHandler(e.id,this.setConnectionStats.bind(this)),e.observer.once("close",(()=>{t.removeConnectionHandler(e.id)}))}setConnectionStats(e){u(this,bg,e,"f")}}bg=new WeakMap;function Sg(e,t){return t.find((t=>t.ssrc===e))}function Cg(e,t,r){return Math.max(t,Math.min(e,r))}function Pg(e,t=2){return Number(e.toFixed(t))}function Tg(e){return Cg(Pg(e),1,5)}function Rg(e,t){if(0===e.length)throw new Error("Cannot compute percentile of empty array");if(1===e.length)return e[0];const r=t*(e.length-1),n=Math.floor(r),i=Math.ceil(r),s=r-n;return Pg(e[n]+s*(e[i]-e[n]))}var kg,Dg,Ig,Ag,Og;let Mg=class{constructor(){kg.set(this,new Map),Dg.set(this,new Map),Ig.set(this,new Map),Ag.set(this,new Map),Og.set(this,new Map)}handle(e){e.forEach((({id:e,stats:t})=>{var r;null===(r=d(this,kg,"f").get(e))||void 0===r||r(t.connection),t.video.inbound.forEach((e=>{var r;return null===(r=d(this,Dg,"f").get(e.trackIdentifier))||void 0===r?void 0:r({inbound:e,connection:t.connection})})),t.audio.inbound.forEach((e=>{var r;return null===(r=d(this,Ig,"f").get(e.trackIdentifier))||void 0===r?void 0:r({inbound:e,connection:t.connection})}));const n=new Map;t.video.outbound.forEach((e=>{const r=Sg(e.ssrc,t.remote.video.inbound);if(!r)return;const i={outbound:e,remoteInbound:r,connection:t.connection},s=n.get(e.mid);s?s.push(i):n.set(e.mid,[i])})),n.forEach((e=>{var t,r;const n=null===(t=e.find((e=>e.outbound.track.trackIdentifier)))||void 0===t?void 0:t.outbound.track.trackIdentifier;n&&(null===(r=d(this,Ag,"f").get(n))||void 0===r||r(e))})),t.audio.outbound.forEach((e=>{var r;const n=Sg(e.ssrc,t.remote.audio.inbound);n&&(null===(r=d(this,Og,"f").get(e.track.trackIdentifier))||void 0===r||r({outbound:e,remoteInbound:n,connection:t.connection}))}))}))}addConnectionHandler(e,t){d(this,kg,"f").set(e,t)}addInboundVideoHandler(e,t){d(this,Dg,"f").set(e,t)}addInboundAudioHandler(e,t){d(this,Ig,"f").set(e,t)}addOutboundVideoHandler(e,t){d(this,Ag,"f").set(e,t)}addOutboundAudioHandler(e,t){d(this,Og,"f").set(e,t)}removeConnectionHandler(e){d(this,kg,"f").delete(e)}removeInboundVideoHandler(e){d(this,Dg,"f").delete(e)}removeInboundAudioHandler(e){d(this,Ig,"f").delete(e)}removeOutboundVideoHandler(e){d(this,Ag,"f").delete(e)}removeOutboundAudioHandler(e){d(this,Og,"f").delete(e)}clear(){d(this,kg,"f").clear(),d(this,Dg,"f").clear(),d(this,Ig,"f").clear(),d(this,Ag,"f").clear(),d(this,Og,"f").clear()}};kg=new WeakMap,Dg=new WeakMap,Ig=new WeakMap,Ag=new WeakMap,Og=new WeakMap,Mg=s([ct()],Mg);var Ng,Lg,xg,Fg,jg,Ug,Vg,Bg,Wg=Mg;let Hg=class{constructor(e,t){var r;Ng.set(this,!1),Lg.set(this,void 0),xg.set(this,void 0),Fg.set(this,void 0),jg.set(this,void 0),Ug.set(this,void 0),Vg.set(this,void 0),Bg.set(this,.5),u(this,Lg,e("IntegrationsService"),"f"),u(this,Vg,t,"f"),u(this,Bg,null!==(r=kf("qosQPercentile"))&&void 0!==r?r:d(this,Bg,"f"),"f")}init({sendTransportConnectionManager:e,receiveTransportConnectionManager:t,media:r,peers:n}){u(this,xg,e,"f"),u(this,Fg,t,"f"),u(this,jg,r,"f"),u(this,Ug,n,"f"),u(this,Ng,!0,"f")}getStats(){try{return this.doGetStats()}catch(e){return d(this,Lg,"f").error("Failed to get stats",{error:Pt(e)}),{}}}clear(){u(this,xg,void 0,"f"),u(this,Fg,void 0,"f"),u(this,jg,void 0,"f"),u(this,Ug,void 0,"f")}doGetStats(){var e,t,r,n;if(!d(this,Ng,"f"))throw new Error("TransportsStatsProvider is not initialized");const i={};if(null===(t=null===(e=d(this,xg,"f"))||void 0===e?void 0:e.connectionStats)||void 0===t?void 0:t.id){const e=this.calculateOutboundTracksResultQValues();i.outbound=Object.assign(Object.assign({},d(this,xg,"f").connectionStats),{bitrate:this.calculateOutboundTracksBitrate(),Qav:e.Qav,Qa:e.Qa,Qv:e.Qv})}if(null===(n=null===(r=d(this,Fg,"f"))||void 0===r?void 0:r.connectionStats)||void 0===n?void 0:n.id){const e=this.calculateInboundTracksResultQValues();i.inbound=Object.assign(Object.assign({},d(this,Fg,"f").connectionStats),{bitrate:this.calculateInboundTracksBitrate(),Qav:e.Qav,Qa:e.Qa,Qv:e.Qv})}return i}calculateInboundTracksBitrate(){if(void 0===d(this,Ug,"f"))throw new Error("Peers is undefined");return d(this,Ug,"f").hosts().reduce(((e,t)=>{if(t.isMe)return e;return e+Array.from(t.tracks.values()).reduce(((e,t)=>{var r,n;const i="video"===t.kind?null===(r=t.videoWebRTCStats)||void 0===r?void 0:r.bitrate:null===(n=t.audioWebRTCStats)||void 0===n?void 0:n.bitrate;return e+(null!=i?i:0)}),0)}),0)}calculateInboundTracksResultQValues(){if(void 0===d(this,Ug,"f"))throw new Error("Peers prop is not defined");const e=[],t=[],r=[];for(const n of d(this,Ug,"f").hosts()){if(n.isMe)continue;const{Qa:i,Qv:s}=this.getWorstQValues(Array.from(n.tracks.values()));void 0!==i&&t.push(i),void 0!==s&&r.push(s);const o=void 0===i||void 0===s?null!=i?i:s:d(this,Vg,"f").calculateAVCompositeMOS(i,s);void 0!==o&&e.push(o)}const n=(e,t)=>e-t;return e.sort(n),t.sort(n),r.sort(n),{Qav:e.length>0?Rg(e,d(this,Bg,"f")):void 0,Qa:t.length>0?Rg(t,d(this,Bg,"f")):void 0,Qv:r.length>0?Rg(r,d(this,Bg,"f")):void 0}}calculateOutboundTracksResultQValues(){var e;if(void 0===d(this,jg,"f"))throw new Error("Media prop is not defined");const t=d(this,jg,"f").getAllTracks().filter((e=>e.isPublished)),{Qa:r,Qv:n}=this.getWorstQValues(t);let i;return void 0!==r&&void 0!==n&&(i=d(this,Vg,"f").calculateAVCompositeMOS(r,n)),{Qav:null!==(e=null!=i?i:r)&&void 0!==e?e:n,Qa:r,Qv:n}}calculateOutboundTracksBitrate(){if(void 0===d(this,jg,"f"))throw new Error("Media is undefined");return d(this,jg,"f").getAllTracks().reduce(((e,t)=>{var r,n;if(!t.isPublished)return e;const i="video"===t.kind?null===(r=t.videoWebRTCStats)||void 0===r?void 0:r.bitrate:null===(n=t.audioWebRTCStats)||void 0===n?void 0:n.bitrate;return e+(null!=i?i:0)}),0)}getWorstQValues(e){let t,r;for(const n of e){const{Qa:e,Qv:i}=n.connectionScores;void 0!==e&&(void 0===t||e<t)&&(t=e),void 0!==i&&(void 0===r||i<r)&&(r=i)}return{Qa:t,Qv:r}}};Ng=new WeakMap,Lg=new WeakMap,xg=new WeakMap,Fg=new WeakMap,jg=new WeakMap,Ug=new WeakMap,Vg=new WeakMap,Bg=new WeakMap,Hg=s([ct(),o(0,ut(Nn.LoggerFactory)),o(1,ut(Nn.ScoresCalculator)),a("design:paramtypes",[Function,Function])],Hg);var qg=Hg;const zg={vp8:40,vp9:40,h264:25},Gg={mobile:[.1558,1.0348,-.0181,-.4048],pc:[.1526,.8788,.0086,-.2242],tv:[.1496,1.0267,-.0248,-.3477]},Yg={video:{codecFactors:{vp9:1.2,vp8:1,h264:1}},defaults:{audio:{ssrc:-1,packetLoss:0,bufferDelay:50,roundTripTime:50,fec:!0,bitrate:0,dtx:!1},video:{ssrc:-1,packetLoss:0,bufferDelay:0,roundTripTime:50,codec:"vp8",width:640,height:480,expectedWidth:640,expectedHeight:480,frameRate:20,expectedFrameRate:20,bitrate:0}}};let $g=class{constructor(e){this.config=this.mergeConfig(e)}calculateAudioMOS(e){const t=this.normalizeAudioStats(e),r=20+t.bufferDelay+t.roundTripTime/2,n=t.packetLoss;let i=0;i=t.dtx?8:t.bitrate>0?Cg(55-4.6*Math.log(t.bitrate),0,30):6;const s=Cg(100-(i+(100-i)*n/(n+(t.fec?20:10)))-(.03*r+(r>150?.1*(r-150):0)),0,100);return Tg(1+.035*s+s*(s-60)*(100-s)*7/1e6)}calculateVideoMOS(e){var t,r,n,i,s,o;const a=this.normalizeVideoStats(e),c=a.expectedWidth*a.expectedHeight;if(!a.frameRate||!c||void 0===a.bitrate)return 1;const d=a.codec&&null!==(n=null===(r=null===(t=this.config.video)||void 0===t?void 0:t.codecFactors)||void 0===r?void 0:r[a.codec.toLowerCase()])&&void 0!==n?n:1,u=a.bufferDelay+a.roundTripTime/2,l=d*a.bitrate/c/a.frameRate,p=Cg(.56*Math.log(l)+5.36,1,5),h=!0===a.decreaseOutboundPenalty&&"none"===a.qualityLimitationReason,f=null!==(o=zg[null!==(s=null===(i=a.codec)||void 0===i?void 0:i.toLowerCase())&&void 0!==s?s:""])&&void 0!==o?o:40,m=void 0!==a.averageQP&&a.averageQP<f;return Tg((h||!0===a.isStaticContent||m?Math.max(p,4):p)-(a.expectedFrameRate>0?1.9*Math.log(a.expectedFrameRate/a.frameRate):0)-.002*u)}calculateAVCompositeMOS(e,t,r){const[n,i,s,o]=Gg[null!=r?r:"pc"];return Tg(n*e+i*t+s*e*t+o)}mergeConfig(e){var t;return e?{video:{codecFactors:Object.assign(Object.assign({},Yg.video.codecFactors),null===(t=e.video)||void 0===t?void 0:t.codecFactors)}}:Yg}normalizeAudioStats(e){return Object.assign(Object.assign({},Yg.defaults.audio),e)}normalizeVideoStats(e){const t=Object.assign(Object.assign({},Yg.defaults.video),e);return void 0!==e.width&&void 0===e.expectedWidth&&(t.expectedWidth=e.width),void 0!==e.height&&void 0===e.expectedHeight&&(t.expectedHeight=e.height),void 0!==e.frameRate&&void 0===e.expectedFrameRate&&(t.expectedFrameRate=e.frameRate),t}};var Jg,Qg,Kg;$g=s([ct(),a("design:paramtypes",[Object])],$g);let Zg=class{constructor(e,t,r,n,i,s,o,a,c,d,l,p,h,f,m,g,v,y,_,b,E,w,S,C,P){var T;this.state=e,this.myPeer=t,this.integrationsService=n,this.processorsCache=i,this.mediaEventHandler=s,this.channelEventsHandler=o,this.peerTrackFactory=a,this.peers=c,this.peersStorage=d,this.system=l,this.media=p,this.network=h,this.networkTransportPolicyManager=f,this.producerCloseManager=m,this.signalingApiClient=g,this.eventsQueue=v,this.clientEventEmitter=y,this.internalEventEmitter=_,this.statsHandler=b,this.transportsStatsProvider=E,this.localMutex=w,this.scoresCalculatorInstance=S,this.clientMetaProvider=C,this.webRtcIssueDetector=P,Jg.set(this,void 0),this.rejoinRequested=!1,this.isReleasing=!1,Qg.set(this,!1),Kg.set(this,!1),this.mark=In(),this.handleSignalingError=e=>{this.isReleasing||!this.isChannelJoined||this.state.isChannelJoining||e instanceof yn&&this.triggerRejoinEventIfAppropriate(e.errorCode)},u(this,Jg,r("Engine"),"f"),this.watchNetworkState(),this.watchDocumentUnload(),this.watchInternalEvents(),this.signalingApiClient.addErrorListener(this.handleSignalingError),T=this.mark,window._sdkMarks||(window._sdkMarks=new Set),window._sdkMarks.add(T)}get isChannelJoined(){return this.state.isJoined}get scoresCalculator(){return this.scoresCalculatorInstance}initialize(){return c(this,void 0,void 0,(function*(){var e,t,r,n;try{const{data:i}=yield this.signalingApiClient.router.getRtpCapabilities(),{rtpCapabilities:s}=i;this.integrationsService.init(),yield this.media.loadDevice(s),d(this,Jg,"f").info("Supported capabilities",{codecs:Rn(this.media.mediasoupDevice)});const[o,a]=yield Promise.all([this.network.createSendTransport(this.media.mediasoupDevice),this.network.createRecvTransport(this.media.mediasoupDevice)]);null===(e=this.webRtcIssueDetector)||void 0===e||e.handleNewPeerConnection(o.handler._pc,o.id),null===(t=this.webRtcIssueDetector)||void 0===t||t.handleNewPeerConnection(a.handler._pc,a.id),this.transportsStatsProvider.init({media:this.media,peers:this.peers,receiveTransportConnectionManager:new wg({transport:a,statsHandler:this.statsHandler}),sendTransportConnectionManager:new wg({transport:o,statsHandler:this.statsHandler})}),yield this.network.initializeHeartbeats();const{isChromiumBased:c}=(e=>{var t;const r=null!=e?e:"undefined"!=typeof navigator?navigator.userAgent:void 0;if(!r)return{isMobile:!1,isChromiumBased:!1};const n=wn.getParser(r),i=n.getPlatformType(!0),s="mobile"===i||"tablet"===i,o=n.getEngineName().toLowerCase(),a=null!==(t=n.satisfies({chrome:">=0",chromium:">=0","chromium webview":">=0",edge:">=0",opera:">=0","opera coast":">=0","samsung internet for android":">=0","yandex browser":">=0",electron:">=0"}))&&void 0!==t&&t;return{isMobile:s,isChromiumBased:"blink"===o||a&&"webkit"!==o}})();c||(yield this.network.createSignalingTransport(this.media.mediasoupDevice),yield this.network.createKeepAliveConsumer()),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)),d(this,Jg,"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})}catch(e){d(this,Jg,"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 _n("Device not supported",_n.UNSUPPORTED_DEVICE_CODE);if(e instanceof vn)throw e;throw new Tt("initialize_engine_error",e)}}))}release(e){return c(this,void 0,void 0,(function*(){var t;if(this.isReleasing)return;const r=this.myPeer.get(),n={case:"release",applicationId:this.state.appId,channelId:this.state.channelId,peerId:null!==(t=null==r?void 0:r.id)&&void 0!==t?t:this.myPeerId,peerRole:null==r?void 0:r.role,isJoined:this.state.isJoined,isChannelJoining:this.state.isChannelJoining,rejoinRequested:this.rejoinRequested};this.isReleasing=!0;const i=yield this.localMutex.lock(gn.Release);try{this.signalingApiClient.abortPendingRequests("release"),e||this.media.clearTracks(),yield Promise.all([Tn((()=>c(this,void 0,void 0,(function*(){return yield this.peers.reset()})))),Tn((()=>c(this,void 0,void 0,(function*(){return yield this.media.unpublishTracks()})))),Tn((()=>c(this,void 0,void 0,(function*(){return yield this.signalingApiClient.peers.disconnectPeer()}))))]),this.cleanup(),d(this,Jg,"f").debug("release()",n)}catch(e){d(this,Jg,"f").error("Failed to release",Object.assign(Object.assign({},n),{error:Pt(e)}))}finally{this.isReleasing=!1,i()}}))}getPeers(){return this.peers.all()}get myPeerId(){return this.myPeer.id}confirmActivity(){return c(this,void 0,void 0,(function*(){try{yield this.signalingApiClient.channel.confirmChannelActivity()}catch(e){throw new Tt("confirm_activity_failed",e)}}))}join(e){return c(this,void 0,void 0,(function*(){if(this.isChannelJoined)throw new Tt("method_not_available_when_joined");const t=yield this.localMutex.lock(gn.Join);try{d(this,Jg,"f").debug("join()",{params:e}),this.state.isChannelJoining=!0,this.signalingApiClient.abortPendingRequests("join"),this.signalingApiClient.setSecurityData({token:e.token,peerApiVersion:8,datacenterType:e.isP2pCall?"p2p":"common"});const{data:r,headers:n}=yield this.signalingApiClient.peers.registerPeer({appData:e.appData}),{appId:i,channelId:s,peerId:o}=r,a=String(n["x-datacenter-name"]),u=String(n["x-node-id"]);this.myPeer.id=o,this.state.appId=i,this.state.channelId=s,this.clientMetaProvider.setPeerId(o),this.clientMetaProvider.setChannelId(s),this.clientMetaProvider.setAppId(i),this.clientMetaProvider.setDatacenterName(a),this.clientMetaProvider.setNodeId(u),yield this.initialize(),yield this.network.waitForReceiveTransportConnected({onReceiveTransportFailed:()=>c(this,void 0,void 0,(function*(){yield this.networkTransportPolicyManager.escalateDirectionToRelay("recv")}))}),yield this.network.waitForChannelMessagesDataConsumerConnected(),this.state.isJoined=!0,this.networkTransportPolicyManager.startMonitoring(),d(this,Jg,"f").info("Successfully joined channel",{channelId:s,datacenterName:a})}catch(e){throw this.signalingApiClient.abortPendingRequests("join"),yield this.release(),d(this,Jg,"f").error("join()",{error:e}),new Tt("join_failed",e)}finally{this.state.isChannelJoining=!1,this.rejoinRequested=!1,t()}}))}loadPeers(e){return c(this,void 0,void 0,(function*(){try{yield this.peers.load(e)}catch(e){throw new Tt("load_peers_failed",e)}}))}requestChannelStateSync(){Mn((()=>c(this,void 0,void 0,(function*(){return yield new Promise(((e,t)=>c(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)?(d(this,Jg,"f").info("Channel state event received",{case:"Engine.requestChannelStateSync"}),e()):t(new Tt("channel_state_event_not_received",new Error("Channel state event not received")))}),5e3),i=()=>{clearTimeout(n),this.clientEventEmitter.off(Ar,i),e()};this.clientEventEmitter.on(Ar,i)}))))}))),{minBackoffDelayMs:0,maxBackoffDelayMs:0,maxRetries:10,actionName:"triggerChannelStateEventWithRetry",logger:d(this,Jg,"f")}).catch((e=>{d(this,Jg,"f").error("Failed to request channel state event",{case:"Engine.requestChannelStateSync",error:Pt(e)})}))}updateAppData(e){return c(this,void 0,void 0,(function*(){const t=this.myPeer.get();if(!t)throw new Tt("need_joined_to_channel",new Error("Need join to channel first"));try{bn(e)}catch(e){throw d(this,Jg,"f").error("updateAppData() validation failed",{error:e}),new Tt("invalid_app_data",e)}try{yield this.network.updatePeerAppData({peerId:t.id,appData:e})}catch(e){throw d(this,Jg,"f").error("updateAppData()",{error:e}),new Tt("update_app_data_failed",e)}}))}createCameraVideoTrack(e){return c(this,void 0,void 0,(function*(){const t=Sm.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 um&&(r.setLabel((null==e?void 0:e.isPreview)?Ln.CameraPreview:Ln.Camera),r.setEncoderConfig(t.encoderConfig),r.setTransformParams(Sm.getVideoTrackTransformParams(r.mediaStreamTrack))),this.media.setTrack(r),d(this,Jg,"f").debug("createCameraVideoTrack()",{trackParams:t}),r}catch(e){throw d(this,Jg,"f").error("createCameraVideoTrack()",{error:e,trackParams:t}),new Tt("create_camera_track_failed",e)}}))}createMicrophoneAudioTrack(e){return c(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)?Ln.MicrophonePreview:Ln.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()!==Ln.Microphone||d(this,Kg,"f")||this.media.initDenoiser(t,e).catch((t=>{this.clientEventEmitter.emit(jr,{cause:"Failed to initialize denoiser",error:t}),d(this,Jg,"f").error("Failed to execute initDenoiser",{case:"Denoiser",options:e,error:Pt(t)})})),this.media.setTrack(t),d(this,Jg,"f").debug("createMicrophoneAudioTrack()",{options:e,trackLabel:t.getLabel()}),t}catch(t){throw d(this,Jg,"f").error("createMicrophoneAudioTrack()",{error:t,options:e}),new Tt("create_microphone_track_failed",t)}}))}createScreenMediaTracks(e){return c(this,void 0,void 0,(function*(){const t=Sm.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=>{d(this,Jg,"f").error("Failed to unpublish screen track",{error:Pt(e)})}))}),{once:!0}),r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof um){r.setLabel(Ln.ScreenVideo),r.setEncoderConfig(t.encoderConfig);const e=Sm.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(e),this.media.setTrack(r),void d(this,Jg,"f").debug("createScreenMediaTrack()",{trackParams:t,transformParams:e,label:r.logCtx})}r.setLabel(Ln.ScreenAudio),(null==e?void 0:e.audioEncoderConfig)&&r.setEncoderConfig(e.audioEncoderConfig),this.media.setTrack(r),d(this,Jg,"f").debug("createScreenMediaTrack()",{trackParams:null==e?void 0:e.audio,encoderConfig:null==e?void 0:e.audioEncoderConfig})})),r}catch(e){throw d(this,Jg,"f").error("createScreenMediaTrack()",{error:e,trackParams:t}),new Tt("create_screen_tracks_failed",e)}}))}createCustomAudioTrack(e){if(!e.audioTrack)throw new Tt("missing_audio_track",new Error("options.audioTrack is required"));try{const t=this.media.createCustomMediaTrack(e.audioTrack,{audio:e.audio});return t.mediaStreamTrack.addEventListener("ended",(()=>{t.unpublish().catch((e=>{d(this,Jg,"f").error("Failed to unpublish custom audio track",{track:t,error:Pt(e)})}))}),{once:!0}),t.setStopTrackOnPause(Boolean(e.stopTrackOnPause)),t.setLabel(Ln.CustomAudio),e.audioEncoderConfig&&t.setEncoderConfig(e.audioEncoderConfig),this.media.setTrack(t),d(this,Jg,"f").debug("createCustomAudioTrack()",{trackParams:e.audio,encoderConfig:e.audioEncoderConfig}),t}catch(t){throw d(this,Jg,"f").error("createCustomAudioTrack()",{error:t,trackParams:e.audioTrack}),new Tt("create_custom_audio_track_failed",t)}}createCustomVideoTrack(e){const t=Sm.getScreenVideoTrackParams(e);if(!e.videoTrack)throw new Tt("missing_video_track",new Error("options.videoTrack is required"));try{const r=this.media.createCustomMediaTrack(e.videoTrack,{video:e.video});r.mediaStreamTrack.addEventListener("ended",(()=>{r.unpublish().catch((e=>{d(this,Jg,"f").error("Failed to unpublish custom video track",{track:r,error:Pt(e)})}))}),{once:!0}),r.mediaStreamTrack.contentHint="customVideo",r.setLabel(Ln.CustomVideo),r.setEncoderConfig(t.encoderConfig);const n=Sm.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(n),this.media.setTrack(r),d(this,Jg,"f").debug("createCustomVideoTrack()",{trackParams:t,transformParams:n,label:r.logCtx}),r}catch(e){throw d(this,Jg,"f").error("createCustomVideoTrack()",{error:e,trackParams:t}),new Tt("create_custom_video_track_failed",e)}}deleteTrack(e){return c(this,void 0,void 0,(function*(){try{yield this.media.deleteTrack(e)}catch(e){throw new Tt("delete_track_failed",e)}}))}transportsStats(){return this.transportsStatsProvider.getStats()}setSignalingServerUrl(e){if(this.isChannelJoined||this.rejoinRequested||this.state.isChannelJoining)throw new Tt("method_not_available_when_joined",new Error("Method not available when joined channel"));this.signalingApiClient.instance.defaults.baseURL=e}cleanup(){var e;this.signalingApiClient.abortPendingRequests("cleanup"),this.rejoinRequested=!1,u(this,Qg,!1,"f"),this.networkTransportPolicyManager.stopMonitoring(),this.state.reset(),this.network.reset(),this.peersStorage.clear(),this.transportsStatsProvider.clear(),this.statsHandler.clear(),this.integrationsService.reset(),null===(e=this.webRtcIssueDetector)||void 0===e||e.stopWatchingNewPeerConnections(),this.processorsCache.reset(),this.clientMetaProvider.clear()}watchInternalEvents(){this.internalEventEmitter.on(Vr,(e=>c(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.internalEventEmitter.on(Br,(e=>c(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=>{d(this,Jg,"f").debug("Failed to close peerTrack",{error:Pt(e)})})),yield this.media.deleteTrack(e)})))),this.internalEventEmitter.on(Wr,(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=>{d(this,Jg,"f").debug("Failed to pause peerTrack",{error:Pt(e)})}))})),this.internalEventEmitter.on(Hr,(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=>{d(this,Jg,"f").debug("Failed to resume peerTrack",{error:Pt(e)})}))})),this.internalEventEmitter.on(qr,(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=>{d(this,Jg,"f").debug("Failed to close peerTrack",{error:Pt(e)})}))})),this.internalEventEmitter.on(zr,(e=>c(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.internalEventEmitter.on(Gr,(e=>{this.clientEventEmitter.safeEmit(kr,{label:e.getLabel()})}))}createSelfPeerTrack(e){return c(this,void 0,void 0,(function*(){var t;if(!this.myPeer.id)return;const r=this.peers.get(this.myPeer.id);if(!r)return;yield null===(t=r.tracks.get(e.getLabel()))||void 0===t?void 0:t.close();const n=this.peerTrackFactory({label:e.getLabel(),mediaStreamTrack:e.mediaStreamTrack,muted:!1,paused:e.isPaused,onClose:()=>{},peerEventEmitter:r.observer});r.tracks.set(n.label,n)}))}triggerRejoinEventIfAppropriate(e){!this.isChannelJoined||this.isReleasing||this.state.isChannelJoining||this.rejoinRequested||(d(this,Jg,"f").debug("Triggering channel rejoin required event",{reason:e}),this.signalingApiClient.abortPendingRequests("channel-rejoin"),this.rejoinRequested=!0,this.clientEventEmitter.emit(Cr))}watchNetworkState(){this.network.observer.on(mn,(({state:e,direction:t})=>{if(!this.isReleasing&&(["disconnected","failed"].includes(e)&&this.isChannelJoined&&!d(this,Qg,"f")&&(u(this,Qg,!0,"f"),d(this,Jg,"f").info("connection lost",{channel:"webrtc-transport",direction:t}),this.clientEventEmitter.safeEmit(Ar)),"reconnected"===e&&this.isChannelJoined&&d(this,Jg,"f").info("connection restored",{channel:"webrtc-transport",direction:t}),"reconnected"===e&&this.isChannelJoined&&d(this,Qg,"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;u(this,Qg,!1,"f"),this.clientEventEmitter.safeEmit(Or),this.producerCloseManager.flushPending().catch((e=>{d(this,Jg,"f").warn("Failed to flush pending remote producers",{error:Pt(e)})}))}}))}watchDocumentUnload(){try{window.addEventListener("unload",(()=>{var e,t;null===(e=this.network.sendTransport)||void 0===e||e.close(),null===(t=this.network.receiveTransport)||void 0===t||t.close()}))}catch(e){d(this,Jg,"f").error("Failed to add watchDocumentUnload listener",{channelId:this.state.channelId,error:Pt(e)})}}};Jg=new WeakMap,Qg=new WeakMap,Kg=new WeakMap,Zg=s([ct(),o(0,ut(Nn.CallState)),o(1,ut(Nn.MyPeer)),o(2,ut(Nn.LoggerFactory)),o(3,ut(Nn.IntegrationsService)),o(4,ut(Nn.ProcessorsCache)),o(5,ut(Nn.MediaEventHandler)),o(6,ut(Nn.ChannelEventHandler)),o(7,ut(Nn.PeerTrackFactory)),o(8,ut(Nn.Peers)),o(9,ut(Nn.PeersStorage)),o(10,ut(Nn.System)),o(11,ut(Nn.Media)),o(12,ut(Nn.Network)),o(13,ut(Nn.NetworkTransportPolicyManager)),o(14,ut(Nn.ProducerCloseManager)),o(15,ut(Nn.SignalingApiClient)),o(16,ut(Nn.EventsQueue)),o(17,ut(Nn.ClientEventEmitter)),o(18,ut(Nn.InternalEventEmitter)),o(19,ut(Nn.StatsHandler)),o(20,ut(Nn.TransportsStatsProvider)),o(21,ut(Nn.LocalMutex)),o(22,ut(Nn.ScoresCalculator)),o(23,ut(Nn.ClientMetaProvider)),o(24,ut(Nn.WebRTCIssueDetector)),a("design:paramtypes",[Fn,Cs,Function,hf,uf,$m,Vm,Function,Object,Tc,Eg,Sm,Xc,cg,sg,bc,ws,wt,wt,Wg,qg,yg,$g,gr,ur])],Zg);var Xg=Zg,ev="undefined"!=typeof Symbol&&Symbol,tv=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},rv="Function.prototype.bind called on incompatible ",nv=Array.prototype.slice,iv=Object.prototype.toString,sv=function(e){var t=this;if("function"!=typeof t||"[object Function]"!==iv.call(t))throw new TypeError(rv+t);for(var r,n=nv.call(arguments,1),i=function(){if(this instanceof r){var i=t.apply(this,n.concat(nv.call(arguments)));return Object(i)===i?i:this}return t.apply(e,n.concat(nv.call(arguments)))},s=Math.max(0,t.length-n.length),o=[],a=0;a<s;a++)o.push("$"+a);if(r=Function("binder","return function ("+o.join(",")+"){ return binder.apply(this,arguments); }")(i),t.prototype){var c=function(){};c.prototype=t.prototype,r.prototype=new c,c.prototype=null}return r},ov=Function.prototype.bind||sv,av="Function.prototype.bind called on incompatible ",cv=Array.prototype.slice,dv=Object.prototype.toString,uv=function(e){var t=this;if("function"!=typeof t||"[object Function]"!==dv.call(t))throw new TypeError(av+t);for(var r,n=cv.call(arguments,1),i=function(){if(this instanceof r){var i=t.apply(this,n.concat(cv.call(arguments)));return Object(i)===i?i:this}return t.apply(e,n.concat(cv.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},lv=(Function.prototype.bind||uv).call(Function.call,Object.prototype.hasOwnProperty),pv=SyntaxError,hv=Function,fv=TypeError,mv=function(e){try{return hv('"use strict"; return ('+e+").constructor;")()}catch(e){}},gv=Object.getOwnPropertyDescriptor;if(gv)try{gv({},"")}catch(kt){gv=null}var vv=function(){throw new fv},yv=gv?function(){try{return vv}catch(e){try{return gv(arguments,"callee").get}catch(e){return vv}}}():vv,_v="function"==typeof ev&&"function"==typeof Symbol&&"symbol"==typeof ev("foo")&&"symbol"==typeof Symbol("bar")&&tv(),bv=Object.getPrototypeOf||function(e){return e.__proto__},Ev={},wv="undefined"==typeof Uint8Array?undefined:bv(Uint8Array),Sv={"%AggregateError%":"undefined"==typeof AggregateError?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":_v?bv([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":Ev,"%AsyncGenerator%":Ev,"%AsyncGeneratorFunction%":Ev,"%AsyncIteratorPrototype%":Ev,"%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%":hv,"%GeneratorFunction%":Ev,"%Int8Array%":"undefined"==typeof Int8Array?undefined:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":_v?bv(bv([][Symbol.iterator]())):undefined,"%JSON%":"object"==typeof JSON?JSON:undefined,"%Map%":"undefined"==typeof Map?undefined:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&_v?bv((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&&_v?bv((new Set)[Symbol.iterator]()):undefined,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":_v?bv(""[Symbol.iterator]()):undefined,"%Symbol%":_v?Symbol:undefined,"%SyntaxError%":pv,"%ThrowTypeError%":yv,"%TypedArray%":wv,"%TypeError%":fv,"%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},Cv=function e(t){var r;if("%AsyncFunction%"===t)r=mv("async function () {}");else if("%GeneratorFunction%"===t)r=mv("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=mv("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&(r=bv(i.prototype))}return Sv[t]=r,r},Pv={"%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"]},Tv=ov,Rv=lv,kv=Tv.call(Function.call,Array.prototype.concat),Dv=Tv.call(Function.apply,Array.prototype.splice),Iv=Tv.call(Function.call,String.prototype.replace),Av=Tv.call(Function.call,String.prototype.slice),Ov=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Mv=/\\(\\)?/g,Nv=function(e){var t=Av(e,0,1),r=Av(e,-1);if("%"===t&&"%"!==r)throw new pv("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new pv("invalid intrinsic syntax, expected opening `%`");var n=[];return Iv(e,Ov,(function(e,t,r,i){n[n.length]=r?Iv(i,Mv,"$1"):t||e})),n},Lv=function(e,t){var r,n=e;if(Rv(Pv,n)&&(n="%"+(r=Pv[n])[0]+"%"),Rv(Sv,n)){var i=Sv[n];if(i===Ev&&(i=Cv(n)),void 0===i&&!t)throw new fv("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:i}}throw new pv("intrinsic "+e+" does not exist!")},xv=function(e,t){if("string"!=typeof e||0===e.length)throw new fv("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new fv('"allowMissing" argument must be a boolean');var r=Nv(e),n=r.length>0?r[0]:"",i=Lv("%"+n+"%",t),s=i.name,o=i.value,a=!1,c=i.alias;c&&(n=c[0],Dv(r,kv([0,1],c)));for(var d=1,u=!0;d<r.length;d+=1){var l=r[d],p=Av(l,0,1),h=Av(l,-1);if(('"'===p||"'"===p||"`"===p||'"'===h||"'"===h||"`"===h)&&p!==h)throw new pv("property names with quotes must have matching quotes");if("constructor"!==l&&u||(a=!0),Rv(Sv,s="%"+(n+="."+l)+"%"))o=Sv[s];else if(null!=o){if(!(l in o)){if(!t)throw new fv("base intrinsic for "+e+" exists, but the property is not available.");return}if(gv&&d+1>=r.length){var f=gv(o,l);o=(u=!!f)&&"get"in f&&!("originalValue"in f.get)?f.get:o[l]}else u=Rv(o,l),o=o[l];u&&!a&&(Sv[s]=o)}}return o},Fv={exports:{}};!function(e){var t=ov,r=xv,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}(Fv);var jv=xv,Uv=Fv.exports,Vv=Uv(jv("String.prototype.indexOf")),Bv=f(Object.freeze({__proto__:null,default:{}})),Wv="function"==typeof Map&&Map.prototype,Hv=Object.getOwnPropertyDescriptor&&Wv?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,qv=Wv&&Hv&&"function"==typeof Hv.get?Hv.get:null,zv=Wv&&Map.prototype.forEach,Gv="function"==typeof Set&&Set.prototype,Yv=Object.getOwnPropertyDescriptor&&Gv?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,$v=Gv&&Yv&&"function"==typeof Yv.get?Yv.get:null,Jv=Gv&&Set.prototype.forEach,Qv="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,Kv="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,Zv="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,Xv=Boolean.prototype.valueOf,ey=Object.prototype.toString,ty=Function.prototype.toString,ry=String.prototype.match,ny="function"==typeof BigInt?BigInt.prototype.valueOf:null,iy=Object.getOwnPropertySymbols,sy="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,oy="function"==typeof Symbol&&"object"==typeof Symbol.iterator,ay=Object.prototype.propertyIsEnumerable,cy=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null),dy=Bv.custom,uy=dy&&my(dy)?dy:null,ly="function"==typeof Symbol&&void 0!==Symbol.toStringTag?Symbol.toStringTag:null;function py(e,t,r){var n="double"===(r.quoteStyle||t)?'"':"'";return n+e+n}function hy(e){return String(e).replace(/"/g,""")}function fy(e){return!("[object Array]"!==yy(e)||ly&&"object"==typeof e&&ly in e)}function my(e){if(oy)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!sy)return!1;try{return sy.call(e),!0}catch(e){}return!1}var gy=Object.prototype.hasOwnProperty||function(e){return e in this};function vy(e,t){return gy.call(e,t)}function yy(e){return ey.call(e)}function _y(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 by(e,t){if(e.length>t.maxStringLength){var r=e.length-t.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return by(e.slice(0,t.maxStringLength),t)+n}return py(e.replace(/(['\\])/g,"\\$1").replace(/[\x00-\x1f]/g,Ey),"single",t)}function Ey(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 wy(e){return"Object("+e+")"}function Sy(e){return e+" { ? }"}function Cy(e,t,r,n){return e+" ("+t+") {"+(n?Py(r,n):r.join(", "))+"}"}function Py(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+e.join(","+r)+"\n"+t.prev}function Ty(e,t){var r=fy(e),n=[];if(r){n.length=e.length;for(var i=0;i<e.length;i++)n[i]=vy(e,i)?t(e[i],e):""}var s,o="function"==typeof iy?iy(e):[];if(oy){s={};for(var a=0;a<o.length;a++)s["$"+o[a]]=o[a]}for(var c in e)vy(e,c)&&(r&&String(Number(c))===c&&c<e.length||oy&&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 iy)for(var d=0;d<o.length;d++)ay.call(e,o[d])&&n.push("["+t(o[d])+"]: "+t(e[o[d]],e));return n}var Ry=xv,ky=function(e,t){var r=jv(e,!!t);return"function"==typeof r&&Vv(e,".prototype.")>-1?Uv(r):r},Dy=function e(t,r,n,i){var s=r||{};if(vy(s,"quoteStyle")&&"single"!==s.quoteStyle&&"double"!==s.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(vy(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=!vy(s,"customInspect")||s.customInspect;if("boolean"!=typeof o&&"symbol"!==o)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(vy(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 by(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 fy(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(_y(i,t)>=0)return"[Circular]";function d(t,r,o){if(r&&(i=i.slice()).push(r),o){var a={depth:s.depth};return vy(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=ry.call(ty.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),l=Ty(t,d);return"[Function"+(u?": "+u:" (anonymous)")+"]"+(l.length>0?" { "+l.join(", ")+" }":"")}if(my(t)){var p=oy?String(t).replace(/^(Symbol\(.*\))_[^)]*$/,"$1"):sy.call(t);return"object"!=typeof t||oy?p:wy(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+"="+py(hy(f[m].value),"double",s);return h+=">",t.childNodes&&t.childNodes.length&&(h+="..."),h+="</"+String(t.nodeName).toLowerCase()+">"}if(fy(t)){if(0===t.length)return"[]";var g=Ty(t,d);return c&&!function(e){for(var t=0;t<e.length;t++)if(_y(e[t],"\n")>=0)return!1;return!0}(g)?"["+Py(g,c)+"]":"[ "+g.join(", ")+" ]"}if(function(e){return!("[object Error]"!==yy(e)||ly&&"object"==typeof e&&ly in e)}(t)){var v=Ty(t,d);return 0===v.length?"["+String(t)+"]":"{ ["+String(t)+"] "+v.join(", ")+" }"}if("object"==typeof t&&o){if(uy&&"function"==typeof t[uy])return t[uy]();if("symbol"!==o&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!qv||!e||"object"!=typeof e)return!1;try{qv.call(e);try{$v.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var y=[];return zv.call(t,(function(e,r){y.push(d(r,t,!0)+" => "+d(e,t))})),Cy("Map",qv.call(t),y,c)}if(function(e){if(!$v||!e||"object"!=typeof e)return!1;try{$v.call(e);try{qv.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var _=[];return Jv.call(t,(function(e){_.push(d(e,t))})),Cy("Set",$v.call(t),_,c)}if(function(e){if(!Qv||!e||"object"!=typeof e)return!1;try{Qv.call(e,Qv);try{Kv.call(e,Kv)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Sy("WeakMap");if(function(e){if(!Kv||!e||"object"!=typeof e)return!1;try{Kv.call(e,Kv);try{Qv.call(e,Qv)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Sy("WeakSet");if(function(e){if(!Zv||!e||"object"!=typeof e)return!1;try{return Zv.call(e),!0}catch(e){}return!1}(t))return Sy("WeakRef");if(function(e){return!("[object Number]"!==yy(e)||ly&&"object"==typeof e&&ly in e)}(t))return wy(d(Number(t)));if(function(e){if(!e||"object"!=typeof e||!ny)return!1;try{return ny.call(e),!0}catch(e){}return!1}(t))return wy(d(ny.call(t)));if(function(e){return!("[object Boolean]"!==yy(e)||ly&&"object"==typeof e&&ly in e)}(t))return wy(Xv.call(t));if(function(e){return!("[object String]"!==yy(e)||ly&&"object"==typeof e&&ly in e)}(t))return wy(d(String(t)));if(!function(e){return!("[object Date]"!==yy(e)||ly&&"object"==typeof e&&ly in e)}(t)&&!function(e){return!("[object RegExp]"!==yy(e)||ly&&"object"==typeof e&&ly in e)}(t)){var b=Ty(t,d),E=cy?cy(t)===Object.prototype:t instanceof Object||t.constructor===Object,w=t instanceof Object?"":"null prototype",S=!E&&ly&&Object(t)===t&&ly in t?yy(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+"{"+Py(b,c)+"}":C+"{ "+b.join(", ")+" }"}return String(t)},Iy=Ry("%TypeError%"),Ay=Ry("%WeakMap%",!0),Oy=Ry("%Map%",!0),My=ky("WeakMap.prototype.get",!0),Ny=ky("WeakMap.prototype.set",!0),Ly=ky("WeakMap.prototype.has",!0),xy=ky("Map.prototype.get",!0),Fy=ky("Map.prototype.set",!0),jy=ky("Map.prototype.has",!0),Uy=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},Vy=String.prototype.replace,By=/%20/g,Wy="RFC3986",Hy={default:Wy,formatters:{RFC1738:function(e){return Vy.call(e,By,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:Wy},qy=Hy,zy=Object.prototype.hasOwnProperty,Gy=Array.isArray,Yy=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),$y=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},Jy={arrayToObject:$y,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(Gy(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===qy.RFC1738&&(40===c||41===c)?o+=s.charAt(a):c<128?o+=Yy[c]:c<2048?o+=Yy[192|c>>6]+Yy[128|63&c]:c<55296||c>=57344?o+=Yy[224|c>>12]+Yy[128|c>>6&63]+Yy[128|63&c]:(a+=1,c=65536+((1023&c)<<10|1023&s.charCodeAt(a)),o+=Yy[240|c>>18]+Yy[128|c>>12&63]+Yy[128|c>>6&63]+Yy[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(Gy(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(Gy(t))t.push(r);else{if(!t||"object"!=typeof t)return[t,r];(n&&(n.plainObjects||n.allowPrototypes)||!zy.call(Object.prototype,r))&&(t[r]=!0)}return t}if(!t||"object"!=typeof t)return[t].concat(r);var i=t;return Gy(t)&&!Gy(r)&&(i=$y(t,n)),Gy(t)&&Gy(r)?(r.forEach((function(r,i){if(zy.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 zy.call(t,i)?t[i]=e(t[i],s,n):t[i]=s,t}),i)}},Qy=function(){var e,t,r,n={assert:function(e){if(!n.has(e))throw new Iy("Side channel does not contain "+Dy(e))},get:function(n){if(Ay&&n&&("object"==typeof n||"function"==typeof n)){if(e)return My(e,n)}else if(Oy){if(t)return xy(t,n)}else if(r)return function(e,t){var r=Uy(e,t);return r&&r.value}(r,n)},has:function(n){if(Ay&&n&&("object"==typeof n||"function"==typeof n)){if(e)return Ly(e,n)}else if(Oy){if(t)return jy(t,n)}else if(r)return function(e,t){return!!Uy(e,t)}(r,n);return!1},set:function(n,i){Ay&&n&&("object"==typeof n||"function"==typeof n)?(e||(e=new Ay),Ny(e,n,i)):Oy?(t||(t=new Oy),Fy(t,n,i)):(r||(r={key:{},next:null}),function(e,t,r){var n=Uy(e,t);n?n.value=r:e.next={key:t,next:e.next,value:r}}(r,n,i))}};return n},Ky=Jy,Zy=Hy,Xy=Object.prototype.hasOwnProperty,e_={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},t_=Array.isArray,r_=String.prototype.split,n_=Array.prototype.push,i_=function(e,t){n_.apply(e,t_(t)?t:[t])},s_=Date.prototype.toISOString,o_=Zy.default,a_={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:Ky.encode,encodeValuesOnly:!1,format:o_,formatter:Zy.formatters[o_],indices:!1,serializeDate:function(e){return s_.call(e)},skipNulls:!1,strictNullHandling:!1},c_={},d_=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(c_))&&!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(c_)&&(_=0)}if("function"==typeof c?v=c(r,v):v instanceof Date?v=l(v):"comma"===n&&t_(v)&&(v=Ky.maybeMap(v,(function(e){return e instanceof Date?l(e):e}))),null===v){if(s)return a&&!f?a(r,a_.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)||Ky.isBuffer(v)){if(a){var w=f?r:a(r,a_.encoder,m,"key",p);if("comma"===n&&f){for(var S=r_.call(String(v),","),C="",P=0;P<S.length;++P)C+=(0===P?"":",")+h(a(S[P],a_.encoder,m,"value",p));return[h(w)+(i&&t_(v)&&1===S.length?"[]":"")+"="+C]}return[h(w)+"="+h(a(v,a_.encoder,m,"value",p))]}return[h(r)+"="+h(String(v))]}var T,R=[];if(void 0===v)return R;if("comma"===n&&t_(v))T=[{value:v.length>0?v.join(",")||null:void 0}];else if(t_(c))T=c;else{var k=Object.keys(v);T=d?k.sort(d):k}for(var D=i&&t_(v)&&1===v.length?r+"[]":r,I=0;I<T.length;++I){var A=T[I],O="object"==typeof A&&void 0!==A.value?A.value:v[A];if(!o||null!==O){var M=t_(v)?"function"==typeof n?n(D,A):D:D+(u?"."+A:"["+A+"]");g.set(t,_);var N=Qy();N.set(c_,g),i_(R,e(O,M,n,i,s,o,a,c,d,u,l,p,h,f,m,N))}}return R},u_=Jy,l_=Object.prototype.hasOwnProperty,p_=Array.isArray,h_={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:u_.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},f_=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},m_=function(e,t){return e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1?e.split(","):e},g_=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&&l_.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&&l_.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:m_(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)}},v_=function(e,t){var r,n=e,i=function(e){if(!e)return a_;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||a_.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=Zy.default;if(void 0!==e.format){if(!Xy.call(Zy.formatters,e.format))throw new TypeError("Unknown format option provided.");r=e.format}var n=Zy.formatters[r],i=a_.filter;return("function"==typeof e.filter||t_(e.filter))&&(i=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:a_.addQueryPrefix,allowDots:void 0===e.allowDots?a_.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:a_.charsetSentinel,delimiter:void 0===e.delimiter?a_.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:a_.encode,encoder:"function"==typeof e.encoder?e.encoder:a_.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:a_.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:a_.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:a_.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:a_.strictNullHandling}}(t);"function"==typeof i.filter?n=(0,i.filter)("",n):t_(i.filter)&&(r=i.filter);var s,o=[];if("object"!=typeof n||null===n)return"";s=t&&t.arrayFormat in e_?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var a=e_[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=Qy(),u=0;u<r.length;++u){var l=r[u];i.skipNulls&&null===n[l]||i_(o,d_(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:""},y_=function(e,t){var r=function(e){if(!e)return h_;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?h_.charset:e.charset;return{allowDots:void 0===e.allowDots?h_.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:h_.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:h_.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:h_.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:h_.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:h_.comma,decoder:"function"==typeof e.decoder?e.decoder:h_.decoder,delimiter:"string"==typeof e.delimiter||u_.isRegExp(e.delimiter)?e.delimiter:h_.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:h_.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:h_.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:h_.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:h_.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:h_.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,h_.decoder,c,"key"),u=t.strictNullHandling?null:""):(d=t.decoder(l.slice(0,h),h_.decoder,c,"key"),u=u_.maybeMap(m_(l.slice(h+1),t),(function(e){return t.decoder(e,h_.decoder,c,"value")}))),u&&t.interpretNumericEntities&&"iso-8859-1"===c&&(u=f_(u)),l.indexOf("[]=")>-1&&(u=p_(u)?[u]:u),l_.call(n,d)?n[d]=u_.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=g_(a,n[a],r,"string"==typeof e);i=u_.merge(i,c,r)}return!0===r.allowSparse?i:u_.compact(i)},__={formats:Hy,parse:y_,stringify:v_};class b_{constructor(e){this.api=e,Fs(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 c(this,void 0,void 0,(function*(){yield this.api.post("/log/batch",e)}))}}class E_{constructor(e){this.api=e,Fs(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 c(this,void 0,void 0,(function*(){yield this.api.post("/analytics/network-metrics",e)}))}sendWIDMetrics(e){return c(this,void 0,void 0,(function*(){yield this.api.post("/analytics/wid-metrics",Object.assign({},e))}))}}let w_=class{constructor(){this.api=Za.create({baseURL:"https://moodhood-analytics.livedigital.space/v1",timeout:1e4,withCredentials:!0,paramsSerializer:e=>__.stringify(e),headers:{"x-cl-id":If()}}),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 b_(this.api),this.metricsApi=new E_(this.api)}get log(){return this.logApi}get metrics(){return this.metricsApi}};w_=s([ct(),a("design:paramtypes",[])],w_);var S_=w_,C_={exports:{}},P_=1e3,T_=60*P_,R_=60*T_,k_=24*R_,D_=7*k_,I_=365.25*k_,A_=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*I_;case"weeks":case"week":case"w":return r*D_;case"days":case"day":case"d":return r*k_;case"hours":case"hour":case"hrs":case"hr":case"h":return r*R_;case"minutes":case"minute":case"mins":case"min":case"m":return r*T_;case"seconds":case"second":case"secs":case"sec":case"s":return r*P_;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>=k_)return O_(e,t,k_,"day");if(t>=R_)return O_(e,t,R_,"hour");if(t>=T_)return O_(e,t,T_,"minute");if(t>=P_)return O_(e,t,P_,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=k_)return Math.round(e/k_)+"d";if(t>=R_)return Math.round(e/R_)+"h";if(t>=T_)return Math.round(e/T_)+"m";if(t>=P_)return Math.round(e/P_)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function O_(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}var M_=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=A_,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=M_(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(C_,C_.exports);var N_=C_.exports,L_={},x_={},F_={},j_={exports:{}};
|
|
30
30
|
/**
|
|
31
31
|
* @license
|
|
32
32
|
* Lodash <https://lodash.com/>
|