@vkontakte/calls-sdk 2.5.2-dev.75f890a.0 → 2.5.2-dev.92f2f89.0

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/calls-sdk.cjs.js CHANGED
@@ -1,15 +1,15 @@
1
1
  /**
2
- * @vkontakte/calls-sdk v2.5.2-dev.75f890a.0
3
- * Mon, 24 Jan 2022 11:47:27 GMT
2
+ * @vkontakte/calls-sdk v2.5.2-dev.92f2f89.0
3
+ * Fri, 28 Jan 2022 10:20:07 GMT
4
4
  * https://st.mycdn.me/static/callssdk/2-5-2/doc/
5
5
  */
6
6
 
7
- var oa=Object.create;var Rt=Object.defineProperty;var ca=Object.getOwnPropertyDescriptor;var da=Object.getOwnPropertyNames,gr=Object.getOwnPropertySymbols,pa=Object.getPrototypeOf,fr=Object.prototype.hasOwnProperty,la=Object.prototype.propertyIsEnumerable;var Sr=Math.pow,vr=(n,e,t)=>e in n?Rt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Er=(n,e)=>{for(var t in e||(e={}))fr.call(e,t)&&vr(n,t,e[t]);if(gr)for(var t of gr(e))la.call(e,t)&&vr(n,t,e[t]);return n};var Tr=n=>Rt(n,"__esModule",{value:!0});var hi=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),ua=(n,e)=>{Tr(n);for(var t in e)Rt(n,t,{get:e[t],enumerable:!0})},ha=(n,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of da(e))!fr.call(n,i)&&i!=="default"&&Rt(n,i,{get:()=>e[i],enumerable:!(t=ca(e,i))||t.enumerable});return n},Me=n=>ha(Tr(Rt(n!=null?oa(pa(n)):{},"default",n&&n.__esModule&&"default"in n?{get:()=>n.default,enumerable:!0}:{value:n,enumerable:!0})),n);var o=(n,e,t)=>new Promise((i,r)=>{var a=p=>{try{d(t.next(p))}catch(u){r(u)}},s=p=>{try{d(t.throw(p))}catch(u){r(u)}},d=p=>p.done?i(p.value):Promise.resolve(p.value).then(a,s);d((t=t.apply(n,e)).next())});var Zr=hi(jt=>{"use strict";jt.byteLength=Ta;jt.toByteArray=Ia;jt.fromByteArray=ba;var Fe=[],Ae=[],Ea=typeof Uint8Array!="undefined"?Uint8Array:Array,Ti="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Xe=0,Qr=Ti.length;Xe<Qr;++Xe)Fe[Xe]=Ti[Xe],Ae[Ti.charCodeAt(Xe)]=Xe;var Xe,Qr;Ae["-".charCodeAt(0)]=62;Ae["_".charCodeAt(0)]=63;function Xr(n){var e=n.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=n.indexOf("=");t===-1&&(t=e);var i=t===e?0:4-t%4;return[t,i]}function Ta(n){var e=Xr(n),t=e[0],i=e[1];return(t+i)*3/4-i}function Ca(n,e,t){return(e+t)*3/4-t}function Ia(n){var e,t=Xr(n),i=t[0],r=t[1],a=new Ea(Ca(n,i,r)),s=0,d=r>0?i-4:i,p;for(p=0;p<d;p+=4)e=Ae[n.charCodeAt(p)]<<18|Ae[n.charCodeAt(p+1)]<<12|Ae[n.charCodeAt(p+2)]<<6|Ae[n.charCodeAt(p+3)],a[s++]=e>>16&255,a[s++]=e>>8&255,a[s++]=e&255;return r===2&&(e=Ae[n.charCodeAt(p)]<<2|Ae[n.charCodeAt(p+1)]>>4,a[s++]=e&255),r===1&&(e=Ae[n.charCodeAt(p)]<<10|Ae[n.charCodeAt(p+1)]<<4|Ae[n.charCodeAt(p+2)]>>2,a[s++]=e>>8&255,a[s++]=e&255),a}function ya(n){return Fe[n>>18&63]+Fe[n>>12&63]+Fe[n>>6&63]+Fe[n&63]}function Ra(n,e,t){for(var i,r=[],a=e;a<t;a+=3)i=(n[a]<<16&16711680)+(n[a+1]<<8&65280)+(n[a+2]&255),r.push(ya(i));return r.join("")}function ba(n){for(var e,t=n.length,i=t%3,r=[],a=16383,s=0,d=t-i;s<d;s+=a)r.push(Ra(n,s,s+a>d?d:s+a));return i===1?(e=n[t-1],r.push(Fe[e>>2]+Fe[e<<4&63]+"==")):i===2&&(e=(n[t-2]<<8)+n[t-1],r.push(Fe[e>>10]+Fe[e>>4&63]+Fe[e<<2&63]+"=")),r.join("")}});var en=hi(Ci=>{Ci.read=function(n,e,t,i,r){var a,s,d=r*8-i-1,p=(1<<d)-1,u=p>>1,_=-7,f=t?r-1:0,W=t?-1:1,K=n[e+f];for(f+=W,a=K&(1<<-_)-1,K>>=-_,_+=d;_>0;a=a*256+n[e+f],f+=W,_-=8);for(s=a&(1<<-_)-1,a>>=-_,_+=i;_>0;s=s*256+n[e+f],f+=W,_-=8);if(a===0)a=1-u;else{if(a===p)return s?NaN:(K?-1:1)*(1/0);s=s+Math.pow(2,i),a=a-u}return(K?-1:1)*s*Math.pow(2,a-i)};Ci.write=function(n,e,t,i,r,a){var s,d,p,u=a*8-r-1,_=(1<<u)-1,f=_>>1,W=r===23?Math.pow(2,-24)-Math.pow(2,-77):0,K=i?0:a-1,k=i?1:-1,Y=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(d=isNaN(e)?1:0,s=_):(s=Math.floor(Math.log(e)/Math.LN2),e*(p=Math.pow(2,-s))<1&&(s--,p*=2),s+f>=1?e+=W/p:e+=W*Math.pow(2,1-f),e*p>=2&&(s++,p/=2),s+f>=_?(d=0,s=_):s+f>=1?(d=(e*p-1)*Math.pow(2,r),s=s+f):(d=e*Math.pow(2,f-1)*Math.pow(2,r),s=0));r>=8;n[t+K]=d&255,K+=k,d/=256,r-=8);for(s=s<<r|d,u+=r;u>0;n[t+K]=s&255,K+=k,s/=256,u-=8);n[t+K-k]|=Y*128}});var Di=hi(_t=>{"use strict";var Ii=Zr(),mt=en(),tn=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;_t.Buffer=h;_t.SlowBuffer=Oa;_t.INSPECT_MAX_BYTES=50;var Kt=2147483647;_t.kMaxLength=Kt;h.TYPED_ARRAY_SUPPORT=Pa();!h.TYPED_ARRAY_SUPPORT&&typeof console!="undefined"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function Pa(){try{var n=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(n,e),n.foo()===42}catch(t){return!1}}Object.defineProperty(h.prototype,"parent",{enumerable:!0,get:function(){if(!!h.isBuffer(this))return this.buffer}});Object.defineProperty(h.prototype,"offset",{enumerable:!0,get:function(){if(!!h.isBuffer(this))return this.byteOffset}});function Ke(n){if(n>Kt)throw new RangeError('The value "'+n+'" is invalid for option "size"');var e=new Uint8Array(n);return Object.setPrototypeOf(e,h.prototype),e}function h(n,e,t){if(typeof n=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return yi(n)}return rn(n,e,t)}h.poolSize=8192;function rn(n,e,t){if(typeof n=="string")return Aa(n,e);if(ArrayBuffer.isView(n))return Da(n);if(n==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof n);if(Ve(n,ArrayBuffer)||n&&Ve(n.buffer,ArrayBuffer)||typeof SharedArrayBuffer!="undefined"&&(Ve(n,SharedArrayBuffer)||n&&Ve(n.buffer,SharedArrayBuffer)))return bi(n,e,t);if(typeof n=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var i=n.valueOf&&n.valueOf();if(i!=null&&i!==n)return h.from(i,e,t);var r=wa(n);if(r)return r;if(typeof Symbol!="undefined"&&Symbol.toPrimitive!=null&&typeof n[Symbol.toPrimitive]=="function")return h.from(n[Symbol.toPrimitive]("string"),e,t);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof n)}h.from=function(n,e,t){return rn(n,e,t)};Object.setPrototypeOf(h.prototype,Uint8Array.prototype);Object.setPrototypeOf(h,Uint8Array);function nn(n){if(typeof n!="number")throw new TypeError('"size" argument must be of type number');if(n<0)throw new RangeError('The value "'+n+'" is invalid for option "size"')}function Ma(n,e,t){return nn(n),n<=0?Ke(n):e!==void 0?typeof t=="string"?Ke(n).fill(e,t):Ke(n).fill(e):Ke(n)}h.alloc=function(n,e,t){return Ma(n,e,t)};function yi(n){return nn(n),Ke(n<0?0:Pi(n)|0)}h.allocUnsafe=function(n){return yi(n)};h.allocUnsafeSlow=function(n){return yi(n)};function Aa(n,e){if((typeof e!="string"||e==="")&&(e="utf8"),!h.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var t=an(n,e)|0,i=Ke(t),r=i.write(n,e);return r!==t&&(i=i.slice(0,r)),i}function Ri(n){for(var e=n.length<0?0:Pi(n.length)|0,t=Ke(e),i=0;i<e;i+=1)t[i]=n[i]&255;return t}function Da(n){if(Ve(n,Uint8Array)){var e=new Uint8Array(n);return bi(e.buffer,e.byteOffset,e.byteLength)}return Ri(n)}function bi(n,e,t){if(e<0||n.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(n.byteLength<e+(t||0))throw new RangeError('"length" is outside of buffer bounds');var i;return e===void 0&&t===void 0?i=new Uint8Array(n):t===void 0?i=new Uint8Array(n,e):i=new Uint8Array(n,e,t),Object.setPrototypeOf(i,h.prototype),i}function wa(n){if(h.isBuffer(n)){var e=Pi(n.length)|0,t=Ke(e);return t.length===0||n.copy(t,0,0,e),t}if(n.length!==void 0)return typeof n.length!="number"||Ai(n.length)?Ke(0):Ri(n);if(n.type==="Buffer"&&Array.isArray(n.data))return Ri(n.data)}function Pi(n){if(n>=Kt)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Kt.toString(16)+" bytes");return n|0}function Oa(n){return+n!=n&&(n=0),h.alloc(+n)}h.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==h.prototype};h.compare=function(e,t){if(Ve(e,Uint8Array)&&(e=h.from(e,e.offset,e.byteLength)),Ve(t,Uint8Array)&&(t=h.from(t,t.offset,t.byteLength)),!h.isBuffer(e)||!h.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var i=e.length,r=t.length,a=0,s=Math.min(i,r);a<s;++a)if(e[a]!==t[a]){i=e[a],r=t[a];break}return i<r?-1:r<i?1:0};h.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};h.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return h.alloc(0);var i;if(t===void 0)for(t=0,i=0;i<e.length;++i)t+=e[i].length;var r=h.allocUnsafe(t),a=0;for(i=0;i<e.length;++i){var s=e[i];if(Ve(s,Uint8Array))a+s.length>r.length?h.from(s).copy(r,a):Uint8Array.prototype.set.call(r,s,a);else if(h.isBuffer(s))s.copy(r,a);else throw new TypeError('"list" argument must be an Array of Buffers');a+=s.length}return r};function an(n,e){if(h.isBuffer(n))return n.length;if(ArrayBuffer.isView(n)||Ve(n,ArrayBuffer))return n.byteLength;if(typeof n!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof n);var t=n.length,i=arguments.length>2&&arguments[2]===!0;if(!i&&t===0)return 0;for(var r=!1;;)switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":return Mi(n).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"base64":return hn(n).length;default:if(r)return i?-1:Mi(n).length;e=(""+e).toLowerCase(),r=!0}}h.byteLength=an;function ka(n,e,t){var i=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return"";for(n||(n="utf8");;)switch(n){case"hex":return Wa(this,e,t);case"utf8":case"utf-8":return cn(this,e,t);case"ascii":return Ha(this,e,t);case"latin1":case"binary":return Ga(this,e,t);case"base64":return Fa(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ja(this,e,t);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(n+"").toLowerCase(),i=!0}}h.prototype._isBuffer=!0;function Ze(n,e,t){var i=n[e];n[e]=n[t],n[t]=i}h.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)Ze(this,t,t+1);return this};h.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)Ze(this,t,t+3),Ze(this,t+1,t+2);return this};h.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)Ze(this,t,t+7),Ze(this,t+1,t+6),Ze(this,t+2,t+5),Ze(this,t+3,t+4);return this};h.prototype.toString=function(){var e=this.length;return e===0?"":arguments.length===0?cn(this,0,e):ka.apply(this,arguments)};h.prototype.toLocaleString=h.prototype.toString;h.prototype.equals=function(e){if(!h.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:h.compare(this,e)===0};h.prototype.inspect=function(){var e="",t=_t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"};tn&&(h.prototype[tn]=h.prototype.inspect);h.prototype.compare=function(e,t,i,r,a){if(Ve(e,Uint8Array)&&(e=h.from(e,e.offset,e.byteLength)),!h.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(t===void 0&&(t=0),i===void 0&&(i=e?e.length:0),r===void 0&&(r=0),a===void 0&&(a=this.length),t<0||i>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=i)return 0;if(r>=a)return-1;if(t>=i)return 1;if(t>>>=0,i>>>=0,r>>>=0,a>>>=0,this===e)return 0;for(var s=a-r,d=i-t,p=Math.min(s,d),u=this.slice(r,a),_=e.slice(t,i),f=0;f<p;++f)if(u[f]!==_[f]){s=u[f],d=_[f];break}return s<d?-1:d<s?1:0};function sn(n,e,t,i,r){if(n.length===0)return-1;if(typeof t=="string"?(i=t,t=0):t>2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,Ai(t)&&(t=r?0:n.length-1),t<0&&(t=n.length+t),t>=n.length){if(r)return-1;t=n.length-1}else if(t<0)if(r)t=0;else return-1;if(typeof e=="string"&&(e=h.from(e,i)),h.isBuffer(e))return e.length===0?-1:on(n,e,t,i,r);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?r?Uint8Array.prototype.indexOf.call(n,e,t):Uint8Array.prototype.lastIndexOf.call(n,e,t):on(n,[e],t,i,r);throw new TypeError("val must be string, number or Buffer")}function on(n,e,t,i,r){var a=1,s=n.length,d=e.length;if(i!==void 0&&(i=String(i).toLowerCase(),i==="ucs2"||i==="ucs-2"||i==="utf16le"||i==="utf-16le")){if(n.length<2||e.length<2)return-1;a=2,s/=2,d/=2,t/=2}function p(K,k){return a===1?K[k]:K.readUInt16BE(k*a)}var u;if(r){var _=-1;for(u=t;u<s;u++)if(p(n,u)===p(e,_===-1?0:u-_)){if(_===-1&&(_=u),u-_+1===d)return _*a}else _!==-1&&(u-=u-_),_=-1}else for(t+d>s&&(t=s-d),u=t;u>=0;u--){for(var f=!0,W=0;W<d;W++)if(p(n,u+W)!==p(e,W)){f=!1;break}if(f)return u}return-1}h.prototype.includes=function(e,t,i){return this.indexOf(e,t,i)!==-1};h.prototype.indexOf=function(e,t,i){return sn(this,e,t,i,!0)};h.prototype.lastIndexOf=function(e,t,i){return sn(this,e,t,i,!1)};function xa(n,e,t,i){t=Number(t)||0;var r=n.length-t;i?(i=Number(i),i>r&&(i=r)):i=r;var a=e.length;i>a/2&&(i=a/2);for(var s=0;s<i;++s){var d=parseInt(e.substr(s*2,2),16);if(Ai(d))return s;n[t+s]=d}return s}function Na(n,e,t,i){return $t(Mi(e,n.length-t),n,t,i)}function La(n,e,t,i){return $t(qa(e),n,t,i)}function Ua(n,e,t,i){return $t(hn(e),n,t,i)}function Ba(n,e,t,i){return $t(Ja(e,n.length-t),n,t,i)}h.prototype.write=function(e,t,i,r){if(t===void 0)r="utf8",i=this.length,t=0;else if(i===void 0&&typeof t=="string")r=t,i=this.length,t=0;else if(isFinite(t))t=t>>>0,isFinite(i)?(i=i>>>0,r===void 0&&(r="utf8")):(r=i,i=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var a=this.length-t;if((i===void 0||i>a)&&(i=a),e.length>0&&(i<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return xa(this,e,t,i);case"utf8":case"utf-8":return Na(this,e,t,i);case"ascii":case"latin1":case"binary":return La(this,e,t,i);case"base64":return Ua(this,e,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ba(this,e,t,i);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}};h.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Fa(n,e,t){return e===0&&t===n.length?Ii.fromByteArray(n):Ii.fromByteArray(n.slice(e,t))}function cn(n,e,t){t=Math.min(n.length,t);for(var i=[],r=e;r<t;){var a=n[r],s=null,d=a>239?4:a>223?3:a>191?2:1;if(r+d<=t){var p,u,_,f;switch(d){case 1:a<128&&(s=a);break;case 2:p=n[r+1],(p&192)==128&&(f=(a&31)<<6|p&63,f>127&&(s=f));break;case 3:p=n[r+1],u=n[r+2],(p&192)==128&&(u&192)==128&&(f=(a&15)<<12|(p&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:p=n[r+1],u=n[r+2],_=n[r+3],(p&192)==128&&(u&192)==128&&(_&192)==128&&(f=(a&15)<<18|(p&63)<<12|(u&63)<<6|_&63,f>65535&&f<1114112&&(s=f))}}s===null?(s=65533,d=1):s>65535&&(s-=65536,i.push(s>>>10&1023|55296),s=56320|s&1023),i.push(s),r+=d}return Va(i)}var dn=4096;function Va(n){var e=n.length;if(e<=dn)return String.fromCharCode.apply(String,n);for(var t="",i=0;i<e;)t+=String.fromCharCode.apply(String,n.slice(i,i+=dn));return t}function Ha(n,e,t){var i="";t=Math.min(n.length,t);for(var r=e;r<t;++r)i+=String.fromCharCode(n[r]&127);return i}function Ga(n,e,t){var i="";t=Math.min(n.length,t);for(var r=e;r<t;++r)i+=String.fromCharCode(n[r]);return i}function Wa(n,e,t){var i=n.length;(!e||e<0)&&(e=0),(!t||t<0||t>i)&&(t=i);for(var r="",a=e;a<t;++a)r+=Ya[n[a]];return r}function ja(n,e,t){for(var i=n.slice(e,t),r="",a=0;a<i.length-1;a+=2)r+=String.fromCharCode(i[a]+i[a+1]*256);return r}h.prototype.slice=function(e,t){var i=this.length;e=~~e,t=t===void 0?i:~~t,e<0?(e+=i,e<0&&(e=0)):e>i&&(e=i),t<0?(t+=i,t<0&&(t=0)):t>i&&(t=i),t<e&&(t=e);var r=this.subarray(e,t);return Object.setPrototypeOf(r,h.prototype),r};function ge(n,e,t){if(n%1!=0||n<0)throw new RangeError("offset is not uint");if(n+e>t)throw new RangeError("Trying to access beyond buffer length")}h.prototype.readUintLE=h.prototype.readUIntLE=function(e,t,i){e=e>>>0,t=t>>>0,i||ge(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r};h.prototype.readUintBE=h.prototype.readUIntBE=function(e,t,i){e=e>>>0,t=t>>>0,i||ge(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r};h.prototype.readUint8=h.prototype.readUInt8=function(e,t){return e=e>>>0,t||ge(e,1,this.length),this[e]};h.prototype.readUint16LE=h.prototype.readUInt16LE=function(e,t){return e=e>>>0,t||ge(e,2,this.length),this[e]|this[e+1]<<8};h.prototype.readUint16BE=h.prototype.readUInt16BE=function(e,t){return e=e>>>0,t||ge(e,2,this.length),this[e]<<8|this[e+1]};h.prototype.readUint32LE=h.prototype.readUInt32LE=function(e,t){return e=e>>>0,t||ge(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};h.prototype.readUint32BE=h.prototype.readUInt32BE=function(e,t){return e=e>>>0,t||ge(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};h.prototype.readIntLE=function(e,t,i){e=e>>>0,t=t>>>0,i||ge(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return a*=128,r>=a&&(r-=Math.pow(2,8*t)),r};h.prototype.readIntBE=function(e,t,i){e=e>>>0,t=t>>>0,i||ge(e,t,this.length);for(var r=t,a=1,s=this[e+--r];r>0&&(a*=256);)s+=this[e+--r]*a;return a*=128,s>=a&&(s-=Math.pow(2,8*t)),s};h.prototype.readInt8=function(e,t){return e=e>>>0,t||ge(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};h.prototype.readInt16LE=function(e,t){e=e>>>0,t||ge(e,2,this.length);var i=this[e]|this[e+1]<<8;return i&32768?i|4294901760:i};h.prototype.readInt16BE=function(e,t){e=e>>>0,t||ge(e,2,this.length);var i=this[e+1]|this[e]<<8;return i&32768?i|4294901760:i};h.prototype.readInt32LE=function(e,t){return e=e>>>0,t||ge(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};h.prototype.readInt32BE=function(e,t){return e=e>>>0,t||ge(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};h.prototype.readFloatLE=function(e,t){return e=e>>>0,t||ge(e,4,this.length),mt.read(this,e,!0,23,4)};h.prototype.readFloatBE=function(e,t){return e=e>>>0,t||ge(e,4,this.length),mt.read(this,e,!1,23,4)};h.prototype.readDoubleLE=function(e,t){return e=e>>>0,t||ge(e,8,this.length),mt.read(this,e,!0,52,8)};h.prototype.readDoubleBE=function(e,t){return e=e>>>0,t||ge(e,8,this.length),mt.read(this,e,!1,52,8)};function Te(n,e,t,i,r,a){if(!h.isBuffer(n))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>r||e<a)throw new RangeError('"value" argument is out of bounds');if(t+i>n.length)throw new RangeError("Index out of range")}h.prototype.writeUintLE=h.prototype.writeUIntLE=function(e,t,i,r){if(e=+e,t=t>>>0,i=i>>>0,!r){var a=Math.pow(2,8*i)-1;Te(this,e,t,i,a,0)}var s=1,d=0;for(this[t]=e&255;++d<i&&(s*=256);)this[t+d]=e/s&255;return t+i};h.prototype.writeUintBE=h.prototype.writeUIntBE=function(e,t,i,r){if(e=+e,t=t>>>0,i=i>>>0,!r){var a=Math.pow(2,8*i)-1;Te(this,e,t,i,a,0)}var s=i-1,d=1;for(this[t+s]=e&255;--s>=0&&(d*=256);)this[t+s]=e/d&255;return t+i};h.prototype.writeUint8=h.prototype.writeUInt8=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,1,255,0),this[t]=e&255,t+1};h.prototype.writeUint16LE=h.prototype.writeUInt16LE=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2};h.prototype.writeUint16BE=h.prototype.writeUInt16BE=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2};h.prototype.writeUint32LE=h.prototype.writeUInt32LE=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4};h.prototype.writeUint32BE=h.prototype.writeUInt32BE=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};h.prototype.writeIntLE=function(e,t,i,r){if(e=+e,t=t>>>0,!r){var a=Math.pow(2,8*i-1);Te(this,e,t,i,a-1,-a)}var s=0,d=1,p=0;for(this[t]=e&255;++s<i&&(d*=256);)e<0&&p===0&&this[t+s-1]!==0&&(p=1),this[t+s]=(e/d>>0)-p&255;return t+i};h.prototype.writeIntBE=function(e,t,i,r){if(e=+e,t=t>>>0,!r){var a=Math.pow(2,8*i-1);Te(this,e,t,i,a-1,-a)}var s=i-1,d=1,p=0;for(this[t+s]=e&255;--s>=0&&(d*=256);)e<0&&p===0&&this[t+s+1]!==0&&(p=1),this[t+s]=(e/d>>0)-p&255;return t+i};h.prototype.writeInt8=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1};h.prototype.writeInt16LE=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2};h.prototype.writeInt16BE=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2};h.prototype.writeInt32LE=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4};h.prototype.writeInt32BE=function(e,t,i){return e=+e,t=t>>>0,i||Te(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function pn(n,e,t,i,r,a){if(t+i>n.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function ln(n,e,t,i,r){return e=+e,t=t>>>0,r||pn(n,e,t,4,34028234663852886e22,-34028234663852886e22),mt.write(n,e,t,i,23,4),t+4}h.prototype.writeFloatLE=function(e,t,i){return ln(this,e,t,!0,i)};h.prototype.writeFloatBE=function(e,t,i){return ln(this,e,t,!1,i)};function un(n,e,t,i,r){return e=+e,t=t>>>0,r||pn(n,e,t,8,17976931348623157e292,-17976931348623157e292),mt.write(n,e,t,i,52,8),t+8}h.prototype.writeDoubleLE=function(e,t,i){return un(this,e,t,!0,i)};h.prototype.writeDoubleBE=function(e,t,i){return un(this,e,t,!1,i)};h.prototype.copy=function(e,t,i,r){if(!h.isBuffer(e))throw new TypeError("argument should be a Buffer");if(i||(i=0),!r&&r!==0&&(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<i&&(r=i),r===i||e.length===0||this.length===0)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-i&&(r=e.length-t+i);var a=r-i;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(t,i,r):Uint8Array.prototype.set.call(e,this.subarray(i,r),t),a};h.prototype.fill=function(e,t,i,r){if(typeof e=="string"){if(typeof t=="string"?(r=t,t=0,i=this.length):typeof i=="string"&&(r=i,i=this.length),r!==void 0&&typeof r!="string")throw new TypeError("encoding must be a string");if(typeof r=="string"&&!h.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(e.length===1){var a=e.charCodeAt(0);(r==="utf8"&&a<128||r==="latin1")&&(e=a)}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(t<0||this.length<t||this.length<i)throw new RangeError("Out of range index");if(i<=t)return this;t=t>>>0,i=i===void 0?this.length:i>>>0,e||(e=0);var s;if(typeof e=="number")for(s=t;s<i;++s)this[s]=e;else{var d=h.isBuffer(e)?e:h.from(e,r),p=d.length;if(p===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<i-t;++s)this[s+t]=d[s%p]}return this};var Ka=/[^+/0-9A-Za-z-_]/g;function $a(n){if(n=n.split("=")[0],n=n.trim().replace(Ka,""),n.length<2)return"";for(;n.length%4!=0;)n=n+"=";return n}function Mi(n,e){e=e||1/0;for(var t,i=n.length,r=null,a=[],s=0;s<i;++s){if(t=n.charCodeAt(s),t>55295&&t<57344){if(!r){if(t>56319){(e-=3)>-1&&a.push(239,191,189);continue}else if(s+1===i){(e-=3)>-1&&a.push(239,191,189);continue}r=t;continue}if(t<56320){(e-=3)>-1&&a.push(239,191,189),r=t;continue}t=(r-55296<<10|t-56320)+65536}else r&&(e-=3)>-1&&a.push(239,191,189);if(r=null,t<128){if((e-=1)<0)break;a.push(t)}else if(t<2048){if((e-=2)<0)break;a.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;a.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;a.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return a}function qa(n){for(var e=[],t=0;t<n.length;++t)e.push(n.charCodeAt(t)&255);return e}function Ja(n,e){for(var t,i,r,a=[],s=0;s<n.length&&!((e-=2)<0);++s)t=n.charCodeAt(s),i=t>>8,r=t%256,a.push(r),a.push(i);return a}function hn(n){return Ii.toByteArray($a(n))}function $t(n,e,t,i){for(var r=0;r<i&&!(r+t>=e.length||r>=n.length);++r)e[r+t]=n[r];return r}function Ve(n,e){return n instanceof e||n!=null&&n.constructor!=null&&n.constructor.name!=null&&n.constructor.name===e.name}function Ai(n){return n!==n}var Ya=function(){for(var n="0123456789abcdef",e=new Array(256),t=0;t<16;++t)for(var i=t*16,r=0;r<16;++r)e[i+r]=n[t]+n[r];return e}()});ua(exports,{Api:()=>Ft,BaseApi:()=>pt,BaseLogger:()=>lt,BaseSignaling:()=>ut,CallDirection:()=>We,CallType:()=>Le,ChatRoomEventType:()=>Ht,ConversationOption:()=>Gt,DebugMessageType:()=>tr,ExternalIdType:()=>nt,FacingMode:()=>ji,FatalError:()=>ne,HangupReason:()=>x,HangupType:()=>P,MediaOption:()=>le,MediaTrackKind:()=>me,MediaType:()=>Ce,MuteState:()=>je,ParticipantState:()=>j,ParticipantStatus:()=>J,RecordRole:()=>qn,Signaling:()=>xe,SignalingCommandType:()=>G,SignalingConnectionType:()=>Ue,SignalingNotification:()=>O,UserRole:()=>Ye,UserType:()=>X,Utils:()=>T,acceptCall:()=>Js,addMovie:()=>Ao,addParticipant:()=>Zs,addParticipantInternal:()=>Zn,apiCall:()=>$s,authorize:()=>qs,browser:()=>Fs,callInternal:()=>zn,callTo:()=>Ws,captureScreen:()=>io,changeConversationOptions:()=>_o,changeDevice:()=>to,changeParticipantState:()=>co,changePriorities:()=>oo,changeVideoEffect:()=>No,chatHistory:()=>fo,chatMessage:()=>go,chatMessageInternal:()=>na,createJoinLink:()=>Eo,customData:()=>So,customDataInternal:()=>aa,debug:()=>ko,debugMessage:()=>xo,declineCall:()=>Ys,forceRelayPolicy:()=>yo,getAnonymTokenByLink:()=>Co,getCurrentConversation:()=>Vo,getStreamInfo:()=>Mo,getTokenForAnonym:()=>Ks,getWaitingHall:()=>Uo,grantRoles:()=>lo,grantRolesInternal:()=>ta,hangup:()=>Xs,init:()=>Gs,joinCall:()=>zs,joinCallByLink:()=>Qs,joinCallInternal:()=>Xn,muteParticipant:()=>uo,muteParticipantInternal:()=>ia,pinParticipant:()=>ho,pinParticipantInternal:()=>ra,processPush:()=>js,processPushInternal:()=>Qn,promoteParticipant:()=>Bo,recordSetRole:()=>Po,removeHistoryRecords:()=>Fo,removeJoinLink:()=>To,removeMovie:()=>wo,removeParticipant:()=>eo,removeParticipantInternal:()=>ea,setApi:()=>Jn,setAudioStream:()=>Lo,setLocalResolution:()=>so,setLogger:()=>Vs,setMediaModifiers:()=>mo,setSignalingFactory:()=>Yn,setStatisticsInterval:()=>Oo,setVideoEffects:()=>Hs,setVideoStream:()=>ro,setVolume:()=>Io,startConversation:()=>vo,startStream:()=>Ro,stopStream:()=>bo,toggleLocalAudio:()=>ao,toggleLocalVideo:()=>no,updateDisplayLayout:()=>po,updateMovie:()=>Do});var hr=Me(require("webrtc-adapter"));var pt=class{createJoinLink(e){return o(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return o(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return o(this,null,function*(){return""})}log(e){}prepareUserIds(e){return o(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return o(this,null,function*(){})}cleanup(){}getTokenForAnonym(e,t){return o(this,null,function*(){return""})}call(i){return o(this,arguments,function*(e,t={}){return null})}};var lt=class{log(e,t,i=!1){}destroy(){}};var Q=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(e,...t){if(!!this._handlers.hasOwnProperty(e))for(let i of this._handlers[e])i.apply(this,t)}addEventListener(e,t){if(typeof t!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(e)||(this._handlers[e]=[]),this._handlers[e].push(t),{dispose:this.removeEventListener.bind(this,e,t)}}removeEventListener(e,t){if(!this._handlers.hasOwnProperty(e))return;t||delete this._handlers[e];let i=this._handlers[e].indexOf(t);i>=0&&this._handlers[e].splice(i,1)}subscribe(e,t,i){let r=e.addEventListener(t,i);this._listeners.push(r)}unsubscribe(){this._listeners.forEach(e=>{e.dispose()})}};var ut=class extends Q{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e){}getNextCommandSequenceNumber(){return 0}};var Cr=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))(Cr||{}),We=Cr;var Ir=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(Ir||{}),Le=Ir;var yr=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(yr||{}),Ht=yr;var Rr=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t))(Rr||{}),br=Rr;var Pr=(i=>(i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL",i))(Pr||{}),Gt=Pr;function Mr(n,e){if(n.length!==e.length)return!1;for(let t of n)if(!e.includes(t))return!1;return!0}function Ar(n,e){let t=new Set(n);for(let[i,r]of Object.entries(e))r?t.add(i):t.delete(i);return Array.from(t)}var Dr=(k=>(k.CAMERA_PERMISSION="camera",k.MIC_PERMISSION="mic",k.CAMERA_ACCESS="cameralock",k.MIC_ACCESS="miclock",k.MIC_NOT_FOUND="nomic",k.SCREEN_PERMISSION="screenpermission",k.SCREEN_ACCESS="screenlock",k.CONNECTION="connection",k.NETWORK="network",k.UNKNOWN="unknown",k.UNSUPPORTED="unsupported",k.SIGNALING_FAILED="signalingfailed",k.API="api",k.AUTH="auth",k))(Dr||{}),ne=Dr;var wr=($=>($.CANCELED="CANCELED",$.REJECTED="REJECTED",$.REMOVED="REMOVED",$.HUNGUP="HUNGUP",$.MISSED="MISSED",$.BUSY="BUSY",$.FAILED="FAILED",$.NETWORK_ERROR="NETWORK_ERROR",$.KILLED="KILLED",$.BANNED="BANNED",$.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",$.NOT_FRIENDS="NOT_FRIENDS",$.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",$.UNKNOWN_ERROR="UNKNOWN_ERROR",$.UNSUPPORTED="UNSUPPORTED",$.OLD_VERSION="OLD_VERSION",$.SERVICE_DISABLED="SERVICE_DISABLED",$.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",$.SOCKET_CLOSED="SOCKET_CLOSED",$.ENDED="ENDED",$))(wr||{}),P=wr;var Or=(i=>(i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING",i))(Or||{}),le=Or;var kr=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(kr||{}),je=kr;var xr=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(xr||{}),j=xr;var Nr=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(Nr||{}),Ue=Nr;var Lr=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(Lr||{}),fe=Lr;var Ur=(D=>(D.TRANSMITTED_DATA="transmitted-data",D.ACCEPTED_CALL="accepted-call",D.HUNGUP="hungup",D.PARTICIPANT_ADDED="participant-added",D.PARTICIPANT_JOINED="participant-joined",D.CLOSED_CONVERSATION="closed-conversation",D.MEDIA_SETTINGS_CHANGED="media-settings-changed",D.PARTICIPANT_STATE_CHANGED="participant-state-changed",D.RATE_CALL_DATA="rate-call-data",D.FEATURE_SET_CHANGED="feature-set-changed",D.TOPOLOGY_CHANGED="topology-changed",D.PRODUCER_UPDATED="producer-updated",D.CONSUMER_ANSWERED="consumer-answered",D.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",D.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",D.SETTINGS_UPDATE="settings-update",D.VIDEO_QUALITY_UPDATE="video-quality-update",D.REGISTERED_PEER="registered-peer",D.SWITCH_MICRO="switch-micro",D.RECORD_STARTED="record-started",D.RECORD_STOPPED="record-stopped",D.REALLOC_CON="realloc-con",D.AUDIO_ACTIVITY="audio-activity",D.SPEAKER_CHANGED="speaker-changed",D.STALLED_ACTIVITY="stalled-activity",D.CHAT_MESSAGE="chat-message",D.CUSTOM_DATA="custom-data",D.ROLES_CHANGED="roles-changed",D.MUTE_PARTICIPANT="mute-participant",D.PIN_PARTICIPANT="pin-participant",D.OPTIONS_CHANGED="options-changed",D.NETWORK_STATUS="network-status",D.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",D.PROMOTE_PARTICIPANT="promote-participant",D.CHAT_ROOM_UPDATED="chat-room-updated",D.PROMOTION_APPROVED="promotion-approved",D.JOIN_LINK_CHANGED="join-link-changed",D))(Ur||{}),O=Ur;var Br=(b=>(b.ERROR="callError",b.DEVICES="callDevices",b.CALL_SPEC_ERROR="callSpecError",b.ICE_CONNECTION_STATE="callIceConnectionState",b.ICE_CONNECTION_TYPE="callIceConnectionType",b.ICE_RESTART="callIceRestart",b.PUSH="callPush",b.OUTGOING_CALL="callStart",b.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",b.JOIN_CONVERSATION="callJoinConversation",b.ACCEPTED_OUTGOING="callAcceptedOutgoing",b.ACCEPT_INCOMING="callAcceptIncoming",b.DECLINE_INCOMING="callDeclineIncoming",b.ACCEPT_CONCURRENT="callAcceptConcurrent",b.HANGUP="callHangup",b.MEDIA_STATUS="callMediaStatus",b.DEVICE_CHANGED="callDeviceChanged",b.SOCKET_ACTION="callSocketAction",b.ADD_PARTICIPANT="callAddParticipant",b.REMOVE_PARTICIPANT="callRemoveParticipant",b.POOR_CONNECTION="callPoorConnection",b.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",b.RELAY_POLICY="callForceRelay",b.PAT_ALLOCATED="patAllocate",b.PAT_DEALLOCATED="patDeallocate",b.PAT_ERROR="patError",b.PAT_WAITING_TIME_ERROR="patWaitingTimeError",b.PAT_OUTDATED_RESPONSE="patOutdatedResponse",b))(Br||{}),g=Br;var Fr=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(Fr||{}),ke=Fr;var Vr=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(Vr||{}),Hr=Vr;function Gr(n){switch(n){case 1:return"no-available-tracks";default:return"unknown-error"}}var Wr=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(Wr||{}),Ye=Wr;function bt(n,e){if(n.length!==e.length)return!1;for(let t of n)if(!e.includes(t))return!1;return!0}var jr=(t=>(t.USER="USER",t.GROUP="GROUP",t))(jr||{}),X=jr;var mi=class{constructor(){this._items=[]}get length(){return this._items.length}push(e){this._items.push(e)}shift(){return this._items.shift()||null}bisect(){let e=this.length>1?Math.floor(this.length/2):1;this._items=this._items.slice(e)}clear(){this._items=[]}toString(){return this._items.length?JSON.stringify(this._items,(e,t)=>t instanceof Error?String(t):t):""}};var Kr=2*1024*1024,ma=512*1024,Pt=100*1024,_a=5,_i="_okcls_logs_session_",ga=3e4,$r=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=Kr;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(_i)!==0)continue;let i=e.getItem(t);if(!i){Yr(t);continue}let r=Jr(i);this.add(t,r)}}catch(e){console.error("Storage is blocked",e),this._storageSize=0}this._items.sort((e,t)=>e.date-t.date),this.cleanup(Pt)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=e}add(e,t){let i=parseInt(e.replace(_i,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(Yr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>Kr||this.length>_a-1||this.size+e>this.available);)this.deleteOldestItem()}};function qr(){return`${_i}${Date.now()}`}function Jr(n){return new Blob([n]).size}function Yr(n){try{window.localStorage.removeItem(n)}catch(e){console.error("Failed to remove log from storage",e)}}function gi(){let n=ze.toString();if(!Ee.available||!n)return;let e=Jr(n);Ee.cleanup(e);try{window.localStorage.setItem(Wt,n)}catch(t){if(console.warn("Failed to write log to storage",t),Ee.storageSize=Ee.size+e,Ee.cleanup(Pt+e),Ee.available>=Pt+e){gi();return}if(e>Pt){ze.bisect(),gi();return}Ee.storageSize=0;return}e>ma&&(Ee.add(Wt,e),Wt=qr(),ze.clear(),Ee.cleanup(Pt))}function fi(){!Ee.available||!ze.length||gi()}function fa(n=!1){let e=[];try{let r=window.localStorage;for(let s of Ee.items){let d=r.getItem(s.key);e.push(d)}let a=ze.toString();a&&e.push(a)}catch(r){console.error("Storage is blocked",r)}let t=`[${e.join(",")}]`;if(n)return t;let i=`logs_${Date.now()}.json`;return Sa(t,i),i}function Sa(n,e){let t=document.createElement("a"),i=new Blob([n],{type:"text/json"});t.href=URL.createObjectURL(i),t.download=e,t.click()}function zr(n,e){!Ee.available||(ze.push({t:Date.now(),l:n,d:e}),vi||(vi=window.setTimeout(()=>{vi=null,fi()},ga)))}function Si(){Ee||(Ee=new $r,ze=new mi,Wt=qr(),window.addEventListener("beforeunload",fi))}var Ee,ze,Wt,vi=null;window.__VKCallsSDKLogs__=(n=!1)=>(Ee||Si(),fi(),fa(n));var Qi=Me(require("file-saver"));var Ei=Me(require("@vkontakte/libvpx"));var Se=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(Se||{});var m=class extends lt{constructor(e,t){super();this._batchInterval=3e3;this._batch=[];this._batchTimeout=null;this._api=e,this._externalLogger=t}_send(e){this._api.log(e)}_sendBatch(){this._stopTimeout(),this._batch.length>0&&(this._send(this._batch),this._batch=[],this._startTimeout())}_startTimeout(){this._batchTimeout=window.setTimeout(()=>this._sendBatch(),this._batchInterval)}_stopTimeout(){this._batchTimeout&&(clearTimeout(this._batchTimeout),this._batchTimeout=null)}_onUnload(){this._sendBatch(),this._stopTimeout()}log(e,t,i=!1){let r={};typeof t!="undefined"&&(r.param=t),this._logInternal(e,r,i),this._externalLogger&&this._externalLogger.log(e,t,i)}logCustom(e,t,i=!1){this._logInternal(e,t,i)}_logInternal(e,t,i){let r={type:1,time:0,operation:e,timestamp:Date.now(),custom:t,uid:this._api.getUserId()};this._batch.push(r),(i||!this._batchTimeout)&&this._sendBatch()}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}static create(e,t){m._instance||(m._instance=new m(e,t))}static log(e,t,i=!1){m._instance&&m._instance.log(e,t,i)}static logCustom(e,t,i=!1){m._instance&&m._instance.logCustom(e,t,i)}static destroy(){m._instance&&m._instance.destroy(),m._instance=null}};var Be=class{constructor(){this._worker=null}_createWorker(s,d){return o(this,arguments,function*(e,t,i=[],r={},a=[]){return new Promise((p,u)=>{let _=i.join(","),f=new Blob([e,`exports.default(${_});`],{type:"application/javascript; charset=utf-8"}),W=window.URL.createObjectURL(f);this._worker=new Worker(W),this._worker.onmessage=K=>{switch(K.data.type){case Se.READY:p();break;case Se.ERROR:u(K.data.error);break;case Se.FRAME:t(K.data);break;case Se.DEBUG:c.debug(K.data.message);break;case Se.LOG_ERROR:m.log(g.ERROR,K.data.message);break}},this._sendToWorker(Se.INIT,r,a)})})}_removeWorker(){var e;(e=this._worker)==null||e.terminate(),this._worker=null}_sendToWorker(e,t={},i=[]){var r;(r=this._worker)==null||r.postMessage(Object.assign({type:e},t),i)}static isBrowserSupported(){throw new Error("Not implemented")}};var ht=class extends Be{init(e){return o(this,null,function*(){c.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var b=Object.defineProperty;var M=a=>b(a,"__esModule",{value:!0});var V=(a,i)=>{M(a);for(var e in i)b(a,e,{get:i[e],enumerable:!0})};var h={};V(h,{default:()=>D});var t=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(t||{});var D=(a,i)=>{let e=null,n=null,g=!0;function R(){return a({locateFile:i}).then(r=>n=r)}function s(r,m,l,y,x,E){if(!n){self.postMessage({type:t.LOG_ERROR,message:"decoder-init-fail-libvpx"}),self.postMessage({type:t.FRAME,error:"Fatal initialization error"});return}if(g!==l&&(g=l,e&&(e=null,self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new n.VpxDecoder,e.debug(E),!e.init(l?n.VpxType.VP9:n.VpxType.VP8))){e=null,self.postMessage({type:t.FRAME,error:"Decoder failed to create"});return}try{e.allocateBuffer(m.byteLength).set(new Uint8Array(m))}catch(o){self.postMessage({type:t.DEBUG,message:o}),e=null,self.postMessage({type:t.FRAME,error:String(o)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:t.FRAME,error:"Decode failed"});return}let c=e.getImageBuffer();if(!c){self.postMessage({type:t.FRAME,error:"No decoded data"});return}let d=e.getImageWidth(),f=e.getImageHeight();e.nextImage()&&(self.postMessage({type:t.DEBUG,message:"LibVPxDecoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxDecoder-drop"}));let p=new Uint8ClampedArray(c.byteLength);if(p.set(c),x){let o=new ImageData(p,d,f);createImageBitmap(o,0,0,d,f).then(u=>{self.postMessage({type:t.FRAME,crc:y,data:u},[u]),u.close()})}else self.postMessage({type:t.FRAME,data:p.buffer,crc:y,width:d,height:f},[p.buffer])}R().then(()=>{self.onmessage=r=>{switch(r.data.type){case t.FRAME:s(r.data.timestamp,r.data.data,r.data.isVP9,r.data.crc,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:t.READY})}).catch(r=>{self.postMessage({type:t.ERROR,error:String(r)})})};return h;})();\n',t=>{if(t.error)c.warn("LibVPxDecoder",t.error);else if(t.data instanceof ArrayBuffer){let i=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);e(i,t.crc)}else e(t.data,t.crc)},[Ei.default,Ei.default.getUrl])})}decodeFrame(e,t,i,r,a){let s="ImageBitmap"in window;this._sendToWorker(Se.FRAME,{timestamp:e,data:t.buffer,isVP9:i,crc:r,keyFrame:a,useImageBitmap:s,debug:c.enabled()},[t.buffer])}destroy(){this._removeWorker(),c.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var Qe=class extends Be{init(e){return o(this,null,function*(){c.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var i=Object.defineProperty;var E=e=>i(e,"__esModule",{value:!0});var g=(e,d)=>{E(e);for(var r in d)i(e,r,{get:d[r],enumerable:!0})};var y={};g(y,{default:()=>V});var s=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(s||{}),o=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(o||{});var V=()=>{let e=null,d=!0;function r(){self.postMessage({type:o.READY})}function l(a,p,t,m,u=!1){(!e||d!==t)&&(d=t,e?self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec changed to ${t?"VP9":"VP8"}`}):(self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec ${t?"VP9":"VP8"}`}),e=new VideoDecoder({output:c=>{("createImageBitmap"in c?c.createImageBitmap():createImageBitmap(c)).then(n=>{self.postMessage({type:o.FRAME,crc:m,data:n}),n.close()}).finally(()=>c.close())},error:c=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:o.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),e.configure({codec:t?s.VP9:s.VP8}));let f=new EncodedVideoChunk({type:u?"key":"delta",timestamp:a,data:p});e.decode(f)}self.onmessage=a=>{switch(a.data.type){case o.INIT:r();break;case o.FRAME:l(a.data.timestamp,a.data.data,a.data.isVP9,a.data.crc,a.data.keyFrame);break}}};return y;})();\n',t=>{t.error?c.warn("WebCod_createWorkerecsDecoder",t.error):e(t.data,t.crc)})})}decodeFrame(e,t,i,r,a=!1){this._sendToWorker(Se.FRAME,{timestamp:e,data:t.buffer,isVP9:i,crc:r,keyFrame:a},[t.buffer])}destroy(){this._removeWorker(),c.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window&&"ImageBitmap"in window&&"createImageBitmap"in window}};var Ji=Me(Di()),Yi=Me(require("crc"));var wi="_okcls_",gt=(()=>{try{let n=Date.now().toString(),e=window.localStorage,t=!1;return e.setItem(n,n),t=e.getItem(n)===n,e.removeItem(n),t?e:null}catch(n){return null}})();function za(n){let e=gt?gt.getItem(wi+n):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function Qa(n,e){try{gt&&gt.setItem(wi+n,JSON.stringify(e))}catch(t){}}function Xa(n){gt&&gt.removeItem(wi+n)}var Oi;(i=>{function n(r){return za(r)||null}i.get=n;function e(r,a){Qa(r,a)}i.set=e;function t(r){Xa(r)}i.remove=t})(Oi||(Oi={}));var qe=Oi;var ft=Me(require("big-integer"));function mn(n,e){if(n.isAudioEnabled!==e.isAudioEnabled||n.isVideoEnabled!==e.isVideoEnabled||n.isScreenSharingEnabled!==e.isScreenSharingEnabled||n.videoStreams.length!==e.videoStreams.length)return!1;for(let t of n.videoStreams)if(!e.videoStreams.find(i=>i.id===t.id&&i.source===t.source))return!1;return!0}function ve(n){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},n||{})}var _n=n=>n.stop(),gn=n=>n.getTracks().forEach(_n),ki=n=>n.getVideoTracks().forEach(_n),fn=n=>n.getVideoTracks()[0].clone();var x=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(P).indexOf(e)>-1?this.hangup=e:this.error=e;let i=[];this.error&&i.push("error"),this.remote&&i.push("remote"),this.code&&i.push(`code: ${this.code}`),t&&t.message&&i.push(`message: '${t.message}'`),this.message=e+(i.length?` (${i.join(", ")})`:""),Error.captureStackTrace&&Error.captureStackTrace(this,x)}};var Ie=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(Ie||{}),me=(i=>(i.audio="audio",i.video="video",i.screen="screen",i))(me||{}),xi=class extends Q{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._sendVideoTrack=null;this._mediaSettings=ve();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener()}request(){return o(this,arguments,function*(e=[le.AUDIO]){if(this._stream)return;let t=e.includes(le.VIDEO),i=e.includes(le.AUDIO);if(!y.isBrowserSupported())throw new x(ne.UNSUPPORTED);try{this._stream=yield y.getUserMedia(t,i),this._mediaSettings.isVideoEnabled=t&&this._stream.getVideoTracks().filter(r=>r.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=i&&this._stream.getAudioTracks().filter(r=>r.enabled).length>0||!1}catch(r){throw new x(r)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t=!1){let i=this.getStream(),r=this._getSendAudioTrack(),a=this.getSendVideoTrack(t);if(!i||!r&&!a)throw new Error("No local stream found");r&&e.addTrack(r,i),a&&e.addTrack(a,i)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return o(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return o(this,null,function*(){return t?this._changeScreen(e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=T.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);navigator.mediaDevices.addEventListener("devicechange",()=>o(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],a=r&&r.enabled&&r.getSettings(),s=a&&a.groupId,d=this._stream.getVideoTracks()[0],p=d&&d.enabled&&d.getSettings(),u=p&&p.groupId;if(!s&&!u)return;let _=yield navigator.mediaDevices.enumerateDevices();!e&&s&&(e=!_.find(f=>f.groupId===s)),!t&&u&&(t=!_.find(f=>f.groupId===u)),i()}))}_changeVideoInput(e=null){return o(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield y.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(r=>r.stop());else{l.consumerScreenTrack||this._disableScreenCapture();let r=this._getVideoEffectTrack(i),a=yield this._videoEffect(this._effect,r);this._stopLocalTrack("video"),m.log(g.DEVICE_CHANGED,t),c.log("Video stream changed"),yield this._replaceLocalTrack(a),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(g.ERROR,"change_video"),c.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=fn(e)),t=this._trackVideoStreamBackup.clone(),ki(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),ki(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return o(this,null,function*(){return this._changeAudioInput(e)})}_changeAudioInput(e=null){return o(this,null,function*(){try{if(e=e||(yield y.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),m.log(g.DEVICE_CHANGED,"audio"),c.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(g.ERROR,"change_audio"),c.error("Microphone change failed",t),t}})}_changeScreen(e){return o(this,null,function*(){try{if(e=e||(yield y.getScreenMedia()),e.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1)},!1),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getVideoTracks()[0],i=l.consumerScreenTrack?t:yield this._videoEffect(null,t);m.log(g.DEVICE_CHANGED,"screen"),c.log("Screen capturing started"),this._screenTrack=i,this._mediaSettings.isScreenSharingEnabled=!0,l.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack("video"),this._sendVideoTrack=l.consumerScreenDataChannel?y.getBlackMediaTrack(l.videoMinWidth,l.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent("SCREEN_STATUS",{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(g.ERROR,"screen"),c.warn("Screen capturing failed",t),t}})}_disableScreenCapture(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings}))}_replaceLocalTrack(e,t){return o(this,null,function*(){!this._stream||this._stream.getTracks().forEach(i=>{var r,a;i.kind===e.kind&&((r=this._stream)==null||r.removeTrack(i),(a=this._stream)==null||a.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t))})})}_stopLocalTrack(e){this._stream&&this._stream.getTracks().forEach(t=>{t.kind===e&&t.stop()})}_videoEffect(e,t){return o(this,null,function*(){if(!l.videoEffects)return t;try{return m.log(g.DEVICE_CHANGED,`effect_${e}`),l.videoEffects.setEffect(e,t)}catch(i){return c.warn("Video effect failed",i),t}})}_stopAndRemoveTrackVideoStreamBackup(){this._trackVideoStreamBackup&&(this._trackVideoStreamBackup.stop(),this._trackVideoStreamBackup=null)}destroy(){l.videoEffects&&(this._effect=null,l.videoEffects.destroy()),this._stream&&(gn(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return o(this,null,function*(){return e?this._changeScreen():l.consumerScreenTrack?this._disableScreenCapture():this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1)})}toggleVideo(e){return o(this,null,function*(){if(!this._stream)return;l.consumerScreenTrack||this._disableScreenCapture();let t;if(e){let i=yield y.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=y.getBlackMediaTrack(l.videoMinWidth,l.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return o(this,null,function*(){if(!this._stream)return;let t;e?t=(yield y.getUserAudio()).getAudioTracks()[0]:t=y.getSilentMediaTrack(),this._stopLocalTrack("audio"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}setResolution(e,t){return o(this,null,function*(){if(!l.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)return;if(!this._stream)throw new Error("Local stream not found");let i=this._stream.getVideoTracks()[0];if(!i)throw new Error("Local video track not found");if(!!i.enabled){if(!this._effect)return i.applyConstraints({width:{ideal:e},height:{ideal:t}});yield this.toggleVideo(!1),yield this.toggleVideo(!0)}})}updateNoiseSuppression(){return o(this,null,function*(){if(!this._stream||!this._mediaSettings.isAudioEnabled)return;let e=this._stream.getAudioTracks()[0];if(!e)throw new Error("Local audio track not found");if(!!e.enabled)return e.applyConstraints({noiseSuppression:l.noiseSuppression})})}videoEffect(e){return o(this,null,function*(){if(!l.videoEffects)throw new Error("Video Effects library is not set");if(!l.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)throw new Error("Can't apply effect to screensharing");if(!this._mediaSettings.isVideoEnabled){this._effect=e;return}if(this._stream&&e!==this._effect)return this._effect=e,this._changeVideoInput(this._stream)})}};var Ni;(_r=>{function n(C,R,M,b,w=!1){let Pe=/[\r\n]+/,Z=`\r
8
- `;if(!R&&!M&&!b)return w?U(C.split(Pe)).join(Z):C;function U(z){let Ne=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],_e="a=rtcp-fb:111",oe=z.findIndex(te=>te.startsWith(_e));return~oe&&(z[oe]=z[oe]+Z+Ne.join(Z)),z}function ee(z,Ne,_e){let oe=z.split(" "),te=oe.slice(0,3),he;for(he=3;he<oe.length;he++)_e.includes(oe[he])&&te.push(oe[he]);for(he=3;he<oe.length;he++)!_e.includes(oe[he])&&!Ne.includes(oe[he])&&te.push(oe[he]);return te.join(" ")}function A(z,Ne){let _e=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),oe,te=[];for(oe=0;oe<z.length;++oe){let he=z[oe].match(_e);he&&he.length===3&&he[2]===Ne&&te.push(he[1])}return te}function q(z,Ne,_e,oe){let te,he="m="+Ne;for(te=0;te<z.length;++te)if(z[te].startsWith(he)){z[te]=ee(z[te],_e,oe);break}}let pe=[],D=C.split(Pe);(M||R)&&(pe=A(D,"H264"));let Ge=[];if(b&&(Ge=A(D,"VP9")),M){let z=pe.slice(0),Ne=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),_e;for(_e=0;_e<D.length;++_e){let te=D[_e].match(Ne);te&&te.length===3&&z.includes(te[2])&&z.push(te[1])}let oe=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(_e=D.length;_e--;){let te=D[_e].match(oe);te&&te.length===3&&z.includes(te[2])&&D.splice(_e,1)}q(D,"video",z,[])}else R&&q(D,"video",[],pe);return b&&q(D,"video",[],Ge),w&&U(D),D.join(Z)}_r.patchSDP=n;function e(C){return C?`${C.type||"WEB_SOCKET"}_${C.id}`:"_"}_r.getPeerIdString=e;function t(C,R){return C&&C.id===R.id&&(C.type||"WEB_SOCKET")===(R.type||"WEB_SOCKET")}_r.comparePeerId=t;function i(C){return o(this,null,function*(){return!C||!C.getStats?Promise.resolve(null):C.getStats(null).then(R=>{let M=null,b=null;if(R.forEach(w=>{w.type==="transport"&&w.selectedCandidatePairId?b=R.get(w.selectedCandidatePairId):w.type==="candidate-pair"&&w.state==="succeeded"&&!b&&(!w.hasOwnProperty("selected")||w.selected)&&(b=w)}),b&&b.localCandidateId){let w=R.get(b.localCandidateId);w&&(M={type:w.candidateType,ip:w.ip||w.ipAddress,port:w.port||w.portNumber})}return M}).catch(()=>null)})}_r.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,a=/^([gu])([0-9]+)$/;function s(C,R){let M=String(C);return a.test(M)?(c.warn(`Already composite id [${C}] type supplied [${R}]`),M):R===X.GROUP?"g"+M:R===X.USER?"u"+M:(c.warn(`Unknown type [${R}] for id [${C}]`),M.match(r)?"u"+M:M)}_r.composeId=s;function d(C){return s(C.id,C.idType||X.USER)}_r.composeParticipantId=d;function p(C){return C.participant?d(C.participant):s(C.participantId,C.participantType||X.USER)}_r.composeMessageId=p;function u(C){let R=String(C),M=R.match(a);return M?{id:Number(M[2]),type:M[1]==="g"?X.GROUP:X.USER}:(c.warn(`Unsupported compositeId [${C}]`),{id:Number(R),type:X.USER})}_r.decomposeId=u;function _(){let C="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),R=new Array(36),M=0,b,w;for(w=0;w<36;w++)w===8||w===13||w===18||w===23?R[w]="-":w===14?R[w]="4":(M<=2&&(M=33554432+Math.random()*16777216|0),b=M&15,M=M>>4,R[w]=C[w===19?b&3|8:b]);return R.join("")}_r.uuid=_;function f(C,R){let M;function b(){let w=this,Pe=arguments;M&&window.clearTimeout(M),M=window.setTimeout(()=>{C.apply(w,Pe)},R)}return b}_r.throttle=f;function W(C){let R="",M=C.split(`
9
- `);for(let Z of M)if(Z.startsWith("a=fingerprint")){let U=Z.split(" ");if(U.length===2){R=U[1];break}}if(!R)return ft.default.minusOne;let b=R.split(":"),w=ft.default.zero;for(let Z=Math.min(7,b.length-1);Z>=0;Z--){let U=(0,ft.default)(b[Z],16);w=w.shiftLeft(8).or(U)}return((Z,U)=>{let ee=U.value;if(typeof ee=="bigint")return(0,ft.default)(BigInt.asIntN(Z,ee));let A=ft.default.one.shiftLeft(Z),q=U.and(A.subtract(1));return q.greaterOrEquals(A.subtract(q))?q.subtract(A):q})(64,w)}_r.sdpFingerprint=W;function K(C){return o(this,null,function*(){return new Promise(R=>window.setTimeout(R,C))})}_r.delay=K;function k(C,R,M){let b=[];return C.getSenders().forEach(w=>Y(R,w,w.track,M,b)),b}_r.applySettings=k;function Y(C,R,M,b,w){if(C&&M&&M.kind===me.video){let Pe=M.getSettings();if(Pe){let Z=C.maxBitrateK?C.maxBitrateK*1024:null,U=Pe.width,ee=Pe.height,A=U&&ee&&C.maxDimension?Math.max(1,Math.max(U,ee)/C.maxDimension):null,q=C.maxFramerate?C.maxFramerate:null,pe=C.degradationPreference?C.degradationPreference:"balanced",D=b[M.id];if(D&&D.bitrate===Z&&D.scaleResolutionDownBy===A&&D.maxFramerate===q&&D.degradationPreference===pe){w[M.id]=D;return}w[M.id]={bitrate:Z,scaleResolutionDownBy:A,maxFramerate:q,degradationPreference:pe};let Ge=R.getParameters();Ge.encodings||(Ge.encodings=[{}]),Ge.encodings.forEach(z=>{Z?z.maxBitrate=Z:delete z.maxBitrate,A?z.scaleResolutionDownBy=A:delete z.scaleResolutionDownBy,q?z.maxFramerate=q:delete z.maxFramerate}),Ge.degradationPreference=pe,R.setParameters(Ge)}}}_r.applyVideoTrackSettings=Y;function se(C,R){Array.isArray(R)||(R=[R]);for(let M of R)if(C.includes(M))return!0;return!1}_r.includesOneOf=se;function ce(C){var R;return Object.entries(((R=C.participantState)==null?void 0:R.state)||{}).reduce((M,[b,w])=>(C.participantState&&(M[b]={ts:C.participantState.stateUpdateTs[b],state:w}),M),{})}_r.mapParticipantState=ce;function dt(C){return Object.entries(C).reduce((R,[M,{state:b}])=>(R[M]=b,R),{})}_r.mapLegacyParticipantState=dt;function ue(C){return C.map(R=>{let M={uid:R.externalId,mediaSettings:R.mediaSettings,status:R.status,muteStates:R.muteStates,unmuteOptions:R.unmuteOptions};return l.participantStateMapped&&(M.participantState=R.participantState),M})}_r.mapSharedParticipants=ue;function $(C,R){let M=Object.keys(C),b=Object.keys(R);if(M.length!==b.length)return!1;for(let w of M)if(!b.hasOwnProperty(w)||C[w].state!==R[w].state||C[w].ts!==R[w].ts)return!1;return!0}_r.isEqualParticipantState=$;function Oe(C,R){let M=Object.keys(C),b=Object.keys(R);if(M.length!==b.length)return!1;for(let w of M)if(!R.hasOwnProperty(w)||C[w]!==R[w])return!1;return!0}_r.isObjectsEquals=Oe;function It(C,R){if(C.length!==R.length)return!1;for(let M of C)if(R.indexOf(M)<0)return!1;return!0}_r.isArraysEquals=It;function mr(C){return!Object.keys(C).length}_r.isEmptyObject=mr})(Ni||(Ni={}));var T=Ni;var et=null,Li=null,qt=[],Jt=[],Ui=[],Mt=null,At=null,Bi=null,Fi=!1,Vi=!1,Yt,St,zt,Sn=!1,vn=!1,Hi=null,Gi="",Qt=[],Wi=null,En=navigator.appVersion,Za=navigator.appName,ye=navigator.userAgent,ji=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(ji||{}),Dt=class{constructor(e,t=!1,i=l.videoMaxWidth,r=l.videoMaxHeight){let a=!1;if(e){a={noiseSuppression:l.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let d;At&&(d=At.deviceId),typeof e=="string"&&(d=e),d&&(a.deviceId={exact:d})}let s=!1;if(t){s={width:{min:l.videoMinWidth,max:i,ideal:i},height:{min:l.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:l.videoAspectRatio},frameRate:{ideal:l.videoFrameRate}};let d;Mt&&(d=Mt.deviceId),typeof t=="string"&&(d=t),d&&(s.deviceId={exact:d}),l.videoFacingMode&&(s.facingMode={exact:l.videoFacingMode})}this.audio=a,this.video=s,this.needVideo=!!s}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let e=typeof this.video=="object"&&(this.video.width||this.video.height||this.video.aspectRatio||this.video.frameRate||this.video.facingMode||this.video.deviceId)||this.video;return!!(typeof this.audio=="object"&&(this.audio.deviceId||this.audio.noiseSuppression||this.audio.echoCancellation||this.audio.autoGainControl)||this.audio||e)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},Tn=class extends Dt{constructor(e,t){super(!1,!0);typeof this.video=="object"?(delete this.video.deviceId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode):this.video={},this.video.cursor="motion",this.video.width=e,this.video.height=t,this.video.frameRate=l.screenFrameRate}};function es(){return o(this,null,function*(){et=null,yield Xt()})}function ts(){et=null,Xt().then(()=>E.onDeviceChange())}function Xt(){return o(this,null,function*(){return et||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!Li&&navigator.mediaDevices.addEventListener&&(Li=T.throttle(ts,1e3),navigator.mediaDevices.addEventListener("devicechange",Li)),et=navigator.mediaDevices.enumerateDevices().then(n=>{qt=n.filter(r=>r.kind==="videoinput"?(r.label&&(Fi=!0),!0):!1),Jt=n.filter(r=>r.kind==="audioinput"?(r.label?Vi=!0:tt.isMobile()&&tt.browserName()==="Firefox"&&(Vi=Fi),!0):!1),Ui=n.filter(r=>r.kind==="audiooutput");let e=qe.get("videoinput"),t=qe.get("audioinput"),i=qe.get("audiooutput");return Mt=qt.find(r=>r.deviceId===e)||null,At=Jt.find(r=>r.deviceId===t)||null,Bi=Ui.find(r=>r.deviceId===i)||null,et=Promise.resolve(n),n}).catch(()=>(et=null,[]))))})}function is(){return o(this,null,function*(){return tt.isBrowserSupported()?new Promise(n=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(Sn=!0),/^a=mid:0$/m.test(t.sdp)&&(vn=!0),n()}).catch(n)}):Promise.resolve()})}function Zt(n,e){return o(this,null,function*(){c.debug("Try to get media",n.getNative());let t=tt.hasPermissions(n.isVideo());!t&&!e&&E.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(n.getNative());return t||(yield es()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=n.isVideo()?ne.CAMERA_PERMISSION:ne.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=n.isVideo()?ne.CAMERA_ACCESS:ne.MIC_ACCESS;break}if(n.canSimplify())return Zt(n.simplify(),e);let r=e||ne.UNKNOWN;throw E.onPermissionsError(r),r}})}function rs(n){return o(this,null,function*(){c.debug("Try to get screen",n.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(n.getNative()),t=e==null?void 0:e.getVideoTracks()[0];return t&&(c.debug("Got display media track",t.id),t.contentHint="text"),e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw ne.SCREEN_PERMISSION;default:throw ne.SCREEN_ACCESS}}})}function Ki(){return Qt.length||(Qt=(()=>{let n,e=!1,t=0,i=ye.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return n=/\brv[ :]+(\d+)/g.exec(ye),["IE",n&&n[1]||"Unknown",e,t];if(i[1]==="Safari"){if(n=ye.match(/\bEdge\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t];if(n=ye.match(/\bCriOS\/(\d+)/),n)return["Chrome",n[1],!0,n[1]];if(n=ye.match(/\bFxiOS\/(\d+)/),n)return["Firefox",n[1],!1,t];if(n=ye.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1],!1,t];if(n=ye.match(/\bOPT\/(\d+)/),n)return["Opera",n[1],!1,t]}if(i[1]==="Chrome"){if(e=!0,t=Number(i[2]),n=ye.match(/\bOPR\/(\d+)/),n)return["Opera",n[1]||"Unknown",e,t];if(n=ye.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1]||"Unknown",e,t];if(n=ye.match(/\bSferum\/((\d+)(?:\.\d+)*)/),n)return["Sferum",n[1]||"Unknown",e,t];if(n=ye.match(/\bEdge?\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t]}return n=ye.match(/version\/(\d+)/i),[i[2]?i[1]:Za,n&&n[1]||i[2]||En,e,t]})()),Qt}var tt;(Z=>{function n(){return o(this,null,function*(){return yield is(),Xt()})}Z.init=n;function e(){return qt}Z.getCameras=e;function t(){return Jt}Z.getMicrophones=t;function i(){return Ui}Z.getOutput=i;function r(){return qt.length>0}Z.hasCamera=r;function a(){return Jt.length>0}Z.hasMicrophone=a;function s(){return Mt}Z.getSavedCamera=s;function d(){return At}Z.getSavedMicrophone=d;function p(){return Bi}Z.getSavedOutput=p;function u(){return Fi}Z.hasCameraPermission=u;function _(){return Vi}Z.hasMicrophonePermission=_;function f(U=!1){return _()?r()&&U?u():!0:!1}Z.hasPermissions=f;function W(U=!1,ee=!0){return o(this,null,function*(){let A=a()&&ee,q=r()&&U,pe;if(!A&&!q)pe=new MediaStream;else try{pe=yield Zt(new Dt(A,q))}catch(D){pe=new MediaStream}return pe.getVideoTracks().length||pe.addTrack(dt()),pe.getAudioTracks().length||pe.addTrack(ce()),pe})}Z.getUserMedia=W;function K(){return o(this,null,function*(){return rs(new Tn(window.screen.width,window.screen.height))})}Z.getScreenMedia=K;function k(U,ee=!1){return o(this,null,function*(){let A=ee?l.videoEffectMaxWidth:l.videoMaxWidth,q=ee?l.videoEffectMaxHeight:l.videoMaxHeight;return Zt(new Dt(!1,U||!0,A,q))})}Z.getUserVideo=k;function Y(U){return o(this,null,function*(){return Zt(new Dt(U||!0,!1))})}Z.getUserAudio=Y;function se(U,ee){return o(this,null,function*(){let q=(yield Xt()).find(pe=>pe.kind===U&&pe.deviceId===ee);return q?(U==="videoinput"?Mt=q:U==="audioinput"?At=q:U==="audiooutput"&&(Bi=q),qe.set(U,ee),q):null})}Z.saveDeviceId=se;function ce(){if(!zt||zt.readyState==="ended"){let U=Pe(),ee=U.createMediaStreamDestination(),A=U.createGain();A.gain.value=1e-5,A.connect(ee),A.connect(U.destination);let q=U.createOscillator();q.type="sine",q.frequency.value=0,q.connect(A),q.start(),zt=ee.stream.getAudioTracks()[0]}return Object.assign(zt.clone(),{enabled:!1})}Z.getSilentMediaTrack=ce;function dt(U=l.videoMinWidth,ee=l.videoMinHeight){return St||(St=document.createElement("canvas"),St.getContext("2d")),St.width=U,St.height=ee,(!Yt||Yt.readyState==="ended")&&(Yt=St.captureStream(l.videoFrameRate).getVideoTracks()[0]),Object.assign(Yt.clone(),{enabled:!1})}Z.getBlackMediaTrack=dt;function ue(){if(M()==="Edge"&&b()<70)return!1;try{let U=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&U.RTCPeerConnection&&U.RTCIceCandidate&&U.RTCSessionDescription&&U.HTMLCanvasElement&&U.HTMLCanvasElement.prototype.captureStream&&U.RTCRtpSender&&U.RTCRtpSender.prototype.replaceTrack&&U.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(U){return!1}}Z.isBrowserSupported=ue;function $(){return!!navigator.mediaDevices.getDisplayMedia}Z.isScreenCapturingSupported=$;function Oe(){return Sn}Z.canVP8=Oe;function It(){return vn}Z.isUnifiedPlan=It;function mr(){return Z.browserName()==="Opera"&&Z.os()==="Windows"}Z.isBrokenH264=mr;function _r(){return!(Z.baseChromeVersion()&&Z.isMobile())}Z.canPreferH264=_r;function C(){return Gi||(Gi=(()=>{let U={Windows:/Win/,Android:/Android/,OpenBSD:/OpenBSD/,SunOS:/SunOS/,Linux:/(Linux|X11)/,iPad:/(iPad)/,iPhone:/(iPhone)/,iPod:/(iPod)/,MacOS:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh|Mac OS X)/,QNX:/QNX/,UNIX:/UNIX/,BeOS:/BeOS/,OS2:/OS\/2/,Bot:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/};for(let ee in U)if(U.hasOwnProperty(ee)&&U[ee].test(ye))return ee;return"Unknown"})()),Gi}Z.os=C;function R(){return Hi===null&&(Hi=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(En)),Hi}Z.isMobile=R;function M(){return Ki()[0]}Z.browserName=M;function b(){return Ki()[1]}Z.browserVersion=b;function w(){return Ki()[3]}Z.baseChromeVersion=w;function Pe(){return Wi||(Wi=new(window.AudioContext||window.webkitAudioContext)),Wi}Z.getAudioContext=Pe})(tt||(tt={}));var y=tt;var Cn=Me(require("bit-buffer")),$i=Me(Di()),qi=Me(require("crc"));var ns=65536,it=class{constructor(e,t){this._chunks=[];this._participantId=e,this._onStream=t}appendChunk(e){let t=this._chunks.length;if(e.start)t&&(c.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!t||(this._chunks[t-1].sequence+1)%ns!==e.sequence){c.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:a}=it.getFrameSize(i);this._processFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe,width:r,height:a})}}destroy(){this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((d,p)=>d+p.data.byteLength,0),i=new Uint8Array(t),r=[],a=0;for(let d of e)r.push(qi.default.crc32($i.default.Buffer.from(d.data)).toFixed()),i.set(new Uint8Array(d.data),a),a+=d.data.byteLength;let s=qi.default.crc32($i.default.Buffer.from(i)).toFixed();return c.debug("processed screenshare frame data",s,r),i}static getFrameSize(e){let t={width:0,height:0},i=new Cn.BitStream(e.buffer);i.bigEndian=!0,i.index+=2;let r=i.readBits(1),s=i.readBits(1)<<1|r;return s===3&&i.index++,i.readBits(1)===1||i.readBits(1)!==0||(i.index++,i.index++,i.index+=24,s>=2&&i.index++,i.readBits(3)!==7?(i.index++,(s===1||s===3)&&(i.index+=3)):(s===1||s===3)&&i.index++,t.width=i.readBits(16)+1,t.height=i.readBits(16)+1),t}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var wt=class extends it{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;c.debug(`StreamBuilder started for participant [${e}]`),this._useImageBitmap="ImageBitmap"in window,Qe.isBrowserSupported()?this._decoder=new Qe:this._decoder=new ht,this._decoder.init((i,r)=>this._drawImage(i,r)).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}_drawImage(e,t){this._track||(this._createStream(e.width,e.height),this._onStream(this._stream));let i=this._canvas;if(i.width=e.width,i.height=e.height,e instanceof ImageData){let r=this._canvasContext;r.clearRect(0,0,i.width,i.height),r.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}_processFrame(e){if(!this._decoderReady||this._decoderQueue.length)this._decoderQueue.push(e),this._decodeQueue();else{let t=Yi.default.crc32(Ji.default.Buffer.from(e.frameData)).toFixed();this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,t,e.keyframe)}}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{let i=Yi.default.crc32(Ji.default.Buffer.from(t.frameData)).toFixed();this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,i,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._removeStream(),c.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(y.browserName()==="Safari"&&y.browserVersion()>=15)}};var ei=1,as=1,In=0,yn=11,Rn=1,bn=2,Pn=4,Mn=8;function An(n,e,t,i,r,a,s){let d=0;e&&(d|=Rn),t&&(d|=bn),i&&(d|=Pn),s||(d|=Mn);let p=new ArrayBuffer(yn),u=new DataView(p);if(u.setUint8(0,ei),u.setUint16(1,r),u.setUint32(3,n),u.setUint8(7,a?1:0),u.setUint16(8,In),u.setUint8(10,d),!s)return p;let _=new Uint8Array(p.byteLength+s.byteLength);return _.set(new Uint8Array(p),0),_.set(new Uint8Array(s),p.byteLength),_.buffer}function Dn(n){let e=new DataView(n),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),a=e.getUint8(7)===1,s=e.getUint16(8),d=e.getUint8(10),p=!!(d&Rn),u=!!(d&bn),_=!!(d&Pn),f=!!(d&Mn);if(t!==ei)throw new Error(`Unexpected protocol version. Got ${t}, expected ${ei}`);return{timestamp:r,start:p,end:u,keyframe:_,sequence:i,isVP9:a,ssrc:s,eos:f,data:n.slice(yn)}}function wn(n){if(!n||!n.byteLength||n.byteLength!==4)return!1;let e=new DataView(n);return!(e.getUint8(0)!==ei||e.getUint8(1)!==as||e.getUint16(2)!==In)}var S=Me(require("simple-ebml-builder"));var ss=Sr(2,15)-1,zi=1,os=5,cs=5;var ti=class{constructor(e){this._queue=[];this._clearBufferTill=0;this._mediaSource=new MediaSource,this._codec=e;let t=()=>{this._mediaSource.removeEventListener("sourceopen",t),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener("sourceopen",t,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let i=this._sourceBuffer.buffered.start(0);i<this._clearBufferTill&&(this._sourceBuffer.remove(i,this._clearBufferTill),c.debug(`[WebmBuilder] SourceBuffer cleanup from ${i} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let e=this._queue;this._queue=[];let t=ti._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return S.build(e[0])}else return new Uint8Array;let t=e.reduce((a,s)=>a+s.countSize(),0),i=new Uint8Array(t),r=0;for(let a of e){let s=S.build(a);i.set(s,r),r+=s.byteLength}return i}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(e){var t;return this._codec=e,(t=this._sourceBuffer)==null?void 0:t.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){var a;let e=(a=this._sourceBuffer)==null?void 0:a.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-os);r-i>cs&&(this._clearBufferTill=r)}destroy(){this._queue=[],this._mediaSource.readyState==="open"&&(this._sourceBuffer.abort(),this._mediaSource.endOfStream()),this._sourceBuffer=null,this._clearBufferTill=0}get codec(){return this._codec}get mediaSource(){return this._mediaSource}get buffered(){var e;return(e=this._sourceBuffer)==null?void 0:e.buffered}},$e=class extends it{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;c.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return S.element(S.ID.EBML,[S.element(S.ID.EBMLVersion,S.number(1)),S.element(S.ID.EBMLReadVersion,S.number(1)),S.element(S.ID.EBMLMaxIDLength,S.number(4)),S.element(S.ID.EBMLMaxSizeLength,S.number(8)),S.element(S.ID.DocType,S.string("webm")),S.element(S.ID.DocTypeVersion,S.number(2)),S.element(S.ID.DocTypeReadVersion,S.number(2))])}static _genSegmentHeader(e,t,i){let r=S.element(S.ID.Info,[S.element(S.ID.TimecodeScale,S.number(1e6)),S.element(S.ID.MuxingApp,S.string("vk-webm-builder")),S.element(S.ID.WritingApp,S.string("vk-webm-builder"))]),a=[S.element(S.ID.PixelWidth,S.number(e)),S.element(S.ID.PixelHeight,S.number(t))],s=S.element(S.ID.Tracks,S.element(S.ID.TrackEntry,[S.element(S.ID.TrackNumber,S.number(zi)),S.element(S.ID.TrackUID,S.number(zi)),S.element(S.ID.TrackType,S.number(1)),S.element(S.ID.FlagLacing,S.number(0)),S.element(S.ID.DefaultDuration,S.number(1e9)),S.element(S.ID.CodecID,S.string(`V_${i.toUpperCase()}`)),S.element(S.ID.Video,a)]));return S.unknownSizeElement(S.ID.Segment,[r,s])}static _genClusterHeader(e){return S.unknownSizeElement(S.ID.Cluster,[S.element(S.ID.Timecode,S.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new ti(e),this._video=document.createElement("video"),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video.src){c.warn(`[WebmBuilder] Video paused for participant [${this._participantId}], try to play again`);let i=this._video.seekable;i.length&&(this._video.currentTime=i.end(i.length-1)-1),this._video.play().catch(()=>{})}};this._video.onpause=t,this._video.onwaiting=t,this._video.onstalled=t,this._video.onerror=()=>c.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(e){let t=e.isVP9?"vp9":"vp8";this._mediaBuffer?this._mediaBuffer.codec!==t&&this._mediaBuffer.changeType(t):this._createVideo(t);let i=e.timestamp;if(i<=this._lastFrameTimestamp&&(i=this._lastFrameTimestamp+10,c.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=i,this._earliestTimestamp)i-=this._earliestTimestamp;else{if(!e.keyframe)return;this._earliestTimestamp=i,i=0}if(e.keyframe){this._clusterStartTime=i,c.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let s=$e._genWebmHeader();this._mediaBuffer.append(s);let d=$e._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(d),this._mediaBuffer.cleanup()}let r=Math.round(i-this._clusterStartTime);if(r>ss&&(this._clusterStartTime=i,r=0),r===0){c.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=$e._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let a=S.element(S.ID.SimpleBlock,[S.vintEncodedNumber(zi),S.bytes($e._intToU16BE(r)),S.number((e.keyframe?1:0)<<7),S.bytes(e.frameData)]);this._mediaBuffer.append(a,!0)}destroy(){super.destroy(),this._video&&(this._video.onpause=null,this._video.onwaiting=null,this._video.onstalled=null,this._video.onerror=null,this._video.pause(),this._video.src="",document.body.removeChild(this._video)),this._mediaBuffer&&(this._mediaBuffer.destroy(),this._mediaBuffer=null),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),c.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){var e,t,i;return"captureStream"in((e=window.HTMLVideoElement)==null?void 0:e.prototype)&&((t=window.MediaSource)==null?void 0:t.isTypeSupported('video/webm; codecs="vp8"'))&&((i=window.MediaSource)==null?void 0:i.isTypeSupported('video/webm; codecs="vp9"'))}};var rt=class{constructor(e,t,i,r){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};this._parts=[];this._lastChunk=0;c.debug("ScreenCaptureReceiver started"),e instanceof RTCDataChannel?(this._datachannel=e,this._datachannel.onmessage=a=>this._onDataChannelMessage(a.data)):this._replay(e),this._participantIdRegistry=t,this._onStream=i,this._onEos=r}_replay(e){return o(this,null,function*(){let t=yield e.arrayBuffer(),i=new DataView(t),r=0;for(;r<i.byteLength;){let a=this._readUint32(i,r);yield this._sleep(a);let s=this._readUint32(i,r+=4),d=t.slice(r+=4,r+=s);this._onDataChannelMessage(d)}})}_sleep(e){return o(this,null,function*(){return new Promise((t,i)=>{setTimeout(()=>{t()},e)})})}_readUint32(e,t){return e.getUint8(t)+(e.getUint8(t+1)<<8)+(e.getUint8(t+2)<<16)+(e.getUint8(t+3)<<24)}_onDataChannelMessage(e){var a,s;if(c.debug("Received "+e.byteLength+" bytes of screenshare data"),this._datachannel){let d=new Date().getTime(),p=this._lastChunk?d-this._lastChunk:0;this._lastChunk=d,this._parts.push(new Uint32Array([p,e.byteLength])),this._parts.push(new Uint8Array(e))}let t=Dn(e),i=(s=(a=this._participantIdRegistry)==null?void 0:a.getStreamDescription(t.ssrc))==null?void 0:s.participantId;if(!i){c.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){if(this.close(i),this._onEos(i),this._lastChunk){let d=new Date().toISOString().replace(/:/g,"-").replace(/.\d+Z/,"").replace("T","_");(0,Qi.saveAs)(new Blob(this._parts),"screenshare-"+i+"-"+d+".dat"),this._parts=[],this._lastChunk=0}return}let r=this._streamBuilders[i];if(!r){let d=p=>this._onStream(i,p);r=new wt(i,d),this._streamBuilders[i]=r}r.appendChunk(t)}close(e){let t=this._streamBuilders[e];t&&(t.destroy(),delete this._streamBuilders[e])}destroy(){if(this._lastChunk){let e=new Date().toISOString().replace(/:/g,"-").replace(/.\d+Z/,"").replace("T","_");(0,Qi.saveAs)(new Blob(this._parts),"screenshare-"+e+".dat"),this._parts=[],this._lastChunk=0}this._datachannel&&(this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null),this._onStream=()=>{},Object.values(this._streamBuilders).forEach(e=>e.destroy()),this._streamBuilders={},this._participantIdRegistry=null,c.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(Qe.isBrowserSupported()||ht.isBrowserSupported())&&(wt.isBrowserSupported()||$e.isBrowserSupported())}};var Xi=Me(require("@vkontakte/libvpx"));var ds=1e3,Ot=class extends Be{constructor(e,t){super();this._video=null;this._imageCapture=null;this._canvas=null;this._canvasCtx=null;this._stream=null;this._track=null;this._frameReadTimeout=0;this._lastFrame=null;this._sourceTrack=e,this._onFrame=t,this._useImageCapture="ImageCapture"in window&&"ImageBitmap"in window,(e.readyState!=="live"||!e.enabled||e.muted)&&(this._useImageCapture=!1)}_createDom(){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="160px",this._canvas.style.zIndex="5000",this._canvasCtx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)),!this._video&&!this._useImageCapture&&(this._video=document.createElement("video"),this._video.controls=!1,this._video.autoplay=!1,this._video.preload="auto",this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",document.body.appendChild(this._video))}_removeDom(){try{this._canvas&&document.body.removeChild(this._canvas),this._video&&document.body.removeChild(this._video)}catch(e){}this._canvasCtx=null,this._canvas=null,this._video=null}_createStream(e){return o(this,null,function*(){if(!this._canvas)throw new Error("Canvas not found");if(!this._video&&!this._useImageCapture)throw new Error("Video element not found");return this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],new Promise((t,i)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let r=this._video;r.srcObject=new MediaStream([e]),r.onloadeddata=d=>t(),r.onerror=()=>i(new Error("Video element error"));let a=r.play(),s=()=>i(new Error("Autoplay is disabled"));a?a.catch(s):s()}})})}_removeStream(){var e;window.clearTimeout(this._frameReadTimeout),(e=this._lastFrame)==null||e.close(),this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null,this._track=null),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video||!this._track)throw new Error("Fatal error");let e=this._video.videoWidth,t=this._video.videoHeight;return this._canvas.width=this._video.width=e,this._canvas.height=this._video.height=t,this._canvasCtx.clearRect(0,0,e,t),this._canvasCtx.drawImage(this._video,0,0,e,t),this._requestCanvasFrame(),this._canvasCtx.getImageData(0,0,e,t)}_getFrameBitmap(){return o(this,null,function*(){if(!this._imageCapture)throw new Error("Destroyed");return this._imageCapture.grabFrame()})}_drawFrameData(e){var r;if(!this._canvas||!this._canvasCtx||!this._track)throw new Error("Destroyed");let t=e.width,i=e.height;return this._canvas.width=t,this._canvas.height=i,this._canvasCtx.clearRect(0,0,t,i),this._canvasCtx.drawImage(e,0,0,t,i),this._requestCanvasFrame(),(r=this._canvasCtx)==null?void 0:r.getImageData(0,0,t,i)}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}init(){return o(this,null,function*(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;c.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createStream(this._sourceTrack),yield this._createWorker(`var exports=(()=>{var u=Object.defineProperty;var b=o=>u(o,"__esModule",{value:!0});var g=(o,n)=>{b(o);for(var t in n)u(o,t,{get:n[t],enumerable:!0})};var y={};g(y,{default:()=>R});var e=(r=>(r.INIT="init",r.READY="ready",r.FRAME="frame",r.ERROR="error",r.DEBUG="debug",r.LOG_ERROR="log_error",r))(e||{});var R=(o,n)=>{let t;function m(a,r){return o({locateFile:n}).then(s=>{if(t=new s.VpxEncoder,t.debug(r),!t.init(a?s.VpxType.VP9:s.VpxType.VP8))throw self.postMessage({type:e.LOG_ERROR,message:"encoder-init-fail-libvpx"}),new Error("LibVPxEncoder failed to create");t.setMaxQuantizer(10),t.setTargetBitrate(1024)})}function E(a,r,s,i){let c=t.allocateImage(a,r);if(!c){self.postMessage({type:e.FRAME,error:"No buffer data"});return}c.set(new Uint8Array(s));let f=Math.round(performance.now()),l=150;if(!t.encode(f,l,i)){self.postMessage({type:e.FRAME,error:"Encode failed"});return}let p=t.readFrame();if(!p){self.postMessage({type:e.FRAME,error:"No encoded data"});return}t.readFrame()&&(self.postMessage({type:e.DEBUG,message:"LibVPxEncoder dropped frame"}),self.postMessage({type:e.LOG_ERROR,message:"LibVPxEncoder-drop"}));let d=new Uint8Array(p.byteLength);d.set(p),self.postMessage({type:e.FRAME,frameType:i?"key":"delta",timestamp:f,duration:l,data:d.buffer},[d.buffer])}self.onmessage=a=>{switch(a.data.type){case e.INIT:m(a.data.isVP9,a.data.debug).then(()=>self.postMessage({type:e.READY})).catch(r=>self.postMessage({type:e.ERROR,error:String(r)}));break;case e.FRAME:E(a.data.width,a.data.height,a.data.imageData,a.data.keyFrame);break}}};return y;})();
10
- `,i=>{var r;i.error?this._onFrame(null,i.error):this._onFrame({type:i.frameType,timestamp:i.timestamp,duration:i.duration,data:i.data,byteLength:(r=i.data)==null?void 0:r.byteLength})},[Xi.default,Xi.default.getUrl],{isVP9:this.isVP9(),debug:c.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(Se.FRAME,{width:e.width,height:e.height,imageData:i,keyFrame:t},[i])}_requestFrameVideo(e){let t=this._drawFrameVideo();this._encode(t,e)}_requestFrameBitmap(e){this._frameReadTimeout=window.setTimeout(()=>{if(this._lastFrame){let t=this._drawFrameData(this._lastFrame);this._encode(t,e)}else this._onFrame(null)},ds),this._getFrameBitmap().then(t=>{var r;window.clearTimeout(this._frameReadTimeout),(r=this._lastFrame)==null||r.close(),this._lastFrame=t;let i=this._drawFrameData(t);this._encode(i,e)}).catch(()=>{})}requestFrame(e=!1){this._useImageCapture?this._requestFrameBitmap(e):this._requestFrameVideo(e)}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),c.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var vt=class extends Be{constructor(e,t){super();this._sourceTrack=e,this._onFrame=t,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return o(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;c.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`var exports=(()=>{var b=Object.defineProperty;var g=i=>b(i,"__esModule",{value:!0});var F=(i,n)=>{g(i);for(var r in n)b(i,r,{get:n[r],enumerable:!0})};var A={};F(A,{default:()=>h});var l=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(l||{}),d=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(d||{});var h=()=>{let i=1e3,n,r,c,s,f,t,a=null,p=0,u=!1;function V(e){n=e.readable,r=n.getReader(),c=e.width,s=e.height,f=e.isVP9,t=e.framerate,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"}),self.postMessage({type:d.READY})}function y(e){p=self.setTimeout(()=>{a&&E(a,e)},i),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(p)}).then(({done:o,value:R})=>{if(a==null||a.close(),a=null,!(o||!R)){if(!m){r.releaseLock(),n.cancel();return}a=R,E(R,e)}}))}function E(e,o){(e.codedWidth!==c||e.codedHeight!==s)&&(c=e.codedWidth,s=e.codedHeight,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"})),m.encode(e,{keyFrame:o})}let m=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:d.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,data:o},[o])},error:e=>{self.postMessage({type:d.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case d.INIT:V(e.data);break;case d.FRAME:y(e.data.keyFrame);break}}};return A;})();
11
- `,r=>{var a;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(a=r.data)==null?void 0:a.byteLength})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:l.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(Se.FRAME,{keyFrame:e})}isVP9(){return!0}destroy(){this._removeWorker(),c.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var ps=16*1024,ls=11,On=ps-ls,us=65536,Zi=0,Et=class{constructor(e,t){this._destroyed=!1;this._needKeyframe=!0;c.debug("ScreenCaptureSender started"),this._datachannel=t;let i=(r,a)=>{if(!this._destroyed){if(!r){c.warn("requestFrame failed, keyFrame: "+this._needKeyframe,a),this._needKeyframe=!0,this._requestFrame();return}this._send(r).catch(s=>{c.warn("sendFrame failed",s),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};vt.isBrowserSupported()?this._encoder=new vt(e,i):this._encoder=new Ot(e,i),this._datachannel.onmessage=r=>{wn(r.data)&&(c.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0)},this._encoder.init().then(()=>this._requestFrame()).catch(r=>c.warn("ScreenCaptureSender init failed",r))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,a){let s=An(e,t,i,r,Zi,this._encoder.isVP9(),a);return Zi=(Zi+1)%us,s}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return o(this,null,function*(){return new Promise((t,i)=>{this._sendChunk(e,0,t,i)})})}_sendChunk(e,t,i,r){if(!this._datachannel||this._datachannel.readyState!=="open"){r();return}let a=e.data.slice(t,t+On),s=e.data.byteLength<=t+a.byteLength,d=this._wrapHeader(e.timestamp,!t,s,e.type==="key",a);this._datachannel.onbufferedamountlow=s?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null;try{this._datachannel.send(d)}catch(p){c.warn("Error send data to DataChannel",p),r();return}s||window.setTimeout(()=>this._sendChunk(e,t+On,i,r),0)}destroy(){this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),c.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return vt.isBrowserSupported()||Ot.isBrowserSupported()}};var ie=class{static get sessionKey(){return ie._sessionKey}static set sessionKey(e){ie._sessionKey=e}static get sessionSecretKey(){return ie._sessionSecretKey}static set sessionSecretKey(e){ie._sessionSecretKey=e}static get accessToken(){return ie._accessToken}static set accessToken(e){ie._accessToken=e}static isEmpty(){return!ie._sessionKey||!ie._sessionSecretKey}};var v=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(v._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(v._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(v._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(ie.accessToken=e.apiAuth.accessToken,ie.sessionKey=e.apiAuth.sessionKey,ie.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(v._params,e)}static get(e){return v._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.5.2-dev.75f890a.0"}static get debug(){return!1}static get protocolVersion(){return 5}static get platform(){return v._params.platform}static set platform(e){v._params.platform=e}static get clientType(){return v._params.clientType}static set clientType(e){v._params.clientType=e}static get device(){return v._params.device}static get apiAppId(){return 42}static get apiKey(){return v._params.apiKey}static get apiEnv(){return v._params.apiEnv}static get apiEndpoint(){switch(v.apiEnv){case"AUTO":case"PROD":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return v._params.apiEnv}}static get authToken(){return v._params.authToken}static set authToken(e){v._params.authToken=e}static get anonymToken(){return v._params.anonymToken}static set anonymToken(e){v._params.anonymToken=e}static get domain(){return v._params.domain}static get iceServers(){return v._params.iceServers}static set iceServers(e){v._params.iceServers=e}static get wssBase(){return v._params.wssBase}static set wssBase(e){v._params.wssBase=e}static get wssToken(){return v._params.wssToken}static set wssToken(e){v._params.wssToken=e}static get signalingReconnectDelay(){return v._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return v._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return v._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return v._params.waitConnectionDelay}static get waitResponseDelay(){return v._params.waitResponseDelay}static get waitMessageDelay(){return v._params.waitMessageDelay}static get debugLog(){return v._params.debugLog}static get forceRelayPolicy(){return v._params.forceRelayPolicy}static set forceRelayPolicy(e){v._params.forceRelayPolicy=e}static get videoMinWidth(){return v._params.videoMinWidth}static get videoMaxWidth(){return v._params.videoMaxWidth}static set videoMaxWidth(e){v._params.videoMaxWidth=e}static get videoMinHeight(){return v._params.videoMinHeight}static get videoMaxHeight(){return v._params.videoMaxHeight}static set videoMaxHeight(e){v._params.videoMaxHeight=e}static get videoAspectRatio(){return v._params.videoAspectRatio}static get videoFrameRate(){return v._params.videoFrameRate}static get videoFacingMode(){return v._params.videoFacingMode}static get screenFrameRate(){return v._params.screenFrameRate}static get videoEffects(){return v._params.videoEffects}static set videoEffects(e){v._params.videoEffects=e}static get videoEffectMaxWidth(){return v._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){v._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return v._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){v._params.videoEffectMaxHeight=e}static get voiceParams(){return v._params.voiceParams}static get specListenerParams(){return v._params.specListenerParams}static get iceRestartWaitTime(){return v._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return v._params.transportConnectionWaitTime}static get statisticsInterval(){return v._params.statisticsInterval}static set statisticsInterval(e){v._params.statisticsInterval=e}static get networkStatisticsInterval(){return v._params.networkStatisticsInterval}static get perfStatReportEnabled(){return v._params.perfStatReportEnabled}static get callStatReportEnabled(){return v._params.callStatReportEnabled}static get producerNotificationDataChannel(){return v._params.producerNotificationDataChannel&&rt.isBrowserSupported()}static get producerCommandDataChannel(){return v._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return v._params.consumerScreenDataChannel&&Et.isBrowserSupported()}static get producerScreenDataChannel(){return v._params.producerScreenDataChannel&&v.producerNotificationDataChannel}static get screenShareWebmBuilder(){return v._params.screenShareWebmBuilder}static get noiseSuppression(){return v._params.noiseSuppression}static set noiseSuppression(e){v._params.noiseSuppression=e}static get preferH264(){return v._params.preferH264}static get preferVP9(){return v._params.preferVP9}static get audioNack(){return v._params.audioNack}static get consumerScreenTrack(){return v._params.consumerScreenTrack&&v.consumerScreenDataChannel}static get producerScreenTrack(){return v._params.producerScreenTrack&&v.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=v._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get movieShare(){return v._params.movieShare&&v.videoTracksCount>0}static get videoTracksCount(){return v.producerNotificationDataChannel?v._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return v._params.breakVideoPayloadTypes}static get filteredMessages(){return v._params.filteredMessages}static get batchParticipantsOnStart(){return v._params.batchParticipantsOnStart}static get participantStateMapped(){return v._params.participantStateMapped}},l=v;l._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!1,producerScreenTrack:!1,videoTracksCount:0,movieShare:!1,filteredMessages:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!1,participantStateMapped:!1};var J=(p=>(p.WAITING_HALL="WAITING_HALL",p.WAITING="WAITING",p.CONNECTING="CONNECTING",p.CONNECTED="CONNECTED",p.RECONNECT="RECONNECT",p.ERROR="ERROR",p.HANGUP="HANGUP",p.PERMISSIONS="PERMISSIONS",p))(J||{});function V(n,...e){let t=l.get(n);t&&setTimeout(t,0,...e)}function He(n){return Object.assign({},n)}function Tt(n){return n.slice()}var er;(he=>{function n(I,B){V("onLocalStream",I,He(B))}he.onLocalStream=n;function e(I,B){V("onScreenStream",I,He(B))}he.onScreenStream=e;function t(I,B){V("onLocalStreamUpdate",He(I),B)}he.onLocalStreamUpdate=t;function i(I){V("onLocalStatus",I)}he.onLocalStatus=i;function r(I,B){V("onRemoteStream",I,B)}he.onRemoteStream=r;function a(I,B,de){V("onRemoteLive",I,B,de)}he.onRemoteLive=a;function s(I,B){V("onRemoteScreenStream",I,B)}he.onRemoteScreenStream=s;function d(I,B,de,yt){V("onConversation",I,He(B),He(de),yt)}he.onConversation=d;function p(I,B){V("onRemoteMediaSettings",I,He(B))}he.onRemoteMediaSettings=p;function u(I,B){V("onRemoteParticipantState",I,He(B))}he.onRemoteParticipantState=u;function _(I,B,de=null){V("onRemoteStatus",I,B,de)}he.onRemoteStatus=_;function f(I,B,de=null){V("onParticipantStatus",I,B,de)}he.onParticipantStatus=f;function W(){V("onPermissionsRequested")}he.onPermissionsRequested=W;function K(I){V("onPermissionsError",I)}he.onPermissionsError=K;function k(I){V("onRemoteRemoved",I)}he.onRemoteRemoved=k;function Y(I,B,de){V("onCallState",I,B,He(de))}he.onCallState=Y;function se(I,B){V("onDeviceSwitched",I,B)}he.onDeviceSwitched=se;function ce(I,B,de,yt=!1,li=!1,ui=null,sa=null){V("onMuteStates",He(I),Tt(B),Tt(de),yt,li,ui,sa)}he.onMuteStates=ce;function dt(I,B){V("onRolesChanged",I,Tt(B))}he.onRolesChanged=dt;function ue(I){V("onLocalRolesChanged",Tt(I))}he.onLocalRolesChanged=ue;function $(I,B){V("onPinnedParticipant",I,B)}he.onPinnedParticipant=$;function Oe(I){V("onLocalPin",I)}he.onLocalPin=Oe;function It(I){V("onOptionsChanged",Tt(I))}he.onOptionsChanged=It;function mr(){V("onCallAccepted")}he.onCallAccepted=mr;function _r(){V("onRateNeeded")}he.onRateNeeded=_r;function C(I){V("onSpeakerChanged",I)}he.onSpeakerChanged=C;function R(I){V("onVolumesDetected",Tt(I))}he.onVolumesDetected=R;function M(I,B){V("onLocalVolume",I,B)}he.onLocalVolume=M;function b(I,B){V("onJoinStatus",I,B)}he.onJoinStatus=b;function w(I,B){V("onHangup",I,B)}he.onHangup=w;function Pe(I){V("onMultipartyChatCreated",He(I))}he.onMultipartyChatCreated=Pe;function Z(){V("onDeviceChange")}he.onDeviceChange=Z;function U(I){V("onFingerprintChange",I)}he.onFingerprintChange=U;function ee(){V("onTokenExpired")}he.onTokenExpired=ee;function A(I,B,de=!1){V("onChatMessage",I,B,de)}he.onChatMessage=A;function q(I,B,de=!1){V("onCustomData",I,B,de)}he.onCustomData=q;function pe(I,B,de,yt,li,ui){V("onRecordStarted",I,B,de,yt,li,ui)}he.onRecordStarted=pe;function D(){V("onRecordStopped")}he.onRecordStopped=D;function Ge(I){V("onLocalNetworkStatusChanged",I)}he.onLocalNetworkStatusChanged=Ge;function z(I){V("onNetworkStatusChanged",I)}he.onNetworkStatusChanged=z;function Ne(I,...B){V("onDebugMessage",I,...B)}he.onDebugMessage=Ne;function _e(I,B){let de=Object.assign({},I,{memory:B});V("onStatistics",de)}he.onStatistics=_e;function oe(){V("onAutoplayError")}he.onAutoplayError=oe;function te(I,B,de){V("onChatRoomUpdated",I,B,de)}he.onChatRoomUpdated=te})(er||(er={}));var E=er;var tr=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(tr||{}),ir;(ue=>{let n="📞",e=($,...Oe)=>{E.onDebugMessage($,...Oe)},t=!1,i=($,Oe)=>(...It)=>{$(...It),zr(Oe,It)},r=console.debug.bind(console,n),a=console.log.bind(console,n),s=console.warn.bind(console,n),d=console.error.bind(console,n),p=e.bind(null,"DEBUG"),u=e.bind(null,"LOG"),_=e.bind(null,"WARN"),f=e.bind(null,"ERROR");ue.debug=p,ue.log=u,ue.warn=_,ue.error=f;function se(){return t}ue.enabled=se;function ce($){t=$,l.debugLog&&Si(),$?(ue.debug=l.debugLog?i(r,"DEBUG"):r,ue.log=l.debugLog?i(a,"LOG"):a,ue.warn=l.debugLog?i(s,"WARN"):s,ue.error=l.debugLog?i(d,"ERROR"):d):(ue.debug=l.debugLog?i(p,"DEBUG"):p,ue.log=l.debugLog?i(u,"LOG"):u,ue.warn=l.debugLog?i(_,"WARN"):_,ue.error=l.debugLog?i(f,"ERROR"):f)}ue.toggle=ce;function dt($,...Oe){switch($){case"DEBUG":ue.debug(...Oe);break;case"LOG":ue.log(...Oe);break;case"WARN":ue.warn(...Oe);break;case"ERROR":ue.error(...Oe);break}}ue.send=dt})(ir||(ir={}));var c=ir;var nt=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(nt||{}),re;(d=>{function n(p){return p.length?typeof p[0]=="object"?p:p.map(u=>e(u)):[]}d.fromIds=n;function e(p,u="USER"){return{id:p,type:u}}d.fromId=e;function t(p){return{id:p.id,type:p.type==="ANONYM"?"ANONYM":"USER"}}d.fromSignaling=t;function i(p){return`{"id":"${p.id}","type":"${p.type}"}`}d.toString=i;function r(p,u="USER"){return i(e(p,u))}d.fromIdToString=r;function a(p){try{return JSON.parse(p)}catch(u){throw new Error(`Failed to parse ExternalId from string '${p}'`)}}d.fromString=a;function s(p,u){return p.id===u.id&&p.type===u.type}d.compare=s})(re||(re={}));var Ce=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(Ce||{}),rr=":",kn="s",xn="m";function at(n){return n.participantId+(n.mediaType?rr+kn+n.mediaType:"")+(n.streamName?rr+xn+n.streamName:"")}function kt(n){let e=n.split(rr),t=e.shift();if(!t)throw new Error("Illegal stream description: "+n);let i={participantId:t,mediaType:null};for(let r of e)switch(r.charAt(0)){case kn:i.mediaType=hs(r.slice(1));break;case xn:i.streamName=r.slice(1);break;default:throw new Error("Unexpected parameter type "+r.charAt(0)+" in stream description "+n)}return i}function hs(n){for(let e of Object.keys(Ce))if(e===n)return Ce[e];return null}function nr(n,e){return n===null||e===null?n===null&&e===null:!(n.maxDimension!==e.maxDimension||n.maxBitrateK!==e.maxBitrateK||n.maxFramerate!==e.maxFramerate||n.degradationPreference!==e.degradationPreference)}function ii(n,e){return!(!nr(n.camera,e.camera)||!nr(n.screenSharing,e.screenSharing))}function ar(n,e){return{camera:Object.assign({},n.camera,e.camera),screenSharing:Object.assign({},n.screenSharing,e.screenSharing)}}function Nn(n){try{return btoa(JSON.stringify(n))}catch(e){c.warn("WaitingParticipant: failed convert to string",n,e)}return null}function Ln(n){try{return JSON.parse(atob(n))}catch(e){c.warn("WaitingParticipant: failed convert from string",n,e)}return null}var xt=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,m.log(g.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,m.log(g.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(c.log("Failed to fix RV"),m.log(g.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(c.log("Fixed RV"),m.log(g.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,c.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=i)}}fix(e){if(!this._mediaSource)return;let t=e.find(i=>i.kind===me.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var ri=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(!((s=this._output)==null?void 0:s.audioTrack))return;let e=y.browserName()!=="Safari",t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{c.warn("Error on play audio"),E.onAutoplayError()},r=d=>{t.srcObject=new MediaStream([d]),t.load();let p=t.play();p?p.catch(i):i()},a=()=>{var p;c.debug("Recover audio playback");let d=(p=this._output)==null?void 0:p.audioTrack;d?r(d):c.warn("Broken audio track")};t.onpause=a,t.onstalled=a,t.onerror=a,r(this._output.audioTrack),this._output.audioElement=t}_stopAudioElement(){var e,t,i;((e=this._output)==null?void 0:e.audioElement)&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(i=(t=this._output)==null?void 0:t.audioTrack)==null||i.stop()}destroy(){!this._output||(this._stopAudioElement(),this._output=null)}changeOutput(){return o(this,null,function*(){var e,t,i;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((e=this._output)==null?void 0:e.audioElement))throw new Error("Audio Element is not initialized");let r=y.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw m.log(g.ERROR,"change_output"),c.error("Output change failed",r),r}})}};var ms=90,_s=3,ni=class extends Q{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),E.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>ms?c.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=_s)&&(c.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var gs=44100,Nt=class{constructor(e,t){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=e,this._stream=t;try{let i=y.getAudioContext();this._gainNode=i.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(i.destination),this._analyser=i.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=i.createMediaStreamSource(t),this._mediaStreamSource.connect(this._analyser)}catch(i){}}get stream(){return this._stream}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=gs/this._fftBins.length,t=Math.ceil(l.voiceParams.minFreq/e),i=Math.floor(l.voiceParams.maxFreq/e);return this._fftBins.subarray(t,i)}getLevel(){let e=this._getBins(),i=e.reduce((a,s)=>a+s,0)/e.length/255,r=this._lastSmoothedLevel*l.voiceParams.smoothing+i*(1-l.voiceParams.smoothing);return this._lastSmoothedLevel=r,{real:i,smoothed:r}}destroy(){this._mediaStreamSource&&(this._mediaStreamSource.disconnect(),this._mediaStreamSource=null),this._gainNode&&(this._gainNode.disconnect(),this._gainNode=null),this._analyser&&(this._analyser.disconnect(),this._analyser=null,this._fftBins=null,this._lastSmoothedLevel=0)}};var ai=class extends Q{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&E.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,l.voiceParams.interval)};this._interval=window.setTimeout(t,l.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,Ie.SOURCE_CHANGED,r=>{r.kind===me.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new Nt("local",new MediaStream([this._track])))}_stopDetector(){this._detector&&(this._detector.destroy(),this._detector=null),this._track&&(this._track.stop(),this._track=null)}destroy(){this.unsubscribe(),this._interval&&(window.clearTimeout(this._interval),this._interval=null),this._stopDetector()}};var fs=1e3;function Re(n,e,t=0){return e in n&&n[e]?n[e]:t}function Un(...n){return e=>{for(let t of n)if(t(e))return!0;return!1}}function Je(n,e){return t=>t[n]===e}function Ss(n){return(e,t)=>e[n]-t[n]}function si(n,e){return e.reduce((t,i)=>(t[i[n]]=i,t),{})}function vs(n){let e={},t=[];for(let i of n)e[i.id]||(e[i.id]=!0,t.push(i));return t}function Es(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function sr(n){return Object.keys(n).filter(e=>n[e]!==void 0).map(e=>[e,n[e]]).reduce((e,t)=>(e[t[0]]=Es(t[1])?sr(t[1]):t[1],e),{})}function Ts(n){let e=[];for(let t of n)t.forEach(i=>e.push(i));return e}function Cs(n){return o(this,null,function*(){let e=[];return RTCRtpReceiver.prototype.getStats?(e.push(...n.getReceivers().map(t=>t.getStats())),e.push(...n.getSenders().map(t=>t.getStats()))):e.push(n.getStats()),Promise.all(e).then(Ts).then(vs)})}function Is(n){let e=n.filter(Je("type","candidate-pair")).sort(Ss("priority")).find(Un(Je("nominated",!0),Je("selected",!0)));if(!e)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let t={totalRoundTripTime:e.totalRoundTripTime||0,currentRoundTripTime:e.currentRoundTripTime||0,bytesSent:e.bytesSent,bytesReceived:e.bytesReceived},i=n.find(Je("id",e.remoteCandidateId));i&&(t=Object.assign({},t,{remote:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol}}));let r=n.find(Je("id",e.localCandidateId));return r&&(t=Object.assign({},t,{local:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol,relayProtocol:r.relayProtocol,networkType:r.networkType}})),sr(t)}function ys(n,e){let t=si("id",n),i=n.filter(Un(Je("type","inbound-rtp"),Je("type","outbound-rtp")));y.browserName()==="Firefox"&&(i=Object.values(i.reduce((a,s)=>{if(!a[s.ssrc])a[s.ssrc]=s;else{let d=Object.assign({},a[s.ssrc],s),p=a[s.ssrc].isRemote?s:a[s.ssrc];d.id=p.id,d.type=p.type,delete d.isRemote,delete d.remoteId,a[d.ssrc]=d}return a},{})));let r={};if(y.browserName()==="Safari"){let a=n.filter(Je("type","track"));r=si("trackIdentifier",a)}return i.map(a=>{let s=Number(a.ssrc),d=a.mediaType||a.kind,p=a.trackId,u=a.type,_=a.codecId;if(y.browserName()==="Safari"){let se=/^.+_([\d]+)$/.exec(a.id);if(se&&(s=parseInt(se[1],10)),d=a.id.indexOf("Audio")>0?"audio":"video",e[s]){let ce=d+"-"+e[s];r[ce]&&(p=r[ce].id)}}if(!u||!s||!d)return null;let f=Re(a,"framesDecoded"),W=Re(a,"totalInterFrameDelay"),k=(Re(a,"totalSquaredInterFrameDelay")-W*W/f)/f,Y={ssrc:s,type:u,kind:d,bytesReceived:Re(a,"bytesReceived"),bytesSent:Re(a,"bytesSent"),jitter:Re(a,"jitter"),packetsLost:Re(a,"packetsLost"),packetsReceived:Re(a,"packetsReceived"),packetsSent:Re(a,"packetsSent"),fractionLost:Re(a,"fractionLost"),pliCount:Re(a,"pliCount"),firCount:Re(a,"firCount"),nackCount:Re(a,"nackCount"),userId:e[s],interframeDelayVariance:k};if(_&&t[_]){let se=t[_];Y.clockRate=se.clockRate,Y.mimeType=se.mimeType}if(p&&t[p]){let se=t[p];Y.frameHeight=se.frameHeight,Y.frameWidth=se.frameWidth,Y.framesDecoded=se.framesDecoded,Y.framesReceived=se.framesReceived,Y.framesDropped=se.framesDropped}return sr(Y)}).filter(a=>!!a)}function Rs(n,e){if(!e||!e.rtps||!n.rtps)return n;let t=si("ssrc",n.rtps),i=si("ssrc",e.rtps),r=(n.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(a=>{let s=t[a],d=i[a];if(!(!s||!d)){if(s.bytesReceived&&s.bytesReceived>d.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-d.bytesReceived)/r)),s.bytesSent&&s.bytesSent>d.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-d.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>d.packetsReceived||s.packetsLost>d.packetsLost){let p=s.packetsLost-d.packetsLost,u=s.packetsReceived-d.packetsReceived;s.packetLoss=parseFloat((100*p/(p+u)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&d.framesDropped&&s.framesDropped>d.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-d.framesDropped)/r).toFixed(0)))}}),n}function Lt(i,r){return o(this,arguments,function*(n,e,t={}){let a=yield Cs(n),s={timestamp:Date.now(),transport:Is(a),rtps:ys(a,t)};return e?Rs(s,e):(yield T.delay(fs),Lt(n,s,t))})}var oi=.8,st=class extends Q{constructor(e,t,i,r,a){super();this._remoteSDP={};this._remoteCandidates={};this._state=F.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=a,this.subscribe(this._signaling,fe.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Ie.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Ie.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:l.iceServers,iceTransportPolicy:l.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(s){m.log(g.ERROR,"addTrack-direct"),c.error("Unable to add media source tracks",s,{participantId:this._participantId}),this._failedOnCreate=s;return}this._createOffer(!1).catch(s=>{this._state===F.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==F.IDLE&&e!==F.CLOSED&&e!==F.FAILED&&this._startStatInterval()}open(e=null){return o(this,null,function*(){if(this._isOpen){c.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(c.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(i){m.log(g.ERROR,"addTrack-direct"),c.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(F.OPENED);let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={},this._triggerEvent(N.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){ii(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent(N.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(c.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(F.FAILED)):(c.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(F.CLOSED)),this._triggerEvent(N.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(c.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(N.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,a;switch(e.notification){case O.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case O.SETTINGS_UPDATE:Object.assign(this._networkLimits.badNet,((t=e.settings)==null?void 0:t.badNet)||{}),Object.assign(this._networkLimits.goodNet,((i=e.settings)==null?void 0:i.goodNet)||{});break;case O.CUSTOM_DATA:e.data.hasOwnProperty("sdk")&&(this._remoteNetworkStat.rtt=((r=e.data.sdk)==null?void 0:r.rtt)||0,this._remoteNetworkStat.loss=((a=e.data.sdk)==null?void 0:a.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=T.getPeerIdString(e.peerId);T.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return o(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){c.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw m.log(g.ERROR,"addIceCandidate-direct"),c.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else c.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return o(this,null,function*(){if(!this._remoteCandidates[e]){c.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let i of t)try{yield this._addIceCandidate(e,i)}catch(r){}})}_setRemoteDescription(e,t){return o(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){c.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw m.log(g.ERROR,"setRemoteDescription-direct"),c.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){c.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(N.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(N.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return o(this,null,function*(){e.candidate&&this._signaling.ready&&(c.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(c.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>o(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(c.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===F.IDLE||e===F.OPENED?this._setState(F.CONNECTING):this._setState(F.RECONNECTING);break}}_onConnectionStateChange(){switch(c.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),m.log(g.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(F.CONNECTED),this._stopReconnection(),T.getPeerConnectionHostInfo(this._pc).then(e=>{e&&m.log(g.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(F.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(c.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},l.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(c.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(be.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(m.log(g.ICE_RESTART),c.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):c.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,c.error("Ice restart failed",{participantId:this._participantId}),m.log(g.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},l.iceRestartWaitTime)}_createOffer(e){return o(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return c.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw c.error("Unable to create offer",i,{participantId:this._participantId}),m.log(g.ERROR,"createOffer-direct"),i}).then(i=>o(this,null,function*(){return c.debug("Created offer",{participantId:this._participantId,offer:i}),i=st._patchDescription(i),c.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw c.error("Unable to set local description",i,{participantId:this._participantId}),m.log(g.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return o(this,null,function*(){return c.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw c.error("Unable to create answer",e,{participantId:this._participantId}),m.log(g.ERROR,"createAnswer-direct"),e}).then(e=>o(this,null,function*(){return c.debug("Created answer",{participantId:this._participantId,answer:e}),e=st._patchDescription(e),c.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw c.error("Unable to set local description",e,{participantId:this._participantId}),m.log(g.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!y.baseChromeVersion();return e.sdp=T.patchSDP(e.sdp,l.preferH264&&y.canPreferH264(),y.isBrokenH264(),l.preferVP9,t&&l.audioNack),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{c.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),m.log(g.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Lt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:be.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:be.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(N.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,l.statisticsInterval)})};this._statInterval=window.setTimeout(e,l.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=ce=>ce.rtt<=this._networkLimits.goodNet.rtt&&ce.loss<=this._networkLimits.goodNet.loss,i=ce=>ce.rtt>=this._networkLimits.badNet.rtt||ce.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,a=e.inbound.rtps.reduce((ce,dt)=>Math.max(ce,dt.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-oi)+r*oi,loss:this._lastNetworkStat.loss*(1-oi)+a*oi},d=i(s),p=t(s),u=i(this._remoteNetworkStat),_=t(this._remoteNetworkStat),f=i(this._lastNetworkStat),W=t(this._lastNetworkStat),Y=d||u?.2:p&&_?1:0,se=Date.now();if((f!==d||W!==p||se-this._lastNetworkStat.date>l.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(ce=>{c.warn("Unable to send [bad-net]",ce)})),Y){let ce={};ce[this._participantId]=ce[""]=Y,this._triggerEvent(N.NETWORK_STATUS,ce)}this._lastNetworkStat.rtt=s.rtt,this._lastNetworkStat.loss=s.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=T.sdpFingerprint(e);this._fingerprint===null?this._fingerprint=t:(E.onFingerprintChange(this._fingerprint.xor(t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=T.applySettings(this._pc,e,this._prevConsumerSettings))}};var Bn=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(Bn||{}),Ut=Bn;var ot=Me(require("messagepack"));var or=class{constructor(){this.streamDescriptionByCompactId=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}handleMessage(e){var a,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let d=(0,ot.decode)(r);return Object.entries(d).forEach(([k,Y])=>{let se=kt(k);this.streamDescriptionByCompactId.set(Y,se)}),null;case 2:case 4:let p=(0,ot.decode)(r),u=[];for(let k of p){let Y=this.getStreamDescription(k);Y&&u.push(Y.participantId)}return i===2?{type:"notification",notification:O.AUDIO_ACTIVITY,activeParticipants:u}:{type:"notification",notification:O.STALLED_ACTIVITY,stalledParticipants:u};case 3:let _=(0,ot.decode)(r);return{type:"notification",notification:O.SPEAKER_CHANGED,speaker:(a=this.getStreamDescription(_))==null?void 0:a.participantId};case 5:let f=(0,ot.decode)(r);return{type:"notification",notification:O.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:f[0],maxDimension:f[1]}};case 6:let W=(0,ot.decode)(r),K={};for(let[k,Y]of Object.entries(W)){let se=(s=this.getStreamDescription(Number(k)))==null?void 0:s.participantId;se&&(K[se]=Y/100)}return{type:"notification",notification:O.NETWORK_STATUS,statuses:K};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return c.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=(0,ot.decode)(e),i=[];for(let[r,a]of Object.entries(t)){let s=a[0],d=a[1],p=a[2],u;if(s!==null){if(u=this.getStreamDescription(s),!u){c.error(`could not uncompress participant ID ${s}`);continue}}else u=null;if(p===null){c.error("unexpected null sequenceNumber",r,a);continue}let _=ke.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,f=d?d>>>0:null;i.push({participantStreamDescription:u,streamId:_,rtpTimestamp:f,sequenceNumber:p})}return{type:"notification",notification:O.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var Fn="videochat-epi",bs=5e3,Ps=3e4,Bt=class extends Q{constructor(e,t){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0};this._signaling=t,this.subscribe(e,N.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(Fn)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return o(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();l.perfStatReportEnabled&&this._previousTimestamp+bs<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),l.callStatReportEnabled&&this._previousCallStatReportTimestamp+Ps<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return o(this,null,function*(){let t=e.inbound.rtps.reduce((i,r)=>(r.kind==="video"&&(i.framesDecoded+=r.framesDecoded||0,i.framesReceived+=r.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem(Fn,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,a)=>(a.kind==="video"?(a.jitter&&(r.jitter_video=r.jitter_video*r.inbound_video_count/(r.inbound_video_count+1)+a.jitter*1e3/(r.inbound_video_count+1),r.interframe_delay_variance=r.interframe_delay_variance*r.inbound_video_count/(r.inbound_video_count+1)+a.interframeDelayVariance*1e6/(r.inbound_video_count+1),r.inbound_video_count++),r.frames_dropped+=a.framesDropped,r.nack_received+=a.nackCount||0,r.pli_received+=a.pliCount||0,r.fir_received+=a.firCount||0):a.jitter&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+a.jitter*1e3/(r.inbound_audio_count+1),r.inbound_audio_count++),r),t),e.outbound.rtps.reduce((r,a)=>(a.kind==="video"&&(r.nack_sent+=a.nackCount||0,r.pli_sent+=a.pliCount||0,r.fir_sent+=a.firCount||0),r),t);let i={nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),m.logCustom("callStat",i),this._previousCallStatReport=t}};var Ms=90,As=4294967295,De=class extends Q{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._reconnectionPrevented=!1;this._state=F.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._signaling=e,this._mediaSource=t,this.subscribe(this._signaling,fe.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,Ie.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,Ie.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,Ie.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new Bt(this,e),this._serverSettings=i,c.debug("ServerTransport: Created")}getState(){return this._state||F.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==F.IDLE&&e!==F.CLOSED&&e!==F.FAILED&&this._startStatInterval()}open(){if(this._isOpen){c.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(c.error("ServerTransport: Closed",e),this._setState(F.FAILED)):(c.debug("ServerTransport: Closed"),this._setState(F.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){ii(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>{var t;return(t=e.track)==null?void 0:t.stop()}),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,De._closeDataChannel(this._producerNotification),De._closeDataChannel(this._producerCommand),De._closeDataChannel(this._producerScreen),De._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(N.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){c.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{c.debug(`[${t}] data channel opened`),r.onerror=a=>{c.error(`[${t}] data channel error`,a)},i(r)}}_openConnection(e=!1){c.debug("ServerTransport: Open single connection");let t={};y.baseChromeVersion()&&(t.sdpSemantics=De._isUnifiedPlanSupported()?"unified-plan":"plan-b"),this._pc=new RTCPeerConnection(t,{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=T.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=De._onSignalingStateChange.bind(this,this._pc),l.producerNotificationDataChannel&&this._createDataChannel(this._pc,Ut.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new or,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),l.producerCommandDataChannel&&this._createDataChannel(this._pc,Ut.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),l.producerScreenDataChannel&&this._createDataChannel(this._pc,Ut.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){c.error("ServerTransport: Unable to add media source tracks",i),m.log(g.ERROR,"addTrack-single"),this.close(i);return}l.consumerScreenDataChannel&&this._createDataChannel(this._pc,Ut.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(F.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==F.OPENED&&(this._setState(F.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(N.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(N.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(N.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(N.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
- `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${ke.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,r=new RegExp(i).exec(t);r&&(this._ssrcMap[r[1]]=r[3])})}_createCaptureSender(e){!e||!l.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new Et(e,this._consumerScreen))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!l.producerScreenDataChannel||!this._producerScreen||!this._participantIdRegistry||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new rt(this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,e,null)}))}replayShare(e){var t;!this._participantIdRegistry||((t=this._captureReceiver)==null||t.destroy(),this._captureReceiver=new rt(e,this._participantIdRegistry,(i,r)=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,i,r)},i=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,i,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!l.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==me.video)return;let r=!this._disabledSenders.has(i),a=e.maxDimension!==0;if(r&&!a){c.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(y.getBlackMediaTrack()).catch(d=>{c.error("Could not disable video upload",d)});return}let s=this._mediaSource.getSendVideoTrack();if(!r&&a&&s){c.log("Enabling video upload"),this._disabledSenders.delete(i);let d=i.track;d.enabled=s.enabled,i.replaceTrack(s).then(()=>d.stop()).catch(p=>{c.error("Could not enable video upload",p)})}T.applyVideoTrackSettings(e,i,s!=null?s:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(N.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,l.statisticsInterval)};this._statInterval=window.setTimeout(e,l.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return o(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield Lt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(N.REMOTE_DATA_STATS,{inbound:{topology:be.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:be.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(s=>s.type==="inbound-rtp"&&s.kind==="audio"&&this._ssrcMap[s.ssrc]==="mix");if(!t)return;let i=ke.AUDIO_MIX,r=this._statBytes[i],a=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(a=!0),r.stalled!==a&&this._triggerEvent(N.REMOTE_ALL_STALL,a)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:a}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:Bt.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:l.producerNotificationDataChannel?6:0,producerCommandDataChannelVersion:l.producerCommandDataChannel?2:0,consumerScreenDataChannelVersion:l.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:l.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:De._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:l.videoTracksCount};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return o(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,c.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(c.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw c.error("[single] unable to set remote offer",i),m.log(g.ERROR,"setRemoteDescription-single"),i}).then(()=>o(this,null,function*(){if(c.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this._pc.createAnswer()})).catch(i=>{throw c.error("[single] unable to create answer",i),m.log(g.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=T.patchSDP(i.sdp,!1,y.isBrokenH264(),!1),i)).then(i=>o(this,null,function*(){if(c.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw c.error("[single] unable to set local answer",i),m.log(g.ERROR,"setLocalDescription-single"),i}).then(i=>o(this,null,function*(){c.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),c.debug("[single] remote offer has been processed")})).catch(i=>{c.warn("[single] unable to send local answer",i),m.log(g.ERROR,"acceptProducer")}).then(()=>o(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){c.debug("[single] there is other unprocessed remote offer, process it");let i=this._producerNextOffer;return this._producerNextOffer=null,this._acceptProducer(i)}})).catch(i=>this.close(i))})}_onSignalingNotification(e){return o(this,null,function*(){if(!!this._isOpen)switch(e.notification){case O.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case O.REALLOC_CON:this._reconnect();break;case O.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case O.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case O.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case O.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return o(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),l.breakVideoPayloadTypes&&(c.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes")),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){c.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=a=>{this._triggerEvent(N.REMOTE_TRACK_REMOVED,i.id,i,a.track)}),i.getTracks().find(a=>a.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(N.REMOTE_TRACK_ADDED,i.id,i,t.track)):c.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){c.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(c.debug("[single] connection state changed",{state:e.connectionState},t),m.log(g.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===F.IDLE||i===F.OPENED?this._setState(F.CONNECTING):e.iceConnectionState==="checking"&&this._setState(F.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(F.RECONNECTING);break;case"connected":this._setState(F.CONNECTED),T.getPeerConnectionHostInfo(e).then(r=>{r&&m.log(g.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(l.consumerScreenDataChannel&&t&&(e=t),this._pc.getSenders().forEach(i=>{i.track&&i.track.kind===e.kind&&!this._disabledSenders.has(i)&&(i.track.enabled=e.enabled,i.replaceTrack(e).catch(r=>{c.error("ServerTransport: Unable to replace track",r),m.log(g.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=y.baseChromeVersion();return e?l.isUnifiedPlanSupported("Chrome",e):l.isUnifiedPlanSupported(y.browserName(),y.browserVersion())}getStreamWaitingTimeMs(e,t){if(!this._pc)return m.log(g.PAT_WAITING_TIME_ERROR,"noConnection"),c.error("Cannot get stream waiting time, peer connection is not initialized"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return m.log(g.PAT_WAITING_TIME_ERROR,"noReceiver"),c.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return c.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let s=r[0].rtpTimestamp;if(!Number.isInteger(s))return m.log(g.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),c.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${s}`),0;let d=t-s&As,p=Math.ceil(d/Ms);return Math.min(100,Math.max(0,p))}};var N=(k=>(k.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",k.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",k.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",k.REMOTE_ALL_STALL="REMOTE_ALL_STALL",k.REMOTE_DATA_STATS="REMOTE_DATA_STATS",k.STATE_CHANGED="STATE_CHANGED",k.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",k.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",k.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",k.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",k.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",k.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",k.NETWORK_STATUS="NETWORK_STATUS",k.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",k))(N||{}),F=(d=>(d.IDLE="IDLE",d.OPENED="OPENED",d.CONNECTING="CONNECTING",d.RECONNECTING="RECONNECTING",d.CONNECTED="CONNECTED",d.CLOSED="CLOSED",d.FAILED="FAILED",d))(F||{}),be=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(be||{}),cr=class extends Q{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,fe.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){c.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null){let i=!1;for(let r of e){if(this._opened.indexOf(r)!==-1){c.warn(`The participant [${r}] has already had opened transport`);continue}if(this._allocated.indexOf(r)===-1){c.warn(`The participant [${r}] has no allocated transport`);continue}this._opened.push(r),i=!0}!i||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),c.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&c.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===O.TOPOLOGY_CHANGED)return this._onTopologyChanged(e);if(e.notification===O.RECORD_STARTED)return this._onRecordStarted(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(c.log(`Topology changed ${this._topology} -> ${e.topology}`),m.log(g.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],r=e.offerToTypes||[],a=i.length&&r.length?T.composeId(i[0],r[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){c.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&c.warn("Topology changed to DIRECT, but the allocated participants count more then one");let s=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let d=a===s;this._directTransport=this._createDirectTransport(s,d)}this._opened.indexOf(s)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new st(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!0),this._dtListeners&&this._dtListeners.length>0&&c.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT"))),i}_createServerTransport(){let e=new De(this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!1),this._stListeners&&this._stListeners.length>0&&c.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("ACTIVE_PARTICIPANTS_NO_SIGNAL",this._onTransportActiveParticipantsNoSignal.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;l.noiseSuppression!==e&&(l.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipantsNoSignal(){this._triggerEvent("ACTIVE_PARTICIPANTS_NO_SIGNAL")}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(m.log(g.PAT_WAITING_TIME_ERROR,"wrongTopology"),c.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(m.log(g.PAT_WAITING_TIME_ERROR,"noTransport"),c.error("Cannot get stream waiting time, server transport is not initialized"),0)}replayShare(e){var t;(t=this._serverTransport)==null||t.replayShare(e)}};var ct=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(ct||{}),dr=class extends Q{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,N.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,N.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,N.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onActiveParticipantsNoSignal.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===me.audio&&((r=this._detector)==null||r.destroy(),this._detector=new Nt(e,t),!this._interval)){let a=()=>{this._collectVolumes(),this._interval=window.setTimeout(a,l.voiceParams.interval)};this._interval=window.setTimeout(a,l.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===me.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===ke.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onActiveParticipantsNoSignal(){this._activeParticipants=null}};var pr=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(pr||{}),lr=class extends Q{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,ct.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,N.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,N.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onStoppedReceivingServerAudioActivity.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverAudioActivityAvailable)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let a=e[r].smoothed;a>t&&a>l.voiceParams.threshold&&(t=a,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*l.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverAudioActivityAvailable&&this._triggerEvent("SPEAKER_CHANGED",e)}_onReceivedServerAudioActivity(){this._serverAudioActivityAvailable=!0}_onStoppedReceivingServerAudioActivity(){this._serverAudioActivityAvailable=!1}};var ci=class extends Q{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,N.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,ct.VOLUMES_DETECTED,this._onVolumesDetected.bind(this))}destroy(){this.unsubscribe(),this._connectionTimeout&&window.clearTimeout(this._connectionTimeout),this._volumeTimeout&&window.clearTimeout(this._volumeTimeout)}onChangeRemoteMediaSettings(e,t){t.isAudioEnabled||(this._volumes[e]=1),t.isAudioEnabled&&(this._volumes[e]=0)}_onTransportStateChanged(e,t){e.forEach(i=>this._states[i]=t),t===F.OPENED&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),l.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),l.specListenerParams.volumeTimeout))),t===F.FAILED&&this._connectionTimeout&&(c.warn("Transport failed, send callSpecError"),m.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==F.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(c.warn("There is not connected transport, send callSpecError"),m.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`)),this._connectionTimeout=0}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0)return;let i="UNKNOWN",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),m.log(g.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&c.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var Ds=1e3,ws=1e4;var H=class extends Q{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state="IDLE";this._participantState=j.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;m.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),m.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new ri,l.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),Ds))}static current(){return H._current}static hangupAfterInit(){H._activationMutex&&!H._current&&(H._delayedHangup=!0)}static id(){var e,t;return((t=(e=H._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",a=!1,s=!1){return o(this,null,function*(){if(H._activationMutex)throw m.log(g.ERROR,"startCall"),c.warn("Conversation: there is already running activation"),new x(P.FAILED);H._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let d=this._mediaSource.getMediaSettings();t===Le.CHAT||e.length>1?this._logWithMediaSettings(g.OUTGOING_MULTIPARTY_CALL,d):this._logWithMediaSettings(g.OUTGOING_CALL,d);let p=yield this._startConversation(e,t,We.OUTGOING,i,r,a,s);if(!this._conversation)throw new x(P.UNKNOWN_ERROR);if(this._participantState=j.ACCEPTED,this._signaling.changeMediaSettings(d),yield this._registerParticipants(p.conversation.participants),this._processConnectionData(p),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),H._delayedHangup)throw new x(P.CANCELED);c.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let u=Object.values(this._participants),_;return l.batchParticipantsOnStart&&(_=T.mapSharedParticipants(u)),E.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,_),E.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),H._current=this,this._conversation.concurrent?yield this._acceptConcurrent():l.batchParticipantsOnStart||this._setParticipantsStatus(u,J.WAITING),this._conversation}catch(d){throw this._close(d,"Unable to start conversation"),d}finally{H._activationMutex=!1}})}onJoin(e){return o(this,null,function*(){if(H._activationMutex)throw m.log(g.ERROR,"joinCall"),c.warn("Conversation: there is already running activation"),new x(P.FAILED);H._activationMutex=!0,this._state="PROCESSING";try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.JOIN_CONVERSATION,t);let i=yield this._joinConversation(e);if(!this._conversation)throw new x(P.UNKNOWN_ERROR);return E.onLocalStream(this._mediaSource.getStream(),t),this._conversation.waitingHall?(c.log("In waiting hall"),H._current=this,H._activationMutex=!1,this._signaling.readyToSend(),E.onLocalStatus(J.WAITING_HALL),this._conversation):this._onJoinPart2(i)}catch(t){throw H._activationMutex=!1,this._close(t,"Unable to join conversation"),t}})}_onJoinPart2(e){return o(this,null,function*(){c.debug("Join conversation part 2"),H._activationMutex=!0;try{if(this._participantState=j.ACCEPTED,!this._conversation||!this._mediaSource)throw new x(P.UNKNOWN_ERROR);if(this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._registerParticipants(e.conversation.participants),this._processConnectionData(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),H._delayedHangup)throw new x(P.CANCELED);let t=Object.values(this._participants),i;return l.batchParticipantsOnStart&&(i=T.mapSharedParticipants(t)),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),E.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),H._current=this,l.batchParticipantsOnStart||this._setParticipantsStatus(t,J.WAITING),this._openTransport(t,!1),this._conversation}catch(t){throw this._close(t,"Unable to join conversation"),t}finally{H._activationMutex=!1}})}onPush(r){return o(this,arguments,function*(e,t=X.USER,i){if(H._activationMutex)throw c.warn("Conversation: there is already running activation"),new x(P.REJECTED);H._activationMutex=!0;try{let a=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new x(P.UNKNOWN_ERROR);if(!a.conversation.participants.find(d=>{var p;return d.state===j.CALLED&&d.id===((p=this._conversation)==null?void 0:p.userId)}))throw c.log("Push rejected (there is an active call)"),m.log(g.PUSH,"rejected"),new x(P.REJECTED);if(yield this._registerParticipants(a.conversation.participants),this._processConnectionData(a),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),m.log(g.PUSH,"accepted"),H._current=this,H._delayedHangup)throw new x(P.CANCELED);H._activationMutex=!1}catch(a){throw H._activationMutex=!1,this._close(a,"Unable to handle inbound call push"),a}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(Gt.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>T.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return o(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new x(P.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.ACCEPT_CONCURRENT,e),c.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),E.onCallAccepted(),this._state="ACTIVE",this._participantState=j.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return o(this,null,function*(){if(this._state!=="IDLE")throw m.log(g.ERROR,"acceptIncoming"),c.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new x(P.UNKNOWN_ERROR);this._state="PROCESSING",c.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(g.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=j.ACCEPTED;let i=Object.values(this._participants),r;l.batchParticipantsOnStart&&(r=T.mapSharedParticipants(i)),E.onCallAccepted(),E.onLocalStream(this._mediaSource.getStream(),t),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),E.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let a=Object.values(this._conversation.muteStates);return(a.includes(je.MUTE)||a.includes(je.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates))),this._state="ACTIVE",this._changeFeatureSet(),l.batchParticipantsOnStart||this._setParticipantsStatus(i,J.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return o(this,null,function*(){var e;if(this._state!=="IDLE")throw m.log(g.ERROR,"declineIncoming"),c.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",c.debug("Decline incoming call"),this._logWithMediaSettings(g.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=j.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(P.REJECTED)),this._close(new x(P.REJECTED))})}hangup(){return o(this,null,function*(){c.debug("Hangup");let e=this._state==="ACTIVE"?P.HUNGUP:P.CANCELED;m.log(g.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new x(e))):E.onHangup(new x(P.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return o(this,null,function*(){if(!this._signaling.ready){this._close(new x(P.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=P.UNKNOWN_ERROR);let a=i.participant;yield this._onAddParticipant(e,a,r)})}removeParticipant(e,t=!1){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){if(!this._transport)return;let i=[];for(let r of e)(r.state===j.CALLED||r.state===j.ACCEPTED)&&this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,t),this._transport&&r.state===j.ACCEPTED&&i.push(r.id);i.length&&this._transport.open(i)}_close(e,t){t&&c.error(t,e),c.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(P.FAILED):m.log(g.ERROR,e.hangup),H._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([P.CANCELED,P.NOT_FRIENDS,P.CALLEE_IS_OFFLINE,P.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===P.REJECTED&&!e.remote){E.onHangup(e,i),this.destroy();return}if(e.hangup===P.HUNGUP&&(!e.remote||this._participantState===j.CALLED)){E.onHangup(e,i),this.destroy();return}if(e.hangup===P.MISSED&&!e.remote){E.onHangup(e,i),this.destroy();return}if(e.hangup===P.SOCKET_CLOSED&&H._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===P.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=j.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),m.destroy(),this._conversation=null,H._current=null,H._delayedHangup=!1,E.onHangup(e||new x(P.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;c.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),m.destroy(),this._conversation=null,H._current=null,H._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return o(this,null,function*(){let t=yield this._api.getConversationParams(e);c.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:a}=t;if(a&&i.push(a),r){let s=r.urls.filter((d,p,u)=>u.indexOf(d)===p);s.forEach(d=>s.push(`${d}?transport=tcp`)),i.push({urls:s,username:r.username,credential:r.credential})}l.iceServers=i,l.wssBase=t.endpoint,l.wssToken=t.token,t.client_type&&(l.clientType=t.client_type)})}_startConversation(e,t,i,r,a="",s=!1,d=!1){return o(this,null,function*(){let p=T.uuid();c.debug("Conversation: start",{conversationId:p,opponentIds:e,opponentType:t,direction:i});let u=r.includes(le.VIDEO),_=yield this._api.startConversation(p,e,t,u,a,s,d);c.debug("Api.startConversation",_),yield this._getConversationParams(_.id);let f=yield this._connectSignaling(Ue.START,_);return yield this._setConversation(_,f,i),f})}_joinConversation(e){return o(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:a}=e;c.debug("Conversation: join",{conversationId:t,joinLink:a});let s=i.includes(le.VIDEO),d;if(t)d=yield this._api.joinConversation(t,s,r);else if(a)d=yield this._api.joinConversationByLink(a,s);else throw new x(P.UNKNOWN_ERROR);c.debug("Api.joinConversation",d),yield this._getConversationParams(d.id);let p=yield this._connectSignaling(Ue.JOIN,d);return yield this._setConversation(d,p,We.JOINING),p})}_prepareConversation(r){return o(this,arguments,function*(e,t=X.USER,i){c.debug("Conversation: push",{conversationId:e,type:t,peerId:i}),yield this._getConversationParams(e);let a=this._api.getUserId();if(!a)throw new x(P.UNKNOWN_ERROR);let s={id:e,peerId:i,endpoint:`${l.wssBase}?userId=${a}&entityType=${t}&conversationId=${e}&token=${l.wssToken}`,is_concurrent:!1,p2p_forbidden:!1},d=yield this._connectSignaling(Ue.ACCEPT,s);return H._current&&(H._current._participantState===j.ACCEPTED||H._current._participantState===j.CALLED)?(c.log("Push rejected (busy)"),m.log(g.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(P.BUSY),Promise.reject({hangup:P.BUSY})):(H._current&&(H._current.destroy(),H._current=null),yield this._setConversation(s,d,We.INCOMING,t),d)})}_createParticipant(e){return o(this,null,function*(){let t=Object.assign({id:null,externalId:null,mediaSettings:ve(),participantState:{},state:j.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[]},e);return e.externalId?this._api.cacheExternalId(t.id,e.externalId):t.externalId=yield this._getUserId(t.id),t})}_getUserId(e){return o(this,null,function*(){try{return yield this._api.userId(e)}catch(t){throw this._close(new x(P.NETWORK_ERROR),t),t}})}_setConversation(a,s,d){return o(this,arguments,function*(e,t,i,r=X.USER){let p=t.conversation.participants.map(W=>W.id);yield this._api.prepareUserIds(p);let u=this._api.getUserId();if(!u){let W=(t.conversation.participants||[]).find(K=>T.comparePeerId(K.peerId,t.peerId));if(!W)throw new x(P.UNKNOWN_ERROR);u=Number(W.id),W.idType&&(r=W.idType),this._api.setUserId(u)}let _=T.composeId(u,r),f=yield this._getUserId(_);this._conversation={userId:u,compositeUserId:_,externalId:f,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||be.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t)},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(l.forceRelayPolicy=e.p2p_forbidden),m.log(g.RELAY_POLICY,l.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new x(P.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||be.DIRECT,this._conversation.concurrent=e.isConcurrent||!1,this._conversation.chatId=e.conversation.multichatId,this._conversation.mediaModifiers=e.mediaModifiers,this._conversation.waitingHall=!1}_createMediaSource(){let e=new xi;return this.subscribe(e,Ie.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,Ie.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new xt(e),e}_connectSignaling(e,t){return o(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,fe.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,fe.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,fe.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_registerParticipants(e){return o(this,null,function*(){if(!!this._conversation)for(let t of e){let i=T.composeParticipantId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(c.debug(`Local roles changed: ${t.roles}`),E.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===j.HUNGUP||t.state===j.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],P.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&re.fromSignaling(t.externalId),mediaSettings:ve(t.mediaSettings),participantState:T.mapParticipantState(t),state:t.state,roles:t.roles||[],status:l.batchParticipantsOnStart?J.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),t.roles&&t.roles.length&&(c.debug(`Roles for participant [${i}] changed: ${t.roles}`),E.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){T.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0}),e.conversation.pinnedParticipantId&&this._onPinParticipant(e.conversation.pinnedParticipantId),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(Ht.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new cr(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new ni,this.subscribe(this._transport,N.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,N.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,N.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,N.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,N.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,N.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,N.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.bind(this)),this.subscribe(this._transport,N.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,N.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,N.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,N.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===We.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===j.ACCEPTED||t.state===j.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new dr(this._transport),this.subscribe(this._volumesDetector,ct.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new lr(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,pr.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new ai(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new ci(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=y.getCameras().length,t=y.getMicrophones().length;c.debug("Cameras: "+e+(y.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(y.hasMicrophonePermission()?"✔":"✖")),m.log(g.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){m.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===j.CALLED||e.state===j.ACCEPTED||this._state==="CLOSE"||!this._participants[e.id]||(t===P.HUNGUP?this._setParticipantsStatus([e],J.HANGUP):this._setParticipantsStatus([e],J.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:Ce.CAMERA,stopStream:!0}]),delete this._participants[e.id],E.onRemoteRemoved(e.externalId))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(a=>a.stop()),(i=e.secondStream)==null||i.getTracks().forEach(a=>a.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){c.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return o(this,null,function*(){c.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===j.ACCEPTED||r.state===j.CALLED)){c.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(this._participants[e]=yield this._createParticipant({id:e,externalId:t.externalId&&re.fromSignaling(t.externalId),mediaSettings:ve(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),r=this._participants[e]),this._setParticipantsStatus([r],J.WAITING),i?(r.state=j.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=j.CALLED,this._transport.allocate(r.id,!0),m.log(g.ADD_PARTICIPANT))})}_onRemoveParticipant(e){c.debug(`Remove participant [${e}]`);let t=this._participants[e];if(!t){c.warn(`Participant [${e}] isn't in conversation`);return}this._transport&&this._transport.close(t.id),m.log(g.REMOVE_PARTICIPANT)}changeDevice(e){return o(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new xt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(ne.UNKNOWN)})}toggleScreenCapturing(e){return o(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(ne.UNKNOWN)})}setVideoStream(e,t=!1){return o(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return o(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return o(this,null,function*(){if(this._mediaSource)return m.log(g.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return o(this,null,function*(){if(this._mediaSource)return m.log(g.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return o(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let a=typeof r.uid=="object"?r.uid:re.fromId(r.uid),s=re.toString(a);i[s]=r.priority}for(let r of Object.values(this._participants)){let a=re.toString(r.externalId);i.hasOwnProperty(a)&&(t[r.id]=i[a])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return o(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}updateDisplayLayout(e){return o(this,null,function*(){if(e.length<1||!this._signaling.ready)return;c.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let a=typeof r.uid=="object"?r.uid:re.fromId(r.uid),s=re.toString(a),d=this._api.getCachedOkIdByExternalId(a);if(!d){c.log(`Unknown participant external ID ${s}`);continue}let p=at({participantId:d,mediaType:r.mediaType,streamName:r.streamName}),u=this._participants[d];u&&(u.lastRequestedLayouts[p]=r),H._isStopStreaming(r)?this._streamIdByStreamDescription.has(p)&&!this._cooldownTimestampByStreamDescription.has(p)&&this._cooldownTimestampByStreamDescription.set(p,Date.now()):(this._cooldownTimestampByStreamDescription.delete(p),!this._streamIdByStreamDescription.has(p)&&l.videoTracksCount>0&&this._streamIdByStreamDescription.set(p,null),t[p]=H._layoutToString(r))}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>l.videoTracksCount;){let r=i.next();if(r.done){c.error("Cannot accommodate all streaming requests: tracks available "+l.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(r.value),t[r.value]=H._layoutToString({stopStream:!0})}yield this._sendUpdateDisplayLayout(t)})}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(c.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=kt(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===Ce.STREAM||i.mediaType===Ce.SCREEN)?E.onRemoteLive(r.externalId,i.streamName,null):E.onRemoteStream(r.externalId,null),m.log(g.PAT_DEALLOCATED)):c.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return o(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,a]of Object.entries(t.errorCodeByParticipantId||{})){let s=kt(r),d=this._participants[s.participantId];if(d){let p;typeof a!="number"?(c.warn(`Unexpected error code ${a} received for participant ${s.participantId}`),p=Hr.UNKNOWN_ERROR):p=Gr(a),i.push({externalId:d.externalId,errorReason:p})}}if(i&&i.length)throw new di("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+ws>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]=H._layoutToString({stopStream:!0})}while(!0);this._sendUpdateDisplayLayout(e)}static _isStopStreaming(e){return e.stopStream}static _layoutToString(e){if(H._isStopStreaming(e))return"ss";let t="";return e.priority!==void 0&&(t+="p="+e.priority),e.width!==void 0&&e.height!==void 0&&(t!==""&&(t+=":"),t+="sz="+Math.round(e.width)+"x"+Math.round(e.height)),e.fit!==void 0&&(t!==""&&(t+=":"),t+="fit="+e.fit),e.keyFrame&&(t!==""&&(t+=":"),t+="kf"),t}_onParticipantSourcesUpdate(e){if(this._conversation){c.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return o(this,null,function*(){c.log("Promoted in waiting hall",!e.demote),e.demote?(c.log("Kicked from waiting hall"),this._close(new x(P.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return o(this,arguments,function*(e,t=0,i=[]){c.log(`Chat room updated: ${e}`);let a=[],s=[];i.length&&(i.forEach(d=>{if(d.externalId){let p=re.fromSignaling(d.externalId);a.push(p),this._api.cacheExternalId(d.id.id,p)}else s.push(T.decomposeId(d.id.id).id)}),s.length&&!a.length&&(a=yield this._api.getExternalIdsByOkIds(s))),E.onChatRoomUpdated(e,t,a)})}_waitForStreamIfNeeded(e){var d,p;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||l.producerScreenTrack&&t.mediaType===Ce.SCREEN)return;let i=at(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){c.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),m.log(g.PAT_OUTDATED_RESPONSE);return}let a=e.streamId,s=e.rtpTimestamp?this._getWaitingTime(a,e.rtpTimestamp):0;if(s<=0){this._streamWaitTimerByStreamDescription.delete(i);let u=t.participantId,_=this._participants[u];if(!_){m.log(g.PAT_ERROR,"participantMissing"),c.error(`Could not find participant by ID: ${u}`);return}let f=this._streamByStreamId.get(a);if(!f){m.log(g.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${a}`);return}m.log(g.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,a);let W=(d=e.participantStreamDescription)==null?void 0:d.mediaType;if(W===Ce.STREAM||W===Ce.MOVIE)((p=e.participantStreamDescription)==null?void 0:p.streamName)&&E.onRemoteLive(_.externalId,e.participantStreamDescription.streamName,f);else{let K=(l.producerScreenTrack?null:_.secondStream)||f;E.onRemoteStream(_.externalId,K)}}else{c.debug(`Waiting for ${s} until stream ${a} for ${i} is switched`);let u=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),s);this._streamWaitTimerByStreamDescription.set(i,u)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(at(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(at(i)))return i}else{let i={participantId:t,mediaType:Ce.CAMERA};if(this._streamIdByStreamDescription.has(at(i)))return i;let r={participantId:t,mediaType:Ce.SCREEN};if(this._streamIdByStreamDescription.has(at(r)))return r}return c.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?T.includesOneOf(this._conversation.roles,[Ye.ADMIN,Ye.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!T.includesOneOf(this._conversation.roles,[Ye.ADMIN,Ye.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return o(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return o(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return o(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return o(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=Ar(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return o(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=Ln(e));let a=yield this._signaling.getWaitingHall(r,t,i);if(a.error)return Promise.reject(a.message);let s=a.participants||[],d=[],p=[],u=null;return s.length&&(s.forEach(_=>{if(_.externalId){let f=re.fromSignaling(_.externalId);d.push(f),this._api.cacheExternalId(_.id.id,f)}else p.push(T.decomposeId(_.id.id).id)}),p.length&&!d.length&&(d=yield this._api.getExternalIdsByOkIds(p)),a.hasMore&&(u=Nn(s[s.length-1].id))),{participants:d,pageMarker:u,totalCount:a.totalCount||0}})}promoteParticipant(e,t){return o(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return o(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let r=t.messages[i];yield this._onChatMessage(r)}}})}customData(e,t=null){return o(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return o(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return o(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(e){return o(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.addMovie(t);if(i.error)throw new Error(i.error);return{movieId:i.movieId,streamType:i.streamType}})}updateMovie(e,t,i,r){return o(this,null,function*(){var d;let a={movieId:e,participantId:(d=this._conversation)==null?void 0:d.compositeUserId};(t||t===0)&&(a.gain=t),i&&(a.offset=i),typeof r!==void 0&&(a.pause=r);let s=yield this._signaling.updateMovie(a);if(s.error)throw new Error(s.error)})}removeMovie(e){return o(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}startStream(e=!1,t=null,i=null,r="DIRECT_LINK",a=null){return o(this,null,function*(){let s={movieId:i,name:t,privacy:r,groupId:a,streamMovie:!e},d=yield this._signaling.startStream(s);return d.error?Promise.reject(d.message):d})}stopStream(){return o(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return o(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return o(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return o(this,null,function*(){var r;if(e<l.videoMinWidth||t<l.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i==null?void 0:i.effect){if(i.effect.width<l.videoMinWidth||i.effect.height<l.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");l.videoEffectMaxHeight=i.effect.height,l.videoEffectMaxWidth=i.effect.width}return l.videoMaxWidth=e,l.videoMaxHeight=t,(r=this._mediaSource)==null?void 0:r.setResolution(e,t)})}videoEffect(e){return o(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}_onLocalMediaStreamChanged(e){return o(this,null,function*(){var t;!this._conversation||(c.debug("Local media stream changed",e.mediaSettings),E.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return o(this,null,function*(){var t;if(c.log("Screen sharing changed",e.track,e.mediaSettings),l.consumerScreenTrack){let i=e.track?new MediaStream([e.track]):null;E.onScreenStream(i,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){c.debug(`Remote media settings changed [${e}]`,t);let i=this._participants[e];!i||(i.mediaSettings=t,this._state==="ACTIVE"&&E.onRemoteMediaSettings(i.externalId,t),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t))}_changeRemoteParticipantState(e,t){c.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];!i||(i.participantState=t||{},this._state==="ACTIVE"&&(l.participantStateMapped?E.onRemoteParticipantState(i.externalId,i.participantState):E.onRemoteParticipantState(i.externalId,T.mapLegacyParticipantState(i.participantState))))}_onSignalingNotification(e){switch(e.notification){case O.ACCEPTED_CALL:return this._onAcceptedCall(e);case O.HUNGUP:return this._onHungup(e);case O.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case O.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case O.CLOSED_CONVERSATION:return this._onClosedConversation(e);case O.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case O.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case O.RATE_CALL_DATA:return this._onNeedRate();case O.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case O.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case O.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case O.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case O.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case O.REGISTERED_PEER:return this._onPeerRegistered(e);case O.SWITCH_MICRO:return this._onMicSwitched(e);case O.CHAT_MESSAGE:return this._onChatMessage(e);case O.CUSTOM_DATA:return this._onCustomData(e);case O.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case O.RECORD_STOPPED:return this._onRecordInfo(null);case O.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case O.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case O.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin);case O.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case O.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case O.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case O.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants)}}_onSignalingReconnect(e){return o(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&this._onPinParticipant(this._conversation.pinnedParticipantId,!0)),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let a of e.conversation.participants){let s=T.composeParticipantId(a),d=a.roles||[];if(s===this._conversation.compositeUserId){t=ve(a.mediaSettings),bt(this._conversation.roles,d)||this._onRolesChanged(s,d);continue}r.push(s);let p=this._participants[s];if(!p)yield this._onJoinedParticipant({participantId:a.id,participant:a,mediaSettings:a.mediaSettings});else{let u=ve(a.mediaSettings);mn(u,p.mediaSettings)||this._changeRemoteMediaSettings(s,u);let _=T.mapParticipantState(a),f=p.participantState;T.isEqualParticipantState(_,f)||this._changeRemoteParticipantState(s,_),bt(d,p.roles)||this._onRolesChanged(p.id,d)}}for(let a of i)r.indexOf(a)<0&&this._removeParticipant(this._participants[a],P.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){c.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return o(this,null,function*(){let t=T.composeMessageId(e),i=T.getPeerIdString(e.peerId);if(c.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new x(P.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:ve(e.mediaSettings)}),r=this._participants[t]),r.state=j.ACCEPTED,r.mediaSettings=ve(e.mediaSettings),this._logWithMediaSettings(g.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===We.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){c.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=T.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new x(e.reason));return}let i=this._participants[t];if(!i){c.warn(`Participant [${t}] isn't in conversation`);return}this._transport&&this._transport.close(t),i.state=e.reason===P.REJECTED?j.REJECTED:j.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,P.HUNGUP)}_onAddedParticipant(e){return o(this,null,function*(){var r,a;c.debug(`Participant added [${e.participantId}]`);let t=T.composeMessageId(e),i=this._participants[t];if(i&&i.state!==j.HUNGUP&&i.state!==j.REJECTED){c.debug(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&re.fromSignaling(e.participant.externalId),mediaSettings:ve(e.participant.mediaSettings),state:e.participant.state,participantState:T.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),i.state=j.CALLED,i.mediaSettings=ve((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=T.mapParticipantState(e.participant),i.roles=((a=e.participant)==null?void 0:a.roles)||[],this._setParticipantsStatus([i],J.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onJoinedParticipant(e){return o(this,null,function*(){var r;c.debug(`Participant joined [${e.participantId}]`);let t=T.composeMessageId(e),i=this._participants[t];if(i&&i.state===j.ACCEPTED){c.warn(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&re.fromSignaling(e.participant.externalId),mediaSettings:ve(e.participant.mediaSettings),state:e.participant.state,participantState:T.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===We.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=j.ACCEPTED,i.mediaSettings=ve(e.mediaSettings),i.participantState=T.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],J.CONNECTED):this._setParticipantsStatus([i],J.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id])),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new x(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){let t=T.composeMessageId(e);this._changeRemoteMediaSettings(t,ve(e.mediaSettings))}_onParticipantStateChanged(e){let t=T.composeMessageId(e);this._changeRemoteParticipantState(t,T.mapParticipantState(e))}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),E.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return o(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=ve(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),l.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=ar(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,r={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=ar(this._serverSettings,r),c.log("Got video quality update notification",this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=T.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return o(this,null,function*(){E.onDeviceSwitched(le.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return o(this,null,function*(){let t=T.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),E.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return o(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=T.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),E.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return o(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let i=yield this._getUserId(e.initiator);E.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else E.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!bt(this._conversation.roles,t)){c.debug(`Local roles changed: ${t}`),this._conversation.roles=t,E.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!bt(i.roles,t)&&(c.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,E.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return o(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],a=e.mediaOptions||[],s=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&e.participantId!==this._conversation.compositeUserId){if(!this._isCallAdmin()){c.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let d=this._participants[e.participantId];d&&(c.debug(`Mute states for participant [${e.participantId}] changed`,i),E.onMuteStates(i,r,a,e.muteAll,e.unmute,d.externalId,s==null?void 0:s.externalId));return}T.isObjectsEquals(this._conversation.muteStates,i)&&T.isArraysEquals(this._conversation.unmuteOptions,r)&&!a.length||(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,e.adminId!==this._conversation.compositeUserId&&(yield this._processMuteState(a,e.muteAll,e.unmute,t,s)))})}_processMuteState(){return o(this,arguments,function*(e=[],t=!1,i=!1,r=null,a=null){if(!this._conversation||!this._mediaSource||this._participantState!==j.ACCEPTED)return;let s=Object.assign({},this._conversation.muteStates),d=this._conversation.unmuteOptions,p=this._mediaSource.getMediaSettings(),u=Object.entries(s);for(let[_,f]of u)if(!(f!==je.MUTE&&f!==je.MUTE_PERMANENT)&&(this._isCallAdmin()&&f===je.MUTE_PERMANENT&&(s[_]=je.MUTE),!(!e.includes(_)||i)))switch(_){case le.VIDEO:p.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(E.onDeviceSwitched(le.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case le.AUDIO:p.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(E.onDeviceSwitched(le.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case le.SCREEN_SHARING:p.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(E.onDeviceSwitched(le.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}E.onMuteStates(s,d,e,t,i,null,a==null?void 0:a.externalId)})}_onPinParticipant(e,t=!1){if(!this._conversation)return;let i=this._conversation.pinnedParticipantId;i&&i!==e&&(this._participants[i]?E.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&E.onLocalPin(!0)),this._participants[e]?E.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&E.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!Mr(this._conversation.options,e)&&(this._conversation.options=e,E.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let a;if(i===this._conversation.compositeUserId||i==="")a=this._conversation.networkRating;else if(this._participants[i])a=this._participants[i].networkRating;else continue;if(a!==r)if(i===this._conversation.compositeUserId||i==="")this._conversation.networkRating=r,E.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;c.log("Received network status update: ",e),E.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(l.producerScreenTrack){E.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,l.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){c.error("Received remote stream notification for a participant that has no track associated with it",r);return}let a=this._streamIdByStreamDescription.get(r);if(!a||this._streamWaitTimerByStreamDescription.has(r)){c.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let s=this._streamByStreamId.get(a);if(!s){m.log(g.PAT_ERROR,"streamNotFound"),c.error(`Could not find stream by ID: ${a}`);return}E.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&E.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===be.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(br.ADD_PARTICIPANT);E.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&E.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let a=this._participants[i];a&&a.externalId&&t.push({uid:a.externalId,volume:r.real})}E.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(E.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return o(this,null,function*(){c.debug(`Transport state has changed: ${t}`,e);let i;if(t===F.CONNECTED?i=J.CONNECTED:t===F.CONNECTING||t===F.OPENED?i=J.CONNECTING:t===F.RECONNECTING&&(i=J.RECONNECT),!i)return;let r=e.reduce((a,s)=>{if(s in this._participants){let d=this._participants[s];a.push(d),t===F.CONNECTED&&(d.remoteStream||(d.mediaSettings&&this._changeRemoteMediaSettings(s,d.mediaSettings),this._changeRemoteParticipantState(s,d.participantState)),this._updateDisplayLayoutFromCache(s))}else c.warn(`Participant [${s}] isn't in conversation`);return a},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return o(this,null,function*(){c.debug(`Local transport state has changed: ${e}`),e===F.CONNECTED&&E.onLocalStatus(J.CONNECTED),e===F.CONNECTING&&E.onLocalStatus(J.CONNECTING),e===F.RECONNECTING&&E.onLocalStatus(J.RECONNECT),e===F.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(P.FAILED)),this._close(new x(P.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return o(this,null,function*(){if(e.endsWith(ke.AUDIO_MIX))c.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(ke.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))c.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{c.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(c.warn(`Conversation: track added before participant [${e}]`),this._participants[e]=yield this._createParticipant({id:e}),r=this._participants[e],this._setParticipantsStatus([r],J.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(E.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===me.audio&&this._audioOutput.add(i),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;E.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),l.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(c.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case me.audio:this._removeAudioTrack(e,t,i);break;case me.video:case me.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==ke.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onRemoteActivityNoSignal(){this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)}_onTopologyChanged(e){this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let a=this._participants[r];e||this._lastStalled[r]?t.push(a):i.push(a)}t.length&&this._setParticipantsStatus(t,J.RECONNECT),i.length&&this._setParticipantsStatus(i,J.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(a=>{if(t[a]=!0,!this._lastStalled[a]){let s=this._participants[a];s&&!this._remoteAllStalled&&i.push(s)}delete this._lastStalled[a]}),Object.keys(this._lastStalled).forEach(a=>{let s=this._participants[a];s&&!this._remoteAllStalled&&r.push(s)}),i.length&&this._setParticipantsStatus(i,J.RECONNECT),r.length&&this._setParticipantsStatus(r,J.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!y.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(c.debug("Toggle join availability",{available:t,chatId:e}),E.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return o(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==be.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((a,s)=>(s.status!==t&&(s.status=t,l.batchParticipantsOnStart?a.push(s.externalId):E.onParticipantStatus(s.externalId,t,i)),a),[]);!r.length||l.batchParticipantsOnStart&&E.onRemoteStatus(r,t,i)}replayShare(e){var t;(t=this._transport)==null||t.replayShare(e)}},L=H;L._delayedHangup=!1;var di=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,di.prototype),this.participantErrors=t}};var pi;function Os(){return o(this,null,function*(){var n;if(l.apiEnv!=="AUTO")return l.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT1hcGkuX2VuZHBvaW50Lm9rLnJ1JnR5cGU9VFhU"),i=yield(yield fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(n=i==null?void 0:i.Answer[0])==null?void 0:n.data;if(!r)throw new Error("Wrong DNS response");return c.debug("Resolved API endpoint",r),r}catch(e){return c.warn("Failed to resolve API endpoint using DNS, default is used",e),l.apiEndpoint}})}function Vn(){if(!l.apiAppId||!l.apiKey)throw new x(ne.API,{message:"Required arguments apiAppId/apiAppKey not passed"})}function ur(n,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Gn(n,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${pi}/fb.do`,r)}function Hn(i){return o(this,arguments,function*(n,e={},t=!1){pi||(pi=yield Os());let r=Gn(n,e,t);return ks(r)})}function ks(n){return o(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${pi}/fb.do`,!0),i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=()=>{if(i.readyState!==XMLHttpRequest.DONE)return;let r;try{r=JSON.parse(i.responseText)}catch(a){r={result:i.responseText}}i.status!==200||r.hasOwnProperty("error_msg")?t(r):e(r)},i.send(n)})})}function Gn(n,e={},t=!1){e.method=n,e.format="JSON",e.application_key||(e.application_key=l.apiKey),t||(ie.sessionKey?e.session_key=ie.sessionKey:ie.accessToken&&(e.access_token=ie.accessToken));for(let[r,a]of Object.entries(e))typeof a=="object"&&(e[r]=JSON.stringify(a));let i="";for(let[r,a]of Object.entries(e))i&&(i+="&"),i+=`${r}=${encodeURIComponent(a)}`;return i}var Ns=10,Ls=700,Us=3e3,Ft=class extends pt{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return o(this,arguments,function*(e,t={},i=!1){let a=s=>o(this,null,function*(){try{return yield Hn(e,t,i)}catch(d){if(!d.hasOwnProperty("error_msg")&&(s++,c.debug(`${e} network error, attempt ${s}...`),s<Ns))return yield T.delay(Math.min(s*Ls,Us)),a(s);throw c.warn(e,"error",d),d}});return a(0)})}_call(r){return o(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(a){c.warn("Api call error",a);let s=ne.API;switch(a.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=P.SERVICE_DISABLED;break;case 1102:s=P.CALLEE_IS_OFFLINE;break;case 1103:s=P.NOT_FRIENDS;break;case 1104:case 1106:s=P.EXTERNAL_API_ERROR;break}throw new x(s,{message:a.error_msg,code:a.error_code})}})}userId(e){return o(this,null,function*(){let t=T.decomposeId(e).id;return ie.isEmpty()?re.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),re.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return o(this,null,function*(){ie.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return o(this,null,function*(){if(!this._uuid){let t=qe.get("uuid");t||(t=T.uuid(),qe.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:l.appVersion,client_type:"SDK_JS"}};return l.authToken&&(e.session_data.auth_token=l.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),ie.sessionKey=t.session_key,ie.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&E.onTokenExpired(),new x(ne.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${l.appName}:${l.sdkVersion}`,platform:l.platform,items:e})};ur("log.externalLog",t)}init(){Vn()}joinConversation(e,t=!1,i){return o(this,null,function*(){let r={conversationId:e,isVideo:t};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return o(this,null,function*(){let r={conversationId:e,createJoinLink:!0,isVideo:!1};return t&&(r.payload=t),l.domain&&(r.domainId=l.domain),i&&(r.requireAuthToJoin=!0),this._startConversation(r)})}startConversation(e,t,i,r=!1,a="",s=!1,d=!1){return o(this,null,function*(){let p={conversationId:e,isVideo:r};if(t&&t.length)switch(i){case Le.USER:p.uids=t.join(",");break;case Le.GROUP:p.gid=t[0];break;case Le.CHAT:p.chatId=t[0];break}return s&&(p.createJoinLink=!0),a&&(p.payload=a),l.domain&&(p.domainId=l.domain),d&&(p.requireAuthToJoin=!0),this._startConversation(p)})}_startConversation(e){return o(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return o(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return o(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return o(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1){return o(this,null,function*(){let i={joinLink:e,isVideo:t};return l.anonymToken&&(i.anonymToken=l.anonymToken),this._call("vchat.joinConversationByLink",i)})}getOkIdsByExternalIds(e){return o(this,null,function*(){let t=re.fromIds(e),i=[],r={methods:[]},a=[],s=Object.keys(this._externalUidsCache),d=Object.values(this._externalUidsCache);for(let u of t){let _=re.toString(u),f=d.indexOf(_);f>-1?i.push(Number(s[f])):(a.push(_),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:u.id,anonym:u.type===nt.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((u,_)=>{if(u.ok){let f=Number(u.ok.ok_id);this._externalUidsCache[f]=a[_],i.push(f)}}),i})}getExternalIdsByOkIds(e){return o(this,null,function*(){let t=[],i=[];for(let a of e)this._externalUidsCache.hasOwnProperty(a)?t.push(re.fromString(this._externalUidsCache[a])):i.push(a);if(!i.length)return t;let r=yield this._getExternalIdsByOkIds(i);Object.assign(this._externalUidsCache,r);for(let a of i)r.hasOwnProperty(a)&&t.push(re.fromString(r[a]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=re.toString(e),a=i.indexOf(r);return a>-1?T.composeId(t[a],X.USER):null}cacheExternalId(e,t){let i=T.decomposeId(e).id;this._externalUidsCache[i]=re.toString(t)}getConversationParams(e){return o(this,null,function*(){let t={};return l.anonymToken&&(t.anonymToken=l.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:P.HUNGUP};l.anonymToken&&(t.anonymToken=l.anonymToken),ur("vchat.hangupConversation",t)}removeHistoryRecords(e){return o(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return o(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[r,a]of Object.entries(i.external_ids))t[r]=re.fromIdToString(a,nt.USER);if(i.anonym_ids)for(let[r,a]of Object.entries(i.anonym_ids))t[r]=re.fromIdToString(a,nt.ANONYM);return t}catch(i){return t}})}getTokenForAnonym(e,t){return o(this,null,function*(){let i={id:e};return t&&(i.application_key=t),(yield this._callUnsafe("auth.getTokenForAnonym",i,!0)).token})}call(i){return o(this,arguments,function*(e,t={}){return this._call(e,t)})}};var Wn=(A=>(A.RECOVER="recover",A.ACCEPT_CALL="accept-call",A.ADD_PARTICIPANT="add-participant",A.REMOVE_PARTICIPANT="remove-participant",A.HANGUP="hangup",A.TRANSMIT_DATA="transmit-data",A.ACCEPT_PRODUCER="accept-producer",A.ALLOCATE_CONSUMER="allocate-consumer",A.CHANGE_MEDIA_SETTINGS="change-media-settings",A.CHANGE_PARTICIPANT_STATE="change-participant-state",A.CHANGE_STREAM_PRIORITIES="change-streams-priorities",A.UPDATE_DISPLAY_LAYOUT="update-display-layout",A.REPORT_PERF_STAT="report-perf-stat",A.RECORD_START="record-start",A.RECORD_STOP="record-stop",A.RECORD_SET_ROLE="record-set-role",A.RECORD_GET_STATUS="record-get-status",A.SWITCH_MICRO="switch-micro",A.SWITCH_TOPOLOGY="switch-topology",A.REQUEST_REALLOC="request-realloc",A.CHAT_MESSAGE="chat-message",A.CHAT_HISTORY="chat-history",A.CUSTOM_DATA="custom-data",A.GRANT_ROLES="grant-roles",A.MUTE_PARTICIPANT="mute-participant",A.PIN_PARTICIPANT="pin-participant",A.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",A.CHANGE_OPTIONS="change-options",A.GET_WAITING_HALL="get-waiting-hall",A.PROMOTE_PARTICIPANT="promote-participant",A.REQUEST_TEST_MODE="request-test-mode",A.ADD_MOVIE="add-movie",A.UPDATE_MOVIE="update-movie",A.REMOVE_MOVIE="remove-movie",A))(Wn||{}),G=Wn;var jn="open",Kn=[()=>l.producerScreenTrack,()=>l.videoTracksCount>0,()=>!0,()=>l.filteredMessages,()=>l.consumerScreenTrack,()=>!0,()=>l.movieShare],Bs=10,we=class extends ut{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.incomingCache=[];this.responseHandlers={};this.reconnectCount=0;this.conversationResolve=null;this.conversationReject=null;this.connected=!1;this.listenersReady=!1;this.postfix="&platform="+l.platform+"&appVersion="+l.appVersion+"&version="+l.protocolVersion+"&device="+l.device+"&capabilities="+we._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null}static _getCapabilityFlags(){let e=0;for(let t=0;t<Kn.length;t++)Kn[t]()&&(e|=1<<t);return e.toString(16).toUpperCase()}get ready(){return this.socket!==null}setEndpoint(e){this.endpoint=e}setConversationId(e){this.conversationId=e}setParticipantIdRegistry(e){this.participantIdRegistry=e}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=this._onMessage.bind(this),this._handleCommandsQueue(this.datachannelCommandsQueue)}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return o(this,null,function*(){return this.postfix+=`&clientType=${l.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){m.log(g.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return o(this,arguments,function*(e,t={},i=0){if(t.participantId){let a=T.decomposeId(t.participantId);t=Object.assign({},t,{participantId:a.id,participantType:a.type})}return this._sendRaw(e,t,i)})}_sendRaw(r){return o(this,arguments,function*(e,t={},i=0){let a=s=>{var p;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((p=this.producerCommandDataChannel)==null?void 0:p.readyState)===jn&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){m.log(g.SOCKET_ACTION,"not_opened"),c.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(m.log(g.SOCKET_ACTION,"invalid_state"),c.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(s),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((s,d)=>{let p=(_,f=!1)=>{!i||f?d(_):(c.debug("Resending a signaling message",e,u.sequence),i--,a(u))},u={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:s,reject:p};a(u)})})}_isDataChannelCommand(e){return this.producerCommandDataChannel?e===G.UPDATE_DISPLAY_LAYOUT||e===G.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===G.UPDATE_DISPLAY_LAYOUT||e===G.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return o(this,null,function*(){return this._send(G.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return o(this,null,function*(){return this._send(G.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return o(this,null,function*(){return this._send(G.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return o(this,null,function*(){return this._send(G.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return o(this,null,function*(){return this._send(G.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return o(this,null,function*(){return this._send(G.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},Bs)})}changeParticipantState(e){return o(this,null,function*(){return this._send(G.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return o(this,null,function*(){return this._send(G.ADD_PARTICIPANT,Er({participantId:e},t))})}removeParticipant(e,t=!1){return o(this,null,function*(){return this._send(G.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return o(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(G.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return o(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(G.ACCEPT_PRODUCER,i)})}changePriorities(e){return o(this,null,function*(){return this._send(G.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return o(this,null,function*(){return this._send(G.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return o(this,null,function*(){return this._send(G.ADD_MOVIE,e)})}updateMovie(e){return o(this,null,function*(){return this._send(G.UPDATE_MOVIE,e)})}removeMovie(e){return o(this,null,function*(){return this._send(G.REMOVE_MOVIE,e)})}startStream(e){return o(this,null,function*(){return this._send(G.RECORD_START,e)})}stopStream(){return o(this,null,function*(){return this._send(G.RECORD_STOP)})}recordSetRole(e,t){return o(this,null,function*(){return this._send(G.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return o(this,null,function*(){return this._send(G.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return o(this,null,function*(){return this._send(G.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return o(this,null,function*(){return this._send(G.REQUEST_REALLOC)})}reportPerfStat(e){return o(this,null,function*(){return this._send(G.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return o(this,null,function*(){return this._send(G.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return o(this,null,function*(){return this._send(G.CHAT_HISTORY,{count:e})})}customData(e,t){return o(this,null,function*(){return this._send(G.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return o(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(G.GRANT_ROLES,r)})}muteParticipant(e,t,i){return o(this,null,function*(){return this._sendRaw(G.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return o(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(G.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return o(this,null,function*(){return this._send(G.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return o(this,null,function*(){return this._send(G.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return o(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(G.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return o(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(G.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Ue.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),c.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor()}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){c.debug("Socket opened"),m.log(g.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){m.log(g.SOCKET_ACTION,"parse_error"),c.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(c.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(fe.RECONNECT,e),e.conversation.topology&&this._triggerEvent(fe.NOTIFICATION,{type:"notification",notification:O.TOPOLOGY_CHANGED,topology:e.conversation.topology})),this.lastStamp&&this._handleCachedMessages(),(t=e.recoverMessages)==null||t.forEach(i=>this._handleMessage(i)),this._handleCommandsQueue(this.websocketCommandsQueue)):!this.connected||!this.listenersReady?this.incomingCache.push(e):this._triggerEvent(fe.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(m.log(g.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(m.log(g.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new x(P.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(fe.NOTIFICATION,{notification:O.CLOSED_CONVERSATION,reason:e.reason}):this.connected||e.error==="invalid-token"?this._throwError(new Error(`Signaling error: ${e.error}`)):e.sequence||(this.conversationReject&&this.conversationReject(new x(ne.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(m.log(g.SOCKET_ACTION,"unknown_message"),c.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(fe.FAILED,e)}_onError(e){m.log(g.SOCKET_ACTION,"error"),c.error("Signaling error",e)}_onClose(e){m.log(g.SOCKET_ACTION,"closed"),c.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<we.RECONNECT_MAX_COUNT?this._reconnect():this.socket&&this._closeSocket(new Error("Connection closed"))}_closeSocket(e=null){!this.socket||(this._disconnect(),Object.values(this.responseHandlers).forEach(t=>{window.clearTimeout(t.responseTimer),e&&t.reject(new Error("Connection closed"),!0)}),this.websocketCommandsQueue=[],this.responseHandlers={},this.lastStamp=0,e&&this._throwError(new Error("Connection closed")))}_reconnect(){let e=Math.min(we.RECONNECT_MAX_DELAY,we.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));c.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),m.log(g.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Ue.RETRY),e)}_handleCommandResponse(e,t){var r;if(!this.responseHandlers.hasOwnProperty(t.sequence))return;let i=this.responseHandlers[t.sequence];window.clearTimeout(i.responseTimer),e?(delete this.responseHandlers[t.sequence],i.resolve(t)):((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],m.log(g.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),we.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){var t,i;for(;e.length>0;){let r=e.shift(),a=Object.assign({command:r.name,sequence:r.sequence},r.params);if(this._isDataChannelCommand(r.name)){if(((t=this.producerCommandDataChannel)==null?void 0:t.readyState)!==jn){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}we._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,a),we.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r),this.producerCommandDataChannel.send(JSON.stringify(a))}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){r.reject(new Error("Invalid state or socket already closed"));continue}r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,a),we.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(JSON.stringify(a))}}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new x(ne.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},we.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{c.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(Ue.RETRY)},we.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},xe=we;xe.RECONNECT_DELAY=l.signalingReconnectDelay,xe.RECONNECT_MAX_DELAY=l.signalingReconnectMaxDelay,xe.RECONNECT_MAX_COUNT=l.signalingReconnectMaxCount,xe.WAIT_CONNECTION_DELAY=l.waitConnectionDelay,xe.WAIT_RESPONSE_DELAY=l.waitResponseDelay,xe.WAIT_MESSAGE_DELAY=l.waitMessageDelay;var $n=(t=>(t.KING="KING",t.PAWN="PAWN",t))($n||{}),qn=$n;var Ct,ae,Vt=null,Fs={getCameras:y.getCameras,getMicrophones:y.getMicrophones,getOutput:y.getOutput,hasCamera:y.hasCamera,hasMicrophone:y.hasMicrophone,getSavedCamera:y.getSavedCamera,getSavedMicrophone:y.getSavedMicrophone,getSavedOutput:y.getSavedOutput,hasCameraPermission:y.hasCameraPermission,hasMicrophonePermission:y.hasMicrophonePermission,hasPermissions:y.hasPermissions,getUserMedia:y.getUserMedia,getUserVideo:y.getUserVideo,getUserAudio:y.getUserAudio,saveDeviceId:y.saveDeviceId,isBrowserSupported:y.isBrowserSupported,isScreenCapturingSupported:y.isScreenCapturingSupported,os:y.os,isMobile:y.isMobile,browserName:y.browserName,browserVersion:y.browserVersion,baseChromeVersion:y.baseChromeVersion,getAudioContext:y.getAudioContext};function Jn(n){ae=n}function Yn(n){Ct=n}function Vs(n){Vt=n}function Hs(n){l.videoEffects=n}function Gs(n){return o(this,null,function*(){if(l.set(n),y.browserName()==="Sferum"&&(l.platform=`SFERUM:${y.browserVersion()}`),ae||Jn(new Ft),Ct||Yn(()=>new xe),l.debug&&(hr.default.disableLog(!1),c.toggle(!0)),c.log(`Calls SDK ${l.sdkVersion}`,n),yield y.init(),!y.isBrowserSupported())throw new x(ne.UNSUPPORTED);ae.init()})}function Ws(a){return o(this,arguments,function*(n,e=[le.AUDIO],t="",i=!1,r=!1){let s=[],d=[];if(Array.isArray(n)?s=n.length?n:[]:n&&(s=[n]),s.length&&(d=yield ae.getOkIdsByExternalIds(s),!d.length))throw new x(P.CALLEE_IS_OFFLINE);return zn(d,Le.USER,e,t,i,r)})}function zn(s){return o(this,arguments,function*(n,e=Le.USER,t,i="",r=!1,a=!1){if(L.current())throw c.error("There is already active call"),new x(P.FAILED);return new L(ae,Ct(),Vt).onStart(n,e,t,i,r,a)})}function js(n){return o(this,null,function*(){return Qn(n)})}function Qn(i){return o(this,arguments,function*(n,e=X.USER,t){if(n===L.id())throw new Error("Push has already been processed");return new L(ae,Ct(),Vt).onPush(n,e,t)})}function Ks(n,e){return o(this,null,function*(){return ae.getTokenForAnonym(n,e)})}function $s(t){return o(this,arguments,function*(n,e={}){return ae.call(n,e)})}function qs(n){return o(this,null,function*(){return n&&(l.authToken=n),ae.authorize()})}function Js(){return o(this,arguments,function*(n=[le.AUDIO]){let e=L.current();if(e)return e.accept(n);throw new Error("Conversation not found")})}function Ys(){return o(this,null,function*(){let n=L.current();if(n)return n.decline()})}function zs(t){return o(this,arguments,function*(n,e=[le.AUDIO]){return Xn(n,e)})}function Xn(n,e,t){return o(this,null,function*(){if(L.current())throw c.error("There is already active call"),new x(P.FAILED);return new L(ae,Ct(),Vt).onJoin({conversationId:n,mediaOptions:e,chatId:t})})}function Qs(i){return o(this,arguments,function*(n,e=[le.AUDIO],t){if(L.current())throw c.error("There is already active call"),new x(P.FAILED);return t&&(l.anonymToken=t),new L(ae,Ct(),Vt).onJoin({joinLink:n,mediaOptions:e})})}function Xs(){return o(this,null,function*(){let n=L.current();if(n)return n.hangup();L.hangupAfterInit()})}function Zs(n,e){return o(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([n]);if(!t.length)throw new Error("User not found");return Zn(t[0],e)})}function Zn(n,e){return o(this,null,function*(){let t=L.current();t&&(yield t.addParticipant(T.composeId(n,X.USER),e))})}function eo(n,e=!1){return o(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([n]);return ea(t[0],e)})}function ea(n,e=!1){return o(this,null,function*(){let t=L.current();t&&(yield t.removeParticipant(T.composeId(n,X.USER),e))})}function to(n,e){return o(this,null,function*(){let t=yield y.saveDeviceId(n,e),i=L.current();return t&&i?i.changeDevice(n):Promise.reject()})}function io(n){return o(this,null,function*(){let e=L.current();return e?e.toggleScreenCapturing(n):Promise.reject()})}function ro(n,e=!1){return o(this,null,function*(){let t=L.current();t&&(yield t.setVideoStream(n,e))})}function no(n){return o(this,null,function*(){let e=L.current();e&&(yield e.toggleLocalVideo(n))})}function ao(n){return o(this,null,function*(){let e=L.current();e&&(yield e.toggleLocalAudio(n))})}function so(n,e,t){return o(this,null,function*(){let i=L.current();if(i)return i.setLocalResolution(n,e,t)})}function oo(n){return o(this,null,function*(){let e=L.current();e&&(yield e.changePriorities(n))})}function co(n){return o(this,null,function*(){let e=L.current();e&&(yield e.changeParticipantState(n))})}function po(n){return o(this,null,function*(){let e=L.current();e&&(yield e.updateDisplayLayout(n))})}function lo(n,e,t=!1){return o(this,null,function*(){let i=yield ae.getOkIdsByExternalIds([n]);return ta(i[0],e,t)})}function ta(n,e,t=!1){return o(this,null,function*(){let i=L.current();i&&(yield i.grantRoles(T.composeId(n,X.USER),e,t))})}function uo(){return o(this,arguments,function*(n=null,e,t=[]){let i=null;return n&&(i=(yield ae.getOkIdsByExternalIds([n]))[0]),ia(i,e,t)})}function ia(){return o(this,arguments,function*(n=null,e,t=[]){let i=L.current();if(i){let r=n?T.composeId(n,X.USER):null;yield i.muteParticipant(r,e,t)}})}function ho(n,e=!1){return o(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([n]);return ra(t[0],e)})}function ra(n,e=!1){return o(this,null,function*(){let t=L.current();t&&(yield t.pinParticipant(T.composeId(n,X.USER),e))})}function mo(n){return o(this,null,function*(){let e=L.current();e&&(yield e.updateMediaModifiers(n))})}function _o(n){return o(this,null,function*(){let e=L.current();e&&(yield e.changeOptions(n))})}function go(n,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield ae.getOkIdsByExternalIds([e]))[0]),na(n,t)})}function na(n,e=null){return o(this,null,function*(){let t=L.current();if(t){let i=e?T.composeId(e,X.USER):null;yield t.chatMessage(n,i)}})}function fo(n=10){return o(this,null,function*(){let e=L.current();if(e)return e.chatHistory(n)})}function So(n,e=null){return o(this,null,function*(){let t=null;return e&&(t=(yield ae.getOkIdsByExternalIds([e]))[0]),aa(n,t)})}function aa(n,e=null){return o(this,null,function*(){let t=L.current();if(t){let i=e?T.composeId(e,X.USER):null;yield t.customData(n,i)}})}function vo(n="",e=!1){return o(this,null,function*(){return(yield ae.createConversation(T.uuid(),n,e)).join_link})}function Eo(){return o(this,null,function*(){let n=L.current();return n?n.createJoinLink():Promise.reject()})}function To(){return o(this,null,function*(){let n=L.current();return n?n.removeJoinLink():Promise.reject()})}function Co(n,e){return o(this,null,function*(){return ae.getAnonymTokenByLink(n,e)})}function Io(n){let e=L.current();e&&e.setVolume(n)}function yo(n){l.forceRelayPolicy=n}function Ro(n=!1,e=null,t=null,i="DIRECT_LINK",r=null){return o(this,null,function*(){let a=L.current();return a?a.startStream(n,e,t,i,r):Promise.reject()})}function bo(){return o(this,null,function*(){let n=L.current();return n?n.stopStream():Promise.reject()})}function Po(n,e){return o(this,null,function*(){let t=L.current();if(t){let i=yield ae.getOkIdsByExternalIds([n]);return t.recordSetRole(T.composeId(i[0],X.USER),e)}return Promise.reject()})}function Mo(){return o(this,null,function*(){let n=L.current();return n?n.getStreamInfo():Promise.reject()})}function Ao(n){return o(this,null,function*(){let e=L.current();return e?e.addMovie(n):Promise.reject()})}function Do(n,e,t,i){return o(this,null,function*(){let r=L.current();return r?r.updateMovie(n,e,t,i):Promise.reject()})}function wo(n){return o(this,null,function*(){let e=L.current();return e?e.removeMovie(n):Promise.reject()})}function Oo(n){l.statisticsInterval=n;let e=L.current();if(e)return e.updateStatisticsInterval()}function ko(n){hr.default.disableLog(!n),c.toggle(n)}function xo(n,...e){!l.debugLog||c.send(n,"[external]",...e)}function No(n){return o(this,null,function*(){let e=L.current();if(e)return e.videoEffect(n)})}function Lo(n){return o(this,null,function*(){let e=L.current();e&&(yield e.setAudioStream(n))})}function Uo(n=null,e,t=!1){return o(this,null,function*(){let i=L.current();if(!i)throw new Error("Conversation not found");return i.getWaitingHall(n,e,t)})}function Bo(n,e=!1){return o(this,null,function*(){let t=L.current();if(!t)throw new Error("Conversation not found");let i=yield ae.getOkIdsByExternalIds([n]);return t.promoteParticipant(T.composeId(i[0],X.USER),e)})}function Fo(n){return o(this,null,function*(){yield ae.removeHistoryRecords(n)})}function Vo(){return L.current()}
7
+ var ca=Object.create;var Rt=Object.defineProperty;var da=Object.getOwnPropertyDescriptor;var pa=Object.getOwnPropertyNames,_r=Object.getOwnPropertySymbols,la=Object.getPrototypeOf,fr=Object.prototype.hasOwnProperty,ua=Object.prototype.propertyIsEnumerable;var Sr=Math.pow,vr=(n,e,t)=>e in n?Rt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Er=(n,e)=>{for(var t in e||(e={}))fr.call(e,t)&&vr(n,t,e[t]);if(_r)for(var t of _r(e))ua.call(e,t)&&vr(n,t,e[t]);return n};var Tr=n=>Rt(n,"__esModule",{value:!0});var hi=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),ha=(n,e)=>{Tr(n);for(var t in e)Rt(n,t,{get:e[t],enumerable:!0})},ma=(n,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of pa(e))!fr.call(n,i)&&i!=="default"&&Rt(n,i,{get:()=>e[i],enumerable:!(t=da(e,i))||t.enumerable});return n},Ie=n=>ma(Tr(Rt(n!=null?ca(la(n)):{},"default",n&&n.__esModule&&"default"in n?{get:()=>n.default,enumerable:!0}:{value:n,enumerable:!0})),n);var c=(n,e,t)=>new Promise((i,r)=>{var a=l=>{try{d(t.next(l))}catch(u){r(u)}},s=l=>{try{d(t.throw(l))}catch(u){r(u)}},d=l=>l.done?i(l.value):Promise.resolve(l.value).then(a,s);d((t=t.apply(n,e)).next())});var tn=hi(jt=>{"use strict";jt.byteLength=Ia;jt.toByteArray=Ra;jt.fromByteArray=Ma;var Fe=[],Ae=[],Ca=typeof Uint8Array!="undefined"?Uint8Array:Array,Ci="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Ze=0,Zr=Ci.length;Ze<Zr;++Ze)Fe[Ze]=Ci[Ze],Ae[Ci.charCodeAt(Ze)]=Ze;var Ze,Zr;Ae["-".charCodeAt(0)]=62;Ae["_".charCodeAt(0)]=63;function en(n){var e=n.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=n.indexOf("=");t===-1&&(t=e);var i=t===e?0:4-t%4;return[t,i]}function Ia(n){var e=en(n),t=e[0],i=e[1];return(t+i)*3/4-i}function ya(n,e,t){return(e+t)*3/4-t}function Ra(n){var e,t=en(n),i=t[0],r=t[1],a=new Ca(ya(n,i,r)),s=0,d=r>0?i-4:i,l;for(l=0;l<d;l+=4)e=Ae[n.charCodeAt(l)]<<18|Ae[n.charCodeAt(l+1)]<<12|Ae[n.charCodeAt(l+2)]<<6|Ae[n.charCodeAt(l+3)],a[s++]=e>>16&255,a[s++]=e>>8&255,a[s++]=e&255;return r===2&&(e=Ae[n.charCodeAt(l)]<<2|Ae[n.charCodeAt(l+1)]>>4,a[s++]=e&255),r===1&&(e=Ae[n.charCodeAt(l)]<<10|Ae[n.charCodeAt(l+1)]<<4|Ae[n.charCodeAt(l+2)]>>2,a[s++]=e>>8&255,a[s++]=e&255),a}function ba(n){return Fe[n>>18&63]+Fe[n>>12&63]+Fe[n>>6&63]+Fe[n&63]}function Pa(n,e,t){for(var i,r=[],a=e;a<t;a+=3)i=(n[a]<<16&16711680)+(n[a+1]<<8&65280)+(n[a+2]&255),r.push(ba(i));return r.join("")}function Ma(n){for(var e,t=n.length,i=t%3,r=[],a=16383,s=0,d=t-i;s<d;s+=a)r.push(Pa(n,s,s+a>d?d:s+a));return i===1?(e=n[t-1],r.push(Fe[e>>2]+Fe[e<<4&63]+"==")):i===2&&(e=(n[t-2]<<8)+n[t-1],r.push(Fe[e>>10]+Fe[e>>4&63]+Fe[e<<2&63]+"=")),r.join("")}});var rn=hi(Ii=>{Ii.read=function(n,e,t,i,r){var a,s,d=r*8-i-1,l=(1<<d)-1,u=l>>1,g=-7,f=t?r-1:0,W=t?-1:1,K=n[e+f];for(f+=W,a=K&(1<<-g)-1,K>>=-g,g+=d;g>0;a=a*256+n[e+f],f+=W,g-=8);for(s=a&(1<<-g)-1,a>>=-g,g+=i;g>0;s=s*256+n[e+f],f+=W,g-=8);if(a===0)a=1-u;else{if(a===l)return s?NaN:(K?-1:1)*(1/0);s=s+Math.pow(2,i),a=a-u}return(K?-1:1)*s*Math.pow(2,a-i)};Ii.write=function(n,e,t,i,r,a){var s,d,l,u=a*8-r-1,g=(1<<u)-1,f=g>>1,W=r===23?Math.pow(2,-24)-Math.pow(2,-77):0,K=i?0:a-1,k=i?1:-1,Y=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(d=isNaN(e)?1:0,s=g):(s=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+f>=1?e+=W/l:e+=W*Math.pow(2,1-f),e*l>=2&&(s++,l/=2),s+f>=g?(d=0,s=g):s+f>=1?(d=(e*l-1)*Math.pow(2,r),s=s+f):(d=e*Math.pow(2,f-1)*Math.pow(2,r),s=0));r>=8;n[t+K]=d&255,K+=k,d/=256,r-=8);for(s=s<<r|d,u+=r;u>0;n[t+K]=s&255,K+=k,s/=256,u-=8);n[t+K-k]|=Y*128}});var wi=hi(gt=>{"use strict";var yi=tn(),mt=rn(),nn=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;gt.Buffer=h;gt.SlowBuffer=xa;gt.INSPECT_MAX_BYTES=50;var Kt=2147483647;gt.kMaxLength=Kt;h.TYPED_ARRAY_SUPPORT=Aa();!h.TYPED_ARRAY_SUPPORT&&typeof console!="undefined"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function Aa(){try{var n=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(n,e),n.foo()===42}catch(t){return!1}}Object.defineProperty(h.prototype,"parent",{enumerable:!0,get:function(){if(!!h.isBuffer(this))return this.buffer}});Object.defineProperty(h.prototype,"offset",{enumerable:!0,get:function(){if(!!h.isBuffer(this))return this.byteOffset}});function Ke(n){if(n>Kt)throw new RangeError('The value "'+n+'" is invalid for option "size"');var e=new Uint8Array(n);return Object.setPrototypeOf(e,h.prototype),e}function h(n,e,t){if(typeof n=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Ri(n)}return an(n,e,t)}h.poolSize=8192;function an(n,e,t){if(typeof n=="string")return wa(n,e);if(ArrayBuffer.isView(n))return Oa(n);if(n==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof n);if(Ve(n,ArrayBuffer)||n&&Ve(n.buffer,ArrayBuffer)||typeof SharedArrayBuffer!="undefined"&&(Ve(n,SharedArrayBuffer)||n&&Ve(n.buffer,SharedArrayBuffer)))return Pi(n,e,t);if(typeof n=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var i=n.valueOf&&n.valueOf();if(i!=null&&i!==n)return h.from(i,e,t);var r=ka(n);if(r)return r;if(typeof Symbol!="undefined"&&Symbol.toPrimitive!=null&&typeof n[Symbol.toPrimitive]=="function")return h.from(n[Symbol.toPrimitive]("string"),e,t);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof n)}h.from=function(n,e,t){return an(n,e,t)};Object.setPrototypeOf(h.prototype,Uint8Array.prototype);Object.setPrototypeOf(h,Uint8Array);function sn(n){if(typeof n!="number")throw new TypeError('"size" argument must be of type number');if(n<0)throw new RangeError('The value "'+n+'" is invalid for option "size"')}function Da(n,e,t){return sn(n),n<=0?Ke(n):e!==void 0?typeof t=="string"?Ke(n).fill(e,t):Ke(n).fill(e):Ke(n)}h.alloc=function(n,e,t){return Da(n,e,t)};function Ri(n){return sn(n),Ke(n<0?0:Mi(n)|0)}h.allocUnsafe=function(n){return Ri(n)};h.allocUnsafeSlow=function(n){return Ri(n)};function wa(n,e){if((typeof e!="string"||e==="")&&(e="utf8"),!h.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var t=on(n,e)|0,i=Ke(t),r=i.write(n,e);return r!==t&&(i=i.slice(0,r)),i}function bi(n){for(var e=n.length<0?0:Mi(n.length)|0,t=Ke(e),i=0;i<e;i+=1)t[i]=n[i]&255;return t}function Oa(n){if(Ve(n,Uint8Array)){var e=new Uint8Array(n);return Pi(e.buffer,e.byteOffset,e.byteLength)}return bi(n)}function Pi(n,e,t){if(e<0||n.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(n.byteLength<e+(t||0))throw new RangeError('"length" is outside of buffer bounds');var i;return e===void 0&&t===void 0?i=new Uint8Array(n):t===void 0?i=new Uint8Array(n,e):i=new Uint8Array(n,e,t),Object.setPrototypeOf(i,h.prototype),i}function ka(n){if(h.isBuffer(n)){var e=Mi(n.length)|0,t=Ke(e);return t.length===0||n.copy(t,0,0,e),t}if(n.length!==void 0)return typeof n.length!="number"||Di(n.length)?Ke(0):bi(n);if(n.type==="Buffer"&&Array.isArray(n.data))return bi(n.data)}function Mi(n){if(n>=Kt)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Kt.toString(16)+" bytes");return n|0}function xa(n){return+n!=n&&(n=0),h.alloc(+n)}h.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==h.prototype};h.compare=function(e,t){if(Ve(e,Uint8Array)&&(e=h.from(e,e.offset,e.byteLength)),Ve(t,Uint8Array)&&(t=h.from(t,t.offset,t.byteLength)),!h.isBuffer(e)||!h.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var i=e.length,r=t.length,a=0,s=Math.min(i,r);a<s;++a)if(e[a]!==t[a]){i=e[a],r=t[a];break}return i<r?-1:r<i?1:0};h.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};h.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return h.alloc(0);var i;if(t===void 0)for(t=0,i=0;i<e.length;++i)t+=e[i].length;var r=h.allocUnsafe(t),a=0;for(i=0;i<e.length;++i){var s=e[i];if(Ve(s,Uint8Array))a+s.length>r.length?h.from(s).copy(r,a):Uint8Array.prototype.set.call(r,s,a);else if(h.isBuffer(s))s.copy(r,a);else throw new TypeError('"list" argument must be an Array of Buffers');a+=s.length}return r};function on(n,e){if(h.isBuffer(n))return n.length;if(ArrayBuffer.isView(n)||Ve(n,ArrayBuffer))return n.byteLength;if(typeof n!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof n);var t=n.length,i=arguments.length>2&&arguments[2]===!0;if(!i&&t===0)return 0;for(var r=!1;;)switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":return Ai(n).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"base64":return gn(n).length;default:if(r)return i?-1:Ai(n).length;e=(""+e).toLowerCase(),r=!0}}h.byteLength=on;function Na(n,e,t){var i=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return"";for(n||(n="utf8");;)switch(n){case"hex":return Ka(this,e,t);case"utf8":case"utf-8":return pn(this,e,t);case"ascii":return Wa(this,e,t);case"latin1":case"binary":return ja(this,e,t);case"base64":return Ha(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return $a(this,e,t);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(n+"").toLowerCase(),i=!0}}h.prototype._isBuffer=!0;function et(n,e,t){var i=n[e];n[e]=n[t],n[t]=i}h.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)et(this,t,t+1);return this};h.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)et(this,t,t+3),et(this,t+1,t+2);return this};h.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)et(this,t,t+7),et(this,t+1,t+6),et(this,t+2,t+5),et(this,t+3,t+4);return this};h.prototype.toString=function(){var e=this.length;return e===0?"":arguments.length===0?pn(this,0,e):Na.apply(this,arguments)};h.prototype.toLocaleString=h.prototype.toString;h.prototype.equals=function(e){if(!h.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:h.compare(this,e)===0};h.prototype.inspect=function(){var e="",t=gt.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"};nn&&(h.prototype[nn]=h.prototype.inspect);h.prototype.compare=function(e,t,i,r,a){if(Ve(e,Uint8Array)&&(e=h.from(e,e.offset,e.byteLength)),!h.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(t===void 0&&(t=0),i===void 0&&(i=e?e.length:0),r===void 0&&(r=0),a===void 0&&(a=this.length),t<0||i>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=i)return 0;if(r>=a)return-1;if(t>=i)return 1;if(t>>>=0,i>>>=0,r>>>=0,a>>>=0,this===e)return 0;for(var s=a-r,d=i-t,l=Math.min(s,d),u=this.slice(r,a),g=e.slice(t,i),f=0;f<l;++f)if(u[f]!==g[f]){s=u[f],d=g[f];break}return s<d?-1:d<s?1:0};function cn(n,e,t,i,r){if(n.length===0)return-1;if(typeof t=="string"?(i=t,t=0):t>2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,Di(t)&&(t=r?0:n.length-1),t<0&&(t=n.length+t),t>=n.length){if(r)return-1;t=n.length-1}else if(t<0)if(r)t=0;else return-1;if(typeof e=="string"&&(e=h.from(e,i)),h.isBuffer(e))return e.length===0?-1:dn(n,e,t,i,r);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?r?Uint8Array.prototype.indexOf.call(n,e,t):Uint8Array.prototype.lastIndexOf.call(n,e,t):dn(n,[e],t,i,r);throw new TypeError("val must be string, number or Buffer")}function dn(n,e,t,i,r){var a=1,s=n.length,d=e.length;if(i!==void 0&&(i=String(i).toLowerCase(),i==="ucs2"||i==="ucs-2"||i==="utf16le"||i==="utf-16le")){if(n.length<2||e.length<2)return-1;a=2,s/=2,d/=2,t/=2}function l(K,k){return a===1?K[k]:K.readUInt16BE(k*a)}var u;if(r){var g=-1;for(u=t;u<s;u++)if(l(n,u)===l(e,g===-1?0:u-g)){if(g===-1&&(g=u),u-g+1===d)return g*a}else g!==-1&&(u-=u-g),g=-1}else for(t+d>s&&(t=s-d),u=t;u>=0;u--){for(var f=!0,W=0;W<d;W++)if(l(n,u+W)!==l(e,W)){f=!1;break}if(f)return u}return-1}h.prototype.includes=function(e,t,i){return this.indexOf(e,t,i)!==-1};h.prototype.indexOf=function(e,t,i){return cn(this,e,t,i,!0)};h.prototype.lastIndexOf=function(e,t,i){return cn(this,e,t,i,!1)};function La(n,e,t,i){t=Number(t)||0;var r=n.length-t;i?(i=Number(i),i>r&&(i=r)):i=r;var a=e.length;i>a/2&&(i=a/2);for(var s=0;s<i;++s){var d=parseInt(e.substr(s*2,2),16);if(Di(d))return s;n[t+s]=d}return s}function Ua(n,e,t,i){return $t(Ai(e,n.length-t),n,t,i)}function Ba(n,e,t,i){return $t(Ya(e),n,t,i)}function Fa(n,e,t,i){return $t(gn(e),n,t,i)}function Va(n,e,t,i){return $t(za(e,n.length-t),n,t,i)}h.prototype.write=function(e,t,i,r){if(t===void 0)r="utf8",i=this.length,t=0;else if(i===void 0&&typeof t=="string")r=t,i=this.length,t=0;else if(isFinite(t))t=t>>>0,isFinite(i)?(i=i>>>0,r===void 0&&(r="utf8")):(r=i,i=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var a=this.length-t;if((i===void 0||i>a)&&(i=a),e.length>0&&(i<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return La(this,e,t,i);case"utf8":case"utf-8":return Ua(this,e,t,i);case"ascii":case"latin1":case"binary":return Ba(this,e,t,i);case"base64":return Fa(this,e,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Va(this,e,t,i);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}};h.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Ha(n,e,t){return e===0&&t===n.length?yi.fromByteArray(n):yi.fromByteArray(n.slice(e,t))}function pn(n,e,t){t=Math.min(n.length,t);for(var i=[],r=e;r<t;){var a=n[r],s=null,d=a>239?4:a>223?3:a>191?2:1;if(r+d<=t){var l,u,g,f;switch(d){case 1:a<128&&(s=a);break;case 2:l=n[r+1],(l&192)==128&&(f=(a&31)<<6|l&63,f>127&&(s=f));break;case 3:l=n[r+1],u=n[r+2],(l&192)==128&&(u&192)==128&&(f=(a&15)<<12|(l&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:l=n[r+1],u=n[r+2],g=n[r+3],(l&192)==128&&(u&192)==128&&(g&192)==128&&(f=(a&15)<<18|(l&63)<<12|(u&63)<<6|g&63,f>65535&&f<1114112&&(s=f))}}s===null?(s=65533,d=1):s>65535&&(s-=65536,i.push(s>>>10&1023|55296),s=56320|s&1023),i.push(s),r+=d}return Ga(i)}var ln=4096;function Ga(n){var e=n.length;if(e<=ln)return String.fromCharCode.apply(String,n);for(var t="",i=0;i<e;)t+=String.fromCharCode.apply(String,n.slice(i,i+=ln));return t}function Wa(n,e,t){var i="";t=Math.min(n.length,t);for(var r=e;r<t;++r)i+=String.fromCharCode(n[r]&127);return i}function ja(n,e,t){var i="";t=Math.min(n.length,t);for(var r=e;r<t;++r)i+=String.fromCharCode(n[r]);return i}function Ka(n,e,t){var i=n.length;(!e||e<0)&&(e=0),(!t||t<0||t>i)&&(t=i);for(var r="",a=e;a<t;++a)r+=Qa[n[a]];return r}function $a(n,e,t){for(var i=n.slice(e,t),r="",a=0;a<i.length-1;a+=2)r+=String.fromCharCode(i[a]+i[a+1]*256);return r}h.prototype.slice=function(e,t){var i=this.length;e=~~e,t=t===void 0?i:~~t,e<0?(e+=i,e<0&&(e=0)):e>i&&(e=i),t<0?(t+=i,t<0&&(t=0)):t>i&&(t=i),t<e&&(t=e);var r=this.subarray(e,t);return Object.setPrototypeOf(r,h.prototype),r};function _e(n,e,t){if(n%1!=0||n<0)throw new RangeError("offset is not uint");if(n+e>t)throw new RangeError("Trying to access beyond buffer length")}h.prototype.readUintLE=h.prototype.readUIntLE=function(e,t,i){e=e>>>0,t=t>>>0,i||_e(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r};h.prototype.readUintBE=h.prototype.readUIntBE=function(e,t,i){e=e>>>0,t=t>>>0,i||_e(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r};h.prototype.readUint8=h.prototype.readUInt8=function(e,t){return e=e>>>0,t||_e(e,1,this.length),this[e]};h.prototype.readUint16LE=h.prototype.readUInt16LE=function(e,t){return e=e>>>0,t||_e(e,2,this.length),this[e]|this[e+1]<<8};h.prototype.readUint16BE=h.prototype.readUInt16BE=function(e,t){return e=e>>>0,t||_e(e,2,this.length),this[e]<<8|this[e+1]};h.prototype.readUint32LE=h.prototype.readUInt32LE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};h.prototype.readUint32BE=h.prototype.readUInt32BE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};h.prototype.readIntLE=function(e,t,i){e=e>>>0,t=t>>>0,i||_e(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return a*=128,r>=a&&(r-=Math.pow(2,8*t)),r};h.prototype.readIntBE=function(e,t,i){e=e>>>0,t=t>>>0,i||_e(e,t,this.length);for(var r=t,a=1,s=this[e+--r];r>0&&(a*=256);)s+=this[e+--r]*a;return a*=128,s>=a&&(s-=Math.pow(2,8*t)),s};h.prototype.readInt8=function(e,t){return e=e>>>0,t||_e(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};h.prototype.readInt16LE=function(e,t){e=e>>>0,t||_e(e,2,this.length);var i=this[e]|this[e+1]<<8;return i&32768?i|4294901760:i};h.prototype.readInt16BE=function(e,t){e=e>>>0,t||_e(e,2,this.length);var i=this[e+1]|this[e]<<8;return i&32768?i|4294901760:i};h.prototype.readInt32LE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};h.prototype.readInt32BE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};h.prototype.readFloatLE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),mt.read(this,e,!0,23,4)};h.prototype.readFloatBE=function(e,t){return e=e>>>0,t||_e(e,4,this.length),mt.read(this,e,!1,23,4)};h.prototype.readDoubleLE=function(e,t){return e=e>>>0,t||_e(e,8,this.length),mt.read(this,e,!0,52,8)};h.prototype.readDoubleBE=function(e,t){return e=e>>>0,t||_e(e,8,this.length),mt.read(this,e,!1,52,8)};function Ce(n,e,t,i,r,a){if(!h.isBuffer(n))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>r||e<a)throw new RangeError('"value" argument is out of bounds');if(t+i>n.length)throw new RangeError("Index out of range")}h.prototype.writeUintLE=h.prototype.writeUIntLE=function(e,t,i,r){if(e=+e,t=t>>>0,i=i>>>0,!r){var a=Math.pow(2,8*i)-1;Ce(this,e,t,i,a,0)}var s=1,d=0;for(this[t]=e&255;++d<i&&(s*=256);)this[t+d]=e/s&255;return t+i};h.prototype.writeUintBE=h.prototype.writeUIntBE=function(e,t,i,r){if(e=+e,t=t>>>0,i=i>>>0,!r){var a=Math.pow(2,8*i)-1;Ce(this,e,t,i,a,0)}var s=i-1,d=1;for(this[t+s]=e&255;--s>=0&&(d*=256);)this[t+s]=e/d&255;return t+i};h.prototype.writeUint8=h.prototype.writeUInt8=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,1,255,0),this[t]=e&255,t+1};h.prototype.writeUint16LE=h.prototype.writeUInt16LE=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2};h.prototype.writeUint16BE=h.prototype.writeUInt16BE=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2};h.prototype.writeUint32LE=h.prototype.writeUInt32LE=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4};h.prototype.writeUint32BE=h.prototype.writeUInt32BE=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};h.prototype.writeIntLE=function(e,t,i,r){if(e=+e,t=t>>>0,!r){var a=Math.pow(2,8*i-1);Ce(this,e,t,i,a-1,-a)}var s=0,d=1,l=0;for(this[t]=e&255;++s<i&&(d*=256);)e<0&&l===0&&this[t+s-1]!==0&&(l=1),this[t+s]=(e/d>>0)-l&255;return t+i};h.prototype.writeIntBE=function(e,t,i,r){if(e=+e,t=t>>>0,!r){var a=Math.pow(2,8*i-1);Ce(this,e,t,i,a-1,-a)}var s=i-1,d=1,l=0;for(this[t+s]=e&255;--s>=0&&(d*=256);)e<0&&l===0&&this[t+s+1]!==0&&(l=1),this[t+s]=(e/d>>0)-l&255;return t+i};h.prototype.writeInt8=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1};h.prototype.writeInt16LE=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2};h.prototype.writeInt16BE=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2};h.prototype.writeInt32LE=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4};h.prototype.writeInt32BE=function(e,t,i){return e=+e,t=t>>>0,i||Ce(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function un(n,e,t,i,r,a){if(t+i>n.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function hn(n,e,t,i,r){return e=+e,t=t>>>0,r||un(n,e,t,4,34028234663852886e22,-34028234663852886e22),mt.write(n,e,t,i,23,4),t+4}h.prototype.writeFloatLE=function(e,t,i){return hn(this,e,t,!0,i)};h.prototype.writeFloatBE=function(e,t,i){return hn(this,e,t,!1,i)};function mn(n,e,t,i,r){return e=+e,t=t>>>0,r||un(n,e,t,8,17976931348623157e292,-17976931348623157e292),mt.write(n,e,t,i,52,8),t+8}h.prototype.writeDoubleLE=function(e,t,i){return mn(this,e,t,!0,i)};h.prototype.writeDoubleBE=function(e,t,i){return mn(this,e,t,!1,i)};h.prototype.copy=function(e,t,i,r){if(!h.isBuffer(e))throw new TypeError("argument should be a Buffer");if(i||(i=0),!r&&r!==0&&(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<i&&(r=i),r===i||e.length===0||this.length===0)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-i&&(r=e.length-t+i);var a=r-i;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(t,i,r):Uint8Array.prototype.set.call(e,this.subarray(i,r),t),a};h.prototype.fill=function(e,t,i,r){if(typeof e=="string"){if(typeof t=="string"?(r=t,t=0,i=this.length):typeof i=="string"&&(r=i,i=this.length),r!==void 0&&typeof r!="string")throw new TypeError("encoding must be a string");if(typeof r=="string"&&!h.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(e.length===1){var a=e.charCodeAt(0);(r==="utf8"&&a<128||r==="latin1")&&(e=a)}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(t<0||this.length<t||this.length<i)throw new RangeError("Out of range index");if(i<=t)return this;t=t>>>0,i=i===void 0?this.length:i>>>0,e||(e=0);var s;if(typeof e=="number")for(s=t;s<i;++s)this[s]=e;else{var d=h.isBuffer(e)?e:h.from(e,r),l=d.length;if(l===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<i-t;++s)this[s+t]=d[s%l]}return this};var qa=/[^+/0-9A-Za-z-_]/g;function Ja(n){if(n=n.split("=")[0],n=n.trim().replace(qa,""),n.length<2)return"";for(;n.length%4!=0;)n=n+"=";return n}function Ai(n,e){e=e||1/0;for(var t,i=n.length,r=null,a=[],s=0;s<i;++s){if(t=n.charCodeAt(s),t>55295&&t<57344){if(!r){if(t>56319){(e-=3)>-1&&a.push(239,191,189);continue}else if(s+1===i){(e-=3)>-1&&a.push(239,191,189);continue}r=t;continue}if(t<56320){(e-=3)>-1&&a.push(239,191,189),r=t;continue}t=(r-55296<<10|t-56320)+65536}else r&&(e-=3)>-1&&a.push(239,191,189);if(r=null,t<128){if((e-=1)<0)break;a.push(t)}else if(t<2048){if((e-=2)<0)break;a.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;a.push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;a.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code point")}return a}function Ya(n){for(var e=[],t=0;t<n.length;++t)e.push(n.charCodeAt(t)&255);return e}function za(n,e){for(var t,i,r,a=[],s=0;s<n.length&&!((e-=2)<0);++s)t=n.charCodeAt(s),i=t>>8,r=t%256,a.push(r),a.push(i);return a}function gn(n){return yi.toByteArray(Ja(n))}function $t(n,e,t,i){for(var r=0;r<i&&!(r+t>=e.length||r>=n.length);++r)e[r+t]=n[r];return r}function Ve(n,e){return n instanceof e||n!=null&&n.constructor!=null&&n.constructor.name!=null&&n.constructor.name===e.name}function Di(n){return n!==n}var Qa=function(){for(var n="0123456789abcdef",e=new Array(256),t=0;t<16;++t)for(var i=t*16,r=0;r<16;++r)e[i+r]=n[t]+n[r];return e}()});ha(exports,{Api:()=>Ft,BaseApi:()=>pt,BaseLogger:()=>lt,BaseSignaling:()=>ut,CallDirection:()=>We,CallType:()=>Le,ChatRoomEventType:()=>Ht,ConversationOption:()=>Gt,DebugMessageType:()=>ir,ExternalIdType:()=>at,FacingMode:()=>Ki,FatalError:()=>ne,HangupReason:()=>x,HangupType:()=>P,MediaOption:()=>le,MediaTrackKind:()=>me,MediaType:()=>Se,MuteState:()=>je,ParticipantState:()=>j,ParticipantStatus:()=>J,RecordRole:()=>Jn,Signaling:()=>xe,SignalingCommandType:()=>G,SignalingConnectionType:()=>Ue,SignalingNotification:()=>O,UserRole:()=>Ye,UserType:()=>X,Utils:()=>T,acceptCall:()=>Ys,addMovie:()=>Do,addParticipant:()=>eo,addParticipantInternal:()=>ea,apiCall:()=>qs,authorize:()=>Js,browser:()=>Vs,callInternal:()=>Qn,callTo:()=>js,captureScreen:()=>ro,changeConversationOptions:()=>_o,changeDevice:()=>io,changeParticipantState:()=>po,changePriorities:()=>co,changeVideoEffect:()=>Lo,chatHistory:()=>So,chatMessage:()=>fo,chatMessageInternal:()=>aa,createJoinLink:()=>To,customData:()=>vo,customDataInternal:()=>sa,debug:()=>xo,debugMessage:()=>No,declineCall:()=>zs,forceRelayPolicy:()=>Ro,getAnonymTokenByLink:()=>Io,getCurrentConversation:()=>Ho,getStreamInfo:()=>Ao,getTokenForAnonym:()=>$s,getWaitingHall:()=>Bo,grantRoles:()=>uo,grantRolesInternal:()=>ia,hangup:()=>Zs,init:()=>Ws,joinCall:()=>Qs,joinCallByLink:()=>Xs,joinCallInternal:()=>Zn,muteParticipant:()=>ho,muteParticipantInternal:()=>ra,pinParticipant:()=>mo,pinParticipantInternal:()=>na,processPush:()=>Ks,processPushInternal:()=>Xn,promoteParticipant:()=>Fo,recordSetRole:()=>Mo,removeHistoryRecords:()=>Vo,removeJoinLink:()=>Co,removeMovie:()=>Oo,removeParticipant:()=>to,removeParticipantInternal:()=>ta,setApi:()=>Yn,setAudioStream:()=>Uo,setLocalResolution:()=>oo,setLogger:()=>Hs,setMediaModifiers:()=>go,setSignalingFactory:()=>zn,setStatisticsInterval:()=>ko,setVideoEffects:()=>Gs,setVideoStream:()=>no,setVolume:()=>yo,startConversation:()=>Eo,startStream:()=>bo,stopStream:()=>Po,toggleLocalAudio:()=>so,toggleLocalVideo:()=>ao,updateDisplayLayout:()=>lo,updateMovie:()=>wo});var hr=Ie(require("webrtc-adapter"));var pt=class{createJoinLink(e){return c(this,null,function*(){return{join_link:"nop"}})}removeJoinLink(e){return c(this,null,function*(){return{success:!0}})}getAnonymTokenByLink(e,t){return c(this,null,function*(){return""})}log(e){}prepareUserIds(e){return c(this,null,function*(){})}getCachedOkIdByExternalId(e){return null}cacheExternalId(e,t){}hangupConversation(e){}removeHistoryRecords(e){return c(this,null,function*(){})}cleanup(){}getTokenForAnonym(e,t){return c(this,null,function*(){return""})}call(i){return c(this,arguments,function*(e,t={}){return null})}};var lt=class{log(e,t,i=!1){}destroy(){}};var Q=class{constructor(){this._handlers={};this._listeners=[]}_triggerEvent(e,...t){if(!!this._handlers.hasOwnProperty(e))for(let i of this._handlers[e])i.apply(this,t)}addEventListener(e,t){if(typeof t!="function")throw new Error("Listener should be a function");return this._handlers.hasOwnProperty(e)||(this._handlers[e]=[]),this._handlers[e].push(t),{dispose:this.removeEventListener.bind(this,e,t)}}removeEventListener(e,t){if(!this._handlers.hasOwnProperty(e))return;t||delete this._handlers[e];let i=this._handlers[e].indexOf(t);i>=0&&this._handlers[e].splice(i,1)}subscribe(e,t,i){let r=e.addEventListener(t,i);this._listeners.push(r)}unsubscribe(){this._listeners.forEach(e=>{e.dispose()})}};var ut=class extends Q{get ready(){return!0}setParticipantIdRegistry(e){}requestRealloc(){}setEndpoint(e){}setConversationId(e){}readyToSend(){}cleanup(){}requestTestMode(e){}getNextCommandSequenceNumber(){return 0}};var Cr=(i=>(i.INCOMING="INCOMING",i.OUTGOING="OUTGOING",i.JOINING="JOINING",i))(Cr||{}),We=Cr;var Ir=(i=>(i.USER="USER",i.GROUP="GROUP",i.CHAT="CHAT",i))(Ir||{}),Le=Ir;var yr=(t=>(t.ATTENDEE="ATTENDEE",t.HAND_UP="HAND_UP",t))(yr||{}),Ht=yr;var Rr=(t=>(t.ADD_PARTICIPANT="ADD_PARTICIPANT",t.RECORD="RECORD",t))(Rr||{}),br=Rr;var Pr=(i=>(i.REQUIRE_AUTH_TO_JOIN="REQUIRE_AUTH_TO_JOIN",i.AUDIENCE_MODE="AUDIENCE_MODE",i.WAITING_HALL="WAITING_HALL",i))(Pr||{}),Gt=Pr;function Mr(n,e){if(n.length!==e.length)return!1;for(let t of n)if(!e.includes(t))return!1;return!0}function Ar(n,e){let t=new Set(n);for(let[i,r]of Object.entries(e))r?t.add(i):t.delete(i);return Array.from(t)}var Dr=(k=>(k.CAMERA_PERMISSION="camera",k.MIC_PERMISSION="mic",k.CAMERA_ACCESS="cameralock",k.MIC_ACCESS="miclock",k.MIC_NOT_FOUND="nomic",k.SCREEN_PERMISSION="screenpermission",k.SCREEN_ACCESS="screenlock",k.CONNECTION="connection",k.NETWORK="network",k.UNKNOWN="unknown",k.UNSUPPORTED="unsupported",k.SIGNALING_FAILED="signalingfailed",k.API="api",k.AUTH="auth",k))(Dr||{}),ne=Dr;var wr=($=>($.CANCELED="CANCELED",$.REJECTED="REJECTED",$.REMOVED="REMOVED",$.HUNGUP="HUNGUP",$.MISSED="MISSED",$.BUSY="BUSY",$.FAILED="FAILED",$.NETWORK_ERROR="NETWORK_ERROR",$.KILLED="KILLED",$.BANNED="BANNED",$.CALLER_IS_BLOCKED="CALLER_IS_BLOCKED",$.NOT_FRIENDS="NOT_FRIENDS",$.CALLEE_IS_OFFLINE="CALLEE_IS_OFFLINE",$.UNKNOWN_ERROR="UNKNOWN_ERROR",$.UNSUPPORTED="UNSUPPORTED",$.OLD_VERSION="OLD_VERSION",$.SERVICE_DISABLED="SERVICE_DISABLED",$.EXTERNAL_API_ERROR="EXTERNAL_API_ERROR",$.SOCKET_CLOSED="SOCKET_CLOSED",$.ENDED="ENDED",$))(wr||{}),P=wr;var Or=(i=>(i.AUDIO="AUDIO",i.VIDEO="VIDEO",i.SCREEN_SHARING="SCREEN_SHARING",i))(Or||{}),le=Or;var kr=(i=>(i.UNMUTE="UNMUTE",i.MUTE="MUTE",i.MUTE_PERMANENT="MUTE_PERMANENT",i))(kr||{}),je=kr;var xr=(r=>(r.CALLED="CALLED",r.ACCEPTED="ACCEPTED",r.REJECTED="REJECTED",r.HUNGUP="HUNGUP",r))(xr||{}),j=xr;var Nr=(r=>(r.START="start",r.ACCEPT="accept",r.JOIN="join",r.RETRY="retry",r))(Nr||{}),Ue=Nr;var Lr=(i=>(i.NOTIFICATION="NOTIFICATION",i.FAILED="FAILED",i.RECONNECT="RECONNECT",i))(Lr||{}),fe=Lr;var Ur=(D=>(D.TRANSMITTED_DATA="transmitted-data",D.ACCEPTED_CALL="accepted-call",D.HUNGUP="hungup",D.PARTICIPANT_ADDED="participant-added",D.PARTICIPANT_JOINED="participant-joined",D.CLOSED_CONVERSATION="closed-conversation",D.MEDIA_SETTINGS_CHANGED="media-settings-changed",D.PARTICIPANT_STATE_CHANGED="participant-state-changed",D.RATE_CALL_DATA="rate-call-data",D.FEATURE_SET_CHANGED="feature-set-changed",D.TOPOLOGY_CHANGED="topology-changed",D.PRODUCER_UPDATED="producer-updated",D.CONSUMER_ANSWERED="consumer-answered",D.MULTIPARTY_CHAT_CREATED="multiparty-chat-created",D.FORCE_MEDIA_SETTINGS_CHANGE="force-media-settings-change",D.SETTINGS_UPDATE="settings-update",D.VIDEO_QUALITY_UPDATE="video-quality-update",D.REGISTERED_PEER="registered-peer",D.SWITCH_MICRO="switch-micro",D.RECORD_STARTED="record-started",D.RECORD_STOPPED="record-stopped",D.REALLOC_CON="realloc-con",D.AUDIO_ACTIVITY="audio-activity",D.SPEAKER_CHANGED="speaker-changed",D.STALLED_ACTIVITY="stalled-activity",D.CHAT_MESSAGE="chat-message",D.CUSTOM_DATA="custom-data",D.ROLES_CHANGED="roles-changed",D.MUTE_PARTICIPANT="mute-participant",D.PIN_PARTICIPANT="pin-participant",D.OPTIONS_CHANGED="options-changed",D.NETWORK_STATUS="network-status",D.PARTICIPANT_SOURCES_UPDATE="participant-sources-update",D.PROMOTE_PARTICIPANT="promote-participant",D.CHAT_ROOM_UPDATED="chat-room-updated",D.PROMOTION_APPROVED="promotion-approved",D.JOIN_LINK_CHANGED="join-link-changed",D))(Ur||{}),O=Ur;var Br=(b=>(b.ERROR="callError",b.DEVICES="callDevices",b.CALL_SPEC_ERROR="callSpecError",b.ICE_CONNECTION_STATE="callIceConnectionState",b.ICE_CONNECTION_TYPE="callIceConnectionType",b.ICE_RESTART="callIceRestart",b.PUSH="callPush",b.OUTGOING_CALL="callStart",b.OUTGOING_MULTIPARTY_CALL="callStartMultiparty",b.JOIN_CONVERSATION="callJoinConversation",b.ACCEPTED_OUTGOING="callAcceptedOutgoing",b.ACCEPT_INCOMING="callAcceptIncoming",b.DECLINE_INCOMING="callDeclineIncoming",b.ACCEPT_CONCURRENT="callAcceptConcurrent",b.HANGUP="callHangup",b.MEDIA_STATUS="callMediaStatus",b.DEVICE_CHANGED="callDeviceChanged",b.SOCKET_ACTION="callSocketAction",b.ADD_PARTICIPANT="callAddParticipant",b.REMOVE_PARTICIPANT="callRemoveParticipant",b.POOR_CONNECTION="callPoorConnection",b.TOPOLOGY_CHANGE_REQUESTED="callTopologyChangeRequested",b.RELAY_POLICY="callForceRelay",b.PAT_ALLOCATED="patAllocate",b.PAT_DEALLOCATED="patDeallocate",b.PAT_ERROR="patError",b.PAT_WAITING_TIME_ERROR="patWaitingTimeError",b.PAT_OUTDATED_RESPONSE="patOutdatedResponse",b))(Br||{}),_=Br;var Fr=(t=>(t.AUDIO_MIX="audio-mix",t.PARTICIPANT_AGNOSTIC_TRACK_PREFIX="pat",t))(Fr||{}),ke=Fr;var Vr=(t=>(t.NO_AVAILABLE_TRACKS="no-available-tracks",t.UNKNOWN_ERROR="unknown-error",t))(Vr||{}),Hr=Vr;function Gr(n){switch(n){case 1:return"no-available-tracks";default:return"unknown-error"}}var Wr=(t=>(t.CREATOR="CREATOR",t.ADMIN="ADMIN",t))(Wr||{}),Ye=Wr;function bt(n,e){if(n.length!==e.length)return!1;for(let t of n)if(!e.includes(t))return!1;return!0}var jr=(t=>(t.USER="USER",t.GROUP="GROUP",t))(jr||{}),X=jr;var mi=class{constructor(){this._items=[]}get length(){return this._items.length}push(e){this._items.push(e)}shift(){return this._items.shift()||null}bisect(){let e=this.length>1?Math.floor(this.length/2):1;this._items=this._items.slice(e)}clear(){this._items=[]}toString(){return this._items.length?JSON.stringify(this._items,(e,t)=>t instanceof Error?String(t):t):""}};var Kr=2*1024*1024,ga=512*1024,Pt=100*1024,_a=5,gi="_okcls_logs_session_",fa=3e4,$r=class{constructor(){this._items=[];this._itemsSize=0;this._storageSize=Kr;try{let e=window.localStorage;for(let t of Object.keys(e)){if(t.indexOf(gi)!==0)continue;let i=e.getItem(t);if(!i){Yr(t);continue}let r=Jr(i);this.add(t,r)}}catch(e){console.error("Storage is blocked",e),this._storageSize=0}this._items.sort((e,t)=>e.date-t.date),this.cleanup(Pt)}get size(){return this._itemsSize}get length(){return this._items.length}get available(){return Math.max(this._storageSize-this._itemsSize,0)}get items(){return this._items}set storageSize(e){this._storageSize=e}add(e,t){let i=parseInt(e.replace(gi,""),10);this._itemsSize+=t,this._items.push({key:e,size:t,date:i})}deleteOldestItem(){let e=this._items.shift();e&&(Yr(e.key),this._itemsSize-=e.size)}cleanup(e){for(;this.length&&(this.size>Kr||this.length>_a-1||this.size+e>this.available);)this.deleteOldestItem()}};function qr(){return`${gi}${Date.now()}`}function Jr(n){return new Blob([n]).size}function Yr(n){try{window.localStorage.removeItem(n)}catch(e){console.error("Failed to remove log from storage",e)}}function _i(){let n=ze.toString();if(!Te.available||!n)return;let e=Jr(n);Te.cleanup(e);try{window.localStorage.setItem(Wt,n)}catch(t){if(console.warn("Failed to write log to storage",t),Te.storageSize=Te.size+e,Te.cleanup(Pt+e),Te.available>=Pt+e){_i();return}if(e>Pt){ze.bisect(),_i();return}Te.storageSize=0;return}e>ga&&(Te.add(Wt,e),Wt=qr(),ze.clear(),Te.cleanup(Pt))}function fi(){!Te.available||!ze.length||_i()}function Sa(n=!1){let e=[];try{let r=window.localStorage;for(let s of Te.items){let d=r.getItem(s.key);e.push(d)}let a=ze.toString();a&&e.push(a)}catch(r){console.error("Storage is blocked",r)}let t=`[${e.join(",")}]`;if(n)return t;let i=`logs_${Date.now()}.json`;return va(t,i),i}function va(n,e){let t=document.createElement("a"),i=new Blob([n],{type:"text/json"});t.href=URL.createObjectURL(i),t.download=e,t.click()}function zr(n,e){!Te.available||(ze.push({t:Date.now(),l:n,d:e}),vi||(vi=window.setTimeout(()=>{vi=null,fi()},fa)))}function Si(){Te||(Te=new $r,ze=new mi,Wt=qr(),window.addEventListener("beforeunload",fi))}var Te,ze,Wt,vi=null;window.__VKCallsSDKLogs__=(n=!1)=>(Te||Si(),fi(),Sa(n));var Xi=Ie(require("file-saver"));var Se=(r=>(r.CAMERA="CAMERA",r.SCREEN="SCREEN",r.STREAM="STREAM",r.MOVIE="MOVIE",r))(Se||{}),Ei=":",Qr="s",Xr="m";function Qe(n){return n.participantId+(n.mediaType?Ei+Qr+n.mediaType:"")+(n.streamName?Ei+Xr+n.streamName:"")}function Mt(n){let e=n.split(Ei),t=e.shift();if(!t)throw new Error("Illegal stream description: "+n);let i={participantId:t,mediaType:null};for(let r of e)switch(r.charAt(0)){case Qr:i.mediaType=Ta(r.slice(1));break;case Xr:i.streamName=r.slice(1);break;default:throw new Error("Unexpected parameter type "+r.charAt(0)+" in stream description "+n)}return i}function Ta(n){for(let e of Object.keys(Se))if(e===n)return Se[e];return null}var Ti=Ie(require("@vkontakte/libvpx"));var ve=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(ve||{});var m=class extends lt{constructor(e,t){super();this._batchInterval=3e3;this._batch=[];this._batchTimeout=null;this._api=e,this._externalLogger=t}_send(e){this._api.log(e)}_sendBatch(){this._stopTimeout(),this._batch.length>0&&(this._send(this._batch),this._batch=[],this._startTimeout())}_startTimeout(){this._batchTimeout=window.setTimeout(()=>this._sendBatch(),this._batchInterval)}_stopTimeout(){this._batchTimeout&&(clearTimeout(this._batchTimeout),this._batchTimeout=null)}_onUnload(){this._sendBatch(),this._stopTimeout()}log(e,t,i=!1){let r={};typeof t!="undefined"&&(r.param=t),this._logInternal(e,r,i),this._externalLogger&&this._externalLogger.log(e,t,i)}logCustom(e,t,i=!1){this._logInternal(e,t,i)}_logInternal(e,t,i){let r={type:1,time:0,operation:e,timestamp:Date.now(),custom:t,uid:this._api.getUserId()};this._batch.push(r),(i||!this._batchTimeout)&&this._sendBatch()}destroy(){this._sendBatch(),this._stopTimeout(),this._externalLogger&&this._externalLogger.destroy()}static create(e,t){m._instance||(m._instance=new m(e,t))}static log(e,t,i=!1){m._instance&&m._instance.log(e,t,i)}static logCustom(e,t,i=!1){m._instance&&m._instance.logCustom(e,t,i)}static destroy(){m._instance&&m._instance.destroy(),m._instance=null}};var Be=class{constructor(){this._worker=null}_createWorker(s,d){return c(this,arguments,function*(e,t,i=[],r={},a=[]){return new Promise((l,u)=>{let g=i.join(","),f=new Blob([e,`exports.default(${g});`],{type:"application/javascript; charset=utf-8"}),W=window.URL.createObjectURL(f);this._worker=new Worker(W),this._worker.onmessage=K=>{switch(K.data.type){case ve.READY:l();break;case ve.ERROR:u(K.data.error);break;case ve.FRAME:t(K.data);break;case ve.DEBUG:o.debug(K.data.message);break;case ve.LOG_ERROR:m.log(_.ERROR,K.data.message);break}},this._sendToWorker(ve.INIT,r,a)})})}_removeWorker(){var e;(e=this._worker)==null||e.terminate(),this._worker=null}_sendToWorker(e,t={},i=[]){var r;(r=this._worker)==null||r.postMessage(Object.assign({type:e},t),i)}static isBrowserSupported(){throw new Error("Not implemented")}};var ht=class extends Be{init(e){return c(this,null,function*(){o.debug("LibVPxDecoder started"),yield this._createWorker('var exports=(()=>{var b=Object.defineProperty;var M=a=>b(a,"__esModule",{value:!0});var V=(a,i)=>{M(a);for(var e in i)b(a,e,{get:i[e],enumerable:!0})};var h={};V(h,{default:()=>D});var t=(s=>(s.INIT="init",s.READY="ready",s.FRAME="frame",s.ERROR="error",s.DEBUG="debug",s.LOG_ERROR="log_error",s))(t||{});var D=(a,i)=>{let e=null,n=null,m=!0;function R(){return a({locateFile:i}).then(r=>n=r)}function s(r,y,l,d,x,E){if(!n){self.postMessage({type:t.LOG_ERROR,message:"decoder-init-fail-libvpx"}),self.postMessage({type:t.FRAME,error:"Fatal initialization error"});return}if(m!==l&&(m=l,e&&(e=null,self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec changed to ${l?"VP9":"VP8"} - reinitialize`}))),!e&&(self.postMessage({type:t.DEBUG,message:`LibVPxDecoder codec ${l?"VP9":"VP8"}`}),e=new n.VpxDecoder,e.debug(E),!e.init(l?n.VpxType.VP9:n.VpxType.VP8))){e=null,self.postMessage({type:t.FRAME,error:"Decoder failed to create"});return}try{e.allocateBuffer(y.byteLength).set(new Uint8Array(y))}catch(o){self.postMessage({type:t.DEBUG,message:o}),e=null,self.postMessage({type:t.FRAME,error:String(o)});return}if(!(e.decode()&&e.nextImage())){self.postMessage({type:t.FRAME,error:"Decode failed for "+d});return}let c=e.getImageBuffer();if(!c){self.postMessage({type:t.FRAME,error:"No decoded data"});return}let f=e.getImageWidth(),u=e.getImageHeight();e.nextImage()&&(self.postMessage({type:t.DEBUG,message:"LibVPxDecoder dropped frame"}),self.postMessage({type:t.LOG_ERROR,message:"LibVPxDecoder-drop"}));let p=new Uint8ClampedArray(c.byteLength);if(p.set(c),x){let o=new ImageData(p,f,u);createImageBitmap(o,0,0,f,u).then(g=>{self.postMessage({type:t.FRAME,crc:d,data:g},[g]),g.close()})}else self.postMessage({type:t.FRAME,data:p.buffer,crc:d,width:f,height:u},[p.buffer])}R().then(()=>{self.onmessage=r=>{switch(r.data.type){case t.FRAME:s(r.data.timestamp,r.data.data,r.data.isVP9,r.data.crc,r.data.useImageBitmap,r.data.debug);break}},self.postMessage({type:t.READY})}).catch(r=>{self.postMessage({type:t.ERROR,error:String(r)})})};return h;})();\n',t=>{if(t.error)o.warn("LibVPxDecoder",t.error);else if(t.data instanceof ArrayBuffer){let i=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);e(i,t.crc)}else e(t.data,t.crc)},[Ti.default,Ti.default.getUrl])})}decodeFrame(e,t,i,r,a){let s="ImageBitmap"in window;this._sendToWorker(ve.FRAME,{timestamp:e,data:t.buffer,isVP9:i,crc:r,keyFrame:a,useImageBitmap:s,debug:o.enabled()},[t.buffer])}destroy(){this._removeWorker(),o.debug("LibVPxDecoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window}};var Xe=class extends Be{init(e){return c(this,null,function*(){o.debug("WebCodecsDecoder started"),yield this._createWorker('var exports=(()=>{var l=Object.defineProperty;var g=e=>l(e,"__esModule",{value:!0});var V=(e,c)=>{g(e);for(var t in c)l(e,t,{get:c[t],enumerable:!0})};var R={};V(R,{default:()=>y});var n=(t=>(t.VP9="vp09.00.50.08",t.VP8="vp8",t))(n||{}),o=(r=>(r.INIT="init",r.READY="ready",r.FRAME="frame",r.ERROR="error",r.DEBUG="debug",r.LOG_ERROR="log_error",r))(o||{});var y=()=>{let e=null,c=!0,t=[];function p(){self.postMessage({type:o.READY})}function m(a,r,d,u,f=!1){t.push(u),(!e||c!==d)&&(c=d,e?self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec changed to ${d?"VP9":"VP8"}`}):(self.postMessage({type:o.DEBUG,message:`WebCodecsDecoder codec ${d?"VP9":"VP8"}`}),e=new VideoDecoder({output:s=>{("createImageBitmap"in s?s.createImageBitmap():createImageBitmap(s)).then(i=>{self.postMessage({type:o.FRAME,crc:t&&t.length?t.pop():"",data:i}),i.close()}).finally(()=>s.close())},error:s=>{e&&e.state!=="closed"&&e.close(),e=null,self.postMessage({type:o.FRAME,error:"WebCodecsDecoder failed, reinitialize"})}})),e.configure({codec:d?n.VP9:n.VP8}));let E=new EncodedVideoChunk({type:f?"key":"delta",timestamp:a,data:r});e.decode(E)}self.onmessage=a=>{switch(a.data.type){case o.INIT:p();break;case o.FRAME:m(a.data.timestamp,a.data.data,a.data.isVP9,a.data.crc,a.data.keyFrame);break}}};return R;})();\n',t=>{t.error?o.warn("WebCod_createWorkerecsDecoder",t.error):e(t.data,t.crc)})})}decodeFrame(e,t,i,r,a=!1){this._sendToWorker(ve.FRAME,{timestamp:e,data:t.buffer,isVP9:i,crc:r,keyFrame:a},[t.buffer])}destroy(){this._removeWorker(),o.debug("WebCodecsDecoder destroyed")}static isBrowserSupported(){return"VideoDecoder"in window&&"Worker"in window&&"VideoFrame"in window&&"ImageBitmap"in window&&"createImageBitmap"in window}};var Yi=Ie(wi()),zi=Ie(require("crc"));var Oi="_okcls_",_t=(()=>{try{let n=Date.now().toString(),e=window.localStorage,t=!1;return e.setItem(n,n),t=e.getItem(n)===n,e.removeItem(n),t?e:null}catch(n){return null}})();function Xa(n){let e=_t?_t.getItem(Oi+n):null;if(e===null)return null;try{return JSON.parse(e)}catch(t){return null}}function Za(n,e){try{_t&&_t.setItem(Oi+n,JSON.stringify(e))}catch(t){}}function es(n){_t&&_t.removeItem(Oi+n)}var ki;(i=>{function n(r){return Xa(r)||null}i.get=n;function e(r,a){Za(r,a)}i.set=e;function t(r){es(r)}i.remove=t})(ki||(ki={}));var qe=ki;var ft=Ie(require("big-integer"));function _n(n,e){if(n.isAudioEnabled!==e.isAudioEnabled||n.isVideoEnabled!==e.isVideoEnabled||n.isScreenSharingEnabled!==e.isScreenSharingEnabled||n.videoStreams.length!==e.videoStreams.length)return!1;for(let t of n.videoStreams)if(!e.videoStreams.find(i=>i.id===t.id&&i.source===t.source))return!1;return!0}function Ee(n){return Object.assign({isAudioEnabled:!1,isVideoEnabled:!1,isScreenSharingEnabled:!1,videoStreams:[]},n||{})}var fn=n=>n.stop(),Sn=n=>n.getTracks().forEach(fn),xi=n=>n.getVideoTracks().forEach(fn),vn=n=>n.getVideoTracks()[0].clone();var x=class extends Error{constructor(e,t){super();this.name="HangupReason",this.code=t&&t.code||0,this.remote=t&&t.remote||!1,Object.values(P).indexOf(e)>-1?this.hangup=e:this.error=e;let i=[];this.error&&i.push("error"),this.remote&&i.push("remote"),this.code&&i.push(`code: ${this.code}`),t&&t.message&&i.push(`message: '${t.message}'`),this.message=e+(i.length?` (${i.join(", ")})`:""),Error.captureStackTrace&&Error.captureStackTrace(this,x)}};var ye=(i=>(i.SOURCE_CHANGED="SOURCE_CHANGED",i.TRACK_REPLACED="TRACK_REPLACED",i.SCREEN_STATUS="SCREEN_STATUS",i))(ye||{}),me=(i=>(i.audio="audio",i.video="video",i.screen="screen",i))(me||{}),Ni=class extends Q{constructor(){super();this._stream=null;this._trackVideoStreamBackup=null;this._screenTrack=null;this._sendVideoTrack=null;this._mediaSettings=Ee();this._videoStatusOnScreenCapturingEnabled=!1;this._effect=null;this._initDeviceChangeListener()}request(){return c(this,arguments,function*(e=[le.AUDIO]){if(this._stream)return;let t=e.includes(le.VIDEO),i=e.includes(le.AUDIO);if(!y.isBrowserSupported())throw new x(ne.UNSUPPORTED);try{this._stream=yield y.getUserMedia(t,i),this._mediaSettings.isVideoEnabled=t&&this._stream.getVideoTracks().filter(r=>r.enabled).length>0||!1,this._mediaSettings.isAudioEnabled=i&&this._stream.getAudioTracks().filter(r=>r.enabled).length>0||!1}catch(r){throw new x(r)}})}getStream(){return this._stream}getScreenTrack(){return this._screenTrack}getSendVideoTrack(e=!1){return this._sendVideoTrack&&!e?this._sendVideoTrack:this._stream?this._stream.getVideoTracks()[0]:null}_getSendAudioTrack(){var e;return((e=this._stream)==null?void 0:e.getAudioTracks()[0])||null}addTrackToPeerConnection(e,t=!1){let i=this.getStream(),r=this._getSendAudioTrack(),a=this.getSendVideoTrack(t);if(!i||!r&&!a)throw new Error("No local stream found");r&&e.addTrack(r,i),a&&e.addTrack(a,i)}getMediaSettings(){return this._mediaSettings}changeDevice(e){return c(this,null,function*(){switch(e){case"videoinput":return this._changeVideoInput();case"audioinput":return this._changeAudioInput();default:return Promise.reject()}})}setVideoStream(e,t){return c(this,null,function*(){return t?this._changeScreen(e):this._changeVideoInput(e)})}_initDeviceChangeListener(){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices||!navigator.mediaDevices.addEventListener)return;let e=!1,t=!1,i=T.throttle(()=>{t&&this._changeVideoInput().catch(()=>{}),e&&this._changeAudioInput().catch(()=>{}),e=!1,t=!1},1e3);navigator.mediaDevices.addEventListener("devicechange",()=>c(this,null,function*(){if(!this._stream)return;let r=this._stream.getAudioTracks()[0],a=r&&r.enabled&&r.getSettings(),s=a&&a.groupId,d=this._stream.getVideoTracks()[0],l=d&&d.enabled&&d.getSettings(),u=l&&l.groupId;if(!s&&!u)return;let g=yield navigator.mediaDevices.enumerateDevices();!e&&s&&(e=!g.find(f=>f.groupId===s)),!t&&u&&(t=!g.find(f=>f.groupId===u)),i()}))}_changeVideoInput(e=null){return c(this,null,function*(){try{let t=e?"stream":"video",i=e||(yield y.getUserVideo(void 0,!!this._effect));if(!this._stream)i.getTracks().forEach(r=>r.stop());else{p.consumerScreenTrack||this._disableScreenCapture();let r=this._getVideoEffectTrack(i),a=yield this._videoEffect(this._effect,r);this._stopLocalTrack("video"),m.log(_.DEVICE_CHANGED,t),o.log("Video stream changed"),yield this._replaceLocalTrack(a),this._mediaSettings.isVideoEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(_.ERROR,"change_video"),o.warn("Camera change failed",t),t}})}_getVideoEffectTrack(e){let t;return this._effect?(this._trackVideoStreamBackup||(this._trackVideoStreamBackup=vn(e)),t=this._trackVideoStreamBackup.clone(),xi(e)):this._trackVideoStreamBackup?(t=this._trackVideoStreamBackup.clone(),this._stopAndRemoveTrackVideoStreamBackup(),xi(e)):t=e.getVideoTracks()[0],t}setAudioStream(e){return c(this,null,function*(){return this._changeAudioInput(e)})}_changeAudioInput(e=null){return c(this,null,function*(){try{if(e=e||(yield y.getUserAudio()),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getAudioTracks()[0];this._stopLocalTrack("audio"),m.log(_.DEVICE_CHANGED,"audio"),o.log("Audio stream changed"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=!0,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(_.ERROR,"change_audio"),o.error("Microphone change failed",t),t}})}_changeScreen(e){return c(this,null,function*(){try{if(e=e||(yield y.getScreenMedia()),e.addEventListener("inactive",()=>{this._mediaSettings.isScreenSharingEnabled&&this.toggleScreenCapturing(!1)},!1),!this._stream)e.getTracks().forEach(t=>t.stop());else{let t=e.getVideoTracks()[0],i=p.consumerScreenTrack?t:yield this._videoEffect(null,t);m.log(_.DEVICE_CHANGED,"screen"),o.log("Screen capturing started"),this._screenTrack=i,this._mediaSettings.isScreenSharingEnabled=!0,p.consumerScreenTrack||(this._videoStatusOnScreenCapturingEnabled=this._mediaSettings.isVideoEnabled,this._mediaSettings.isVideoEnabled=!0,this._stopLocalTrack("video"),this._sendVideoTrack=p.consumerScreenDataChannel?y.getBlackMediaTrack(p.videoMinWidth,p.videoMinHeight):i,yield this._replaceLocalTrack(i,this._sendVideoTrack)),this._triggerEvent("SCREEN_STATUS",{track:i,mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings})}}catch(t){throw m.log(_.ERROR,"screen"),o.warn("Screen capturing failed",t),t}})}_disableScreenCapture(){this._sendVideoTrack&&(this._sendVideoTrack.stop(),this._sendVideoTrack=null),this._screenTrack&&(this._screenTrack.stop(),this._screenTrack=null),this._mediaSettings.isScreenSharingEnabled&&(this._mediaSettings.isScreenSharingEnabled=!1,this._triggerEvent("SCREEN_STATUS",{mediaSettings:this._mediaSettings}),this._triggerEvent("SOURCE_CHANGED",{kind:"screen",mediaSettings:this._mediaSettings}))}_replaceLocalTrack(e,t){return c(this,null,function*(){!this._stream||this._stream.getTracks().forEach(i=>{var r,a;i.kind===e.kind&&((r=this._stream)==null||r.removeTrack(i),(a=this._stream)==null||a.addTrack(e),this._triggerEvent("TRACK_REPLACED",e,t))})})}_stopLocalTrack(e){this._stream&&this._stream.getTracks().forEach(t=>{t.kind===e&&t.stop()})}_videoEffect(e,t){return c(this,null,function*(){if(!p.videoEffects)return t;try{return m.log(_.DEVICE_CHANGED,`effect_${e}`),p.videoEffects.setEffect(e,t)}catch(i){return o.warn("Video effect failed",i),t}})}_stopAndRemoveTrackVideoStreamBackup(){this._trackVideoStreamBackup&&(this._trackVideoStreamBackup.stop(),this._trackVideoStreamBackup=null)}destroy(){p.videoEffects&&(this._effect=null,p.videoEffects.destroy()),this._stream&&(Sn(this._stream),this._stream=null),this._stopAndRemoveTrackVideoStreamBackup(),this._disableScreenCapture()}toggleScreenCapturing(e){return c(this,null,function*(){return e?this._changeScreen():p.consumerScreenTrack?this._disableScreenCapture():this._videoStatusOnScreenCapturingEnabled?this._changeVideoInput():this.toggleVideo(!1)})}toggleVideo(e){return c(this,null,function*(){if(!this._stream)return;p.consumerScreenTrack||this._disableScreenCapture();let t;if(e){let i=yield y.getUserVideo(void 0,!!this._effect);t=this._getVideoEffectTrack(i),t=yield this._videoEffect(this._effect,t)}else t=y.getBlackMediaTrack(p.videoMinWidth,p.videoMinHeight),t=yield this._videoEffect(null,t),this._stopAndRemoveTrackVideoStreamBackup();this._stopLocalTrack("video"),yield this._replaceLocalTrack(t),this._mediaSettings.isVideoEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"video",mediaSettings:this._mediaSettings})})}toggleAudio(e){return c(this,null,function*(){if(!this._stream)return;let t;e?t=(yield y.getUserAudio()).getAudioTracks()[0]:t=y.getSilentMediaTrack(),this._stopLocalTrack("audio"),yield this._replaceLocalTrack(t),this._mediaSettings.isAudioEnabled=e,this._triggerEvent("SOURCE_CHANGED",{kind:"audio",mediaSettings:this._mediaSettings})})}setResolution(e,t){return c(this,null,function*(){if(!p.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)return;if(!this._stream)throw new Error("Local stream not found");let i=this._stream.getVideoTracks()[0];if(!i)throw new Error("Local video track not found");if(!!i.enabled){if(!this._effect)return i.applyConstraints({width:{ideal:e},height:{ideal:t}});yield this.toggleVideo(!1),yield this.toggleVideo(!0)}})}updateNoiseSuppression(){return c(this,null,function*(){if(!this._stream||!this._mediaSettings.isAudioEnabled)return;let e=this._stream.getAudioTracks()[0];if(!e)throw new Error("Local audio track not found");if(!!e.enabled)return e.applyConstraints({noiseSuppression:p.noiseSuppression})})}videoEffect(e){return c(this,null,function*(){if(!p.videoEffects)throw new Error("Video Effects library is not set");if(!p.consumerScreenTrack&&this._mediaSettings.isScreenSharingEnabled)throw new Error("Can't apply effect to screensharing");if(!this._mediaSettings.isVideoEnabled){this._effect=e;return}if(this._stream&&e!==this._effect)return this._effect=e,this._changeVideoInput(this._stream)})}};var Li;(gr=>{function n(C,R,M,b,w=!1){let Me=/[\r\n]+/,Z=`\r
8
+ `;if(!R&&!M&&!b)return w?U(C.split(Me)).join(Z):C;function U(z){let Ne=["a=rtcp-fb:111 nack","a=rtcp-fb:111 nack pli"],ge="a=rtcp-fb:111",oe=z.findIndex(te=>te.startsWith(ge));return~oe&&(z[oe]=z[oe]+Z+Ne.join(Z)),z}function ee(z,Ne,ge){let oe=z.split(" "),te=oe.slice(0,3),he;for(he=3;he<oe.length;he++)ge.includes(oe[he])&&te.push(oe[he]);for(he=3;he<oe.length;he++)!ge.includes(oe[he])&&!Ne.includes(oe[he])&&te.push(oe[he]);return te.join(" ")}function A(z,Ne){let ge=new RegExp("a=rtpmap:(\\d+) ([a-zA-Z0-9-]+)\\/\\d+"),oe,te=[];for(oe=0;oe<z.length;++oe){let he=z[oe].match(ge);he&&he.length===3&&he[2]===Ne&&te.push(he[1])}return te}function q(z,Ne,ge,oe){let te,he="m="+Ne;for(te=0;te<z.length;++te)if(z[te].startsWith(he)){z[te]=ee(z[te],ge,oe);break}}let pe=[],D=C.split(Me);(M||R)&&(pe=A(D,"H264"));let Ge=[];if(b&&(Ge=A(D,"VP9")),M){let z=pe.slice(0),Ne=new RegExp("a=fmtp:(\\d+) apt=(\\d+)"),ge;for(ge=0;ge<D.length;++ge){let te=D[ge].match(Ne);te&&te.length===3&&z.includes(te[2])&&z.push(te[1])}let oe=new RegExp("a=(rtpmap|rtcp-fb|fmtp):(\\d+) .*");for(ge=D.length;ge--;){let te=D[ge].match(oe);te&&te.length===3&&z.includes(te[2])&&D.splice(ge,1)}q(D,"video",z,[])}else R&&q(D,"video",[],pe);return b&&q(D,"video",[],Ge),w&&U(D),D.join(Z)}gr.patchSDP=n;function e(C){return C?`${C.type||"WEB_SOCKET"}_${C.id}`:"_"}gr.getPeerIdString=e;function t(C,R){return C&&C.id===R.id&&(C.type||"WEB_SOCKET")===(R.type||"WEB_SOCKET")}gr.comparePeerId=t;function i(C){return c(this,null,function*(){return!C||!C.getStats?Promise.resolve(null):C.getStats(null).then(R=>{let M=null,b=null;if(R.forEach(w=>{w.type==="transport"&&w.selectedCandidatePairId?b=R.get(w.selectedCandidatePairId):w.type==="candidate-pair"&&w.state==="succeeded"&&!b&&(!w.hasOwnProperty("selected")||w.selected)&&(b=w)}),b&&b.localCandidateId){let w=R.get(b.localCandidateId);w&&(M={type:w.candidateType,ip:w.ip||w.ipAddress,port:w.port||w.portNumber})}return M}).catch(()=>null)})}gr.getPeerConnectionHostInfo=i;let r=/^[0-9]+$/,a=/^([gu])([0-9]+)$/;function s(C,R){let M=String(C);return a.test(M)?(o.warn(`Already composite id [${C}] type supplied [${R}]`),M):R===X.GROUP?"g"+M:R===X.USER?"u"+M:(o.warn(`Unknown type [${R}] for id [${C}]`),M.match(r)?"u"+M:M)}gr.composeId=s;function d(C){return s(C.id,C.idType||X.USER)}gr.composeParticipantId=d;function l(C){return C.participant?d(C.participant):s(C.participantId,C.participantType||X.USER)}gr.composeMessageId=l;function u(C){let R=String(C),M=R.match(a);return M?{id:Number(M[2]),type:M[1]==="g"?X.GROUP:X.USER}:(o.warn(`Unsupported compositeId [${C}]`),{id:Number(R),type:X.USER})}gr.decomposeId=u;function g(){let C="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),R=new Array(36),M=0,b,w;for(w=0;w<36;w++)w===8||w===13||w===18||w===23?R[w]="-":w===14?R[w]="4":(M<=2&&(M=33554432+Math.random()*16777216|0),b=M&15,M=M>>4,R[w]=C[w===19?b&3|8:b]);return R.join("")}gr.uuid=g;function f(C,R){let M;function b(){let w=this,Me=arguments;M&&window.clearTimeout(M),M=window.setTimeout(()=>{C.apply(w,Me)},R)}return b}gr.throttle=f;function W(C){let R="",M=C.split(`
9
+ `);for(let Z of M)if(Z.startsWith("a=fingerprint")){let U=Z.split(" ");if(U.length===2){R=U[1];break}}if(!R)return ft.default.minusOne;let b=R.split(":"),w=ft.default.zero;for(let Z=Math.min(7,b.length-1);Z>=0;Z--){let U=(0,ft.default)(b[Z],16);w=w.shiftLeft(8).or(U)}return((Z,U)=>{let ee=U.value;if(typeof ee=="bigint")return(0,ft.default)(BigInt.asIntN(Z,ee));let A=ft.default.one.shiftLeft(Z),q=U.and(A.subtract(1));return q.greaterOrEquals(A.subtract(q))?q.subtract(A):q})(64,w)}gr.sdpFingerprint=W;function K(C){return c(this,null,function*(){return new Promise(R=>window.setTimeout(R,C))})}gr.delay=K;function k(C,R,M){let b=[];return C.getSenders().forEach(w=>Y(R,w,w.track,M,b)),b}gr.applySettings=k;function Y(C,R,M,b,w){if(C&&M&&M.kind===me.video){let Me=M.getSettings();if(Me){let Z=C.maxBitrateK?C.maxBitrateK*1024:null,U=Me.width,ee=Me.height,A=U&&ee&&C.maxDimension?Math.max(1,Math.max(U,ee)/C.maxDimension):null,q=C.maxFramerate?C.maxFramerate:null,pe=C.degradationPreference?C.degradationPreference:"balanced",D=b[M.id];if(D&&D.bitrate===Z&&D.scaleResolutionDownBy===A&&D.maxFramerate===q&&D.degradationPreference===pe){w[M.id]=D;return}w[M.id]={bitrate:Z,scaleResolutionDownBy:A,maxFramerate:q,degradationPreference:pe};let Ge=R.getParameters();Ge.encodings||(Ge.encodings=[{}]),Ge.encodings.forEach(z=>{Z?z.maxBitrate=Z:delete z.maxBitrate,A?z.scaleResolutionDownBy=A:delete z.scaleResolutionDownBy,q?z.maxFramerate=q:delete z.maxFramerate}),Ge.degradationPreference=pe,R.setParameters(Ge)}}}gr.applyVideoTrackSettings=Y;function se(C,R){Array.isArray(R)||(R=[R]);for(let M of R)if(C.includes(M))return!0;return!1}gr.includesOneOf=se;function ce(C){var R;return Object.entries(((R=C.participantState)==null?void 0:R.state)||{}).reduce((M,[b,w])=>(C.participantState&&(M[b]={ts:C.participantState.stateUpdateTs[b],state:w}),M),{})}gr.mapParticipantState=ce;function dt(C){return Object.entries(C).reduce((R,[M,{state:b}])=>(R[M]=b,R),{})}gr.mapLegacyParticipantState=dt;function ue(C){return C.map(R=>{let M={uid:R.externalId,mediaSettings:R.mediaSettings,status:R.status,muteStates:R.muteStates,unmuteOptions:R.unmuteOptions};return p.participantStateMapped&&(M.participantState=R.participantState),M})}gr.mapSharedParticipants=ue;function $(C,R){let M=Object.keys(C),b=Object.keys(R);if(M.length!==b.length)return!1;for(let w of M)if(!b.hasOwnProperty(w)||C[w].state!==R[w].state||C[w].ts!==R[w].ts)return!1;return!0}gr.isEqualParticipantState=$;function Oe(C,R){let M=Object.keys(C),b=Object.keys(R);if(M.length!==b.length)return!1;for(let w of M)if(!R.hasOwnProperty(w)||C[w]!==R[w])return!1;return!0}gr.isObjectsEquals=Oe;function It(C,R){if(C.length!==R.length)return!1;for(let M of C)if(R.indexOf(M)<0)return!1;return!0}gr.isArraysEquals=It;function mr(C){return!Object.keys(C).length}gr.isEmptyObject=mr})(Li||(Li={}));var T=Li;var tt=null,Ui=null,qt=[],Jt=[],Bi=[],At=null,Dt=null,Fi=null,Vi=!1,Hi=!1,Yt,St,zt,En=!1,Tn=!1,Gi=null,Wi="",Qt=[],ji=null,Cn=navigator.appVersion,ts=navigator.appName,Re=navigator.userAgent,Ki=(r=>(r.USER="user",r.ENVIRONMENT="environment",r.LEFT="left",r.RIGHT="right",r))(Ki||{}),wt=class{constructor(e,t=!1,i=p.videoMaxWidth,r=p.videoMaxHeight){let a=!1;if(e){a={noiseSuppression:p.noiseSuppression,echoCancellation:!0,autoGainControl:!0};let d;Dt&&(d=Dt.deviceId),typeof e=="string"&&(d=e),d&&(a.deviceId={exact:d})}let s=!1;if(t){s={width:{min:p.videoMinWidth,max:i,ideal:i},height:{min:p.videoMinHeight,max:r,ideal:r},aspectRatio:{ideal:p.videoAspectRatio},frameRate:{ideal:p.videoFrameRate}};let d;At&&(d=At.deviceId),typeof t=="string"&&(d=t),d&&(s.deviceId={exact:d}),p.videoFacingMode&&(s.facingMode={exact:p.videoFacingMode})}this.audio=a,this.video=s,this.needVideo=!!s}getNative(){return Object.assign({},{audio:this.audio,video:this.video})}simplify(){return typeof this.video=="object"&&(this.video.width||this.video.height?(delete this.video.width,delete this.video.height):this.video.aspectRatio?delete this.video.aspectRatio:this.video.frameRate?delete this.video.frameRate:(this.video.deviceId||this.video.facingMode)&&(delete this.video.deviceId,delete this.video.facingMode)),typeof this.audio=="object"&&(this.audio.echoCancellation||this.audio.autoGainControl||this.audio.noiseSuppression?(delete this.audio.echoCancellation,delete this.audio.autoGainControl,delete this.audio.noiseSuppression):this.audio.deviceId&&delete this.audio.deviceId),this.video===!0&&this.audio===!0?this.video=!1:this.video===!1&&this.audio===!0?(this.audio=!1,this.video=this.needVideo):this.video===!0&&this.audio===!1&&(this.video=!1),this.video&&!Object.keys(this.video).length&&(this.video=!0),this.audio&&!Object.keys(this.audio).length&&(this.audio=!0),this}canSimplify(){let e=typeof this.video=="object"&&(this.video.width||this.video.height||this.video.aspectRatio||this.video.frameRate||this.video.facingMode||this.video.deviceId)||this.video;return!!(typeof this.audio=="object"&&(this.audio.deviceId||this.audio.noiseSuppression||this.audio.echoCancellation||this.audio.autoGainControl)||this.audio||e)}isVideo(){return!!this.video}isAudio(){return!!this.audio}},In=class extends wt{constructor(e,t){super(!1,!0);typeof this.video=="object"?(delete this.video.deviceId,delete this.video.aspectRatio,delete this.video.frameRate,delete this.video.facingMode):this.video={},this.video.cursor="motion",this.video.width=e,this.video.height=t,this.video.frameRate=p.screenFrameRate}};function is(){return c(this,null,function*(){tt=null,yield Xt()})}function rs(){tt=null,Xt().then(()=>E.onDeviceChange())}function Xt(){return c(this,null,function*(){return tt||(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices?[]:(!Ui&&navigator.mediaDevices.addEventListener&&(Ui=T.throttle(rs,1e3),navigator.mediaDevices.addEventListener("devicechange",Ui)),tt=navigator.mediaDevices.enumerateDevices().then(n=>{qt=n.filter(r=>r.kind==="videoinput"?(r.label&&(Vi=!0),!0):!1),Jt=n.filter(r=>r.kind==="audioinput"?(r.label?Hi=!0:it.isMobile()&&it.browserName()==="Firefox"&&(Hi=Vi),!0):!1),Bi=n.filter(r=>r.kind==="audiooutput");let e=qe.get("videoinput"),t=qe.get("audioinput"),i=qe.get("audiooutput");return At=qt.find(r=>r.deviceId===e)||null,Dt=Jt.find(r=>r.deviceId===t)||null,Fi=Bi.find(r=>r.deviceId===i)||null,tt=Promise.resolve(n),n}).catch(()=>(tt=null,[]))))})}function ns(){return c(this,null,function*(){return it.isBrowserSupported()?new Promise(n=>{new window.RTCPeerConnection().createOffer({offerToReceiveVideo:!0}).then(t=>{/^a=rtpmap:\d+ VP8\/\d+$/m.test(t.sdp)&&(En=!0),/^a=mid:0$/m.test(t.sdp)&&(Tn=!0),n()}).catch(n)}):Promise.resolve()})}function Zt(n,e){return c(this,null,function*(){o.debug("Try to get media",n.getNative());let t=it.hasPermissions(n.isVideo());!t&&!e&&E.onPermissionsRequested();try{let i=yield navigator.mediaDevices.getUserMedia(n.getNative());return t||(yield is()),i}catch(i){switch(i.name){case"PermissionDeniedError":case"PermissionDismissedError":case"NotAllowedError":case"SecurityError":case"DOMException":e=n.isVideo()?ne.CAMERA_PERMISSION:ne.MIC_PERMISSION;break;case"OverconstrainedError":case"TypeError":case"NotFoundError":break;case"AbortError":case"NotReadableError":e=n.isVideo()?ne.CAMERA_ACCESS:ne.MIC_ACCESS;break}if(n.canSimplify())return Zt(n.simplify(),e);let r=e||ne.UNKNOWN;throw E.onPermissionsError(r),r}})}function as(n){return c(this,null,function*(){o.debug("Try to get screen",n.getNative());try{let e=yield navigator.mediaDevices.getDisplayMedia(n.getNative()),t=e==null?void 0:e.getVideoTracks()[0];return t&&(o.debug("Got display media track",t.id),t.contentHint="text"),e}catch(e){switch(e.name){case"PermissionDeniedError":case"NotAllowedError":case"SecurityError":throw ne.SCREEN_PERMISSION;default:throw ne.SCREEN_ACCESS}}})}function $i(){return Qt.length||(Qt=(()=>{let n,e=!1,t=0,i=Re.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return n=/\brv[ :]+(\d+)/g.exec(Re),["IE",n&&n[1]||"Unknown",e,t];if(i[1]==="Safari"){if(n=Re.match(/\bEdge\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t];if(n=Re.match(/\bCriOS\/(\d+)/),n)return["Chrome",n[1],!0,n[1]];if(n=Re.match(/\bFxiOS\/(\d+)/),n)return["Firefox",n[1],!1,t];if(n=Re.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1],!1,t];if(n=Re.match(/\bOPT\/(\d+)/),n)return["Opera",n[1],!1,t]}if(i[1]==="Chrome"){if(e=!0,t=Number(i[2]),n=Re.match(/\bOPR\/(\d+)/),n)return["Opera",n[1]||"Unknown",e,t];if(n=Re.match(/\bYaBrowser\/(\d+)/),n)return["Yandex",n[1]||"Unknown",e,t];if(n=Re.match(/\bSferum\/((\d+)(?:\.\d+)*)/),n)return["Sferum",n[1]||"Unknown",e,t];if(n=Re.match(/\bEdge?\/(\d+)/),n)return["Edge",n[1]||"Unknown",e,t];if(typeof window.opr!="undefined"&&/^(.+\.)?ok.ru$/.test(window.location.host))return["Opera","Hidden",e,t]}return n=Re.match(/version\/(\d+)/i),[i[2]?i[1]:ts,n&&n[1]||i[2]||Cn,e,t]})()),Qt}var it;(Z=>{function n(){return c(this,null,function*(){return yield ns(),Xt()})}Z.init=n;function e(){return qt}Z.getCameras=e;function t(){return Jt}Z.getMicrophones=t;function i(){return Bi}Z.getOutput=i;function r(){return qt.length>0}Z.hasCamera=r;function a(){return Jt.length>0}Z.hasMicrophone=a;function s(){return At}Z.getSavedCamera=s;function d(){return Dt}Z.getSavedMicrophone=d;function l(){return Fi}Z.getSavedOutput=l;function u(){return Vi}Z.hasCameraPermission=u;function g(){return Hi}Z.hasMicrophonePermission=g;function f(U=!1){return g()?r()&&U?u():!0:!1}Z.hasPermissions=f;function W(U=!1,ee=!0){return c(this,null,function*(){let A=a()&&ee,q=r()&&U,pe;if(!A&&!q)pe=new MediaStream;else try{pe=yield Zt(new wt(A,q))}catch(D){pe=new MediaStream}return pe.getVideoTracks().length||pe.addTrack(dt()),pe.getAudioTracks().length||pe.addTrack(ce()),pe})}Z.getUserMedia=W;function K(){return c(this,null,function*(){return as(new In(window.screen.width,window.screen.height))})}Z.getScreenMedia=K;function k(U,ee=!1){return c(this,null,function*(){let A=ee?p.videoEffectMaxWidth:p.videoMaxWidth,q=ee?p.videoEffectMaxHeight:p.videoMaxHeight;return Zt(new wt(!1,U||!0,A,q))})}Z.getUserVideo=k;function Y(U){return c(this,null,function*(){return Zt(new wt(U||!0,!1))})}Z.getUserAudio=Y;function se(U,ee){return c(this,null,function*(){let q=(yield Xt()).find(pe=>pe.kind===U&&pe.deviceId===ee);return q?(U==="videoinput"?At=q:U==="audioinput"?Dt=q:U==="audiooutput"&&(Fi=q),qe.set(U,ee),q):null})}Z.saveDeviceId=se;function ce(){if(!zt||zt.readyState==="ended"){let U=Me(),ee=U.createMediaStreamDestination(),A=U.createGain();A.gain.value=1e-5,A.connect(ee),A.connect(U.destination);let q=U.createOscillator();q.type="sine",q.frequency.value=0,q.connect(A),q.start(),zt=ee.stream.getAudioTracks()[0]}return Object.assign(zt.clone(),{enabled:!1})}Z.getSilentMediaTrack=ce;function dt(U=p.videoMinWidth,ee=p.videoMinHeight){return St||(St=document.createElement("canvas"),St.getContext("2d")),St.width=U,St.height=ee,(!Yt||Yt.readyState==="ended")&&(Yt=St.captureStream(p.videoFrameRate).getVideoTracks()[0]),Object.assign(Yt.clone(),{enabled:!1})}Z.getBlackMediaTrack=dt;function ue(){if(M()==="Edge"&&b()<70)return!1;try{let U=window;return navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&U.RTCPeerConnection&&U.RTCIceCandidate&&U.RTCSessionDescription&&U.HTMLCanvasElement&&U.HTMLCanvasElement.prototype.captureStream&&U.RTCRtpSender&&U.RTCRtpSender.prototype.replaceTrack&&U.RTCRtpSender.prototype.getParameters&&navigator.sendBeacon&&!0||!1}catch(U){return!1}}Z.isBrowserSupported=ue;function $(){return!!navigator.mediaDevices.getDisplayMedia}Z.isScreenCapturingSupported=$;function Oe(){return En}Z.canVP8=Oe;function It(){return Tn}Z.isUnifiedPlan=It;function mr(){return Z.browserName()==="Opera"&&Z.os()==="Windows"}Z.isBrokenH264=mr;function gr(){return!(Z.baseChromeVersion()&&Z.isMobile())}Z.canPreferH264=gr;function C(){return Wi||(Wi=(()=>{let U={Windows:/Win/,Android:/Android/,OpenBSD:/OpenBSD/,SunOS:/SunOS/,Linux:/(Linux|X11)/,iPad:/(iPad)/,iPhone:/(iPhone)/,iPod:/(iPod)/,MacOS:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh|Mac OS X)/,QNX:/QNX/,UNIX:/UNIX/,BeOS:/BeOS/,OS2:/OS\/2/,Bot:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/};for(let ee in U)if(U.hasOwnProperty(ee)&&U[ee].test(Re))return ee;return"Unknown"})()),Wi}Z.os=C;function R(){return Gi===null&&(Gi=/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(Cn)),Gi}Z.isMobile=R;function M(){return $i()[0]}Z.browserName=M;function b(){return $i()[1]}Z.browserVersion=b;function w(){return $i()[3]}Z.baseChromeVersion=w;function Me(){return ji||(ji=new(window.AudioContext||window.webkitAudioContext)),ji}Z.getAudioContext=Me})(it||(it={}));var y=it;var yn=Ie(require("bit-buffer")),qi=Ie(wi()),Ji=Ie(require("crc"));var ss=65536,rt=class{constructor(e,t){this._chunks=[];this._participantId=e,this._onStream=t}appendChunk(e){let t=this._chunks.length;if(e.start)t&&(o.warn("[FrameBuilder] Cleanup buffer",Array.prototype.slice.call(this._chunks)),this._chunks=[]);else if(!t||(this._chunks[t-1].sequence+1)%ss!==e.sequence){o.warn("[FrameBuilder] Got incorrect chunk");return}if(this._chunks.push(e),e.end){let i=this._processFrameData(),{width:r,height:a}=rt.getFrameSize(i);this._processFrame({timestamp:e.timestamp,frameData:i,isVP9:e.isVP9,keyframe:e.keyframe,width:r,height:a})}}destroy(){this._chunks=[]}_processFrameData(){let e=this._chunks;this._chunks=[];let t=e.reduce((s,d)=>s+d.data.byteLength,0),i=new Uint8Array(t),r=[],a=0;for(let s of e)p.sharePrintChunkData&&o.debug("got chunk",a,s.data.byteLength,s.sequence,s.timestamp,s.keyframe,s.isVP9,s.data),r.push(Ji.default.crc32(qi.default.Buffer.from(s.data)).toFixed()),i.set(new Uint8Array(s.data),a),a+=s.data.byteLength;if(p.sharePrintFrameData){let s=Ji.default.crc32(qi.default.Buffer.from(i)).toFixed();o.debug("processed screenshare frame data",s,r)}return i}static getFrameSize(e){let t={width:0,height:0},i=new yn.BitStream(e.buffer);i.bigEndian=!0,i.index+=2;let r=i.readBits(1),s=i.readBits(1)<<1|r;return s===3&&i.index++,i.readBits(1)===1||i.readBits(1)!==0||(i.index++,i.index++,i.index+=24,s>=2&&i.index++,i.readBits(3)!==7?(i.index++,(s===1||s===3)&&(i.index+=3)):(s===1||s===3)&&i.index++,t.width=i.readBits(16)+1,t.height=i.readBits(16)+1),t}static isBrowserSupported(){throw new Error("Method `isBrowserSupported` is not implemented")}};var Ot=class extends rt{constructor(e,t){super(e,t);this._decoderReady=!1;this._decoderQueue=[];this._canvas=null;this._canvasContext=null;this._stream=null;this._track=null;o.debug(`StreamBuilder started for participant [${e}]`),this._useImageBitmap="ImageBitmap"in window,Xe.isBrowserSupported()&&!p.sharePlayWebcodecDisabled?this._decoder=new Xe:this._decoder=new ht,this._decoder.init((i,r)=>this._drawImage(i,r)).then(()=>{this._decoderReady=!0,this._decodeQueue()})}_createStream(e,t){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.width=e,this._canvas.height=t,this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="0",this._canvas.style.zIndex="5000",document.body.appendChild(this._canvas),this._useImageBitmap?this._canvasContext=this._canvas.getContext("bitmaprenderer"):this._canvasContext=this._canvas.getContext("2d"),this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],this._track.contentHint="text")}_removeStream(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null,this._track=null),this._canvasContext=null;try{this._canvas&&document.body.removeChild(this._canvas)}catch(e){}this._canvas=null}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}_drawImage(e,t){if(this._track||(this._createStream(e.width,e.height),this._onStream(this._stream)),p.sharePlayPrintFrameByFrame){let i=document.createElement("canvas");i.width=e.width,i.height=e.height,i.style.width="160px",i.style.height="90px",document.body.appendChild(i);let r;if(this._useImageBitmap?r=i.getContext("bitmaprenderer"):r=i.getContext("2d"),i.setAttribute("crc",t),e instanceof ImageData){let a=r;a.clearRect(0,0,i.width,i.height),a.putImageData(e,0,0)}else r.transferFromImageBitmap(e)}else{let i=this._canvas;if(i.width=e.width,i.height=e.height,e instanceof ImageData){let r=this._canvasContext;r.clearRect(0,0,i.width,i.height),r.putImageData(e,0,0)}else this._canvasContext.transferFromImageBitmap(e);this._requestCanvasFrame()}}_processFrame(e){if(!this._decoderReady||this._decoderQueue.length)this._decoderQueue.push(e),this._decodeQueue();else{let t=zi.default.crc32(Yi.default.Buffer.from(e.frameData)).toFixed();this._decoder.decodeFrame(e.timestamp,e.frameData,e.isVP9,t,e.keyframe)}}_decodeQueue(){if(!this._decoderReady)return;let e=this._decoderQueue;this._decoderQueue=[],e.forEach(t=>{let i=zi.default.crc32(Yi.default.Buffer.from(t.frameData)).toFixed();this._decoder.decodeFrame(t.timestamp,t.frameData,t.isVP9,i,t.keyframe)})}destroy(){super.destroy(),this._decoder.destroy(),this._removeStream(),o.debug(`StreamBuilder destroyed for participant ${this._participantId}`)}static isBrowserSupported(){return("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)&&!(y.browserName()==="Safari"&&y.browserVersion()>=15)}};var ei=1,os=1,Rn=0,bn=11,Pn=1,Mn=2,An=4,Dn=8;function wn(n,e,t,i,r,a,s){let d=0;e&&(d|=Pn),t&&(d|=Mn),i&&(d|=An),s||(d|=Dn);let l=new ArrayBuffer(bn),u=new DataView(l);if(u.setUint8(0,ei),u.setUint16(1,r),u.setUint32(3,n),u.setUint8(7,a?1:0),u.setUint16(8,Rn),u.setUint8(10,d),!s)return l;let g=new Uint8Array(l.byteLength+s.byteLength);return g.set(new Uint8Array(l),0),g.set(new Uint8Array(s),l.byteLength),g.buffer}function On(n){let e=new DataView(n),t=e.getUint8(0),i=e.getUint16(1),r=e.getUint32(3),a=e.getUint8(7)===1,s=e.getUint16(8),d=e.getUint8(10),l=!!(d&Pn),u=!!(d&Mn),g=!!(d&An),f=!!(d&Dn);if(t!==ei)throw new Error(`Unexpected protocol version. Got ${t}, expected ${ei}`);return{timestamp:r,start:l,end:u,keyframe:g,sequence:i,isVP9:a,ssrc:s,eos:f,data:n.slice(bn)}}function kn(n){if(!n||!n.byteLength||n.byteLength!==4)return!1;let e=new DataView(n);return!(e.getUint8(0)!==ei||e.getUint8(1)!==os||e.getUint16(2)!==Rn)}var S=Ie(require("simple-ebml-builder"));var cs=Sr(2,15)-1,Qi=1,ds=5,ps=5;var ti=class{constructor(e){this._queue=[];this._clearBufferTill=0;this._mediaSource=new MediaSource,this._codec=e;let t=()=>{this._mediaSource.removeEventListener("sourceopen",t),this._initBuffer(),this._handleQueue()};this._mediaSource.addEventListener("sourceopen",t,!1)}_handleQueue(){if(!this._sourceBuffer||this._sourceBuffer.updating||!this._queue.length)return;if(this._clearBufferTill&&this._sourceBuffer.buffered.length){let i=this._sourceBuffer.buffered.start(0);i<this._clearBufferTill&&(this._sourceBuffer.remove(i,this._clearBufferTill),o.debug(`[WebmBuilder] SourceBuffer cleanup from ${i} to ${this._clearBufferTill}`)),this._clearBufferTill=0;return}let e=this._queue;this._queue=[];let t=ti._buildQueue(e);this._sourceBuffer.appendBuffer(t)}static _buildQueue(e){if(e.length){if(e.length===1)return S.build(e[0])}else return new Uint8Array;let t=e.reduce((a,s)=>a+s.countSize(),0),i=new Uint8Array(t),r=0;for(let a of e){let s=S.build(a);i.set(s,r),r+=s.byteLength}return i}_initBuffer(){this._sourceBuffer=this._mediaSource.addSourceBuffer(`video/webm; codecs="${this._codec}"`),this._sourceBuffer.mode="sequence",this._sourceBuffer.addEventListener("updateend",()=>this._handleQueue())}changeType(e){var t;return this._codec=e,(t=this._sourceBuffer)==null?void 0:t.changeType(e)}append(e,t=!1){this._queue.push(e),t&&this._handleQueue()}cleanup(){var a;let e=(a=this._sourceBuffer)==null?void 0:a.buffered,t=e==null?void 0:e.length;if(!t)return;let i=e.start(0),r=Math.max(0,e.end(t-1)-ds);r-i>ps&&(this._clearBufferTill=r)}destroy(){this._queue=[],this._mediaSource.readyState==="open"&&(this._sourceBuffer.abort(),this._mediaSource.endOfStream()),this._sourceBuffer=null,this._clearBufferTill=0}get codec(){return this._codec}get mediaSource(){return this._mediaSource}get buffered(){var e;return(e=this._sourceBuffer)==null?void 0:e.buffered}},$e=class extends rt{constructor(e,t){super(e,t);this._video=null;this._stream=null;this._earliestTimestamp=0;this._clusterStartTime=0;this._lastFrameTimestamp=0;o.debug(`[WebmBuilder] started for participant [${e}]`)}static _intToU16BE(e){return new Uint8Array([e>>8,e])}static _genWebmHeader(){return S.element(S.ID.EBML,[S.element(S.ID.EBMLVersion,S.number(1)),S.element(S.ID.EBMLReadVersion,S.number(1)),S.element(S.ID.EBMLMaxIDLength,S.number(4)),S.element(S.ID.EBMLMaxSizeLength,S.number(8)),S.element(S.ID.DocType,S.string("webm")),S.element(S.ID.DocTypeVersion,S.number(2)),S.element(S.ID.DocTypeReadVersion,S.number(2))])}static _genSegmentHeader(e,t,i){let r=S.element(S.ID.Info,[S.element(S.ID.TimecodeScale,S.number(1e6)),S.element(S.ID.MuxingApp,S.string("vk-webm-builder")),S.element(S.ID.WritingApp,S.string("vk-webm-builder"))]),a=[S.element(S.ID.PixelWidth,S.number(e)),S.element(S.ID.PixelHeight,S.number(t))],s=S.element(S.ID.Tracks,S.element(S.ID.TrackEntry,[S.element(S.ID.TrackNumber,S.number(Qi)),S.element(S.ID.TrackUID,S.number(Qi)),S.element(S.ID.TrackType,S.number(1)),S.element(S.ID.FlagLacing,S.number(0)),S.element(S.ID.DefaultDuration,S.number(1e9)),S.element(S.ID.CodecID,S.string(`V_${i.toUpperCase()}`)),S.element(S.ID.Video,a)]));return S.unknownSizeElement(S.ID.Segment,[r,s])}static _genClusterHeader(e){return S.unknownSizeElement(S.ID.Cluster,[S.element(S.ID.Timecode,S.number(Math.round(e)))])}_createVideo(e){this._mediaBuffer=new ti(e),this._video=document.createElement("video"),this._video.autoplay=!0,this._video.controls=!1,this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",this._video.src=URL.createObjectURL(this._mediaBuffer.mediaSource),document.body.appendChild(this._video);let t=()=>{if(this._video.src){o.warn(`[WebmBuilder] Video paused for participant [${this._participantId}], try to play again`);let i=this._video.seekable;i.length&&(this._video.currentTime=i.end(i.length-1)-1),this._video.play().catch(()=>{})}};this._video.onpause=t,this._video.onwaiting=t,this._video.onstalled=t,this._video.onerror=()=>o.warn(`[WebmBuilder] Video Error for participant [${this._participantId}]`,this._video.error),this._stream=this._video.captureStream(),this._onStream(this._stream)}_processFrame(e){let t=e.isVP9?"vp9":"vp8";this._mediaBuffer?this._mediaBuffer.codec!==t&&this._mediaBuffer.changeType(t):this._createVideo(t);let i=e.timestamp;if(i<=this._lastFrameTimestamp&&(i=this._lastFrameTimestamp+10,o.debug(`[WebmBuilder] Fixup timestamp for participant [${this._participantId}]`)),this._lastFrameTimestamp=i,this._earliestTimestamp)i-=this._earliestTimestamp;else{if(!e.keyframe)return;this._earliestTimestamp=i,i=0}if(e.keyframe){this._clusterStartTime=i,o.debug(`[WebmBuilder] Segment header for participant [${this._participantId}]`);let s=$e._genWebmHeader();this._mediaBuffer.append(s);let d=$e._genSegmentHeader(e.width,e.height,t);this._mediaBuffer.append(d),this._mediaBuffer.cleanup()}let r=Math.round(i-this._clusterStartTime);if(r>cs&&(this._clusterStartTime=i,r=0),r===0){o.debug(`[WebmBuilder] Cluster header for participant [${this._participantId}]`);let s=$e._genClusterHeader(this._clusterStartTime);this._mediaBuffer.append(s)}let a=S.element(S.ID.SimpleBlock,[S.vintEncodedNumber(Qi),S.bytes($e._intToU16BE(r)),S.number((e.keyframe?1:0)<<7),S.bytes(e.frameData)]);this._mediaBuffer.append(a,!0)}destroy(){super.destroy(),this._video&&(this._video.onpause=null,this._video.onwaiting=null,this._video.onstalled=null,this._video.onerror=null,this._video.pause(),this._video.src="",document.body.removeChild(this._video)),this._mediaBuffer&&(this._mediaBuffer.destroy(),this._mediaBuffer=null),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),o.debug(`[WebmBuilder] destroyed for participant [${this._participantId}]`)}static isBrowserSupported(){var e,t,i;return"captureStream"in((e=window.HTMLVideoElement)==null?void 0:e.prototype)&&((t=window.MediaSource)==null?void 0:t.isTypeSupported('video/webm; codecs="vp8"'))&&((i=window.MediaSource)==null?void 0:i.isTypeSupported('video/webm; codecs="vp9"'))}};var nt=class{constructor(e,t,i,r,a){this._participantIdRegistry=null;this._streamBuilders={};this._onStream=()=>{};this._onEos=()=>{};this._parts=[];this._lastChunk=0;this._frames=0;o.debug("ScreenCaptureReceiver started"),t instanceof RTCDataChannel?(this._datachannel=t,this._datachannel.onmessage=s=>this._onDataChannelMessage(s.data)):this._replay(t),this._participantIdRegistry=i,this._conversation=e,this._onStream=r,this._onEos=a}_replay(e){return c(this,null,function*(){let t=yield e.arrayBuffer(),i=new DataView(t),r=0;for(;r<i.byteLength;){let a=this._readUint32(i,r);yield this._sleep(p.sharePlayFixedDelay?p.sharePlayFixedDelay:a);let s=this._readUint32(i,r+=4),d=t.slice(r+=4,r+=s);this._onDataChannelMessage(d)}})}_sleep(e){return c(this,null,function*(){return new Promise((t,i)=>{setTimeout(()=>{t()},e)})})}_readUint32(e,t){return e.getUint8(t)+(e.getUint8(t+1)<<8)+(e.getUint8(t+2)<<16)+(e.getUint8(t+3)<<24)}_onDataChannelMessage(e){var a,s;if(p.shareDumpReceived&&this._datachannel){let d=new Date().getTime(),l=this._lastChunk?d-this._lastChunk:0;this._lastChunk=d,this._parts.push(new Uint32Array([l,e.byteLength])),this._parts.push(new Uint8Array(e))}let t=On(e);t.end&&this._frames++;let i=(s=(a=this._participantIdRegistry)==null?void 0:a.getStreamDescription(t.ssrc))==null?void 0:s.participantId;if(!i)if(p.sharePlayRegisterMissingParticipantId&&this._conversation&&this._conversation.getRandomParticipant()){let d=this._conversation.getRandomParticipant();o.warn(`Registering ${d.id} as compacted ID ${t.ssrc}`),this._participantIdRegistry.register(t.ssrc,{participantId:d.id,mediaType:Se.SCREEN})}else{o.warn(`Participant id for ssrc ${t.ssrc} not found in registry`);return}if(t.eos){if(this.close(i),this._onEos(i),p.shareDumpReceived&&this._lastChunk){let d=new Date().toISOString().replace(/:/g,"-").replace(/.\d+Z/,"").replace("T","_");(0,Xi.saveAs)(new Blob(this._parts),"received-screenshare-"+i+"-"+d+".dat"),this._parts=[],this._lastChunk=0}o.log(`Received ${this._frames} screenshare frames`),this._frames=0;return}let r=this._streamBuilders[i];if(!r){let d=l=>this._onStream(i,l);r=new Ot(i,d),this._streamBuilders[i]=r}r.appendChunk(t)}close(e){let t=this._streamBuilders[e];t&&(t.destroy(),delete this._streamBuilders[e])}destroy(){if(o.log(`Received ${this._frames} screenshare frames`),this._frames=0,p.shareDumpReceived&&this._lastChunk){let e=new Date().toISOString().replace(/:/g,"-").replace(/.\d+Z/,"").replace("T","_");(0,Xi.saveAs)(new Blob(this._parts),"received-screenshare-"+e+".dat"),this._parts=[],this._lastChunk=0}this._datachannel&&(this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null),this._onStream=()=>{},Object.values(this._streamBuilders).forEach(e=>e.destroy()),this._streamBuilders={},this._participantIdRegistry=null,o.debug("ScreenCaptureReceiver destroyed")}static isBrowserSupported(){return(Xe.isBrowserSupported()||ht.isBrowserSupported())&&(Ot.isBrowserSupported()||$e.isBrowserSupported())}};var xn=Ie(require("file-saver"));var Zi=Ie(require("@vkontakte/libvpx"));var ls=1e3,kt=class extends Be{constructor(e,t){super();this._video=null;this._imageCapture=null;this._canvas=null;this._canvasCtx=null;this._stream=null;this._track=null;this._frameReadTimeout=0;this._lastFrame=null;this._sourceTrack=e,this._onFrame=t,this._useImageCapture="ImageCapture"in window&&"ImageBitmap"in window,(e.readyState!=="live"||!e.enabled||e.muted)&&(this._useImageCapture=!1)}_createDom(){this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.style.pointerEvents="none",this._canvas.style.visibility="hidden",this._canvas.style.position="absolute",this._canvas.style.width="160px",this._canvas.style.height="90px",this._canvas.style.bottom="0",this._canvas.style.right="160px",this._canvas.style.zIndex="5000",this._canvasCtx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)),!this._video&&!this._useImageCapture&&(this._video=document.createElement("video"),this._video.controls=!1,this._video.autoplay=!1,this._video.preload="auto",this._video.muted=!0,this._video.style.pointerEvents="none",this._video.style.visibility="hidden",this._video.style.position="absolute",this._video.style.width="160px",this._video.style.height="90px",this._video.style.bottom="0",this._video.style.right="0",this._video.style.zIndex="5000",document.body.appendChild(this._video))}_removeDom(){try{this._canvas&&document.body.removeChild(this._canvas),this._video&&document.body.removeChild(this._video)}catch(e){}this._canvasCtx=null,this._canvas=null,this._video=null}_createStream(e){return c(this,null,function*(){if(!this._canvas)throw new Error("Canvas not found");if(!this._video&&!this._useImageCapture)throw new Error("Video element not found");return this._stream=this._canvas.captureStream(0),this._track=this._stream.getVideoTracks()[0],new Promise((t,i)=>{if(this._useImageCapture)this._imageCapture=new ImageCapture(e),t();else{let r=this._video;r.srcObject=new MediaStream([e]),r.onloadeddata=d=>t(),r.onerror=()=>i(new Error("Video element error"));let a=r.play(),s=()=>i(new Error("Autoplay is disabled"));a?a.catch(s):s()}})})}_removeStream(){var e;window.clearTimeout(this._frameReadTimeout),(e=this._lastFrame)==null||e.close(),this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null,this._track=null),this._video&&(this._video.pause(),this._video.srcObject=null),this._imageCapture&&(this._imageCapture=null)}_drawFrameVideo(){if(!this._canvas||!this._canvasCtx||!this._video||!this._track)throw new Error("Fatal error");let e=this._video.videoWidth,t=this._video.videoHeight;return this._canvas.width=this._video.width=e,this._canvas.height=this._video.height=t,this._canvasCtx.clearRect(0,0,e,t),this._canvasCtx.drawImage(this._video,0,0,e,t),this._requestCanvasFrame(),this._canvasCtx.getImageData(0,0,e,t)}_getFrameBitmap(){return c(this,null,function*(){if(!this._imageCapture)throw new Error("Destroyed");return this._imageCapture.grabFrame()})}_drawFrameData(e){var r;if(!this._canvas||!this._canvasCtx||!this._track)throw new Error("Destroyed");let t=e.width,i=e.height;return this._canvas.width=t,this._canvas.height=i,this._canvasCtx.clearRect(0,0,t,i),this._canvasCtx.drawImage(e,0,0,t,i),this._requestCanvasFrame(),(r=this._canvasCtx)==null?void 0:r.getImageData(0,0,t,i)}_requestCanvasFrame(){this._track&&this._track.requestFrame?this._track.requestFrame():this._stream&&this._stream.requestFrame&&this._stream.requestFrame()}init(){return c(this,null,function*(){this._createDom();let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height;o.debug(`LibVPxEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createStream(this._sourceTrack),yield this._createWorker(`var exports=(()=>{var u=Object.defineProperty;var b=o=>u(o,"__esModule",{value:!0});var g=(o,n)=>{b(o);for(var t in n)u(o,t,{get:n[t],enumerable:!0})};var y={};g(y,{default:()=>R});var e=(r=>(r.INIT="init",r.READY="ready",r.FRAME="frame",r.ERROR="error",r.DEBUG="debug",r.LOG_ERROR="log_error",r))(e||{});var R=(o,n)=>{let t;function m(a,r){return o({locateFile:n}).then(s=>{if(t=new s.VpxEncoder,t.debug(r),!t.init(a?s.VpxType.VP9:s.VpxType.VP8))throw self.postMessage({type:e.LOG_ERROR,message:"encoder-init-fail-libvpx"}),new Error("LibVPxEncoder failed to create");t.setMaxQuantizer(10),t.setTargetBitrate(1024)})}function E(a,r,s,i){let c=t.allocateImage(a,r);if(!c){self.postMessage({type:e.FRAME,error:"No buffer data"});return}c.set(new Uint8Array(s));let f=Math.round(performance.now()),l=150;if(!t.encode(f,l,i)){self.postMessage({type:e.FRAME,error:"Encode failed"});return}let p=t.readFrame();if(!p){self.postMessage({type:e.FRAME,error:"No encoded data"});return}t.readFrame()&&(self.postMessage({type:e.DEBUG,message:"LibVPxEncoder dropped frame"}),self.postMessage({type:e.LOG_ERROR,message:"LibVPxEncoder-drop"}));let d=new Uint8Array(p.byteLength);d.set(p),self.postMessage({type:e.FRAME,frameType:i?"key":"delta",timestamp:f,duration:l,data:d.buffer},[d.buffer])}self.onmessage=a=>{switch(a.data.type){case e.INIT:m(a.data.isVP9,a.data.debug).then(()=>self.postMessage({type:e.READY})).catch(r=>self.postMessage({type:e.ERROR,error:String(r)}));break;case e.FRAME:E(a.data.width,a.data.height,a.data.imageData,a.data.keyFrame);break}}};return y;})();
10
+ `,i=>{var r;i.error?this._onFrame(null,i.error):this._onFrame({type:i.frameType,timestamp:i.timestamp,duration:i.duration,data:i.data,byteLength:(r=i.data)==null?void 0:r.byteLength})},[Zi.default,Zi.default.getUrl],{isVP9:this.isVP9(),debug:o.enabled()})})}_encode(e,t){let i=e.data.buffer;this._sendToWorker(ve.FRAME,{width:e.width,height:e.height,imageData:i,keyFrame:t},[i])}_requestFrameVideo(e){let t=this._drawFrameVideo();this._encode(t,e)}_requestFrameBitmap(e){this._frameReadTimeout=window.setTimeout(()=>{if(this._lastFrame){let t=this._drawFrameData(this._lastFrame);this._encode(t,e)}else this._onFrame(null)},ls),this._getFrameBitmap().then(t=>{var r;window.clearTimeout(this._frameReadTimeout),(r=this._lastFrame)==null||r.close(),this._lastFrame=t;let i=this._drawFrameData(t);this._encode(i,e)}).catch(()=>{})}requestFrame(e=!1){this._useImageCapture?this._requestFrameBitmap(e):this._requestFrameVideo(e)}isVP9(){return!1}destroy(){this._removeWorker(),this._removeStream(),this._removeDom(),o.debug("LibVPxEncoder destroyed")}static isBrowserSupported(){return"WebAssembly"in window&&"Worker"in window&&("CanvasCaptureMediaStream"in window||"CanvasCaptureMediaStreamTrack"in window)}};var vt=class extends Be{constructor(e,t){super();this._sourceTrack=e,this._onFrame=t,this._trackProcessor=new MediaStreamTrackProcessor(e)}init(){return c(this,null,function*(){let e=this._sourceTrack.getSettings().width,t=this._sourceTrack.getSettings().height,i=this._trackProcessor.readable;o.debug(`WebCodecsEncoder started ${e}x${t}, codec ${this.isVP9()?"VP9":"VP8"}`),yield this._createWorker(`var exports=(()=>{var b=Object.defineProperty;var g=i=>b(i,"__esModule",{value:!0});var F=(i,n)=>{g(i);for(var r in n)b(i,r,{get:n[r],enumerable:!0})};var A={};F(A,{default:()=>h});var l=(r=>(r.VP9="vp09.00.50.08",r.VP8="vp8",r))(l||{}),d=(t=>(t.INIT="init",t.READY="ready",t.FRAME="frame",t.ERROR="error",t.DEBUG="debug",t.LOG_ERROR="log_error",t))(d||{});var h=()=>{let i=1e3,n,r,c,s,f,t,a=null,p=0,u=!1;function V(e){n=e.readable,r=n.getReader(),c=e.width,s=e.height,f=e.isVP9,t=e.framerate,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"}),self.postMessage({type:d.READY})}function y(e){p=self.setTimeout(()=>{a&&E(a,e)},i),!u&&(u=!0,r.read().finally(()=>{u=!1,self.clearTimeout(p)}).then(({done:o,value:R})=>{if(a==null||a.close(),a=null,!(o||!R)){if(!m){r.releaseLock(),n.cancel();return}a=R,E(R,e)}}))}function E(e,o){(e.codedWidth!==c||e.codedHeight!==s)&&(c=e.codedWidth,s=e.codedHeight,m.configure({framerate:t,codec:f?l.VP9:l.VP8,width:c,height:s,latencyMode:"realtime"})),m.encode(e,{keyFrame:o})}let m=new VideoEncoder({output:e=>{let o;e.data?o=e.data:(o=new ArrayBuffer(e.byteLength),e.copyTo(o)),self.postMessage({type:d.FRAME,frameType:e.type,timestamp:e.timestamp,duration:e.duration,data:o},[o])},error:e=>{self.postMessage({type:d.FRAME,error:String(e)})}});self.onmessage=e=>{switch(e.data.type){case d.INIT:V(e.data);break;case d.FRAME:y(e.data.keyFrame);break}}};return A;})();
11
+ `,r=>{var a;r.error?this._onFrame(null,r.error):this._onFrame({type:r.frameType,timestamp:r.timestamp,duration:r.duration,data:r.data,byteLength:(a=r.data)==null?void 0:a.byteLength})},[],{readable:i,width:e,height:t,isVP9:this.isVP9(),framerate:p.screenFrameRate},[i])})}requestFrame(e=!1){this._sendToWorker(ve.FRAME,{keyFrame:e})}isVP9(){return!0}destroy(){this._removeWorker(),o.debug("WebCodecsEncoder destroyed")}static isBrowserSupported(){return"VideoEncoder"in window&&"Worker"in window&&"EncodedVideoChunk"in window&&"MediaStreamTrackProcessor"in window}};var us=16*1024,hs=11,Nn=us-hs,ms=65536,er=0,Et=class{constructor(e,t){this._destroyed=!1;this._needKeyframe=!0;this._parts=[];this._lastChunk=0;o.debug("ScreenCaptureSender started"),this._datachannel=t;let i=(r,a)=>{if(!this._destroyed){if(!r){o.warn("requestFrame failed, keyFrame: "+this._needKeyframe,a),this._needKeyframe=!0,this._requestFrame();return}this._send(r).catch(s=>{o.warn("sendFrame failed",s),this._needKeyframe=!0}).finally(()=>this._requestFrame())}};vt.isBrowserSupported()?this._encoder=new vt(e,i):this._encoder=new kt(e,i),this._datachannel.onmessage=r=>{kn(r.data)&&(o.debug(`[${this._datachannel.label}] Requested keyframe`),this._needKeyframe=!0)},this._encoder.init().then(()=>this._requestFrame()).catch(r=>o.warn("ScreenCaptureSender init failed",r))}_requestFrame(){this._destroyed||(this._encoder.requestFrame(this._needKeyframe),this._needKeyframe=!1)}_wrapHeader(e,t,i,r,a){let s=wn(e,t,i,r,er,this._encoder.isVP9(),a);return er=(er+1)%ms,s}_stopPacket(){return this._wrapHeader(Date.now(),!1,!1,!1,null)}_send(e){return c(this,null,function*(){return new Promise((t,i)=>{this._sendChunk(e,0,t,i)})})}_sendChunk(e,t,i,r){if(!this._datachannel||this._datachannel.readyState!=="open"){r();return}let a=e.data.slice(t,t+Nn),s=e.data.byteLength<=t+a.byteLength,d=this._wrapHeader(e.timestamp,!t,s,e.type==="key",a);if(this._datachannel.onbufferedamountlow=s?()=>{this._datachannel.bufferedAmount<=this._datachannel.bufferedAmountLowThreshold&&i()}:null,p.shareDumpSent){let l=new Date().getTime(),u=this._lastChunk?l-this._lastChunk:0;this._lastChunk=l,this._parts.push(new Uint32Array([u,d.byteLength])),this._parts.push(new Uint8Array(d))}try{this._datachannel.send(d)}catch(l){o.warn("Error send data to DataChannel",l),r();return}s||window.setTimeout(()=>this._sendChunk(e,t+Nn,i,r),0)}destroy(){if(p.shareDumpSent&&this._lastChunk){let e=new Date().toISOString().replace(/:/g,"-").replace(/.\d+Z/,"").replace("T","_");(0,xn.saveAs)(new Blob(this._parts),"sent-screenshare-"+e+".dat"),this._parts=[],this._lastChunk=0}this._datachannel.onbufferedamountlow=null,this._datachannel.onmessage=null,this._datachannel.readyState==="open"&&this._datachannel.send(this._stopPacket()),this._destroyed=!0,this._encoder.destroy(),o.debug("ScreenCaptureSender destroyed")}static isBrowserSupported(){return vt.isBrowserSupported()||kt.isBrowserSupported()}};var ie=class{static get sessionKey(){return ie._sessionKey}static set sessionKey(e){ie._sessionKey=e}static get sessionSecretKey(){return ie._sessionSecretKey}static set sessionSecretKey(e){ie._sessionSecretKey=e}static get accessToken(){return ie._accessToken}static set accessToken(e){ie._accessToken=e}static isEmpty(){return!ie._sessionKey||!ie._sessionSecretKey}};var v=class{static set(e){e.hasOwnProperty("voiceParams")&&(Object.assign(v._params.voiceParams,e.voiceParams),delete e.voiceParams),e.hasOwnProperty("specListenerParams")&&(Object.assign(v._params.specListenerParams,e.specListenerParams),delete e.specListenerParams),e.hasOwnProperty("unifiedPlanBrowsers")&&(Object.assign(v._params.unifiedPlanBrowsers,e.unifiedPlanBrowsers),delete e.unifiedPlanBrowsers),e.hasOwnProperty("apiAuth")&&(ie.accessToken=e.apiAuth.accessToken,ie.sessionKey=e.apiAuth.sessionKey,ie.sessionSecretKey=e.apiAuth.sessionSecretKey),Object.assign(v._params,e)}static get(e){return v._params[e]}static get appName(){return"ok.calls.sdk.js"}static get appVersion(){return 1.1}static get sdkVersion(){return"2.5.2-dev.92f2f89.0"}static get debug(){return!1}static get protocolVersion(){return 5}static get platform(){return v._params.platform}static set platform(e){v._params.platform=e}static get clientType(){return v._params.clientType}static set clientType(e){v._params.clientType=e}static get device(){return v._params.device}static get apiAppId(){return 42}static get apiKey(){return v._params.apiKey}static get apiEnv(){return v._params.apiEnv}static get apiEndpoint(){switch(v.apiEnv){case"AUTO":case"PROD":return"https://api.ok.ru";case"TEST":return"https://apitest.ok.ru/api";case"VIDEOTEST":return"https://videotestapi.ok.ru/api";default:return v._params.apiEnv}}static get authToken(){return v._params.authToken}static set authToken(e){v._params.authToken=e}static get anonymToken(){return v._params.anonymToken}static set anonymToken(e){v._params.anonymToken=e}static get domain(){return v._params.domain}static get iceServers(){return v._params.iceServers}static set iceServers(e){v._params.iceServers=e}static get wssBase(){return v._params.wssBase}static set wssBase(e){v._params.wssBase=e}static get wssToken(){return v._params.wssToken}static set wssToken(e){v._params.wssToken=e}static get signalingReconnectDelay(){return v._params.signalingReconnectDelay}static get signalingReconnectMaxDelay(){return v._params.signalingReconnectMaxDelay}static get signalingReconnectMaxCount(){return v._params.signalingReconnectMaxCount}static get waitConnectionDelay(){return v._params.waitConnectionDelay}static get waitResponseDelay(){return v._params.waitResponseDelay}static get waitMessageDelay(){return v._params.waitMessageDelay}static get debugLog(){return v._params.debugLog}static get forceRelayPolicy(){return v._params.forceRelayPolicy}static set forceRelayPolicy(e){v._params.forceRelayPolicy=e}static get videoMinWidth(){return v._params.videoMinWidth}static get videoMaxWidth(){return v._params.videoMaxWidth}static set videoMaxWidth(e){v._params.videoMaxWidth=e}static get videoMinHeight(){return v._params.videoMinHeight}static get videoMaxHeight(){return v._params.videoMaxHeight}static set videoMaxHeight(e){v._params.videoMaxHeight=e}static get videoAspectRatio(){return v._params.videoAspectRatio}static get videoFrameRate(){return v._params.videoFrameRate}static get videoFacingMode(){return v._params.videoFacingMode}static get screenFrameRate(){return v._params.screenFrameRate}static get videoEffects(){return v._params.videoEffects}static set videoEffects(e){v._params.videoEffects=e}static get videoEffectMaxWidth(){return v._params.videoEffectMaxWidth}static set videoEffectMaxWidth(e){v._params.videoEffectMaxWidth=e}static get videoEffectMaxHeight(){return v._params.videoEffectMaxHeight}static set videoEffectMaxHeight(e){v._params.videoEffectMaxHeight=e}static get voiceParams(){return v._params.voiceParams}static get specListenerParams(){return v._params.specListenerParams}static get iceRestartWaitTime(){return v._params.iceRestartWaitTime}static get transportConnectionWaitTime(){return v._params.transportConnectionWaitTime}static get statisticsInterval(){return v._params.statisticsInterval}static set statisticsInterval(e){v._params.statisticsInterval=e}static get networkStatisticsInterval(){return v._params.networkStatisticsInterval}static get perfStatReportEnabled(){return v._params.perfStatReportEnabled}static get callStatReportEnabled(){return v._params.callStatReportEnabled}static get producerNotificationDataChannel(){return v._params.producerNotificationDataChannel&&nt.isBrowserSupported()}static get producerCommandDataChannel(){return v._params.producerCommandDataChannel}static get consumerScreenDataChannel(){return v._params.consumerScreenDataChannel&&Et.isBrowserSupported()}static get producerScreenDataChannel(){return v._params.producerScreenDataChannel&&v.producerNotificationDataChannel}static get screenShareWebmBuilder(){return v._params.screenShareWebmBuilder}static get noiseSuppression(){return v._params.noiseSuppression}static set noiseSuppression(e){v._params.noiseSuppression=e}static get preferH264(){return v._params.preferH264}static get preferVP9(){return v._params.preferVP9}static get audioNack(){return v._params.audioNack}static get consumerScreenTrack(){return v._params.consumerScreenTrack&&v.consumerScreenDataChannel}static get producerScreenTrack(){return v._params.producerScreenTrack&&v.producerScreenDataChannel}static isUnifiedPlanSupported(e,t){let i=v._params.unifiedPlanBrowsers;return i.hasOwnProperty(e)?t>=i[e]:!1}static get movieShare(){return v._params.movieShare&&v.videoTracksCount>0}static get videoTracksCount(){return v.producerNotificationDataChannel?v._params.videoTracksCount:0}static get breakVideoPayloadTypes(){return v._params.breakVideoPayloadTypes}static get filteredMessages(){return v._params.filteredMessages}static get batchParticipantsOnStart(){return v._params.batchParticipantsOnStart}static get participantStateMapped(){return v._params.participantStateMapped}static get shareDumpSent(){return!0}static get shareDumpReceived(){return!0}static get sharePrintChunkData(){return!0}static get sharePrintFrameData(){return!0}static get sharePlayWebcodecDisabled(){return!1}static get sharePlayPrintFrameByFrame(){return!1}static get sharePlayRegisterMissingParticipantId(){return!1}static get sharePlayFixedDelay(){return 0}},p=v;p._params={platform:"WEB",clientType:"PORTAL",device:"browser",apiKey:"",authToken:"",anonymToken:"",apiEnv:"AUTO",domain:"",iceServers:[],wssBase:"",wssToken:"",signalingReconnectDelay:1e3,signalingReconnectMaxDelay:5e3,signalingReconnectMaxCount:20,waitConnectionDelay:1e4,waitResponseDelay:1e4,waitMessageDelay:15e3,debugLog:!1,forceRelayPolicy:!1,videoMinWidth:428,videoMinHeight:240,videoMaxWidth:1280,videoMaxHeight:720,videoAspectRatio:16/9,videoFrameRate:25,screenFrameRate:15,videoEffects:null,videoEffectMaxWidth:640,videoEffectMaxHeight:360,iceRestartWaitTime:2e4,transportConnectionWaitTime:5e3,statisticsInterval:5e3,networkStatisticsInterval:2e4,perfStatReportEnabled:!0,callStatReportEnabled:!1,voiceParams:{smoothing:.8,minFreq:200,maxFreq:5e3,interval:500,threshold:.35,speakerLevelMultiplier:1.8},specListenerParams:{connectionTimeout:1e4,volumeTimeout:1e4},unifiedPlanBrowsers:{Firefox:10,Chrome:76,Safari:12},producerNotificationDataChannel:!0,producerCommandDataChannel:!0,consumerScreenDataChannel:!0,producerScreenDataChannel:!0,screenShareWebmBuilder:!1,noiseSuppression:!0,preferH264:!1,preferVP9:!0,audioNack:!0,consumerScreenTrack:!1,producerScreenTrack:!1,videoTracksCount:0,movieShare:!1,filteredMessages:!1,breakVideoPayloadTypes:!1,batchParticipantsOnStart:!1,participantStateMapped:!1};var J=(l=>(l.WAITING_HALL="WAITING_HALL",l.WAITING="WAITING",l.CONNECTING="CONNECTING",l.CONNECTED="CONNECTED",l.RECONNECT="RECONNECT",l.ERROR="ERROR",l.HANGUP="HANGUP",l.PERMISSIONS="PERMISSIONS",l))(J||{});function V(n,...e){let t=p.get(n);t&&setTimeout(t,0,...e)}function He(n){return Object.assign({},n)}function Tt(n){return n.slice()}var tr;(he=>{function n(I,B){V("onLocalStream",I,He(B))}he.onLocalStream=n;function e(I,B){V("onScreenStream",I,He(B))}he.onScreenStream=e;function t(I,B){V("onLocalStreamUpdate",He(I),B)}he.onLocalStreamUpdate=t;function i(I){V("onLocalStatus",I)}he.onLocalStatus=i;function r(I,B){V("onRemoteStream",I,B)}he.onRemoteStream=r;function a(I,B,de){V("onRemoteLive",I,B,de)}he.onRemoteLive=a;function s(I,B){V("onRemoteScreenStream",I,B)}he.onRemoteScreenStream=s;function d(I,B,de,yt){V("onConversation",I,He(B),He(de),yt)}he.onConversation=d;function l(I,B){V("onRemoteMediaSettings",I,He(B))}he.onRemoteMediaSettings=l;function u(I,B){V("onRemoteParticipantState",I,He(B))}he.onRemoteParticipantState=u;function g(I,B,de=null){V("onRemoteStatus",I,B,de)}he.onRemoteStatus=g;function f(I,B,de=null){V("onParticipantStatus",I,B,de)}he.onParticipantStatus=f;function W(){V("onPermissionsRequested")}he.onPermissionsRequested=W;function K(I){V("onPermissionsError",I)}he.onPermissionsError=K;function k(I){V("onRemoteRemoved",I)}he.onRemoteRemoved=k;function Y(I,B,de){V("onCallState",I,B,He(de))}he.onCallState=Y;function se(I,B){V("onDeviceSwitched",I,B)}he.onDeviceSwitched=se;function ce(I,B,de,yt=!1,li=!1,ui=null,oa=null){V("onMuteStates",He(I),Tt(B),Tt(de),yt,li,ui,oa)}he.onMuteStates=ce;function dt(I,B){V("onRolesChanged",I,Tt(B))}he.onRolesChanged=dt;function ue(I){V("onLocalRolesChanged",Tt(I))}he.onLocalRolesChanged=ue;function $(I,B){V("onPinnedParticipant",I,B)}he.onPinnedParticipant=$;function Oe(I){V("onLocalPin",I)}he.onLocalPin=Oe;function It(I){V("onOptionsChanged",Tt(I))}he.onOptionsChanged=It;function mr(){V("onCallAccepted")}he.onCallAccepted=mr;function gr(){V("onRateNeeded")}he.onRateNeeded=gr;function C(I){V("onSpeakerChanged",I)}he.onSpeakerChanged=C;function R(I){V("onVolumesDetected",Tt(I))}he.onVolumesDetected=R;function M(I,B){V("onLocalVolume",I,B)}he.onLocalVolume=M;function b(I,B){V("onJoinStatus",I,B)}he.onJoinStatus=b;function w(I,B){V("onHangup",I,B)}he.onHangup=w;function Me(I){V("onMultipartyChatCreated",He(I))}he.onMultipartyChatCreated=Me;function Z(){V("onDeviceChange")}he.onDeviceChange=Z;function U(I){V("onFingerprintChange",I)}he.onFingerprintChange=U;function ee(){V("onTokenExpired")}he.onTokenExpired=ee;function A(I,B,de=!1){V("onChatMessage",I,B,de)}he.onChatMessage=A;function q(I,B,de=!1){V("onCustomData",I,B,de)}he.onCustomData=q;function pe(I,B,de,yt,li,ui){V("onRecordStarted",I,B,de,yt,li,ui)}he.onRecordStarted=pe;function D(){V("onRecordStopped")}he.onRecordStopped=D;function Ge(I){V("onLocalNetworkStatusChanged",I)}he.onLocalNetworkStatusChanged=Ge;function z(I){V("onNetworkStatusChanged",I)}he.onNetworkStatusChanged=z;function Ne(I,...B){V("onDebugMessage",I,...B)}he.onDebugMessage=Ne;function ge(I,B){let de=Object.assign({},I,{memory:B});V("onStatistics",de)}he.onStatistics=ge;function oe(){V("onAutoplayError")}he.onAutoplayError=oe;function te(I,B,de){V("onChatRoomUpdated",I,B,de)}he.onChatRoomUpdated=te})(tr||(tr={}));var E=tr;var ir=(r=>(r.DEBUG="DEBUG",r.LOG="LOG",r.WARN="WARN",r.ERROR="ERROR",r))(ir||{}),rr;(ue=>{let n="📞",e=($,...Oe)=>{E.onDebugMessage($,...Oe)},t=!1,i=($,Oe)=>(...It)=>{$(...It),zr(Oe,It)},r=console.debug.bind(console,n),a=console.log.bind(console,n),s=console.warn.bind(console,n),d=console.error.bind(console,n),l=e.bind(null,"DEBUG"),u=e.bind(null,"LOG"),g=e.bind(null,"WARN"),f=e.bind(null,"ERROR");ue.debug=l,ue.log=u,ue.warn=g,ue.error=f;function se(){return t}ue.enabled=se;function ce($){t=$,p.debugLog&&Si(),$?(ue.debug=p.debugLog?i(r,"DEBUG"):r,ue.log=p.debugLog?i(a,"LOG"):a,ue.warn=p.debugLog?i(s,"WARN"):s,ue.error=p.debugLog?i(d,"ERROR"):d):(ue.debug=p.debugLog?i(l,"DEBUG"):l,ue.log=p.debugLog?i(u,"LOG"):u,ue.warn=p.debugLog?i(g,"WARN"):g,ue.error=p.debugLog?i(f,"ERROR"):f)}ue.toggle=ce;function dt($,...Oe){switch($){case"DEBUG":ue.debug(...Oe);break;case"LOG":ue.log(...Oe);break;case"WARN":ue.warn(...Oe);break;case"ERROR":ue.error(...Oe);break}}ue.send=dt})(rr||(rr={}));var o=rr;var at=(i=>(i.USER="USER",i.ANONYM="ANONYM",i.GROUP="GROUP",i))(at||{}),re;(d=>{function n(l){return l.length?typeof l[0]=="object"?l:l.map(u=>e(u)):[]}d.fromIds=n;function e(l,u="USER"){return{id:l,type:u}}d.fromId=e;function t(l){return{id:l.id,type:l.type==="ANONYM"?"ANONYM":"USER"}}d.fromSignaling=t;function i(l){return`{"id":"${l.id}","type":"${l.type}"}`}d.toString=i;function r(l,u="USER"){return i(e(l,u))}d.fromIdToString=r;function a(l){try{return JSON.parse(l)}catch(u){throw new Error(`Failed to parse ExternalId from string '${l}'`)}}d.fromString=a;function s(l,u){return l.id===u.id&&l.type===u.type}d.compare=s})(re||(re={}));function nr(n,e){return n===null||e===null?n===null&&e===null:!(n.maxDimension!==e.maxDimension||n.maxBitrateK!==e.maxBitrateK||n.maxFramerate!==e.maxFramerate||n.degradationPreference!==e.degradationPreference)}function ii(n,e){return!(!nr(n.camera,e.camera)||!nr(n.screenSharing,e.screenSharing))}function ar(n,e){return{camera:Object.assign({},n.camera,e.camera),screenSharing:Object.assign({},n.screenSharing,e.screenSharing)}}function Ln(n){try{return btoa(JSON.stringify(n))}catch(e){o.warn("WaitingParticipant: failed convert to string",n,e)}return null}function Un(n){try{return JSON.parse(atob(n))}catch(e){o.warn("WaitingParticipant: failed convert from string",n,e)}return null}var xt=class{constructor(e){this._fixNoPacketsApplied=!1;this._fixNoPacketsChecked=!1;this._fixTooManyPacketsApplied=!1;this._fixTooManyPacketsSucceeded=!1;this._fixTooManyPacketsFailed=!1;this._mediaSource=e}_fixAudioDeviceNoPackets(e){if(!(this._fixNoPacketsApplied&&this._fixNoPacketsChecked)){if(this._fixNoPacketsApplied&&!this._fixNoPacketsChecked){this._fixNoPacketsChecked=!0,m.log(_.ERROR,`audio_device_recover_${e.bandwidth?"success":"fail"}`);return}!this._fixNoPacketsApplied&&!e.bandwidth&&(this._fixNoPacketsApplied=!0,m.log(_.ERROR,"audio_device_recover"),this._mediaSource.toggleAudio(!0))}}_fixAudioDeviceTooManyPackets(e){if(this._fixTooManyPacketsSucceeded||this._fixTooManyPacketsFailed)return;let t=75,i=Date.now();if(!this._lastPacketsSentTime)e.packetsSent>0&&(this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent);else if(i-this._lastPacketsSentTime>500){let r=(e.packetsSent-this._lastPacketsSent)*1e3/(i-this._lastPacketsSentTime);this._lastPacketsSentTime=i,this._lastPacketsSent=e.packetsSent,this._fixTooManyPacketsApplied?r>t?(o.log("Failed to fix RV"),m.log(_.ERROR,"audio_device_recover_rv_fail"),this._fixTooManyPacketsFailed=!0):i-this._fixTooManyPacketsTime>6e4&&(o.log("Fixed RV"),m.log(_.ERROR,"audio_device_recover_rv_success"),this._fixTooManyPacketsSucceeded=!0):r>t&&(this._fixTooManyPacketsApplied=!0,o.log("Trying to fix RV"),this._mediaSource.toggleAudio(!0),this._fixTooManyPacketsTime=i)}}fix(e){if(!this._mediaSource)return;let t=e.find(i=>i.kind===me.audio);!t||(this._fixAudioDeviceNoPackets(t),this._fixAudioDeviceTooManyPackets(t))}};var ri=class{constructor(){this._output=null;this._volume=1;this._features={setSinkId:!!Audio.prototype.setSinkId}}add(e){this.destroy(),this._output={},this._output.audioTrack=e,this._initAudioElement()}remove(e){!this._output||this._output.audioTrack!==e||this.destroy()}get volume(){return this._volume}set volume(e){this._volume=Math.max(0,Math.min(1,e)),this._output&&this._output.audioElement&&(this._output.audioElement.volume=this._volume)}_initAudioElement(){var s;if(!((s=this._output)==null?void 0:s.audioTrack))return;let e=y.browserName()!=="Safari",t=document.createElement(e?"audio":"video");t.muted=!1,t.volume=this._volume,t.preload="auto";let i=()=>{o.warn("Error on play audio"),E.onAutoplayError()},r=d=>{t.srcObject=new MediaStream([d]),t.load();let l=t.play();l?l.catch(i):i()},a=()=>{var l;o.debug("Recover audio playback");let d=(l=this._output)==null?void 0:l.audioTrack;d?r(d):o.warn("Broken audio track")};t.onpause=a,t.onstalled=a,t.onerror=a,r(this._output.audioTrack),this._output.audioElement=t}_stopAudioElement(){var e,t,i;((e=this._output)==null?void 0:e.audioElement)&&(this._output.audioElement.pause(),this._output.audioElement.srcObject=null),(i=(t=this._output)==null?void 0:t.audioTrack)==null||i.stop()}destroy(){!this._output||(this._stopAudioElement(),this._output=null)}changeOutput(){return c(this,null,function*(){var e,t,i;try{if(!this._features.setSinkId)throw new Error('Feature "setSinkId" is not supported');if(!((e=this._output)==null?void 0:e.audioElement))throw new Error("Audio Element is not initialized");let r=y.getSavedOutput();r&&(yield(i=(t=this._output.audioElement).setSinkId)==null?void 0:i.call(t,r.deviceId))}catch(r){throw m.log(_.ERROR,"change_output"),o.error("Output change failed",r),r}})}};var gs=90,_s=3,ni=class extends Q{constructor(){super(...arguments);this._lastMemoryStat={percent:0,bytes:0}}onRemoteDataStats(e,t){this._calcMemory(),e.inbound.rtps.map(i=>{let r=typeof i.userId=="string"&&t[i.userId]||null;i.userId=r==null?void 0:r.externalId}),E.onStatistics(e,this._lastMemoryStat)}_calcMemory(){var r;let e=(r=window==null?void 0:window.performance)==null?void 0:r.memory;if(!e||!e.usedJSHeapSize||!e.jsHeapSizeLimit)return;let t=Number((100*e.usedJSHeapSize/e.jsHeapSizeLimit).toFixed(2)),i=Number((e.usedJSHeapSize/1024/1024).toFixed(1));t>gs?o.warn(`High memory usage: ${t}% (${i} MiB)`):(!this._lastMemoryStat.percent||Math.abs(t-this._lastMemoryStat.percent)>=_s)&&(o.debug(`Memory usage: ${t}% (${i} MiB)`),this._lastMemoryStat.percent=t,this._lastMemoryStat.bytes=e.usedJSHeapSize)}};var fs=44100,Nt=class{constructor(e,t){this._analyser=null;this._gainNode=null;this._fftBins=null;this._mediaStreamSource=null;this._lastSmoothedLevel=0;this._trackId=e,this._stream=t;try{let i=y.getAudioContext();this._gainNode=i.createGain(),this._gainNode.gain.value=1e-5,this._gainNode.connect(i.destination),this._analyser=i.createAnalyser(),this._analyser.fftSize=1024,this._analyser.smoothingTimeConstant=0,this._analyser.connect(this._gainNode),this._fftBins=new Uint8Array(this._analyser.frequencyBinCount),this._mediaStreamSource=i.createMediaStreamSource(t),this._mediaStreamSource.connect(this._analyser)}catch(i){}}get stream(){return this._stream}get trackId(){return this._trackId}_getBins(){if(!this._fftBins||!this._analyser)return new Uint8Array;this._analyser.getByteFrequencyData(this._fftBins);let e=fs/this._fftBins.length,t=Math.ceil(p.voiceParams.minFreq/e),i=Math.floor(p.voiceParams.maxFreq/e);return this._fftBins.subarray(t,i)}getLevel(){let e=this._getBins(),i=e.reduce((a,s)=>a+s,0)/e.length/255,r=this._lastSmoothedLevel*p.voiceParams.smoothing+i*(1-p.voiceParams.smoothing);return this._lastSmoothedLevel=r,{real:i,smoothed:r}}destroy(){this._mediaStreamSource&&(this._mediaStreamSource.disconnect(),this._mediaStreamSource=null),this._gainNode&&(this._gainNode.disconnect(),this._gainNode=null),this._analyser&&(this._analyser.disconnect(),this._analyser=null,this._fftBins=null,this._lastSmoothedLevel=0)}};var ai=class extends Q{constructor(e){super();this._detector=null;this._track=null;this._interval=null;let t=()=>{this._detector&&E.onLocalVolume(this._detector.getLevel().real,e.getMediaSettings().isAudioEnabled),this._interval=window.setTimeout(t,p.voiceParams.interval)};this._interval=window.setTimeout(t,p.voiceParams.interval);let i=()=>{let r=e.getStream();r&&this.init(r)};this.subscribe(e,ye.SOURCE_CHANGED,r=>{r.kind===me.audio&&r.mediaSettings.isAudioEnabled&&i()}),i()}init(e){this._stopDetector();let t=e.getAudioTracks();t.length&&(this._track=t[0].clone(),this._detector=new Nt("local",new MediaStream([this._track])))}_stopDetector(){this._detector&&(this._detector.destroy(),this._detector=null),this._track&&(this._track.stop(),this._track=null)}destroy(){this.unsubscribe(),this._interval&&(window.clearTimeout(this._interval),this._interval=null),this._stopDetector()}};var Ss=1e3;function be(n,e,t=0){return e in n&&n[e]?n[e]:t}function Bn(...n){return e=>{for(let t of n)if(t(e))return!0;return!1}}function Je(n,e){return t=>t[n]===e}function vs(n){return(e,t)=>e[n]-t[n]}function si(n,e){return e.reduce((t,i)=>(t[i[n]]=i,t),{})}function Es(n){let e={},t=[];for(let i of n)e[i.id]||(e[i.id]=!0,t.push(i));return t}function Ts(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function sr(n){return Object.keys(n).filter(e=>n[e]!==void 0).map(e=>[e,n[e]]).reduce((e,t)=>(e[t[0]]=Ts(t[1])?sr(t[1]):t[1],e),{})}function Cs(n){let e=[];for(let t of n)t.forEach(i=>e.push(i));return e}function Is(n){return c(this,null,function*(){let e=[];return RTCRtpReceiver.prototype.getStats?(e.push(...n.getReceivers().map(t=>t.getStats())),e.push(...n.getSenders().map(t=>t.getStats()))):e.push(n.getStats()),Promise.all(e).then(Cs).then(Es)})}function ys(n){let e=n.filter(Je("type","candidate-pair")).sort(vs("priority")).find(Bn(Je("nominated",!0),Je("selected",!0)));if(!e)return{totalRoundTripTime:0,currentRoundTripTime:0,bytesSent:0,bytesReceived:0};let t={totalRoundTripTime:e.totalRoundTripTime||0,currentRoundTripTime:e.currentRoundTripTime||0,bytesSent:e.bytesSent,bytesReceived:e.bytesReceived},i=n.find(Je("id",e.remoteCandidateId));i&&(t=Object.assign({},t,{remote:{type:i.candidateType,address:i.ip||i.address,port:i.port,protocol:i.protocol}}));let r=n.find(Je("id",e.localCandidateId));return r&&(t=Object.assign({},t,{local:{type:r.candidateType,address:r.ip||r.address,port:r.port,protocol:r.protocol,relayProtocol:r.relayProtocol,networkType:r.networkType}})),sr(t)}function Rs(n,e){let t=si("id",n),i=n.filter(Bn(Je("type","inbound-rtp"),Je("type","outbound-rtp")));y.browserName()==="Firefox"&&(i=Object.values(i.reduce((a,s)=>{if(!a[s.ssrc])a[s.ssrc]=s;else{let d=Object.assign({},a[s.ssrc],s),l=a[s.ssrc].isRemote?s:a[s.ssrc];d.id=l.id,d.type=l.type,delete d.isRemote,delete d.remoteId,a[d.ssrc]=d}return a},{})));let r={};if(y.browserName()==="Safari"){let a=n.filter(Je("type","track"));r=si("trackIdentifier",a)}return i.map(a=>{let s=Number(a.ssrc),d=a.mediaType||a.kind,l=a.trackId,u=a.type,g=a.codecId;if(y.browserName()==="Safari"){let se=/^.+_([\d]+)$/.exec(a.id);if(se&&(s=parseInt(se[1],10)),d=a.id.indexOf("Audio")>0?"audio":"video",e[s]){let ce=d+"-"+e[s];r[ce]&&(l=r[ce].id)}}if(!u||!s||!d)return null;let f=be(a,"framesDecoded"),W=be(a,"totalInterFrameDelay"),k=(be(a,"totalSquaredInterFrameDelay")-W*W/f)/f,Y={ssrc:s,type:u,kind:d,bytesReceived:be(a,"bytesReceived"),bytesSent:be(a,"bytesSent"),jitter:be(a,"jitter"),packetsLost:be(a,"packetsLost"),packetsReceived:be(a,"packetsReceived"),packetsSent:be(a,"packetsSent"),fractionLost:be(a,"fractionLost"),pliCount:be(a,"pliCount"),firCount:be(a,"firCount"),nackCount:be(a,"nackCount"),userId:e[s],interframeDelayVariance:k};if(g&&t[g]){let se=t[g];Y.clockRate=se.clockRate,Y.mimeType=se.mimeType}if(l&&t[l]){let se=t[l];Y.frameHeight=se.frameHeight,Y.frameWidth=se.frameWidth,Y.framesDecoded=se.framesDecoded,Y.framesReceived=se.framesReceived,Y.framesDropped=se.framesDropped}return sr(Y)}).filter(a=>!!a)}function bs(n,e){if(!e||!e.rtps||!n.rtps)return n;let t=si("ssrc",n.rtps),i=si("ssrc",e.rtps),r=(n.timestamp-e.timestamp)/1e3;return!t||!i||Object.keys(t).forEach(a=>{let s=t[a],d=i[a];if(!(!s||!d)){if(s.bytesReceived&&s.bytesReceived>d.bytesReceived&&(s.bandwidth=Math.round((s.bytesReceived-d.bytesReceived)/r)),s.bytesSent&&s.bytesSent>d.bytesSent&&(s.bandwidth=Math.round((s.bytesSent-d.bytesSent)/r)),s.packetsReceived)if(s.packetsReceived>d.packetsReceived||s.packetsLost>d.packetsLost){let l=s.packetsLost-d.packetsLost,u=s.packetsReceived-d.packetsReceived;s.packetLoss=parseFloat((100*l/(l+u)).toFixed(2))}else s.packetLoss=0;s.framesDropped&&d.framesDropped&&s.framesDropped>d.framesDropped&&(s.framesDroppedDelta=parseFloat(((s.framesDropped-d.framesDropped)/r).toFixed(0)))}}),n}function Lt(i,r){return c(this,arguments,function*(n,e,t={}){let a=yield Is(n),s={timestamp:Date.now(),transport:ys(a),rtps:Rs(a,t)};return e?bs(s,e):(yield T.delay(Ss),Lt(n,s,t))})}var oi=.8,st=class extends Q{constructor(e,t,i,r,a){super();this._remoteSDP={};this._remoteCandidates={};this._state=F.IDLE;this._isOpen=!1;this._remotePeerId=null;this._statInterval=null;this._settingsInterval=null;this._failedOnCreate=null;this._remoteStream=null;this._iceRestartTimeout=null;this._reconnectionTimeout=null;this._reconnectionPrevented=!1;this._fingerprint=null;this._neverConnected=!0;this._prevConsumerSettings={};this._lastNetworkStat={rtt:0,loss:0,date:0};this._remoteNetworkStat={rtt:0,loss:0};this._networkLimits={badNet:{loss:3,rtt:1e3},goodNet:{loss:.5,rtt:600}};if(this._signaling=i,this._mediaSource=r,this._participantId=e,this._isMaster=t,this._serverSettings=a,this.subscribe(this._signaling,fe.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ye.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ye.SOURCE_CHANGED,this._applySettings.bind(this)),this._pc=new RTCPeerConnection({iceServers:p.iceServers,iceTransportPolicy:p.forceRelayPolicy?"relay":"all"},{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.onicecandidate=this._handleIceCandidate.bind(this),this._pc.ontrack=this._onAddTrack.bind(this),this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this),this._pc.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this),this._prevConsumerSettings={},this._isMaster){try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(s){m.log(_.ERROR,"addTrack-direct"),o.error("Unable to add media source tracks",s,{participantId:this._participantId}),this._failedOnCreate=s;return}this._createOffer(!1).catch(s=>{this._state===F.IDLE?this._failedOnCreate=s:this.close(s)})}this._startSettingsInterval(),this._startStatInterval()}getState(){return this._state}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==F.IDLE&&e!==F.CLOSED&&e!==F.FAILED&&this._startStatInterval()}open(e=null){return c(this,null,function*(){if(this._isOpen){o.warn("DirectTransport: Already opened",{participantId:this._participantId});return}if(this._failedOnCreate){this.close(this._failedOnCreate);return}if(o.debug("DirectTransport: Open transport",{participantId:this._participantId}),this._isOpen=!0,this._remotePeerId=e,!this._isMaster)try{this._mediaSource.addTrackToPeerConnection(this._pc,!0),this._applySettings()}catch(i){m.log(_.ERROR,"addTrack-direct"),o.error("DirectTransport: Unable to add media source tracks",i,{participantId:this._participantId}),this.close(i);return}this._setState(F.OPENED);let t=e;if(!e){let i=Object.keys(this._remoteSDP);t=i[i.length-1]}if(t&&this._remoteSDP[t])try{yield this._setRemoteDescription(t,this._remoteSDP[t])}catch(i){this.close();return}this._remoteSDP={},this._remoteCandidates={},this._triggerEvent(N.ACTIVE_PARTICIPANTS_NO_SIGNAL)})}updateSettings(e){ii(e,this._serverSettings)||(this._serverSettings=e,this._applySettings())}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}close(e){this._isOpen=!1,this._stopReconnection(),this._remoteStream&&(this._remoteStream.getTracks().forEach(t=>{t.stop(),this._triggerEvent(N.REMOTE_TRACK_REMOVED,this._remoteStream,t)}),this._remoteStream=null),this._stopStatInterval(),this._stopSettingsInterval(),this._pc&&(this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.oniceconnectionstatechange=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._pc.close()),this.unsubscribe(),e?(o.error("DirectTransport: Closed",e,{participantId:this._participantId}),this._setState(F.FAILED)):(o.debug("DirectTransport: Closed",{participantId:this._participantId}),this._setState(F.CLOSED)),this._triggerEvent(N.PEER_CONNECTION_CLOSED)}_setState(e){this._state!==e&&(o.debug(`DirectTransport: State changed to ${e}`,{participantId:this._participantId}),this._state=e,this._triggerEvent(N.STATE_CHANGED,e))}_onSignalingNotification(e){var t,i,r,a;switch(e.notification){case O.TRANSMITTED_DATA:this._handleTransmittedData(e);break;case O.SETTINGS_UPDATE:Object.assign(this._networkLimits.badNet,((t=e.settings)==null?void 0:t.badNet)||{}),Object.assign(this._networkLimits.goodNet,((i=e.settings)==null?void 0:i.goodNet)||{});break;case O.CUSTOM_DATA:e.data.hasOwnProperty("sdk")&&(this._remoteNetworkStat.rtt=((r=e.data.sdk)==null?void 0:r.rtt)||0,this._remoteNetworkStat.loss=((a=e.data.sdk)==null?void 0:a.loss)||0);break}}_handleTransmittedData(e){let t=e.data,i=T.getPeerIdString(e.peerId);T.composeMessageId(e)===this._participantId&&(t.candidate&&t.candidate.candidate?this._addIceCandidate(i,t.candidate).catch(this.close.bind(this)):t.sdp&&this._setRemoteDescription(i,t.sdp).catch(this.close.bind(this)))}_addIceCandidate(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc&&this._pc.remoteDescription){o.debug("Add remote ice candidate",{participantId:this._participantId,candidate:t});try{yield this._pc.addIceCandidate(new RTCIceCandidate(t))}catch(i){throw m.log(_.ERROR,"addIceCandidate-direct"),o.error("Unable to add remote ice candidate",i,{participantId:this._participantId,candidate:t}),i}}else o.debug("Cache remote ice candidate",{participantId:this._participantId,candidate:t}),this._remoteCandidates[e]=this._remoteCandidates[e]||[],this._remoteCandidates[e].push(t)})}_setRemoteCandidates(e){return c(this,null,function*(){if(!this._remoteCandidates[e]){o.log(`No cached candidates found for peer ${e}`);return}let t=this._remoteCandidates[e];this._remoteCandidates[e]=[];for(let i of t)try{yield this._addIceCandidate(e,i)}catch(r){}})}_setRemoteDescription(e,t){return c(this,null,function*(){if(this._isOpen&&(!this._remotePeerId||this._remotePeerId===e)&&this._pc){o.debug("Add remote description",{participantId:this._participantId,sdp:t}),this._calcFingerprint(t.sdp);try{yield this._pc.setRemoteDescription(new RTCSessionDescription(t)),yield this._setRemoteCandidates(e)}catch(i){throw m.log(_.ERROR,"setRemoteDescription-direct"),o.error("Unable to set remote description",i,{participantId:this._participantId,sdp:t}),i}}else this._remoteSDP[e]=t})}_onAddTrack(e){o.debug("Added remote track",{participantId:this._participantId,kind:e.track.kind}),this._remoteStream?this._remoteStream.addTrack(e.track):(this._remoteStream=new MediaStream([e.track]),this._remoteStream.onremovetrack=t=>{this._triggerEvent(N.REMOTE_TRACK_REMOVED,this._remoteStream,t.track)}),this._triggerEvent(N.REMOTE_TRACK_ADDED,this._remoteStream,e.track)}_handleIceCandidate(e){return c(this,null,function*(){e.candidate&&this._signaling.ready&&(o.debug("Local ice candidate",{participantId:this._participantId,candidate:e.candidate}),yield this._signaling.sendCandidate(this._participantId,e.candidate))})}_onSignalingStateChange(){switch(o.debug(`DirectTransport: Signaling state changed to ${this._pc.signalingState}`,{participantId:this._participantId}),this._pc.signalingState){case"have-local-offer":let e=this._pc.localDescription;e?this._signaling.sendSdp(this._participantId,e).catch(this.close.bind(this)):this.close(new Error);break;case"have-remote-offer":this._createAnswer().catch(this.close.bind(this)).then(t=>c(this,null,function*(){return this._signaling.sendSdp(this._participantId,t)})).catch(this.close.bind(this));break}}_onIceConnectionStateChange(){switch(o.debug(`DirectTransport: Ice Connection state changed to ${this._pc.iceConnectionState}`,{participantId:this._participantId}),this._pc.iceConnectionState){case"checking":let e=this.getState();e===F.IDLE||e===F.OPENED?this._setState(F.CONNECTING):this._setState(F.RECONNECTING);break}}_onConnectionStateChange(){switch(o.debug(`DirectTransport: Connection state changed to ${this._pc.connectionState}`,{participantId:this._participantId}),m.log(_.ICE_CONNECTION_STATE,this._pc.connectionState),this._pc.connectionState){case"connected":this._neverConnected=!1,this._setState(F.CONNECTED),this._stopReconnection(),T.getPeerConnectionHostInfo(this._pc).then(e=>{e&&m.log(_.ICE_CONNECTION_TYPE,e.type)});break;case"failed":case"disconnected":this._reconnectionPrevented?this.close(new Error(`Ice connection ${this._pc.connectionState}`)):(this._setState(F.RECONNECTING),this._startReconnection());break;case"closed":this.close(new Error("Ice connection closed"));break}}_startReconnection(){this._reconnectionTimeout||this._iceRestartTimeout||(o.log("Waiting for reconnection...",{participantId:this._participantId}),this._reconnectionTimeout=window.setTimeout(()=>{this._reconnectionTimeout=null,this._neverConnected?this._requestTopologySwitch():this._startIceRestart()},p.transportConnectionWaitTime))}_requestTopologySwitch(){this._isMaster&&this._signaling.ready&&(o.log("Switch topology DIRECT to SERVER",{participantId:this._participantId}),this._signaling.switchTopology(Pe.SERVER))}_stopReconnection(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=null),this._iceRestartTimeout&&(clearTimeout(this._iceRestartTimeout),this._iceRestartTimeout=null)}_startIceRestart(){this._isMaster?(m.log(_.ICE_RESTART),o.log("Ice restart",{participantId:this._participantId}),this._createOffer(!0).catch(this.close.bind(this))):o.debug("Waiting for ice restart...",{participantId:this._participantId}),this._iceRestartTimeout=window.setTimeout(()=>{this._iceRestartTimeout=null,o.error("Ice restart failed",{participantId:this._participantId}),m.log(_.ERROR,"iceRestart-direct"),this._requestTopologySwitch()},p.iceRestartWaitTime)}_createOffer(e){return c(this,null,function*(){let t={iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0};return o.debug("Create offer",{participantId:this._participantId,options:t}),this._pc.createOffer(t).catch(i=>{throw o.error("Unable to create offer",i,{participantId:this._participantId}),m.log(_.ERROR,"createOffer-direct"),i}).then(i=>c(this,null,function*(){return o.debug("Created offer",{participantId:this._participantId,offer:i}),i=st._patchDescription(i),o.debug("Set local description",{participantId:this._participantId,offer:i}),this._calcFingerprint(i.sdp),this._pc.setLocalDescription(i).then(()=>this._pc.localDescription)})).catch(i=>{throw o.error("Unable to set local description",i,{participantId:this._participantId}),m.log(_.ERROR,"setLocalDescription-direct"),i})})}_createAnswer(){return c(this,null,function*(){return o.debug("Create answer",{participantId:this._participantId}),this._pc.createAnswer().catch(e=>{throw o.error("Unable to create answer",e,{participantId:this._participantId}),m.log(_.ERROR,"createAnswer-direct"),e}).then(e=>c(this,null,function*(){return o.debug("Created answer",{participantId:this._participantId,answer:e}),e=st._patchDescription(e),o.debug("Set local description",{participantId:this._participantId,answer:e}),this._calcFingerprint(e.sdp),this._pc.setLocalDescription(e)})).then(()=>this._pc.localDescription).catch(e=>{throw o.error("Unable to set local description",e,{participantId:this._participantId}),m.log(_.ERROR,"setLocalDescription-direct"),e})})}static _patchDescription(e){let t=!!y.baseChromeVersion();return e.sdp=T.patchSDP(e.sdp,p.preferH264&&y.canPreferH264(),y.isBrokenH264(),p.preferVP9,t&&p.audioNack),e}_onReplacedTrack(e){this._pc&&(this._pc.getSenders().forEach(t=>{t.track&&t.track.kind===e.kind&&(t.track.enabled=e.enabled,t.replaceTrack(e).catch(i=>{o.error("DirectTransport: Unable to replace track",i,{participantId:this._participantId}),m.log(_.ERROR,"replaceTrack-direct")}))}),this._applySettings())}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}Lt(this._pc,this._lastStat).then(t=>{this._lastStat=t;let i={inbound:{topology:Pe.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="inbound-rtp"?(r.userId=this._participantId,!0):!1)},outbound:{topology:Pe.DIRECT,transport:t.transport,rtps:t.rtps.filter(r=>r.type==="outbound-rtp")}};this._checkBadNetwork(i),this._triggerEvent(N.REMOTE_DATA_STATS,i),this._statInterval=window.setTimeout(e,p.statisticsInterval)})};this._statInterval=window.setTimeout(e,p.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null)}_checkBadNetwork(e){if(!this._signaling.ready)return;let t=ce=>ce.rtt<=this._networkLimits.goodNet.rtt&&ce.loss<=this._networkLimits.goodNet.loss,i=ce=>ce.rtt>=this._networkLimits.badNet.rtt||ce.loss>=this._networkLimits.badNet.loss,r=Math.round(e.outbound.transport.currentRoundTripTime*1e3)||0,a=e.inbound.rtps.reduce((ce,dt)=>Math.max(ce,dt.packetLoss||0),0),s={rtt:this._lastNetworkStat.rtt*(1-oi)+r*oi,loss:this._lastNetworkStat.loss*(1-oi)+a*oi},d=i(s),l=t(s),u=i(this._remoteNetworkStat),g=t(this._remoteNetworkStat),f=i(this._lastNetworkStat),W=t(this._lastNetworkStat),Y=d||u?.2:l&&g?1:0,se=Date.now();if((f!==d||W!==l||se-this._lastNetworkStat.date>p.networkStatisticsInterval)&&(this._lastNetworkStat.date=Date.now(),this._signaling.customData({sdk:Object.assign({type:"bad-net"},s)},null).catch(ce=>{o.warn("Unable to send [bad-net]",ce)})),Y){let ce={};ce[this._participantId]=ce[""]=Y,this._triggerEvent(N.NETWORK_STATUS,ce)}this._lastNetworkStat.rtt=s.rtt,this._lastNetworkStat.loss=s.loss}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applySettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_calcFingerprint(e){let t=T.sdpFingerprint(e);this._fingerprint===null?this._fingerprint=t:(E.onFingerprintChange(this._fingerprint.xor(t).toString()),this._fingerprint=null)}_applySettings(){var t;let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled?this._serverSettings.screenSharing:this._serverSettings.camera;e&&((t=this._pc)==null?void 0:t.connectionState)==="connected"&&(this._prevConsumerSettings=T.applySettings(this._pc,e,this._prevConsumerSettings))}};var Fn=(r=>(r.producerNotification="producerNotification",r.producerCommand="producerCommand",r.consumerScreenShare="consumerScreenShare",r.producerScreenShare="producerScreenShare",r))(Fn||{}),Ut=Fn;var ot=Ie(require("messagepack"));var or=class{constructor(){this.streamDescriptionByCompactId=new Map}getStreamDescription(e){return this.streamDescriptionByCompactId.get(e)}register(e,t){this.streamDescriptionByCompactId.set(e,t)}handleMessage(e){var a,s;let t=new Uint8Array(e),i=t[0],r=t.subarray(1);switch(i){case 1:let d=(0,ot.decode)(r);return Object.entries(d).forEach(([k,Y])=>{let se=Mt(k);this.streamDescriptionByCompactId.set(Y,se)}),null;case 2:case 4:let l=(0,ot.decode)(r),u=[];for(let k of l){let Y=this.getStreamDescription(k);Y&&u.push(Y.participantId)}return i===2?{type:"notification",notification:O.AUDIO_ACTIVITY,activeParticipants:u}:{type:"notification",notification:O.STALLED_ACTIVITY,stalledParticipants:u};case 3:let g=(0,ot.decode)(r);return{type:"notification",notification:O.SPEAKER_CHANGED,speaker:(a=this.getStreamDescription(g))==null?void 0:a.participantId};case 5:let f=(0,ot.decode)(r);return{type:"notification",notification:O.VIDEO_QUALITY_UPDATE,quality:{maxBitrate:f[0],maxDimension:f[1]}};case 6:let W=(0,ot.decode)(r),K={};for(let[k,Y]of Object.entries(W)){let se=(s=this.getStreamDescription(Number(k)))==null?void 0:s.participantId;se&&(K[se]=Y/100)}return{type:"notification",notification:O.NETWORK_STATUS,statuses:K};case 7:return this._createParticipantSourcesUpdateNotification(r);default:return o.debug("unsupported message type: "+i),null}}_createParticipantSourcesUpdateNotification(e){let t=(0,ot.decode)(e),i=[];for(let[r,a]of Object.entries(t)){let s=a[0],d=a[1],l=a[2],u;if(s!==null){if(u=this.getStreamDescription(s),!u){o.error(`could not uncompress participant ID ${s}`);continue}}else u=null;if(l===null){o.error("unexpected null sequenceNumber",r,a);continue}let g=ke.PARTICIPANT_AGNOSTIC_TRACK_PREFIX+"-"+r,f=d?d>>>0:null;i.push({participantStreamDescription:u,streamId:g,rtpTimestamp:f,sequenceNumber:l})}return{type:"notification",notification:O.PARTICIPANT_SOURCES_UPDATE,participantUpdateInfos:i}}};var Vn="videochat-epi",Ps=5e3,Ms=3e4,Bt=class extends Q{constructor(e,t){super();this._previousTimestamp=0;this._previousCallStatReportTimestamp=0;this._previousCallStatReport={nack_sent:0,nack_received:0,pli_sent:0,pli_received:0,fir_sent:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0};this._signaling=t,this.subscribe(e,N.REMOTE_DATA_STATS,this._handleStats.bind(this))}destroy(){this.unsubscribe()}static getEstimatedPerformanceIndex(){try{let e=parseInt(localStorage.getItem(Vn)||"",10);return isNaN(e)?0:e}catch(e){return 0}}_handleStats(e){return c(this,null,function*(){if(!e.inbound||!e.inbound.rtps)return;let t=Date.now();p.perfStatReportEnabled&&this._previousTimestamp+Ps<=t&&(yield this.reportPerfStats(e),this._previousTimestamp=t),p.callStatReportEnabled&&this._previousCallStatReportTimestamp+Ms<=t&&(this._reportCallStats(e),this._previousCallStatReportTimestamp=t)})}reportPerfStats(e){return c(this,null,function*(){let t=e.inbound.rtps.reduce((i,r)=>(r.kind==="video"&&(i.framesDecoded+=r.framesDecoded||0,i.framesReceived+=r.framesReceived||0),i),{framesDecoded:0,framesReceived:0});if(t.framesDecoded)try{let i=yield this._signaling.reportPerfStat(t);localStorage.setItem(Vn,i.estimatedPerformanceIndex)}catch(i){}})}_reportCallStats(e){let t={nack_received:0,pli_received:0,fir_received:0,frames_dropped:0,jitter_video:0,jitter_audio:0,interframe_delay_variance:0,nack_sent:0,pli_sent:0,fir_sent:0,inbound_video_count:0,inbound_audio_count:0};e.inbound.rtps.reduce((r,a)=>(a.kind==="video"?(a.jitter&&(r.jitter_video=r.jitter_video*r.inbound_video_count/(r.inbound_video_count+1)+a.jitter*1e3/(r.inbound_video_count+1),r.interframe_delay_variance=r.interframe_delay_variance*r.inbound_video_count/(r.inbound_video_count+1)+a.interframeDelayVariance*1e6/(r.inbound_video_count+1),r.inbound_video_count++),r.frames_dropped+=a.framesDropped,r.nack_received+=a.nackCount||0,r.pli_received+=a.pliCount||0,r.fir_received+=a.firCount||0):a.jitter&&(r.jitter_audio=r.jitter_audio*r.inbound_audio_count/(r.inbound_audio_count+1)+a.jitter*1e3/(r.inbound_audio_count+1),r.inbound_audio_count++),r),t),e.outbound.rtps.reduce((r,a)=>(a.kind==="video"&&(r.nack_sent+=a.nackCount||0,r.pli_sent+=a.pliCount||0,r.fir_sent+=a.firCount||0),r),t);let i={nack_sent:t.nack_sent-this._previousCallStatReport.nack_sent,nack_received:t.nack_received-this._previousCallStatReport.nack_received,pli_sent:t.pli_sent-this._previousCallStatReport.pli_sent,pli_received:t.pli_received-this._previousCallStatReport.pli_received,fir_sent:t.fir_sent-this._previousCallStatReport.fir_sent,fir_received:t.fir_received-this._previousCallStatReport.fir_received,frames_dropped:t.frames_dropped-this._previousCallStatReport.frames_dropped};t.jitter_video&&(i.jitter_video=t.jitter_video),t.jitter_audio&&(i.jitter_audio=t.jitter_audio),t.interframe_delay_variance&&(i.interframe_delay_variance=t.interframe_delay_variance),m.logCustom("callStat",i),this._previousCallStatReport=t}};var As=90,Ds=4294967295,De=class extends Q{constructor(e,t,i){super();this._pc=null;this._producerNotification=null;this._producerCommand=null;this._producerScreen=null;this._consumerScreen=null;this._isOpen=!1;this._reconnectionPrevented=!1;this._state=F.IDLE;this._statInterval=null;this._settingsInterval=null;this._statBytes={};this._ssrcMap={};this._producerOfferIsProcessing=!1;this._producerNextOffer=null;this._prevConsumerSettings={};this._captureSender=null;this._captureReceiver=null;this._participantIdRegistry=null;this._disabledSenders=new Set;this._rtpReceiversByStreamId={};this._producerSessionId="";this._signaling=e,this._mediaSource=t,this.subscribe(this._signaling,fe.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._mediaSource,ye.TRACK_REPLACED,this._onReplacedTrack.bind(this)),this.subscribe(this._mediaSource,ye.SOURCE_CHANGED,this._applyConsumerSettings.bind(this)),this.subscribe(this._mediaSource,ye.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._perfStatReporter=new Bt(this,e),this._serverSettings=i,o.debug("ServerTransport: Created")}getState(){return this._state||F.IDLE}updateStatisticsInterval(){this._stopStatInterval();let e=this.getState();e!==F.IDLE&&e!==F.CLOSED&&e!==F.FAILED&&this._startStatInterval()}open(){if(this._isOpen){o.log("ServerTransport: Already opened connections");return}this._isOpen=!0,this._openConnection()}close(e){this._isOpen=!1,this._closeConnection(),this.unsubscribe(),e?(o.error("ServerTransport: Closed",e),this._setState(F.FAILED)):(o.debug("ServerTransport: Closed"),this._setState(F.CLOSED))}removeParticipant(e){var t;(t=this._captureReceiver)==null||t.close(e)}preventRestart(){this._reconnectionPrevented=!0}allowRestart(){this._reconnectionPrevented=!1}updateSettings(e){ii(e,this._serverSettings)||(this._serverSettings=e,this._applyConsumerSettings())}_closeConnection(){this._stopStatInterval(),this._stopSettingsInterval(),this._removeCaptureSender(),this._removeCaptureReceiver(),this._pc&&(this._rtpReceiversByStreamId={},this._disabledSenders.forEach(e=>{var t;return(t=e.track)==null?void 0:t.stop()}),this._disabledSenders.clear(),this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.onsignalingstatechange=null,this._participantIdRegistry=null,De._closeDataChannel(this._producerNotification),De._closeDataChannel(this._producerCommand),De._closeDataChannel(this._producerScreen),De._closeDataChannel(this._consumerScreen),this._pc.close(),this._pc=null,this._producerOfferIsProcessing=!1,this._producerNextOffer=null),this._triggerEvent(N.PEER_CONNECTION_CLOSED)}static _closeDataChannel(e){e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.close())}_createDataChannel(e,t,i){o.debug(`[${t}] data channel opening`);let r=e.createDataChannel(t,{ordered:!0});r.onopen=()=>{o.debug(`[${t}] data channel opened`),r.onerror=a=>{o.error(`[${t}] data channel error`,a)},i(r)}}_openConnection(e=!1){o.debug("ServerTransport: Open single connection");let t={};y.baseChromeVersion()&&(t.sdpSemantics=De._isUnifiedPlanSupported()?"unified-plan":"plan-b"),this._pc=new RTCPeerConnection(t,{optional:[{googSuspendBelowMinBitrate:!1}]}),this._pc.ontrack=this._onAddTrack.bind(this,this._pc),this._pc.onconnectionstatechange=T.throttle(i=>{this._pc&&this._onConnectionStateChange(this._pc,i)},500),this._pc.onsignalingstatechange=De._onSignalingStateChange.bind(this,this._pc),p.producerNotificationDataChannel&&this._createDataChannel(this._pc,Ut.producerNotification,i=>{this._producerNotification=i,this._producerNotification.binaryType="arraybuffer",this._participantIdRegistry=new or,this._signaling.setParticipantIdRegistry(this._participantIdRegistry),this._signaling.setProducerNotificationDataChannel(i)}),p.producerCommandDataChannel&&this._createDataChannel(this._pc,Ut.producerCommand,i=>{this._producerCommand=i,this._signaling.setProducerCommandDataChannel(i)}),p.producerScreenDataChannel&&this._createDataChannel(this._pc,Ut.producerScreenShare,i=>{this._producerScreen=i,this._producerScreen.binaryType="arraybuffer",this._createCaptureReceiver()});try{this._mediaSource.addTrackToPeerConnection(this._pc),this._prevConsumerSettings={},this._applyConsumerSettings()}catch(i){o.error("ServerTransport: Unable to add media source tracks",i),m.log(_.ERROR,"addTrack-single"),this.close(i);return}p.consumerScreenDataChannel&&this._createDataChannel(this._pc,Ut.consumerScreenShare,i=>{this._consumerScreen=i,this._consumerScreen.binaryType="arraybuffer";let r=this._mediaSource.getScreenTrack();r&&this._createCaptureSender(r)}),e||this._allocateConsumer(),this._setState(F.OPENED),this._startStatInterval(),this._startSettingsInterval()}_reconnect(){this.getState()!==F.OPENED&&(this._setState(F.RECONNECTING),this._closeConnection(),this._openConnection(!0))}_signalActiveParticipants(e){this._triggerEvent(N.SIGNALLED_ACTIVE_PARTICIPANTS,e)}_signalStalledParticipants(e){this._triggerEvent(N.SIGNALLED_STALLED_PARTICIPANTS,e)}_signalSpeakerChanged(e){this._triggerEvent(N.SIGNALLED_SPEAKER_CHANGED,e)}_signalNetworkStatus(e){this._triggerEvent(N.NETWORK_STATUS,e)}_updateSSRCMap(e){e&&e.sdp.split(`
12
+ `).forEach(t=>{let i=`a=ssrc:([0-9]+) label:(audio|video)-((?:[ug]?[\\d]+)|(?:mix)|(?:${ke.PARTICIPANT_AGNOSTIC_TRACK_PREFIX}-[0-9]+))`,r=new RegExp(i).exec(t);r&&(this._ssrcMap[r[1]]=r[3])})}_createCaptureSender(e){!e||!p.consumerScreenDataChannel||!this._consumerScreen||!this._mediaSource.getMediaSettings().isScreenSharingEnabled||(this._captureSender&&this._removeCaptureSender(),this._captureSender=new Et(e,this._consumerScreen))}_removeCaptureSender(){var e;(e=this._captureSender)==null||e.destroy(),this._captureSender=null}_createCaptureReceiver(){!p.producerScreenDataChannel||!this._producerScreen||!this._participantIdRegistry||(this._captureReceiver&&this._removeCaptureReceiver(),this._captureReceiver=new nt(null,this._producerScreen,this._participantIdRegistry,(e,t)=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,e,t)},e=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,e,null)}))}replayShare(e,t){var i;!this._participantIdRegistry||((i=this._captureReceiver)==null||i.destroy(),this._captureReceiver=new nt(t,e,this._participantIdRegistry,(r,a)=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,r,a)},r=>{this._triggerEvent(N.REMOTE_STREAM_SECOND,r,null)}))}_removeCaptureReceiver(){var e;(e=this._captureReceiver)==null||e.destroy(),this._captureReceiver=null}_applyConsumerSettings(){let e=this._mediaSource.getMediaSettings().isScreenSharingEnabled&&!p.consumerScreenDataChannel?this._serverSettings.screenSharing:this._serverSettings.camera;if(e&&this._pc){let t=[];this._pc.getSenders().forEach(i=>{if(!i.track||i.track.kind!==me.video)return;let r=!this._disabledSenders.has(i),a=e.maxDimension!==0;if(r&&!a){o.log("Disabling video upload"),this._disabledSenders.add(i),i.replaceTrack(y.getBlackMediaTrack()).catch(d=>{o.error("Could not disable video upload",d)});return}let s=this._mediaSource.getSendVideoTrack();if(!r&&a&&s){o.log("Enabling video upload"),this._disabledSenders.delete(i);let d=i.track;d.enabled=s.enabled,i.replaceTrack(s).then(()=>d.stop()).catch(l=>{o.error("Could not enable video upload",l)})}T.applyVideoTrackSettings(e,i,s!=null?s:i.track,this._prevConsumerSettings,t)}),this._prevConsumerSettings=t}}_onScreenSharingStatus(e){e.track?this._createCaptureSender(e.track):this._removeCaptureSender()}_setState(e){this._state!==e&&(this._state=e,this._triggerEvent(N.STATE_CHANGED,e))}_startStatInterval(){if(this._statInterval)return;let e=()=>{if(!this._pc){this._stopStatInterval();return}this._collectStat().then(t=>{this._reportStats(t),this._detectStaleTracks(t)}).catch(()=>{}),this._statInterval=window.setTimeout(e,p.statisticsInterval)};this._statInterval=window.setTimeout(e,p.statisticsInterval)}_stopStatInterval(){this._statInterval&&(window.clearTimeout(this._statInterval),this._statInterval=null),this._statBytes={}}_startSettingsInterval(){let e=2e3;if(this._settingsInterval)return;let t=()=>{if(!this._pc){this._stopSettingsInterval();return}this._applyConsumerSettings(),this._settingsInterval=window.setTimeout(t,e)};this._settingsInterval=window.setTimeout(t,e)}_stopSettingsInterval(){this._settingsInterval&&(window.clearTimeout(this._settingsInterval),this._settingsInterval=null)}_collectStat(){return c(this,null,function*(){if(!this._pc)return Promise.reject();let e=yield Lt(this._pc,this._lastStat,this._ssrcMap);return this._lastStat=e,e})}_reportStats(e){this._triggerEvent(N.REMOTE_DATA_STATS,{inbound:{topology:Pe.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="inbound-rtp")},outbound:{topology:Pe.SERVER,transport:e.transport,rtps:e.rtps.filter(t=>t.type==="outbound-rtp")}})}_detectStaleTracks(e){let t=e.rtps.find(s=>s.type==="inbound-rtp"&&s.kind==="audio"&&this._ssrcMap[s.ssrc]==="mix");if(!t)return;let i=ke.AUDIO_MIX,r=this._statBytes[i],a=!1;if(r){let s=t.bytesReceived-r.bytesReceived;s>=0&&s<=5&&(a=!0),r.stalled!==a&&this._triggerEvent(N.REMOTE_ALL_STALL,a)}this._statBytes[i]={bytesReceived:t.bytesReceived,stalled:a}}_allocateConsumer(){if(!this._signaling.ready)return;let e={estimatedPerformanceIndex:Bt.getEstimatedPerformanceIndex(),audioMix:!0,consumerUpdate:!0,producerNotificationDataChannelVersion:p.producerNotificationDataChannel?6:0,producerCommandDataChannelVersion:p.producerCommandDataChannel?2:0,consumerScreenDataChannelVersion:p.consumerScreenDataChannel?1:0,producerScreenDataChannelVersion:p.producerScreenDataChannel?1:0,onDemandTracks:!0,unifiedPlan:De._isUnifiedPlanSupported(),singleSession:!0,videoTracksCount:p.videoTracksCount};this._signaling.allocateConsumer(null,e)}_acceptProducer(e){return c(this,null,function*(){if(this._producerOfferIsProcessing){this._producerNextOffer=e,o.debug("[single] wait until other remote offer is processed");return}this._producerOfferIsProcessing=!0;let t=new RTCSessionDescription({type:"offer",sdp:e});if(o.debug("[single] set remote offer",{offer:t}),!this._pc)throw new Error("Interrupt allocation");this._pc.setRemoteDescription(t).catch(i=>{throw o.error("[single] unable to set remote offer",i),m.log(_.ERROR,"setRemoteDescription-single"),i}).then(()=>c(this,null,function*(){if(o.debug("[single] create local answer"),!this._pc)throw new Error("Interrupt allocation");return this._pc.createAnswer()})).catch(i=>{throw o.error("[single] unable to create answer",i),m.log(_.ERROR,"createAnswer-single"),i}).then(i=>(i.sdp=T.patchSDP(i.sdp,!1,y.isBrokenH264(),!1),i)).then(i=>c(this,null,function*(){if(o.debug("[single] set local answer",{answer:i}),!this._pc)throw new Error("Interrupt allocation");return yield this._pc.setLocalDescription(i),i})).catch(i=>{throw o.error("[single] unable to set local answer",i),m.log(_.ERROR,"setLocalDescription-single"),i}).then(i=>c(this,null,function*(){o.debug("[single] transmit local answer",{answer:i}),this._updateSSRCMap(t),yield this._signaling.acceptProducer(i,Object.keys(this._ssrcMap)),o.debug("[single] remote offer has been processed")})).catch(i=>{o.warn("[single] unable to send local answer",i),m.log(_.ERROR,"acceptProducer")}).then(()=>c(this,null,function*(){if(this._producerOfferIsProcessing=!1,this._producerNextOffer){o.debug("[single] there is other unprocessed remote offer, process it");let i=this._producerNextOffer;return this._producerNextOffer=null,this._acceptProducer(i)}})).catch(i=>this.close(i))})}_onSignalingNotification(e){return c(this,null,function*(){if(!!this._isOpen)switch(e.notification){case O.PRODUCER_UPDATED:yield this._onProducerUpdated(e);break;case O.REALLOC_CON:this._reconnect();break;case O.AUDIO_ACTIVITY:this._signalActiveParticipants(e.activeParticipants);break;case O.SPEAKER_CHANGED:this._signalSpeakerChanged(e.speaker);break;case O.STALLED_ACTIVITY:this._signalStalledParticipants(e.stalledParticipants);break;case O.NETWORK_STATUS:this._signalNetworkStatus(e.statuses);break}})}_onProducerUpdated(e){return c(this,null,function*(){this._producerSessionId&&this._producerSessionId!==e.sessionId&&this._reconnect(),p.breakVideoPayloadTypes&&(o.log("test mode enabled, video switched off"),this._signaling.requestTestMode("breakVideoPayloadTypes")),this._producerSessionId=e.sessionId,yield this._acceptProducer(e.description)})}_onAddTrack(e,t){o.debug("[single] remote track (added)",{track:t.track});let i=t.streams[0];i?(i.onremovetrack||(i.onremovetrack=a=>{this._triggerEvent(N.REMOTE_TRACK_REMOVED,i.id,i,a.track)}),i.getTracks().find(a=>a.id===t.track.id)||i.addTrack(t.track),this._rtpReceiversByStreamId[i.id]=t.receiver,this._triggerEvent(N.REMOTE_TRACK_ADDED,i.id,i,t.track)):o.error("[single] unable to get media stream from track event")}static _onSignalingStateChange(e,t){o.debug("[single] signaling state changed",{state:e.signalingState},t)}_onConnectionStateChange(e,t){switch(o.debug("[single] connection state changed",{state:e.connectionState},t),m.log(_.ICE_CONNECTION_STATE,e.connectionState),e.connectionState){case"failed":this._reconnectionPrevented?this.close(new Error("Ice connection failed")):this._reconnect();break;case"connecting":let i=this.getState();i===F.IDLE||i===F.OPENED?this._setState(F.CONNECTING):e.iceConnectionState==="checking"&&this._setState(F.RECONNECTING);break;case"disconnected":this._reconnectionPrevented?this.close(new Error("Ice connection disconnected")):this._setState(F.RECONNECTING);break;case"connected":this._setState(F.CONNECTED),T.getPeerConnectionHostInfo(e).then(r=>{r&&m.log(_.ICE_CONNECTION_TYPE,r.type)});break}}_onReplacedTrack(e,t){this._pc&&(p.consumerScreenDataChannel&&t&&(e=t),this._pc.getSenders().forEach(i=>{i.track&&i.track.kind===e.kind&&!this._disabledSenders.has(i)&&(i.track.enabled=e.enabled,i.replaceTrack(e).catch(r=>{o.error("ServerTransport: Unable to replace track",r),m.log(_.ERROR,"replaceTrack-single")}))})),this._applyConsumerSettings()}static _isUnifiedPlanSupported(){let e=y.baseChromeVersion();return e?p.isUnifiedPlanSupported("Chrome",e):p.isUnifiedPlanSupported(y.browserName(),y.browserVersion())}getStreamWaitingTimeMs(e,t){if(!this._pc)return m.log(_.PAT_WAITING_TIME_ERROR,"noConnection"),o.error("Cannot get stream waiting time, peer connection is not initialized"),0;let i=this._rtpReceiversByStreamId[e];if(!i)return m.log(_.PAT_WAITING_TIME_ERROR,"noReceiver"),o.error(`Cannot get stream waiting time, cannot find RTP receiver by stream ID: ${e}`),0;let r=i.getSynchronizationSources();if(!r||!r.length)return o.log(`Cannot get stream waiting time, ${e} receiver has no synchronization sources`),0;let s=r[0].rtpTimestamp;if(!Number.isInteger(s))return m.log(_.PAT_WAITING_TIME_ERROR,"timestampNotInteger"),o.error(`Cannot get stream waiting time, ${e} receiver's RTP timestamp is not an integer: ${s}`),0;let d=t-s&Ds,l=Math.ceil(d/As);return Math.min(100,Math.max(0,l))}};var N=(k=>(k.REMOTE_TRACK_ADDED="REMOTE_TRACK_ADDED",k.REMOTE_TRACK_REMOVED="REMOTE_TRACK_REMOVED",k.REMOTE_STREAM_SECOND="REMOTE_STREAM_SECOND",k.REMOTE_ALL_STALL="REMOTE_ALL_STALL",k.REMOTE_DATA_STATS="REMOTE_DATA_STATS",k.STATE_CHANGED="STATE_CHANGED",k.LOCAL_STATE_CHANGED="LOCAL_STATE_CHANGED",k.SIGNALLED_ACTIVE_PARTICIPANTS="SIGNALLED_ACTIVE_PARTICIPANTS",k.ACTIVE_PARTICIPANTS_NO_SIGNAL="ACTIVE_PARTICIPANTS_NO_SIGNAL",k.SIGNALLED_SPEAKER_CHANGED="SIGNALLED_SPEAKER_CHANGED",k.SIGNALLED_STALLED_PARTICIPANTS="SIGNALLED_STALLED_PARTICIPANTS",k.TOPOLOGY_CHANGED="TOPOLOGY_CHANGED",k.NETWORK_STATUS="NETWORK_STATUS",k.PEER_CONNECTION_CLOSED="PEER_CONNECTION_CLOSED",k))(N||{}),F=(d=>(d.IDLE="IDLE",d.OPENED="OPENED",d.CONNECTING="CONNECTING",d.RECONNECTING="RECONNECTING",d.CONNECTED="CONNECTED",d.CLOSED="CLOSED",d.FAILED="FAILED",d))(F||{}),Pe=(t=>(t.DIRECT="DIRECT",t.SERVER="SERVER",t))(Pe||{}),cr=class extends Q{constructor(e,t,i,r){super();this._allocated=[];this._opened=[];this._directTransport=null;this._serverTransport=null;this._dtListeners=[];this._stListeners=[];this._states={};this._localState="IDLE";this._signaling=t,this._mediaSource=i,this._topology=e,this._serverSettings=r,this.subscribe(this._signaling,fe.NOTIFICATION,this._onSignalingNotification.bind(this)),e==="SERVER"&&(this._serverTransport=this._createServerTransport())}updateSettings(e){this._serverSettings=e,this._directTransport&&this._directTransport.updateSettings(e),this._serverTransport&&this._serverTransport.updateSettings(e)}updateStatisticsInterval(){this._directTransport&&this._directTransport.updateStatisticsInterval(),this._serverTransport&&this._serverTransport.updateStatisticsInterval()}allocate(e,t=!1){if(this._allocated.indexOf(e)!==-1){o.warn(`The participant [${e}] has already had allocated transport`);return}this._allocated.push(e),this._topology==="DIRECT"&&!this._directTransport&&(this._directTransport=this._createDirectTransport(e,t)),this._topology==="SERVER"&&!this._serverTransport&&(this._serverTransport=this._createServerTransport())}open(e,t=null){let i=!1;for(let r of e){if(this._opened.indexOf(r)!==-1){o.warn(`The participant [${r}] has already had opened transport`);continue}if(this._allocated.indexOf(r)===-1){o.warn(`The participant [${r}] has no allocated transport`);continue}this._opened.push(r),i=!0}!i||(this._topology==="DIRECT"&&this._directTransport&&this._directTransport.open(t),this._topology==="SERVER"&&this._serverTransport&&(this._serverTransport.open(),this._setStates(e,this._serverTransport.getState()),this._setLocalState(this._serverTransport.getState())),o.debug("The transport has been opened",e))}close(e){var r;let t=this._allocated.indexOf(e),i=this._opened.indexOf(e);t<0&&o.warn(`The participant [${e}] transport has already deallocated`),this._topology==="DIRECT"&&this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._topology==="SERVER"&&((r=this._serverTransport)==null||r.removeParticipant(e),this._setState(e,"CLOSED")),i>=0&&this._opened.splice(i,1),t>=0&&this._allocated.splice(t,1)}destroy(){this.unsubscribe(),this._dtListeners&&this._dtListeners.forEach(e=>{e.dispose()}),this._stListeners&&this._stListeners.forEach(e=>{e.dispose()}),this._directTransport&&(this._directTransport.close(),this._directTransport=null),this._serverTransport&&(this._serverTransport.close(),this._serverTransport=null),this._allocated=[],this._opened=[]}getTopology(){return this._topology}isAllocated(e){return this._allocated.indexOf(e)>=0}allocated(){return this._allocated.slice()}opened(){return this._opened.slice()}_setStates(e,t){let i=e.filter(r=>this._states[r]!==t?(this._states[r]=t,!0):!1);i.length&&this._triggerEvent("STATE_CHANGED",i,t)}_setState(e,t){this._states[e]!==t&&(this._states[e]=t,this._triggerEvent("STATE_CHANGED",[e],t))}_setLocalState(e){this._localState!==e&&(this._localState=e,this._triggerEvent("LOCAL_STATE_CHANGED",e))}_onSignalingNotification(e){if(e.notification===O.TOPOLOGY_CHANGED)return this._onTopologyChanged(e);if(e.notification===O.RECORD_STARTED)return this._onRecordStarted(e)}_onTopologyChanged(e){var t;if(e.topology!==this._topology){if(o.log(`Topology changed ${this._topology} -> ${e.topology}`),m.log(_.TOPOLOGY_CHANGE_REQUESTED,e.topology),this._topology=e.topology,this._topology==="SERVER"&&(this._serverTransport?this._serverTransport.allowRestart():(this._serverTransport=this._createServerTransport(),this._opened.length>0&&((t=this._directTransport)==null||t.preventRestart(),this._serverTransport.open()))),this._topology==="DIRECT"){let i=e.offerTo||[],r=e.offerToTypes||[],a=i.length&&r.length?T.composeId(i[0],r[0]):null;if(this._serverTransport&&this._serverTransport.preventRestart(),!this._allocated||this._allocated.length===0){o.error("Topology changed to DIRECT, but the list of allocated participants is empty");return}this._allocated.length>1&&o.warn("Topology changed to DIRECT, but the allocated participants count more then one");let s=this._allocated[0];if(this._directTransport)this._directTransport.allowRestart();else{let d=a===s;this._directTransport=this._createDirectTransport(s,d)}this._opened.indexOf(s)>=0&&this._directTransport.open()}this._triggerEvent("TOPOLOGY_CHANGED",this._topology)}}_onRecordStarted(e){this._serverTransport&&this._serverTransport.open()}_createDirectTransport(e,t=!1){let i=new st(e,t,this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!0),this._dtListeners&&this._dtListeners.length>0&&o.warn(`The list of direct listeners for the participant [${e}] is not empty`),this._dtListeners=[],this._dtListeners.push(i.addEventListener("REMOTE_TRACK_ADDED",this._onDirectRemoteTrackAdded.bind(this,e)),i.addEventListener("REMOTE_TRACK_REMOVED",this._onDirectRemoteTrackRemoved.bind(this,e)),i.addEventListener("REMOTE_DATA_STATS",this._onDirectRemoteDataStats.bind(this)),i.addEventListener("STATE_CHANGED",this._onDirectTransportChanged.bind(this,e)),i.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),i.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"DIRECT"))),i}_createServerTransport(){let e=new De(this._signaling,this._mediaSource,this._serverSettings);return this._setLocalNoiseSuppression(!1),this._stListeners&&this._stListeners.length>0&&o.warn("The list of server transport listeners is not empty"),this._stListeners=[],this._stListeners.push(e.addEventListener("REMOTE_TRACK_ADDED",this._onServerRemoteTrackAdded.bind(this)),e.addEventListener("REMOTE_TRACK_REMOVED",this._onServerRemoteTrackRemoved.bind(this)),e.addEventListener("REMOTE_ALL_STALL",this._onServerRemoteAllStall.bind(this)),e.addEventListener("REMOTE_DATA_STATS",this._onServerRemoteDataStats.bind(this)),e.addEventListener("STATE_CHANGED",this._onServerTransportChanged.bind(this)),e.addEventListener("ACTIVE_PARTICIPANTS_NO_SIGNAL",this._onTransportActiveParticipantsNoSignal.bind(this)),e.addEventListener("SIGNALLED_ACTIVE_PARTICIPANTS",this._onTransportActiveParticipants.bind(this)),e.addEventListener("SIGNALLED_SPEAKER_CHANGED",this._onTransportSpeakerChanged.bind(this)),e.addEventListener("SIGNALLED_STALLED_PARTICIPANTS",this._onTransportStalledParticipants.bind(this)),e.addEventListener("NETWORK_STATUS",this._onTransportNetworkStatus.bind(this)),e.addEventListener("REMOTE_STREAM_SECOND",this._onRemoteStreamSecond.bind(this)),e.addEventListener("PEER_CONNECTION_CLOSED",this._onPeerConnectionClosed.bind(this,"SERVER"))),e}_releaseDirectTransport(e){this._directTransport&&(e&&this._directTransport.close(),this._directTransport=null),this._dtListeners&&(this._dtListeners.forEach(t=>{t.dispose()}),this._dtListeners=[])}_releaseServerTransport(e){this._serverTransport&&(e&&this._serverTransport.close(),this._serverTransport=null),this._stListeners&&(this._stListeners.forEach(t=>{t.dispose()}),this._stListeners=[])}_setLocalNoiseSuppression(e){var t;p.noiseSuppression!==e&&(p.noiseSuppression=e,(t=this._mediaSource)==null||t.updateNoiseSuppression())}_onDirectTransportChanged(e,t){if(t==="CONNECTED"&&this._topology==="DIRECT"&&this._releaseServerTransport(!0),(t==="CLOSED"||t==="FAILED")&&(this._releaseDirectTransport(!1),this._topology==="DIRECT")){let i=this._opened.indexOf(e);i>=0&&this._opened.splice(i,1);let r=this._allocated.indexOf(e);r>=0&&this._allocated.splice(r,1)}this._topology==="DIRECT"&&(this._setState(e,t),this._setLocalState(t))}_onServerTransportChanged(e){let t=this._opened.slice();e==="CONNECTED"&&this._topology==="SERVER"&&this._releaseDirectTransport(!0),(e==="CLOSED"||e==="FAILED")&&(this._releaseServerTransport(!1),this._topology==="SERVER"&&(this._allocated=[],this._opened=[])),this._topology==="SERVER"&&(this._setStates(t,e),this._setLocalState(e))}_onTransportActiveParticipantsNoSignal(){this._triggerEvent("ACTIVE_PARTICIPANTS_NO_SIGNAL")}_onTransportActiveParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_ACTIVE_PARTICIPANTS",e)}_onTransportStalledParticipants(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_STALLED_PARTICIPANTS",e)}_onTransportSpeakerChanged(e){this._topology==="SERVER"&&this._triggerEvent("SIGNALLED_SPEAKER_CHANGED",e)}_onTransportNetworkStatus(e){this._triggerEvent("NETWORK_STATUS",e)}_onRemoteStreamSecond(e,t){this._triggerEvent("REMOTE_STREAM_SECOND",e,t)}_onPeerConnectionClosed(e){this._triggerEvent("PEER_CONNECTION_CLOSED",e)}_onServerRemoteAllStall(e){this._topology==="SERVER"&&this._triggerEvent("REMOTE_ALL_STALL",e)}_onServerRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onDirectRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onDirectRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}_onDirectRemoteDataStats(e){this._triggerEvent("REMOTE_DATA_STATS",e)}_onServerRemoteTrackAdded(e,t,i){this._triggerEvent("REMOTE_TRACK_ADDED",e,t,i)}_onServerRemoteTrackRemoved(e,t,i){this._triggerEvent("REMOTE_TRACK_REMOVED",e,t,i)}getStreamWaitingTimeMs(e,t){return this._topology!=="SERVER"?(m.log(_.PAT_WAITING_TIME_ERROR,"wrongTopology"),o.error(`Cannot get stream waiting time, incorrect topology: ${this._topology}`),0):this._serverTransport?this._serverTransport.getStreamWaitingTimeMs(e,t):(m.log(_.PAT_WAITING_TIME_ERROR,"noTransport"),o.error("Cannot get stream waiting time, server transport is not initialized"),0)}replayShare(e,t){var i;(i=this._serverTransport)==null||i.replayShare(e,t)}};var ct=(e=>(e.VOLUMES_DETECTED="VOLUMES_DETECTED",e))(ct||{}),dr=class extends Q{constructor(e){super();this._detector=null;this._interval=null;this.subscribe(e,N.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(e,N.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(e,N.SIGNALLED_ACTIVE_PARTICIPANTS,this._onSignalledActiveParticipants.bind(this)),this.subscribe(e,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onActiveParticipantsNoSignal.bind(this))}destroy(){var e;this._interval&&(window.clearTimeout(this._interval),this._interval=null),this.unsubscribe(),(e=this._detector)==null||e.destroy(),this._detector=null}_onRemoteTrackAdded(e,t,i){var r;if(i.kind===me.audio&&((r=this._detector)==null||r.destroy(),this._detector=new Nt(e,t),!this._interval)){let a=()=>{this._collectVolumes(),this._interval=window.setTimeout(a,p.voiceParams.interval)};this._interval=window.setTimeout(a,p.voiceParams.interval)}}_onRemoteTrackRemoved(e,t,i){i.kind===me.audio&&(!this._detector||this._detector.stream!==t||(this._detector.destroy(),this._detector=null))}_collectVolumes(){if(!this._detector)return;let e={},t=this._detector.trackId,i=this._detector.getLevel();if(t===ke.AUDIO_MIX){if(this._activeParticipants)for(let r of this._activeParticipants)e[r]=i}else e[t]=i;this._triggerEvent("VOLUMES_DETECTED",e)}_onSignalledActiveParticipants(e){this._activeParticipants=e}_onActiveParticipantsNoSignal(){this._activeParticipants=null}};var pr=(e=>(e.SPEAKER_CHANGED="SPEAKER_CHANGED",e))(pr||{}),lr=class extends Q{constructor(e,t){super();this._speakerId=null;this._serverAudioActivityAvailable=!1;this.subscribe(e,ct.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this.subscribe(t,N.SIGNALLED_SPEAKER_CHANGED,this._onServerSpeakerChanged.bind(this)),this.subscribe(t,N.SIGNALLED_ACTIVE_PARTICIPANTS,this._onReceivedServerAudioActivity.bind(this)),this.subscribe(t,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onStoppedReceivingServerAudioActivity.bind(this))}destroy(){this.unsubscribe()}_onVolumesDetected(e){if(this._serverAudioActivityAvailable)return;let t=0,i=null;if(Object.keys(e).forEach(r=>{let a=e[r].smoothed;a>t&&a>p.voiceParams.threshold&&(t=a,i=r)}),i&&i!==this._speakerId){let r=this._speakerId&&e.hasOwnProperty(this._speakerId)?e[this._speakerId].smoothed:0;t>r*p.voiceParams.speakerLevelMultiplier&&(this._speakerId=i,this._triggerEvent("SPEAKER_CHANGED",i))}}_onServerSpeakerChanged(e){this._serverAudioActivityAvailable&&this._triggerEvent("SPEAKER_CHANGED",e)}_onReceivedServerAudioActivity(){this._serverAudioActivityAvailable=!0}_onStoppedReceivingServerAudioActivity(){this._serverAudioActivityAvailable=!1}};var ci=class extends Q{constructor(e,t,i){super();this._states={};this._volumes={};this._participants={};this._connectionTimeout=0;this._volumeTimeout=0;this._transport=e,this._participants=i,this.subscribe(e,N.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(t,ct.VOLUMES_DETECTED,this._onVolumesDetected.bind(this))}destroy(){this.unsubscribe(),this._connectionTimeout&&window.clearTimeout(this._connectionTimeout),this._volumeTimeout&&window.clearTimeout(this._volumeTimeout)}onChangeRemoteMediaSettings(e,t){t.isAudioEnabled||(this._volumes[e]=1),t.isAudioEnabled&&(this._volumes[e]=0)}_onTransportStateChanged(e,t){e.forEach(i=>this._states[i]=t),t===F.OPENED&&(this._connectionTimeout||(this._connectionTimeout=window.setTimeout(this._onConnectionTimeout.bind(this),p.specListenerParams.connectionTimeout)),this._volumeTimeout||(this._volumeTimeout=window.setTimeout(this._onVolumeTimeout.bind(this),p.specListenerParams.volumeTimeout))),t===F.FAILED&&this._connectionTimeout&&(o.warn("Transport failed, send callSpecError"),m.log(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`))}_onVolumesDetected(e){Object.keys(e).forEach(t=>{this._volumes[t]=Math.max(e[t].real,this._volumes[t]||0)})}_onConnectionTimeout(){let e=i=>i!==F.CONNECTED;(()=>Object.values(this._states).filter(e).length>0)()&&(o.warn("There is not connected transport, send callSpecError"),m.log(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_CONNECTION_TIMEOUT`)),this._connectionTimeout=0}_onVolumeTimeout(){let e=[];Object.keys(this._volumes).forEach(t=>{if(this._volumes[t]>0)return;let i="UNKNOWN",r=this._participants[t];r&&r.platform&&(i=r.platform),e.indexOf(i)<0&&(e.push(i),m.log(_.CALL_SPEC_ERROR,`${this._transport.getTopology()}_VOLUME_TIMEOUT_${i}`))}),e.length&&o.warn("There is silent participant, send callSpecError"),this._volumeTimeout=0}};var ws=1e3,Os=1e4;var H=class extends Q{constructor(e,t,i){super();this._mediaSource=null;this._conversation=null;this._state="IDLE";this._participantState=j.CALLED;this._participants={};this._transport=null;this._debugInfo=null;this._volumesDetector=null;this._speakerDetector=null;this._localVolumeDetector=null;this._specListener=null;this._activeSpeakerId=null;this._lastSignalledActiveSpeakerId=null;this._serverSettings={camera:null,screenSharing:null};this._lastStalled={};this._remoteAllStalled=!1;this._audioFix=null;this._streamByStreamId=new Map;this._streamIdByStreamDescription=new Map;this._streamWaitTimerByStreamDescription=new Map;this._sequenceNumberByStreamDescription=new Map;this._cooldownTimestampByStreamDescription=new Map;this._cooldownQueueCleanupTimer=null;m.create(e,i),this._api=e,this._signaling=t,this._onUnload=()=>{this._conversation&&this._api&&this._api.hangupConversation(this._conversation.id),m.destroy()},window.addEventListener("unload",this._onUnload),this._audioOutput=new ri,p.videoTracksCount>0&&(this._cooldownQueueCleanupTimer=window.setInterval(this._cleanupCooldownQueue.bind(this),ws))}static current(){return H._current}static hangupAfterInit(){H._activationMutex&&!H._current&&(H._delayedHangup=!0)}static id(){var e,t;return((t=(e=H._current)==null?void 0:e._conversation)==null?void 0:t.id)||null}onStart(e,t,i,r="",a=!1,s=!1){return c(this,null,function*(){if(H._activationMutex)throw m.log(_.ERROR,"startCall"),o.warn("Conversation: there is already running activation"),new x(P.FAILED);H._activationMutex=!0;try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(i);let d=this._mediaSource.getMediaSettings();t===Le.CHAT||e.length>1?this._logWithMediaSettings(_.OUTGOING_MULTIPARTY_CALL,d):this._logWithMediaSettings(_.OUTGOING_CALL,d);let l=yield this._startConversation(e,t,We.OUTGOING,i,r,a,s);if(!this._conversation)throw new x(P.UNKNOWN_ERROR);if(this._participantState=j.ACCEPTED,this._signaling.changeMediaSettings(d),yield this._registerParticipants(l.conversation.participants),this._processConnectionData(l),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),H._delayedHangup)throw new x(P.CANCELED);o.debug("Outgoing call",{opponentIds:e,opponentType:t,mediaOptions:i});let u=Object.values(this._participants),g;return p.batchParticipantsOnStart&&(g=T.mapSharedParticipants(u)),E.onLocalStream(this._mediaSource.getStream(),this._mediaSource.getMediaSettings()),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,g),E.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeFeatureSet(),this._changeNeedRate(),H._current=this,this._conversation.concurrent?yield this._acceptConcurrent():p.batchParticipantsOnStart||this._setParticipantsStatus(u,J.WAITING),this._conversation}catch(d){throw this._close(d,"Unable to start conversation"),d}finally{H._activationMutex=!1}})}onJoin(e){return c(this,null,function*(){if(H._activationMutex)throw m.log(_.ERROR,"joinCall"),o.warn("Conversation: there is already running activation"),new x(P.FAILED);H._activationMutex=!0,this._state="PROCESSING";try{this._mediaSource=this._createMediaSource(),yield this._mediaSource.request(e.mediaOptions);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.JOIN_CONVERSATION,t);let i=yield this._joinConversation(e);if(!this._conversation)throw new x(P.UNKNOWN_ERROR);return E.onLocalStream(this._mediaSource.getStream(),t),this._conversation.waitingHall?(o.log("In waiting hall"),H._current=this,H._activationMutex=!1,this._signaling.readyToSend(),E.onLocalStatus(J.WAITING_HALL),this._conversation):this._onJoinPart2(i)}catch(t){throw H._activationMutex=!1,this._close(t,"Unable to join conversation"),t}})}_onJoinPart2(e){return c(this,null,function*(){o.debug("Join conversation part 2"),H._activationMutex=!0;try{if(this._participantState=j.ACCEPTED,!this._conversation||!this._mediaSource)throw new x(P.UNKNOWN_ERROR);if(this._signaling.changeMediaSettings(this._mediaSource.getMediaSettings()),yield this._registerParticipants(e.conversation.participants),this._processConnectionData(e),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),H._delayedHangup)throw new x(P.CANCELED);let t=Object.values(this._participants),i;return p.batchParticipantsOnStart&&(i=T.mapSharedParticipants(t)),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,i),E.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate(),this._state="ACTIVE",this._changeFeatureSet(),H._current=this,p.batchParticipantsOnStart||this._setParticipantsStatus(t,J.WAITING),this._openTransport(t,!1),this._conversation}catch(t){throw this._close(t,"Unable to join conversation"),t}finally{H._activationMutex=!1}})}onPush(r){return c(this,arguments,function*(e,t=X.USER,i){if(H._activationMutex)throw o.warn("Conversation: there is already running activation"),new x(P.REJECTED);H._activationMutex=!0;try{let a=yield this._prepareConversation(e,t,i);if(this._mediaSource=this._createMediaSource(),!this._conversation)throw new x(P.UNKNOWN_ERROR);if(!a.conversation.participants.find(d=>{var l;return d.state===j.CALLED&&d.id===((l=this._conversation)==null?void 0:l.userId)}))throw o.log("Push rejected (there is an active call)"),m.log(_.PUSH,"rejected"),new x(P.REJECTED);if(yield this._registerParticipants(a.conversation.participants),this._processConnectionData(a),this._allocateTransport(),this._createSpeakerDetector(),this._createSpecListener(),this._signaling.readyToSend(),m.log(_.PUSH,"accepted"),H._current=this,H._delayedHangup)throw new x(P.CANCELED);H._activationMutex=!1}catch(a){throw H._activationMutex=!1,this._close(a,"Unable to handle inbound call push"),a}})}_isInWaitingHall(e){if(!e.conversation||(e.conversation.options||[]).indexOf(Gt.WAITING_HALL)<0)return!1;let t=(e.conversation.participants||[]).find(i=>T.comparePeerId(i.peerId,e.peerId));return t&&t.restricted||!1}_acceptConcurrent(){return c(this,null,function*(){if(!this._mediaSource||!this._conversation)throw new x(P.UNKNOWN_ERROR);this._state="PROCESSING";let e=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.ACCEPT_CONCURRENT,e),o.debug("Concurrent call",{conversationId:this._conversation.id});try{yield this._signaling.acceptCall(this._mediaSource.getMediaSettings()),E.onCallAccepted(),this._state="ACTIVE",this._participantState=j.ACCEPTED,this._changeFeatureSet(),this._openTransport(Object.values(this._participants),!0)}catch(t){this._close(t,"Unable to accept concurrent call")}})}accept(e){return c(this,null,function*(){if(this._state!=="IDLE")throw m.log(_.ERROR,"acceptIncoming"),o.error("Unable to accept a call - invalid state"),new Error("Unable to accept a call - invalid state");if(!this._mediaSource||!this._conversation)throw new x(P.UNKNOWN_ERROR);this._state="PROCESSING",o.debug("Accept incoming call",e);try{yield this._mediaSource.request(e);let t=this._mediaSource.getMediaSettings();this._logWithMediaSettings(_.ACCEPT_INCOMING,t),this._signaling.changeMediaSettings(t),yield this._signaling.acceptCall(t),this._participantState=j.ACCEPTED;let i=Object.values(this._participants),r;p.batchParticipantsOnStart&&(r=T.mapSharedParticipants(i)),E.onCallAccepted(),E.onLocalStream(this._mediaSource.getStream(),t),E.onConversation(this._conversation.externalId,this._conversation.mediaModifiers,this._conversation.muteStates,r),E.onLocalStatus(J.WAITING),this._toggleJoinAvailability(),this._changeNeedRate();let a=Object.values(this._conversation.muteStates);return(a.includes(je.MUTE)||a.includes(je.MUTE_PERMANENT))&&(yield this._processMuteState(Object.keys(this._conversation.muteStates))),this._state="ACTIVE",this._changeFeatureSet(),p.batchParticipantsOnStart||this._setParticipantsStatus(i,J.WAITING),this._openTransport(i,!0),this._conversation}catch(t){throw this._close(t,"Unable to accept call"),t}})}decline(){return c(this,null,function*(){var e;if(this._state!=="IDLE")throw m.log(_.ERROR,"declineIncoming"),o.error("Unable to decline a call - invalid state"),new Error("Unable to decline a call - invalid state");this._state="PROCESSING",o.debug("Decline incoming call"),this._logWithMediaSettings(_.DECLINE_INCOMING,(e=this._mediaSource)==null?void 0:e.getMediaSettings()),this._participantState=j.HUNGUP,this._signaling.ready&&(yield this._signaling.hangup(P.REJECTED)),this._close(new x(P.REJECTED))})}hangup(){return c(this,null,function*(){o.debug("Hangup");let e=this._state==="ACTIVE"?P.HUNGUP:P.CANCELED;m.log(_.HANGUP,e),this._signaling.ready?(yield this._signaling.hangup(e),this._close(new x(e))):E.onHangup(new x(P.HUNGUP),this._conversation&&this._conversation.id)})}addParticipant(e,t){return c(this,null,function*(){if(!this._signaling.ready){this._close(new x(P.UNKNOWN_ERROR),"Unable to add participant");return}let i=yield this._signaling.addParticipant(e,t),r=null;i.type==="error"&&(i.error==="call-unfeasible"?r=i.status:r=P.UNKNOWN_ERROR);let a=i.participant;yield this._onAddParticipant(e,a,r)})}removeParticipant(e,t=!1){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.removeParticipant(e,t),this._onRemoveParticipant(e))})}setVolume(e){this._audioOutput.volume=e}updateStatisticsInterval(){this._transport&&this._transport.updateStatisticsInterval()}_openTransport(e,t){if(!this._transport)return;let i=[];for(let r of e)(r.state===j.CALLED||r.state===j.ACCEPTED)&&this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,t),this._transport&&r.state===j.ACCEPTED&&i.push(r.id);i.length&&this._transport.open(i)}_close(e,t){t&&o.error(t,e),o.debug("Close conversation",e),e.error?this._signaling.ready&&this._signaling.hangup(P.FAILED):m.log(_.ERROR,e.hangup),H._activationMutex=!1;let i=this._conversation&&this._conversation.id;if([P.CANCELED,P.NOT_FRIENDS,P.CALLEE_IS_OFFLINE,P.CALLER_IS_BLOCKED].indexOf(e.hangup)!==-1||e.hangup===P.REJECTED&&!e.remote){E.onHangup(e,i),this.destroy();return}if(e.hangup===P.HUNGUP&&(!e.remote||this._participantState===j.CALLED)){E.onHangup(e,i),this.destroy();return}if(e.hangup===P.MISSED&&!e.remote){E.onHangup(e,i),this.destroy();return}if(e.hangup===P.SOCKET_CLOSED&&H._current&&!this._conversation){this._cleanupSignaling(),this._cleanupMediaSource();return}if(e.hangup===P.BUSY&&!e.remote){this._cleanupSignaling(),this._cleanupMediaSource();return}this._state="CLOSE",this._participantState=j.HUNGUP,this._changeFeatureSet(),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),m.destroy(),this._conversation=null,H._current=null,H._delayedHangup=!1,E.onHangup(e||new x(P.UNKNOWN_ERROR),i),this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}destroy(){let e=this._conversation&&this._conversation.id;o.debug("Destroy conversation",{conversationId:e}),this._cleanupMediaSource(),this._cleanupParticipants(),this._cleanupParticipantAgnosticStreams(),this._cleanupTransport(),this._cleanupSpeakerDetector(),this._cleanupSpecListener(),this._cleanupSignaling(),this._api.cleanup(),this._cleanupListeners(),m.destroy(),this._conversation=null,H._current=null,H._delayedHangup=!1,this._cooldownQueueCleanupTimer!==null&&(window.clearInterval(this._cooldownQueueCleanupTimer),this._cooldownQueueCleanupTimer=null)}_getConversationParams(e){return c(this,null,function*(){let t=yield this._api.getConversationParams(e);o.debug("Api.getConversationParams",t);let i=[],{turn_server:r,stun_server:a}=t;if(a&&i.push(a),r){let s=r.urls.filter((d,l,u)=>u.indexOf(d)===l);s.forEach(d=>s.push(`${d}?transport=tcp`)),i.push({urls:s,username:r.username,credential:r.credential})}p.iceServers=i,p.wssBase=t.endpoint,p.wssToken=t.token,t.client_type&&(p.clientType=t.client_type)})}_startConversation(e,t,i,r,a="",s=!1,d=!1){return c(this,null,function*(){let l=T.uuid();o.debug("Conversation: start",{conversationId:l,opponentIds:e,opponentType:t,direction:i});let u=r.includes(le.VIDEO),g=yield this._api.startConversation(l,e,t,u,a,s,d);o.debug("Api.startConversation",g),yield this._getConversationParams(g.id);let f=yield this._connectSignaling(Ue.START,g);return yield this._setConversation(g,f,i),f})}_joinConversation(e){return c(this,null,function*(){let{conversationId:t,mediaOptions:i,chatId:r,joinLink:a}=e;o.debug("Conversation: join",{conversationId:t,joinLink:a});let s=i.includes(le.VIDEO),d;if(t)d=yield this._api.joinConversation(t,s,r);else if(a)d=yield this._api.joinConversationByLink(a,s);else throw new x(P.UNKNOWN_ERROR);o.debug("Api.joinConversation",d),yield this._getConversationParams(d.id);let l=yield this._connectSignaling(Ue.JOIN,d);return yield this._setConversation(d,l,We.JOINING),l})}_prepareConversation(r){return c(this,arguments,function*(e,t=X.USER,i){o.debug("Conversation: push",{conversationId:e,type:t,peerId:i}),yield this._getConversationParams(e);let a=this._api.getUserId();if(!a)throw new x(P.UNKNOWN_ERROR);let s={id:e,peerId:i,endpoint:`${p.wssBase}?userId=${a}&entityType=${t}&conversationId=${e}&token=${p.wssToken}`,is_concurrent:!1,p2p_forbidden:!1},d=yield this._connectSignaling(Ue.ACCEPT,s);return H._current&&(H._current._participantState===j.ACCEPTED||H._current._participantState===j.CALLED)?(o.log("Push rejected (busy)"),m.log(_.PUSH,"busy"),this._signaling.ready&&this._signaling.hangup(P.BUSY),Promise.reject({hangup:P.BUSY})):(H._current&&(H._current.destroy(),H._current=null),yield this._setConversation(s,d,We.INCOMING,t),d)})}_createParticipant(e){return c(this,null,function*(){let t=Object.assign({id:null,externalId:null,mediaSettings:Ee(),participantState:{},state:j.CALLED,status:null,remoteStream:null,mediaSource:null,platform:null,clientType:null,roles:[],networkRating:1,lastRequestedLayouts:{},muteStates:{},unmuteOptions:[]},e);return e.externalId?this._api.cacheExternalId(t.id,e.externalId):t.externalId=yield this._getUserId(t.id),t})}_getUserId(e){return c(this,null,function*(){try{return yield this._api.userId(e)}catch(t){throw this._close(new x(P.NETWORK_ERROR),t),t}})}_setConversation(a,s,d){return c(this,arguments,function*(e,t,i,r=X.USER){let l=t.conversation.participants.map(W=>W.id);yield this._api.prepareUserIds(l);let u=this._api.getUserId();if(!u){let W=(t.conversation.participants||[]).find(K=>T.comparePeerId(K.peerId,t.peerId));if(!W)throw new x(P.UNKNOWN_ERROR);u=Number(W.id),W.idType&&(r=W.idType),this._api.setUserId(u)}let g=T.composeId(u,r),f=yield this._getUserId(g);this._conversation={userId:u,compositeUserId:g,externalId:f,acceptTime:t.conversation.acceptTime,features:t.conversation.features||[],id:t.conversation.id||e.id,participantsLimit:t.conversation.participantsLimit||30,topology:t.conversation.topology||Pe.DIRECT,direction:i,concurrent:t.isConcurrent||e.is_concurrent||!1,needRate:!1,chatId:t.conversation.multichatId,roles:[],recordInfo:null,joinLink:e.join_link,pinnedParticipantId:null,mediaModifiers:t.mediaModifiers,options:[],muteStates:{},unmuteOptions:[],networkRating:1,waitingHall:this._isInWaitingHall(t)},this._signaling.setConversationId(e.id),e.p2p_forbidden&&(p.forceRelayPolicy=e.p2p_forbidden),m.log(_.RELAY_POLICY,p.forceRelayPolicy?"1":"0"),this._changeFeatureSet(),this._logDevices()})}_updateConversation(e){if(!this._conversation)throw new x(P.UNKNOWN_ERROR);this._conversation.acceptTime=e.conversation.acceptTime,this._conversation.features=e.conversation.features||[],this._conversation.participantsLimit=e.conversation.participantsLimit||30,this._conversation.topology=e.conversation.topology||Pe.DIRECT,this._conversation.concurrent=e.isConcurrent||!1,this._conversation.chatId=e.conversation.multichatId,this._conversation.mediaModifiers=e.mediaModifiers,this._conversation.waitingHall=!1}_createMediaSource(){let e=new Ni;return this.subscribe(e,ye.SOURCE_CHANGED,this._onLocalMediaStreamChanged.bind(this)),this.subscribe(e,ye.SCREEN_STATUS,this._onScreenSharingStatus.bind(this)),this._audioFix=new xt(e),e}_connectSignaling(e,t){return c(this,null,function*(){return this._signaling.setEndpoint(t.endpoint),this.subscribe(this._signaling,fe.NOTIFICATION,this._onSignalingNotification.bind(this)),this.subscribe(this._signaling,fe.FAILED,this._onSignalingFailed.bind(this)),this.subscribe(this._signaling,fe.RECONNECT,this._onSignalingReconnect.bind(this)),this._signaling.connect(e,t)})}_registerParticipants(e){return c(this,null,function*(){if(!!this._conversation)for(let t of e){let i=T.composeParticipantId(t);if(i===this._conversation.compositeUserId){this._conversation.roles=t.roles||[],this._conversation.roles.length&&(o.debug(`Local roles changed: ${t.roles}`),E.onLocalRolesChanged(this._conversation.roles)),t.muteStates&&(yield this._onMuteParticipant({muteStates:t.muteStates,unmuteOptions:t.unmuteOptions,mediaOptions:Object.keys(t.muteStates)}));continue}if(t.state===j.HUNGUP||t.state===j.REJECTED){this._participants[t.id]&&this._removeParticipant(this._participants[t.id],P.HUNGUP);continue}this._participants[i]=yield this._createParticipant({id:i,externalId:t.externalId&&re.fromSignaling(t.externalId),mediaSettings:Ee(t.mediaSettings),participantState:T.mapParticipantState(t),state:t.state,roles:t.roles||[],status:p.batchParticipantsOnStart?J.WAITING:null,muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),t.roles&&t.roles.length&&(o.debug(`Roles for participant [${i}] changed: ${t.roles}`),E.onRolesChanged(this._participants[i].externalId,t.roles))}})}_processConnectionData(e){T.isEmptyObject(this._conversation.muteStates)&&e.conversation.muteStates&&this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:Object.keys(e.conversation.muteStates),muteAll:!0}),e.conversation.pinnedParticipantId&&this._onPinParticipant(e.conversation.pinnedParticipantId),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options),e.chatRoom&&e.chatRoom.totalCount&&this._onChatRoomUpdated(Ht.ATTENDEE,e.chatRoom.totalCount,e.chatRoom.firstParticipants)}_allocateTransport(){if(!this._conversation||!this._mediaSource)return;this._transport=new cr(this._conversation.topology,this._signaling,this._mediaSource,this._serverSettings),this._debugInfo=new ni,this.subscribe(this._transport,N.STATE_CHANGED,this._onTransportStateChanged.bind(this)),this.subscribe(this._transport,N.LOCAL_STATE_CHANGED,this._onTransportLocalStateChanged.bind(this)),this.subscribe(this._transport,N.REMOTE_TRACK_ADDED,this._onRemoteTrackAdded.bind(this)),this.subscribe(this._transport,N.REMOTE_TRACK_REMOVED,this._onRemoteTrackRemoved.bind(this)),this.subscribe(this._transport,N.REMOTE_ALL_STALL,this._onRemoteAllStall.bind(this)),this.subscribe(this._transport,N.REMOTE_DATA_STATS,this._onRemoteDataStats.bind(this)),this.subscribe(this._transport,N.SIGNALLED_STALLED_PARTICIPANTS,this._onRemoteSignalledStall.bind(this)),this.subscribe(this._transport,N.ACTIVE_PARTICIPANTS_NO_SIGNAL,this._onRemoteActivityNoSignal.bind(this)),this.subscribe(this._transport,N.TOPOLOGY_CHANGED,this._onTopologyChanged.bind(this)),this.subscribe(this._transport,N.NETWORK_STATUS,this._onNetworkStatus.bind(this)),this.subscribe(this._transport,N.REMOTE_STREAM_SECOND,this._onRemoteStreamSecond.bind(this)),this.subscribe(this._transport,N.PEER_CONNECTION_CLOSED,this._onPeerConnectionClosed.bind(this));let e=this._conversation.direction===We.OUTGOING&&!this._conversation.concurrent;for(let t of Object.values(this._participants))(t.state===j.ACCEPTED||t.state===j.CALLED)&&this._transport.allocate(t.id,e)}_createSpeakerDetector(){this._transport&&(this._volumesDetector=new dr(this._transport),this.subscribe(this._volumesDetector,ct.VOLUMES_DETECTED,this._onVolumesDetected.bind(this)),this._speakerDetector=new lr(this._volumesDetector,this._transport),this.subscribe(this._speakerDetector,pr.SPEAKER_CHANGED,this._onSpeakerChanged.bind(this)),this._localVolumeDetector=new ai(this._mediaSource))}_createSpecListener(){this._transport&&this._volumesDetector&&(this._specListener=new ci(this._transport,this._volumesDetector,this._participants))}_logDevices(){let e=y.getCameras().length,t=y.getMicrophones().length;o.debug("Cameras: "+e+(y.hasCameraPermission()?"✔":"✖")+", Microphones: "+t+(y.hasMicrophonePermission()?"✔":"✖")),m.log(_.DEVICES,`${e}_${t}`)}_logWithMediaSettings(e,t){m.log(e,[(t==null?void 0:t.isAudioEnabled)&&"audio",(t==null?void 0:t.isVideoEnabled)&&"video"].filter(Boolean).join("_"))}_removeParticipant(e,t){var i;e.state===j.CALLED||e.state===j.ACCEPTED||this._state==="CLOSE"||!this._participants[e.id]||(t===P.HUNGUP?this._setParticipantsStatus([e],J.HANGUP):this._setParticipantsStatus([e],J.ERROR,t),(i=e.mediaSource)==null||i.disconnect(),this._conversation&&this._conversation.pinnedParticipantId===e.id&&(this._conversation.pinnedParticipantId=null),this.updateDisplayLayout([{uid:e.externalId,mediaType:Se.CAMERA,stopStream:!0}]),delete this._participants[e.id],E.onRemoteRemoved(e.externalId))}_cleanupListeners(){this.unsubscribe(),window.removeEventListener("unload",this._onUnload)}_cleanupMediaSource(){this._mediaSource&&(this._mediaSource.destroy(),this._mediaSource=null)}_cleanupParticipants(){Object.values(this._participants).forEach(e=>{var t,i,r;(t=e.remoteStream)==null||t.getTracks().forEach(a=>a.stop()),(i=e.secondStream)==null||i.getTracks().forEach(a=>a.stop()),(r=e.mediaSource)==null||r.disconnect()}),this._participants={},this._audioOutput&&this._audioOutput.destroy()}_cleanupParticipantAgnosticStreams(){o.debug("cleaning up participant-agnostic streams"),this._streamByStreamId.forEach(e=>{e.getTracks().forEach(t=>{t.stop()})}),this._streamByStreamId=new Map,this._streamWaitTimerByStreamDescription.forEach(e=>{window.clearTimeout(e)}),this._streamWaitTimerByStreamDescription=new Map,this._streamIdByStreamDescription=new Map,this._sequenceNumberByStreamDescription=new Map,this._cooldownTimestampByStreamDescription=new Map}_cleanupTransport(){this._transport&&(this._transport.destroy(),this._transport=null),this._debugInfo&&(this._debugInfo=null)}_cleanupSpeakerDetector(){this._speakerDetector&&(this._speakerDetector.destroy(),this._speakerDetector=null),this._volumesDetector&&(this._volumesDetector.destroy(),this._volumesDetector=null),this._localVolumeDetector&&(this._localVolumeDetector.destroy(),this._localVolumeDetector=null)}_cleanupSpecListener(){this._specListener&&(this._specListener.destroy(),this._specListener=null)}_cleanupSignaling(){this._signaling.close(),this._signaling.cleanup()}_onAddParticipant(e,t,i){return c(this,null,function*(){o.debug(`Add new participant [${e}]`);let r=this._participants[e];if(r&&(r.state===j.ACCEPTED||r.state===j.CALLED)){o.warn(`Participant [${r.id}:${r.state}] is already in conversation`);return}r||(this._participants[e]=yield this._createParticipant({id:e,externalId:t.externalId&&re.fromSignaling(t.externalId),mediaSettings:Ee(t.mediaSettings),state:t.state,roles:t.roles||[],muteStates:t.muteStates||{},unmuteOptions:t.unmuteOptions||[]}),r=this._participants[e]),this._setParticipantsStatus([r],J.WAITING),i?(r.state=j.HUNGUP,this._removeParticipant(r,i)):this._transport&&(r.state=j.CALLED,this._transport.allocate(r.id,!0),m.log(_.ADD_PARTICIPANT))})}_onRemoveParticipant(e){o.debug(`Remove participant [${e}]`);let t=this._participants[e];if(!t){o.warn(`Participant [${e}] isn't in conversation`);return}this._transport&&this._transport.close(t.id),m.log(_.REMOVE_PARTICIPANT)}changeDevice(e){return c(this,null,function*(){return e==="audiooutput"?this._audioOutput.changeOutput():this._mediaSource?(e==="audioinput"&&(this._audioFix=new xt(this._mediaSource)),this._mediaSource.changeDevice(e)):Promise.reject(ne.UNKNOWN)})}toggleScreenCapturing(e){return c(this,null,function*(){return this._mediaSource?this._mediaSource.toggleScreenCapturing(e):Promise.reject(ne.UNKNOWN)})}setVideoStream(e,t=!1){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setVideoStream(e,t)})}setAudioStream(e){return c(this,null,function*(){if(this._mediaSource)return this._mediaSource.setAudioStream(e)})}toggleLocalVideo(e){return c(this,null,function*(){if(this._mediaSource)return m.log(_.MEDIA_STATUS,e?"video_1":"video_0"),this._mediaSource.toggleVideo(e)})}toggleLocalAudio(e){return c(this,null,function*(){if(this._mediaSource)return m.log(_.MEDIA_STATUS,e?"audio_1":"audio_0"),this._mediaSource.toggleAudio(e)})}changePriorities(e){return c(this,null,function*(){if(e.length<2||!this._signaling.ready)return;let t={},i={};for(let r of e){let a=typeof r.uid=="object"?r.uid:re.fromId(r.uid),s=re.toString(a);i[s]=r.priority}for(let r of Object.values(this._participants)){let a=re.toString(r.externalId);i.hasOwnProperty(a)&&(t[r.id]=i[a])}yield this._signaling.changePriorities(t)})}changeParticipantState(e){return c(this,null,function*(){for(let[t,i]of Object.entries(e))if(t.length>5||i.length>5)throw new Error("key/value max length is 5 chars, mappings with empty values (null or empty string) are discarded");yield this._signaling.changeParticipantState(e)})}updateDisplayLayout(e){return c(this,null,function*(){if(e.length<1||!this._signaling.ready)return;o.log(`Update display layout [${this._signaling.getNextCommandSequenceNumber()}]`,e);let t={};for(let r of e){let a=typeof r.uid=="object"?r.uid:re.fromId(r.uid),s=re.toString(a),d=this._api.getCachedOkIdByExternalId(a);if(!d){o.log(`Unknown participant external ID ${s}`);continue}let l=Qe({participantId:d,mediaType:r.mediaType,streamName:r.streamName}),u=this._participants[d];u&&(u.lastRequestedLayouts[l]=r),H._isStopStreaming(r)?this._streamIdByStreamDescription.has(l)&&!this._cooldownTimestampByStreamDescription.has(l)&&this._cooldownTimestampByStreamDescription.set(l,Date.now()):(this._cooldownTimestampByStreamDescription.delete(l),!this._streamIdByStreamDescription.has(l)&&p.videoTracksCount>0&&this._streamIdByStreamDescription.set(l,null),t[l]=H._layoutToString(r))}let i=this._cooldownTimestampByStreamDescription.keys();for(;this._streamIdByStreamDescription.size>p.videoTracksCount;){let r=i.next();if(r.done){o.error("Cannot accommodate all streaming requests: tracks available "+p.videoTracksCount+"; requested streams: "+Array.from(this._streamIdByStreamDescription.keys()));break}this._stopStreaming(r.value),t[r.value]=H._layoutToString({stopStream:!0})}yield this._sendUpdateDisplayLayout(t)})}_stopStreaming(e){if(this._cooldownTimestampByStreamDescription.delete(e),this._sequenceNumberByStreamDescription.set(e,this._signaling.getNextCommandSequenceNumber()),this._streamWaitTimerByStreamDescription.has(e)&&(o.log("Client asked to stop streaming before stream became available",e),window.clearTimeout(this._streamWaitTimerByStreamDescription.get(e)),this._streamWaitTimerByStreamDescription.delete(e)),this._streamIdByStreamDescription.get(e)){let i=Mt(e),r=this._participants[i.participantId];r?(i.streamName&&(i.mediaType===Se.STREAM||i.mediaType===Se.SCREEN)?E.onRemoteLive(r.externalId,i.streamName,null):E.onRemoteStream(r.externalId,null),m.log(_.PAT_DEALLOCATED)):o.log(`Cannot find participant to stop streaming: ${i.participantId}`)}this._streamIdByStreamDescription.delete(e)}_sendUpdateDisplayLayout(e){return c(this,null,function*(){if(Object.keys(e).length===0)return;let t=yield this._signaling.updateDisplayLayout(e);if(!t)return;let i=[];for(let[r,a]of Object.entries(t.errorCodeByParticipantId||{})){let s=Mt(r),d=this._participants[s.participantId];if(d){let l;typeof a!="number"?(o.warn(`Unexpected error code ${a} received for participant ${s.participantId}`),l=Hr.UNKNOWN_ERROR):l=Gr(a),i.push({externalId:d.externalId,errorReason:l})}}if(i&&i.length)throw new di("Could not allocate one or more participants",i)})}_cleanupCooldownQueue(){let e={},t=this._cooldownTimestampByStreamDescription.entries();do{let i=t.next();if(i.done)break;let r=i.value;if(r[1]+Os>Date.now())break;let s=r[0];this._stopStreaming(s),e[s]=H._layoutToString({stopStream:!0})}while(!0);this._sendUpdateDisplayLayout(e)}static _isStopStreaming(e){return e.stopStream}static _layoutToString(e){if(H._isStopStreaming(e))return"ss";let t="";return e.priority!==void 0&&(t+="p="+e.priority),e.width!==void 0&&e.height!==void 0&&(t!==""&&(t+=":"),t+="sz="+Math.round(e.width)+"x"+Math.round(e.height)),e.fit!==void 0&&(t!==""&&(t+=":"),t+="fit="+e.fit),e.keyFrame&&(t!==""&&(t+=":"),t+="kf"),t}_onParticipantSourcesUpdate(e){if(this._conversation){o.log("Received participant sources update notification",e);for(let t of e)this._waitForStreamIfNeeded(t)}}_onParticipantPromoted(e){return c(this,null,function*(){o.log("Promoted in waiting hall",!e.demote),e.demote?(o.log("Kicked from waiting hall"),this._close(new x(P.REMOVED))):(this._updateConversation(e),yield this._onJoinPart2(e))})}_onChatRoomUpdated(r){return c(this,arguments,function*(e,t=0,i=[]){o.log(`Chat room updated: ${e}`);let a=[],s=[];i.length&&(i.forEach(d=>{if(d.externalId){let l=re.fromSignaling(d.externalId);a.push(l),this._api.cacheExternalId(d.id.id,l)}else s.push(T.decomposeId(d.id.id).id)}),s.length&&!a.length&&(a=yield this._api.getExternalIdsByOkIds(s))),E.onChatRoomUpdated(e,t,a)})}_waitForStreamIfNeeded(e){var d,l;let t=this._matchStreamDescription(e.participantStreamDescription);if(!t||p.producerScreenTrack&&t.mediaType===Se.SCREEN)return;let i=Qe(t),r=this._sequenceNumberByStreamDescription.get(i);if(r&&r>e.sequenceNumber){o.warn(`Participant ${t.participantId} received outdated PAT response: sequence number ${e.sequenceNumber}; last sent sequence number for given participant is ${r}`),m.log(_.PAT_OUTDATED_RESPONSE);return}let a=e.streamId,s=e.rtpTimestamp?this._getWaitingTime(a,e.rtpTimestamp):0;if(s<=0){this._streamWaitTimerByStreamDescription.delete(i);let u=t.participantId,g=this._participants[u];if(!g){m.log(_.PAT_ERROR,"participantMissing"),o.error(`Could not find participant by ID: ${u}`);return}let f=this._streamByStreamId.get(a);if(!f){m.log(_.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${a}`);return}m.log(_.PAT_ALLOCATED),this._streamIdByStreamDescription.set(i,a);let W=(d=e.participantStreamDescription)==null?void 0:d.mediaType;if(W===Se.STREAM||W===Se.MOVIE)((l=e.participantStreamDescription)==null?void 0:l.streamName)&&E.onRemoteLive(g.externalId,e.participantStreamDescription.streamName,f);else{let K=(p.producerScreenTrack?null:g.secondStream)||f;E.onRemoteStream(g.externalId,K)}}else{o.debug(`Waiting for ${s} until stream ${a} for ${i} is switched`);let u=window.setTimeout(this._waitForStreamIfNeeded.bind(this,e),s);this._streamWaitTimerByStreamDescription.set(i,u)}}_matchStreamDescription(e){if(!e)return null;if(this._streamIdByStreamDescription.has(Qe(e)))return e;let t=e.participantId;if(e.mediaType){let i={participantId:t,mediaType:null};if(this._streamIdByStreamDescription.has(Qe(i)))return i}else{let i={participantId:t,mediaType:Se.CAMERA};if(this._streamIdByStreamDescription.has(Qe(i)))return i;let r={participantId:t,mediaType:Se.SCREEN};if(this._streamIdByStreamDescription.has(Qe(r)))return r}return o.error("Received unrequested allocation",e),null}_getWaitingTime(e,t){if(this._transport)return this._transport.getStreamWaitingTimeMs(e,t);throw new Error("transport is not initialized")}_isCallAdmin(){return this._conversation?T.includesOneOf(this._conversation.roles,[Ye.ADMIN,Ye.CREATOR]):!1}_checkAdminRole(){if(!!this._conversation&&!T.includesOneOf(this._conversation.roles,[Ye.ADMIN,Ye.CREATOR]))throw new Error("You don't have the required permission")}grantRoles(e,t,i){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.grantRoles(e,t,i)})}muteParticipant(){return c(this,arguments,function*(e=null,t,i=[]){this._checkAdminRole(),yield this._signaling.muteParticipant(e,t,i)})}pinParticipant(e,t){return c(this,null,function*(){this._checkAdminRole(),yield this._signaling.pinParticipant(e,t)})}updateMediaModifiers(e){return c(this,null,function*(){this._signaling.ready&&this._conversation&&(this._conversation.mediaModifiers=e,yield this._signaling.updateMediaModifiers(e))})}changeOptions(e){return c(this,null,function*(){if(this._signaling.ready&&this._conversation){this._checkAdminRole(),yield this._signaling.changeOptions(e);let t=Ar(this._conversation.options,e);this._onOptionsChanged(t)}})}getWaitingHall(e,t,i){return c(this,null,function*(){if(!this._signaling)return Promise.reject();let r=null;e&&(r=Un(e));let a=yield this._signaling.getWaitingHall(r,t,i);if(a.error)return Promise.reject(a.message);let s=a.participants||[],d=[],l=[],u=null;return s.length&&(s.forEach(g=>{if(g.externalId){let f=re.fromSignaling(g.externalId);d.push(f),this._api.cacheExternalId(g.id.id,f)}else l.push(T.decomposeId(g.id.id).id)}),l.length&&!d.length&&(d=yield this._api.getExternalIdsByOkIds(l)),a.hasMore&&(u=Ln(s[s.length-1].id))),{participants:d,pageMarker:u,totalCount:a.totalCount||0}})}promoteParticipant(e,t){return c(this,null,function*(){this._signaling&&(yield this._signaling.promoteParticipant(e,t))})}chatMessage(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.chatMessage(e,t))})}chatHistory(e){return c(this,null,function*(){if(this._signaling.ready){let t=yield this._signaling.chatHistory(e);for(let i=t.messages.length-1;i>=0;i--){let r=t.messages[i];yield this._onChatMessage(r)}}})}customData(e,t=null){return c(this,null,function*(){this._signaling.ready&&(yield this._signaling.customData(e,t))})}createJoinLink(){return c(this,null,function*(){if(this._conversation){let t=(yield this._api.createJoinLink(this._conversation.id)).join_link;if(t)return this._conversation.joinLink=t,t}return Promise.reject()})}removeJoinLink(){return c(this,null,function*(){if(this._conversation&&(yield this._api.removeJoinLink(this._conversation.id)).success){delete this._conversation.joinLink;return}return Promise.reject()})}addMovie(e){return c(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.addMovie(t);if(i.error)throw new Error(i.error);return{movieId:i.movieId,streamType:i.streamType}})}updateMovie(e,t,i,r){return c(this,null,function*(){var d;let a={movieId:e,participantId:(d=this._conversation)==null?void 0:d.compositeUserId};(t||t===0)&&(a.gain=t),i&&(a.offset=i),typeof r!==void 0&&(a.pause=r);let s=yield this._signaling.updateMovie(a);if(s.error)throw new Error(s.error)})}removeMovie(e){return c(this,null,function*(){var r;let t={movieId:e,participantId:(r=this._conversation)==null?void 0:r.compositeUserId},i=yield this._signaling.removeMovie(t);if(i.error)throw new Error(i.error)})}startStream(e=!1,t=null,i=null,r="DIRECT_LINK",a=null){return c(this,null,function*(){let s={movieId:i,name:t,privacy:r,groupId:a,streamMovie:!e},d=yield this._signaling.startStream(s);return d.error?Promise.reject(d.message):d})}stopStream(){return c(this,null,function*(){let e=yield this._signaling.stopStream();return e.error?Promise.reject():e})}recordSetRole(e,t){return c(this,null,function*(){let i=yield this._signaling.recordSetRole(e,t);if(i.error)throw new Error(i.error)})}getStreamInfo(){return c(this,null,function*(){let e=yield this._signaling.getRecordStatus();return{movieId:e.recordMovieId,preview:e.recordMoviePreviewUrl}})}setLocalResolution(e,t,i){return c(this,null,function*(){var r;if(e<p.videoMinWidth||t<p.videoMinHeight)throw new Error("Sizes received are less than the `videoMinWidth` or `videoMinHeight`");if(i==null?void 0:i.effect){if(i.effect.width<p.videoMinWidth||i.effect.height<p.videoMinHeight)throw new Error("Sizes of effect received are less than the `videoMinWidth` or `videoMinHeight`");p.videoEffectMaxHeight=i.effect.height,p.videoEffectMaxWidth=i.effect.width}return p.videoMaxWidth=e,p.videoMaxHeight=t,(r=this._mediaSource)==null?void 0:r.setResolution(e,t)})}videoEffect(e){return c(this,null,function*(){var t;return(t=this._mediaSource)==null?void 0:t.videoEffect(e)})}_onLocalMediaStreamChanged(e){return c(this,null,function*(){var t;!this._conversation||(o.debug("Local media stream changed",e.mediaSettings),E.onLocalStreamUpdate(e.mediaSettings,e.kind),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings)))})}_onScreenSharingStatus(e){return c(this,null,function*(){var t;if(o.log("Screen sharing changed",e.track,e.mediaSettings),p.consumerScreenTrack){let i=e.track?new MediaStream([e.track]):null;E.onScreenStream(i,e.mediaSettings),this._signaling.ready&&!((t=this._conversation)==null?void 0:t.waitingHall)&&(yield this._signaling.changeMediaSettings(e.mediaSettings))}})}_changeRemoteMediaSettings(e,t){o.debug(`Remote media settings changed [${e}]`,t);let i=this._participants[e];!i||(i.mediaSettings=t,this._state==="ACTIVE"&&E.onRemoteMediaSettings(i.externalId,t),this._specListener&&this._specListener.onChangeRemoteMediaSettings(e,t))}_changeRemoteParticipantState(e,t){o.debug(`Remote participant state changed [${e}]`,t);let i=this._participants[e];!i||(i.participantState=t||{},this._state==="ACTIVE"&&(p.participantStateMapped?E.onRemoteParticipantState(i.externalId,i.participantState):E.onRemoteParticipantState(i.externalId,T.mapLegacyParticipantState(i.participantState))))}_onSignalingNotification(e){switch(e.notification){case O.ACCEPTED_CALL:return this._onAcceptedCall(e);case O.HUNGUP:return this._onHungup(e);case O.PARTICIPANT_ADDED:return this._onAddedParticipant(e);case O.PARTICIPANT_JOINED:return this._onJoinedParticipant(e);case O.CLOSED_CONVERSATION:return this._onClosedConversation(e);case O.MEDIA_SETTINGS_CHANGED:return this._onMediaSettingsChanged(e);case O.PARTICIPANT_STATE_CHANGED:return this._onParticipantStateChanged(e);case O.RATE_CALL_DATA:return this._onNeedRate();case O.FEATURE_SET_CHANGED:return this._onFeatureSetChanged(e);case O.MULTIPARTY_CHAT_CREATED:return this._onMultipartyChatCreated(e);case O.FORCE_MEDIA_SETTINGS_CHANGE:return this._onForceMediaSettingsChange(e);case O.SETTINGS_UPDATE:return this._onSettingsUpdate(e);case O.VIDEO_QUALITY_UPDATE:return this._onVideoQualityUpdate(e);case O.REGISTERED_PEER:return this._onPeerRegistered(e);case O.SWITCH_MICRO:return this._onMicSwitched(e);case O.CHAT_MESSAGE:return this._onChatMessage(e);case O.CUSTOM_DATA:return this._onCustomData(e);case O.RECORD_STARTED:return this._onRecordInfo(e.recordInfo);case O.RECORD_STOPPED:return this._onRecordInfo(null);case O.ROLES_CHANGED:return this._onRolesChanged(e.participantId,e.roles||[]);case O.MUTE_PARTICIPANT:return this._onMuteParticipant(e);case O.PIN_PARTICIPANT:return this._onPinParticipant(e.participantId,e.unpin);case O.OPTIONS_CHANGED:return this._onOptionsChanged(e.options||[]);case O.PARTICIPANT_SOURCES_UPDATE:return this._onParticipantSourcesUpdate(e.participantUpdateInfos);case O.PROMOTE_PARTICIPANT:return this._onParticipantPromoted(e);case O.CHAT_ROOM_UPDATED:return this._onChatRoomUpdated(e.eventType,e.totalCount,e.firstParticipants)}}_onSignalingReconnect(e){return c(this,null,function*(){if(!this._conversation)return;e.conversation.acceptTime&&(this._conversation.acceptTime=e.conversation.acceptTime),e.conversation.participantsLimit&&(this._conversation.participantsLimit=e.conversation.participantsLimit),e.conversation.features&&(this._conversation.features=e.conversation.features,this._changeFeatureSet()),e.conversation.pinnedParticipantId!==this._conversation.pinnedParticipantId&&(e.conversation.pinnedParticipantId?this._onPinParticipant(e.conversation.pinnedParticipantId,!1):this._conversation.pinnedParticipantId&&this._onPinParticipant(this._conversation.pinnedParticipantId,!0)),e.conversation.state;let t=null;if(e.conversation.participants){let i=Object.keys(this._participants),r=[];for(let a of e.conversation.participants){let s=T.composeParticipantId(a),d=a.roles||[];if(s===this._conversation.compositeUserId){t=Ee(a.mediaSettings),bt(this._conversation.roles,d)||this._onRolesChanged(s,d);continue}r.push(s);let l=this._participants[s];if(!l)yield this._onJoinedParticipant({participantId:a.id,participant:a,mediaSettings:a.mediaSettings});else{let u=Ee(a.mediaSettings);_n(u,l.mediaSettings)||this._changeRemoteMediaSettings(s,u);let g=T.mapParticipantState(a),f=l.participantState;T.isEqualParticipantState(g,f)||this._changeRemoteParticipantState(s,g),bt(d,l.roles)||this._onRolesChanged(l.id,d)}}for(let a of i)r.indexOf(a)<0&&this._removeParticipant(this._participants[a],P.HUNGUP)}this._onMuteParticipant({muteStates:e.conversation.muteStates,unmuteOptions:e.unmuteOptions,mediaOptions:[]},t),this._onRecordInfo(e.conversation.recordInfo),this._onOptionsChanged(e.conversation.options)})}_onSignalingFailed(e){o.error("Signaling failed",e),this._close(e)}_onAcceptedCall(e){return c(this,null,function*(){let t=T.composeMessageId(e),i=T.getPeerIdString(e.peerId);if(o.debug(`Participant accepted call [${t}]`),this._conversation&&t===this._conversation.compositeUserId){this._close(new x(P.MISSED),"Call accepted on other device");return}let r=this._participants[t];r||(this._participants[t]=yield this._createParticipant({id:t,mediaSettings:Ee(e.mediaSettings)}),r=this._participants[t]),r.state=j.ACCEPTED,r.mediaSettings=Ee(e.mediaSettings),this._logWithMediaSettings(_.ACCEPTED_OUTGOING,r.mediaSettings),this._conversation&&this._conversation.direction===We.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),this._state==="ACTIVE"&&this._transport&&this._transport.open([r.id],i),this._changeRemoteMediaSettings(t,r.mediaSettings),this._changeRemoteParticipantState(t)})}_onHungup(e){o.debug(`Participant hungup [${e.participantId}]`,{reason:e.reason});let t=T.composeMessageId(e);if(this._conversation&&this._conversation.compositeUserId===t){this._close(new x(e.reason));return}let i=this._participants[t];if(!i){o.warn(`Participant [${t}] isn't in conversation`);return}this._transport&&this._transport.close(t),i.state=e.reason===P.REJECTED?j.REJECTED:j.HUNGUP,this._state!=="CLOSE"&&this._removeParticipant(i,P.HUNGUP)}_onAddedParticipant(e){return c(this,null,function*(){var r,a;o.debug(`Participant added [${e.participantId}]`);let t=T.composeMessageId(e),i=this._participants[t];if(i&&i.state!==j.HUNGUP&&i.state!==j.REJECTED){o.debug(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&re.fromSignaling(e.participant.externalId),mediaSettings:Ee(e.participant.mediaSettings),state:e.participant.state,participantState:T.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),i.state=j.CALLED,i.mediaSettings=Ee((r=e.participant)==null?void 0:r.mediaSettings),i.participantState=T.mapParticipantState(e.participant),i.roles=((a=e.participant)==null?void 0:a.roles)||[],this._setParticipantsStatus([i],J.WAITING),this._state==="ACTIVE"&&this._transport&&this._transport.allocate(i.id,!0),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onJoinedParticipant(e){return c(this,null,function*(){var r;o.debug(`Participant joined [${e.participantId}]`);let t=T.composeMessageId(e),i=this._participants[t];if(i&&i.state===j.ACCEPTED){o.warn(`Participant [${t}] is already in conversation and is active`);return}i||(this._participants[t]=yield this._createParticipant({id:t,externalId:e.participant.externalId&&re.fromSignaling(e.participant.externalId),mediaSettings:Ee(e.participant.mediaSettings),state:e.participant.state,participantState:T.mapParticipantState(e.participant),roles:e.participant.roles||[],muteStates:e.participant.muteStates||{},unmuteOptions:e.participant.unmuteOptions||[]}),i=this._participants[t]),this._conversation&&this._conversation.direction===We.OUTGOING&&(this._state==="IDLE"||this._state==="PROCESSING")&&(this._state="ACTIVE",this._changeFeatureSet()),i.state=j.ACCEPTED,i.mediaSettings=Ee(e.mediaSettings),i.participantState=T.mapParticipantState(e.participant),i.roles=e.participant.roles||[],((r=this._transport)==null?void 0:r.isAllocated(i.id))?this._setParticipantsStatus([i],J.CONNECTED):this._setParticipantsStatus([i],J.WAITING),this._state==="ACTIVE"&&this._transport&&(this._transport.isAllocated(i.id)||this._transport.allocate(i.id,!0),this._transport.open([i.id])),this._changeRemoteMediaSettings(t,i.mediaSettings),this._changeRemoteParticipantState(t,i.participantState)})}_onClosedConversation(e){this._toggleJoinAvailability(),this._close(new x(e.reason,{remote:!0}))}_onMediaSettingsChanged(e){let t=T.composeMessageId(e);this._changeRemoteMediaSettings(t,Ee(e.mediaSettings))}_onParticipantStateChanged(e){let t=T.composeMessageId(e);this._changeRemoteParticipantState(t,T.mapParticipantState(e))}_onNeedRate(){this._conversation&&(this._conversation.needRate=!0,this._changeNeedRate())}_onFeatureSetChanged(e){this._conversation&&(this._conversation.features=e.features,this._changeFeatureSet())}_onMultipartyChatCreated(e){this._conversation&&(this._conversation.chatId=e.chatId,this._toggleJoinAvailability(),E.onMultipartyChatCreated(this._conversation))}_onForceMediaSettingsChange(e){return c(this,null,function*(){if(!this._mediaSource)return;let t=this._mediaSource.getMediaSettings(),i=Ee(e.mediaSettings);t.isAudioEnabled!==i.isAudioEnabled&&(yield this._mediaSource.toggleAudio(i.isAudioEnabled)),t.isVideoEnabled!==i.isVideoEnabled&&(yield this._mediaSource.toggleVideo(i.isVideoEnabled)),p.consumerScreenTrack&&t.isScreenSharingEnabled!==i.isScreenSharingEnabled&&(yield this._mediaSource.toggleScreenCapturing(i.isScreenSharingEnabled))})}_onSettingsUpdate(e){let t={camera:e.camera,screenSharing:e.screenSharing};this._serverSettings=ar(this._serverSettings,t),this._transport&&this._transport.updateSettings(this._serverSettings)}_onVideoQualityUpdate(e){let t=Math.round(e.quality.maxBitrate/1024),i=e.quality.maxDimension,r={camera:Object.assign({},this._serverSettings.camera,{maxBitrateK:t,maxDimension:i}),screenSharing:null};this._serverSettings=ar(this._serverSettings,r),o.log("Got video quality update notification",this._serverSettings),this._transport&&this._transport.updateSettings(this._serverSettings)}_onPeerRegistered(e){let t=T.composeMessageId(e);this._participants[t]&&(this._participants[t].clientType=e.clientType,this._participants[t].platform=e.platform)}_onMicSwitched(e){return c(this,null,function*(){E.onDeviceSwitched(le.AUDIO,!e.mute),yield this.toggleLocalAudio(!e.mute)})}_onChatMessage(e){return c(this,null,function*(){let t=T.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),E.onChatMessage(e.message,i,e.direct)})}_onCustomData(e){return c(this,null,function*(){if(e.data.hasOwnProperty("sdk"))return;let t=T.composeMessageId(e),i;this._participants[t]?i=this._participants[t].externalId:i=yield this._getUserId(t),E.onCustomData(e.data,i,e.direct)})}_onRecordInfo(e){return c(this,null,function*(){if(!this._conversation)return;let t=!1;if(!this._conversation.recordInfo!=!e?t=!0:this._conversation.recordInfo&&e&&(t=this._conversation.recordInfo.recordMovieId!==e.recordMovieId),t)if(e){let i=yield this._getUserId(e.initiator);E.onRecordStarted(i,e.recordMovieId,e.recordStartTime,e.recordType,e.recordExternalMovieId,e.recordExternalOwnerId)}else E.onRecordStopped();this._conversation.recordInfo=e})}_onRolesChanged(e,t){if(this._conversation&&e===this._conversation.compositeUserId&&!bt(this._conversation.roles,t)){o.debug(`Local roles changed: ${t}`),this._conversation.roles=t,E.onLocalRolesChanged(t),this._processMuteState(Object.keys(this._conversation.muteStates));return}let i=this._participants[e];i&&!bt(i.roles,t)&&(o.debug(`Roles for participant [${e}] changed: ${t}`),i.roles=t,E.onRolesChanged(i.externalId,t))}_onMuteParticipant(e,t=null){return c(this,null,function*(){if(!this._conversation)return;let i=e.muteStates||{},r=e.unmuteOptions||[],a=e.mediaOptions||[],s=e.adminId?this._participants[e.adminId]:null;if(e.participantId&&e.participantId!==this._conversation.compositeUserId){if(!this._isCallAdmin()){o.warn(`Not admin got mute states for participant [${e.participantId}]`);return}let d=this._participants[e.participantId];d&&(o.debug(`Mute states for participant [${e.participantId}] changed`,i),E.onMuteStates(i,r,a,e.muteAll,e.unmute,d.externalId,s==null?void 0:s.externalId));return}T.isObjectsEquals(this._conversation.muteStates,i)&&T.isArraysEquals(this._conversation.unmuteOptions,r)&&!a.length||(this._conversation.muteStates=i,this._conversation.unmuteOptions=r,e.adminId!==this._conversation.compositeUserId&&(yield this._processMuteState(a,e.muteAll,e.unmute,t,s)))})}_processMuteState(){return c(this,arguments,function*(e=[],t=!1,i=!1,r=null,a=null){if(!this._conversation||!this._mediaSource||this._participantState!==j.ACCEPTED)return;let s=Object.assign({},this._conversation.muteStates),d=this._conversation.unmuteOptions,l=this._mediaSource.getMediaSettings(),u=Object.entries(s);for(let[g,f]of u)if(!(f!==je.MUTE&&f!==je.MUTE_PERMANENT)&&(this._isCallAdmin()&&f===je.MUTE_PERMANENT&&(s[g]=je.MUTE),!(!e.includes(g)||i)))switch(g){case le.VIDEO:l.isVideoEnabled&&!(r==null?void 0:r.isVideoEnabled)&&(E.onDeviceSwitched(le.VIDEO,!1),yield this.toggleLocalVideo(!1));break;case le.AUDIO:l.isAudioEnabled&&!(r==null?void 0:r.isAudioEnabled)&&(E.onDeviceSwitched(le.AUDIO,!1),yield this.toggleLocalAudio(!1));break;case le.SCREEN_SHARING:l.isScreenSharingEnabled&&!(r==null?void 0:r.isScreenSharingEnabled)&&(E.onDeviceSwitched(le.SCREEN_SHARING,!1),yield this.toggleScreenCapturing(!1));break}E.onMuteStates(s,d,e,t,i,null,a==null?void 0:a.externalId)})}_onPinParticipant(e,t=!1){if(!this._conversation)return;let i=this._conversation.pinnedParticipantId;i&&i!==e&&(this._participants[i]?E.onPinnedParticipant(this._participants[i].externalId,!0):this._conversation.compositeUserId===i&&E.onLocalPin(!0)),this._participants[e]?E.onPinnedParticipant(this._participants[e].externalId,t):this._conversation.compositeUserId===e&&E.onLocalPin(t),this._conversation.pinnedParticipantId=t?null:e}_onOptionsChanged(e){this._conversation&&!Mr(this._conversation.options,e)&&(this._conversation.options=e,E.onOptionsChanged(e))}_onNetworkStatus(e){if(this._conversation){let t=[];for(let[i,r]of Object.entries(e)){let a;if(i===this._conversation.compositeUserId||i==="")a=this._conversation.networkRating;else if(this._participants[i])a=this._participants[i].networkRating;else continue;if(a!==r)if(i===this._conversation.compositeUserId||i==="")this._conversation.networkRating=r,E.onLocalNetworkStatusChanged(r);else{let s=this._participants[i];s.networkRating=r,t.push({uid:s.externalId,rating:r})}}if(t.length===0)return;o.log("Received network status update: ",e),E.onNetworkStatusChanged(t)}}_onRemoteStreamSecond(e,t){let i=this._participants[e];if(!!i){if(p.producerScreenTrack){E.onRemoteScreenStream(i.externalId,t);return}if(i.secondStream=t,p.videoTracksCount>0){let r=e;if(!this._streamIdByStreamDescription.has(r)){o.error("Received remote stream notification for a participant that has no track associated with it",r);return}let a=this._streamIdByStreamDescription.get(r);if(!a||this._streamWaitTimerByStreamDescription.has(r)){o.log("Delaying secondary stream start/stop until main stream becomes available",r);return}let s=this._streamByStreamId.get(a);if(!s){m.log(_.PAT_ERROR,"streamNotFound"),o.error(`Could not find stream by ID: ${a}`);return}E.onRemoteStream(i.externalId,i.secondStream||s)}else{let r=t||i.remoteStream;r&&E.onRemoteStream(i.externalId,r)}}}_onPeerConnectionClosed(e){e===Pe.SERVER&&this._cleanupParticipantAgnosticStreams()}_changeFeatureSet(){if(this._conversation){let e=this._state==="ACTIVE",t=this._conversation.features.includes(br.ADD_PARTICIPANT);E.onCallState(e,t,this._conversation)}}_changeNeedRate(){this._conversation&&this._conversation.needRate&&E.onRateNeeded()}_onVolumesDetected(e){let t=[];for(let[i,r]of Object.entries(e)){let a=this._participants[i];a&&a.externalId&&t.push({uid:a.externalId,volume:r.real})}E.onVolumesDetected(t)}_onSpeakerChanged(e){this._activeSpeakerId=e,this._participants[e]&&this._lastSignalledActiveSpeakerId!==e&&(E.onSpeakerChanged(this._participants[e].externalId),this._lastSignalledActiveSpeakerId=e)}_onTransportStateChanged(e,t){return c(this,null,function*(){o.debug(`Transport state has changed: ${t}`,e);let i;if(t===F.CONNECTED?i=J.CONNECTED:t===F.CONNECTING||t===F.OPENED?i=J.CONNECTING:t===F.RECONNECTING&&(i=J.RECONNECT),!i)return;let r=e.reduce((a,s)=>{if(s in this._participants){let d=this._participants[s];a.push(d),t===F.CONNECTED&&(d.remoteStream||(d.mediaSettings&&this._changeRemoteMediaSettings(s,d.mediaSettings),this._changeRemoteParticipantState(s,d.participantState)),this._updateDisplayLayoutFromCache(s))}else o.warn(`Participant [${s}] isn't in conversation`);return a},[]);!r.length||this._setParticipantsStatus(r,i)})}_onTransportLocalStateChanged(e){return c(this,null,function*(){o.debug(`Local transport state has changed: ${e}`),e===F.CONNECTED&&E.onLocalStatus(J.CONNECTED),e===F.CONNECTING&&E.onLocalStatus(J.CONNECTING),e===F.RECONNECTING&&E.onLocalStatus(J.RECONNECT),e===F.FAILED&&this._transport&&this._transport.allocated().length===0&&(this._signaling.ready&&(yield this._signaling.hangup(P.FAILED)),this._close(new x(P.FAILED),"Transport failed"))})}_onRemoteTrackAdded(e,t,i){return c(this,null,function*(){if(e.endsWith(ke.AUDIO_MIX))o.debug("Remote audio mix track added"),this._audioOutput.add(i);else if(e.startsWith(ke.PARTICIPANT_AGNOSTIC_TRACK_PREFIX))o.debug(`Participant-agnostic track added: ${e}`),this._streamByStreamId.set(e,t);else{o.debug(`Remote track added on the participant [${e}]`,{kind:i.kind});let r=this._participants[e];if(r||(o.warn(`Conversation: track added before participant [${e}]`),this._participants[e]=yield this._createParticipant({id:e}),r=this._participants[e],this._setParticipantsStatus([r],J.WAITING),this._activeSpeakerId===e&&this._lastSignalledActiveSpeakerId!==e&&(E.onSpeakerChanged(r.externalId),this._lastSignalledActiveSpeakerId=e)),this._transport&&!this._transport.isAllocated(r.id)&&this._transport.allocate(r.id,!1),i.kind===me.audio&&this._audioOutput.add(i),r.remoteStream!==t){if(r.remoteStream=t,r.secondStream)return;E.onRemoteStream(r.externalId,t)}r.mediaSettings&&this._changeRemoteMediaSettings(e,r.mediaSettings),p.batchParticipantsOnStart||this._changeRemoteParticipantState(e,r.participantState)}})}_onRemoteTrackRemoved(e,t,i){switch(o.debug(`[${e}] remote track (removed)`,{track:i}),i.kind){case me.audio:this._removeAudioTrack(e,t,i);break;case me.video:case me.screen:this._removeVideoTrack(e,t,i);break}}_removeAudioTrack(e,t,i){if(e!==ke.AUDIO_MIX){let r=this._participants[e];if(!r||r.remoteStream&&r.remoteStream!==t)return}this._audioOutput.remove(i)}_removeVideoTrack(e,t,i){}_onRemoteActivityNoSignal(){this._onRemoteSignalledStall([]),this._onRemoteAllStall(!1)}_onTopologyChanged(e){this._conversation&&(this._conversation.topology=e,this._changeFeatureSet())}_onRemoteAllStall(e){if(this._remoteAllStalled===e)return;this._remoteAllStalled=e;let t=[],i=[];for(let r in this._participants)if(this._participants.hasOwnProperty(r)){let a=this._participants[r];e||this._lastStalled[r]?t.push(a):i.push(a)}t.length&&this._setParticipantsStatus(t,J.RECONNECT),i.length&&this._setParticipantsStatus(i,J.CONNECTED)}_onRemoteSignalledStall(e){let t={},i=[],r=[];e.forEach(a=>{if(t[a]=!0,!this._lastStalled[a]){let s=this._participants[a];s&&!this._remoteAllStalled&&i.push(s)}delete this._lastStalled[a]}),Object.keys(this._lastStalled).forEach(a=>{let s=this._participants[a];s&&!this._remoteAllStalled&&r.push(s)}),i.length&&this._setParticipantsStatus(i,J.RECONNECT),r.length&&this._setParticipantsStatus(r,J.CONNECTED),this._lastStalled=t}_onRemoteDataStats(e){this._debugInfo&&this._debugInfo.onRemoteDataStats(e,this._participants),this._fixAudioDevice(e.outbound.rtps)}_fixAudioDevice(e){var t;!y.hasMicrophone()||!this._audioFix||!((t=this._mediaSource)==null?void 0:t.getMediaSettings().isAudioEnabled)||this._audioFix.fix(e)}_toggleJoinAvailability(){let e=this._conversation&&this._conversation.chatId,t=e&&this._state!=="CLOSE"||!1;e&&(o.debug("Toggle join availability",{available:t,chatId:e}),E.onJoinStatus(t,e))}_updateDisplayLayoutFromCache(e){return c(this,null,function*(){var i;if(((i=this._transport)==null?void 0:i.getTopology())!==Pe.SERVER)return;let t=this._participants[e];t&&t.lastRequestedLayouts&&Object.keys(t.lastRequestedLayouts).length&&(yield this.updateDisplayLayout(Object.values(t.lastRequestedLayouts)))})}_setParticipantsStatus(e,t,i=null){if(!e.length)return;let r=e.reduce((a,s)=>(s.status!==t&&(s.status=t,p.batchParticipantsOnStart?a.push(s.externalId):E.onParticipantStatus(s.externalId,t,i)),a),[]);!r.length||p.batchParticipantsOnStart&&E.onRemoteStatus(r,t,i)}replayShare(e){var t;(t=this._transport)==null||t.replayShare(e,this)}getRandomParticipant(){let e=Object.values(this._participants);for(let t of e)return t;return null}},L=H;L._delayedHangup=!1;var di=class extends Error{constructor(e,t){super(e);Object.setPrototypeOf(this,di.prototype),this.participantErrors=t}};var pi;function ks(){return c(this,null,function*(){var n;if(p.apiEnv!=="AUTO")return p.apiEndpoint;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT1hcGkuX2VuZHBvaW50Lm9rLnJ1JnR5cGU9VFhU"),i=yield(yield fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(n=i==null?void 0:i.Answer[0])==null?void 0:n.data;if(!r)throw new Error("Wrong DNS response");return o.debug("Resolved API endpoint",r),r}catch(e){return o.warn("Failed to resolve API endpoint using DNS, default is used",e),p.apiEndpoint}})}function Hn(){if(!p.apiAppId||!p.apiKey)throw new x(ne.API,{message:"Required arguments apiAppId/apiAppKey not passed"})}function ur(n,e={},t=!1){if(!window.Blob||!window.navigator.sendBeacon)return;let i=Wn(n,e,t),r=new window.Blob([i],{type:"application/x-www-form-urlencoded"});window.navigator.sendBeacon(`${pi}/fb.do`,r)}function Gn(i){return c(this,arguments,function*(n,e={},t=!1){pi||(pi=yield ks());let r=Wn(n,e,t);return xs(r)})}function xs(n){return c(this,null,function*(){return new Promise((e,t)=>{let i=new XMLHttpRequest;i.open("POST",`${pi}/fb.do`,!0),i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.onreadystatechange=()=>{if(i.readyState!==XMLHttpRequest.DONE)return;let r;try{r=JSON.parse(i.responseText)}catch(a){r={result:i.responseText}}i.status!==200||r.hasOwnProperty("error_msg")?t(r):e(r)},i.send(n)})})}function Wn(n,e={},t=!1){e.method=n,e.format="JSON",e.application_key||(e.application_key=p.apiKey),t||(ie.sessionKey?e.session_key=ie.sessionKey:ie.accessToken&&(e.access_token=ie.accessToken));for(let[r,a]of Object.entries(e))typeof a=="object"&&(e[r]=JSON.stringify(a));let i="";for(let[r,a]of Object.entries(e))i&&(i+="&"),i+=`${r}=${encodeURIComponent(a)}`;return i}var Ls=10,Us=700,Bs=3e3,Ft=class extends pt{constructor(){super(...arguments);this._userId=null;this._externalUidsCache={}}_callUnsafe(r){return c(this,arguments,function*(e,t={},i=!1){let a=s=>c(this,null,function*(){try{return yield Gn(e,t,i)}catch(d){if(!d.hasOwnProperty("error_msg")&&(s++,o.debug(`${e} network error, attempt ${s}...`),s<Ls))return yield T.delay(Math.min(s*Us,Bs)),a(s);throw o.warn(e,"error",d),d}});return a(0)})}_call(r){return c(this,arguments,function*(e,t={},i=!1){try{return yield this._callUnsafe(e,t,i)}catch(a){o.warn("Api call error",a);let s=ne.API;switch(a.error_code){case 102:case 103:case 104:return yield this.authorize(),this._callUnsafe(e,t,i);case 1101:s=P.SERVICE_DISABLED;break;case 1102:s=P.CALLEE_IS_OFFLINE;break;case 1103:s=P.NOT_FRIENDS;break;case 1104:case 1106:s=P.EXTERNAL_API_ERROR;break}throw new x(s,{message:a.error_msg,code:a.error_code})}})}userId(e){return c(this,null,function*(){let t=T.decomposeId(e).id;return ie.isEmpty()?re.fromId(String(t)):(this._externalUidsCache.hasOwnProperty(t)||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds([t])),re.fromString(this._externalUidsCache[t]))})}prepareUserIds(e){return c(this,null,function*(){ie.isEmpty()||Object.assign(this._externalUidsCache,yield this._getExternalIdsByOkIds(e))})}authorize(){return c(this,null,function*(){if(!this._uuid){let t=qe.get("uuid");t||(t=T.uuid(),qe.set("uuid",t)),this._uuid=String(t)}let e={session_data:{version:2,device_id:this._uuid,client_version:p.appVersion,client_type:"SDK_JS"}};return p.authToken&&(e.session_data.auth_token=p.authToken,e.session_data.version=3),this._callUnsafe("auth.anonymLogin",e,!0).then(t=>{t.uid&&(this._userId=Number(t.uid)),ie.sessionKey=t.session_key,ie.sessionSecretKey=t.session_secret_key}).catch(t=>{throw t.error_code===401&&E.onTokenExpired(),new x(ne.AUTH,{message:t.error_msg,code:t.error_code})})})}log(e){let t={collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${p.appName}:${p.sdkVersion}`,platform:p.platform,items:e})};ur("log.externalLog",t)}init(){Hn()}joinConversation(e,t=!1,i){return c(this,null,function*(){let r={conversationId:e,isVideo:t};return i&&(r.chatId=i),this._call("vchat.joinConversation",r)})}createConversation(e,t="",i=!1){return c(this,null,function*(){let r={conversationId:e,createJoinLink:!0,isVideo:!1};return t&&(r.payload=t),p.domain&&(r.domainId=p.domain),i&&(r.requireAuthToJoin=!0),this._startConversation(r)})}startConversation(e,t,i,r=!1,a="",s=!1,d=!1){return c(this,null,function*(){let l={conversationId:e,isVideo:r};if(t&&t.length)switch(i){case Le.USER:l.uids=t.join(",");break;case Le.GROUP:l.gid=t[0];break;case Le.CHAT:l.chatId=t[0];break}return s&&(l.createJoinLink=!0),a&&(l.payload=a),p.domain&&(l.domainId=p.domain),d&&(l.requireAuthToJoin=!0),this._startConversation(l)})}_startConversation(e){return c(this,null,function*(){return this._call("vchat.startConversation",e)})}createJoinLink(e){return c(this,null,function*(){return this._call("vchat.createJoinLink",{conversationId:e})})}removeJoinLink(e){return c(this,null,function*(){return this._call("vchat.removeJoinLink",{conversationId:e})})}getAnonymTokenByLink(e,t){return c(this,null,function*(){let i={joinLink:e};t&&(i.anonymName=t);let r=yield this._call("vchat.getAnonymTokenByLink",i);return this._userId=Number(r.uid),r.token})}joinConversationByLink(e,t=!1){return c(this,null,function*(){let i={joinLink:e,isVideo:t};return p.anonymToken&&(i.anonymToken=p.anonymToken),this._call("vchat.joinConversationByLink",i)})}getOkIdsByExternalIds(e){return c(this,null,function*(){let t=re.fromIds(e),i=[],r={methods:[]},a=[],s=Object.keys(this._externalUidsCache),d=Object.values(this._externalUidsCache);for(let u of t){let g=re.toString(u),f=d.indexOf(g);f>-1?i.push(Number(s[f])):(a.push(g),r.methods.push({"vchat.getOkIdByExternalId":{params:{externalId:u.id,anonym:u.type===at.ANONYM},onError:"SKIP"}}))}return r.methods.length&&(yield this._call("batch.executeV2",r)).forEach((u,g)=>{if(u.ok){let f=Number(u.ok.ok_id);this._externalUidsCache[f]=a[g],i.push(f)}}),i})}getExternalIdsByOkIds(e){return c(this,null,function*(){let t=[],i=[];for(let a of e)this._externalUidsCache.hasOwnProperty(a)?t.push(re.fromString(this._externalUidsCache[a])):i.push(a);if(!i.length)return t;let r=yield this._getExternalIdsByOkIds(i);Object.assign(this._externalUidsCache,r);for(let a of i)r.hasOwnProperty(a)&&t.push(re.fromString(r[a]));return t})}getCachedOkIdByExternalId(e){let t=Object.keys(this._externalUidsCache),i=Object.values(this._externalUidsCache),r=re.toString(e),a=i.indexOf(r);return a>-1?T.composeId(t[a],X.USER):null}cacheExternalId(e,t){let i=T.decomposeId(e).id;this._externalUidsCache[i]=re.toString(t)}getConversationParams(e){return c(this,null,function*(){let t={};return p.anonymToken&&(t.anonymToken=p.anonymToken),e&&(t.conversationId=e),this._call("vchat.getConversationParams",t)})}getUserId(){return this._userId}setUserId(e){this._userId=e}hangupConversation(e){let t={conversationId:e,reason:P.HUNGUP};p.anonymToken&&(t.anonymToken=p.anonymToken),ur("vchat.hangupConversation",t)}removeHistoryRecords(e){return c(this,null,function*(){yield this._call("vchat.removeHistoryRecords",{recordIds:e.join(",")})})}cleanup(){}_getExternalIdsByOkIds(e){return c(this,null,function*(){let t={};try{let i=yield this._call("vchat.getExternalIdsByOkIds",{uids:e.join(",")});if(i.external_ids)for(let[r,a]of Object.entries(i.external_ids))t[r]=re.fromIdToString(a,at.USER);if(i.anonym_ids)for(let[r,a]of Object.entries(i.anonym_ids))t[r]=re.fromIdToString(a,at.ANONYM);return t}catch(i){return t}})}getTokenForAnonym(e,t){return c(this,null,function*(){let i={id:e};return t&&(i.application_key=t),(yield this._callUnsafe("auth.getTokenForAnonym",i,!0)).token})}call(i){return c(this,arguments,function*(e,t={}){return this._call(e,t)})}};var jn=(A=>(A.RECOVER="recover",A.ACCEPT_CALL="accept-call",A.ADD_PARTICIPANT="add-participant",A.REMOVE_PARTICIPANT="remove-participant",A.HANGUP="hangup",A.TRANSMIT_DATA="transmit-data",A.ACCEPT_PRODUCER="accept-producer",A.ALLOCATE_CONSUMER="allocate-consumer",A.CHANGE_MEDIA_SETTINGS="change-media-settings",A.CHANGE_PARTICIPANT_STATE="change-participant-state",A.CHANGE_STREAM_PRIORITIES="change-streams-priorities",A.UPDATE_DISPLAY_LAYOUT="update-display-layout",A.REPORT_PERF_STAT="report-perf-stat",A.RECORD_START="record-start",A.RECORD_STOP="record-stop",A.RECORD_SET_ROLE="record-set-role",A.RECORD_GET_STATUS="record-get-status",A.SWITCH_MICRO="switch-micro",A.SWITCH_TOPOLOGY="switch-topology",A.REQUEST_REALLOC="request-realloc",A.CHAT_MESSAGE="chat-message",A.CHAT_HISTORY="chat-history",A.CUSTOM_DATA="custom-data",A.GRANT_ROLES="grant-roles",A.MUTE_PARTICIPANT="mute-participant",A.PIN_PARTICIPANT="pin-participant",A.UPDATE_MEDIA_MODIFIERS="update-media-modifiers",A.CHANGE_OPTIONS="change-options",A.GET_WAITING_HALL="get-waiting-hall",A.PROMOTE_PARTICIPANT="promote-participant",A.REQUEST_TEST_MODE="request-test-mode",A.ADD_MOVIE="add-movie",A.UPDATE_MOVIE="update-movie",A.REMOVE_MOVIE="remove-movie",A))(jn||{}),G=jn;var Kn="open",$n=[()=>p.producerScreenTrack,()=>p.videoTracksCount>0,()=>!0,()=>p.filteredMessages,()=>p.consumerScreenTrack,()=>!0,()=>p.movieShare],Fs=10,we=class extends ut{constructor(){super(...arguments);this.socket=null;this.sequence=1;this.lastStamp=0;this.websocketCommandsQueue=[];this.datachannelCommandsQueue=[];this.incomingCache=[];this.responseHandlers={};this.reconnectCount=0;this.conversationResolve=null;this.conversationReject=null;this.connected=!1;this.listenersReady=!1;this.postfix="&platform="+p.platform+"&appVersion="+p.appVersion+"&version="+p.protocolVersion+"&device="+p.device+"&capabilities="+we._getCapabilityFlags();this.peerId=null;this.conversationId=null;this.reconnectTimer=0;this.connectionMessageWaitTimer=0;this.doctorTimer=0;this.participantIdRegistry=null;this.producerNotificationDataChannel=null;this.producerCommandDataChannel=null}static _getCapabilityFlags(){let e=0;for(let t=0;t<$n.length;t++)$n[t]()&&(e|=1<<t);return e.toString(16).toUpperCase()}get ready(){return this.socket!==null}setEndpoint(e){this.endpoint=e}setConversationId(e){this.conversationId=e}setParticipantIdRegistry(e){this.participantIdRegistry=e}setProducerNotificationDataChannel(e){this.producerNotificationDataChannel=e,this.producerNotificationDataChannel.onmessage=t=>{var r;let i=(r=this.participantIdRegistry)==null?void 0:r.handleMessage(t.data);i&&this._handleMessage(i)}}setProducerCommandDataChannel(e){this.producerCommandDataChannel=e,this.producerCommandDataChannel.onmessage=this._onMessage.bind(this),this._handleCommandsQueue(this.datachannelCommandsQueue)}cleanup(){this.datachannelCommandsQueue=[]}connect(e){return c(this,null,function*(){return this.postfix+=`&clientType=${p.clientType}`,new Promise((t,i)=>{if(this.socket&&this.socket.readyState<WebSocket.CLOSING){m.log(_.SOCKET_ACTION,"already_opened"),i(Error("Socket already opened"));return}this.conversationResolve=r=>{t(r),this.conversationResolve=null,this.conversationReject=null},this.conversationReject=r=>{i(r),this.conversationResolve=null,this.conversationReject=null},this._connect(e)})})}_send(r){return c(this,arguments,function*(e,t={},i=0){if(t.participantId){let a=T.decomposeId(t.participantId);t=Object.assign({},t,{participantId:a.id,participantType:a.type})}return this._sendRaw(e,t,i)})}_sendRaw(r){return c(this,arguments,function*(e,t={},i=0){let a=s=>{var l;if(this._isDataChannelCommand(e))this.datachannelCommandsQueue.push(s),((l=this.producerCommandDataChannel)==null?void 0:l.readyState)===Kn&&this._handleCommandsQueue(this.datachannelCommandsQueue);else{if(!this.socket){m.log(_.SOCKET_ACTION,"not_opened"),o.warn("Socket not opened"),s.reject(new Error(`Socket not opened [${e}]`),!0);return}this.socket.readyState>WebSocket.OPEN&&(m.log(_.SOCKET_ACTION,"invalid_state"),o.warn(`Socket is not opened, state ${this.socket.readyState}`)),this.websocketCommandsQueue.push(s),this.socket&&this.socket.readyState===WebSocket.OPEN&&this._handleCommandsQueue(this.websocketCommandsQueue)}};return new Promise((s,d)=>{let l=(g,f=!1)=>{!i||f?d(g):(o.debug("Resending a signaling message",e,u.sequence),i--,a(u))},u={sequence:this.sequence++,name:e,params:t,responseTimer:0,resolve:s,reject:l};a(u)})})}_isDataChannelCommand(e){return this.producerCommandDataChannel?e===G.UPDATE_DISPLAY_LAYOUT||e===G.REPORT_PERF_STAT:!1}static _isDataChannelResponseRequired(e){return e===G.UPDATE_DISPLAY_LAYOUT||e===G.REPORT_PERF_STAT}getNextCommandSequenceNumber(){return this.sequence}hangup(e){return c(this,null,function*(){return this._send(G.HANGUP,{reason:e}).catch(()=>{})})}sendCandidate(e,t){return c(this,null,function*(){return this._send(G.TRANSMIT_DATA,{participantId:e,data:{candidate:t}})})}requestTestMode(e){return c(this,null,function*(){return this._send(G.REQUEST_TEST_MODE,{consumerCommand:e})})}sendSdp(e,t){return c(this,null,function*(){return this._send(G.TRANSMIT_DATA,{participantId:e,data:{sdp:t}})})}acceptCall(e){return c(this,null,function*(){return this._send(G.ACCEPT_CALL,{mediaSettings:e})})}changeMediaSettings(e){return c(this,null,function*(){return this._send(G.CHANGE_MEDIA_SETTINGS,{mediaSettings:e},Fs)})}changeParticipantState(e){return c(this,null,function*(){return this._send(G.CHANGE_PARTICIPANT_STATE,{participantState:{state:e}})})}addParticipant(e,t){return c(this,null,function*(){return this._send(G.ADD_PARTICIPANT,Er({participantId:e},t))})}removeParticipant(e,t=!1){return c(this,null,function*(){return this._send(G.REMOVE_PARTICIPANT,{participantId:e,ban:t})})}allocateConsumer(e,t){return c(this,null,function*(){let i={capabilities:t};return e&&(i.description=e.sdp),this._send(G.ALLOCATE_CONSUMER,i)})}acceptProducer(e,t){return c(this,null,function*(){let i={description:e.sdp};return t&&(i.ssrcs=t),this._send(G.ACCEPT_PRODUCER,i)})}changePriorities(e){return c(this,null,function*(){return this._send(G.CHANGE_STREAM_PRIORITIES,{typedPriorities:e}).catch(()=>{})})}updateDisplayLayout(e){return c(this,null,function*(){return this._send(G.UPDATE_DISPLAY_LAYOUT,{layouts:e})})}addMovie(e){return c(this,null,function*(){return this._send(G.ADD_MOVIE,e)})}updateMovie(e){return c(this,null,function*(){return this._send(G.UPDATE_MOVIE,e)})}removeMovie(e){return c(this,null,function*(){return this._send(G.REMOVE_MOVIE,e)})}startStream(e){return c(this,null,function*(){return this._send(G.RECORD_START,e)})}stopStream(){return c(this,null,function*(){return this._send(G.RECORD_STOP)})}recordSetRole(e,t){return c(this,null,function*(){return this._send(G.RECORD_SET_ROLE,{participantId:e,role:t})})}getRecordStatus(){return c(this,null,function*(){return this._send(G.RECORD_GET_STATUS)})}switchTopology(e,t=!1){return c(this,null,function*(){return this._send(G.SWITCH_TOPOLOGY,{topology:e,force:t})})}requestRealloc(){return c(this,null,function*(){return this._send(G.REQUEST_REALLOC)})}reportPerfStat(e){return c(this,null,function*(){return this._send(G.REPORT_PERF_STAT,{report:e})})}chatMessage(e,t=null){return c(this,null,function*(){return this._send(G.CHAT_MESSAGE,{message:e,participantId:t})})}chatHistory(e){return c(this,null,function*(){return this._send(G.CHAT_HISTORY,{count:e})})}customData(e,t){return c(this,null,function*(){return this._send(G.CUSTOM_DATA,{data:e,participantId:t})})}grantRoles(e,t,i){return c(this,null,function*(){let r={participantId:e,roles:t};return i&&(r.revoke=!0),this._sendRaw(G.GRANT_ROLES,r)})}muteParticipant(e,t,i){return c(this,null,function*(){return this._sendRaw(G.MUTE_PARTICIPANT,{participantId:e,muteStates:t,requestedMedia:i})})}pinParticipant(e,t){return c(this,null,function*(){let i={participantId:e};return t&&(i.unpin=!0),this._sendRaw(G.PIN_PARTICIPANT,i)})}updateMediaModifiers(e){return c(this,null,function*(){return this._send(G.UPDATE_MEDIA_MODIFIERS,{mediaModifiers:e})})}changeOptions(e){return c(this,null,function*(){return this._send(G.CHANGE_OPTIONS,{options:e})})}getWaitingHall(e=null,t,i=!1){return c(this,null,function*(){let r={};return e&&(r.fromId=e),t&&(r.count=t),i&&(r.backward=i),this._send(G.GET_WAITING_HALL,r)})}promoteParticipant(e,t=!1){return c(this,null,function*(){let i={participantId:e};return t&&(i.demote=t),this._sendRaw(G.PROMOTE_PARTICIPANT,i)})}close(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&this._closeSocket(),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}readyToSend(){this.listenersReady=!0,this._handleCachedMessages()}_connect(e){if(this.socket&&this.socket.readyState<WebSocket.CLOSING)return;let t="";e&&(t+=`&tgt=${e}`),e===Ue.RETRY&&this.lastStamp&&(t+=`&recoverTs=${this.lastStamp}`),o.debug("Connecting to "+this.endpoint+this.postfix+t),this.socket=new WebSocket(this.endpoint+this.postfix+t),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this._startDoctor()}_disconnect(){this.socket&&this.socket.readyState<WebSocket.CLOSING&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.socket.close(),this.socket=null),this._stopWaitConnectionMessage(),this._stopDoctor(),clearTimeout(this.reconnectTimer)}_onOpen(){o.debug("Socket opened"),m.log(_.SOCKET_ACTION,"opened"),this._waitConnectionMessage(),this._startDoctor()}_onMessage(e){if(this._startDoctor(),e.data==="ping"){this.socket&&this.socket.readyState===WebSocket.OPEN&&this.socket.send("pong");return}try{this._handleMessage(JSON.parse(e.data))}catch(t){m.log(_.SOCKET_ACTION,"parse_error"),o.error("Unable to parse message",t,e.data)}}_handleMessage(e){var t;e.type==="notification"?e.notification==="connection"?(o.debug("Signaling connected",e),this.connected=!0,this.reconnectCount=0,this.endpoint=e.endpoint,e.peerId&&this.peerId!==e.peerId.id&&(this.postfix+=`&peerId=${e.peerId.id}`,this.peerId=e.peerId.id),this._stopWaitConnectionMessage(),this.conversationResolve?this.conversationResolve(e):(this._triggerEvent(fe.RECONNECT,e),e.conversation.topology&&this._triggerEvent(fe.NOTIFICATION,{type:"notification",notification:O.TOPOLOGY_CHANGED,topology:e.conversation.topology})),this.lastStamp&&this._handleCachedMessages(),(t=e.recoverMessages)==null||t.forEach(i=>this._handleMessage(i)),this._handleCommandsQueue(this.websocketCommandsQueue)):!this.connected||!this.listenersReady?this.incomingCache.push(e):this._triggerEvent(fe.NOTIFICATION,e):e.type==="response"&&this.responseHandlers[e.sequence]?this._handleCommandResponse(!0,e):e.type==="error"&&this.responseHandlers[e.sequence]?(m.log(_.SOCKET_ACTION,`error-${e.error}`),this._handleCommandResponse(!1,e)):e.type==="error"?(m.log(_.SOCKET_ACTION,`error-${e.error}`),e.error==="service-unavailable"?this._reconnect():e.error==="conversation-ended"?this.conversationReject?this.conversationReject(new x(P.SOCKET_CLOSED,{message:`Unable to connect to the signaling: ${e.error}`})):this._triggerEvent(fe.NOTIFICATION,{notification:O.CLOSED_CONVERSATION,reason:e.reason}):this.connected||e.error==="invalid-token"?this._throwError(new Error(`Signaling error: ${e.error}`)):e.sequence||(this.conversationReject&&this.conversationReject(new x(ne.SIGNALING_FAILED,{message:`Unable to connect to the signaling: ${e.error}`})),this._closeSocket())):(m.log(_.SOCKET_ACTION,"unknown_message"),o.warn("Unhandled message",e)),this.lastStamp=e.stamp||this.lastStamp}_handleCachedMessages(){let e=[...this.incomingCache];for(this.incomingCache=[];e.length>0;){let t=e.shift();this._handleMessage(t)}}_throwError(e){this._triggerEvent(fe.FAILED,e)}_onError(e){m.log(_.SOCKET_ACTION,"error"),o.error("Signaling error",e)}_onClose(e){m.log(_.SOCKET_ACTION,"closed"),o.debug("Connection closed",{code:e.code,reason:e.reason}),this.connected=!1,this._stopDoctor(),this.socket&&this.reconnectCount++<we.RECONNECT_MAX_COUNT?this._reconnect():this.socket&&this._closeSocket(new Error("Connection closed"))}_closeSocket(e=null){!this.socket||(this._disconnect(),Object.values(this.responseHandlers).forEach(t=>{window.clearTimeout(t.responseTimer),e&&t.reject(new Error("Connection closed"),!0)}),this.websocketCommandsQueue=[],this.responseHandlers={},this.lastStamp=0,e&&this._throwError(new Error("Connection closed")))}_reconnect(){let e=Math.min(we.RECONNECT_MAX_DELAY,we.RECONNECT_DELAY*Math.pow(2,this.reconnectCount-1));o.log(`Reconnect websocket after ${e}ms (${this.reconnectCount})`),m.log(_.SOCKET_ACTION,"reconnect"),this.reconnectTimer=window.setTimeout(this._connect.bind(this,Ue.RETRY),e)}_handleCommandResponse(e,t){var r;if(!this.responseHandlers.hasOwnProperty(t.sequence))return;let i=this.responseHandlers[t.sequence];window.clearTimeout(i.responseTimer),e?(delete this.responseHandlers[t.sequence],i.resolve(t)):((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN?(delete this.responseHandlers[t.sequence],m.log(_.SOCKET_ACTION,"response-timeout"),i.reject(new Error(t.error||`Response timeout [${i.name}]`))):i.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,t),we.WAIT_RESPONSE_DELAY)}_handleCommandsQueue(e){var t,i;for(;e.length>0;){let r=e.shift(),a=Object.assign({command:r.name,sequence:r.sequence},r.params);if(this._isDataChannelCommand(r.name)){if(((t=this.producerCommandDataChannel)==null?void 0:t.readyState)!==Kn){r.reject(new Error(`Invalid data channel state: ${(i=this.producerCommandDataChannel)==null?void 0:i.readyState}`));return}we._isDataChannelResponseRequired(r.name)&&(r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,a),we.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r),this.producerCommandDataChannel.send(JSON.stringify(a))}else{if(!this.socket||this.socket.readyState!==WebSocket.OPEN){r.reject(new Error("Invalid state or socket already closed"));continue}r.responseTimer=window.setTimeout(()=>this._handleCommandResponse(!1,a),we.WAIT_RESPONSE_DELAY),this.responseHandlers[r.sequence]=r,this.socket.send(JSON.stringify(a))}}}_waitConnectionMessage(){this.connectionMessageWaitTimer=window.setTimeout(()=>{this.conversationReject&&this.conversationReject(new x(ne.SIGNALING_FAILED,{message:"Unable to connect to the signaling: connection timeout"}))},we.WAIT_CONNECTION_DELAY)}_stopWaitConnectionMessage(){window.clearTimeout(this.connectionMessageWaitTimer),this.connectionMessageWaitTimer=0}_startDoctor(){this._stopDoctor(),this.doctorTimer=window.setTimeout(()=>{o.warn("Socket is dead, trying to reconnect"),this._disconnect(),this._connect(Ue.RETRY)},we.WAIT_MESSAGE_DELAY)}_stopDoctor(){window.clearTimeout(this.doctorTimer),this.doctorTimer=0}},xe=we;xe.RECONNECT_DELAY=p.signalingReconnectDelay,xe.RECONNECT_MAX_DELAY=p.signalingReconnectMaxDelay,xe.RECONNECT_MAX_COUNT=p.signalingReconnectMaxCount,xe.WAIT_CONNECTION_DELAY=p.waitConnectionDelay,xe.WAIT_RESPONSE_DELAY=p.waitResponseDelay,xe.WAIT_MESSAGE_DELAY=p.waitMessageDelay;var qn=(t=>(t.KING="KING",t.PAWN="PAWN",t))(qn||{}),Jn=qn;var Ct,ae,Vt=null,Vs={getCameras:y.getCameras,getMicrophones:y.getMicrophones,getOutput:y.getOutput,hasCamera:y.hasCamera,hasMicrophone:y.hasMicrophone,getSavedCamera:y.getSavedCamera,getSavedMicrophone:y.getSavedMicrophone,getSavedOutput:y.getSavedOutput,hasCameraPermission:y.hasCameraPermission,hasMicrophonePermission:y.hasMicrophonePermission,hasPermissions:y.hasPermissions,getUserMedia:y.getUserMedia,getUserVideo:y.getUserVideo,getUserAudio:y.getUserAudio,saveDeviceId:y.saveDeviceId,isBrowserSupported:y.isBrowserSupported,isScreenCapturingSupported:y.isScreenCapturingSupported,os:y.os,isMobile:y.isMobile,browserName:y.browserName,browserVersion:y.browserVersion,baseChromeVersion:y.baseChromeVersion,getAudioContext:y.getAudioContext};function Yn(n){ae=n}function zn(n){Ct=n}function Hs(n){Vt=n}function Gs(n){p.videoEffects=n}function Ws(n){return c(this,null,function*(){if(p.set(n),y.browserName()==="Sferum"&&(p.platform=`SFERUM:${y.browserVersion()}`),ae||Yn(new Ft),Ct||zn(()=>new xe),p.debug&&(hr.default.disableLog(!1),o.toggle(!0)),o.log(`Calls SDK ${p.sdkVersion}`,n),yield y.init(),!y.isBrowserSupported())throw new x(ne.UNSUPPORTED);ae.init()})}function js(a){return c(this,arguments,function*(n,e=[le.AUDIO],t="",i=!1,r=!1){let s=[],d=[];if(Array.isArray(n)?s=n.length?n:[]:n&&(s=[n]),s.length&&(d=yield ae.getOkIdsByExternalIds(s),!d.length))throw new x(P.CALLEE_IS_OFFLINE);return Qn(d,Le.USER,e,t,i,r)})}function Qn(s){return c(this,arguments,function*(n,e=Le.USER,t,i="",r=!1,a=!1){if(L.current())throw o.error("There is already active call"),new x(P.FAILED);return new L(ae,Ct(),Vt).onStart(n,e,t,i,r,a)})}function Ks(n){return c(this,null,function*(){return Xn(n)})}function Xn(i){return c(this,arguments,function*(n,e=X.USER,t){if(n===L.id())throw new Error("Push has already been processed");return new L(ae,Ct(),Vt).onPush(n,e,t)})}function $s(n,e){return c(this,null,function*(){return ae.getTokenForAnonym(n,e)})}function qs(t){return c(this,arguments,function*(n,e={}){return ae.call(n,e)})}function Js(n){return c(this,null,function*(){return n&&(p.authToken=n),ae.authorize()})}function Ys(){return c(this,arguments,function*(n=[le.AUDIO]){let e=L.current();if(e)return e.accept(n);throw new Error("Conversation not found")})}function zs(){return c(this,null,function*(){let n=L.current();if(n)return n.decline()})}function Qs(t){return c(this,arguments,function*(n,e=[le.AUDIO]){return Zn(n,e)})}function Zn(n,e,t){return c(this,null,function*(){if(L.current())throw o.error("There is already active call"),new x(P.FAILED);return new L(ae,Ct(),Vt).onJoin({conversationId:n,mediaOptions:e,chatId:t})})}function Xs(i){return c(this,arguments,function*(n,e=[le.AUDIO],t){if(L.current())throw o.error("There is already active call"),new x(P.FAILED);return t&&(p.anonymToken=t),new L(ae,Ct(),Vt).onJoin({joinLink:n,mediaOptions:e})})}function Zs(){return c(this,null,function*(){let n=L.current();if(n)return n.hangup();L.hangupAfterInit()})}function eo(n,e){return c(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([n]);if(!t.length)throw new Error("User not found");return ea(t[0],e)})}function ea(n,e){return c(this,null,function*(){let t=L.current();t&&(yield t.addParticipant(T.composeId(n,X.USER),e))})}function to(n,e=!1){return c(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([n]);return ta(t[0],e)})}function ta(n,e=!1){return c(this,null,function*(){let t=L.current();t&&(yield t.removeParticipant(T.composeId(n,X.USER),e))})}function io(n,e){return c(this,null,function*(){let t=yield y.saveDeviceId(n,e),i=L.current();return t&&i?i.changeDevice(n):Promise.reject()})}function ro(n){return c(this,null,function*(){let e=L.current();return e?e.toggleScreenCapturing(n):Promise.reject()})}function no(n,e=!1){return c(this,null,function*(){let t=L.current();t&&(yield t.setVideoStream(n,e))})}function ao(n){return c(this,null,function*(){let e=L.current();e&&(yield e.toggleLocalVideo(n))})}function so(n){return c(this,null,function*(){let e=L.current();e&&(yield e.toggleLocalAudio(n))})}function oo(n,e,t){return c(this,null,function*(){let i=L.current();if(i)return i.setLocalResolution(n,e,t)})}function co(n){return c(this,null,function*(){let e=L.current();e&&(yield e.changePriorities(n))})}function po(n){return c(this,null,function*(){let e=L.current();e&&(yield e.changeParticipantState(n))})}function lo(n){return c(this,null,function*(){let e=L.current();e&&(yield e.updateDisplayLayout(n))})}function uo(n,e,t=!1){return c(this,null,function*(){let i=yield ae.getOkIdsByExternalIds([n]);return ia(i[0],e,t)})}function ia(n,e,t=!1){return c(this,null,function*(){let i=L.current();i&&(yield i.grantRoles(T.composeId(n,X.USER),e,t))})}function ho(){return c(this,arguments,function*(n=null,e,t=[]){let i=null;return n&&(i=(yield ae.getOkIdsByExternalIds([n]))[0]),ra(i,e,t)})}function ra(){return c(this,arguments,function*(n=null,e,t=[]){let i=L.current();if(i){let r=n?T.composeId(n,X.USER):null;yield i.muteParticipant(r,e,t)}})}function mo(n,e=!1){return c(this,null,function*(){let t=yield ae.getOkIdsByExternalIds([n]);return na(t[0],e)})}function na(n,e=!1){return c(this,null,function*(){let t=L.current();t&&(yield t.pinParticipant(T.composeId(n,X.USER),e))})}function go(n){return c(this,null,function*(){let e=L.current();e&&(yield e.updateMediaModifiers(n))})}function _o(n){return c(this,null,function*(){let e=L.current();e&&(yield e.changeOptions(n))})}function fo(n,e=null){return c(this,null,function*(){let t=null;return e&&(t=(yield ae.getOkIdsByExternalIds([e]))[0]),aa(n,t)})}function aa(n,e=null){return c(this,null,function*(){let t=L.current();if(t){let i=e?T.composeId(e,X.USER):null;yield t.chatMessage(n,i)}})}function So(n=10){return c(this,null,function*(){let e=L.current();if(e)return e.chatHistory(n)})}function vo(n,e=null){return c(this,null,function*(){let t=null;return e&&(t=(yield ae.getOkIdsByExternalIds([e]))[0]),sa(n,t)})}function sa(n,e=null){return c(this,null,function*(){let t=L.current();if(t){let i=e?T.composeId(e,X.USER):null;yield t.customData(n,i)}})}function Eo(n="",e=!1){return c(this,null,function*(){return(yield ae.createConversation(T.uuid(),n,e)).join_link})}function To(){return c(this,null,function*(){let n=L.current();return n?n.createJoinLink():Promise.reject()})}function Co(){return c(this,null,function*(){let n=L.current();return n?n.removeJoinLink():Promise.reject()})}function Io(n,e){return c(this,null,function*(){return ae.getAnonymTokenByLink(n,e)})}function yo(n){let e=L.current();e&&e.setVolume(n)}function Ro(n){p.forceRelayPolicy=n}function bo(n=!1,e=null,t=null,i="DIRECT_LINK",r=null){return c(this,null,function*(){let a=L.current();return a?a.startStream(n,e,t,i,r):Promise.reject()})}function Po(){return c(this,null,function*(){let n=L.current();return n?n.stopStream():Promise.reject()})}function Mo(n,e){return c(this,null,function*(){let t=L.current();if(t){let i=yield ae.getOkIdsByExternalIds([n]);return t.recordSetRole(T.composeId(i[0],X.USER),e)}return Promise.reject()})}function Ao(){return c(this,null,function*(){let n=L.current();return n?n.getStreamInfo():Promise.reject()})}function Do(n){return c(this,null,function*(){let e=L.current();return e?e.addMovie(n):Promise.reject()})}function wo(n,e,t,i){return c(this,null,function*(){let r=L.current();return r?r.updateMovie(n,e,t,i):Promise.reject()})}function Oo(n){return c(this,null,function*(){let e=L.current();return e?e.removeMovie(n):Promise.reject()})}function ko(n){p.statisticsInterval=n;let e=L.current();if(e)return e.updateStatisticsInterval()}function xo(n){hr.default.disableLog(!n),o.toggle(n)}function No(n,...e){!p.debugLog||o.send(n,"[external]",...e)}function Lo(n){return c(this,null,function*(){let e=L.current();if(e)return e.videoEffect(n)})}function Uo(n){return c(this,null,function*(){let e=L.current();e&&(yield e.setAudioStream(n))})}function Bo(n=null,e,t=!1){return c(this,null,function*(){let i=L.current();if(!i)throw new Error("Conversation not found");return i.getWaitingHall(n,e,t)})}function Fo(n,e=!1){return c(this,null,function*(){let t=L.current();if(!t)throw new Error("Conversation not found");let i=yield ae.getOkIdsByExternalIds([n]);return t.promoteParticipant(T.composeId(i[0],X.USER),e)})}function Vo(n){return c(this,null,function*(){yield ae.removeHistoryRecords(n)})}function Ho(){return L.current()}
13
13
  /*!
14
14
  * The buffer module from node.js, for the browser.
15
15
  *