aliyun-rtc-sdk 7.2.1 → 7.3.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,217 @@
1
- (function(W,X){typeof exports=="object"&&typeof module!="undefined"?X(exports,require("aliyun-rts-sdk"),require("eventemitter3")):typeof define=="function"&&define.amd?define(["exports","aliyun-rts-sdk","eventemitter3"],X):X((W=typeof globalThis!="undefined"?globalThis:W||self).AliRtcEngine={},W.AliyunRts,W.EventEmitter)})(this,function(W,X,se){var St,Ge,Te,Ht,Ft,Ze,$,Tn;"use strict";var et=(s=>(s.EnableNonOnePcDefaultJoinMode="h5_enable_non_one_pc_default_join_mode",s))(et||{});function ui(s,a,e){Object.defineProperty(s,a,{writable:!0,enumerable:!0,configurable:!0,value:e})}function Mi(s,a,e,t){t?t(()=>{ui(s,a,e)}):ui(s,a,e)}Array(32);var ti=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function pi(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Ct(s){if(s.__esModule)return s;var a=s.default;if(typeof a=="function"){var e=function t(){return this instanceof t?Reflect.construct(a,arguments,this.constructor):a.apply(this,arguments)};e.prototype=a.prototype}else e={};return Object.defineProperty(e,"__esModule",{value:!0}),Object.keys(s).forEach(function(t){var i=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:function(){return s[t]}})}),e}var ii={exports:{}},es={exports:{}};const Vn=Ct(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var ts;function pe(){return ts||(ts=1,function(s){s.exports=function(){var a=a||function(e,t){var i;if(typeof window!="undefined"&&window.crypto&&(i=window.crypto),typeof self!="undefined"&&self.crypto&&(i=self.crypto),typeof globalThis!="undefined"&&globalThis.crypto&&(i=globalThis.crypto),!i&&typeof window!="undefined"&&window.msCrypto&&(i=window.msCrypto),!i&&ti!==void 0&&ti.crypto&&(i=ti.crypto),!i)try{i=Vn}catch(S){}var r=function(){if(i){if(typeof i.getRandomValues=="function")try{return i.getRandomValues(new Uint32Array(1))[0]}catch(S){}if(typeof i.randomBytes=="function")try{return i.randomBytes(4).readInt32LE()}catch(S){}}throw new Error("Native crypto module could not be used to get secure random number.")},n=Object.create||function(){function S(){}return function(v){var R;return S.prototype=v,R=new S,S.prototype=null,R}}(),c={},o=c.lib={},l=o.Base={extend:function(S){var v=n(this);return S&&v.mixIn(S),v.hasOwnProperty("init")&&this.init!==v.init||(v.init=function(){v.$super.init.apply(this,arguments)}),v.init.prototype=v,v.$super=this,v},create:function(){var S=this.extend();return S.init.apply(S,arguments),S},init:function(){},mixIn:function(S){for(var v in S)S.hasOwnProperty(v)&&(this[v]=S[v]);S.hasOwnProperty("toString")&&(this.toString=S.toString)},clone:function(){return this.init.prototype.extend(this)}},d=o.WordArray=l.extend({init:function(S,v){S=this.words=S||[],this.sigBytes=v!=t?v:4*S.length},toString:function(S){return(S||p).stringify(this)},concat:function(S){var v=this.words,R=S.words,w=this.sigBytes,y=S.sigBytes;if(this.clamp(),w%4)for(var A=0;A<y;A++){var _=R[A>>>2]>>>24-A%4*8&255;v[w+A>>>2]|=_<<24-(w+A)%4*8}else for(var E=0;E<y;E+=4)v[w+E>>>2]=R[E>>>2];return this.sigBytes+=y,this},clamp:function(){var S=this.words,v=this.sigBytes;S[v>>>2]&=4294967295<<32-v%4*8,S.length=e.ceil(v/4)},clone:function(){var S=l.clone.call(this);return S.words=this.words.slice(0),S},random:function(S){for(var v=[],R=0;R<S;R+=4)v.push(r());return new d.init(v,S)}}),h=c.enc={},p=h.Hex={stringify:function(S){for(var v=S.words,R=S.sigBytes,w=[],y=0;y<R;y++){var A=v[y>>>2]>>>24-y%4*8&255;w.push((A>>>4).toString(16)),w.push((15&A).toString(16))}return w.join("")},parse:function(S){for(var v=S.length,R=[],w=0;w<v;w+=2)R[w>>>3]|=parseInt(S.substr(w,2),16)<<24-w%8*4;return new d.init(R,v/2)}},u=h.Latin1={stringify:function(S){for(var v=S.words,R=S.sigBytes,w=[],y=0;y<R;y++){var A=v[y>>>2]>>>24-y%4*8&255;w.push(String.fromCharCode(A))}return w.join("")},parse:function(S){for(var v=S.length,R=[],w=0;w<v;w++)R[w>>>2]|=(255&S.charCodeAt(w))<<24-w%4*8;return new d.init(R,v)}},f=h.Utf8={stringify:function(S){try{return decodeURIComponent(escape(u.stringify(S)))}catch(v){throw new Error("Malformed UTF-8 data")}},parse:function(S){return u.parse(unescape(encodeURIComponent(S)))}},m=o.BufferedBlockAlgorithm=l.extend({reset:function(){this._data=new d.init,this._nDataBytes=0},_append:function(S){typeof S=="string"&&(S=f.parse(S)),this._data.concat(S),this._nDataBytes+=S.sigBytes},_process:function(S){var v,R=this._data,w=R.words,y=R.sigBytes,A=this.blockSize,_=y/(4*A),E=(_=S?e.ceil(_):e.max((0|_)-this._minBufferSize,0))*A,T=e.min(4*E,y);if(E){for(var k=0;k<E;k+=A)this._doProcessBlock(w,k);v=w.splice(0,E),R.sigBytes-=T}return new d.init(v,T)},clone:function(){var S=l.clone.call(this);return S._data=this._data.clone(),S},_minBufferSize:0});o.Hasher=m.extend({cfg:l.extend(),init:function(S){this.cfg=this.cfg.extend(S),this.reset()},reset:function(){m.reset.call(this),this._doReset()},update:function(S){return this._append(S),this._process(),this},finalize:function(S){return S&&this._append(S),this._doFinalize()},blockSize:16,_createHelper:function(S){return function(v,R){return new S.init(R).finalize(v)}},_createHmacHelper:function(S){return function(v,R){return new b.HMAC.init(S,R).finalize(v)}}});var b=c.algo={};return c}(Math);return a}()}(es)),es.exports}var is,rs={exports:{}};function Li(){return is||(is=1,function(s){s.exports=function(a){return i=(t=a).lib,r=i.Base,n=i.WordArray,(c=t.x64={}).Word=r.extend({init:function(o,l){this.high=o,this.low=l}}),c.WordArray=r.extend({init:function(o,l){o=this.words=o||[],this.sigBytes=l!=e?l:8*o.length},toX32:function(){for(var o=this.words,l=o.length,d=[],h=0;h<l;h++){var p=o[h];d.push(p.high),d.push(p.low)}return n.create(d,this.sigBytes)},clone:function(){for(var o=r.clone.call(this),l=o.words=this.words.slice(0),d=l.length,h=0;h<d;h++)l[h]=l[h].clone();return o}}),a;var e,t,i,r,n,c}(pe())}(rs)),rs.exports}var ss,as={exports:{}};function Un(){return ss||(ss=1,function(s){s.exports=function(a){return function(){if(typeof ArrayBuffer=="function"){var e=a.lib.WordArray,t=e.init,i=e.init=function(r){if(r instanceof ArrayBuffer&&(r=new Uint8Array(r)),(r instanceof Int8Array||typeof Uint8ClampedArray!="undefined"&&r instanceof Uint8ClampedArray||r instanceof Int16Array||r instanceof Uint16Array||r instanceof Int32Array||r instanceof Uint32Array||r instanceof Float32Array||r instanceof Float64Array)&&(r=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),r instanceof Uint8Array){for(var n=r.byteLength,c=[],o=0;o<n;o++)c[o>>>2]|=r[o]<<24-o%4*8;t.call(this,c,n)}else t.apply(this,arguments)};i.prototype=e}}(),a.lib.WordArray}(pe())}(as)),as.exports}var ns,os={exports:{}};function Bn(){return ns||(ns=1,function(s){s.exports=function(a){return function(){var e=a,t=e.lib.WordArray,i=e.enc;function r(n){return n<<8&4278255360|n>>>8&16711935}i.Utf16=i.Utf16BE={stringify:function(n){for(var c=n.words,o=n.sigBytes,l=[],d=0;d<o;d+=2){var h=c[d>>>2]>>>16-d%4*8&65535;l.push(String.fromCharCode(h))}return l.join("")},parse:function(n){for(var c=n.length,o=[],l=0;l<c;l++)o[l>>>1]|=n.charCodeAt(l)<<16-l%2*16;return t.create(o,2*c)}},i.Utf16LE={stringify:function(n){for(var c=n.words,o=n.sigBytes,l=[],d=0;d<o;d+=2){var h=r(c[d>>>2]>>>16-d%4*8&65535);l.push(String.fromCharCode(h))}return l.join("")},parse:function(n){for(var c=n.length,o=[],l=0;l<c;l++)o[l>>>1]|=r(n.charCodeAt(l)<<16-l%2*16);return t.create(o,2*c)}}}(),a.enc.Utf16}(pe())}(os)),os.exports}var cs,ls={exports:{}};function zt(){return cs||(cs=1,function(s){s.exports=function(a){return function(){var e=a,t=e.lib.WordArray;function i(r,n,c){for(var o=[],l=0,d=0;d<n;d++)if(d%4){var h=c[r.charCodeAt(d-1)]<<d%4*2|c[r.charCodeAt(d)]>>>6-d%4*2;o[l>>>2]|=h<<24-l%4*8,l++}return t.create(o,l)}e.enc.Base64={stringify:function(r){var n=r.words,c=r.sigBytes,o=this._map;r.clamp();for(var l=[],d=0;d<c;d+=3)for(var h=(n[d>>>2]>>>24-d%4*8&255)<<16|(n[d+1>>>2]>>>24-(d+1)%4*8&255)<<8|n[d+2>>>2]>>>24-(d+2)%4*8&255,p=0;p<4&&d+.75*p<c;p++)l.push(o.charAt(h>>>6*(3-p)&63));var u=o.charAt(64);if(u)for(;l.length%4;)l.push(u);return l.join("")},parse:function(r){var n=r.length,c=this._map,o=this._reverseMap;if(!o){o=this._reverseMap=[];for(var l=0;l<c.length;l++)o[c.charCodeAt(l)]=l}var d=c.charAt(64);if(d){var h=r.indexOf(d);h!==-1&&(n=h)}return i(r,n,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64}(pe())}(ls)),ls.exports}var ds,hs={exports:{}};function Hn(){return ds||(ds=1,function(s){s.exports=function(a){return function(){var e=a,t=e.lib.WordArray;function i(r,n,c){for(var o=[],l=0,d=0;d<n;d++)if(d%4){var h=c[r.charCodeAt(d-1)]<<d%4*2|c[r.charCodeAt(d)]>>>6-d%4*2;o[l>>>2]|=h<<24-l%4*8,l++}return t.create(o,l)}e.enc.Base64url={stringify:function(r,n){n===void 0&&(n=!0);var c=r.words,o=r.sigBytes,l=n?this._safe_map:this._map;r.clamp();for(var d=[],h=0;h<o;h+=3)for(var p=(c[h>>>2]>>>24-h%4*8&255)<<16|(c[h+1>>>2]>>>24-(h+1)%4*8&255)<<8|c[h+2>>>2]>>>24-(h+2)%4*8&255,u=0;u<4&&h+.75*u<o;u++)d.push(l.charAt(p>>>6*(3-u)&63));var f=l.charAt(64);if(f)for(;d.length%4;)d.push(f);return d.join("")},parse:function(r,n){n===void 0&&(n=!0);var c=r.length,o=n?this._safe_map:this._map,l=this._reverseMap;if(!l){l=this._reverseMap=[];for(var d=0;d<o.length;d++)l[o.charCodeAt(d)]=d}var h=o.charAt(64);if(h){var p=r.indexOf(h);p!==-1&&(c=p)}return i(r,c,l)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_safe_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"}}(),a.enc.Base64url}(pe())}(hs)),hs.exports}var us,ps={exports:{}};function Wt(){return us||(us=1,function(s){s.exports=function(a){return function(e){var t=a,i=t.lib,r=i.WordArray,n=i.Hasher,c=t.algo,o=[];(function(){for(var f=0;f<64;f++)o[f]=4294967296*e.abs(e.sin(f+1))|0})();var l=c.MD5=n.extend({_doReset:function(){this._hash=new r.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(f,m){for(var b=0;b<16;b++){var S=m+b,v=f[S];f[S]=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8)}var R=this._hash.words,w=f[m+0],y=f[m+1],A=f[m+2],_=f[m+3],E=f[m+4],T=f[m+5],k=f[m+6],P=f[m+7],H=f[m+8],q=f[m+9],Y=f[m+10],J=f[m+11],z=f[m+12],Z=f[m+13],ee=f[m+14],ge=f[m+15],D=R[0],x=R[1],L=R[2],O=R[3];D=d(D,x,L,O,w,7,o[0]),O=d(O,D,x,L,y,12,o[1]),L=d(L,O,D,x,A,17,o[2]),x=d(x,L,O,D,_,22,o[3]),D=d(D,x,L,O,E,7,o[4]),O=d(O,D,x,L,T,12,o[5]),L=d(L,O,D,x,k,17,o[6]),x=d(x,L,O,D,P,22,o[7]),D=d(D,x,L,O,H,7,o[8]),O=d(O,D,x,L,q,12,o[9]),L=d(L,O,D,x,Y,17,o[10]),x=d(x,L,O,D,J,22,o[11]),D=d(D,x,L,O,z,7,o[12]),O=d(O,D,x,L,Z,12,o[13]),L=d(L,O,D,x,ee,17,o[14]),D=h(D,x=d(x,L,O,D,ge,22,o[15]),L,O,y,5,o[16]),O=h(O,D,x,L,k,9,o[17]),L=h(L,O,D,x,J,14,o[18]),x=h(x,L,O,D,w,20,o[19]),D=h(D,x,L,O,T,5,o[20]),O=h(O,D,x,L,Y,9,o[21]),L=h(L,O,D,x,ge,14,o[22]),x=h(x,L,O,D,E,20,o[23]),D=h(D,x,L,O,q,5,o[24]),O=h(O,D,x,L,ee,9,o[25]),L=h(L,O,D,x,_,14,o[26]),x=h(x,L,O,D,H,20,o[27]),D=h(D,x,L,O,Z,5,o[28]),O=h(O,D,x,L,A,9,o[29]),L=h(L,O,D,x,P,14,o[30]),D=p(D,x=h(x,L,O,D,z,20,o[31]),L,O,T,4,o[32]),O=p(O,D,x,L,H,11,o[33]),L=p(L,O,D,x,J,16,o[34]),x=p(x,L,O,D,ee,23,o[35]),D=p(D,x,L,O,y,4,o[36]),O=p(O,D,x,L,E,11,o[37]),L=p(L,O,D,x,P,16,o[38]),x=p(x,L,O,D,Y,23,o[39]),D=p(D,x,L,O,Z,4,o[40]),O=p(O,D,x,L,w,11,o[41]),L=p(L,O,D,x,_,16,o[42]),x=p(x,L,O,D,k,23,o[43]),D=p(D,x,L,O,q,4,o[44]),O=p(O,D,x,L,z,11,o[45]),L=p(L,O,D,x,ge,16,o[46]),D=u(D,x=p(x,L,O,D,A,23,o[47]),L,O,w,6,o[48]),O=u(O,D,x,L,P,10,o[49]),L=u(L,O,D,x,ee,15,o[50]),x=u(x,L,O,D,T,21,o[51]),D=u(D,x,L,O,z,6,o[52]),O=u(O,D,x,L,_,10,o[53]),L=u(L,O,D,x,Y,15,o[54]),x=u(x,L,O,D,y,21,o[55]),D=u(D,x,L,O,H,6,o[56]),O=u(O,D,x,L,ge,10,o[57]),L=u(L,O,D,x,k,15,o[58]),x=u(x,L,O,D,Z,21,o[59]),D=u(D,x,L,O,E,6,o[60]),O=u(O,D,x,L,J,10,o[61]),L=u(L,O,D,x,A,15,o[62]),x=u(x,L,O,D,q,21,o[63]),R[0]=R[0]+D|0,R[1]=R[1]+x|0,R[2]=R[2]+L|0,R[3]=R[3]+O|0},_doFinalize:function(){var f=this._data,m=f.words,b=8*this._nDataBytes,S=8*f.sigBytes;m[S>>>5]|=128<<24-S%32;var v=e.floor(b/4294967296),R=b;m[15+(S+64>>>9<<4)]=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),m[14+(S+64>>>9<<4)]=16711935&(R<<8|R>>>24)|4278255360&(R<<24|R>>>8),f.sigBytes=4*(m.length+1),this._process();for(var w=this._hash,y=w.words,A=0;A<4;A++){var _=y[A];y[A]=16711935&(_<<8|_>>>24)|4278255360&(_<<24|_>>>8)}return w},clone:function(){var f=n.clone.call(this);return f._hash=this._hash.clone(),f}});function d(f,m,b,S,v,R,w){var y=f+(m&b|~m&S)+v+w;return(y<<R|y>>>32-R)+m}function h(f,m,b,S,v,R,w){var y=f+(m&S|b&~S)+v+w;return(y<<R|y>>>32-R)+m}function p(f,m,b,S,v,R,w){var y=f+(m^b^S)+v+w;return(y<<R|y>>>32-R)+m}function u(f,m,b,S,v,R,w){var y=f+(b^(m|~S))+v+w;return(y<<R|y>>>32-R)+m}t.MD5=n._createHelper(l),t.HmacMD5=n._createHmacHelper(l)}(Math),a.MD5}(pe())}(ps)),ps.exports}var gs,ms={exports:{}};function fs(){return gs||(gs=1,function(s){s.exports=function(a){return t=(e=a).lib,i=t.WordArray,r=t.Hasher,n=e.algo,c=[],o=n.SHA1=r.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(l,d){for(var h=this._hash.words,p=h[0],u=h[1],f=h[2],m=h[3],b=h[4],S=0;S<80;S++){if(S<16)c[S]=0|l[d+S];else{var v=c[S-3]^c[S-8]^c[S-14]^c[S-16];c[S]=v<<1|v>>>31}var R=(p<<5|p>>>27)+b+c[S];R+=S<20?1518500249+(u&f|~u&m):S<40?1859775393+(u^f^m):S<60?(u&f|u&m|f&m)-1894007588:(u^f^m)-899497514,b=m,m=f,f=u<<30|u>>>2,u=p,p=R}h[0]=h[0]+p|0,h[1]=h[1]+u|0,h[2]=h[2]+f|0,h[3]=h[3]+m|0,h[4]=h[4]+b|0},_doFinalize:function(){var l=this._data,d=l.words,h=8*this._nDataBytes,p=8*l.sigBytes;return d[p>>>5]|=128<<24-p%32,d[14+(p+64>>>9<<4)]=Math.floor(h/4294967296),d[15+(p+64>>>9<<4)]=h,l.sigBytes=4*d.length,this._process(),this._hash},clone:function(){var l=r.clone.call(this);return l._hash=this._hash.clone(),l}}),e.SHA1=r._createHelper(o),e.HmacSHA1=r._createHmacHelper(o),a.SHA1;var e,t,i,r,n,c,o}(pe())}(ms)),ms.exports}var Ss,bs={exports:{}};function Yi(){return Ss||(Ss=1,function(s){s.exports=function(a){return function(e){var t=a,i=t.lib,r=i.WordArray,n=i.Hasher,c=t.algo,o=[],l=[];(function(){function p(b){for(var S=e.sqrt(b),v=2;v<=S;v++)if(!(b%v))return!1;return!0}function u(b){return 4294967296*(b-(0|b))|0}for(var f=2,m=0;m<64;)p(f)&&(m<8&&(o[m]=u(e.pow(f,.5))),l[m]=u(e.pow(f,1/3)),m++),f++})();var d=[],h=c.SHA256=n.extend({_doReset:function(){this._hash=new r.init(o.slice(0))},_doProcessBlock:function(p,u){for(var f=this._hash.words,m=f[0],b=f[1],S=f[2],v=f[3],R=f[4],w=f[5],y=f[6],A=f[7],_=0;_<64;_++){if(_<16)d[_]=0|p[u+_];else{var E=d[_-15],T=(E<<25|E>>>7)^(E<<14|E>>>18)^E>>>3,k=d[_-2],P=(k<<15|k>>>17)^(k<<13|k>>>19)^k>>>10;d[_]=T+d[_-7]+P+d[_-16]}var H=m&b^m&S^b&S,q=(m<<30|m>>>2)^(m<<19|m>>>13)^(m<<10|m>>>22),Y=A+((R<<26|R>>>6)^(R<<21|R>>>11)^(R<<7|R>>>25))+(R&w^~R&y)+l[_]+d[_];A=y,y=w,w=R,R=v+Y|0,v=S,S=b,b=m,m=Y+(q+H)|0}f[0]=f[0]+m|0,f[1]=f[1]+b|0,f[2]=f[2]+S|0,f[3]=f[3]+v|0,f[4]=f[4]+R|0,f[5]=f[5]+w|0,f[6]=f[6]+y|0,f[7]=f[7]+A|0},_doFinalize:function(){var p=this._data,u=p.words,f=8*this._nDataBytes,m=8*p.sigBytes;return u[m>>>5]|=128<<24-m%32,u[14+(m+64>>>9<<4)]=e.floor(f/4294967296),u[15+(m+64>>>9<<4)]=f,p.sigBytes=4*u.length,this._process(),this._hash},clone:function(){var p=n.clone.call(this);return p._hash=this._hash.clone(),p}});t.SHA256=n._createHelper(h),t.HmacSHA256=n._createHmacHelper(h)}(Math),a.SHA256}(pe())}(bs)),bs.exports}var vs,Fn={exports:{}},ys,Rs={exports:{}};function As(){return ys||(ys=1,function(s){s.exports=function(a){return function(){var e=a,t=e.lib.Hasher,i=e.x64,r=i.Word,n=i.WordArray,c=e.algo;function o(){return r.create.apply(r,arguments)}var l=[o(1116352408,3609767458),o(1899447441,602891725),o(3049323471,3964484399),o(3921009573,2173295548),o(961987163,4081628472),o(1508970993,3053834265),o(2453635748,2937671579),o(2870763221,3664609560),o(3624381080,2734883394),o(310598401,1164996542),o(607225278,1323610764),o(1426881987,3590304994),o(1925078388,4068182383),o(2162078206,991336113),o(2614888103,633803317),o(3248222580,3479774868),o(3835390401,2666613458),o(4022224774,944711139),o(264347078,2341262773),o(604807628,2007800933),o(770255983,1495990901),o(1249150122,1856431235),o(1555081692,3175218132),o(1996064986,2198950837),o(2554220882,3999719339),o(2821834349,766784016),o(2952996808,2566594879),o(3210313671,3203337956),o(3336571891,1034457026),o(3584528711,2466948901),o(113926993,3758326383),o(338241895,168717936),o(666307205,1188179964),o(773529912,1546045734),o(1294757372,1522805485),o(1396182291,2643833823),o(1695183700,2343527390),o(1986661051,1014477480),o(2177026350,1206759142),o(2456956037,344077627),o(2730485921,1290863460),o(2820302411,3158454273),o(3259730800,3505952657),o(3345764771,106217008),o(3516065817,3606008344),o(3600352804,1432725776),o(4094571909,1467031594),o(275423344,851169720),o(430227734,3100823752),o(506948616,1363258195),o(659060556,3750685593),o(883997877,3785050280),o(958139571,3318307427),o(1322822218,3812723403),o(1537002063,2003034995),o(1747873779,3602036899),o(1955562222,1575990012),o(2024104815,1125592928),o(2227730452,2716904306),o(2361852424,442776044),o(2428436474,593698344),o(2756734187,3733110249),o(3204031479,2999351573),o(3329325298,3815920427),o(3391569614,3928383900),o(3515267271,566280711),o(3940187606,3454069534),o(4118630271,4000239992),o(116418474,1914138554),o(174292421,2731055270),o(289380356,3203993006),o(460393269,320620315),o(685471733,587496836),o(852142971,1086792851),o(1017036298,365543100),o(1126000580,2618297676),o(1288033470,3409855158),o(1501505948,4234509866),o(1607167915,987167468),o(1816402316,1246189591)],d=[];(function(){for(var p=0;p<80;p++)d[p]=o()})();var h=c.SHA512=t.extend({_doReset:function(){this._hash=new n.init([new r.init(1779033703,4089235720),new r.init(3144134277,2227873595),new r.init(1013904242,4271175723),new r.init(2773480762,1595750129),new r.init(1359893119,2917565137),new r.init(2600822924,725511199),new r.init(528734635,4215389547),new r.init(1541459225,327033209)])},_doProcessBlock:function(p,u){for(var f=this._hash.words,m=f[0],b=f[1],S=f[2],v=f[3],R=f[4],w=f[5],y=f[6],A=f[7],_=m.high,E=m.low,T=b.high,k=b.low,P=S.high,H=S.low,q=v.high,Y=v.low,J=R.high,z=R.low,Z=w.high,ee=w.low,ge=y.high,D=y.low,x=A.high,L=A.low,O=_,de=E,Pe=T,K=k,me=P,Me=H,_e=q,ke=Y,fe=J,we=z,he=Z,De=ee,ye=ge,qe=D,st=x,ne=L,re=0;re<80;re++){var ie,Se,Ve=d[re];if(re<16)Se=Ve.high=0|p[u+2*re],ie=Ve.low=0|p[u+2*re+1];else{var ue=d[re-15],We=ue.high,Q=ue.low,Le=(We>>>1|Q<<31)^(We>>>8|Q<<24)^We>>>7,at=(Q>>>1|We<<31)^(Q>>>8|We<<24)^(Q>>>7|We<<25),xe=d[re-2],bt=xe.high,Tt=xe.low,vt=(bt>>>19|Tt<<13)^(bt<<3|Tt>>>29)^bt>>>6,jt=(Tt>>>19|bt<<13)^(Tt<<3|bt>>>29)^(Tt>>>6|bt<<26),Pi=d[re-7],qi=Pi.high,Oc=Pi.low,Cn=d[re-16],Vc=Cn.high,kn=Cn.low;Se=(Se=(Se=Le+qi+((ie=at+Oc)>>>0<at>>>0?1:0))+vt+((ie+=jt)>>>0<jt>>>0?1:0))+Vc+((ie+=kn)>>>0<kn>>>0?1:0),Ve.high=Se,Ve.low=ie}var ei,Uc=fe&he^~fe&ye,Pn=we&De^~we&qe,Bc=O&Pe^O&me^Pe&me,Hc=de&K^de&Me^K&Me,Fc=(O>>>28|de<<4)^(O<<30|de>>>2)^(O<<25|de>>>7),Dn=(de>>>28|O<<4)^(de<<30|O>>>2)^(de<<25|O>>>7),jc=(fe>>>14|we<<18)^(fe>>>18|we<<14)^(fe<<23|we>>>9),zc=(we>>>14|fe<<18)^(we>>>18|fe<<14)^(we<<23|fe>>>9),Mn=l[re],Wc=Mn.high,Ln=Mn.low,Di=st+jc+((ei=ne+zc)>>>0<ne>>>0?1:0),Nn=Dn+Hc;st=ye,ne=qe,ye=he,qe=De,he=fe,De=we,fe=_e+(Di=(Di=(Di=Di+Uc+((ei+=Pn)>>>0<Pn>>>0?1:0))+Wc+((ei+=Ln)>>>0<Ln>>>0?1:0))+Se+((ei+=ie)>>>0<ie>>>0?1:0))+((we=ke+ei|0)>>>0<ke>>>0?1:0)|0,_e=me,ke=Me,me=Pe,Me=K,Pe=O,K=de,O=Di+(Fc+Bc+(Nn>>>0<Dn>>>0?1:0))+((de=ei+Nn|0)>>>0<ei>>>0?1:0)|0}E=m.low=E+de,m.high=_+O+(E>>>0<de>>>0?1:0),k=b.low=k+K,b.high=T+Pe+(k>>>0<K>>>0?1:0),H=S.low=H+Me,S.high=P+me+(H>>>0<Me>>>0?1:0),Y=v.low=Y+ke,v.high=q+_e+(Y>>>0<ke>>>0?1:0),z=R.low=z+we,R.high=J+fe+(z>>>0<we>>>0?1:0),ee=w.low=ee+De,w.high=Z+he+(ee>>>0<De>>>0?1:0),D=y.low=D+qe,y.high=ge+ye+(D>>>0<qe>>>0?1:0),L=A.low=L+ne,A.high=x+st+(L>>>0<ne>>>0?1:0)},_doFinalize:function(){var p=this._data,u=p.words,f=8*this._nDataBytes,m=8*p.sigBytes;return u[m>>>5]|=128<<24-m%32,u[30+(m+128>>>10<<5)]=Math.floor(f/4294967296),u[31+(m+128>>>10<<5)]=f,p.sigBytes=4*u.length,this._process(),this._hash.toX32()},clone:function(){var p=t.clone.call(this);return p._hash=this._hash.clone(),p},blockSize:32});e.SHA512=t._createHelper(h),e.HmacSHA512=t._createHmacHelper(h)}(),a.SHA512}(pe(),Li())}(Rs)),Rs.exports}var _s,jn={exports:{}},ws,Es={exports:{}};function zn(){return ws||(ws=1,function(s){s.exports=function(a){return function(e){var t=a,i=t.lib,r=i.WordArray,n=i.Hasher,c=t.x64.Word,o=t.algo,l=[],d=[],h=[];(function(){for(var f=1,m=0,b=0;b<24;b++){l[f+5*m]=(b+1)*(b+2)/2%64;var S=(2*f+3*m)%5;f=m%5,m=S}for(f=0;f<5;f++)for(m=0;m<5;m++)d[f+5*m]=m+(2*f+3*m)%5*5;for(var v=1,R=0;R<24;R++){for(var w=0,y=0,A=0;A<7;A++){if(1&v){var _=(1<<A)-1;_<32?y^=1<<_:w^=1<<_-32}128&v?v=v<<1^113:v<<=1}h[R]=c.create(w,y)}})();var p=[];(function(){for(var f=0;f<25;f++)p[f]=c.create()})();var u=o.SHA3=n.extend({cfg:n.cfg.extend({outputLength:512}),_doReset:function(){for(var f=this._state=[],m=0;m<25;m++)f[m]=new c.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(f,m){for(var b=this._state,S=this.blockSize/2,v=0;v<S;v++){var R=f[m+2*v],w=f[m+2*v+1];R=16711935&(R<<8|R>>>24)|4278255360&(R<<24|R>>>8),w=16711935&(w<<8|w>>>24)|4278255360&(w<<24|w>>>8),(L=b[v]).high^=w,L.low^=R}for(var y=0;y<24;y++){for(var A=0;A<5;A++){for(var _=0,E=0,T=0;T<5;T++)_^=(L=b[A+5*T]).high,E^=L.low;var k=p[A];k.high=_,k.low=E}for(A=0;A<5;A++){var P=p[(A+4)%5],H=p[(A+1)%5],q=H.high,Y=H.low;for(_=P.high^(q<<1|Y>>>31),E=P.low^(Y<<1|q>>>31),T=0;T<5;T++)(L=b[A+5*T]).high^=_,L.low^=E}for(var J=1;J<25;J++){var z=(L=b[J]).high,Z=L.low,ee=l[J];ee<32?(_=z<<ee|Z>>>32-ee,E=Z<<ee|z>>>32-ee):(_=Z<<ee-32|z>>>64-ee,E=z<<ee-32|Z>>>64-ee);var ge=p[d[J]];ge.high=_,ge.low=E}var D=p[0],x=b[0];for(D.high=x.high,D.low=x.low,A=0;A<5;A++)for(T=0;T<5;T++){var L=b[J=A+5*T],O=p[J],de=p[(A+1)%5+5*T],Pe=p[(A+2)%5+5*T];L.high=O.high^~de.high&Pe.high,L.low=O.low^~de.low&Pe.low}L=b[0];var K=h[y];L.high^=K.high,L.low^=K.low}},_doFinalize:function(){var f=this._data,m=f.words;this._nDataBytes;var b=8*f.sigBytes,S=32*this.blockSize;m[b>>>5]|=1<<24-b%32,m[(e.ceil((b+1)/S)*S>>>5)-1]|=128,f.sigBytes=4*m.length,this._process();for(var v=this._state,R=this.cfg.outputLength/8,w=R/8,y=[],A=0;A<w;A++){var _=v[A],E=_.high,T=_.low;E=16711935&(E<<8|E>>>24)|4278255360&(E<<24|E>>>8),T=16711935&(T<<8|T>>>24)|4278255360&(T<<24|T>>>8),y.push(T),y.push(E)}return new r.init(y,R)},clone:function(){for(var f=n.clone.call(this),m=f._state=this._state.slice(0),b=0;b<25;b++)m[b]=m[b].clone();return f}});t.SHA3=n._createHelper(u),t.HmacSHA3=n._createHmacHelper(u)}(Math),a.SHA3}(pe(),Li())}(Es)),Es.exports}var Is,Wn={exports:{}},Ts,Cs={exports:{}};function Qi(){return Ts||(Ts=1,function(s){s.exports=function(a){var e,t,i;t=(e=a).lib.Base,i=e.enc.Utf8,e.algo.HMAC=t.extend({init:function(r,n){r=this._hasher=new r.init,typeof n=="string"&&(n=i.parse(n));var c=r.blockSize,o=4*c;n.sigBytes>o&&(n=r.finalize(n)),n.clamp();for(var l=this._oKey=n.clone(),d=this._iKey=n.clone(),h=l.words,p=d.words,u=0;u<c;u++)h[u]^=1549556828,p[u]^=909522486;l.sigBytes=d.sigBytes=o,this.reset()},reset:function(){var r=this._hasher;r.reset(),r.update(this._iKey)},update:function(r){return this._hasher.update(r),this},finalize:function(r){var n=this._hasher,c=n.finalize(r);return n.reset(),n.finalize(this._oKey.clone().concat(c))}})}(pe())}(Cs)),Cs.exports}var ks,$n={exports:{}},Ps,Ds={exports:{}};function Lt(){return Ps||(Ps=1,function(s){s.exports=function(a){return t=(e=a).lib,i=t.Base,r=t.WordArray,n=e.algo,c=n.MD5,o=n.EvpKDF=i.extend({cfg:i.extend({keySize:4,hasher:c,iterations:1}),init:function(l){this.cfg=this.cfg.extend(l)},compute:function(l,d){for(var h,p=this.cfg,u=p.hasher.create(),f=r.create(),m=f.words,b=p.keySize,S=p.iterations;m.length<b;){h&&u.update(h),h=u.update(l).finalize(d),u.reset();for(var v=1;v<S;v++)h=u.finalize(h),u.reset();f.concat(h)}return f.sigBytes=4*b,f}}),e.EvpKDF=function(l,d,h){return o.create(h).compute(l,d)},a.EvpKDF;var e,t,i,r,n,c,o}(pe(),fs(),Qi())}(Ds)),Ds.exports}var Ms,Ls={exports:{}};function $e(){return Ms||(Ms=1,function(s){s.exports=function(a){a.lib.Cipher||function(e){var t=a,i=t.lib,r=i.Base,n=i.WordArray,c=i.BufferedBlockAlgorithm,o=t.enc;o.Utf8;var l=o.Base64,d=t.algo.EvpKDF,h=i.Cipher=c.extend({cfg:r.extend(),createEncryptor:function(y,A){return this.create(this._ENC_XFORM_MODE,y,A)},createDecryptor:function(y,A){return this.create(this._DEC_XFORM_MODE,y,A)},init:function(y,A,_){this.cfg=this.cfg.extend(_),this._xformMode=y,this._key=A,this.reset()},reset:function(){c.reset.call(this),this._doReset()},process:function(y){return this._append(y),this._process()},finalize:function(y){return y&&this._append(y),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function y(A){return typeof A=="string"?w:v}return function(A){return{encrypt:function(_,E,T){return y(E).encrypt(A,_,E,T)},decrypt:function(_,E,T){return y(E).decrypt(A,_,E,T)}}}}()});i.StreamCipher=h.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var p=t.mode={},u=i.BlockCipherMode=r.extend({createEncryptor:function(y,A){return this.Encryptor.create(y,A)},createDecryptor:function(y,A){return this.Decryptor.create(y,A)},init:function(y,A){this._cipher=y,this._iv=A}}),f=p.CBC=function(){var y=u.extend();function A(_,E,T){var k,P=this._iv;P?(k=P,this._iv=e):k=this._prevBlock;for(var H=0;H<T;H++)_[E+H]^=k[H]}return y.Encryptor=y.extend({processBlock:function(_,E){var T=this._cipher,k=T.blockSize;A.call(this,_,E,k),T.encryptBlock(_,E),this._prevBlock=_.slice(E,E+k)}}),y.Decryptor=y.extend({processBlock:function(_,E){var T=this._cipher,k=T.blockSize,P=_.slice(E,E+k);T.decryptBlock(_,E),A.call(this,_,E,k),this._prevBlock=P}}),y}(),m=(t.pad={}).Pkcs7={pad:function(y,A){for(var _=4*A,E=_-y.sigBytes%_,T=E<<24|E<<16|E<<8|E,k=[],P=0;P<E;P+=4)k.push(T);var H=n.create(k,E);y.concat(H)},unpad:function(y){var A=255&y.words[y.sigBytes-1>>>2];y.sigBytes-=A}};i.BlockCipher=h.extend({cfg:h.cfg.extend({mode:f,padding:m}),reset:function(){var y;h.reset.call(this);var A=this.cfg,_=A.iv,E=A.mode;this._xformMode==this._ENC_XFORM_MODE?y=E.createEncryptor:(y=E.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==y?this._mode.init(this,_&&_.words):(this._mode=y.call(E,this,_&&_.words),this._mode.__creator=y)},_doProcessBlock:function(y,A){this._mode.processBlock(y,A)},_doFinalize:function(){var y,A=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(A.pad(this._data,this.blockSize),y=this._process(!0)):(y=this._process(!0),A.unpad(y)),y},blockSize:4});var b=i.CipherParams=r.extend({init:function(y){this.mixIn(y)},toString:function(y){return(y||this.formatter).stringify(this)}}),S=(t.format={}).OpenSSL={stringify:function(y){var A=y.ciphertext,_=y.salt;return(_?n.create([1398893684,1701076831]).concat(_).concat(A):A).toString(l)},parse:function(y){var A,_=l.parse(y),E=_.words;return E[0]==1398893684&&E[1]==1701076831&&(A=n.create(E.slice(2,4)),E.splice(0,4),_.sigBytes-=16),b.create({ciphertext:_,salt:A})}},v=i.SerializableCipher=r.extend({cfg:r.extend({format:S}),encrypt:function(y,A,_,E){E=this.cfg.extend(E);var T=y.createEncryptor(_,E),k=T.finalize(A),P=T.cfg;return b.create({ciphertext:k,key:_,iv:P.iv,algorithm:y,mode:P.mode,padding:P.padding,blockSize:y.blockSize,formatter:E.format})},decrypt:function(y,A,_,E){return E=this.cfg.extend(E),A=this._parse(A,E.format),y.createDecryptor(_,E).finalize(A.ciphertext)},_parse:function(y,A){return typeof y=="string"?A.parse(y,this):y}}),R=(t.kdf={}).OpenSSL={execute:function(y,A,_,E,T){if(E||(E=n.random(8)),T)k=d.create({keySize:A+_,hasher:T}).compute(y,E);else var k=d.create({keySize:A+_}).compute(y,E);var P=n.create(k.words.slice(A),4*_);return k.sigBytes=4*A,b.create({key:k,iv:P,salt:E})}},w=i.PasswordBasedCipher=v.extend({cfg:v.cfg.extend({kdf:R}),encrypt:function(y,A,_,E){var T=(E=this.cfg.extend(E)).kdf.execute(_,y.keySize,y.ivSize,E.salt,E.hasher);E.iv=T.iv;var k=v.encrypt.call(this,y,A,T.key,E);return k.mixIn(T),k},decrypt:function(y,A,_,E){E=this.cfg.extend(E),A=this._parse(A,E.format);var T=E.kdf.execute(_,y.keySize,y.ivSize,A.salt,E.hasher);return E.iv=T.iv,v.decrypt.call(this,y,A,T.key,E)}})}()}(pe(),Lt())}(Ls)),Ls.exports}var Ns,xs={exports:{}};function Kn(){return Ns||(Ns=1,function(s){s.exports=function(a){return a.mode.CFB=function(){var e=a.lib.BlockCipherMode.extend();function t(i,r,n,c){var o,l=this._iv;l?(o=l.slice(0),this._iv=void 0):o=this._prevBlock,c.encryptBlock(o,0);for(var d=0;d<n;d++)i[r+d]^=o[d]}return e.Encryptor=e.extend({processBlock:function(i,r){var n=this._cipher,c=n.blockSize;t.call(this,i,r,c,n),this._prevBlock=i.slice(r,r+c)}}),e.Decryptor=e.extend({processBlock:function(i,r){var n=this._cipher,c=n.blockSize,o=i.slice(r,r+c);t.call(this,i,r,c,n),this._prevBlock=o}}),e}(),a.mode.CFB}(pe(),$e())}(xs)),xs.exports}var Os,Vs={exports:{}};function Jn(){return Os||(Os=1,function(s){s.exports=function(a){return a.mode.CTR=(e=a.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(i,r){var n=this._cipher,c=n.blockSize,o=this._iv,l=this._counter;o&&(l=this._counter=o.slice(0),this._iv=void 0);var d=l.slice(0);n.encryptBlock(d,0),l[c-1]=l[c-1]+1|0;for(var h=0;h<c;h++)i[r+h]^=d[h]}}),e.Decryptor=t,e),a.mode.CTR;var e,t}(pe(),$e())}(Vs)),Vs.exports}var Us,Bs={exports:{}};function Gn(){return Us||(Us=1,function(s){s.exports=function(a){return a.mode.CTRGladman=function(){var e=a.lib.BlockCipherMode.extend();function t(n){if(255&~(n>>24))n+=1<<24;else{var c=n>>16&255,o=n>>8&255,l=255&n;c===255?(c=0,o===255?(o=0,l===255?l=0:++l):++o):++c,n=0,n+=c<<16,n+=o<<8,n+=l}return n}function i(n){return(n[0]=t(n[0]))===0&&(n[1]=t(n[1])),n}var r=e.Encryptor=e.extend({processBlock:function(n,c){var o=this._cipher,l=o.blockSize,d=this._iv,h=this._counter;d&&(h=this._counter=d.slice(0),this._iv=void 0),i(h);var p=h.slice(0);o.encryptBlock(p,0);for(var u=0;u<l;u++)n[c+u]^=p[u]}});return e.Decryptor=r,e}(),a.mode.CTRGladman}(pe(),$e())}(Bs)),Bs.exports}var Hs,Fs={exports:{}};function qn(){return Hs||(Hs=1,function(s){s.exports=function(a){return a.mode.OFB=(e=a.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(i,r){var n=this._cipher,c=n.blockSize,o=this._iv,l=this._keystream;o&&(l=this._keystream=o.slice(0),this._iv=void 0),n.encryptBlock(l,0);for(var d=0;d<c;d++)i[r+d]^=l[d]}}),e.Decryptor=t,e),a.mode.OFB;var e,t}(pe(),$e())}(Fs)),Fs.exports}var js,Xn={exports:{}},zs,Yn={exports:{}},Ws,Qn={exports:{}},$s,Zn={exports:{}},Ks,eo={exports:{}},Js,to={exports:{}},Gs,io={exports:{}},qs,ro={exports:{}},Xs,Ys={exports:{}};function so(){return Xs||(Xs=1,function(s){s.exports=function(a){return function(){var e=a,t=e.lib,i=t.WordArray,r=t.BlockCipher,n=e.algo,c=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],o=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],l=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],d=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],h=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],p=n.DES=r.extend({_doReset:function(){for(var b=this._key.words,S=[],v=0;v<56;v++){var R=c[v]-1;S[v]=b[R>>>5]>>>31-R%32&1}for(var w=this._subKeys=[],y=0;y<16;y++){var A=w[y]=[],_=l[y];for(v=0;v<24;v++)A[v/6|0]|=S[(o[v]-1+_)%28]<<31-v%6,A[4+(v/6|0)]|=S[28+(o[v+24]-1+_)%28]<<31-v%6;for(A[0]=A[0]<<1|A[0]>>>31,v=1;v<7;v++)A[v]=A[v]>>>4*(v-1)+3;A[7]=A[7]<<5|A[7]>>>27}var E=this._invSubKeys=[];for(v=0;v<16;v++)E[v]=w[15-v]},encryptBlock:function(b,S){this._doCryptBlock(b,S,this._subKeys)},decryptBlock:function(b,S){this._doCryptBlock(b,S,this._invSubKeys)},_doCryptBlock:function(b,S,v){this._lBlock=b[S],this._rBlock=b[S+1],u.call(this,4,252645135),u.call(this,16,65535),f.call(this,2,858993459),f.call(this,8,16711935),u.call(this,1,1431655765);for(var R=0;R<16;R++){for(var w=v[R],y=this._lBlock,A=this._rBlock,_=0,E=0;E<8;E++)_|=d[E][((A^w[E])&h[E])>>>0];this._lBlock=A,this._rBlock=y^_}var T=this._lBlock;this._lBlock=this._rBlock,this._rBlock=T,u.call(this,1,1431655765),f.call(this,8,16711935),f.call(this,2,858993459),u.call(this,16,65535),u.call(this,4,252645135),b[S]=this._lBlock,b[S+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});function u(b,S){var v=(this._lBlock>>>b^this._rBlock)&S;this._rBlock^=v,this._lBlock^=v<<b}function f(b,S){var v=(this._rBlock>>>b^this._lBlock)&S;this._lBlock^=v,this._rBlock^=v<<b}e.DES=r._createHelper(p);var m=n.TripleDES=r.extend({_doReset:function(){var b=this._key.words;if(b.length!==2&&b.length!==4&&b.length<6)throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");var S=b.slice(0,2),v=b.length<4?b.slice(0,2):b.slice(2,4),R=b.length<6?b.slice(0,2):b.slice(4,6);this._des1=p.createEncryptor(i.create(S)),this._des2=p.createEncryptor(i.create(v)),this._des3=p.createEncryptor(i.create(R))},encryptBlock:function(b,S){this._des1.encryptBlock(b,S),this._des2.decryptBlock(b,S),this._des3.encryptBlock(b,S)},decryptBlock:function(b,S){this._des3.decryptBlock(b,S),this._des2.encryptBlock(b,S),this._des1.decryptBlock(b,S)},keySize:6,ivSize:2,blockSize:2});e.TripleDES=r._createHelper(m)}(),a.TripleDES}(pe(),zt(),Wt(),Lt(),$e())}(Ys)),Ys.exports}var Qs,ao={exports:{}},Zs,no={exports:{}},ea,oo={exports:{}},ta,ia={exports:{}};function co(){return ta||(ta=1,function(s){s.exports=function(a){return function(){var e=a,t=e.lib.BlockCipher,i=e.algo;const r=16,n=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],c=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]];var o={pbox:[],sbox:[]};function l(f,m){let b=m>>24&255,S=m>>16&255,v=m>>8&255,R=255&m,w=f.sbox[0][b]+f.sbox[1][S];return w^=f.sbox[2][v],w+=f.sbox[3][R],w}function d(f,m,b){let S,v=m,R=b;for(let w=0;w<r;++w)v^=f.pbox[w],R=l(f,v)^R,S=v,v=R,R=S;return S=v,v=R,R=S,R^=f.pbox[r],v^=f.pbox[r+1],{left:v,right:R}}function h(f,m,b){let S,v=m,R=b;for(let w=r+1;w>1;--w)v^=f.pbox[w],R=l(f,v)^R,S=v,v=R,R=S;return S=v,v=R,R=S,R^=f.pbox[1],v^=f.pbox[0],{left:v,right:R}}function p(f,m,b){for(let y=0;y<4;y++){f.sbox[y]=[];for(let A=0;A<256;A++)f.sbox[y][A]=c[y][A]}let S=0;for(let y=0;y<r+2;y++)f.pbox[y]=n[y]^m[S],S++,S>=b&&(S=0);let v=0,R=0,w=0;for(let y=0;y<r+2;y+=2)w=d(f,v,R),v=w.left,R=w.right,f.pbox[y]=v,f.pbox[y+1]=R;for(let y=0;y<4;y++)for(let A=0;A<256;A+=2)w=d(f,v,R),v=w.left,R=w.right,f.sbox[y][A]=v,f.sbox[y][A+1]=R;return!0}var u=i.Blowfish=t.extend({_doReset:function(){if(this._keyPriorReset!==this._key){var f=this._keyPriorReset=this._key,m=f.words,b=f.sigBytes/4;p(o,m,b)}},encryptBlock:function(f,m){var b=d(o,f[m],f[m+1]);f[m]=b.left,f[m+1]=b.right},decryptBlock:function(f,m){var b=h(o,f[m],f[m+1]);f[m]=b.left,f[m+1]=b.right},blockSize:2,keySize:4,ivSize:2});e.Blowfish=t._createHelper(u)}(),a.Blowfish}(pe(),zt(),Wt(),Lt(),$e())}(ia)),ia.exports}(function(s){s.exports=function(a){return a}(pe(),Li(),Un(),Bn(),zt(),Hn(),Wt(),fs(),Yi(),vs||(vs=1,function(a){a.exports=function(e){return i=(t=e).lib.WordArray,r=t.algo,n=r.SHA256,c=r.SHA224=n.extend({_doReset:function(){this._hash=new i.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var o=n._doFinalize.call(this);return o.sigBytes-=4,o}}),t.SHA224=n._createHelper(c),t.HmacSHA224=n._createHmacHelper(c),e.SHA224;var t,i,r,n,c}(pe(),Yi())}(Fn)),As(),_s||(_s=1,function(a){a.exports=function(e){return i=(t=e).x64,r=i.Word,n=i.WordArray,c=t.algo,o=c.SHA512,l=c.SHA384=o.extend({_doReset:function(){this._hash=new n.init([new r.init(3418070365,3238371032),new r.init(1654270250,914150663),new r.init(2438529370,812702999),new r.init(355462360,4144912697),new r.init(1731405415,4290775857),new r.init(2394180231,1750603025),new r.init(3675008525,1694076839),new r.init(1203062813,3204075428)])},_doFinalize:function(){var d=o._doFinalize.call(this);return d.sigBytes-=16,d}}),t.SHA384=o._createHelper(l),t.HmacSHA384=o._createHmacHelper(l),e.SHA384;var t,i,r,n,c,o,l}(pe(),Li(),As())}(jn)),zn(),Is||(Is=1,function(a){a.exports=function(e){return function(){var t=e,i=t.lib,r=i.WordArray,n=i.Hasher,c=t.algo,o=r.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),l=r.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),d=r.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),h=r.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),p=r.create([0,1518500249,1859775393,2400959708,2840853838]),u=r.create([1352829926,1548603684,1836072691,2053994217,0]),f=c.RIPEMD160=n.extend({_doReset:function(){this._hash=r.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(y,A){for(var _=0;_<16;_++){var E=A+_,T=y[E];y[E]=16711935&(T<<8|T>>>24)|4278255360&(T<<24|T>>>8)}var k,P,H,q,Y,J,z,Z,ee,ge,D,x=this._hash.words,L=p.words,O=u.words,de=o.words,Pe=l.words,K=d.words,me=h.words;for(J=k=x[0],z=P=x[1],Z=H=x[2],ee=q=x[3],ge=Y=x[4],_=0;_<80;_+=1)D=k+y[A+de[_]]|0,D+=_<16?m(P,H,q)+L[0]:_<32?b(P,H,q)+L[1]:_<48?S(P,H,q)+L[2]:_<64?v(P,H,q)+L[3]:R(P,H,q)+L[4],D=(D=w(D|=0,K[_]))+Y|0,k=Y,Y=q,q=w(H,10),H=P,P=D,D=J+y[A+Pe[_]]|0,D+=_<16?R(z,Z,ee)+O[0]:_<32?v(z,Z,ee)+O[1]:_<48?S(z,Z,ee)+O[2]:_<64?b(z,Z,ee)+O[3]:m(z,Z,ee)+O[4],D=(D=w(D|=0,me[_]))+ge|0,J=ge,ge=ee,ee=w(Z,10),Z=z,z=D;D=x[1]+H+ee|0,x[1]=x[2]+q+ge|0,x[2]=x[3]+Y+J|0,x[3]=x[4]+k+z|0,x[4]=x[0]+P+Z|0,x[0]=D},_doFinalize:function(){var y=this._data,A=y.words,_=8*this._nDataBytes,E=8*y.sigBytes;A[E>>>5]|=128<<24-E%32,A[14+(E+64>>>9<<4)]=16711935&(_<<8|_>>>24)|4278255360&(_<<24|_>>>8),y.sigBytes=4*(A.length+1),this._process();for(var T=this._hash,k=T.words,P=0;P<5;P++){var H=k[P];k[P]=16711935&(H<<8|H>>>24)|4278255360&(H<<24|H>>>8)}return T},clone:function(){var y=n.clone.call(this);return y._hash=this._hash.clone(),y}});function m(y,A,_){return y^A^_}function b(y,A,_){return y&A|~y&_}function S(y,A,_){return(y|~A)^_}function v(y,A,_){return y&_|A&~_}function R(y,A,_){return y^(A|~_)}function w(y,A){return y<<A|y>>>32-A}t.RIPEMD160=n._createHelper(f),t.HmacRIPEMD160=n._createHmacHelper(f)}(),e.RIPEMD160}(pe())}(Wn)),Qi(),ks||(ks=1,function(a){a.exports=function(e){return r=(i=(t=e).lib).Base,n=i.WordArray,o=(c=t.algo).SHA256,l=c.HMAC,d=c.PBKDF2=r.extend({cfg:r.extend({keySize:4,hasher:o,iterations:25e4}),init:function(h){this.cfg=this.cfg.extend(h)},compute:function(h,p){for(var u=this.cfg,f=l.create(u.hasher,h),m=n.create(),b=n.create([1]),S=m.words,v=b.words,R=u.keySize,w=u.iterations;S.length<R;){var y=f.update(p).finalize(b);f.reset();for(var A=y.words,_=A.length,E=y,T=1;T<w;T++){E=f.finalize(E),f.reset();for(var k=E.words,P=0;P<_;P++)A[P]^=k[P]}m.concat(y),v[0]++}return m.sigBytes=4*R,m}}),t.PBKDF2=function(h,p,u){return d.create(u).compute(h,p)},e.PBKDF2;var t,i,r,n,c,o,l,d}(pe(),Yi(),Qi())}($n)),Lt(),$e(),Kn(),Jn(),Gn(),qn(),js||(js=1,function(a){a.exports=function(e){return e.mode.ECB=((t=e.lib.BlockCipherMode.extend()).Encryptor=t.extend({processBlock:function(i,r){this._cipher.encryptBlock(i,r)}}),t.Decryptor=t.extend({processBlock:function(i,r){this._cipher.decryptBlock(i,r)}}),t),e.mode.ECB;var t}(pe(),$e())}(Xn)),zs||(zs=1,function(a){a.exports=function(e){return e.pad.AnsiX923={pad:function(t,i){var r=t.sigBytes,n=4*i,c=n-r%n,o=r+c-1;t.clamp(),t.words[o>>>2]|=c<<24-o%4*8,t.sigBytes+=c},unpad:function(t){var i=255&t.words[t.sigBytes-1>>>2];t.sigBytes-=i}},e.pad.Ansix923}(pe(),$e())}(Yn)),Ws||(Ws=1,function(a){a.exports=function(e){return e.pad.Iso10126={pad:function(t,i){var r=4*i,n=r-t.sigBytes%r;t.concat(e.lib.WordArray.random(n-1)).concat(e.lib.WordArray.create([n<<24],1))},unpad:function(t){var i=255&t.words[t.sigBytes-1>>>2];t.sigBytes-=i}},e.pad.Iso10126}(pe(),$e())}(Qn)),$s||($s=1,function(a){a.exports=function(e){return e.pad.Iso97971={pad:function(t,i){t.concat(e.lib.WordArray.create([2147483648],1)),e.pad.ZeroPadding.pad(t,i)},unpad:function(t){e.pad.ZeroPadding.unpad(t),t.sigBytes--}},e.pad.Iso97971}(pe(),$e())}(Zn)),Ks||(Ks=1,function(a){a.exports=function(e){return e.pad.ZeroPadding={pad:function(t,i){var r=4*i;t.clamp(),t.sigBytes+=r-(t.sigBytes%r||r)},unpad:function(t){var i=t.words,r=t.sigBytes-1;for(r=t.sigBytes-1;r>=0;r--)if(i[r>>>2]>>>24-r%4*8&255){t.sigBytes=r+1;break}}},e.pad.ZeroPadding}(pe(),$e())}(eo)),Js||(Js=1,function(a){a.exports=function(e){return e.pad.NoPadding={pad:function(){},unpad:function(){}},e.pad.NoPadding}(pe(),$e())}(to)),Gs||(Gs=1,function(a){a.exports=function(e){return i=(t=e).lib.CipherParams,r=t.enc.Hex,t.format.Hex={stringify:function(n){return n.ciphertext.toString(r)},parse:function(n){var c=r.parse(n);return i.create({ciphertext:c})}},e.format.Hex;var t,i,r}(pe(),$e())}(io)),qs||(qs=1,function(a){a.exports=function(e){return function(){var t=e,i=t.lib.BlockCipher,r=t.algo,n=[],c=[],o=[],l=[],d=[],h=[],p=[],u=[],f=[],m=[];(function(){for(var v=[],R=0;R<256;R++)v[R]=R<128?R<<1:R<<1^283;var w=0,y=0;for(R=0;R<256;R++){var A=y^y<<1^y<<2^y<<3^y<<4;A=A>>>8^255&A^99,n[w]=A,c[A]=w;var _=v[w],E=v[_],T=v[E],k=257*v[A]^16843008*A;o[w]=k<<24|k>>>8,l[w]=k<<16|k>>>16,d[w]=k<<8|k>>>24,h[w]=k,k=16843009*T^65537*E^257*_^16843008*w,p[A]=k<<24|k>>>8,u[A]=k<<16|k>>>16,f[A]=k<<8|k>>>24,m[A]=k,w?(w=_^v[v[v[T^_]]],y^=v[v[y]]):w=y=1}})();var b=[0,1,2,4,8,16,32,64,128,27,54],S=r.AES=i.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var v=this._keyPriorReset=this._key,R=v.words,w=v.sigBytes/4,y=4*((this._nRounds=w+6)+1),A=this._keySchedule=[],_=0;_<y;_++)_<w?A[_]=R[_]:(k=A[_-1],_%w?w>6&&_%w==4&&(k=n[k>>>24]<<24|n[k>>>16&255]<<16|n[k>>>8&255]<<8|n[255&k]):(k=n[(k=k<<8|k>>>24)>>>24]<<24|n[k>>>16&255]<<16|n[k>>>8&255]<<8|n[255&k],k^=b[_/w|0]<<24),A[_]=A[_-w]^k);for(var E=this._invKeySchedule=[],T=0;T<y;T++){if(_=y-T,T%4)var k=A[_];else k=A[_-4];E[T]=T<4||_<=4?k:p[n[k>>>24]]^u[n[k>>>16&255]]^f[n[k>>>8&255]]^m[n[255&k]]}}},encryptBlock:function(v,R){this._doCryptBlock(v,R,this._keySchedule,o,l,d,h,n)},decryptBlock:function(v,R){var w=v[R+1];v[R+1]=v[R+3],v[R+3]=w,this._doCryptBlock(v,R,this._invKeySchedule,p,u,f,m,c),w=v[R+1],v[R+1]=v[R+3],v[R+3]=w},_doCryptBlock:function(v,R,w,y,A,_,E,T){for(var k=this._nRounds,P=v[R]^w[0],H=v[R+1]^w[1],q=v[R+2]^w[2],Y=v[R+3]^w[3],J=4,z=1;z<k;z++){var Z=y[P>>>24]^A[H>>>16&255]^_[q>>>8&255]^E[255&Y]^w[J++],ee=y[H>>>24]^A[q>>>16&255]^_[Y>>>8&255]^E[255&P]^w[J++],ge=y[q>>>24]^A[Y>>>16&255]^_[P>>>8&255]^E[255&H]^w[J++],D=y[Y>>>24]^A[P>>>16&255]^_[H>>>8&255]^E[255&q]^w[J++];P=Z,H=ee,q=ge,Y=D}Z=(T[P>>>24]<<24|T[H>>>16&255]<<16|T[q>>>8&255]<<8|T[255&Y])^w[J++],ee=(T[H>>>24]<<24|T[q>>>16&255]<<16|T[Y>>>8&255]<<8|T[255&P])^w[J++],ge=(T[q>>>24]<<24|T[Y>>>16&255]<<16|T[P>>>8&255]<<8|T[255&H])^w[J++],D=(T[Y>>>24]<<24|T[P>>>16&255]<<16|T[H>>>8&255]<<8|T[255&q])^w[J++],v[R]=Z,v[R+1]=ee,v[R+2]=ge,v[R+3]=D},keySize:8});t.AES=i._createHelper(S)}(),e.AES}(pe(),zt(),Wt(),Lt(),$e())}(ro)),so(),Qs||(Qs=1,function(a){a.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,r=t.algo,n=r.RC4=i.extend({_doReset:function(){for(var l=this._key,d=l.words,h=l.sigBytes,p=this._S=[],u=0;u<256;u++)p[u]=u;u=0;for(var f=0;u<256;u++){var m=u%h,b=d[m>>>2]>>>24-m%4*8&255;f=(f+p[u]+b)%256;var S=p[u];p[u]=p[f],p[f]=S}this._i=this._j=0},_doProcessBlock:function(l,d){l[d]^=c.call(this)},keySize:8,ivSize:0});function c(){for(var l=this._S,d=this._i,h=this._j,p=0,u=0;u<4;u++){h=(h+l[d=(d+1)%256])%256;var f=l[d];l[d]=l[h],l[h]=f,p|=l[(l[d]+l[h])%256]<<24-8*u}return this._i=d,this._j=h,p}t.RC4=i._createHelper(n);var o=r.RC4Drop=n.extend({cfg:n.cfg.extend({drop:192}),_doReset:function(){n._doReset.call(this);for(var l=this.cfg.drop;l>0;l--)c.call(this)}});t.RC4Drop=i._createHelper(o)}(),e.RC4}(pe(),zt(),Wt(),Lt(),$e())}(ao)),Zs||(Zs=1,function(a){a.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,r=t.algo,n=[],c=[],o=[],l=r.Rabbit=i.extend({_doReset:function(){for(var h=this._key.words,p=this.cfg.iv,u=0;u<4;u++)h[u]=16711935&(h[u]<<8|h[u]>>>24)|4278255360&(h[u]<<24|h[u]>>>8);var f=this._X=[h[0],h[3]<<16|h[2]>>>16,h[1],h[0]<<16|h[3]>>>16,h[2],h[1]<<16|h[0]>>>16,h[3],h[2]<<16|h[1]>>>16],m=this._C=[h[2]<<16|h[2]>>>16,4294901760&h[0]|65535&h[1],h[3]<<16|h[3]>>>16,4294901760&h[1]|65535&h[2],h[0]<<16|h[0]>>>16,4294901760&h[2]|65535&h[3],h[1]<<16|h[1]>>>16,4294901760&h[3]|65535&h[0]];for(this._b=0,u=0;u<4;u++)d.call(this);for(u=0;u<8;u++)m[u]^=f[u+4&7];if(p){var b=p.words,S=b[0],v=b[1],R=16711935&(S<<8|S>>>24)|4278255360&(S<<24|S>>>8),w=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),y=R>>>16|4294901760&w,A=w<<16|65535&R;for(m[0]^=R,m[1]^=y,m[2]^=w,m[3]^=A,m[4]^=R,m[5]^=y,m[6]^=w,m[7]^=A,u=0;u<4;u++)d.call(this)}},_doProcessBlock:function(h,p){var u=this._X;d.call(this),n[0]=u[0]^u[5]>>>16^u[3]<<16,n[1]=u[2]^u[7]>>>16^u[5]<<16,n[2]=u[4]^u[1]>>>16^u[7]<<16,n[3]=u[6]^u[3]>>>16^u[1]<<16;for(var f=0;f<4;f++)n[f]=16711935&(n[f]<<8|n[f]>>>24)|4278255360&(n[f]<<24|n[f]>>>8),h[p+f]^=n[f]},blockSize:4,ivSize:2});function d(){for(var h=this._X,p=this._C,u=0;u<8;u++)c[u]=p[u];for(p[0]=p[0]+1295307597+this._b|0,p[1]=p[1]+3545052371+(p[0]>>>0<c[0]>>>0?1:0)|0,p[2]=p[2]+886263092+(p[1]>>>0<c[1]>>>0?1:0)|0,p[3]=p[3]+1295307597+(p[2]>>>0<c[2]>>>0?1:0)|0,p[4]=p[4]+3545052371+(p[3]>>>0<c[3]>>>0?1:0)|0,p[5]=p[5]+886263092+(p[4]>>>0<c[4]>>>0?1:0)|0,p[6]=p[6]+1295307597+(p[5]>>>0<c[5]>>>0?1:0)|0,p[7]=p[7]+3545052371+(p[6]>>>0<c[6]>>>0?1:0)|0,this._b=p[7]>>>0<c[7]>>>0?1:0,u=0;u<8;u++){var f=h[u]+p[u],m=65535&f,b=f>>>16,S=((m*m>>>17)+m*b>>>15)+b*b,v=((4294901760&f)*f|0)+((65535&f)*f|0);o[u]=S^v}h[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,h[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,h[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,h[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,h[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,h[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,h[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,h[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}t.Rabbit=i._createHelper(l)}(),e.Rabbit}(pe(),zt(),Wt(),Lt(),$e())}(no)),ea||(ea=1,function(a){a.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,r=t.algo,n=[],c=[],o=[],l=r.RabbitLegacy=i.extend({_doReset:function(){var h=this._key.words,p=this.cfg.iv,u=this._X=[h[0],h[3]<<16|h[2]>>>16,h[1],h[0]<<16|h[3]>>>16,h[2],h[1]<<16|h[0]>>>16,h[3],h[2]<<16|h[1]>>>16],f=this._C=[h[2]<<16|h[2]>>>16,4294901760&h[0]|65535&h[1],h[3]<<16|h[3]>>>16,4294901760&h[1]|65535&h[2],h[0]<<16|h[0]>>>16,4294901760&h[2]|65535&h[3],h[1]<<16|h[1]>>>16,4294901760&h[3]|65535&h[0]];this._b=0;for(var m=0;m<4;m++)d.call(this);for(m=0;m<8;m++)f[m]^=u[m+4&7];if(p){var b=p.words,S=b[0],v=b[1],R=16711935&(S<<8|S>>>24)|4278255360&(S<<24|S>>>8),w=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),y=R>>>16|4294901760&w,A=w<<16|65535&R;for(f[0]^=R,f[1]^=y,f[2]^=w,f[3]^=A,f[4]^=R,f[5]^=y,f[6]^=w,f[7]^=A,m=0;m<4;m++)d.call(this)}},_doProcessBlock:function(h,p){var u=this._X;d.call(this),n[0]=u[0]^u[5]>>>16^u[3]<<16,n[1]=u[2]^u[7]>>>16^u[5]<<16,n[2]=u[4]^u[1]>>>16^u[7]<<16,n[3]=u[6]^u[3]>>>16^u[1]<<16;for(var f=0;f<4;f++)n[f]=16711935&(n[f]<<8|n[f]>>>24)|4278255360&(n[f]<<24|n[f]>>>8),h[p+f]^=n[f]},blockSize:4,ivSize:2});function d(){for(var h=this._X,p=this._C,u=0;u<8;u++)c[u]=p[u];for(p[0]=p[0]+1295307597+this._b|0,p[1]=p[1]+3545052371+(p[0]>>>0<c[0]>>>0?1:0)|0,p[2]=p[2]+886263092+(p[1]>>>0<c[1]>>>0?1:0)|0,p[3]=p[3]+1295307597+(p[2]>>>0<c[2]>>>0?1:0)|0,p[4]=p[4]+3545052371+(p[3]>>>0<c[3]>>>0?1:0)|0,p[5]=p[5]+886263092+(p[4]>>>0<c[4]>>>0?1:0)|0,p[6]=p[6]+1295307597+(p[5]>>>0<c[5]>>>0?1:0)|0,p[7]=p[7]+3545052371+(p[6]>>>0<c[6]>>>0?1:0)|0,this._b=p[7]>>>0<c[7]>>>0?1:0,u=0;u<8;u++){var f=h[u]+p[u],m=65535&f,b=f>>>16,S=((m*m>>>17)+m*b>>>15)+b*b,v=((4294901760&f)*f|0)+((65535&f)*f|0);o[u]=S^v}h[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,h[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,h[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,h[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,h[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,h[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,h[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,h[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}t.RabbitLegacy=i._createHelper(l)}(),e.RabbitLegacy}(pe(),zt(),Wt(),Lt(),$e())}(oo)),co())})(ii);const gi=pi(ii.exports);function lo(s){return a=this,e=null,t=function*(){const i=new Date;if(s.refreshSTSTokenInterval||(s.refreshSTSTokenInterval=3e5),!s.stsTokenFreshTime||+i-s.stsTokenFreshTime>=s.refreshSTSTokenInterval){s.stsTokenFreshTime=i;try{yield s.refreshSTSToken()}catch(r){typeof console.error=="function"&&console.error(`Some error occured during excuting refreshSTSToken, see:
2
- `+r)}}return null},new Promise((i,r)=>{var n=l=>{try{o(t.next(l))}catch(d){r(d)}},c=l=>{try{o(t.throw(l))}catch(d){r(d)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(n,c);o((t=t.apply(a,e)).next())});var a,e,t}function Zi(s){return{transString:function(a){let e={},t=0,i=!1;for(let r in a)r!=="time"&&r!=="__time__"||typeof a[r]!="number"?typeof a[r]=="object"?e[r]=JSON.stringify(a[r]):e[r]=String(a[r]):(t=a[r],i=!0);return e.__time__=i?t:Math.floor(new Date().getTime()/1e3),e},process:function(a,e){return t=this,i=null,r=function*(){yield lo(s);let n=a.slice(a.indexOf("/logstores")),c=e.length,o=(l=e,gi.MD5(l).toString().toUpperCase());var l;let d=new Date().toUTCString(),h=new Map,p=new Map([["Content-Type","application/json"],["Content-MD5",o],["x-log-bodyrawsize",c.toString()]]);s.securityToken&&p.set("x-acs-security-token",s.securityToken),function(f,m,b,S,v,R,w,y){var A;let _="";R.set("x-log-apiversion","0.6.0"),R.set("x-log-signaturemethod","hmac-sha1"),_+=f+`
1
+ (function(q,de){typeof exports=="object"&&typeof module!="undefined"?de(exports,require("eventemitter3")):typeof define=="function"&&define.amd?define(["exports","eventemitter3"],de):de((q=typeof globalThis!="undefined"?globalThis:q||self).AliRtcEngine={},q.EventEmitter)})(this,function(q,de){var Yt,jr,Ee,Er,yr,Rt,ee,ih;"use strict";var Ne=(s=>(s.EnableNonOnePcDefaultJoinMode="h5_enable_non_one_pc_default_join_mode",s))(Ne||{});function Et(s,r,e){Object.defineProperty(s,r,{writable:!0,enumerable:!0,configurable:!0,value:e})}function li(s,r,e,t){t?t(()=>{Et(s,r,e)}):Et(s,r,e)}Array(32);var Kr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Cr(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function hi(s){if(s.__esModule)return s;var r=s.default;if(typeof r=="function"){var e=function t(){return this instanceof t?Reflect.construct(r,arguments,this.constructor):r.apply(this,arguments)};e.prototype=r.prototype}else e={};return Object.defineProperty(e,"__esModule",{value:!0}),Object.keys(s).forEach(function(t){var i=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:function(){return s[t]}})}),e}var er={exports:{}},Jr={exports:{}};const mh=hi(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var ha;function Ce(){return ha||(ha=1,function(s){s.exports=function(){var r=r||function(e,t){var i;if(typeof window!="undefined"&&window.crypto&&(i=window.crypto),typeof self!="undefined"&&self.crypto&&(i=self.crypto),typeof globalThis!="undefined"&&globalThis.crypto&&(i=globalThis.crypto),!i&&typeof window!="undefined"&&window.msCrypto&&(i=window.msCrypto),!i&&Kr!==void 0&&Kr.crypto&&(i=Kr.crypto),!i)try{i=mh}catch(S){}var n=function(){if(i){if(typeof i.getRandomValues=="function")try{return i.getRandomValues(new Uint32Array(1))[0]}catch(S){}if(typeof i.randomBytes=="function")try{return i.randomBytes(4).readInt32LE()}catch(S){}}throw new Error("Native crypto module could not be used to get secure random number.")},a=Object.create||function(){function S(){}return function(v){var E;return S.prototype=v,E=new S,S.prototype=null,E}}(),c={},o=c.lib={},l=o.Base={extend:function(S){var v=a(this);return S&&v.mixIn(S),v.hasOwnProperty("init")&&this.init!==v.init||(v.init=function(){v.$super.init.apply(this,arguments)}),v.init.prototype=v,v.$super=this,v},create:function(){var S=this.extend();return S.init.apply(S,arguments),S},init:function(){},mixIn:function(S){for(var v in S)S.hasOwnProperty(v)&&(this[v]=S[v]);S.hasOwnProperty("toString")&&(this.toString=S.toString)},clone:function(){return this.init.prototype.extend(this)}},d=o.WordArray=l.extend({init:function(S,v){S=this.words=S||[],this.sigBytes=v!=t?v:4*S.length},toString:function(S){return(S||u).stringify(this)},concat:function(S){var v=this.words,E=S.words,T=this.sigBytes,R=S.sigBytes;if(this.clamp(),T%4)for(var y=0;y<R;y++){var C=E[y>>>2]>>>24-y%4*8&255;v[T+y>>>2]|=C<<24-(T+y)%4*8}else for(var w=0;w<R;w+=4)v[T+w>>>2]=E[w>>>2];return this.sigBytes+=R,this},clamp:function(){var S=this.words,v=this.sigBytes;S[v>>>2]&=4294967295<<32-v%4*8,S.length=e.ceil(v/4)},clone:function(){var S=l.clone.call(this);return S.words=this.words.slice(0),S},random:function(S){for(var v=[],E=0;E<S;E+=4)v.push(n());return new d.init(v,S)}}),h=c.enc={},u=h.Hex={stringify:function(S){for(var v=S.words,E=S.sigBytes,T=[],R=0;R<E;R++){var y=v[R>>>2]>>>24-R%4*8&255;T.push((y>>>4).toString(16)),T.push((15&y).toString(16))}return T.join("")},parse:function(S){for(var v=S.length,E=[],T=0;T<v;T+=2)E[T>>>3]|=parseInt(S.substr(T,2),16)<<24-T%8*4;return new d.init(E,v/2)}},p=h.Latin1={stringify:function(S){for(var v=S.words,E=S.sigBytes,T=[],R=0;R<E;R++){var y=v[R>>>2]>>>24-R%4*8&255;T.push(String.fromCharCode(y))}return T.join("")},parse:function(S){for(var v=S.length,E=[],T=0;T<v;T++)E[T>>>2]|=(255&S.charCodeAt(T))<<24-T%4*8;return new d.init(E,v)}},f=h.Utf8={stringify:function(S){try{return decodeURIComponent(escape(p.stringify(S)))}catch(v){throw new Error("Malformed UTF-8 data")}},parse:function(S){return p.parse(unescape(encodeURIComponent(S)))}},m=o.BufferedBlockAlgorithm=l.extend({reset:function(){this._data=new d.init,this._nDataBytes=0},_append:function(S){typeof S=="string"&&(S=f.parse(S)),this._data.concat(S),this._nDataBytes+=S.sigBytes},_process:function(S){var v,E=this._data,T=E.words,R=E.sigBytes,y=this.blockSize,C=R/(4*y),w=(C=S?e.ceil(C):e.max((0|C)-this._minBufferSize,0))*y,A=e.min(4*w,R);if(w){for(var P=0;P<w;P+=y)this._doProcessBlock(T,P);v=T.splice(0,w),E.sigBytes-=A}return new d.init(v,A)},clone:function(){var S=l.clone.call(this);return S._data=this._data.clone(),S},_minBufferSize:0});o.Hasher=m.extend({cfg:l.extend(),init:function(S){this.cfg=this.cfg.extend(S),this.reset()},reset:function(){m.reset.call(this),this._doReset()},update:function(S){return this._append(S),this._process(),this},finalize:function(S){return S&&this._append(S),this._doFinalize()},blockSize:16,_createHelper:function(S){return function(v,E){return new S.init(E).finalize(v)}},_createHmacHelper:function(S){return function(v,E){return new g.HMAC.init(S,E).finalize(v)}}});var g=c.algo={};return c}(Math);return r}()}(Jr)),Jr.exports}var ua,pa={exports:{}};function Ui(){return ua||(ua=1,function(s){s.exports=function(r){return i=(t=r).lib,n=i.Base,a=i.WordArray,(c=t.x64={}).Word=n.extend({init:function(o,l){this.high=o,this.low=l}}),c.WordArray=n.extend({init:function(o,l){o=this.words=o||[],this.sigBytes=l!=e?l:8*o.length},toX32:function(){for(var o=this.words,l=o.length,d=[],h=0;h<l;h++){var u=o[h];d.push(u.high),d.push(u.low)}return a.create(d,this.sigBytes)},clone:function(){for(var o=n.clone.call(this),l=o.words=this.words.slice(0),d=l.length,h=0;h<d;h++)l[h]=l[h].clone();return o}}),r;var e,t,i,n,a,c}(Ce())}(pa)),pa.exports}var ma,fa={exports:{}};function fh(){return ma||(ma=1,function(s){s.exports=function(r){return function(){if(typeof ArrayBuffer=="function"){var e=r.lib.WordArray,t=e.init,i=e.init=function(n){if(n instanceof ArrayBuffer&&(n=new Uint8Array(n)),(n instanceof Int8Array||typeof Uint8ClampedArray!="undefined"&&n instanceof Uint8ClampedArray||n instanceof Int16Array||n instanceof Uint16Array||n instanceof Int32Array||n instanceof Uint32Array||n instanceof Float32Array||n instanceof Float64Array)&&(n=new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),n instanceof Uint8Array){for(var a=n.byteLength,c=[],o=0;o<a;o++)c[o>>>2]|=n[o]<<24-o%4*8;t.call(this,c,a)}else t.apply(this,arguments)};i.prototype=e}}(),r.lib.WordArray}(Ce())}(fa)),fa.exports}var ga,Sa={exports:{}};function gh(){return ga||(ga=1,function(s){s.exports=function(r){return function(){var e=r,t=e.lib.WordArray,i=e.enc;function n(a){return a<<8&4278255360|a>>>8&16711935}i.Utf16=i.Utf16BE={stringify:function(a){for(var c=a.words,o=a.sigBytes,l=[],d=0;d<o;d+=2){var h=c[d>>>2]>>>16-d%4*8&65535;l.push(String.fromCharCode(h))}return l.join("")},parse:function(a){for(var c=a.length,o=[],l=0;l<c;l++)o[l>>>1]|=a.charCodeAt(l)<<16-l%2*16;return t.create(o,2*c)}},i.Utf16LE={stringify:function(a){for(var c=a.words,o=a.sigBytes,l=[],d=0;d<o;d+=2){var h=n(c[d>>>2]>>>16-d%4*8&65535);l.push(String.fromCharCode(h))}return l.join("")},parse:function(a){for(var c=a.length,o=[],l=0;l<c;l++)o[l>>>1]|=n(a.charCodeAt(l)<<16-l%2*16);return t.create(o,2*c)}}}(),r.enc.Utf16}(Ce())}(Sa)),Sa.exports}var ba,va={exports:{}};function _r(){return ba||(ba=1,function(s){s.exports=function(r){return function(){var e=r,t=e.lib.WordArray;function i(n,a,c){for(var o=[],l=0,d=0;d<a;d++)if(d%4){var h=c[n.charCodeAt(d-1)]<<d%4*2|c[n.charCodeAt(d)]>>>6-d%4*2;o[l>>>2]|=h<<24-l%4*8,l++}return t.create(o,l)}e.enc.Base64={stringify:function(n){var a=n.words,c=n.sigBytes,o=this._map;n.clamp();for(var l=[],d=0;d<c;d+=3)for(var h=(a[d>>>2]>>>24-d%4*8&255)<<16|(a[d+1>>>2]>>>24-(d+1)%4*8&255)<<8|a[d+2>>>2]>>>24-(d+2)%4*8&255,u=0;u<4&&d+.75*u<c;u++)l.push(o.charAt(h>>>6*(3-u)&63));var p=o.charAt(64);if(p)for(;l.length%4;)l.push(p);return l.join("")},parse:function(n){var a=n.length,c=this._map,o=this._reverseMap;if(!o){o=this._reverseMap=[];for(var l=0;l<c.length;l++)o[c.charCodeAt(l)]=l}var d=c.charAt(64);if(d){var h=n.indexOf(d);h!==-1&&(a=h)}return i(n,a,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),r.enc.Base64}(Ce())}(va)),va.exports}var Ra,Ea={exports:{}};function Sh(){return Ra||(Ra=1,function(s){s.exports=function(r){return function(){var e=r,t=e.lib.WordArray;function i(n,a,c){for(var o=[],l=0,d=0;d<a;d++)if(d%4){var h=c[n.charCodeAt(d-1)]<<d%4*2|c[n.charCodeAt(d)]>>>6-d%4*2;o[l>>>2]|=h<<24-l%4*8,l++}return t.create(o,l)}e.enc.Base64url={stringify:function(n,a){a===void 0&&(a=!0);var c=n.words,o=n.sigBytes,l=a?this._safe_map:this._map;n.clamp();for(var d=[],h=0;h<o;h+=3)for(var u=(c[h>>>2]>>>24-h%4*8&255)<<16|(c[h+1>>>2]>>>24-(h+1)%4*8&255)<<8|c[h+2>>>2]>>>24-(h+2)%4*8&255,p=0;p<4&&h+.75*p<o;p++)d.push(l.charAt(u>>>6*(3-p)&63));var f=l.charAt(64);if(f)for(;d.length%4;)d.push(f);return d.join("")},parse:function(n,a){a===void 0&&(a=!0);var c=n.length,o=a?this._safe_map:this._map,l=this._reverseMap;if(!l){l=this._reverseMap=[];for(var d=0;d<o.length;d++)l[o.charCodeAt(d)]=d}var h=o.charAt(64);if(h){var u=n.indexOf(h);u!==-1&&(c=u)}return i(n,c,l)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_safe_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"}}(),r.enc.Base64url}(Ce())}(Ea)),Ea.exports}var ya,Ta={exports:{}};function wr(){return ya||(ya=1,function(s){s.exports=function(r){return function(e){var t=r,i=t.lib,n=i.WordArray,a=i.Hasher,c=t.algo,o=[];(function(){for(var f=0;f<64;f++)o[f]=4294967296*e.abs(e.sin(f+1))|0})();var l=c.MD5=a.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(f,m){for(var g=0;g<16;g++){var S=m+g,v=f[S];f[S]=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8)}var E=this._hash.words,T=f[m+0],R=f[m+1],y=f[m+2],C=f[m+3],w=f[m+4],A=f[m+5],P=f[m+6],M=f[m+7],I=f[m+8],j=f[m+9],K=f[m+10],B=f[m+11],F=f[m+12],X=f[m+13],$=f[m+14],se=f[m+15],N=E[0],V=E[1],x=E[2],U=E[3];N=d(N,V,x,U,T,7,o[0]),U=d(U,N,V,x,R,12,o[1]),x=d(x,U,N,V,y,17,o[2]),V=d(V,x,U,N,C,22,o[3]),N=d(N,V,x,U,w,7,o[4]),U=d(U,N,V,x,A,12,o[5]),x=d(x,U,N,V,P,17,o[6]),V=d(V,x,U,N,M,22,o[7]),N=d(N,V,x,U,I,7,o[8]),U=d(U,N,V,x,j,12,o[9]),x=d(x,U,N,V,K,17,o[10]),V=d(V,x,U,N,B,22,o[11]),N=d(N,V,x,U,F,7,o[12]),U=d(U,N,V,x,X,12,o[13]),x=d(x,U,N,V,$,17,o[14]),N=h(N,V=d(V,x,U,N,se,22,o[15]),x,U,R,5,o[16]),U=h(U,N,V,x,P,9,o[17]),x=h(x,U,N,V,B,14,o[18]),V=h(V,x,U,N,T,20,o[19]),N=h(N,V,x,U,A,5,o[20]),U=h(U,N,V,x,K,9,o[21]),x=h(x,U,N,V,se,14,o[22]),V=h(V,x,U,N,w,20,o[23]),N=h(N,V,x,U,j,5,o[24]),U=h(U,N,V,x,$,9,o[25]),x=h(x,U,N,V,C,14,o[26]),V=h(V,x,U,N,I,20,o[27]),N=h(N,V,x,U,X,5,o[28]),U=h(U,N,V,x,y,9,o[29]),x=h(x,U,N,V,M,14,o[30]),N=u(N,V=h(V,x,U,N,F,20,o[31]),x,U,A,4,o[32]),U=u(U,N,V,x,I,11,o[33]),x=u(x,U,N,V,B,16,o[34]),V=u(V,x,U,N,$,23,o[35]),N=u(N,V,x,U,R,4,o[36]),U=u(U,N,V,x,w,11,o[37]),x=u(x,U,N,V,M,16,o[38]),V=u(V,x,U,N,K,23,o[39]),N=u(N,V,x,U,X,4,o[40]),U=u(U,N,V,x,T,11,o[41]),x=u(x,U,N,V,C,16,o[42]),V=u(V,x,U,N,P,23,o[43]),N=u(N,V,x,U,j,4,o[44]),U=u(U,N,V,x,F,11,o[45]),x=u(x,U,N,V,se,16,o[46]),N=p(N,V=u(V,x,U,N,y,23,o[47]),x,U,T,6,o[48]),U=p(U,N,V,x,M,10,o[49]),x=p(x,U,N,V,$,15,o[50]),V=p(V,x,U,N,A,21,o[51]),N=p(N,V,x,U,F,6,o[52]),U=p(U,N,V,x,C,10,o[53]),x=p(x,U,N,V,K,15,o[54]),V=p(V,x,U,N,R,21,o[55]),N=p(N,V,x,U,I,6,o[56]),U=p(U,N,V,x,se,10,o[57]),x=p(x,U,N,V,P,15,o[58]),V=p(V,x,U,N,X,21,o[59]),N=p(N,V,x,U,w,6,o[60]),U=p(U,N,V,x,B,10,o[61]),x=p(x,U,N,V,y,15,o[62]),V=p(V,x,U,N,j,21,o[63]),E[0]=E[0]+N|0,E[1]=E[1]+V|0,E[2]=E[2]+x|0,E[3]=E[3]+U|0},_doFinalize:function(){var f=this._data,m=f.words,g=8*this._nDataBytes,S=8*f.sigBytes;m[S>>>5]|=128<<24-S%32;var v=e.floor(g/4294967296),E=g;m[15+(S+64>>>9<<4)]=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),m[14+(S+64>>>9<<4)]=16711935&(E<<8|E>>>24)|4278255360&(E<<24|E>>>8),f.sigBytes=4*(m.length+1),this._process();for(var T=this._hash,R=T.words,y=0;y<4;y++){var C=R[y];R[y]=16711935&(C<<8|C>>>24)|4278255360&(C<<24|C>>>8)}return T},clone:function(){var f=a.clone.call(this);return f._hash=this._hash.clone(),f}});function d(f,m,g,S,v,E,T){var R=f+(m&g|~m&S)+v+T;return(R<<E|R>>>32-E)+m}function h(f,m,g,S,v,E,T){var R=f+(m&S|g&~S)+v+T;return(R<<E|R>>>32-E)+m}function u(f,m,g,S,v,E,T){var R=f+(m^g^S)+v+T;return(R<<E|R>>>32-E)+m}function p(f,m,g,S,v,E,T){var R=f+(g^(m|~S))+v+T;return(R<<E|R>>>32-E)+m}t.MD5=a._createHelper(l),t.HmacMD5=a._createHmacHelper(l)}(Math),r.MD5}(Ce())}(Ta)),Ta.exports}var Ca,_a={exports:{}};function wa(){return Ca||(Ca=1,function(s){s.exports=function(r){return t=(e=r).lib,i=t.WordArray,n=t.Hasher,a=e.algo,c=[],o=a.SHA1=n.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(l,d){for(var h=this._hash.words,u=h[0],p=h[1],f=h[2],m=h[3],g=h[4],S=0;S<80;S++){if(S<16)c[S]=0|l[d+S];else{var v=c[S-3]^c[S-8]^c[S-14]^c[S-16];c[S]=v<<1|v>>>31}var E=(u<<5|u>>>27)+g+c[S];E+=S<20?1518500249+(p&f|~p&m):S<40?1859775393+(p^f^m):S<60?(p&f|p&m|f&m)-1894007588:(p^f^m)-899497514,g=m,m=f,f=p<<30|p>>>2,p=u,u=E}h[0]=h[0]+u|0,h[1]=h[1]+p|0,h[2]=h[2]+f|0,h[3]=h[3]+m|0,h[4]=h[4]+g|0},_doFinalize:function(){var l=this._data,d=l.words,h=8*this._nDataBytes,u=8*l.sigBytes;return d[u>>>5]|=128<<24-u%32,d[14+(u+64>>>9<<4)]=Math.floor(h/4294967296),d[15+(u+64>>>9<<4)]=h,l.sigBytes=4*d.length,this._process(),this._hash},clone:function(){var l=n.clone.call(this);return l._hash=this._hash.clone(),l}}),e.SHA1=n._createHelper(o),e.HmacSHA1=n._createHmacHelper(o),r.SHA1;var e,t,i,n,a,c,o}(Ce())}(_a)),_a.exports}var Aa,Ia={exports:{}};function As(){return Aa||(Aa=1,function(s){s.exports=function(r){return function(e){var t=r,i=t.lib,n=i.WordArray,a=i.Hasher,c=t.algo,o=[],l=[];(function(){function u(g){for(var S=e.sqrt(g),v=2;v<=S;v++)if(!(g%v))return!1;return!0}function p(g){return 4294967296*(g-(0|g))|0}for(var f=2,m=0;m<64;)u(f)&&(m<8&&(o[m]=p(e.pow(f,.5))),l[m]=p(e.pow(f,1/3)),m++),f++})();var d=[],h=c.SHA256=a.extend({_doReset:function(){this._hash=new n.init(o.slice(0))},_doProcessBlock:function(u,p){for(var f=this._hash.words,m=f[0],g=f[1],S=f[2],v=f[3],E=f[4],T=f[5],R=f[6],y=f[7],C=0;C<64;C++){if(C<16)d[C]=0|u[p+C];else{var w=d[C-15],A=(w<<25|w>>>7)^(w<<14|w>>>18)^w>>>3,P=d[C-2],M=(P<<15|P>>>17)^(P<<13|P>>>19)^P>>>10;d[C]=A+d[C-7]+M+d[C-16]}var I=m&g^m&S^g&S,j=(m<<30|m>>>2)^(m<<19|m>>>13)^(m<<10|m>>>22),K=y+((E<<26|E>>>6)^(E<<21|E>>>11)^(E<<7|E>>>25))+(E&T^~E&R)+l[C]+d[C];y=R,R=T,T=E,E=v+K|0,v=S,S=g,g=m,m=K+(j+I)|0}f[0]=f[0]+m|0,f[1]=f[1]+g|0,f[2]=f[2]+S|0,f[3]=f[3]+v|0,f[4]=f[4]+E|0,f[5]=f[5]+T|0,f[6]=f[6]+R|0,f[7]=f[7]+y|0},_doFinalize:function(){var u=this._data,p=u.words,f=8*this._nDataBytes,m=8*u.sigBytes;return p[m>>>5]|=128<<24-m%32,p[14+(m+64>>>9<<4)]=e.floor(f/4294967296),p[15+(m+64>>>9<<4)]=f,u.sigBytes=4*p.length,this._process(),this._hash},clone:function(){var u=a.clone.call(this);return u._hash=this._hash.clone(),u}});t.SHA256=a._createHelper(h),t.HmacSHA256=a._createHmacHelper(h)}(Math),r.SHA256}(Ce())}(Ia)),Ia.exports}var Pa,bh={exports:{}},Da,ka={exports:{}};function Ma(){return Da||(Da=1,function(s){s.exports=function(r){return function(){var e=r,t=e.lib.Hasher,i=e.x64,n=i.Word,a=i.WordArray,c=e.algo;function o(){return n.create.apply(n,arguments)}var l=[o(1116352408,3609767458),o(1899447441,602891725),o(3049323471,3964484399),o(3921009573,2173295548),o(961987163,4081628472),o(1508970993,3053834265),o(2453635748,2937671579),o(2870763221,3664609560),o(3624381080,2734883394),o(310598401,1164996542),o(607225278,1323610764),o(1426881987,3590304994),o(1925078388,4068182383),o(2162078206,991336113),o(2614888103,633803317),o(3248222580,3479774868),o(3835390401,2666613458),o(4022224774,944711139),o(264347078,2341262773),o(604807628,2007800933),o(770255983,1495990901),o(1249150122,1856431235),o(1555081692,3175218132),o(1996064986,2198950837),o(2554220882,3999719339),o(2821834349,766784016),o(2952996808,2566594879),o(3210313671,3203337956),o(3336571891,1034457026),o(3584528711,2466948901),o(113926993,3758326383),o(338241895,168717936),o(666307205,1188179964),o(773529912,1546045734),o(1294757372,1522805485),o(1396182291,2643833823),o(1695183700,2343527390),o(1986661051,1014477480),o(2177026350,1206759142),o(2456956037,344077627),o(2730485921,1290863460),o(2820302411,3158454273),o(3259730800,3505952657),o(3345764771,106217008),o(3516065817,3606008344),o(3600352804,1432725776),o(4094571909,1467031594),o(275423344,851169720),o(430227734,3100823752),o(506948616,1363258195),o(659060556,3750685593),o(883997877,3785050280),o(958139571,3318307427),o(1322822218,3812723403),o(1537002063,2003034995),o(1747873779,3602036899),o(1955562222,1575990012),o(2024104815,1125592928),o(2227730452,2716904306),o(2361852424,442776044),o(2428436474,593698344),o(2756734187,3733110249),o(3204031479,2999351573),o(3329325298,3815920427),o(3391569614,3928383900),o(3515267271,566280711),o(3940187606,3454069534),o(4118630271,4000239992),o(116418474,1914138554),o(174292421,2731055270),o(289380356,3203993006),o(460393269,320620315),o(685471733,587496836),o(852142971,1086792851),o(1017036298,365543100),o(1126000580,2618297676),o(1288033470,3409855158),o(1501505948,4234509866),o(1607167915,987167468),o(1816402316,1246189591)],d=[];(function(){for(var u=0;u<80;u++)d[u]=o()})();var h=c.SHA512=t.extend({_doReset:function(){this._hash=new a.init([new n.init(1779033703,4089235720),new n.init(3144134277,2227873595),new n.init(1013904242,4271175723),new n.init(2773480762,1595750129),new n.init(1359893119,2917565137),new n.init(2600822924,725511199),new n.init(528734635,4215389547),new n.init(1541459225,327033209)])},_doProcessBlock:function(u,p){for(var f=this._hash.words,m=f[0],g=f[1],S=f[2],v=f[3],E=f[4],T=f[5],R=f[6],y=f[7],C=m.high,w=m.low,A=g.high,P=g.low,M=S.high,I=S.low,j=v.high,K=v.low,B=E.high,F=E.low,X=T.high,$=T.low,se=R.high,N=R.low,V=y.high,x=y.low,U=C,ce=w,ue=A,te=P,Re=M,He=I,Ve=j,je=K,_e=B,Ue=F,ye=X,Ge=$,Oe=se,mt=N,At=V,Se=x,le=0;le<80;le++){var ae,Ie,Ze=d[le];if(le<16)Ie=Ze.high=0|u[p+2*le],ae=Ze.low=0|u[p+2*le+1];else{var Te=d[le-15],at=Te.high,re=Te.low,dt=(at>>>1|re<<31)^(at>>>8|re<<24)^at>>>7,It=(re>>>1|at<<31)^(re>>>8|at<<24)^(re>>>7|at<<25),Ke=d[le-2],Qt=Ke.high,or=Ke.low,qt=(Qt>>>19|or<<13)^(Qt<<3|or>>>29)^Qt>>>6,Tr=(or>>>19|Qt<<13)^(or<<3|Qt>>>29)^(or>>>6|Qt<<26),Li=d[le-7],_s=Li.high,Km=Li.low,sh=d[le-16],Jm=sh.high,nh=sh.low;Ie=(Ie=(Ie=dt+_s+((ae=It+Km)>>>0<It>>>0?1:0))+qt+((ae+=Tr)>>>0<Tr>>>0?1:0))+Jm+((ae+=nh)>>>0<nh>>>0?1:0),Ze.high=Ie,Ze.low=ae}var zr,$m=_e&ye^~_e&Oe,ah=Ue&Ge^~Ue&mt,Xm=U&ue^U&Re^ue&Re,Zm=ce&te^ce&He^te&He,Ym=(U>>>28|ce<<4)^(U<<30|ce>>>2)^(U<<25|ce>>>7),oh=(ce>>>28|U<<4)^(ce<<30|U>>>2)^(ce<<25|U>>>7),Qm=(_e>>>14|Ue<<18)^(_e>>>18|Ue<<14)^(_e<<23|Ue>>>9),qm=(Ue>>>14|_e<<18)^(Ue>>>18|_e<<14)^(Ue<<23|_e>>>9),ch=l[le],ef=ch.high,dh=ch.low,xi=At+Qm+((zr=Se+qm)>>>0<Se>>>0?1:0),lh=oh+Zm;At=Oe,Se=mt,Oe=ye,mt=Ge,ye=_e,Ge=Ue,_e=Ve+(xi=(xi=(xi=xi+$m+((zr+=ah)>>>0<ah>>>0?1:0))+ef+((zr+=dh)>>>0<dh>>>0?1:0))+Ie+((zr+=ae)>>>0<ae>>>0?1:0))+((Ue=je+zr|0)>>>0<je>>>0?1:0)|0,Ve=Re,je=He,Re=ue,He=te,ue=U,te=ce,U=xi+(Ym+Xm+(lh>>>0<oh>>>0?1:0))+((ce=zr+lh|0)>>>0<zr>>>0?1:0)|0}w=m.low=w+ce,m.high=C+U+(w>>>0<ce>>>0?1:0),P=g.low=P+te,g.high=A+ue+(P>>>0<te>>>0?1:0),I=S.low=I+He,S.high=M+Re+(I>>>0<He>>>0?1:0),K=v.low=K+je,v.high=j+Ve+(K>>>0<je>>>0?1:0),F=E.low=F+Ue,E.high=B+_e+(F>>>0<Ue>>>0?1:0),$=T.low=$+Ge,T.high=X+ye+($>>>0<Ge>>>0?1:0),N=R.low=N+mt,R.high=se+Oe+(N>>>0<mt>>>0?1:0),x=y.low=x+Se,y.high=V+At+(x>>>0<Se>>>0?1:0)},_doFinalize:function(){var u=this._data,p=u.words,f=8*this._nDataBytes,m=8*u.sigBytes;return p[m>>>5]|=128<<24-m%32,p[30+(m+128>>>10<<5)]=Math.floor(f/4294967296),p[31+(m+128>>>10<<5)]=f,u.sigBytes=4*p.length,this._process(),this._hash.toX32()},clone:function(){var u=t.clone.call(this);return u._hash=this._hash.clone(),u},blockSize:32});e.SHA512=t._createHelper(h),e.HmacSHA512=t._createHmacHelper(h)}(),r.SHA512}(Ce(),Ui())}(ka)),ka.exports}var Oa,vh={exports:{}},Na,La={exports:{}};function Rh(){return Na||(Na=1,function(s){s.exports=function(r){return function(e){var t=r,i=t.lib,n=i.WordArray,a=i.Hasher,c=t.x64.Word,o=t.algo,l=[],d=[],h=[];(function(){for(var f=1,m=0,g=0;g<24;g++){l[f+5*m]=(g+1)*(g+2)/2%64;var S=(2*f+3*m)%5;f=m%5,m=S}for(f=0;f<5;f++)for(m=0;m<5;m++)d[f+5*m]=m+(2*f+3*m)%5*5;for(var v=1,E=0;E<24;E++){for(var T=0,R=0,y=0;y<7;y++){if(1&v){var C=(1<<y)-1;C<32?R^=1<<C:T^=1<<C-32}128&v?v=v<<1^113:v<<=1}h[E]=c.create(T,R)}})();var u=[];(function(){for(var f=0;f<25;f++)u[f]=c.create()})();var p=o.SHA3=a.extend({cfg:a.cfg.extend({outputLength:512}),_doReset:function(){for(var f=this._state=[],m=0;m<25;m++)f[m]=new c.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(f,m){for(var g=this._state,S=this.blockSize/2,v=0;v<S;v++){var E=f[m+2*v],T=f[m+2*v+1];E=16711935&(E<<8|E>>>24)|4278255360&(E<<24|E>>>8),T=16711935&(T<<8|T>>>24)|4278255360&(T<<24|T>>>8),(x=g[v]).high^=T,x.low^=E}for(var R=0;R<24;R++){for(var y=0;y<5;y++){for(var C=0,w=0,A=0;A<5;A++)C^=(x=g[y+5*A]).high,w^=x.low;var P=u[y];P.high=C,P.low=w}for(y=0;y<5;y++){var M=u[(y+4)%5],I=u[(y+1)%5],j=I.high,K=I.low;for(C=M.high^(j<<1|K>>>31),w=M.low^(K<<1|j>>>31),A=0;A<5;A++)(x=g[y+5*A]).high^=C,x.low^=w}for(var B=1;B<25;B++){var F=(x=g[B]).high,X=x.low,$=l[B];$<32?(C=F<<$|X>>>32-$,w=X<<$|F>>>32-$):(C=X<<$-32|F>>>64-$,w=F<<$-32|X>>>64-$);var se=u[d[B]];se.high=C,se.low=w}var N=u[0],V=g[0];for(N.high=V.high,N.low=V.low,y=0;y<5;y++)for(A=0;A<5;A++){var x=g[B=y+5*A],U=u[B],ce=u[(y+1)%5+5*A],ue=u[(y+2)%5+5*A];x.high=U.high^~ce.high&ue.high,x.low=U.low^~ce.low&ue.low}x=g[0];var te=h[R];x.high^=te.high,x.low^=te.low}},_doFinalize:function(){var f=this._data,m=f.words;this._nDataBytes;var g=8*f.sigBytes,S=32*this.blockSize;m[g>>>5]|=1<<24-g%32,m[(e.ceil((g+1)/S)*S>>>5)-1]|=128,f.sigBytes=4*m.length,this._process();for(var v=this._state,E=this.cfg.outputLength/8,T=E/8,R=[],y=0;y<T;y++){var C=v[y],w=C.high,A=C.low;w=16711935&(w<<8|w>>>24)|4278255360&(w<<24|w>>>8),A=16711935&(A<<8|A>>>24)|4278255360&(A<<24|A>>>8),R.push(A),R.push(w)}return new n.init(R,E)},clone:function(){for(var f=a.clone.call(this),m=f._state=this._state.slice(0),g=0;g<25;g++)m[g]=m[g].clone();return f}});t.SHA3=a._createHelper(p),t.HmacSHA3=a._createHmacHelper(p)}(Math),r.SHA3}(Ce(),Ui())}(La)),La.exports}var xa,Eh={exports:{}},Va,Ua={exports:{}};function Is(){return Va||(Va=1,function(s){s.exports=function(r){var e,t,i;t=(e=r).lib.Base,i=e.enc.Utf8,e.algo.HMAC=t.extend({init:function(n,a){n=this._hasher=new n.init,typeof a=="string"&&(a=i.parse(a));var c=n.blockSize,o=4*c;a.sigBytes>o&&(a=n.finalize(a)),a.clamp();for(var l=this._oKey=a.clone(),d=this._iKey=a.clone(),h=l.words,u=d.words,p=0;p<c;p++)h[p]^=1549556828,u[p]^=909522486;l.sigBytes=d.sigBytes=o,this.reset()},reset:function(){var n=this._hasher;n.reset(),n.update(this._iKey)},update:function(n){return this._hasher.update(n),this},finalize:function(n){var a=this._hasher,c=a.finalize(n);return a.reset(),a.finalize(this._oKey.clone().concat(c))}})}(Ce())}(Ua)),Ua.exports}var Ba,yh={exports:{}},Fa,Ha={exports:{}};function pr(){return Fa||(Fa=1,function(s){s.exports=function(r){return t=(e=r).lib,i=t.Base,n=t.WordArray,a=e.algo,c=a.MD5,o=a.EvpKDF=i.extend({cfg:i.extend({keySize:4,hasher:c,iterations:1}),init:function(l){this.cfg=this.cfg.extend(l)},compute:function(l,d){for(var h,u=this.cfg,p=u.hasher.create(),f=n.create(),m=f.words,g=u.keySize,S=u.iterations;m.length<g;){h&&p.update(h),h=p.update(l).finalize(d),p.reset();for(var v=1;v<S;v++)h=p.finalize(h),p.reset();f.concat(h)}return f.sigBytes=4*g,f}}),e.EvpKDF=function(l,d,h){return o.create(h).compute(l,d)},r.EvpKDF;var e,t,i,n,a,c,o}(Ce(),wa(),Is())}(Ha)),Ha.exports}var Wa,ja={exports:{}};function ot(){return Wa||(Wa=1,function(s){s.exports=function(r){r.lib.Cipher||function(e){var t=r,i=t.lib,n=i.Base,a=i.WordArray,c=i.BufferedBlockAlgorithm,o=t.enc;o.Utf8;var l=o.Base64,d=t.algo.EvpKDF,h=i.Cipher=c.extend({cfg:n.extend(),createEncryptor:function(R,y){return this.create(this._ENC_XFORM_MODE,R,y)},createDecryptor:function(R,y){return this.create(this._DEC_XFORM_MODE,R,y)},init:function(R,y,C){this.cfg=this.cfg.extend(C),this._xformMode=R,this._key=y,this.reset()},reset:function(){c.reset.call(this),this._doReset()},process:function(R){return this._append(R),this._process()},finalize:function(R){return R&&this._append(R),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function R(y){return typeof y=="string"?T:v}return function(y){return{encrypt:function(C,w,A){return R(w).encrypt(y,C,w,A)},decrypt:function(C,w,A){return R(w).decrypt(y,C,w,A)}}}}()});i.StreamCipher=h.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var u=t.mode={},p=i.BlockCipherMode=n.extend({createEncryptor:function(R,y){return this.Encryptor.create(R,y)},createDecryptor:function(R,y){return this.Decryptor.create(R,y)},init:function(R,y){this._cipher=R,this._iv=y}}),f=u.CBC=function(){var R=p.extend();function y(C,w,A){var P,M=this._iv;M?(P=M,this._iv=e):P=this._prevBlock;for(var I=0;I<A;I++)C[w+I]^=P[I]}return R.Encryptor=R.extend({processBlock:function(C,w){var A=this._cipher,P=A.blockSize;y.call(this,C,w,P),A.encryptBlock(C,w),this._prevBlock=C.slice(w,w+P)}}),R.Decryptor=R.extend({processBlock:function(C,w){var A=this._cipher,P=A.blockSize,M=C.slice(w,w+P);A.decryptBlock(C,w),y.call(this,C,w,P),this._prevBlock=M}}),R}(),m=(t.pad={}).Pkcs7={pad:function(R,y){for(var C=4*y,w=C-R.sigBytes%C,A=w<<24|w<<16|w<<8|w,P=[],M=0;M<w;M+=4)P.push(A);var I=a.create(P,w);R.concat(I)},unpad:function(R){var y=255&R.words[R.sigBytes-1>>>2];R.sigBytes-=y}};i.BlockCipher=h.extend({cfg:h.cfg.extend({mode:f,padding:m}),reset:function(){var R;h.reset.call(this);var y=this.cfg,C=y.iv,w=y.mode;this._xformMode==this._ENC_XFORM_MODE?R=w.createEncryptor:(R=w.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==R?this._mode.init(this,C&&C.words):(this._mode=R.call(w,this,C&&C.words),this._mode.__creator=R)},_doProcessBlock:function(R,y){this._mode.processBlock(R,y)},_doFinalize:function(){var R,y=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(y.pad(this._data,this.blockSize),R=this._process(!0)):(R=this._process(!0),y.unpad(R)),R},blockSize:4});var g=i.CipherParams=n.extend({init:function(R){this.mixIn(R)},toString:function(R){return(R||this.formatter).stringify(this)}}),S=(t.format={}).OpenSSL={stringify:function(R){var y=R.ciphertext,C=R.salt;return(C?a.create([1398893684,1701076831]).concat(C).concat(y):y).toString(l)},parse:function(R){var y,C=l.parse(R),w=C.words;return w[0]==1398893684&&w[1]==1701076831&&(y=a.create(w.slice(2,4)),w.splice(0,4),C.sigBytes-=16),g.create({ciphertext:C,salt:y})}},v=i.SerializableCipher=n.extend({cfg:n.extend({format:S}),encrypt:function(R,y,C,w){w=this.cfg.extend(w);var A=R.createEncryptor(C,w),P=A.finalize(y),M=A.cfg;return g.create({ciphertext:P,key:C,iv:M.iv,algorithm:R,mode:M.mode,padding:M.padding,blockSize:R.blockSize,formatter:w.format})},decrypt:function(R,y,C,w){return w=this.cfg.extend(w),y=this._parse(y,w.format),R.createDecryptor(C,w).finalize(y.ciphertext)},_parse:function(R,y){return typeof R=="string"?y.parse(R,this):R}}),E=(t.kdf={}).OpenSSL={execute:function(R,y,C,w,A){if(w||(w=a.random(8)),A)P=d.create({keySize:y+C,hasher:A}).compute(R,w);else var P=d.create({keySize:y+C}).compute(R,w);var M=a.create(P.words.slice(y),4*C);return P.sigBytes=4*y,g.create({key:P,iv:M,salt:w})}},T=i.PasswordBasedCipher=v.extend({cfg:v.cfg.extend({kdf:E}),encrypt:function(R,y,C,w){var A=(w=this.cfg.extend(w)).kdf.execute(C,R.keySize,R.ivSize,w.salt,w.hasher);w.iv=A.iv;var P=v.encrypt.call(this,R,y,A.key,w);return P.mixIn(A),P},decrypt:function(R,y,C,w){w=this.cfg.extend(w),y=this._parse(y,w.format);var A=w.kdf.execute(C,R.keySize,R.ivSize,y.salt,w.hasher);return w.iv=A.iv,v.decrypt.call(this,R,y,A.key,w)}})}()}(Ce(),pr())}(ja)),ja.exports}var Ga,za={exports:{}};function Th(){return Ga||(Ga=1,function(s){s.exports=function(r){return r.mode.CFB=function(){var e=r.lib.BlockCipherMode.extend();function t(i,n,a,c){var o,l=this._iv;l?(o=l.slice(0),this._iv=void 0):o=this._prevBlock,c.encryptBlock(o,0);for(var d=0;d<a;d++)i[n+d]^=o[d]}return e.Encryptor=e.extend({processBlock:function(i,n){var a=this._cipher,c=a.blockSize;t.call(this,i,n,c,a),this._prevBlock=i.slice(n,n+c)}}),e.Decryptor=e.extend({processBlock:function(i,n){var a=this._cipher,c=a.blockSize,o=i.slice(n,n+c);t.call(this,i,n,c,a),this._prevBlock=o}}),e}(),r.mode.CFB}(Ce(),ot())}(za)),za.exports}var Ka,Ja={exports:{}};function Ch(){return Ka||(Ka=1,function(s){s.exports=function(r){return r.mode.CTR=(e=r.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(i,n){var a=this._cipher,c=a.blockSize,o=this._iv,l=this._counter;o&&(l=this._counter=o.slice(0),this._iv=void 0);var d=l.slice(0);a.encryptBlock(d,0),l[c-1]=l[c-1]+1|0;for(var h=0;h<c;h++)i[n+h]^=d[h]}}),e.Decryptor=t,e),r.mode.CTR;var e,t}(Ce(),ot())}(Ja)),Ja.exports}var $a,Xa={exports:{}};function _h(){return $a||($a=1,function(s){s.exports=function(r){return r.mode.CTRGladman=function(){var e=r.lib.BlockCipherMode.extend();function t(a){if(255&~(a>>24))a+=1<<24;else{var c=a>>16&255,o=a>>8&255,l=255&a;c===255?(c=0,o===255?(o=0,l===255?l=0:++l):++o):++c,a=0,a+=c<<16,a+=o<<8,a+=l}return a}function i(a){return(a[0]=t(a[0]))===0&&(a[1]=t(a[1])),a}var n=e.Encryptor=e.extend({processBlock:function(a,c){var o=this._cipher,l=o.blockSize,d=this._iv,h=this._counter;d&&(h=this._counter=d.slice(0),this._iv=void 0),i(h);var u=h.slice(0);o.encryptBlock(u,0);for(var p=0;p<l;p++)a[c+p]^=u[p]}});return e.Decryptor=n,e}(),r.mode.CTRGladman}(Ce(),ot())}(Xa)),Xa.exports}var Za,Ya={exports:{}};function wh(){return Za||(Za=1,function(s){s.exports=function(r){return r.mode.OFB=(e=r.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(i,n){var a=this._cipher,c=a.blockSize,o=this._iv,l=this._keystream;o&&(l=this._keystream=o.slice(0),this._iv=void 0),a.encryptBlock(l,0);for(var d=0;d<c;d++)i[n+d]^=l[d]}}),e.Decryptor=t,e),r.mode.OFB;var e,t}(Ce(),ot())}(Ya)),Ya.exports}var Qa,Ah={exports:{}},qa,Ih={exports:{}},eo,Ph={exports:{}},to,Dh={exports:{}},ro,kh={exports:{}},io,Mh={exports:{}},so,Oh={exports:{}},no,Nh={exports:{}},ao,oo={exports:{}};function Lh(){return ao||(ao=1,function(s){s.exports=function(r){return function(){var e=r,t=e.lib,i=t.WordArray,n=t.BlockCipher,a=e.algo,c=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],o=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],l=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],d=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],h=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],u=a.DES=n.extend({_doReset:function(){for(var g=this._key.words,S=[],v=0;v<56;v++){var E=c[v]-1;S[v]=g[E>>>5]>>>31-E%32&1}for(var T=this._subKeys=[],R=0;R<16;R++){var y=T[R]=[],C=l[R];for(v=0;v<24;v++)y[v/6|0]|=S[(o[v]-1+C)%28]<<31-v%6,y[4+(v/6|0)]|=S[28+(o[v+24]-1+C)%28]<<31-v%6;for(y[0]=y[0]<<1|y[0]>>>31,v=1;v<7;v++)y[v]=y[v]>>>4*(v-1)+3;y[7]=y[7]<<5|y[7]>>>27}var w=this._invSubKeys=[];for(v=0;v<16;v++)w[v]=T[15-v]},encryptBlock:function(g,S){this._doCryptBlock(g,S,this._subKeys)},decryptBlock:function(g,S){this._doCryptBlock(g,S,this._invSubKeys)},_doCryptBlock:function(g,S,v){this._lBlock=g[S],this._rBlock=g[S+1],p.call(this,4,252645135),p.call(this,16,65535),f.call(this,2,858993459),f.call(this,8,16711935),p.call(this,1,1431655765);for(var E=0;E<16;E++){for(var T=v[E],R=this._lBlock,y=this._rBlock,C=0,w=0;w<8;w++)C|=d[w][((y^T[w])&h[w])>>>0];this._lBlock=y,this._rBlock=R^C}var A=this._lBlock;this._lBlock=this._rBlock,this._rBlock=A,p.call(this,1,1431655765),f.call(this,8,16711935),f.call(this,2,858993459),p.call(this,16,65535),p.call(this,4,252645135),g[S]=this._lBlock,g[S+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});function p(g,S){var v=(this._lBlock>>>g^this._rBlock)&S;this._rBlock^=v,this._lBlock^=v<<g}function f(g,S){var v=(this._rBlock>>>g^this._lBlock)&S;this._lBlock^=v,this._rBlock^=v<<g}e.DES=n._createHelper(u);var m=a.TripleDES=n.extend({_doReset:function(){var g=this._key.words;if(g.length!==2&&g.length!==4&&g.length<6)throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");var S=g.slice(0,2),v=g.length<4?g.slice(0,2):g.slice(2,4),E=g.length<6?g.slice(0,2):g.slice(4,6);this._des1=u.createEncryptor(i.create(S)),this._des2=u.createEncryptor(i.create(v)),this._des3=u.createEncryptor(i.create(E))},encryptBlock:function(g,S){this._des1.encryptBlock(g,S),this._des2.decryptBlock(g,S),this._des3.encryptBlock(g,S)},decryptBlock:function(g,S){this._des3.decryptBlock(g,S),this._des2.encryptBlock(g,S),this._des1.decryptBlock(g,S)},keySize:6,ivSize:2,blockSize:2});e.TripleDES=n._createHelper(m)}(),r.TripleDES}(Ce(),_r(),wr(),pr(),ot())}(oo)),oo.exports}var co,xh={exports:{}},lo,Vh={exports:{}},ho,Uh={exports:{}},uo,po={exports:{}};function Bh(){return uo||(uo=1,function(s){s.exports=function(r){return function(){var e=r,t=e.lib.BlockCipher,i=e.algo;const n=16,a=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],c=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]];var o={pbox:[],sbox:[]};function l(f,m){let g=m>>24&255,S=m>>16&255,v=m>>8&255,E=255&m,T=f.sbox[0][g]+f.sbox[1][S];return T^=f.sbox[2][v],T+=f.sbox[3][E],T}function d(f,m,g){let S,v=m,E=g;for(let T=0;T<n;++T)v^=f.pbox[T],E=l(f,v)^E,S=v,v=E,E=S;return S=v,v=E,E=S,E^=f.pbox[n],v^=f.pbox[n+1],{left:v,right:E}}function h(f,m,g){let S,v=m,E=g;for(let T=n+1;T>1;--T)v^=f.pbox[T],E=l(f,v)^E,S=v,v=E,E=S;return S=v,v=E,E=S,E^=f.pbox[1],v^=f.pbox[0],{left:v,right:E}}function u(f,m,g){for(let R=0;R<4;R++){f.sbox[R]=[];for(let y=0;y<256;y++)f.sbox[R][y]=c[R][y]}let S=0;for(let R=0;R<n+2;R++)f.pbox[R]=a[R]^m[S],S++,S>=g&&(S=0);let v=0,E=0,T=0;for(let R=0;R<n+2;R+=2)T=d(f,v,E),v=T.left,E=T.right,f.pbox[R]=v,f.pbox[R+1]=E;for(let R=0;R<4;R++)for(let y=0;y<256;y+=2)T=d(f,v,E),v=T.left,E=T.right,f.sbox[R][y]=v,f.sbox[R][y+1]=E;return!0}var p=i.Blowfish=t.extend({_doReset:function(){if(this._keyPriorReset!==this._key){var f=this._keyPriorReset=this._key,m=f.words,g=f.sigBytes/4;u(o,m,g)}},encryptBlock:function(f,m){var g=d(o,f[m],f[m+1]);f[m]=g.left,f[m+1]=g.right},decryptBlock:function(f,m){var g=h(o,f[m],f[m+1]);f[m]=g.left,f[m+1]=g.right},blockSize:2,keySize:4,ivSize:2});e.Blowfish=t._createHelper(p)}(),r.Blowfish}(Ce(),_r(),wr(),pr(),ot())}(po)),po.exports}(function(s){s.exports=function(r){return r}(Ce(),Ui(),fh(),gh(),_r(),Sh(),wr(),wa(),As(),Pa||(Pa=1,function(r){r.exports=function(e){return i=(t=e).lib.WordArray,n=t.algo,a=n.SHA256,c=n.SHA224=a.extend({_doReset:function(){this._hash=new i.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var o=a._doFinalize.call(this);return o.sigBytes-=4,o}}),t.SHA224=a._createHelper(c),t.HmacSHA224=a._createHmacHelper(c),e.SHA224;var t,i,n,a,c}(Ce(),As())}(bh)),Ma(),Oa||(Oa=1,function(r){r.exports=function(e){return i=(t=e).x64,n=i.Word,a=i.WordArray,c=t.algo,o=c.SHA512,l=c.SHA384=o.extend({_doReset:function(){this._hash=new a.init([new n.init(3418070365,3238371032),new n.init(1654270250,914150663),new n.init(2438529370,812702999),new n.init(355462360,4144912697),new n.init(1731405415,4290775857),new n.init(2394180231,1750603025),new n.init(3675008525,1694076839),new n.init(1203062813,3204075428)])},_doFinalize:function(){var d=o._doFinalize.call(this);return d.sigBytes-=16,d}}),t.SHA384=o._createHelper(l),t.HmacSHA384=o._createHmacHelper(l),e.SHA384;var t,i,n,a,c,o,l}(Ce(),Ui(),Ma())}(vh)),Rh(),xa||(xa=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib,n=i.WordArray,a=i.Hasher,c=t.algo,o=n.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),l=n.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),d=n.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),h=n.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),u=n.create([0,1518500249,1859775393,2400959708,2840853838]),p=n.create([1352829926,1548603684,1836072691,2053994217,0]),f=c.RIPEMD160=a.extend({_doReset:function(){this._hash=n.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(R,y){for(var C=0;C<16;C++){var w=y+C,A=R[w];R[w]=16711935&(A<<8|A>>>24)|4278255360&(A<<24|A>>>8)}var P,M,I,j,K,B,F,X,$,se,N,V=this._hash.words,x=u.words,U=p.words,ce=o.words,ue=l.words,te=d.words,Re=h.words;for(B=P=V[0],F=M=V[1],X=I=V[2],$=j=V[3],se=K=V[4],C=0;C<80;C+=1)N=P+R[y+ce[C]]|0,N+=C<16?m(M,I,j)+x[0]:C<32?g(M,I,j)+x[1]:C<48?S(M,I,j)+x[2]:C<64?v(M,I,j)+x[3]:E(M,I,j)+x[4],N=(N=T(N|=0,te[C]))+K|0,P=K,K=j,j=T(I,10),I=M,M=N,N=B+R[y+ue[C]]|0,N+=C<16?E(F,X,$)+U[0]:C<32?v(F,X,$)+U[1]:C<48?S(F,X,$)+U[2]:C<64?g(F,X,$)+U[3]:m(F,X,$)+U[4],N=(N=T(N|=0,Re[C]))+se|0,B=se,se=$,$=T(X,10),X=F,F=N;N=V[1]+I+$|0,V[1]=V[2]+j+se|0,V[2]=V[3]+K+B|0,V[3]=V[4]+P+F|0,V[4]=V[0]+M+X|0,V[0]=N},_doFinalize:function(){var R=this._data,y=R.words,C=8*this._nDataBytes,w=8*R.sigBytes;y[w>>>5]|=128<<24-w%32,y[14+(w+64>>>9<<4)]=16711935&(C<<8|C>>>24)|4278255360&(C<<24|C>>>8),R.sigBytes=4*(y.length+1),this._process();for(var A=this._hash,P=A.words,M=0;M<5;M++){var I=P[M];P[M]=16711935&(I<<8|I>>>24)|4278255360&(I<<24|I>>>8)}return A},clone:function(){var R=a.clone.call(this);return R._hash=this._hash.clone(),R}});function m(R,y,C){return R^y^C}function g(R,y,C){return R&y|~R&C}function S(R,y,C){return(R|~y)^C}function v(R,y,C){return R&C|y&~C}function E(R,y,C){return R^(y|~C)}function T(R,y){return R<<y|R>>>32-y}t.RIPEMD160=a._createHelper(f),t.HmacRIPEMD160=a._createHmacHelper(f)}(),e.RIPEMD160}(Ce())}(Eh)),Is(),Ba||(Ba=1,function(r){r.exports=function(e){return n=(i=(t=e).lib).Base,a=i.WordArray,o=(c=t.algo).SHA256,l=c.HMAC,d=c.PBKDF2=n.extend({cfg:n.extend({keySize:4,hasher:o,iterations:25e4}),init:function(h){this.cfg=this.cfg.extend(h)},compute:function(h,u){for(var p=this.cfg,f=l.create(p.hasher,h),m=a.create(),g=a.create([1]),S=m.words,v=g.words,E=p.keySize,T=p.iterations;S.length<E;){var R=f.update(u).finalize(g);f.reset();for(var y=R.words,C=y.length,w=R,A=1;A<T;A++){w=f.finalize(w),f.reset();for(var P=w.words,M=0;M<C;M++)y[M]^=P[M]}m.concat(R),v[0]++}return m.sigBytes=4*E,m}}),t.PBKDF2=function(h,u,p){return d.create(p).compute(h,u)},e.PBKDF2;var t,i,n,a,c,o,l,d}(Ce(),As(),Is())}(yh)),pr(),ot(),Th(),Ch(),_h(),wh(),Qa||(Qa=1,function(r){r.exports=function(e){return e.mode.ECB=((t=e.lib.BlockCipherMode.extend()).Encryptor=t.extend({processBlock:function(i,n){this._cipher.encryptBlock(i,n)}}),t.Decryptor=t.extend({processBlock:function(i,n){this._cipher.decryptBlock(i,n)}}),t),e.mode.ECB;var t}(Ce(),ot())}(Ah)),qa||(qa=1,function(r){r.exports=function(e){return e.pad.AnsiX923={pad:function(t,i){var n=t.sigBytes,a=4*i,c=a-n%a,o=n+c-1;t.clamp(),t.words[o>>>2]|=c<<24-o%4*8,t.sigBytes+=c},unpad:function(t){var i=255&t.words[t.sigBytes-1>>>2];t.sigBytes-=i}},e.pad.Ansix923}(Ce(),ot())}(Ih)),eo||(eo=1,function(r){r.exports=function(e){return e.pad.Iso10126={pad:function(t,i){var n=4*i,a=n-t.sigBytes%n;t.concat(e.lib.WordArray.random(a-1)).concat(e.lib.WordArray.create([a<<24],1))},unpad:function(t){var i=255&t.words[t.sigBytes-1>>>2];t.sigBytes-=i}},e.pad.Iso10126}(Ce(),ot())}(Ph)),to||(to=1,function(r){r.exports=function(e){return e.pad.Iso97971={pad:function(t,i){t.concat(e.lib.WordArray.create([2147483648],1)),e.pad.ZeroPadding.pad(t,i)},unpad:function(t){e.pad.ZeroPadding.unpad(t),t.sigBytes--}},e.pad.Iso97971}(Ce(),ot())}(Dh)),ro||(ro=1,function(r){r.exports=function(e){return e.pad.ZeroPadding={pad:function(t,i){var n=4*i;t.clamp(),t.sigBytes+=n-(t.sigBytes%n||n)},unpad:function(t){var i=t.words,n=t.sigBytes-1;for(n=t.sigBytes-1;n>=0;n--)if(i[n>>>2]>>>24-n%4*8&255){t.sigBytes=n+1;break}}},e.pad.ZeroPadding}(Ce(),ot())}(kh)),io||(io=1,function(r){r.exports=function(e){return e.pad.NoPadding={pad:function(){},unpad:function(){}},e.pad.NoPadding}(Ce(),ot())}(Mh)),so||(so=1,function(r){r.exports=function(e){return i=(t=e).lib.CipherParams,n=t.enc.Hex,t.format.Hex={stringify:function(a){return a.ciphertext.toString(n)},parse:function(a){var c=n.parse(a);return i.create({ciphertext:c})}},e.format.Hex;var t,i,n}(Ce(),ot())}(Oh)),no||(no=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib.BlockCipher,n=t.algo,a=[],c=[],o=[],l=[],d=[],h=[],u=[],p=[],f=[],m=[];(function(){for(var v=[],E=0;E<256;E++)v[E]=E<128?E<<1:E<<1^283;var T=0,R=0;for(E=0;E<256;E++){var y=R^R<<1^R<<2^R<<3^R<<4;y=y>>>8^255&y^99,a[T]=y,c[y]=T;var C=v[T],w=v[C],A=v[w],P=257*v[y]^16843008*y;o[T]=P<<24|P>>>8,l[T]=P<<16|P>>>16,d[T]=P<<8|P>>>24,h[T]=P,P=16843009*A^65537*w^257*C^16843008*T,u[y]=P<<24|P>>>8,p[y]=P<<16|P>>>16,f[y]=P<<8|P>>>24,m[y]=P,T?(T=C^v[v[v[A^C]]],R^=v[v[R]]):T=R=1}})();var g=[0,1,2,4,8,16,32,64,128,27,54],S=n.AES=i.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var v=this._keyPriorReset=this._key,E=v.words,T=v.sigBytes/4,R=4*((this._nRounds=T+6)+1),y=this._keySchedule=[],C=0;C<R;C++)C<T?y[C]=E[C]:(P=y[C-1],C%T?T>6&&C%T==4&&(P=a[P>>>24]<<24|a[P>>>16&255]<<16|a[P>>>8&255]<<8|a[255&P]):(P=a[(P=P<<8|P>>>24)>>>24]<<24|a[P>>>16&255]<<16|a[P>>>8&255]<<8|a[255&P],P^=g[C/T|0]<<24),y[C]=y[C-T]^P);for(var w=this._invKeySchedule=[],A=0;A<R;A++){if(C=R-A,A%4)var P=y[C];else P=y[C-4];w[A]=A<4||C<=4?P:u[a[P>>>24]]^p[a[P>>>16&255]]^f[a[P>>>8&255]]^m[a[255&P]]}}},encryptBlock:function(v,E){this._doCryptBlock(v,E,this._keySchedule,o,l,d,h,a)},decryptBlock:function(v,E){var T=v[E+1];v[E+1]=v[E+3],v[E+3]=T,this._doCryptBlock(v,E,this._invKeySchedule,u,p,f,m,c),T=v[E+1],v[E+1]=v[E+3],v[E+3]=T},_doCryptBlock:function(v,E,T,R,y,C,w,A){for(var P=this._nRounds,M=v[E]^T[0],I=v[E+1]^T[1],j=v[E+2]^T[2],K=v[E+3]^T[3],B=4,F=1;F<P;F++){var X=R[M>>>24]^y[I>>>16&255]^C[j>>>8&255]^w[255&K]^T[B++],$=R[I>>>24]^y[j>>>16&255]^C[K>>>8&255]^w[255&M]^T[B++],se=R[j>>>24]^y[K>>>16&255]^C[M>>>8&255]^w[255&I]^T[B++],N=R[K>>>24]^y[M>>>16&255]^C[I>>>8&255]^w[255&j]^T[B++];M=X,I=$,j=se,K=N}X=(A[M>>>24]<<24|A[I>>>16&255]<<16|A[j>>>8&255]<<8|A[255&K])^T[B++],$=(A[I>>>24]<<24|A[j>>>16&255]<<16|A[K>>>8&255]<<8|A[255&M])^T[B++],se=(A[j>>>24]<<24|A[K>>>16&255]<<16|A[M>>>8&255]<<8|A[255&I])^T[B++],N=(A[K>>>24]<<24|A[M>>>16&255]<<16|A[I>>>8&255]<<8|A[255&j])^T[B++],v[E]=X,v[E+1]=$,v[E+2]=se,v[E+3]=N},keySize:8});t.AES=i._createHelper(S)}(),e.AES}(Ce(),_r(),wr(),pr(),ot())}(Nh)),Lh(),co||(co=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,n=t.algo,a=n.RC4=i.extend({_doReset:function(){for(var l=this._key,d=l.words,h=l.sigBytes,u=this._S=[],p=0;p<256;p++)u[p]=p;p=0;for(var f=0;p<256;p++){var m=p%h,g=d[m>>>2]>>>24-m%4*8&255;f=(f+u[p]+g)%256;var S=u[p];u[p]=u[f],u[f]=S}this._i=this._j=0},_doProcessBlock:function(l,d){l[d]^=c.call(this)},keySize:8,ivSize:0});function c(){for(var l=this._S,d=this._i,h=this._j,u=0,p=0;p<4;p++){h=(h+l[d=(d+1)%256])%256;var f=l[d];l[d]=l[h],l[h]=f,u|=l[(l[d]+l[h])%256]<<24-8*p}return this._i=d,this._j=h,u}t.RC4=i._createHelper(a);var o=n.RC4Drop=a.extend({cfg:a.cfg.extend({drop:192}),_doReset:function(){a._doReset.call(this);for(var l=this.cfg.drop;l>0;l--)c.call(this)}});t.RC4Drop=i._createHelper(o)}(),e.RC4}(Ce(),_r(),wr(),pr(),ot())}(xh)),lo||(lo=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,n=t.algo,a=[],c=[],o=[],l=n.Rabbit=i.extend({_doReset:function(){for(var h=this._key.words,u=this.cfg.iv,p=0;p<4;p++)h[p]=16711935&(h[p]<<8|h[p]>>>24)|4278255360&(h[p]<<24|h[p]>>>8);var f=this._X=[h[0],h[3]<<16|h[2]>>>16,h[1],h[0]<<16|h[3]>>>16,h[2],h[1]<<16|h[0]>>>16,h[3],h[2]<<16|h[1]>>>16],m=this._C=[h[2]<<16|h[2]>>>16,4294901760&h[0]|65535&h[1],h[3]<<16|h[3]>>>16,4294901760&h[1]|65535&h[2],h[0]<<16|h[0]>>>16,4294901760&h[2]|65535&h[3],h[1]<<16|h[1]>>>16,4294901760&h[3]|65535&h[0]];for(this._b=0,p=0;p<4;p++)d.call(this);for(p=0;p<8;p++)m[p]^=f[p+4&7];if(u){var g=u.words,S=g[0],v=g[1],E=16711935&(S<<8|S>>>24)|4278255360&(S<<24|S>>>8),T=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),R=E>>>16|4294901760&T,y=T<<16|65535&E;for(m[0]^=E,m[1]^=R,m[2]^=T,m[3]^=y,m[4]^=E,m[5]^=R,m[6]^=T,m[7]^=y,p=0;p<4;p++)d.call(this)}},_doProcessBlock:function(h,u){var p=this._X;d.call(this),a[0]=p[0]^p[5]>>>16^p[3]<<16,a[1]=p[2]^p[7]>>>16^p[5]<<16,a[2]=p[4]^p[1]>>>16^p[7]<<16,a[3]=p[6]^p[3]>>>16^p[1]<<16;for(var f=0;f<4;f++)a[f]=16711935&(a[f]<<8|a[f]>>>24)|4278255360&(a[f]<<24|a[f]>>>8),h[u+f]^=a[f]},blockSize:4,ivSize:2});function d(){for(var h=this._X,u=this._C,p=0;p<8;p++)c[p]=u[p];for(u[0]=u[0]+1295307597+this._b|0,u[1]=u[1]+3545052371+(u[0]>>>0<c[0]>>>0?1:0)|0,u[2]=u[2]+886263092+(u[1]>>>0<c[1]>>>0?1:0)|0,u[3]=u[3]+1295307597+(u[2]>>>0<c[2]>>>0?1:0)|0,u[4]=u[4]+3545052371+(u[3]>>>0<c[3]>>>0?1:0)|0,u[5]=u[5]+886263092+(u[4]>>>0<c[4]>>>0?1:0)|0,u[6]=u[6]+1295307597+(u[5]>>>0<c[5]>>>0?1:0)|0,u[7]=u[7]+3545052371+(u[6]>>>0<c[6]>>>0?1:0)|0,this._b=u[7]>>>0<c[7]>>>0?1:0,p=0;p<8;p++){var f=h[p]+u[p],m=65535&f,g=f>>>16,S=((m*m>>>17)+m*g>>>15)+g*g,v=((4294901760&f)*f|0)+((65535&f)*f|0);o[p]=S^v}h[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,h[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,h[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,h[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,h[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,h[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,h[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,h[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}t.Rabbit=i._createHelper(l)}(),e.Rabbit}(Ce(),_r(),wr(),pr(),ot())}(Vh)),ho||(ho=1,function(r){r.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,n=t.algo,a=[],c=[],o=[],l=n.RabbitLegacy=i.extend({_doReset:function(){var h=this._key.words,u=this.cfg.iv,p=this._X=[h[0],h[3]<<16|h[2]>>>16,h[1],h[0]<<16|h[3]>>>16,h[2],h[1]<<16|h[0]>>>16,h[3],h[2]<<16|h[1]>>>16],f=this._C=[h[2]<<16|h[2]>>>16,4294901760&h[0]|65535&h[1],h[3]<<16|h[3]>>>16,4294901760&h[1]|65535&h[2],h[0]<<16|h[0]>>>16,4294901760&h[2]|65535&h[3],h[1]<<16|h[1]>>>16,4294901760&h[3]|65535&h[0]];this._b=0;for(var m=0;m<4;m++)d.call(this);for(m=0;m<8;m++)f[m]^=p[m+4&7];if(u){var g=u.words,S=g[0],v=g[1],E=16711935&(S<<8|S>>>24)|4278255360&(S<<24|S>>>8),T=16711935&(v<<8|v>>>24)|4278255360&(v<<24|v>>>8),R=E>>>16|4294901760&T,y=T<<16|65535&E;for(f[0]^=E,f[1]^=R,f[2]^=T,f[3]^=y,f[4]^=E,f[5]^=R,f[6]^=T,f[7]^=y,m=0;m<4;m++)d.call(this)}},_doProcessBlock:function(h,u){var p=this._X;d.call(this),a[0]=p[0]^p[5]>>>16^p[3]<<16,a[1]=p[2]^p[7]>>>16^p[5]<<16,a[2]=p[4]^p[1]>>>16^p[7]<<16,a[3]=p[6]^p[3]>>>16^p[1]<<16;for(var f=0;f<4;f++)a[f]=16711935&(a[f]<<8|a[f]>>>24)|4278255360&(a[f]<<24|a[f]>>>8),h[u+f]^=a[f]},blockSize:4,ivSize:2});function d(){for(var h=this._X,u=this._C,p=0;p<8;p++)c[p]=u[p];for(u[0]=u[0]+1295307597+this._b|0,u[1]=u[1]+3545052371+(u[0]>>>0<c[0]>>>0?1:0)|0,u[2]=u[2]+886263092+(u[1]>>>0<c[1]>>>0?1:0)|0,u[3]=u[3]+1295307597+(u[2]>>>0<c[2]>>>0?1:0)|0,u[4]=u[4]+3545052371+(u[3]>>>0<c[3]>>>0?1:0)|0,u[5]=u[5]+886263092+(u[4]>>>0<c[4]>>>0?1:0)|0,u[6]=u[6]+1295307597+(u[5]>>>0<c[5]>>>0?1:0)|0,u[7]=u[7]+3545052371+(u[6]>>>0<c[6]>>>0?1:0)|0,this._b=u[7]>>>0<c[7]>>>0?1:0,p=0;p<8;p++){var f=h[p]+u[p],m=65535&f,g=f>>>16,S=((m*m>>>17)+m*g>>>15)+g*g,v=((4294901760&f)*f|0)+((65535&f)*f|0);o[p]=S^v}h[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,h[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,h[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,h[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,h[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,h[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,h[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,h[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}t.RabbitLegacy=i._createHelper(l)}(),e.RabbitLegacy}(Ce(),_r(),wr(),pr(),ot())}(Uh)),Bh())})(er);const ui=Cr(er.exports);function Fh(s){return r=this,e=null,t=function*(){const i=new Date;if(s.refreshSTSTokenInterval||(s.refreshSTSTokenInterval=3e5),!s.stsTokenFreshTime||+i-s.stsTokenFreshTime>=s.refreshSTSTokenInterval){s.stsTokenFreshTime=i;try{yield s.refreshSTSToken()}catch(n){typeof console.error=="function"&&console.error(`Some error occured during excuting refreshSTSToken, see:
2
+ `+n)}}return null},new Promise((i,n)=>{var a=l=>{try{o(t.next(l))}catch(d){n(d)}},c=l=>{try{o(t.throw(l))}catch(d){n(d)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(a,c);o((t=t.apply(r,e)).next())});var r,e,t}function Ps(s){return{transString:function(r){let e={},t=0,i=!1;for(let n in r)n!=="time"&&n!=="__time__"||typeof r[n]!="number"?typeof r[n]=="object"?e[n]=JSON.stringify(r[n]):e[n]=String(r[n]):(t=r[n],i=!0);return e.__time__=i?t:Math.floor(new Date().getTime()/1e3),e},process:function(r,e,t){return i=this,n=null,a=function*(){yield Fh(s);let c=r.slice(r.indexOf("/logstores")),o=e.length,l=(d=e,ui.MD5(d).toString().toUpperCase());var d;let h="",u=new Date().getTime()/1e3;s.latestTime=u;let p=s.latestInvalidTime?u-s.latestInvalidTime:0;if(t&&(s.latestInvalidTime=s.latestTime,s.latestValidTime=t),t)h=new Date(1e3*t).toUTCString();else if(s.latestValidTime){const S=s.latestValidTime+p;h=new Date(1e3*S).toUTCString()}else h=new Date(1e3*u).toUTCString();let f=new Map,m=new Map([["Content-Type","application/json"],["Content-MD5",l],["x-log-bodyrawsize",o.toString()]]);s.securityToken&&m.set("x-acs-security-token",s.securityToken),function(S,v,E,T,R,y,C,w){var A;let P="";y.set("x-log-apiversion","0.6.0"),y.set("x-log-signaturemethod","hmac-sha1"),P+=S+`
3
+ `+C+`
4
+ `+((A=y.get("Content-Type"))!=null?A:"")+`
3
5
  `+w+`
4
- `+((A=R.get("Content-Type"))!=null?A:"")+`
5
- `+y+`
6
- `;const E=(P,H)=>P[0].localeCompare(H[0]),T=P=>P[0].startsWith("x-log-")||P[0].startsWith("x-acs-");try{const P=[...R.entries()].filter(T).sort(E).map(H=>H[0]+":"+H[1]+`
7
- `).join("");_+=P}catch(P){}_+=m,v.size>0&&(_+="?");try{_+=[...v.entries()].sort(E).map(P=>P[0]+"="+P[1]).join("&")}catch(P){}const k="LOG "+b+":"+gi.HmacSHA1(_,S).toString(gi.enc.Base64);R.set("Authorization",k),R.set("x-log-date",y)}("POST",n,s.accessKeyId,s.accessKeySecret,h,p,o,d);let u=Object.fromEntries(p);return{data:e,header:u}},new Promise((n,c)=>{var o=h=>{try{d(r.next(h))}catch(p){c(p)}},l=h=>{try{d(r.throw(h))}catch(p){c(p)}},d=h=>h.done?n(h.value):Promise.resolve(h.value).then(o,l);d((r=r.apply(t,i)).next())});var t,i,r}}}typeof window!="undefined"&&Mi(window,"stsPlugin",Zi);for(var er,Je=[],tr=0;tr<256;++tr)Je.push((tr+256).toString(16).slice(1));var ho=new Uint8Array(16);function uo(){if(!er&&!(er=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return er(ho)}const ra={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function lt(s,a,e){if(ra.randomUUID&&!a&&!s)return ra.randomUUID();var t=(s=s||{}).random||(s.rng||uo)();if(t[6]=15&t[6]|64,t[8]=63&t[8]|128,a){e=e||0;for(var i=0;i<16;++i)a[e+i]=t[i];return a}return function(r,n=0){return(Je[r[n+0]]+Je[r[n+1]]+Je[r[n+2]]+Je[r[n+3]]+"-"+Je[r[n+4]]+Je[r[n+5]]+"-"+Je[r[n+6]]+Je[r[n+7]]+"-"+Je[r[n+8]]+Je[r[n+9]]+"-"+Je[r[n+10]]+Je[r[n+11]]+Je[r[n+12]]+Je[r[n+13]]+Je[r[n+14]]+Je[r[n+15]]).toLowerCase()}(t)}var po=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g,go=/\b(?:[A-Z]{1,3}[A-Z][TC])(?:[-+]\d{4})?|((?:Australian )?(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time)\b/g,mo=/[^-+\dA-Z]/g;function ir(s,a,e,t){if(arguments.length!==1||typeof s!="string"||/\d/.test(s)||(a=s,s=void 0),(s=s||s===0?s:new Date)instanceof Date||(s=new Date(s)),isNaN(s))throw TypeError("Invalid date");var i=(a=String(sa[a]||a||sa.default)).slice(0,4);i!=="UTC:"&&i!=="GMT:"||(a=a.slice(4),e=!0,i==="GMT:"&&(t=!0));var r=function(){return e?"getUTC":"get"},n=function(){return s[r()+"Date"]()},c=function(){return s[r()+"Day"]()},o=function(){return s[r()+"Month"]()},l=function(){return s[r()+"FullYear"]()},d=function(){return s[r()+"Hours"]()},h=function(){return s[r()+"Minutes"]()},p=function(){return s[r()+"Seconds"]()},u=function(){return s[r()+"Milliseconds"]()},f=function(){return e?0:s.getTimezoneOffset()},m=function(){return fo(s)},b={d:function(){return n()},dd:function(){return nt(n())},ddd:function(){return tt.dayNames[c()]},DDD:function(){return aa({y:l(),m:o(),d:n(),_:r(),dayName:tt.dayNames[c()],short:!0})},dddd:function(){return tt.dayNames[c()+7]},DDDD:function(){return aa({y:l(),m:o(),d:n(),_:r(),dayName:tt.dayNames[c()+7]})},m:function(){return o()+1},mm:function(){return nt(o()+1)},mmm:function(){return tt.monthNames[o()]},mmmm:function(){return tt.monthNames[o()+12]},yy:function(){return String(l()).slice(2)},yyyy:function(){return nt(l(),4)},h:function(){return d()%12||12},hh:function(){return nt(d()%12||12)},H:function(){return d()},HH:function(){return nt(d())},M:function(){return h()},MM:function(){return nt(h())},s:function(){return p()},ss:function(){return nt(p())},l:function(){return nt(u(),3)},L:function(){return nt(Math.floor(u()/10))},t:function(){return d()<12?tt.timeNames[0]:tt.timeNames[1]},tt:function(){return d()<12?tt.timeNames[2]:tt.timeNames[3]},T:function(){return d()<12?tt.timeNames[4]:tt.timeNames[5]},TT:function(){return d()<12?tt.timeNames[6]:tt.timeNames[7]},Z:function(){return t?"GMT":e?"UTC":bo(s)},o:function(){return(f()>0?"-":"+")+nt(100*Math.floor(Math.abs(f())/60)+Math.abs(f())%60,4)},p:function(){return(f()>0?"-":"+")+nt(Math.floor(Math.abs(f())/60),2)+":"+nt(Math.floor(Math.abs(f())%60),2)},S:function(){return["th","st","nd","rd"][n()%10>3?0:(n()%100-n()%10!=10)*n()%10]},W:function(){return m()},WW:function(){return nt(m())},N:function(){return So(s)}};return a.replace(po,function(S){return S in b?b[S]():S.slice(1,S.length-1)})}var sa={default:"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",paddedShortDate:"mm/dd/yyyy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:sso",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",expiresHeaderFormat:"ddd, dd mmm yyyy HH:MM:ss Z"},tt={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],timeNames:["a","p","am","pm","A","P","AM","PM"]},nt=function(s){var a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return String(s).padStart(a,"0")},aa=function(s){var a=s.y,e=s.m,t=s.d,i=s._,r=s.dayName,n=s.short,c=n!==void 0&&n,o=new Date,l=new Date;l.setDate(l[i+"Date"]()-1);var d=new Date;return d.setDate(d[i+"Date"]()+1),o[i+"FullYear"]()===a&&o[i+"Month"]()===e&&o[i+"Date"]()===t?c?"Tdy":"Today":l[i+"FullYear"]()===a&&l[i+"Month"]()===e&&l[i+"Date"]()===t?c?"Ysd":"Yesterday":d[i+"FullYear"]()===a&&d[i+"Month"]()===e&&d[i+"Date"]()===t?c?"Tmw":"Tomorrow":r},fo=function(s){var a=new Date(s.getFullYear(),s.getMonth(),s.getDate());a.setDate(a.getDate()-(a.getDay()+6)%7+3);var e=new Date(a.getFullYear(),0,4);e.setDate(e.getDate()-(e.getDay()+6)%7+3);var t=a.getTimezoneOffset()-e.getTimezoneOffset();a.setHours(a.getHours()-t);var i=(a-e)/6048e5;return 1+Math.floor(i)},So=function(s){var a=s.getDay();return a===0&&(a=7),a},bo=function(s){return(String(s).match(go)||[""]).pop().replace(mo,"").replace(/GMT\+0000/g,"UTC")},ri=(s=>(s.prod="rs.rtn.aliyuncs.com",s.pre="prs.rtn.aliyuncs.com",s))(ri||{});const Ni="7.2.1";class Ne{static getVersionNumber(){let a=Ni.split("."),e="";return a.forEach(t=>{t.length===1?e+="0"+t:e+=t}),parseInt(e)}static queryingParam(a){let e=[];if(a)for(let t in a)e.push(t+"="+a[t]);return e.join("&")}static getQueryParams(a){const e=window.location.search.substring(1).split("&");for(let t=0;t<e.length;t++){const i=e[t].split("=");if(decodeURIComponent(i[0])===a)return decodeURIComponent(i[1])}}static createCallid(a=""){const e=lt();return a&&e&&e.length>a.length?`${a}${e.substring(a.length)}`:e}static checkSubOptionsValid(a){if(a){const{audio:e,video:t,screen:i}=a;if(e===!1&&t===!1&&i===!1)return!1}return!0}static isNetworkAvailable(){return I(this,null,function*(){const a=ri.prod,{onLine:e}=navigator;if(!e)return!1;try{return yield fetch(`https://${a}/roomserver/v1/ws/version`),!0}catch(t){return!1}})}static toString(a){let e;if(a instanceof Error)e=a.message;else if(typeof a=="string")e=a;else try{e=JSON.stringify(a)}catch(t){e="undefined"}return e}static paramArrayToString(a){let e="";for(let t=0;t<a.length;t++)e!==""&&(e+=" "),e+=Ne.toString(a[t]);return e}static removeQueryString(a){if(!a)return a;let e=a.indexOf("?");return e>0?a.substring(0,e):a}}const{BrowserUtil:vo}=X.AliRTS,yo="EdgeHTML",na="Blink",Ro="Trident",Ao="Gecko",_o="WebKit",xi=(s,a)=>{const e=a.match(s);return e&&e.length>0&&e[1]||""},wo=[{test:[/\sedg\//i,[/edg([ea]|ios)/i]],describe(s){if(/\sedg\//i.test(s))return{name:na};const a=xi(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:yo,version:a}}},{test:[/trident/i],describe(s){const a={name:Ro},e=xi(/trident\/(\d+(\.?_?\d+)+)/i,s);return e&&(a.version=e),a}},{test(s){const a=/gecko/i.test(s),e=/like gecko/i.test(s);return a&&!e},describe(s){const a={name:Ao},e=xi(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(a.version=e),a}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:na})},{test:[/(apple)?webkit/i],describe(s){const a={name:_o},e=xi(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(a.version=e),a}}],rr=(s,a)=>s.find(e=>typeof e.test=="function"?e.test(a):Array.isArray(e.test)?e.test.some(t=>typeof t=="string"?a.indexOf(t)>-1:t instanceof RegExp&&t.test(a)):void 0),Eo=()=>{try{const s=navigator.userAgent||"",a=rr(wo,s);if(a){const e=a.describe(s);return`${e.name}/${e.version||vo.browserVersion}`}}catch(s){}return navigator.userAgent},Io=[{test:["wow64","win64","x64"],describe:()=>"amd64"},{test:["i686","x86"],describe:()=>"x86"},{test:["aarch64","arm64"],describe:()=>"arm64"},{test:["arm"],describe:()=>"arm"}],oa=()=>{let s="unknown";try{const a=navigator.userAgent||"",e=rr(Io,a);if(!e)return s;s=e.describe(a)}catch(a){}return s},To=[{test:[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],describe:()=>"Samsung"},{test:[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i,/\((ipad);[-\w\),; ]+apple/i,/(macintosh);/i],describe:()=>"Apple"},{test:[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],describe:()=>"Huawei"},{test:[/(?:honor)([-\w ]+)[;\)]/i],describe:()=>"Honor"},{test:[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],describe:()=>"Xiaomi"},{test:[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],describe:()=>"Oppo"},{test:[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],describe:()=>"Vivo"},{test:[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],describe:()=>"Realme"},{test:[/(pixel c)\b/i,/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],describe:()=>"Google"},{test:[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],describe:()=>"ZTE"},{test:[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],describe:()=>"Meizu"}],Co=()=>{let s="Unknown";try{const a=navigator.userAgent||"",e=rr(To,a);if(!e)return s;s=e.describe(a)}catch(a){}return s};class ca{constructor(a){var e,t;this.timer=null,this.time=10,this.count=10,this.arr=[],this.time=(e=a.time)!=null?e:10,this.count=(t=a.count)!=null?t:10,a.host.startsWith("http://")||a.host.startsWith("https://")?this.url=a.host+"/logstores/"+a.logstore+"/track":this.url="https://"+a.project+"."+a.host+"/logstores/"+a.logstore+"/track",this.opt=a,a.installUnloadHook&&typeof a.installUnloadHook=="function"&&a.installUnloadHook(()=>{this.sendImmediateInner()})}assemblePayload(a){const e={__logs__:a};return this.opt.tags&&(e.__tags__=this.opt.tags),this.opt.topic&&(e.__topic__=this.opt.topic),this.opt.source&&(e.__source__=this.opt.source),JSON.stringify(e)}platformSend(){if(this.opt.sendPayload&&typeof this.opt.sendPayload=="function"){const a=this.assemblePayload(this.arr);this.opt.sendPayload(this.url,a)}}transString(a){let e={};for(let t in a)typeof a[t]=="object"?e[t]=JSON.stringify(a[t]):e[t]=String(a[t]);return e}sendImmediateInner(){this.arr&&this.arr.length>0&&(this.platformSend(),this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.arr=[])}sendInner(){if(this.timer)this.arr.length>=this.count&&(clearTimeout(this.timer),this.timer=null,this.sendImmediateInner());else{const a=this;this.arr.length>=this.count||this.time<=0?this.sendImmediateInner():this.timer=setTimeout(function(){a.sendImmediateInner()},1e3*this.time)}}send(a){const e=this.transString(a);this.arr.push(e),this.sendInner()}sendImmediate(a){const e=this.transString(a);this.arr.push(e),this.sendImmediateInner()}sendBatchLogs(a){const e=a.map(t=>this.transString(t));this.arr.push(...e),this.sendInner()}sendBatchLogsImmediate(a){const e=a.map(t=>this.transString(t));this.arr.push(...e),this.sendImmediateInner()}overwriteTransString(a){this.transString=a.transString}getOpt(){return this.opt}}function la(s,a){return new Promise((e,t)=>{const i=new window.XMLHttpRequest;i.onload=()=>{i.status>=200&&i.status<300?e():t(new Error(`HTTP ${i.status}: ${i.statusText}`))},i.onerror=()=>{t(new Error("Network error occurred"))},i.ontimeout=()=>{t(new Error("Request timeout"))},i.timeout=1e4,i.open("POST",`${s}?APIVersion=0.6.0`,!0),i.send(a)})}function ko(s,a,e=!1){return I(this,null,function*(){try{if(e||a.length>=32768)return void(yield la(s,a));(function(t,i){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${t}?APIVersion=0.6.0`,i)})(s,a)||(yield la(s,a))}catch(t){const i=t instanceof Error?t:new Error(String(t));throw window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
8
- `+i.message),console.error("Failed log data:",s)),i}})}let Po=class extends ca{constructor(a){const f=a,{maxRetries:e=10,retryDelay:t=2e3,backoffMultiplier:i=2,maxRetryDelay:r=3e5,enableLocalStorage:n=!0,maxStorageSize:c=1e3,storageKey:o="artc_reliable_logs",enableNetworkMonitor:l=!0,onNetworkChange:d=()=>{},forceXhrMode:h=!0,debug:p=!1}=f,u=Mt(f,["maxRetries","retryDelay","backoffMultiplier","maxRetryDelay","enableLocalStorage","maxStorageSize","storageKey","enableNetworkMonitor","onNetworkChange","forceXhrMode","debug"]);super(Object.assign({},u,{installUnloadHook:m=>{window.addEventListener("beforeunload",()=>{this.saveFailedLogs(),m()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.saveFailedLogs()})},sendPayload:(m,b)=>I(this,null,function*(){return Promise.resolve()})}));g(this,"reliableConfig");g(this,"failedLogs",new Map);g(this,"networkStatus","online");g(this,"retryTimer",null);g(this,"originalSendPayload",null);this.reliableConfig={maxRetries:e,retryDelay:t,backoffMultiplier:i,maxRetryDelay:r,enableLocalStorage:n,maxStorageSize:c,storageKey:o,enableNetworkMonitor:l,onNetworkChange:d,forceXhrMode:h,debug:p},this.originalSendPayload=(m,b)=>I(this,null,function*(){return ko(m,b,h)}),this.getOpt().sendPayload=(m,b)=>I(this,null,function*(){return this.reliableSendAsync(m,b)}),this.initNetworkMonitor(),this.loadFailedLogs(),this.startRetryTimer()}reliableSendAsync(a,e){return I(this,null,function*(){const t=this.generateId();try{yield Promise.resolve(this.originalSendPayload(a,e)),this.debug(`Log ${t} sent successfully`)}catch(i){this.debug(`Log ${t} failed, adding to retry queue:`,i),this.addToFailedQueue(t,a,e,i)}})}addToFailedQueue(a,e,t,i){const r={id:a,data:{error:i.message},timestamp:Date.now(),retryCount:0,lastRetryTime:0,url:e,payload:t};this.failedLogs.set(a,r),this.scheduleRetry(r)}scheduleRetry(a){if(a.retryCount>=this.reliableConfig.maxRetries)return this.debug(`Log ${a.id} exceeded max retries, removing from queue`),void this.failedLogs.delete(a.id);const e=Math.min(this.reliableConfig.retryDelay*Math.pow(this.reliableConfig.backoffMultiplier,a.retryCount),this.reliableConfig.maxRetryDelay);this.debug(`Scheduling retry for log ${a.id} in ${e}ms (attempt ${a.retryCount+1}/${this.reliableConfig.maxRetries})`),setTimeout(()=>{this.retryLog(a)},e)}retryLog(a){return I(this,null,function*(){if(this.failedLogs.has(a.id)){a.retryCount++,a.lastRetryTime=Date.now();try{if(this.networkStatus==="offline")return this.debug(`Log ${a.id} retry skipped - network offline`),void this.scheduleRetry(a);yield this.originalSendPayload(a.url,a.payload),this.debug(`Log ${a.id} retry successful`),this.failedLogs.delete(a.id)}catch(e){this.debug(`Log ${a.id} retry failed:`,e),this.scheduleRetry(a)}}})}initNetworkMonitor(){this.reliableConfig.enableNetworkMonitor&&typeof window!="undefined"&&(this.networkStatus=navigator.onLine?"online":"offline",window.addEventListener("online",()=>{this.handleNetworkChange("online")}),window.addEventListener("offline",()=>{this.handleNetworkChange("offline")}),this.debug(`Network monitor initialized. Current status: ${this.networkStatus}`))}handleNetworkChange(a){const e=this.networkStatus;this.networkStatus=a,this.debug(`Network status changed: ${e} -> ${a}`),this.reliableConfig.onNetworkChange(a==="online"),a==="online"&&e==="offline"&&(this.debug("Network recovered, retrying failed logs"),this.retryAllFailedLogs())}retryAllFailedLogs(){this.failedLogs.size!==0&&(this.debug(`Retrying ${this.failedLogs.size} failed logs after network recovery`),Array.from(this.failedLogs.values()).forEach(a=>{setTimeout(()=>this.retryLog(a),100*Math.random())}))}startRetryTimer(){typeof window!="undefined"&&(this.retryTimer=window.setInterval(()=>{if(this.failedLogs.size>0&&this.networkStatus==="online"){const a=Date.now();Array.from(this.failedLogs.values()).forEach(e=>{a-e.lastRetryTime>this.reliableConfig.retryDelay&&this.retryLog(e)})}},this.reliableConfig.retryDelay),this.debug(`Retry timer started with interval ${this.reliableConfig.retryDelay}ms`))}loadFailedLogs(){if(this.reliableConfig.enableLocalStorage&&typeof localStorage!="undefined")try{const a=localStorage.getItem(this.reliableConfig.storageKey);if(a){const e=JSON.parse(a);e.forEach(t=>{this.failedLogs.set(t.id,t)}),this.debug(`Loaded ${e.length} failed logs from storage`),localStorage.removeItem(this.reliableConfig.storageKey),this.networkStatus==="online"&&this.retryAllFailedLogs()}}catch(a){this.debug("Failed to load failed logs from storage:",a)}}saveFailedLogs(){if(this.reliableConfig.enableLocalStorage&&typeof localStorage!="undefined"&&this.failedLogs.size!==0)try{const a=Array.from(this.failedLogs.values()).slice(-this.reliableConfig.maxStorageSize);localStorage.setItem(this.reliableConfig.storageKey,JSON.stringify(a)),this.debug(`Saved ${a.length} failed logs to storage`)}catch(a){this.debug("Failed to save failed logs to storage:",a)}}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}debug(...a){this.reliableConfig.debug&&typeof console!="undefined"&&console.log("[ReliableWebTracker]",...a)}useStsPlugin(a){this.originalSendPayload=(e,t)=>I(this,null,function*(){return function(i,r,n){return I(this,null,function*(){try{i=i.slice(0,-6);const{data:c,header:o}=yield n.process(i,r);return new Promise((l,d)=>{const h=new window.XMLHttpRequest;h.onload=()=>{h.status>=200&&h.status<300?l():d(new Error(`HTTP ${h.status}: ${h.statusText}`))},h.onerror=()=>{d(new Error("Network error occurred"))},h.ontimeout=()=>{d(new Error("Request timeout"))},h.timeout=1e4,h.open("POST",i,!0);for(let p in o)h.setRequestHeader(p,o[p]);h.send(c)})}catch(c){const o=c instanceof Error?c:new Error(String(c));throw window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
9
- `+o.message),console.error("Failed log data:",i)),o}})}(e,t,a)}),this.getOpt().sendPayload=(e,t)=>I(this,null,function*(){return this.reliableSendAsync(e,t)}),this.overwriteTransString(a)}getStatus(){return{networkStatus:this.networkStatus,failedLogsCount:this.failedLogs.size,isRetryActive:this.retryTimer!==null,config:this.reliableConfig}}retryAll(){this.debug("Manual retry triggered"),this.retryAllFailedLogs()}clearFailedLogs(){const a=this.failedLogs.size;this.failedLogs.clear(),this.debug(`Cleared ${a} failed logs`)}getFailedLogs(){return Array.from(this.failedLogs.values())}destroy(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),this.saveFailedLogs(),this.failedLogs.clear(),this.debug("WebTrackerBrowser destroyed")}};const{BrowserUtil:da,SystenUtil:ha}=X.AliRTS,Do=oa(),Oi=6e5,Vi={host:"cn-hangzhou.log.aliyuncs.com",project:"alivc-aio",logstore:"logger",time:10,count:10};function sr(){return ir(new Date,"HH:MM:ss.l")}function ua(){return ir(new Date,"isoDate")}var ar=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.API=2]="API",s[s.WARNING=3]="WARNING",s[s.ERROR=4]="ERROR",s[s.NONE=5]="NONE",s))(ar||{});class Mo{constructor(){g(this,"tracker");g(this,"stsPlugin");g(this,"stsData");g(this,"stsExpiration",Date.now());g(this,"clientId",lt());g(this,"bSesid",lt());g(this,"logLevel",3);g(this,"appId","");g(this,"sessionId","");g(this,"logCache",[]);g(this,"updateTaskTimer");g(this,"endReported",!0);g(this,"logSequence",0);g(this,"sendLogBeforeUnload",a=>I(this,null,function*(){if(!this.stsPlugin)return;this.logSequence+=1,a.unshift(this.getLogParams(710203,{log:`[${ua()} ${sr()}] [INF] beforeunload`,stat_log_seq:this.logSequence}));const e=`https://${Vi.project}.${Vi.host}/logstores/${Vi.logstore}`,t={__logs__:a.map(n=>this.stsPlugin.transString(n))},{data:i,header:r}=yield this.stsPlugin.process(e,JSON.stringify(t));fetch(e,{keepalive:!0,method:"POST",headers:r,body:i})}));g(this,"logMethod",(a,e=console.log)=>(...t)=>{let i=sr();this.logLevel<=a&&e(i,...t);let r=Ne.paramArrayToString(t);a>0&&this.addLog(r)});g(this,"d",this.logMethod(0,console.debug));g(this,"i",this.logMethod(1));g(this,"w",this.logMethod(3,console.warn));g(this,"e",this.logMethod(4,(...a)=>{const[e,...t]=a;console.error(e,"<error>",t)}));g(this,"ev",this.logMethod(2));g(this,"a",this.logMethod(2,(...a)=>{const[e,...t]=a;if(t.length>2){const i=`${t[1]}`;i.startsWith("__g__")&&console.group(`${i.substring(5)}_${t[2]}`)}console.log(e,...t)}));g(this,"ar",this.logMethod(2,(...a)=>{const[e,...t]=a;console.log(e,...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));g(this,"ae",this.logMethod(2,(...a)=>{const[e,...t]=a;console.error(e,"<error>",...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));window.addEventListener("beforeunload",()=>{this.reportEnd(!0)})}init(){this.reset(),this.startSTSUpdateTask()}destroy(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer)}reset(){this.bSesid=lt(),this.endReported=!0,this.logSequence=0,this.appId="",this.sessionId=""}startSTSUpdateTask(){return I(this,null,function*(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer);try{const a=yield this.refreshSTSToken();this.createTracker(a)}catch(a){}this.updateTaskTimer=setTimeout(()=>{this.startSTSUpdateTask()},Oi)})}refreshSTSToken(){return I(this,null,function*(){if(!this.stsData||this.stsExpiration<=Date.now()+Oi){const a=yield this.requestSTSToken(),e=new Date(a==null?void 0:a.Expiration).getTime()||0,t=Date.now()+Oi;this.stsExpiration=Math.max(e,t),this.stsData=a}return this.stsData})}requestSTSToken(){const a=Date.now(),e=`${this.clientId}|woMMssV6jmyol9fr|${a}`,t={Action:"AssumeSlsRoleV2",AuthInfo:gi.MD5(e).toString(gi.enc.Hex),ClientId:this.clientId,BusinessType:"logger",AppVersion:"1.0",Version:"2017-03-14",AuthTimestamp:`${a}`,TerminalType:"web",DeviceModel:"",Format:"JSON",SignatureMethod:"HMAC-SHA1",SignatureVersion:"1.0",Timestamp:ir(a,"isoUtcDateTime")},i=new URLSearchParams(t).toString();return fetch(`https://slsrole.alicdn.com/?${i}`).then(r=>r.json()).then(r=>JSON.parse(window.atob(r.SlsAuthResult)))}createTracker(a){if(!this.tracker){const e={accessKeyId:a.AccessKeyId,accessKeySecret:a.AccessKeySecret,securityToken:a.SecurityToken,refreshSTSTokenInterval:Oi,stsTokenFreshTime:void 0,refreshSTSToken:()=>{this.refreshSTSToken().then(r=>{e.accessKeyId=r.AccessKeyId,e.accessKeySecret=r.AccessKeySecret,e.securityToken=r.SecurityToken}).catch(()=>{})}},t=new Po(Vi),i=Zi(e);t.useStsPlugin(i),this.stsPlugin=i,this.tracker=t,this.reportStartAndCache()}}changeConfig(a){a.logLevel!==void 0&&a.logLevel>=0&&a.logLevel<=5&&(this.logLevel=a.logLevel)}setSessionID(a,e){a&&e&&(this.appId=a,this.sessionId=e,this.reportStartAndCache())}reportStartAndCache(){if(!this.tracker||!this.sessionId)return;this.endReported=!1;const a={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},e=[this.getLogParams(710201,a),this.getLogParams(710202,a)];this.tracker.sendBatchLogsImmediate(e),this.logCache.forEach(t=>{this.sendLog(t)})}reportEnd(a=!1){if(!this.tracker||!this.sessionId||this.endReported)return void this.reset();const e={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},t=[this.getLogParams(710204,e),this.getLogParams(710205,e)];a?this.sendLogBeforeUnload(t):(this.tracker.sendBatchLogsImmediate(t),this.endReported=!0),this.reset()}getLogParams(a,e){return G({appid:`${window.location.host}`,appid_list:this.appId,appver:"",b_sesid:this.bSesid,biz_type:"rtc",cpu_info:Do,db:da.browserName,dm:da.browserVersion,install_uuid:this.clientId,logger_v:"0.0.1",os:ha.systemName,osv:ha.systemVersion,p_sesid:this.bSesid,sdk_version:Ni,sdkname:"AliRTCSdk",stm:Date.now(),tar_pf:"web",traceid:this.sessionId,event_id:a},e||{})}sendLog(a){if(!this.tracker||!this.sessionId)return;this.logSequence+=1;const e=this.getLogParams(710203,{log:a,stat_log_seq:this.logSequence});this.tracker.send(e)}addLog(a){const e=sr(),t=`[${ua()} ${e}] ${a}`;this.sessionId&&this.tracker?this.sendLog(t):(this.logCache.push(t),this.logCache.length>=200&&this.logCache.shift())}}class N{static getLogger(){return this.logger||(this.logger=new Mo),this.logger}static init(){this.getLogger().init()}static destroy(){this.getLogger().destroy()}static setLogLevel(a){this.getLogger().changeConfig({logLevel:a})}static setSessionID(a,e){this.getLogger().setSessionID(a,e)}static reportEnd(){this.getLogger().reportEnd()}static interface(...a){this.getLogger().a("[API]",...a)}static interfaceResult(a,e,t,...i){t?this.getLogger().ar("[ARE]",a,e,...i):this.getLogger().ae("[ARE]",a,e,...i)}static event(...a){this.getLogger().ev("[EVT]",...a)}static debug(...a){this.getLogger().d("[DBG]",...a)}static info(...a){this.getLogger().i("[INF]",...a)}static warn(...a){this.getLogger().w("[WARN]",...a)}static error(...a){this.getLogger().e("[ERR]",...a)}}g(N,"logger");var nr={exports:{}};(function(s,a){(function(e,t){var i="function",r="undefined",n="object",c="string",o="major",l="model",d="name",h="type",p="vendor",u="version",f="architecture",m="console",b="mobile",S="tablet",v="smarttv",R="wearable",w="embedded",y="Amazon",A="Apple",_="ASUS",E="BlackBerry",T="Browser",k="Chrome",P="Firefox",H="Google",q="Huawei",Y="LG",J="Microsoft",z="Motorola",Z="Opera",ee="Samsung",ge="Sharp",D="Sony",x="Xiaomi",L="Zebra",O="Facebook",de="Chromium OS",Pe="Mac OS",K=" Browser",me=function(ne){for(var re={},ie=0;ie<ne.length;ie++)re[ne[ie].toUpperCase()]=ne[ie];return re},Me=function(ne,re){return typeof ne===c&&_e(re).indexOf(_e(ne))!==-1},_e=function(ne){return ne.toLowerCase()},ke=function(ne,re){if(typeof ne===c)return ne=ne.replace(/^\s\s*/,""),typeof re===r?ne:ne.substring(0,500)},fe=function(ne,re){for(var ie,Se,Ve,ue,We,Q,Le=0;Le<re.length&&!We;){var at=re[Le],xe=re[Le+1];for(ie=Se=0;ie<at.length&&!We&&at[ie];)if(We=at[ie++].exec(ne))for(Ve=0;Ve<xe.length;Ve++)Q=We[++Se],typeof(ue=xe[Ve])===n&&ue.length>0?ue.length===2?typeof ue[1]==i?this[ue[0]]=ue[1].call(this,Q):this[ue[0]]=ue[1]:ue.length===3?typeof ue[1]!==i||ue[1].exec&&ue[1].test?this[ue[0]]=Q?Q.replace(ue[1],ue[2]):t:this[ue[0]]=Q?ue[1].call(this,Q,ue[2]):t:ue.length===4&&(this[ue[0]]=Q?ue[3].call(this,Q.replace(ue[1],ue[2])):t):this[ue]=Q||t;Le+=2}},we=function(ne,re){for(var ie in re)if(typeof re[ie]===n&&re[ie].length>0){for(var Se=0;Se<re[ie].length;Se++)if(Me(re[ie][Se],ne))return ie==="?"?t:ie}else if(Me(re[ie],ne))return ie==="?"?t:ie;return re.hasOwnProperty("*")?re["*"]:ne},he={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},De={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[u,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[u,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,u],[/opios[\/ ]+([\w\.]+)/i],[u,[d,Z+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[u,[d,Z+" GX"]],[/\bopr\/([\w\.]+)/i],[u,[d,Z]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[u,[d,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[u,[d,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[d,u],[/quark(?:pc)?\/([-\w\.]+)/i],[u,[d,"Quark"]],[/\bddg\/([\w\.]+)/i],[u,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[u,[d,"UC"+T]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[u,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[u,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[u,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[u,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[u,[d,"Smart Lenovo "+T]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+T],u],[/\bfocus\/([\w\.]+)/i],[u,[d,P+" Focus"]],[/\bopt\/([\w\.]+)/i],[u,[d,Z+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[u,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[u,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[u,[d,Z+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[u,[d,"MIUI"+K]],[/fxios\/([\w\.-]+)/i],[u,[d,P]],[/\bqihoobrowser\/?([\w\.]*)/i],[u,[d,"360"]],[/\b(qq)\/([\w\.]+)/i],[[d,/(.+)/,"$1Browser"],u],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1"+K],u],[/samsungbrowser\/([\w\.]+)/i],[u,[d,ee+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[u,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],u],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[d,u],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[d],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[u,d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,O],u],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[d,u],[/\bgsa\/([\w\.]+) .*safari\//i],[u,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[u,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[u,[d,k+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,k+" WebView"],u],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[u,[d,"Android "+T]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,u],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[u,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[u,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[u,we,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[d,u],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],u],[/(wolvic|librewolf)\/([\w\.]+)/i],[d,u],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[u,[d,P+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[d,[u,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[d,[u,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[f,"amd64"]],[/(ia32(?=;))/i],[[f,_e]],[/((?:i[346]|x)86)[;\)]/i],[[f,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[f,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[f,"armhf"]],[/windows (ce|mobile); ppc;/i],[[f,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[f,/ower/,"",_e]],[/(sun4\w)[;\)]/i],[[f,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[f,_e]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[l,[p,ee],[h,S]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[l,[p,ee],[h,b]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[l,[p,A],[h,b]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[l,[p,A],[h,S]],[/(macintosh);/i],[l,[p,A]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[l,[p,ge],[h,b]],[/(?:honor)([-\w ]+)[;\)]/i],[l,[p,"Honor"],[h,b]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[l,[p,q],[h,S]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[l,[p,q],[h,b]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[l,/_/g," "],[p,x],[h,b]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[l,/_/g," "],[p,x],[h,S]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[l,[p,"OPPO"],[h,b]],[/\b(opd2\d{3}a?) bui/i],[l,[p,"OPPO"],[h,S]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[l,[p,"Vivo"],[h,b]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[l,[p,"Realme"],[h,b]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[l,[p,z],[h,b]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[l,[p,z],[h,S]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[l,[p,Y],[h,S]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[l,[p,Y],[h,b]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[l,[p,"Lenovo"],[h,S]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[l,/_/g," "],[p,"Nokia"],[h,b]],[/(pixel c)\b/i],[l,[p,H],[h,S]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[l,[p,H],[h,b]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[l,[p,D],[h,b]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[l,"Xperia Tablet"],[p,D],[h,S]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[l,[p,"OnePlus"],[h,b]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[l,[p,y],[h,S]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[l,/(.+)/g,"Fire Phone $1"],[p,y],[h,b]],[/(playbook);[-\w\),; ]+(rim)/i],[l,p,[h,S]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[l,[p,E],[h,b]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[l,[p,_],[h,S]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[l,[p,_],[h,b]],[/(nexus 9)/i],[l,[p,"HTC"],[h,S]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[l,/_/g," "],[h,b]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[l,[p,"TCL"],[h,S]],[/(itel) ((\w+))/i],[[p,_e],l,[h,we,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[l,[p,"Acer"],[h,S]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[l,[p,"Meizu"],[h,b]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[l,[p,"Ulefone"],[h,b]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[l,[p,"Energizer"],[h,b]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[l,[p,"Cat"],[h,b]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[l,[p,"Smartfren"],[h,b]],[/droid.+; (a(?:015|06[35]|142p?))/i],[l,[p,"Nothing"],[h,b]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[p,l,[h,b]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[p,l,[h,S]],[/(surface duo)/i],[l,[p,J],[h,S]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[l,[p,"Fairphone"],[h,b]],[/(u304aa)/i],[l,[p,"AT&T"],[h,b]],[/\bsie-(\w*)/i],[l,[p,"Siemens"],[h,b]],[/\b(rct\w+) b/i],[l,[p,"RCA"],[h,S]],[/\b(venue[\d ]{2,7}) b/i],[l,[p,"Dell"],[h,S]],[/\b(q(?:mv|ta)\w+) b/i],[l,[p,"Verizon"],[h,S]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[l,[p,"Barnes & Noble"],[h,S]],[/\b(tm\d{3}\w+) b/i],[l,[p,"NuVision"],[h,S]],[/\b(k88) b/i],[l,[p,"ZTE"],[h,S]],[/\b(nx\d{3}j) b/i],[l,[p,"ZTE"],[h,b]],[/\b(gen\d{3}) b.+49h/i],[l,[p,"Swiss"],[h,b]],[/\b(zur\d{3}) b/i],[l,[p,"Swiss"],[h,S]],[/\b((zeki)?tb.*\b) b/i],[l,[p,"Zeki"],[h,S]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],l,[h,S]],[/\b(ns-?\w{0,9}) b/i],[l,[p,"Insignia"],[h,S]],[/\b((nxa|next)-?\w{0,9}) b/i],[l,[p,"NextBook"],[h,S]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],l,[h,b]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],l,[h,b]],[/\b(ph-1) /i],[l,[p,"Essential"],[h,b]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[l,[p,"Envizen"],[h,S]],[/\b(trio[-\w\. ]+) b/i],[l,[p,"MachSpeed"],[h,S]],[/\btu_(1491) b/i],[l,[p,"Rotor"],[h,S]],[/(shield[\w ]+) b/i],[l,[p,"Nvidia"],[h,S]],[/(sprint) (\w+)/i],[p,l,[h,b]],[/(kin\.[onetw]{3})/i],[[l,/\./g," "],[p,J],[h,b]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[l,[p,L],[h,S]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[l,[p,L],[h,b]],[/smart-tv.+(samsung)/i],[p,[h,v]],[/hbbtv.+maple;(\d+)/i],[[l,/^/,"SmartTV"],[p,ee],[h,v]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,Y],[h,v]],[/(apple) ?tv/i],[p,[l,A+" TV"],[h,v]],[/crkey/i],[[l,k+"cast"],[p,H],[h,v]],[/droid.+aft(\w+)( bui|\))/i],[l,[p,y],[h,v]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[l,[p,ge],[h,v]],[/(bravia[\w ]+)( bui|\))/i],[l,[p,D],[h,v]],[/(mitv-\w{5}) bui/i],[l,[p,x],[h,v]],[/Hbbtv.*(technisat) (.*);/i],[p,l,[h,v]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,ke],[l,ke],[h,v]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[h,v]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,l,[h,m]],[/droid.+; (shield) bui/i],[l,[p,"Nvidia"],[h,m]],[/(playstation [345portablevi]+)/i],[l,[p,D],[h,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[l,[p,J],[h,m]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[l,[p,ee],[h,R]],[/((pebble))app/i],[p,l,[h,R]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[l,[p,A],[h,R]],[/droid.+; (glass) \d/i],[l,[p,H],[h,R]],[/droid.+; (wt63?0{2,3})\)/i],[l,[p,L],[h,R]],[/droid.+; (glass) \d/i],[l,[p,H],[h,R]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,l,[h,R]],[/; (quest( \d| pro)?)/i],[l,[p,O],[h,R]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[h,w]],[/(aeobc)\b/i],[l,[p,y],[h,w]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[l,[h,b]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[l,[h,S]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[h,S]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[h,b]],[/(android[-\w\. ]{0,9});.+buil/i],[l,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[u,[d,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[d,u],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[u,[d,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[d,u],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[u,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,u],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[d,[u,we,he]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[u,we,he],[d,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[u,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,Pe],[u,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[u,d],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[d,u],[/\(bb(10);/i],[u,[d,E]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[u,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[u,[d,P+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[u,[d,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[u,[d,"watchOS"]],[/crkey\/([\d\.]+)/i],[u,[d,k+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,de],u],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[d,u],[/(sunos) ?([\w\.\d]*)/i],[[d,"Solaris"],u],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[d,u]]},ye=function(ne,re){if(typeof ne===n&&(re=ne,ne=t),!(this instanceof ye))return new ye(ne,re).getResult();var ie=typeof e!==r&&e.navigator?e.navigator:t,Se=ne||(ie&&ie.userAgent?ie.userAgent:""),Ve=ie&&ie.userAgentData?ie.userAgentData:t,ue=re?function(Q,Le){var at={};for(var xe in Q)Le[xe]&&Le[xe].length%2==0?at[xe]=Le[xe].concat(Q[xe]):at[xe]=Q[xe];return at}(De,re):De,We=ie&&ie.userAgent==Se;return this.getBrowser=function(){var Q,Le={};return Le[d]=t,Le[u]=t,fe.call(Le,Se,ue.browser),Le[o]=typeof(Q=Le[u])===c?Q.replace(/[^\d\.]/g,"").split(".")[0]:t,We&&ie&&ie.brave&&typeof ie.brave.isBrave==i&&(Le[d]="Brave"),Le},this.getCPU=function(){var Q={};return Q[f]=t,fe.call(Q,Se,ue.cpu),Q},this.getDevice=function(){var Q={};return Q[p]=t,Q[l]=t,Q[h]=t,fe.call(Q,Se,ue.device),We&&!Q[h]&&Ve&&Ve.mobile&&(Q[h]=b),We&&Q[l]=="Macintosh"&&ie&&typeof ie.standalone!==r&&ie.maxTouchPoints&&ie.maxTouchPoints>2&&(Q[l]="iPad",Q[h]=S),Q},this.getEngine=function(){var Q={};return Q[d]=t,Q[u]=t,fe.call(Q,Se,ue.engine),Q},this.getOS=function(){var Q={};return Q[d]=t,Q[u]=t,fe.call(Q,Se,ue.os),We&&!Q[d]&&Ve&&Ve.platform&&Ve.platform!="Unknown"&&(Q[d]=Ve.platform.replace(/chrome os/i,de).replace(/macos/i,Pe)),Q},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return Se},this.setUA=function(Q){return Se=typeof Q===c&&Q.length>500?ke(Q,500):Q,this},this.setUA(Se),this};ye.VERSION="1.0.40",ye.BROWSER=me([d,u,o]),ye.CPU=me([f]),ye.DEVICE=me([l,p,h,m,b,v,S,R,w]),ye.ENGINE=ye.OS=me([d,u]),s.exports&&(a=s.exports=ye),a.UAParser=ye;var qe=typeof e!==r&&(e.jQuery||e.Zepto);if(qe&&!qe.ua){var st=new ye;qe.ua=st.getResult(),qe.ua.get=function(){return st.getUA()},qe.ua.set=function(ne){st.setUA(ne);var re=st.getResult();for(var ie in re)qe.ua[ie]=re[ie]}}})(typeof window=="object"?window:ti)})(nr,nr.exports);var Lo=nr.exports,Ue=(s=>(s.KEEPALIVE="keepalive",s.JOINCHANNEL="joinchannel",s.NOTIFYJOIN="notifyjoin",s.NOTIFYSTATUS="notifystatus",s.STATUSREPORT="statusreport",s.LEAVECHANNEL="leavechannel",s.NOTIFYLEAVE="notifyleave",s.NOTIFYPUBLISH="notifypublish",s.BYE="bye",s.RECONNECT="reconnect",s.PUBLISH="publish",s.REFRESHURL="refreshurl",s.UNSUBSCRIBE="unsubscribe",s.ROLEUPDATE="roleupdate",s))(Ue||{});class Ui{constructor(a,e){g(this,"authInfo");g(this,"userName");g(this,"seqIndex",0);this.authInfo=a,this.userName=typeof e=="number"?e.toString():e}get roleAuth(){if(this.authInfo.role){const{timestamp:a,nonce:e,token:t,role:i}=this.authInfo;return{timestamp:a,nonce:e,token:t,tokenrole:i}}}static get adaptInfo(){var e,t,i,r;let a=new Lo.UAParser().getResult();return{os_name:((e=a.os.name)==null?void 0:e.replace(" ",""))+"_"+((t=a.browser.name)==null?void 0:t.replace(" ","")),device_name:((i=a.device.model)==null?void 0:i.replace(" ",""))||"",brand_name:((r=a.device.vendor)==null?void 0:r.replace(" ",""))||"",device_key:window.navigator.userAgent,os_version:a.browser.version||"",sdk_version:"7.2.1",version:"v1"}}refreshAuthInfo(a){this.authInfo=a}getSeqIndex(){return this.seqIndex}createKeepAlivePackage(){return this.createBaseSendPackage("keepalive")}createJoinPackage(a){let e=this.createBaseSendPackage("joinchannel");return e.header.displayName=this.userName,e.header.clientversion=Ne.getVersionNumber().toString(),e.header.platform="web",this.roleAuth&&(e.data.auth=this.roleAuth),e.data.adapt=Ui.adaptInfo,a&&(e.data=G(G({},e.data),a)),e}createLeavePackage(){return this.createBaseSendPackage("leavechannel")}createStatusPackage(a){let e=this.createBaseSendPackage("statusreport");return e.header.displayName=this.userName,e.data.status=a,e}createPublishPackage(){let a=this.createBaseSendPackage("publish");return a.data.users=[{}],this.roleAuth&&(a.data.auth=this.roleAuth),a}createRoleUpdatePackage(){let a=this.createBaseSendPackage("roleupdate");return a.header.displayName=this.userName,a}createReconnectPackage(a){let e=this.createBaseSendPackage("reconnect");return e.header.displayName=this.userName,e.header.clientversion=Ne.getVersionNumber().toString(),e.header.platform="web",e.data=G(G({},e.data),a!=null?a:{}),this.roleAuth&&(e.data.auth=this.roleAuth),e}createRefreshUrlPackage(){let a=this.createBaseSendPackage("refreshurl");return a.header.displayName=this.userName,a}createResponsePackage(a,e){return{version:1,code:200,tid:a,msgtype:e}}createBaseSendPackage(a){var e;return++this.seqIndex,{version:1,msgtype:a,tid:lt(),header:{appid:this.authInfo.appId,channelid:this.authInfo.channelId,sessionid:(e=this.authInfo.sessionId)!=null?e:"",userid:this.authInfo.userId},data:{seq:this.seqIndex}}}}var mt=(s=>(s.pre="pre",s.prod="prod",s))(mt||{}),kt=(s=>(s.AliRtcSdkCommunication="communication",s.AliRtcSdkInteractiveLive="interactive_live",s.AliRtcSdkInteractiveWithLowLatencyLive="cdn_live",s))(kt||{}),Nt=(s=>(s.AliRtcSdkInteractive="interactive",s.AliRtcSdkLive="live",s))(Nt||{}),Rt=(s=>(s[s.AliEngineLocalDeviceTypeUnknown=0]="AliEngineLocalDeviceTypeUnknown",s[s.AliEngineLocalDeviceTypeMic=1]="AliEngineLocalDeviceTypeMic",s[s.AliEngineLocalDeviceTypeSpeaker=2]="AliEngineLocalDeviceTypeSpeaker",s[s.AliEngineLocalDeviceTypeAudioDevice=3]="AliEngineLocalDeviceTypeAudioDevice",s[s.AliEngineLocalDeviceTypeCamera=4]="AliEngineLocalDeviceTypeCamera",s[s.AliEngineLocalDeviceTypeDisplay=5]="AliEngineLocalDeviceTypeDisplay",s[s.AliEngineLocalDeviceTypeVideoDevice=6]="AliEngineLocalDeviceTypeVideoDevice",s))(Rt||{}),Be=(s=>(s[s.AliEngineLocalDeviceExceptionTypeUnknown=0]="AliEngineLocalDeviceExceptionTypeUnknown",s[s.AliEngineLocalDeviceExceptionTypeMicOpenFail=1]="AliEngineLocalDeviceExceptionTypeMicOpenFail",s[s.AliEngineLocalDeviceExceptionTypeMicInterrupt=2]="AliEngineLocalDeviceExceptionTypeMicInterrupt",s[s.AliEngineLocalDeviceExceptionTypeMicAuthFail=3]="AliEngineLocalDeviceExceptionTypeMicAuthFail",s[s.AliEngineLocalDeviceExceptionTypeMicNotAvailable=4]="AliEngineLocalDeviceExceptionTypeMicNotAvailable",s[s.AliEngineLocalDeviceExceptionTypeSpeakerOpenFail=5]="AliEngineLocalDeviceExceptionTypeSpeakerOpenFail",s[s.AliEngineLocalDeviceExceptionTypeSpeakerInterrupt=6]="AliEngineLocalDeviceExceptionTypeSpeakerInterrupt",s[s.AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable=7]="AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable",s[s.AliEngineLocalDeviceExceptionTypeAudioDeviceException=8]="AliEngineLocalDeviceExceptionTypeAudioDeviceException",s[s.AliEngineLocalDeviceExceptionTypeCameraOpenFail=9]="AliEngineLocalDeviceExceptionTypeCameraOpenFail",s[s.AliEngineLocalDeviceExceptionTypeCameraInterrupt=10]="AliEngineLocalDeviceExceptionTypeCameraInterrupt",s[s.AliEngineLocalDeviceExceptionTypeCameraAuthFail=11]="AliEngineLocalDeviceExceptionTypeCameraAuthFail",s[s.AliEngineLocalDeviceExceptionTypeDisplayException=12]="AliEngineLocalDeviceExceptionTypeDisplayException",s[s.AliEngineLocalDeviceExceptionTypeVideoDeviceException=13]="AliEngineLocalDeviceExceptionTypeVideoDeviceException",s))(Be||{}),oe=(s=>(s[s.AliRtcConnectionStatusInit=0]="AliRtcConnectionStatusInit",s[s.AliRtcConnectionStatusDisconnected=1]="AliRtcConnectionStatusDisconnected",s[s.AliRtcConnectionStatusConnecting=2]="AliRtcConnectionStatusConnecting",s[s.AliRtcConnectionStatusConnected=3]="AliRtcConnectionStatusConnected",s[s.AliRtcConnectionStatusReconnecting=4]="AliRtcConnectionStatusReconnecting",s[s.AliRtcConnectionStatusFailed=5]="AliRtcConnectionStatusFailed",s))(oe||{}),At=(s=>(s[s.AliRtcConnectionChangedDummyReason=0]="AliRtcConnectionChangedDummyReason",s[s.AliRtcConnectionMediaPathChanged=1]="AliRtcConnectionMediaPathChanged",s[s.AliRtcConnectionSignalingHeartbeatTimeout=2]="AliRtcConnectionSignalingHeartbeatTimeout",s[s.AliRtcConnectionSignalingHeartbeatAlive=3]="AliRtcConnectionSignalingHeartbeatAlive",s[s.AliRtcConnectionSignalingHttpDnsResolved=4]="AliRtcConnectionSignalingHttpDnsResolved",s[s.AliRtcConnectionSignalingHttpDnsFailure=5]="AliRtcConnectionSignalingHttpDnsFailure",s[s.AliRtcConnectionSignalingGslbFailure=6]="AliRtcConnectionSignalingGslbFailure",s[s.AliRtcConnectionSignalingGslbSuccess=7]="AliRtcConnectionSignalingGslbSuccess",s[s.AliRtcConnectionSignalingJoinRoomFailure=8]="AliRtcConnectionSignalingJoinRoomFailure",s[s.AliRtcConnectionSignalingJoinRoomSuccess=9]="AliRtcConnectionSignalingJoinRoomSuccess",s[s.AliRtcConnectionSignalingLeaveRoom=10]="AliRtcConnectionSignalingLeaveRoom",s[s.AliRtcConnectionSignalingConnecting=11]="AliRtcConnectionSignalingConnecting",s[s.AliRtcConnectionChangedNetworkInterrupted=12]="AliRtcConnectionChangedNetworkInterrupted",s))(At||{}),or=(s=>(s[s.AliRtcUserOfflineQuit=0]="AliRtcUserOfflineQuit",s[s.AliRtcUserOfflineDropped=1]="AliRtcUserOfflineDropped",s[s.AliRtcUserOfflineBecomeAudience=2]="AliRtcUserOfflineBecomeAudience",s))(or||{}),$t=(s=>(s[s.AliRtcAudioTrackNo=0]="AliRtcAudioTrackNo",s[s.AliRtcAudioTrackMic=1]="AliRtcAudioTrackMic",s[s.AliRtcAudioTrackDual=2]="AliRtcAudioTrackDual",s))($t||{}),ce=(s=>(s[s.AliRtcVideoTrackNo=0]="AliRtcVideoTrackNo",s[s.AliRtcVideoTrackCamera=1]="AliRtcVideoTrackCamera",s[s.AliRtcVideoTrackScreen=2]="AliRtcVideoTrackScreen",s[s.AliRtcVideoTrackBoth=3]="AliRtcVideoTrackBoth",s))(ce||{}),te=(s=>(s[s.AliRtcStatePublishIdle=0]="AliRtcStatePublishIdle",s[s.AliRtcStateNoPublish=1]="AliRtcStateNoPublish",s[s.AliRtcStatePublishing=2]="AliRtcStatePublishing",s[s.AliRtcStatePublished=3]="AliRtcStatePublished",s[s.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",s))(te||{}),ae=(s=>(s[s.AliRtcStateSubscribeIdle=0]="AliRtcStateSubscribeIdle",s[s.AliRtcStateNoSubscribe=1]="AliRtcStateNoSubscribe",s[s.AliRtcStateSubscribing=2]="AliRtcStateSubscribing",s[s.AliRtcStateSubscribed=3]="AliRtcStateSubscribed",s[s.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",s))(ae||{}),Ke=(s=>(s[s.AliRtcVideoStreamTypeNone=0]="AliRtcVideoStreamTypeNone",s[s.AliRtcVideoStreamTypeHigh=1]="AliRtcVideoStreamTypeHigh",s[s.AliRtcVideoStreamTypeLow=2]="AliRtcVideoStreamTypeLow",s))(Ke||{}),mi=(s=>(s[s.CAMERA_INVALID=-1]="CAMERA_INVALID",s[s.CAMERA_REAR=0]="CAMERA_REAR",s[s.CAMERA_FRONT=1]="CAMERA_FRONT",s))(mi||{});const pa="ALI_RTC_SDK_ALLOCATE_RESULT",di=class di{constructor(a,e,t){g(this,"result",null);g(this,"pms");let i=localStorage.getItem(pa);if(i){const u=JSON.parse(i);u.appId===e.appId&&u.expireTs-3e5>Date.now()?this.result=u.allocatedData:N.info(`[${di.logName}]`,"allocate","cached data is invalid")}const{appId:r,channelId:n,userId:c,timestamp:o,token:l,nonce:d}=e,h=new URLSearchParams({appid:r,channelid:n,userid:c,timestamp:`${o}`,token:l,nonce:d!=null?d:"",adapt:"true",clitype:"2"});t&&h.set("joinmode",t);const p=a===mt.pre?ri.pre:ri.prod;this.pms=fetch(`https://${p}/gslb/v1/allocate?${h.toString()}`,{method:"POST",body:JSON.stringify(Ui.adaptInfo)}).then(u=>u.json()).then(u=>{if(u.code===0){const f=u.data;this.result=f;const{ice_ufrag:m}=f.h5auth,[b,S]=atob(m).split("_"),v={appId:r,expireTs:1e3*parseInt(S),allocatedData:f};return N.info(`[${di.logName}]`,"got allocate result and save",f.h5auth.ice_ufrag),localStorage.setItem(pa,JSON.stringify(v)),f}return null}).catch(u=>(N.error(`[${di.logName}]`,"allocate",u),null))}};g(di,"logName","Allocator");let fi=di;var U=(s=>(s[s.ERR_JOIN_ALREADY_JOINED=16843521]="ERR_JOIN_ALREADY_JOINED",s[s.ERR_JOIN_BAD_APPID=33620481]="ERR_JOIN_BAD_APPID",s[s.ERR_JOIN_INVALID_APPID=33620482]="ERR_JOIN_INVALID_APPID",s[s.ERR_JOIN_BAD_CHANNEL=33620484]="ERR_JOIN_BAD_CHANNEL",s[s.ERR_JOIN_INVALID_CHANNEL=33620483]="ERR_JOIN_INVALID_CHANNEL",s[s.ERR_JOIN_BAD_TOKEN=33620485]="ERR_JOIN_BAD_TOKEN",s[s.ERR_JOIN_TIMEOUT=16908804]="ERR_JOIN_TIMEOUT",s[s.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD=16974081]="ERR_JOIN_ERR_JOIN_BAD_PARAMBAD",s[s.ERR_JOIN_CHANNEL_FAILED=16974338]="ERR_JOIN_CHANNEL_FAILED",s[s.ERR_LOG_ALREADY_INIT=16974085]="ERR_LOG_ALREADY_INIT",s[s.ERR_LOG_ROOT_PATH_ERROR=16974086]="ERR_LOG_ROOT_PATH_ERROR",s[s.ERR_MIC_OPEN_FAIL=17040388]="ERR_MIC_OPEN_FAIL",s[s.ERR_SPEAKER_OPEN_FAIL=17040389]="ERR_SPEAKER_OPEN_FAIL",s[s.ERR_MIC_INTERRUPT=17040390]="ERR_MIC_INTERRUPT",s[s.ERR_SPEAKER_INTERRUPT=17040391]="ERR_SPEAKER_INTERRUPT",s[s.ERR_MIC_AUTH_FAIL=17040392]="ERR_MIC_AUTH_FAIL",s[s.ERR_MIC_NOT_AVAILABLE=17040393]="ERR_MIC_NOT_AVAILABLE",s[s.ERR_SPEAKER_NOT_AVAILABLE=17040400]="ERR_SPEAKER_NOT_AVAILABLE",s[s.ERR_CAMERA_OPEN_FAIL=17039620]="ERR_CAMERA_OPEN_FAIL",s[s.ERR_CAMERA_AUTH_FAIL=17039621]="ERR_CAMERA_AUTH_FAIL",s[s.ERR_CAMERA_INTERRUPT=17039622]="ERR_CAMERA_INTERRUPT",s[s.ERR_CAMERA_NOT_AVAILABLE=17039623]="ERR_CAMERA_NOT_AVAILABLE",s[s.ERR_VIDEO_DISPLAY_OPEN_FAIL=17039873]="ERR_VIDEO_DISPLAY_OPEN_FAIL",s[s.ERR_VIDEO_DISPLAY_INTERRUPT=1064992]="ERR_VIDEO_DISPLAY_INTERRUPT",s[s.ERR_ICE_CONNECTION_CONNECT_FAIL=17105409]="ERR_ICE_CONNECTION_CONNECT_FAIL",s[s.ERR_ICE_CONNECTION_RECONNECT_FAI=17105410]="ERR_ICE_CONNECTION_RECONNECT_FAI",s[s.ERR_ICE_CONNECTION_MOBILITY_FAIL=17105411]="ERR_ICE_CONNECTION_MOBILITY_FAIL",s[s.ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT=16908812]="ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT",s[s.ERR_LATENCY_LIVE_COMMUNICATION_FAILED=17235971]="ERR_LATENCY_LIVE_COMMUNICATION_FAILED",s[s.ERR_LATENCY_LIVE_MEIDASETTING_FAILED=17235972]="ERR_LATENCY_LIVE_MEIDASETTING_FAILED",s[s.ERR_LATENCY_LIVE_NONE_BROADCASTER=17235973]="ERR_LATENCY_LIVE_NONE_BROADCASTER",s[s.ERR_LATENCY_LIVE_NEED_RESTART=17235974]="ERR_LATENCY_LIVE_NEED_RESTART",s[s.ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER=17235975]="ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER",s[s.ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE=17235976]="ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE",s[s.ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION=17235977]="ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION",s[s.ERR_SDK_PUBLISH_INVAILD=16974597]="ERR_SDK_PUBLISH_INVAILD",s[s.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL=16843782]="ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL",s[s.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED=16843856]="ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED",s[s.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED=16843857]="ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED",s[s.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED=16843858]="ERR_SDK_PUBLISH_DUAL_STREAM_FAILED",s[s.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED=16843859]="ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED",s[s.ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR=16843860]="ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR",s[s.ERR_SDK_SUBSCRIBE_INVAILD=16974852]="ERR_SDK_SUBSCRIBE_INVAILD",s[s.ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL=16844112]="ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL",s[s.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED=16844113]="ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED=16844114]="ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED=16844115]="ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED=16844116]="ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED",s[s.ERR_SDK_SUBSCRIBE_DATA_FAILED=16844117]="ERR_SDK_SUBSCRIBE_DATA_FAILED",s[s.ERR_SDK_SUBSCRIBE_DATA_ERROR=16844118]="ERR_SDK_SUBSCRIBE_DATA_ERROR",s[s.ERR_SDK_INVALID_STATE=16974340]="ERR_SDK_INVALID_STATE",s[s.ERR_INVALID_ARGUMENTS=16974083]="ERR_INVALID_ARGUMENTS",s[s.ERR_SESSION_REMOVED=33620229]="ERR_SESSION_REMOVED",s[s.ERR_SDK_UPDATE_ROLE_CHANNEL=16908801]="ERR_SDK_UPDATE_ROLE_CHANNEL",s[s.ERR_INNER=-1]="ERR_INNER",s[s.ERR_SDK_MPU_TASK_PUBLISH_OK=0]="ERR_SDK_MPU_TASK_PUBLISH_OK",s[s.ERR_SDK_MPU_TASK_STREAM_NOT_FOUND=17825793]="ERR_SDK_MPU_TASK_STREAM_NOT_FOUND",s[s.ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST=17825794]="ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST",s[s.ERR_SDK_MPU_TASK_INVALID_PARAM=17825795]="ERR_SDK_MPU_TASK_INVALID_PARAM",s[s.ERR_SDK_MPU_TASK_INTERNAL_ERROR=17825796]="ERR_SDK_MPU_TASK_INTERNAL_ERROR",s[s.ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR=17825797]="ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR",s[s.ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR=17825798]="ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR",s[s.ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT=17825799]="ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT",s[s.ERR_SDK_MPU_TASK_NOT_AUTHORIZED=17825800]="ERR_SDK_MPU_TASK_NOT_AUTHORIZED",s[s.ERR_SDK_CHANNEL_RELAY_STATE_ERROR=18874369]="ERR_SDK_CHANNEL_RELAY_STATE_ERROR",s[s.ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW=18874370]="ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW",s[s.ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED=18874371]="ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED",s[s.ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID=18874372]="ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID",s[s.ERR_SDK_CHANNEL_RELAY_ROLE_ERROR=18874373]="ERR_SDK_CHANNEL_RELAY_ROLE_ERROR",s[s.ERR_SDK_CHANNEL_RELAY_INVALID_PARAM=18874374]="ERR_SDK_CHANNEL_RELAY_INVALID_PARAM",s[s.ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR=18874375]="ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR",s))(U||{});class V extends Error{constructor(e,t,i){super(t);g(this,"_code");g(this,"_extra");this._code=e,this._extra=i}static fromRtsError(e){return e instanceof V?e:new V((e==null?void 0:e.errorCode)||-1,(e==null?void 0:e.message)||(e==null?void 0:e.errorCodeName)||"rts error",e)}static fromError(e,t=-1,i=""){return new V(t,(e==null?void 0:e.message)||(e==null?void 0:e.reason)||i||"error",e)}get code(){return this._code}set code(e){this._code=e}get reason(){return this.message}get extra(){return this._extra}}function ga(s){var a;if(((a=s==null?void 0:s.nodeName)==null?void 0:a.toLowerCase())==="video")return s.setAttribute("playsinline",""),s;if(typeof s=="string"){let e=document.getElementById(s);if(e){if(e.nodeName.toLocaleLowerCase()==="video")return e.setAttribute("playsinline",""),e;throw new V(U.ERR_INVALID_ARGUMENTS,"element should be HtmlVideoElement")}throw new V(U.ERR_INVALID_ARGUMENTS,"element not founded")}throw new V(U.ERR_INVALID_ARGUMENTS,"element id should be string")}function cr(s){var e;const a=[];if(Array.isArray(s))s.forEach(t=>{try{a.push(ga(t))}catch(i){}});else if(typeof s=="string"||((e=s==null?void 0:s.nodeName)==null?void 0:e.toLowerCase())==="video")try{a.push(ga(s))}catch(t){}return a}function xt(s){return new Promise(a=>setTimeout(a,s))}function ma(s,a,e=1e3,t=i=>!0){return I(this,null,function*(){let i=0;for(;i<a;)try{return yield s(i)}catch(r){if(i++,i>=a||!t(r))throw r||void 0;yield new Promise(n=>setTimeout(n,e))}})}function lr(s,a){let e=a;return typeof window.__ali_prefer_media_server=="string"&&window.__ali_prefer_media_server!==""&&(e=window.__ali_prefer_media_server),e?`${s}&ali_prefer_media_server=${e}`:s}function Kt(s,a){var e;try{const{archCfgs:t}=s;if(!t||!Array.isArray(t))return;const i=t.find(r=>r.arch==="grtn");return i?(e=i.user_specified)==null?void 0:e[a]:void 0}catch(t){return}}function si(s,a){try{const{config:e}=s;return e?e==null?void 0:e[a]:void 0}catch(e){return}}class dr{constructor(a,e){g(this,"originTrack");g(this,"originVideo");g(this,"targetWidth");g(this,"targetHeight");g(this,"targetFrameRate");g(this,"targetCanvas");g(this,"animationFrameId");g(this,"resultTrack");this.targetWidth=e.width,this.targetHeight=e.height,this.targetFrameRate=e.frameRate,this.originTrack=a,this.originVideo=document.createElement("video"),this.originVideo.muted=!0,this.originVideo.autoplay=!0,this.originVideo.controls=!1,this.targetCanvas=document.createElement("canvas"),this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight}updateOptions(a){this.targetWidth=a.width,this.targetHeight=a.height,this.targetFrameRate=a.frameRate,this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight,this.resultTrack&&this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})}dispose(){}getVideoTrack(){return this.resultTrack||(this.resultTrack=this.targetCanvas.captureStream().getVideoTracks()[0],this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})),this.resultTrack}cancelAnimation(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}getPositionAndSize(a,e,t,i){const r=e/a,n=i/t;let c=t,o=i,l=0,d=0;return n>r?(c=Math.round(o/r),l=Math.round((t-c)/2)):n<r&&(o=Math.round(c*r),d=Math.round((i-o)/2)),{x:l,y:d,width:c,height:o}}}class No extends dr{constructor(e,t){super(e,t);g(this,"targetCtx");this.targetCtx=this.targetCanvas.getContext("2d"),this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.initStream(e)}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender)}startRender(){this.cancelAnimation();const e=()=>{if(!this.targetCtx)return;const t=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight);this.targetCtx.drawImage(this.originVideo,0,0,this.originVideo.videoWidth,this.originVideo.videoHeight,t.x,t.y,t.width,t.height),this.originVideo.paused||this.originVideo.ended||(this.animationFrameId=requestAnimationFrame(e))};e()}stopRender(){this.cancelAnimation()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.pause(),this.originVideo.srcObject=null}}function fa(s,a,e){const t=s.createShader(a);if(t)return s.shaderSource(t,e),s.compileShader(t),s.getShaderParameter(t,s.COMPILE_STATUS)?t:(console.error(`An error occurred compiling the shaders: ${s.getShaderInfoLog(t)}`),s.deleteShader(t),null);console.error("create shader failed")}class Sa extends dr{constructor(e,t){super(e,t);g(this,"targetCtx");g(this,"targetTexture");g(this,"locationMap");this.targetCtx=this.targetCanvas.getContext("webgl2"),this.locationMap={},this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.updateBuffer=this.updateBuffer.bind(this),this.initGL(),this.initStream(e)}static isSupport(){return function(){let e;try{const t=document.createElement("canvas");t.width=1,t.height=1;const i={alpha:!1,depth:!1,stencil:!1,antialias:!1,preferLowPowerToHighPerformance:!0};e=t.getContext("webgl2",i)}catch(t){return!1}return!!e}()}initGL(){const e=this.targetCtx;if(!e)return;this.targetTexture=function(o){const l=o.createTexture();return o.bindTexture(o.TEXTURE_2D,l),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),l}(e);const t=function(o,l,d){const h=fa(o,o.VERTEX_SHADER,l),p=fa(o,o.FRAGMENT_SHADER,d),u=o.createProgram();if(u&&h&&p)return o.attachShader(u,h),o.attachShader(u,p),o.linkProgram(u),o.getProgramParameter(u,o.LINK_STATUS)?u:(console.error(`Unable to initialize the shader program: ${o.getProgramInfoLog(u)}`),null)}(e,`
6
+ `;const M=(K,B)=>K[0].localeCompare(B[0]),I=K=>K[0].startsWith("x-log-")||K[0].startsWith("x-acs-");try{const K=[...y.entries()].filter(I).sort(M).map(B=>B[0]+":"+B[1]+`
7
+ `).join("");P+=K}catch(K){}P+=v,R.size>0&&(P+="?");try{P+=[...R.entries()].sort(M).map(K=>K[0]+"="+K[1]).join("&")}catch(K){}const j="LOG "+E+":"+ui.HmacSHA1(P,T).toString(ui.enc.Base64);y.set("Authorization",j),y.set("x-log-date",w)}("POST",c,s.accessKeyId,s.accessKeySecret,f,m,l,h);let g=Object.fromEntries(m);return{data:e,header:g}},new Promise((c,o)=>{var l=u=>{try{h(a.next(u))}catch(p){o(p)}},d=u=>{try{h(a.throw(u))}catch(p){o(p)}},h=u=>u.done?c(u.value):Promise.resolve(u.value).then(l,d);h((a=a.apply(i,n)).next())});var i,n,a}}}typeof window!="undefined"&&li(window,"stsPlugin",Ps);let mo=!0,fo=!0;function pi(s,r,e){const t=s.match(r);return t&&t.length>=e&&parseInt(t[e],10)}function $r(s,r,e){if(!s.RTCPeerConnection)return;const t=s.RTCPeerConnection.prototype,i=t.addEventListener;t.addEventListener=function(a,c){if(a!==r)return i.apply(this,arguments);const o=l=>{const d=e(l);d&&(c.handleEvent?c.handleEvent(d):c(d))};return this._eventMap=this._eventMap||{},this._eventMap[r]||(this._eventMap[r]=new Map),this._eventMap[r].set(c,o),i.apply(this,[a,o])};const n=t.removeEventListener;t.removeEventListener=function(a,c){if(a!==r||!this._eventMap||!this._eventMap[r])return n.apply(this,arguments);if(!this._eventMap[r].has(c))return n.apply(this,arguments);const o=this._eventMap[r].get(c);return this._eventMap[r].delete(c),this._eventMap[r].size===0&&delete this._eventMap[r],Object.keys(this._eventMap).length===0&&delete this._eventMap,n.apply(this,[a,o])},Object.defineProperty(t,"on"+r,{get(){return this["_on"+r]},set(a){this["_on"+r]&&(this.removeEventListener(r,this["_on"+r]),delete this["_on"+r]),a&&this.addEventListener(r,this["_on"+r]=a)},enumerable:!0,configurable:!0})}function Hh(s){return typeof s!="boolean"?new Error("Argument type: "+typeof s+". Please use a boolean."):(mo=s,s?"adapter.js logging disabled":"adapter.js logging enabled")}function Wh(s){return typeof s!="boolean"?new Error("Argument type: "+typeof s+". Please use a boolean."):(fo=!s,"adapter.js deprecation warnings "+(s?"disabled":"enabled"))}function Ds(){if(typeof window=="object"){if(mo)return;typeof console!="undefined"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Bi(s,r){fo&&console.warn(s+" is deprecated, please use "+r+" instead.")}function go(s){return Object.prototype.toString.call(s)==="[object Object]"}function So(s){return go(s)?Object.keys(s).reduce(function(r,e){const t=go(s[e]),i=t?So(s[e]):s[e],n=t&&!Object.keys(i).length;return i===void 0||n?r:Object.assign(r,{[e]:i})},{}):s}function ks(s,r,e){r&&!e.has(r.id)&&(e.set(r.id,r),Object.keys(r).forEach(t=>{t.endsWith("Id")?ks(s,s.get(r[t]),e):t.endsWith("Ids")&&r[t].forEach(i=>{ks(s,s.get(i),e)})}))}function bo(s,r,e){const t=e?"outbound-rtp":"inbound-rtp",i=new Map;if(r===null)return i;const n=[];return s.forEach(a=>{a.type==="track"&&a.trackIdentifier===r.id&&n.push(a)}),n.forEach(a=>{s.forEach(c=>{c.type===t&&c.trackId===a.id&&ks(s,c,i)})}),i}const vo=Ds;function Ro(s,r){const e=s&&s.navigator;if(!e.mediaDevices)return;const t=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(o=>{if(o==="require"||o==="advanced"||o==="mediaSource")return;const l=typeof a[o]=="object"?a[o]:{ideal:a[o]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const d=function(h,u){return h?h+u.charAt(0).toUpperCase()+u.slice(1):u==="deviceId"?"sourceId":u};if(l.ideal!==void 0){c.optional=c.optional||[];let h={};typeof l.ideal=="number"?(h[d("min",o)]=l.ideal,c.optional.push(h),h={},h[d("max",o)]=l.ideal,c.optional.push(h)):(h[d("",o)]=l.ideal,c.optional.push(h))}l.exact!==void 0&&typeof l.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[d("",o)]=l.exact):["min","max"].forEach(h=>{l[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[d(h,o)]=l[h])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},i=function(a,c){if(r.version>=61)return c(a);if((a=JSON.parse(JSON.stringify(a)))&&typeof a.audio=="object"){const o=function(l,d,h){d in l&&!(h in l)&&(l[h]=l[d],delete l[d])};o((a=JSON.parse(JSON.stringify(a))).audio,"autoGainControl","googAutoGainControl"),o(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=t(a.audio)}if(a&&typeof a.video=="object"){let o=a.video.facingMode;o=o&&(typeof o=="object"?o:{ideal:o});const l=r.version<66;if(o&&(o.exact==="user"||o.exact==="environment"||o.ideal==="user"||o.ideal==="environment")&&(!e.mediaDevices.getSupportedConstraints||!e.mediaDevices.getSupportedConstraints().facingMode||l)){let d;if(delete a.video.facingMode,o.exact==="environment"||o.ideal==="environment"?d=["back","rear"]:o.exact!=="user"&&o.ideal!=="user"||(d=["front"]),d)return e.mediaDevices.enumerateDevices().then(h=>{let u=(h=h.filter(p=>p.kind==="videoinput")).find(p=>d.some(f=>p.label.toLowerCase().includes(f)));return!u&&h.length&&d.includes("back")&&(u=h[h.length-1]),u&&(a.video.deviceId=o.exact?{exact:u.deviceId}:{ideal:u.deviceId}),a.video=t(a.video),vo("chrome: "+JSON.stringify(a)),c(a)})}a.video=t(a.video)}return vo("chrome: "+JSON.stringify(a)),c(a)},n=function(a){return r.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(e.getUserMedia=function(a,c,o){i(a,l=>{e.webkitGetUserMedia(l,c,d=>{o&&o(n(d))})})}.bind(e),e.mediaDevices.getUserMedia){const a=e.mediaDevices.getUserMedia.bind(e.mediaDevices);e.mediaDevices.getUserMedia=function(c){return i(c,o=>a(o).then(l=>{if(o.audio&&!l.getAudioTracks().length||o.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(d=>{d.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(n(l))))}}}function Eo(s){s.MediaStream=s.MediaStream||s.webkitMediaStream}function yo(s){if(typeof s=="object"&&s.RTCPeerConnection&&!("ontrack"in s.RTCPeerConnection.prototype)){Object.defineProperty(s.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const r=s.RTCPeerConnection.prototype.setRemoteDescription;s.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=e=>{e.stream.addEventListener("addtrack",t=>{let i;i=s.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(a=>a.track&&a.track.id===t.track.id):{track:t.track};const n=new Event("track");n.track=t.track,n.receiver=i,n.transceiver={receiver:i},n.streams=[e.stream],this.dispatchEvent(n)}),e.stream.getTracks().forEach(t=>{let i;i=s.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(a=>a.track&&a.track.id===t.id):{track:t};const n=new Event("track");n.track=t,n.receiver=i,n.transceiver={receiver:i},n.streams=[e.stream],this.dispatchEvent(n)})},this.addEventListener("addstream",this._ontrackpoly)),r.apply(this,arguments)}}else $r(s,"track",r=>(r.transceiver||Object.defineProperty(r,"transceiver",{value:{receiver:r.receiver}}),r))}function To(s){if(typeof s=="object"&&s.RTCPeerConnection&&!("getSenders"in s.RTCPeerConnection.prototype)&&"createDTMFSender"in s.RTCPeerConnection.prototype){const r=function(i,n){return{track:n,get dtmf(){return this._dtmf===void 0&&(n.kind==="audio"?this._dtmf=i.createDTMFSender(n):this._dtmf=null),this._dtmf},_pc:i}};if(!s.RTCPeerConnection.prototype.getSenders){s.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=s.RTCPeerConnection.prototype.addTrack;s.RTCPeerConnection.prototype.addTrack=function(a,c){let o=i.apply(this,arguments);return o||(o=r(this,a),this._senders.push(o)),o};const n=s.RTCPeerConnection.prototype.removeTrack;s.RTCPeerConnection.prototype.removeTrack=function(a){n.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const e=s.RTCPeerConnection.prototype.addStream;s.RTCPeerConnection.prototype.addStream=function(i){this._senders=this._senders||[],e.apply(this,[i]),i.getTracks().forEach(n=>{this._senders.push(r(this,n))})};const t=s.RTCPeerConnection.prototype.removeStream;s.RTCPeerConnection.prototype.removeStream=function(i){this._senders=this._senders||[],t.apply(this,[i]),i.getTracks().forEach(n=>{const a=this._senders.find(c=>c.track===n);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof s=="object"&&s.RTCPeerConnection&&"getSenders"in s.RTCPeerConnection.prototype&&"createDTMFSender"in s.RTCPeerConnection.prototype&&s.RTCRtpSender&&!("dtmf"in s.RTCRtpSender.prototype)){const r=s.RTCPeerConnection.prototype.getSenders;s.RTCPeerConnection.prototype.getSenders=function(){const e=r.apply(this,[]);return e.forEach(t=>t._pc=this),e},Object.defineProperty(s.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Co(s){if(!s.RTCPeerConnection)return;const r=s.RTCPeerConnection.prototype.getStats;s.RTCPeerConnection.prototype.getStats=function(){const[e,t,i]=arguments;if(arguments.length>0&&typeof e=="function")return r.apply(this,arguments);if(r.length===0&&(arguments.length===0||typeof e!="function"))return r.apply(this,[]);const n=function(c){const o={};return c.result().forEach(l=>{const d={id:l.id,timestamp:l.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[l.type]||l.type};l.names().forEach(h=>{d[h]=l.stat(h)}),o[d.id]=d}),o},a=function(c){return new Map(Object.keys(c).map(o=>[o,c[o]]))};if(arguments.length>=2){const c=function(o){t(a(n(o)))};return r.apply(this,[c,e])}return new Promise((c,o)=>{r.apply(this,[function(l){c(a(n(l)))},o])}).then(t,i)}}function _o(s){if(!(typeof s=="object"&&s.RTCPeerConnection&&s.RTCRtpSender&&s.RTCRtpReceiver))return;if(!("getStats"in s.RTCRtpSender.prototype)){const e=s.RTCPeerConnection.prototype.getSenders;e&&(s.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(n=>n._pc=this),i});const t=s.RTCPeerConnection.prototype.addTrack;t&&(s.RTCPeerConnection.prototype.addTrack=function(){const i=t.apply(this,arguments);return i._pc=this,i}),s.RTCRtpSender.prototype.getStats=function(){const i=this;return this._pc.getStats().then(n=>bo(n,i.track,!0))}}if(!("getStats"in s.RTCRtpReceiver.prototype)){const e=s.RTCPeerConnection.prototype.getReceivers;e&&(s.RTCPeerConnection.prototype.getReceivers=function(){const t=e.apply(this,[]);return t.forEach(i=>i._pc=this),t}),$r(s,"track",t=>(t.receiver._pc=t.srcElement,t)),s.RTCRtpReceiver.prototype.getStats=function(){const t=this;return this._pc.getStats().then(i=>bo(i,t.track,!1))}}if(!("getStats"in s.RTCRtpSender.prototype)||!("getStats"in s.RTCRtpReceiver.prototype))return;const r=s.RTCPeerConnection.prototype.getStats;s.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof s.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach(a=>{a.track===e&&(t?n=!0:t=a)}),this.getReceivers().forEach(a=>(a.track===e&&(i?n=!0:i=a),a.track===e)),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return r.apply(this,arguments)}}function wo(s){s.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(n=>this._shimmedLocalStreams[n][0])};const r=s.RTCPeerConnection.prototype.addTrack;s.RTCPeerConnection.prototype.addTrack=function(n,a){if(!a)return r.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=r.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const e=s.RTCPeerConnection.prototype.addStream;s.RTCPeerConnection.prototype.addStream=function(n){this._shimmedLocalStreams=this._shimmedLocalStreams||{},n.getTracks().forEach(o=>{if(this.getSenders().find(d=>d.track===o))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();e.apply(this,arguments);const c=this.getSenders().filter(o=>a.indexOf(o)===-1);this._shimmedLocalStreams[n.id]=[n].concat(c)};const t=s.RTCPeerConnection.prototype.removeStream;s.RTCPeerConnection.prototype.removeStream=function(n){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[n.id],t.apply(this,arguments)};const i=s.RTCPeerConnection.prototype.removeTrack;s.RTCPeerConnection.prototype.removeTrack=function(n){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},n&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(n);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),i.apply(this,arguments)}}function Ao(s,r){if(!s.RTCPeerConnection)return;if(s.RTCPeerConnection.prototype.addTrack&&r.version>=65)return wo(s);const e=s.RTCPeerConnection.prototype.getLocalStreams;s.RTCPeerConnection.prototype.getLocalStreams=function(){const o=e.apply(this);return this._reverseStreams=this._reverseStreams||{},o.map(l=>this._reverseStreams[l.id])};const t=s.RTCPeerConnection.prototype.addStream;s.RTCPeerConnection.prototype.addStream=function(o){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},o.getTracks().forEach(l=>{if(this.getSenders().find(h=>h.track===l))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[o.id]){const l=new s.MediaStream(o.getTracks());this._streams[o.id]=l,this._reverseStreams[l.id]=o,o=l}t.apply(this,[o])};const i=s.RTCPeerConnection.prototype.removeStream;function n(o,l){let d=l.sdp;return Object.keys(o._reverseStreams||[]).forEach(h=>{const u=o._reverseStreams[h],p=o._streams[u.id];d=d.replace(new RegExp(p.id,"g"),u.id)}),new RTCSessionDescription({type:l.type,sdp:d})}s.RTCPeerConnection.prototype.removeStream=function(o){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[o.id]||o]),delete this._reverseStreams[this._streams[o.id]?this._streams[o.id].id:o.id],delete this._streams[o.id]},s.RTCPeerConnection.prototype.addTrack=function(o,l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const d=[].slice.call(arguments,1);if(d.length!==1||!d[0].getTracks().find(p=>p===o))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(p=>p.track===o))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const u=this._streams[l.id];if(u)u.addTrack(o),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const p=new s.MediaStream([o]);this._streams[l.id]=p,this._reverseStreams[p.id]=l,this.addStream(p)}return this.getSenders().find(p=>p.track===o)},["createOffer","createAnswer"].forEach(function(o){const l=s.RTCPeerConnection.prototype[o],d={[o](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[u=>{const p=n(this,u);h[0].apply(null,[p])},u=>{h[1]&&h[1].apply(null,u)},arguments[2]]):l.apply(this,arguments).then(u=>n(this,u))}};s.RTCPeerConnection.prototype[o]=d[o]});const a=s.RTCPeerConnection.prototype.setLocalDescription;s.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(o,l){let d=l.sdp;return Object.keys(o._reverseStreams||[]).forEach(h=>{const u=o._reverseStreams[h],p=o._streams[u.id];d=d.replace(new RegExp(u.id,"g"),p.id)}),new RTCSessionDescription({type:l.type,sdp:d})}(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const c=Object.getOwnPropertyDescriptor(s.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(s.RTCPeerConnection.prototype,"localDescription",{get(){const o=c.get.apply(this);return o.type===""?o:n(this,o)}}),s.RTCPeerConnection.prototype.removeTrack=function(o){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!o._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(o._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let l;this._streams=this._streams||{},Object.keys(this._streams).forEach(d=>{this._streams[d].getTracks().find(h=>o.track===h)&&(l=this._streams[d])}),l&&(l.getTracks().length===1?this.removeStream(this._reverseStreams[l.id]):l.removeTrack(o.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Ms(s,r){!s.RTCPeerConnection&&s.webkitRTCPeerConnection&&(s.RTCPeerConnection=s.webkitRTCPeerConnection),s.RTCPeerConnection&&r.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(e){const t=s.RTCPeerConnection.prototype[e],i={[e](){return arguments[0]=new(e==="addIceCandidate"?s.RTCIceCandidate:s.RTCSessionDescription)(arguments[0]),t.apply(this,arguments)}};s.RTCPeerConnection.prototype[e]=i[e]})}function Io(s,r){$r(s,"negotiationneeded",e=>{const t=e.target;if(!(r.version<72||t.getConfiguration&&t.getConfiguration().sdpSemantics==="plan-b")||t.signalingState==="stable")return e})}const Po=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:Io,shimAddTrackRemoveTrack:Ao,shimAddTrackRemoveTrackWithNative:wo,shimGetDisplayMedia:function(s,r){s.navigator.mediaDevices&&"getDisplayMedia"in s.navigator.mediaDevices||s.navigator.mediaDevices&&(typeof r=="function"?s.navigator.mediaDevices.getDisplayMedia=function(e){return r(e).then(t=>{const i=e.video&&e.video.width,n=e.video&&e.video.height,a=e.video&&e.video.frameRate;return e.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:a||3}},i&&(e.video.mandatory.maxWidth=i),n&&(e.video.mandatory.maxHeight=n),s.navigator.mediaDevices.getUserMedia(e)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:To,shimGetStats:Co,shimGetUserMedia:Ro,shimMediaStream:Eo,shimOnTrack:yo,shimPeerConnection:Ms,shimSenderReceiverGetStats:_o},Symbol.toStringTag,{value:"Module"}));var Do={exports:{}};(function(s){var r={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};r.localCName=r.generateIdentifier(),r.splitLines=function(e){return e.trim().split(`
8
+ `).map(function(t){return t.trim()})},r.splitSections=function(e){return e.split(`
9
+ m=`).map(function(t,i){return(i>0?"m="+t:t).trim()+`\r
10
+ `})},r.getDescription=function(e){var t=r.splitSections(e);return t&&t[0]},r.getMediaSections=function(e){var t=r.splitSections(e);return t.shift(),t},r.matchPrefix=function(e,t){return r.splitLines(e).filter(function(i){return i.indexOf(t)===0})},r.parseCandidate=function(e){for(var t,i={foundation:(t=e.indexOf("a=candidate:")===0?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:parseInt(t[1],10),protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},n=8;n<t.length;n+=2)switch(t[n]){case"raddr":i.relatedAddress=t[n+1];break;case"rport":i.relatedPort=parseInt(t[n+1],10);break;case"tcptype":i.tcpType=t[n+1];break;case"ufrag":i.ufrag=t[n+1],i.usernameFragment=t[n+1];break;default:i[t[n]]=t[n+1]}return i},r.writeCandidate=function(e){var t=[];t.push(e.foundation),t.push(e.component),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var i=e.type;return t.push("typ"),t.push(i),i!=="host"&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&e.protocol.toLowerCase()==="tcp"&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},r.parseIceOptions=function(e){return e.substr(14).split(" ")},r.parseRtpMap=function(e){var t=e.substr(9).split(" "),i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=t.length===3?parseInt(t[2],10):1,i.numChannels=i.channels,i},r.writeRtpMap=function(e){var t=e.payloadType;e.preferredPayloadType!==void 0&&(t=e.preferredPayloadType);var i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(i!==1?"/"+i:"")+`\r
11
+ `},r.parseExtmap=function(e){var t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},r.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&e.direction!=="sendrecv"?"/"+e.direction:"")+" "+e.uri+`\r
12
+ `},r.parseFmtp=function(e){for(var t,i={},n=e.substr(e.indexOf(" ")+1).split(";"),a=0;a<n.length;a++)i[(t=n[a].trim().split("="))[0].trim()]=t[1];return i},r.writeFmtp=function(e){var t="",i=e.payloadType;if(e.preferredPayloadType!==void 0&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var n=[];Object.keys(e.parameters).forEach(function(a){e.parameters[a]?n.push(a+"="+e.parameters[a]):n.push(a)}),t+="a=fmtp:"+i+" "+n.join(";")+`\r
13
+ `}return t},r.parseRtcpFb=function(e){var t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},r.writeRtcpFb=function(e){var t="",i=e.payloadType;return e.preferredPayloadType!==void 0&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(function(n){t+="a=rtcp-fb:"+i+" "+n.type+(n.parameter&&n.parameter.length?" "+n.parameter:"")+`\r
14
+ `}),t},r.parseSsrcMedia=function(e){var t=e.indexOf(" "),i={ssrc:parseInt(e.substr(7,t-7),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substr(t+1,n-t-1),i.value=e.substr(n+1)):i.attribute=e.substr(t+1),i},r.parseSsrcGroup=function(e){var t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(function(i){return parseInt(i,10)})}},r.getMid=function(e){var t=r.matchPrefix(e,"a=mid:")[0];if(t)return t.substr(6)},r.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},r.getDtlsParameters=function(e,t){return{role:"auto",fingerprints:r.matchPrefix(e+t,"a=fingerprint:").map(r.parseFingerprint)}},r.writeDtlsParameters=function(e,t){var i="a=setup:"+t+`\r
15
+ `;return e.fingerprints.forEach(function(n){i+="a=fingerprint:"+n.algorithm+" "+n.value+`\r
16
+ `}),i},r.parseCryptoLine=function(e){var t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},r.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+(typeof e.keyParams=="object"?r.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+`\r
17
+ `},r.parseCryptoKeyParams=function(e){if(e.indexOf("inline:")!==0)return null;var t=e.substr(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},r.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},r.getCryptoParameters=function(e,t){return r.matchPrefix(e+t,"a=crypto:").map(r.parseCryptoLine)},r.getIceParameters=function(e,t){var i=r.matchPrefix(e+t,"a=ice-ufrag:")[0],n=r.matchPrefix(e+t,"a=ice-pwd:")[0];return i&&n?{usernameFragment:i.substr(12),password:n.substr(10)}:null},r.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+`\r
18
+ a=ice-pwd:`+e.password+`\r
19
+ `},r.parseRtpParameters=function(e){for(var t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=r.splitLines(e)[0].split(" "),n=3;n<i.length;n++){var a=i[n],c=r.matchPrefix(e,"a=rtpmap:"+a+" ")[0];if(c){var o=r.parseRtpMap(c),l=r.matchPrefix(e,"a=fmtp:"+a+" ");switch(o.parameters=l.length?r.parseFmtp(l[0]):{},o.rtcpFeedback=r.matchPrefix(e,"a=rtcp-fb:"+a+" ").map(r.parseRtcpFb),t.codecs.push(o),o.name.toUpperCase()){case"RED":case"ULPFEC":t.fecMechanisms.push(o.name.toUpperCase())}}}return r.matchPrefix(e,"a=extmap:").forEach(function(d){t.headerExtensions.push(r.parseExtmap(d))}),t},r.writeRtpDescription=function(e,t){var i="";i+="m="+e+" ",i+=t.codecs.length>0?"9":"0",i+=" UDP/TLS/RTP/SAVPF ",i+=t.codecs.map(function(a){return a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType}).join(" ")+`\r
20
+ `,i+=`c=IN IP4 0.0.0.0\r
21
+ `,i+=`a=rtcp:9 IN IP4 0.0.0.0\r
22
+ `,t.codecs.forEach(function(a){i+=r.writeRtpMap(a),i+=r.writeFmtp(a),i+=r.writeRtcpFb(a)});var n=0;return t.codecs.forEach(function(a){a.maxptime>n&&(n=a.maxptime)}),n>0&&(i+="a=maxptime:"+n+`\r
23
+ `),i+=`a=rtcp-mux\r
24
+ `,t.headerExtensions&&t.headerExtensions.forEach(function(a){i+=r.writeExtmap(a)}),i},r.parseRtpEncodingParameters=function(e){var t,i=[],n=r.parseRtpParameters(e),a=n.fecMechanisms.indexOf("RED")!==-1,c=n.fecMechanisms.indexOf("ULPFEC")!==-1,o=r.matchPrefix(e,"a=ssrc:").map(function(u){return r.parseSsrcMedia(u)}).filter(function(u){return u.attribute==="cname"}),l=o.length>0&&o[0].ssrc,d=r.matchPrefix(e,"a=ssrc-group:FID").map(function(u){return u.substr(17).split(" ").map(function(p){return parseInt(p,10)})});d.length>0&&d[0].length>1&&d[0][0]===l&&(t=d[0][1]),n.codecs.forEach(function(u){if(u.name.toUpperCase()==="RTX"&&u.parameters.apt){var p={ssrc:l,codecPayloadType:parseInt(u.parameters.apt,10)};l&&t&&(p.rtx={ssrc:t}),i.push(p),a&&((p=JSON.parse(JSON.stringify(p))).fec={ssrc:l,mechanism:c?"red+ulpfec":"red"},i.push(p))}}),i.length===0&&l&&i.push({ssrc:l});var h=r.matchPrefix(e,"b=");return h.length&&(h=h[0].indexOf("b=TIAS:")===0?parseInt(h[0].substr(7),10):h[0].indexOf("b=AS:")===0?1e3*parseInt(h[0].substr(5),10)*.95-16e3:void 0,i.forEach(function(u){u.maxBitrate=h})),i},r.parseRtcpParameters=function(e){var t={},i=r.matchPrefix(e,"a=ssrc:").map(function(c){return r.parseSsrcMedia(c)}).filter(function(c){return c.attribute==="cname"})[0];i&&(t.cname=i.value,t.ssrc=i.ssrc);var n=r.matchPrefix(e,"a=rtcp-rsize");t.reducedSize=n.length>0,t.compound=n.length===0;var a=r.matchPrefix(e,"a=rtcp-mux");return t.mux=a.length>0,t},r.parseMsid=function(e){var t,i=r.matchPrefix(e,"a=msid:");if(i.length===1)return{stream:(t=i[0].substr(7).split(" "))[0],track:t[1]};var n=r.matchPrefix(e,"a=ssrc:").map(function(a){return r.parseSsrcMedia(a)}).filter(function(a){return a.attribute==="msid"});return n.length>0?{stream:(t=n[0].value.split(" "))[0],track:t[1]}:void 0},r.parseSctpDescription=function(e){var t,i=r.parseMLine(e),n=r.matchPrefix(e,"a=max-message-size:");n.length>0&&(t=parseInt(n[0].substr(19),10)),isNaN(t)&&(t=65536);var a=r.matchPrefix(e,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substr(12),10),protocol:i.fmt,maxMessageSize:t};if(r.matchPrefix(e,"a=sctpmap:").length>0){var c=r.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(c[0],10),protocol:c[1],maxMessageSize:t}}},r.writeSctpDescription=function(e,t){var i=[];return i=e.protocol!=="DTLS/SCTP"?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+`\r
25
+ `,`c=IN IP4 0.0.0.0\r
26
+ `,"a=sctp-port:"+t.port+`\r
27
+ `]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+`\r
28
+ `,`c=IN IP4 0.0.0.0\r
29
+ `,"a=sctpmap:"+t.port+" "+t.protocol+` 65535\r
30
+ `],t.maxMessageSize!==void 0&&i.push("a=max-message-size:"+t.maxMessageSize+`\r
31
+ `),i.join("")},r.generateSessionId=function(){return Math.random().toString().substr(2,21)},r.writeSessionBoilerplate=function(e,t,i){var n=t!==void 0?t:2;return`v=0\r
32
+ o=`+(i||"thisisadapterortc")+" "+(e||r.generateSessionId())+" "+n+` IN IP4 127.0.0.1\r
33
+ s=-\r
34
+ t=0 0\r
35
+ `},r.writeMediaSection=function(e,t,i,n){var a=r.writeRtpDescription(e.kind,t);if(a+=r.writeIceParameters(e.iceGatherer.getLocalParameters()),a+=r.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),i==="offer"?"actpass":"active"),a+="a=mid:"+e.mid+`\r
36
+ `,e.direction?a+="a="+e.direction+`\r
37
+ `:e.rtpSender&&e.rtpReceiver?a+=`a=sendrecv\r
38
+ `:e.rtpSender?a+=`a=sendonly\r
39
+ `:e.rtpReceiver?a+=`a=recvonly\r
40
+ `:a+=`a=inactive\r
41
+ `,e.rtpSender){var c="msid:"+n.id+" "+e.rtpSender.track.id+`\r
42
+ `;a+="a="+c,a+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+c,e.sendEncodingParameters[0].rtx&&(a+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+c,a+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+`\r
43
+ `)}return a+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+r.localCName+`\r
44
+ `,e.rtpSender&&e.sendEncodingParameters[0].rtx&&(a+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+r.localCName+`\r
45
+ `),a},r.getDirection=function(e,t){for(var i=r.splitLines(e),n=0;n<i.length;n++)switch(i[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[n].substr(2)}return t?r.getDirection(t):"sendrecv"},r.getKind=function(e){return r.splitLines(e)[0].split(" ")[0].substr(2)},r.isRejected=function(e){return e.split(" ",2)[1]==="0"},r.parseMLine=function(e){var t=r.splitLines(e)[0].substr(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}},r.parseOLine=function(e){var t=r.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:t[0],sessionId:t[1],sessionVersion:parseInt(t[2],10),netType:t[3],addressType:t[4],address:t[5]}},r.isValidSDP=function(e){if(typeof e!="string"||e.length===0)return!1;for(var t=r.splitLines(e),i=0;i<t.length;i++)if(t[i].length<2||t[i].charAt(1)!=="=")return!1;return!0},s.exports=r})(Do);var oe=Do.exports;function ko(s,r,e,t,i){var n=oe.writeRtpDescription(s.kind,r);if(n+=oe.writeIceParameters(s.iceGatherer.getLocalParameters()),n+=oe.writeDtlsParameters(s.dtlsTransport.getLocalParameters(),e==="offer"?"actpass":i||"active"),n+="a=mid:"+s.mid+`\r
46
+ `,s.rtpSender&&s.rtpReceiver?n+=`a=sendrecv\r
47
+ `:s.rtpSender?n+=`a=sendonly\r
48
+ `:s.rtpReceiver?n+=`a=recvonly\r
49
+ `:n+=`a=inactive\r
50
+ `,s.rtpSender){var a=s.rtpSender._initialTrackId||s.rtpSender.track.id;s.rtpSender._initialTrackId=a;var c="msid:"+(t?t.id:"-")+" "+a+`\r
51
+ `;n+="a="+c,n+="a=ssrc:"+s.sendEncodingParameters[0].ssrc+" "+c,s.sendEncodingParameters[0].rtx&&(n+="a=ssrc:"+s.sendEncodingParameters[0].rtx.ssrc+" "+c,n+="a=ssrc-group:FID "+s.sendEncodingParameters[0].ssrc+" "+s.sendEncodingParameters[0].rtx.ssrc+`\r
52
+ `)}return n+="a=ssrc:"+s.sendEncodingParameters[0].ssrc+" cname:"+oe.localCName+`\r
53
+ `,s.rtpSender&&s.sendEncodingParameters[0].rtx&&(n+="a=ssrc:"+s.sendEncodingParameters[0].rtx.ssrc+" cname:"+oe.localCName+`\r
54
+ `),n}function Fi(s,r){var e={codecs:[],headerExtensions:[],fecMechanisms:[]},t=function(n,a){n=parseInt(n,10);for(var c=0;c<a.length;c++)if(a[c].payloadType===n||a[c].preferredPayloadType===n)return a[c]},i=function(n,a,c,o){var l=t(n.parameters.apt,c),d=t(a.parameters.apt,o);return l&&d&&l.name.toLowerCase()===d.name.toLowerCase()};return s.codecs.forEach(function(n){for(var a=0;a<r.codecs.length;a++){var c=r.codecs[a];if(n.name.toLowerCase()===c.name.toLowerCase()&&n.clockRate===c.clockRate){if(n.name.toLowerCase()==="rtx"&&n.parameters&&c.parameters.apt&&!i(n,c,s.codecs,r.codecs))continue;(c=JSON.parse(JSON.stringify(c))).numChannels=Math.min(n.numChannels,c.numChannels),e.codecs.push(c),c.rtcpFeedback=c.rtcpFeedback.filter(function(o){for(var l=0;l<n.rtcpFeedback.length;l++)if(n.rtcpFeedback[l].type===o.type&&n.rtcpFeedback[l].parameter===o.parameter)return!0;return!1});break}}}),s.headerExtensions.forEach(function(n){for(var a=0;a<r.headerExtensions.length;a++){var c=r.headerExtensions[a];if(n.uri===c.uri){e.headerExtensions.push(c);break}}}),e}function Mo(s,r,e){return{offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[r][s].indexOf(e)!==-1}function Os(s,r){var e=s.getRemoteCandidates().find(function(t){return r.foundation===t.foundation&&r.ip===t.ip&&r.port===t.port&&r.priority===t.priority&&r.protocol===t.protocol&&r.type===t.type});return e||s.addRemoteCandidate(r),!e}function ft(s,r){var e=new Error(r);return e.name=s,e.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[s],e}var jh=function(s,r){function e(a,c){c.addTrack(a),c.dispatchEvent(new s.MediaStreamTrackEvent("addtrack",{track:a}))}function t(a,c,o,l){var d=new Event("track");d.track=c,d.receiver=o,d.transceiver={receiver:o},d.streams=l,s.setTimeout(function(){a._dispatchEvent("track",d)})}var i=function(a){var c=this,o=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(d){c[d]=o[d].bind(o)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",a=JSON.parse(JSON.stringify(a||{})),this.usingBundle=a.bundlePolicy==="max-bundle",a.rtcpMuxPolicy==="negotiate")throw ft("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(a.rtcpMuxPolicy||(a.rtcpMuxPolicy="require"),a.iceTransportPolicy){case"all":case"relay":break;default:a.iceTransportPolicy="all"}switch(a.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:a.bundlePolicy="balanced"}if(a.iceServers=function(d,h){var u=!1;return(d=JSON.parse(JSON.stringify(d))).filter(function(p){if(p&&(p.urls||p.url)){var f=p.urls||p.url;p.url&&!p.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var m=typeof f=="string";return m&&(f=[f]),f=f.filter(function(g){return g.indexOf("turn:")!==0||g.indexOf("transport=udp")===-1||g.indexOf("turn:[")!==-1||u?g.indexOf("stun:")===0&&h>=14393&&g.indexOf("?transport=udp")===-1:(u=!0,!0)}),delete p.url,p.urls=m?f[0]:f,!!f.length}})}(a.iceServers||[],r),this._iceGatherers=[],a.iceCandidatePoolSize)for(var l=a.iceCandidatePoolSize;l>0;l--)this._iceGatherers.push(new s.RTCIceGatherer({iceServers:a.iceServers,gatherPolicy:a.iceTransportPolicy}));else a.iceCandidatePoolSize=0;this._config=a,this.transceivers=[],this._sdpSessionId=oe.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(i.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(i.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),i.prototype.onicecandidate=null,i.prototype.onaddstream=null,i.prototype.ontrack=null,i.prototype.onremovestream=null,i.prototype.onsignalingstatechange=null,i.prototype.oniceconnectionstatechange=null,i.prototype.onconnectionstatechange=null,i.prototype.onicegatheringstatechange=null,i.prototype.onnegotiationneeded=null,i.prototype.ondatachannel=null,i.prototype._dispatchEvent=function(a,c){this._isClosed||(this.dispatchEvent(c),typeof this["on"+a]=="function"&&this["on"+a](c))},i.prototype._emitGatheringStateChange=function(){var a=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",a)},i.prototype.getConfiguration=function(){return this._config},i.prototype.getLocalStreams=function(){return this.localStreams},i.prototype.getRemoteStreams=function(){return this.remoteStreams},i.prototype._createTransceiver=function(a,c){var o=this.transceivers.length>0,l={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:a,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&o)l.iceTransport=this.transceivers[0].iceTransport,l.dtlsTransport=this.transceivers[0].dtlsTransport;else{var d=this._createIceAndDtlsTransports();l.iceTransport=d.iceTransport,l.dtlsTransport=d.dtlsTransport}return c||this.transceivers.push(l),l},i.prototype.addTrack=function(a,c){if(this._isClosed)throw ft("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var o,l=this.transceivers.find(function(h){return h.track===a});if(l)throw ft("InvalidAccessError","Track already exists.");for(var d=0;d<this.transceivers.length;d++)this.transceivers[d].track||this.transceivers[d].kind!==a.kind||(o=this.transceivers[d]);return o||(o=this._createTransceiver(a.kind)),this._maybeFireNegotiationNeeded(),this.localStreams.indexOf(c)===-1&&this.localStreams.push(c),o.track=a,o.stream=c,o.rtpSender=new s.RTCRtpSender(a,o.dtlsTransport),o.rtpSender},i.prototype.addStream=function(a){var c=this;if(r>=15025)a.getTracks().forEach(function(l){c.addTrack(l,a)});else{var o=a.clone();a.getTracks().forEach(function(l,d){var h=o.getTracks()[d];l.addEventListener("enabled",function(u){h.enabled=u.enabled})}),o.getTracks().forEach(function(l){c.addTrack(l,o)})}},i.prototype.removeTrack=function(a){if(this._isClosed)throw ft("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(a instanceof s.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var c=this.transceivers.find(function(l){return l.rtpSender===a});if(!c)throw ft("InvalidAccessError","Sender was not created by this connection.");var o=c.stream;c.rtpSender.stop(),c.rtpSender=null,c.track=null,c.stream=null,this.transceivers.map(function(l){return l.stream}).indexOf(o)===-1&&this.localStreams.indexOf(o)>-1&&this.localStreams.splice(this.localStreams.indexOf(o),1),this._maybeFireNegotiationNeeded()},i.prototype.removeStream=function(a){var c=this;a.getTracks().forEach(function(o){var l=c.getSenders().find(function(d){return d.track===o});l&&c.removeTrack(l)})},i.prototype.getSenders=function(){return this.transceivers.filter(function(a){return!!a.rtpSender}).map(function(a){return a.rtpSender})},i.prototype.getReceivers=function(){return this.transceivers.filter(function(a){return!!a.rtpReceiver}).map(function(a){return a.rtpReceiver})},i.prototype._createIceGatherer=function(a,c){var o=this;if(c&&a>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var l=new s.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(l,"state",{value:"new",writable:!0}),this.transceivers[a].bufferedCandidateEvents=[],this.transceivers[a].bufferCandidates=function(d){var h=!d.candidate||Object.keys(d.candidate).length===0;l.state=h?"completed":"gathering",o.transceivers[a].bufferedCandidateEvents!==null&&o.transceivers[a].bufferedCandidateEvents.push(d)},l.addEventListener("localcandidate",this.transceivers[a].bufferCandidates),l},i.prototype._gather=function(a,c){var o=this,l=this.transceivers[c].iceGatherer;if(!l.onlocalcandidate){var d=this.transceivers[c].bufferedCandidateEvents;this.transceivers[c].bufferedCandidateEvents=null,l.removeEventListener("localcandidate",this.transceivers[c].bufferCandidates),l.onlocalcandidate=function(h){if(!(o.usingBundle&&c>0)){var u=new Event("icecandidate");u.candidate={sdpMid:a,sdpMLineIndex:c};var p=h.candidate,f=!p||Object.keys(p).length===0;if(f)l.state!=="new"&&l.state!=="gathering"||(l.state="completed");else{l.state==="new"&&(l.state="gathering"),p.component=1,p.ufrag=l.getLocalParameters().usernameFragment;var m=oe.writeCandidate(p);u.candidate=Object.assign(u.candidate,oe.parseCandidate(m)),u.candidate.candidate=m,u.candidate.toJSON=function(){return{candidate:u.candidate.candidate,sdpMid:u.candidate.sdpMid,sdpMLineIndex:u.candidate.sdpMLineIndex,usernameFragment:u.candidate.usernameFragment}}}var g=oe.getMediaSections(o._localDescription.sdp);g[u.candidate.sdpMLineIndex]+=f?`a=end-of-candidates\r
55
+ `:"a="+u.candidate.candidate+`\r
56
+ `,o._localDescription.sdp=oe.getDescription(o._localDescription.sdp)+g.join("");var S=o.transceivers.every(function(v){return v.iceGatherer&&v.iceGatherer.state==="completed"});o.iceGatheringState!=="gathering"&&(o.iceGatheringState="gathering",o._emitGatheringStateChange()),f||o._dispatchEvent("icecandidate",u),S&&(o._dispatchEvent("icecandidate",new Event("icecandidate")),o.iceGatheringState="complete",o._emitGatheringStateChange())}},s.setTimeout(function(){d.forEach(function(h){l.onlocalcandidate(h)})},0)}},i.prototype._createIceAndDtlsTransports=function(){var a=this,c=new s.RTCIceTransport(null);c.onicestatechange=function(){a._updateIceConnectionState(),a._updateConnectionState()};var o=new s.RTCDtlsTransport(c);return o.ondtlsstatechange=function(){a._updateConnectionState()},o.onerror=function(){Object.defineProperty(o,"state",{value:"failed",writable:!0}),a._updateConnectionState()},{iceTransport:c,dtlsTransport:o}},i.prototype._disposeIceAndDtlsTransports=function(a){var c=this.transceivers[a].iceGatherer;c&&(delete c.onlocalcandidate,delete this.transceivers[a].iceGatherer);var o=this.transceivers[a].iceTransport;o&&(delete o.onicestatechange,delete this.transceivers[a].iceTransport);var l=this.transceivers[a].dtlsTransport;l&&(delete l.ondtlsstatechange,delete l.onerror,delete this.transceivers[a].dtlsTransport)},i.prototype._transceive=function(a,c,o){var l=Fi(a.localCapabilities,a.remoteCapabilities);c&&a.rtpSender&&(l.encodings=a.sendEncodingParameters,l.rtcp={cname:oe.localCName,compound:a.rtcpParameters.compound},a.recvEncodingParameters.length&&(l.rtcp.ssrc=a.recvEncodingParameters[0].ssrc),a.rtpSender.send(l)),o&&a.rtpReceiver&&l.codecs.length>0&&(a.kind==="video"&&a.recvEncodingParameters&&r<15019&&a.recvEncodingParameters.forEach(function(d){delete d.rtx}),a.recvEncodingParameters.length?l.encodings=a.recvEncodingParameters:l.encodings=[{}],l.rtcp={compound:a.rtcpParameters.compound},a.rtcpParameters.cname&&(l.rtcp.cname=a.rtcpParameters.cname),a.sendEncodingParameters.length&&(l.rtcp.ssrc=a.sendEncodingParameters[0].ssrc),a.rtpReceiver.receive(l))},i.prototype.setLocalDescription=function(a){var c,o,l=this;if(["offer","answer"].indexOf(a.type)===-1)return Promise.reject(ft("TypeError",'Unsupported type "'+a.type+'"'));if(!Mo("setLocalDescription",a.type,l.signalingState)||l._isClosed)return Promise.reject(ft("InvalidStateError","Can not set local "+a.type+" in state "+l.signalingState));if(a.type==="offer")c=oe.splitSections(a.sdp),o=c.shift(),c.forEach(function(h,u){var p=oe.parseRtpParameters(h);l.transceivers[u].localCapabilities=p}),l.transceivers.forEach(function(h,u){l._gather(h.mid,u)});else if(a.type==="answer"){c=oe.splitSections(l._remoteDescription.sdp),o=c.shift();var d=oe.matchPrefix(o,"a=ice-lite").length>0;c.forEach(function(h,u){var p=l.transceivers[u],f=p.iceGatherer,m=p.iceTransport,g=p.dtlsTransport,S=p.localCapabilities,v=p.remoteCapabilities;if(!(oe.isRejected(h)&&oe.matchPrefix(h,"a=bundle-only").length===0)&&!p.rejected){var E=oe.getIceParameters(h,o),T=oe.getDtlsParameters(h,o);d&&(T.role="server"),l.usingBundle&&u!==0||(l._gather(p.mid,u),m.state==="new"&&m.start(f,E,d?"controlling":"controlled"),g.state==="new"&&g.start(T));var R=Fi(S,v);l._transceive(p,R.codecs.length>0,!1)}})}return l._localDescription={type:a.type,sdp:a.sdp},a.type==="offer"?l._updateSignalingState("have-local-offer"):l._updateSignalingState("stable"),Promise.resolve()},i.prototype.setRemoteDescription=function(a){var c=this;if(["offer","answer"].indexOf(a.type)===-1)return Promise.reject(ft("TypeError",'Unsupported type "'+a.type+'"'));if(!Mo("setRemoteDescription",a.type,c.signalingState)||c._isClosed)return Promise.reject(ft("InvalidStateError","Can not set remote "+a.type+" in state "+c.signalingState));var o={};c.remoteStreams.forEach(function(m){o[m.id]=m});var l=[],d=oe.splitSections(a.sdp),h=d.shift(),u=oe.matchPrefix(h,"a=ice-lite").length>0,p=oe.matchPrefix(h,"a=group:BUNDLE ").length>0;c.usingBundle=p;var f=oe.matchPrefix(h,"a=ice-options:")[0];return c.canTrickleIceCandidates=!!f&&f.substr(14).split(" ").indexOf("trickle")>=0,d.forEach(function(m,g){var S=oe.splitLines(m),v=oe.getKind(m),E=oe.isRejected(m)&&oe.matchPrefix(m,"a=bundle-only").length===0,T=S[0].substr(2).split(" ")[2],R=oe.getDirection(m,h),y=oe.parseMsid(m),C=oe.getMid(m)||oe.generateIdentifier();if(E||v==="application"&&(T==="DTLS/SCTP"||T==="UDP/DTLS/SCTP"))c.transceivers[g]={mid:C,kind:v,protocol:T,rejected:!0};else{var w,A,P,M,I,j,K,B,F;!E&&c.transceivers[g]&&c.transceivers[g].rejected&&(c.transceivers[g]=c._createTransceiver(v,!0));var X,$,se=oe.parseRtpParameters(m);E||(X=oe.getIceParameters(m,h),($=oe.getDtlsParameters(m,h)).role="client"),K=oe.parseRtpEncodingParameters(m);var N=oe.parseRtcpParameters(m),V=oe.matchPrefix(m,"a=end-of-candidates",h).length>0,x=oe.matchPrefix(m,"a=candidate:").map(function(ue){return oe.parseCandidate(ue)}).filter(function(ue){return ue.component===1});if((a.type==="offer"||a.type==="answer")&&!E&&p&&g>0&&c.transceivers[g]&&(c._disposeIceAndDtlsTransports(g),c.transceivers[g].iceGatherer=c.transceivers[0].iceGatherer,c.transceivers[g].iceTransport=c.transceivers[0].iceTransport,c.transceivers[g].dtlsTransport=c.transceivers[0].dtlsTransport,c.transceivers[g].rtpSender&&c.transceivers[g].rtpSender.setTransport(c.transceivers[0].dtlsTransport),c.transceivers[g].rtpReceiver&&c.transceivers[g].rtpReceiver.setTransport(c.transceivers[0].dtlsTransport)),a.type!=="offer"||E)a.type==="answer"&&!E&&(A=(w=c.transceivers[g]).iceGatherer,P=w.iceTransport,M=w.dtlsTransport,I=w.rtpReceiver,j=w.sendEncodingParameters,B=w.localCapabilities,c.transceivers[g].recvEncodingParameters=K,c.transceivers[g].remoteCapabilities=se,c.transceivers[g].rtcpParameters=N,x.length&&P.state==="new"&&(!u&&!V||p&&g!==0?x.forEach(function(ue){Os(w.iceTransport,ue)}):P.setRemoteCandidates(x)),p&&g!==0||(P.state==="new"&&P.start(A,X,"controlling"),M.state==="new"&&M.start($)),!Fi(w.localCapabilities,w.remoteCapabilities).codecs.filter(function(ue){return ue.name.toLowerCase()==="rtx"}).length&&w.sendEncodingParameters[0].rtx&&delete w.sendEncodingParameters[0].rtx,c._transceive(w,R==="sendrecv"||R==="recvonly",R==="sendrecv"||R==="sendonly"),!I||R!=="sendrecv"&&R!=="sendonly"?delete w.rtpReceiver:(F=I.track,y?(o[y.stream]||(o[y.stream]=new s.MediaStream),e(F,o[y.stream]),l.push([F,I,o[y.stream]])):(o.default||(o.default=new s.MediaStream),e(F,o.default),l.push([F,I,o.default]))));else{(w=c.transceivers[g]||c._createTransceiver(v)).mid=C,w.iceGatherer||(w.iceGatherer=c._createIceGatherer(g,p)),x.length&&w.iceTransport.state==="new"&&(!V||p&&g!==0?x.forEach(function(ue){Os(w.iceTransport,ue)}):w.iceTransport.setRemoteCandidates(x)),B=s.RTCRtpReceiver.getCapabilities(v),r<15019&&(B.codecs=B.codecs.filter(function(ue){return ue.name!=="rtx"})),j=w.sendEncodingParameters||[{ssrc:1001*(2*g+2)}];var U,ce=!1;R==="sendrecv"||R==="sendonly"?(ce=!w.rtpReceiver,I=w.rtpReceiver||new s.RTCRtpReceiver(w.dtlsTransport,v),ce&&(F=I.track,y&&y.stream==="-"||(y?(o[y.stream]||(o[y.stream]=new s.MediaStream,Object.defineProperty(o[y.stream],"id",{get:function(){return y.stream}})),Object.defineProperty(F,"id",{get:function(){return y.track}}),U=o[y.stream]):(o.default||(o.default=new s.MediaStream),U=o.default)),U&&(e(F,U),w.associatedRemoteMediaStreams.push(U)),l.push([F,I,U]))):w.rtpReceiver&&w.rtpReceiver.track&&(w.associatedRemoteMediaStreams.forEach(function(ue){var te=ue.getTracks().find(function(Re){return Re.id===w.rtpReceiver.track.id});te&&function(Re,He){He.removeTrack(Re),He.dispatchEvent(new s.MediaStreamTrackEvent("removetrack",{track:Re}))}(te,ue)}),w.associatedRemoteMediaStreams=[]),w.localCapabilities=B,w.remoteCapabilities=se,w.rtpReceiver=I,w.rtcpParameters=N,w.sendEncodingParameters=j,w.recvEncodingParameters=K,c._transceive(c.transceivers[g],!1,ce)}}}),c._dtlsRole===void 0&&(c._dtlsRole=a.type==="offer"?"active":"passive"),c._remoteDescription={type:a.type,sdp:a.sdp},a.type==="offer"?c._updateSignalingState("have-remote-offer"):c._updateSignalingState("stable"),Object.keys(o).forEach(function(m){var g=o[m];if(g.getTracks().length){if(c.remoteStreams.indexOf(g)===-1){c.remoteStreams.push(g);var S=new Event("addstream");S.stream=g,s.setTimeout(function(){c._dispatchEvent("addstream",S)})}l.forEach(function(v){var E=v[0],T=v[1];g.id===v[2].id&&t(c,E,T,[g])})}}),l.forEach(function(m){m[2]||t(c,m[0],m[1],[])}),s.setTimeout(function(){c&&c.transceivers&&c.transceivers.forEach(function(m){m.iceTransport&&m.iceTransport.state==="new"&&m.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),m.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},i.prototype.close=function(){this.transceivers.forEach(function(a){a.iceTransport&&a.iceTransport.stop(),a.dtlsTransport&&a.dtlsTransport.stop(),a.rtpSender&&a.rtpSender.stop(),a.rtpReceiver&&a.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},i.prototype._updateSignalingState=function(a){this.signalingState=a;var c=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",c)},i.prototype._maybeFireNegotiationNeeded=function(){var a=this;this.signalingState==="stable"&&this.needNegotiation!==!0&&(this.needNegotiation=!0,s.setTimeout(function(){if(a.needNegotiation){a.needNegotiation=!1;var c=new Event("negotiationneeded");a._dispatchEvent("negotiationneeded",c)}},0))},i.prototype._updateIceConnectionState=function(){var a,c={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(l){l.iceTransport&&!l.rejected&&c[l.iceTransport.state]++}),a="new",c.failed>0?a="failed":c.checking>0?a="checking":c.disconnected>0?a="disconnected":c.new>0?a="new":c.connected>0?a="connected":c.completed>0&&(a="completed"),a!==this.iceConnectionState){this.iceConnectionState=a;var o=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",o)}},i.prototype._updateConnectionState=function(){var a,c={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(l){l.iceTransport&&l.dtlsTransport&&!l.rejected&&(c[l.iceTransport.state]++,c[l.dtlsTransport.state]++)}),c.connected+=c.completed,a="new",c.failed>0?a="failed":c.connecting>0?a="connecting":c.disconnected>0?a="disconnected":c.new>0?a="new":c.connected>0&&(a="connected"),a!==this.connectionState){this.connectionState=a;var o=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",o)}},i.prototype.createOffer=function(){var a=this;if(a._isClosed)return Promise.reject(ft("InvalidStateError","Can not call createOffer after close"));var c=a.transceivers.filter(function(u){return u.kind==="audio"}).length,o=a.transceivers.filter(function(u){return u.kind==="video"}).length,l=arguments[0];if(l){if(l.mandatory||l.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");l.offerToReceiveAudio!==void 0&&(c=l.offerToReceiveAudio===!0?1:l.offerToReceiveAudio===!1?0:l.offerToReceiveAudio),l.offerToReceiveVideo!==void 0&&(o=l.offerToReceiveVideo===!0?1:l.offerToReceiveVideo===!1?0:l.offerToReceiveVideo)}for(a.transceivers.forEach(function(u){u.kind==="audio"?--c<0&&(u.wantReceive=!1):u.kind==="video"&&--o<0&&(u.wantReceive=!1)});c>0||o>0;)c>0&&(a._createTransceiver("audio"),c--),o>0&&(a._createTransceiver("video"),o--);var d=oe.writeSessionBoilerplate(a._sdpSessionId,a._sdpSessionVersion++);a.transceivers.forEach(function(u,p){var f=u.track,m=u.kind,g=u.mid||oe.generateIdentifier();u.mid=g,u.iceGatherer||(u.iceGatherer=a._createIceGatherer(p,a.usingBundle));var S=s.RTCRtpSender.getCapabilities(m);r<15019&&(S.codecs=S.codecs.filter(function(E){return E.name!=="rtx"})),S.codecs.forEach(function(E){E.name==="H264"&&E.parameters["level-asymmetry-allowed"]===void 0&&(E.parameters["level-asymmetry-allowed"]="1"),u.remoteCapabilities&&u.remoteCapabilities.codecs&&u.remoteCapabilities.codecs.forEach(function(T){E.name.toLowerCase()===T.name.toLowerCase()&&E.clockRate===T.clockRate&&(E.preferredPayloadType=T.payloadType)})}),S.headerExtensions.forEach(function(E){(u.remoteCapabilities&&u.remoteCapabilities.headerExtensions||[]).forEach(function(T){E.uri===T.uri&&(E.id=T.id)})});var v=u.sendEncodingParameters||[{ssrc:1001*(2*p+1)}];f&&r>=15019&&m==="video"&&!v[0].rtx&&(v[0].rtx={ssrc:v[0].ssrc+1}),u.wantReceive&&(u.rtpReceiver=new s.RTCRtpReceiver(u.dtlsTransport,m)),u.localCapabilities=S,u.sendEncodingParameters=v}),a._config.bundlePolicy!=="max-compat"&&(d+="a=group:BUNDLE "+a.transceivers.map(function(u){return u.mid}).join(" ")+`\r
57
+ `),d+=`a=ice-options:trickle\r
58
+ `,a.transceivers.forEach(function(u,p){d+=ko(u,u.localCapabilities,"offer",u.stream,a._dtlsRole),d+=`a=rtcp-rsize\r
59
+ `,!u.iceGatherer||a.iceGatheringState==="new"||p!==0&&a.usingBundle||(u.iceGatherer.getLocalCandidates().forEach(function(f){f.component=1,d+="a="+oe.writeCandidate(f)+`\r
60
+ `}),u.iceGatherer.state==="completed"&&(d+=`a=end-of-candidates\r
61
+ `))});var h=new s.RTCSessionDescription({type:"offer",sdp:d});return Promise.resolve(h)},i.prototype.createAnswer=function(){var a=this;if(a._isClosed)return Promise.reject(ft("InvalidStateError","Can not call createAnswer after close"));if(a.signalingState!=="have-remote-offer"&&a.signalingState!=="have-local-pranswer")return Promise.reject(ft("InvalidStateError","Can not call createAnswer in signalingState "+a.signalingState));var c=oe.writeSessionBoilerplate(a._sdpSessionId,a._sdpSessionVersion++);a.usingBundle&&(c+="a=group:BUNDLE "+a.transceivers.map(function(d){return d.mid}).join(" ")+`\r
62
+ `),c+=`a=ice-options:trickle\r
63
+ `;var o=oe.getMediaSections(a._remoteDescription.sdp).length;a.transceivers.forEach(function(d,h){if(!(h+1>o)){if(d.rejected)return d.kind==="application"?d.protocol==="DTLS/SCTP"?c+=`m=application 0 DTLS/SCTP 5000\r
64
+ `:c+="m=application 0 "+d.protocol+` webrtc-datachannel\r
65
+ `:d.kind==="audio"?c+=`m=audio 0 UDP/TLS/RTP/SAVPF 0\r
66
+ a=rtpmap:0 PCMU/8000\r
67
+ `:d.kind==="video"&&(c+=`m=video 0 UDP/TLS/RTP/SAVPF 120\r
68
+ a=rtpmap:120 VP8/90000\r
69
+ `),void(c+=`c=IN IP4 0.0.0.0\r
70
+ a=inactive\r
71
+ a=mid:`+d.mid+`\r
72
+ `);var u;d.stream&&(d.kind==="audio"?u=d.stream.getAudioTracks()[0]:d.kind==="video"&&(u=d.stream.getVideoTracks()[0]),u&&r>=15019&&d.kind==="video"&&!d.sendEncodingParameters[0].rtx&&(d.sendEncodingParameters[0].rtx={ssrc:d.sendEncodingParameters[0].ssrc+1}));var p=Fi(d.localCapabilities,d.remoteCapabilities);!p.codecs.filter(function(f){return f.name.toLowerCase()==="rtx"}).length&&d.sendEncodingParameters[0].rtx&&delete d.sendEncodingParameters[0].rtx,c+=ko(d,p,"answer",d.stream,a._dtlsRole),d.rtcpParameters&&d.rtcpParameters.reducedSize&&(c+=`a=rtcp-rsize\r
73
+ `)}});var l=new s.RTCSessionDescription({type:"answer",sdp:c});return Promise.resolve(l)},i.prototype.addIceCandidate=function(a){var c,o=this;return a&&a.sdpMLineIndex===void 0&&!a.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(l,d){if(!o._remoteDescription)return d(ft("InvalidStateError","Can not add ICE candidate without a remote description"));if(a&&a.candidate!==""){var h=a.sdpMLineIndex;if(a.sdpMid){for(var u=0;u<o.transceivers.length;u++)if(o.transceivers[u].mid===a.sdpMid){h=u;break}}var p=o.transceivers[h];if(!p)return d(ft("OperationError","Can not add ICE candidate"));if(p.rejected)return l();var f=Object.keys(a.candidate).length>0?oe.parseCandidate(a.candidate):{};if(f.protocol==="tcp"&&(f.port===0||f.port===9)||f.component&&f.component!==1)return l();if((h===0||h>0&&p.iceTransport!==o.transceivers[0].iceTransport)&&!Os(p.iceTransport,f))return d(ft("OperationError","Can not add ICE candidate"));var m=a.candidate.trim();m.indexOf("a=")===0&&(m=m.substr(2)),(c=oe.getMediaSections(o._remoteDescription.sdp))[h]+="a="+(f.type?m:"end-of-candidates")+`\r
74
+ `,o._remoteDescription.sdp=oe.getDescription(o._remoteDescription.sdp)+c.join("")}else for(var g=0;g<o.transceivers.length&&(o.transceivers[g].rejected||(o.transceivers[g].iceTransport.addRemoteCandidate({}),(c=oe.getMediaSections(o._remoteDescription.sdp))[g]+=`a=end-of-candidates\r
75
+ `,o._remoteDescription.sdp=oe.getDescription(o._remoteDescription.sdp)+c.join(""),!o.usingBundle));g++);l()})},i.prototype.getStats=function(a){if(a&&a instanceof s.MediaStreamTrack){var c=null;if(this.transceivers.forEach(function(l){l.rtpSender&&l.rtpSender.track===a?c=l.rtpSender:l.rtpReceiver&&l.rtpReceiver.track===a&&(c=l.rtpReceiver)}),!c)throw ft("InvalidAccessError","Invalid selector.");return c.getStats()}var o=[];return this.transceivers.forEach(function(l){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(d){l[d]&&o.push(l[d].getStats())})}),Promise.all(o).then(function(l){var d=new Map;return l.forEach(function(h){h.forEach(function(u){d.set(u.id,u)})}),d})},["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach(function(a){var c=s[a];if(c&&c.prototype&&c.prototype.getStats){var o=c.prototype.getStats;c.prototype.getStats=function(){return o.apply(this).then(function(l){var d=new Map;return Object.keys(l).forEach(function(h){var u;l[h].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(u=l[h]).type]||u.type,d.set(h,l[h])}),d})}}});var n=["createOffer","createAnswer"];return n.forEach(function(a){var c=i.prototype[a];i.prototype[a]=function(){var o=arguments;return typeof o[0]=="function"||typeof o[1]=="function"?c.apply(this,[arguments[2]]).then(function(l){typeof o[0]=="function"&&o[0].apply(null,[l])},function(l){typeof o[1]=="function"&&o[1].apply(null,[l])}):c.apply(this,arguments)}}),(n=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach(function(a){var c=i.prototype[a];i.prototype[a]=function(){var o=arguments;return typeof o[1]=="function"||typeof o[2]=="function"?c.apply(this,arguments).then(function(){typeof o[1]=="function"&&o[1].apply(null)},function(l){typeof o[2]=="function"&&o[2].apply(null,[l])}):c.apply(this,arguments)}}),["getStats"].forEach(function(a){var c=i.prototype[a];i.prototype[a]=function(){var o=arguments;return typeof o[1]=="function"?c.apply(this,arguments).then(function(){typeof o[1]=="function"&&o[1].apply(null)}):c.apply(this,arguments)}}),i};const Gh=Cr(jh);function Oo(s){const r=s&&s.navigator,e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return e(t).catch(i=>Promise.reject(function(n){return{name:{PermissionDeniedError:"NotAllowedError"}[n.name]||n.name,message:n.message,constraint:n.constraint,toString(){return this.name}}}(i)))}}function No(s){"getDisplayMedia"in s.navigator&&s.navigator.mediaDevices&&(s.navigator.mediaDevices&&"getDisplayMedia"in s.navigator.mediaDevices||(s.navigator.mediaDevices.getDisplayMedia=s.navigator.getDisplayMedia.bind(s.navigator)))}function Ns(s,r){if(s.RTCIceGatherer&&(s.RTCIceCandidate||(s.RTCIceCandidate=function(t){return t}),s.RTCSessionDescription||(s.RTCSessionDescription=function(t){return t}),r.version<15025)){const t=Object.getOwnPropertyDescriptor(s.MediaStreamTrack.prototype,"enabled");Object.defineProperty(s.MediaStreamTrack.prototype,"enabled",{set(i){t.set.call(this,i);const n=new Event("enabled");n.enabled=i,this.dispatchEvent(n)}})}s.RTCRtpSender&&!("dtmf"in s.RTCRtpSender.prototype)&&Object.defineProperty(s.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=new s.RTCDtmfSender(this):this.track.kind==="video"&&(this._dtmf=null)),this._dtmf}}),s.RTCDtmfSender&&!s.RTCDTMFSender&&(s.RTCDTMFSender=s.RTCDtmfSender);const e=Gh(s,r.version);s.RTCPeerConnection=function(t){return t&&t.iceServers&&(t.iceServers=function(i){let n=!1;return(i=JSON.parse(JSON.stringify(i))).filter(a=>{if(a&&(a.urls||a.url)){let c=a.urls||a.url;a.url&&!a.urls&&Bi("RTCIceServer.url","RTCIceServer.urls");const o=typeof c=="string";return o&&(c=[c]),c=c.filter(l=>{if(l.indexOf("stun:")===0)return!1;const d=l.startsWith("turn")&&!l.startsWith("turn:[")&&l.includes("transport=udp");return d&&!n?(n=!0,!0):d&&!n}),delete a.url,a.urls=o?c[0]:c,!!c.length}})}(t.iceServers,r.version),Ds("ICE servers after filtering:",t.iceServers)),new e(t)},s.RTCPeerConnection.prototype=e.prototype}function Lo(s){s.RTCRtpSender&&!("replaceTrack"in s.RTCRtpSender.prototype)&&(s.RTCRtpSender.prototype.replaceTrack=s.RTCRtpSender.prototype.setTrack)}const xo=Object.freeze(Object.defineProperty({__proto__:null,shimGetDisplayMedia:No,shimGetUserMedia:Oo,shimPeerConnection:Ns,shimReplaceTrack:Lo},Symbol.toStringTag,{value:"Module"}));function Vo(s,r){const e=s&&s.navigator,t=s&&s.MediaStreamTrack;if(e.getUserMedia=function(i,n,a){Bi("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),e.mediaDevices.getUserMedia(i).then(n,a)},!(r.version>55&&"autoGainControl"in e.mediaDevices.getSupportedConstraints())){const i=function(a,c,o){c in a&&!(o in a)&&(a[o]=a[c],delete a[c])},n=e.mediaDevices.getUserMedia.bind(e.mediaDevices);if(e.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),i(a.audio,"autoGainControl","mozAutoGainControl"),i(a.audio,"noiseSuppression","mozNoiseSuppression")),n(a)},t&&t.prototype.getSettings){const a=t.prototype.getSettings;t.prototype.getSettings=function(){const c=a.apply(this,arguments);return i(c,"mozAutoGainControl","autoGainControl"),i(c,"mozNoiseSuppression","noiseSuppression"),c}}if(t&&t.prototype.applyConstraints){const a=t.prototype.applyConstraints;t.prototype.applyConstraints=function(c){return this.kind==="audio"&&typeof c=="object"&&(c=JSON.parse(JSON.stringify(c)),i(c,"autoGainControl","mozAutoGainControl"),i(c,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[c])}}}}function Uo(s){typeof s=="object"&&s.RTCTrackEvent&&"receiver"in s.RTCTrackEvent.prototype&&!("transceiver"in s.RTCTrackEvent.prototype)&&Object.defineProperty(s.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ls(s,r){if(typeof s!="object"||!s.RTCPeerConnection&&!s.mozRTCPeerConnection)return;!s.RTCPeerConnection&&s.mozRTCPeerConnection&&(s.RTCPeerConnection=s.mozRTCPeerConnection),r.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(i){const n=s.RTCPeerConnection.prototype[i],a={[i](){return arguments[0]=new(i==="addIceCandidate"?s.RTCIceCandidate:s.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};s.RTCPeerConnection.prototype[i]=a[i]});const e={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},t=s.RTCPeerConnection.prototype.getStats;s.RTCPeerConnection.prototype.getStats=function(){const[i,n,a]=arguments;return t.apply(this,[i||null]).then(c=>{if(r.version<53&&!n)try{c.forEach(o=>{o.type=e[o.type]||o.type})}catch(o){if(o.name!=="TypeError")throw o;c.forEach((l,d)=>{c.set(d,Object.assign({},l,{type:e[l.type]||l.type}))})}return c}).then(n,a)}}function Bo(s){if(typeof s!="object"||!s.RTCPeerConnection||!s.RTCRtpSender||s.RTCRtpSender&&"getStats"in s.RTCRtpSender.prototype)return;const r=s.RTCPeerConnection.prototype.getSenders;r&&(s.RTCPeerConnection.prototype.getSenders=function(){const t=r.apply(this,[]);return t.forEach(i=>i._pc=this),t});const e=s.RTCPeerConnection.prototype.addTrack;e&&(s.RTCPeerConnection.prototype.addTrack=function(){const t=e.apply(this,arguments);return t._pc=this,t}),s.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Fo(s){if(typeof s!="object"||!s.RTCPeerConnection||!s.RTCRtpSender||s.RTCRtpSender&&"getStats"in s.RTCRtpReceiver.prototype)return;const r=s.RTCPeerConnection.prototype.getReceivers;r&&(s.RTCPeerConnection.prototype.getReceivers=function(){const e=r.apply(this,[]);return e.forEach(t=>t._pc=this),e}),$r(s,"track",e=>(e.receiver._pc=e.srcElement,e)),s.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ho(s){s.RTCPeerConnection&&!("removeStream"in s.RTCPeerConnection.prototype)&&(s.RTCPeerConnection.prototype.removeStream=function(r){Bi("removeStream","removeTrack"),this.getSenders().forEach(e=>{e.track&&r.getTracks().includes(e.track)&&this.removeTrack(e)})})}function Wo(s){s.DataChannel&&!s.RTCDataChannel&&(s.RTCDataChannel=s.DataChannel)}function jo(s){if(typeof s!="object"||!s.RTCPeerConnection)return;const r=s.RTCPeerConnection.prototype.addTransceiver;r&&(s.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const e=arguments[1],t=e&&"sendEncodings"in e;t&&e.sendEncodings.forEach(n=>{if("rid"in n&&!/^[a-z0-9]{0,16}$/i.test(n.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in n&&!(parseFloat(n.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in n&&!(parseFloat(n.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const i=r.apply(this,arguments);if(t){const{sender:n}=i,a=n.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=e.sendEncodings,n.sendEncodings=e.sendEncodings,this.setParametersPromises.push(n.setParameters(a).then(()=>{delete n.sendEncodings}).catch(()=>{delete n.sendEncodings})))}return i})}function Go(s){if(typeof s!="object"||!s.RTCRtpSender)return;const r=s.RTCRtpSender.prototype.getParameters;r&&(s.RTCRtpSender.prototype.getParameters=function(){const e=r.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function zo(s){if(typeof s!="object"||!s.RTCPeerConnection)return;const r=s.RTCPeerConnection.prototype.createOffer;s.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>r.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):r.apply(this,arguments)}}function Ko(s){if(typeof s!="object"||!s.RTCPeerConnection)return;const r=s.RTCPeerConnection.prototype.createAnswer;s.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>r.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):r.apply(this,arguments)}}const Jo=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:jo,shimCreateAnswer:Ko,shimCreateOffer:zo,shimGetDisplayMedia:function(s,r){s.navigator.mediaDevices&&"getDisplayMedia"in s.navigator.mediaDevices||s.navigator.mediaDevices&&(s.navigator.mediaDevices.getDisplayMedia=function(e){if(!e||!e.video){const t=new DOMException("getDisplayMedia without video constraints is undefined");return t.name="NotFoundError",t.code=8,Promise.reject(t)}return e.video===!0?e.video={mediaSource:r}:e.video.mediaSource=r,s.navigator.mediaDevices.getUserMedia(e)})},shimGetParameters:Go,shimGetUserMedia:Vo,shimOnTrack:Uo,shimPeerConnection:Ls,shimRTCDataChannel:Wo,shimReceiverGetStats:Fo,shimRemoveStream:Ho,shimSenderGetStats:Bo},Symbol.toStringTag,{value:"Module"}));function $o(s){if(typeof s=="object"&&s.RTCPeerConnection){if("getLocalStreams"in s.RTCPeerConnection.prototype||(s.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in s.RTCPeerConnection.prototype)){const r=s.RTCPeerConnection.prototype.addTrack;s.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(t=>r.call(this,t,e)),e.getVideoTracks().forEach(t=>r.call(this,t,e))},s.RTCPeerConnection.prototype.addTrack=function(e,...t){return t&&t.forEach(i=>{this._localStreams?this._localStreams.includes(i)||this._localStreams.push(i):this._localStreams=[i]}),r.apply(this,arguments)}}"removeStream"in s.RTCPeerConnection.prototype||(s.RTCPeerConnection.prototype.removeStream=function(r){this._localStreams||(this._localStreams=[]);const e=this._localStreams.indexOf(r);if(e===-1)return;this._localStreams.splice(e,1);const t=r.getTracks();this.getSenders().forEach(i=>{t.includes(i.track)&&this.removeTrack(i)})})}}function Xo(s){if(typeof s=="object"&&s.RTCPeerConnection&&("getRemoteStreams"in s.RTCPeerConnection.prototype||(s.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in s.RTCPeerConnection.prototype))){Object.defineProperty(s.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=t=>{t.streams.forEach(i=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(i))return;this._remoteStreams.push(i);const n=new Event("addstream");n.stream=i,this.dispatchEvent(n)})})}});const r=s.RTCPeerConnection.prototype.setRemoteDescription;s.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(i=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(i)>=0)return;e._remoteStreams.push(i);const n=new Event("addstream");n.stream=i,e.dispatchEvent(n)})}),r.apply(e,arguments)}}}function Zo(s){if(typeof s!="object"||!s.RTCPeerConnection)return;const r=s.RTCPeerConnection.prototype,e=r.createOffer,t=r.createAnswer,i=r.setLocalDescription,n=r.setRemoteDescription,a=r.addIceCandidate;r.createOffer=function(o,l){const d=arguments.length>=2?arguments[2]:arguments[0],h=e.apply(this,[d]);return l?(h.then(o,l),Promise.resolve()):h},r.createAnswer=function(o,l){const d=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[d]);return l?(h.then(o,l),Promise.resolve()):h};let c=function(o,l,d){const h=i.apply(this,[o]);return d?(h.then(l,d),Promise.resolve()):h};r.setLocalDescription=c,c=function(o,l,d){const h=n.apply(this,[o]);return d?(h.then(l,d),Promise.resolve()):h},r.setRemoteDescription=c,c=function(o,l,d){const h=a.apply(this,[o]);return d?(h.then(l,d),Promise.resolve()):h},r.addIceCandidate=c}function Yo(s){const r=s&&s.navigator;if(r.mediaDevices&&r.mediaDevices.getUserMedia){const e=r.mediaDevices,t=e.getUserMedia.bind(e);r.mediaDevices.getUserMedia=i=>t(Qo(i))}!r.getUserMedia&&r.mediaDevices&&r.mediaDevices.getUserMedia&&(r.getUserMedia=function(e,t,i){r.mediaDevices.getUserMedia(e).then(t,i)}.bind(r))}function Qo(s){return s&&s.video!==void 0?Object.assign({},s,{video:So(s.video)}):s}function qo(s){if(!s.RTCPeerConnection)return;const r=s.RTCPeerConnection;s.RTCPeerConnection=function(e,t){if(e&&e.iceServers){const i=[];for(let n=0;n<e.iceServers.length;n++){let a=e.iceServers[n];!a.hasOwnProperty("urls")&&a.hasOwnProperty("url")?(Bi("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,i.push(a)):i.push(e.iceServers[n])}e.iceServers=i}return new r(e,t)},s.RTCPeerConnection.prototype=r.prototype,"generateCertificate"in r&&Object.defineProperty(s.RTCPeerConnection,"generateCertificate",{get:()=>r.generateCertificate})}function ec(s){typeof s=="object"&&s.RTCTrackEvent&&"receiver"in s.RTCTrackEvent.prototype&&!("transceiver"in s.RTCTrackEvent.prototype)&&Object.defineProperty(s.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function tc(s){const r=s.RTCPeerConnection.prototype.createOffer;s.RTCPeerConnection.prototype.createOffer=function(e){if(e){e.offerToReceiveAudio!==void 0&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find(n=>n.receiver.track.kind==="audio");e.offerToReceiveAudio===!1&&t?t.direction==="sendrecv"?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":t.direction==="recvonly"&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):e.offerToReceiveAudio!==!0||t||this.addTransceiver("audio"),e.offerToReceiveVideo!==void 0&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find(n=>n.receiver.track.kind==="video");e.offerToReceiveVideo===!1&&i?i.direction==="sendrecv"?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":i.direction==="recvonly"&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):e.offerToReceiveVideo!==!0||i||this.addTransceiver("video")}return r.apply(this,arguments)}}function rc(s){typeof s!="object"||s.AudioContext||(s.AudioContext=s.webkitAudioContext)}const ic=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:rc,shimCallbacksAPI:Zo,shimConstraints:Qo,shimCreateOfferLegacy:tc,shimGetUserMedia:Yo,shimLocalStreamsAPI:$o,shimRTCIceServerUrls:qo,shimRemoteStreamsAPI:Xo,shimTrackEventTransceiver:ec},Symbol.toStringTag,{value:"Module"}));var sc={exports:{}};(function(s){var r={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};r.localCName=r.generateIdentifier(),r.splitLines=function(e){return e.trim().split(`
76
+ `).map(function(t){return t.trim()})},r.splitSections=function(e){return e.split(`
77
+ m=`).map(function(t,i){return(i>0?"m="+t:t).trim()+`\r
78
+ `})},r.getDescription=function(e){var t=r.splitSections(e);return t&&t[0]},r.getMediaSections=function(e){var t=r.splitSections(e);return t.shift(),t},r.matchPrefix=function(e,t){return r.splitLines(e).filter(function(i){return i.indexOf(t)===0})},r.parseCandidate=function(e){for(var t,i={foundation:(t=e.indexOf("a=candidate:")===0?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:parseInt(t[1],10),protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},n=8;n<t.length;n+=2)switch(t[n]){case"raddr":i.relatedAddress=t[n+1];break;case"rport":i.relatedPort=parseInt(t[n+1],10);break;case"tcptype":i.tcpType=t[n+1];break;case"ufrag":i.ufrag=t[n+1],i.usernameFragment=t[n+1];break;default:i[t[n]]=t[n+1]}return i},r.writeCandidate=function(e){var t=[];t.push(e.foundation),t.push(e.component),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var i=e.type;return t.push("typ"),t.push(i),i!=="host"&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&e.protocol.toLowerCase()==="tcp"&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},r.parseIceOptions=function(e){return e.substr(14).split(" ")},r.parseRtpMap=function(e){var t=e.substr(9).split(" "),i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=t.length===3?parseInt(t[2],10):1,i.numChannels=i.channels,i},r.writeRtpMap=function(e){var t=e.payloadType;e.preferredPayloadType!==void 0&&(t=e.preferredPayloadType);var i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(i!==1?"/"+i:"")+`\r
79
+ `},r.parseExtmap=function(e){var t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},r.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&e.direction!=="sendrecv"?"/"+e.direction:"")+" "+e.uri+`\r
80
+ `},r.parseFmtp=function(e){for(var t,i={},n=e.substr(e.indexOf(" ")+1).split(";"),a=0;a<n.length;a++)i[(t=n[a].trim().split("="))[0].trim()]=t[1];return i},r.writeFmtp=function(e){var t="",i=e.payloadType;if(e.preferredPayloadType!==void 0&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var n=[];Object.keys(e.parameters).forEach(function(a){e.parameters[a]?n.push(a+"="+e.parameters[a]):n.push(a)}),t+="a=fmtp:"+i+" "+n.join(";")+`\r
81
+ `}return t},r.parseRtcpFb=function(e){var t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},r.writeRtcpFb=function(e){var t="",i=e.payloadType;return e.preferredPayloadType!==void 0&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(function(n){t+="a=rtcp-fb:"+i+" "+n.type+(n.parameter&&n.parameter.length?" "+n.parameter:"")+`\r
82
+ `}),t},r.parseSsrcMedia=function(e){var t=e.indexOf(" "),i={ssrc:parseInt(e.substr(7,t-7),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substr(t+1,n-t-1),i.value=e.substr(n+1)):i.attribute=e.substr(t+1),i},r.parseSsrcGroup=function(e){var t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(function(i){return parseInt(i,10)})}},r.getMid=function(e){var t=r.matchPrefix(e,"a=mid:")[0];if(t)return t.substr(6)},r.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},r.getDtlsParameters=function(e,t){return{role:"auto",fingerprints:r.matchPrefix(e+t,"a=fingerprint:").map(r.parseFingerprint)}},r.writeDtlsParameters=function(e,t){var i="a=setup:"+t+`\r
83
+ `;return e.fingerprints.forEach(function(n){i+="a=fingerprint:"+n.algorithm+" "+n.value+`\r
84
+ `}),i},r.parseCryptoLine=function(e){var t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},r.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+(typeof e.keyParams=="object"?r.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+`\r
85
+ `},r.parseCryptoKeyParams=function(e){if(e.indexOf("inline:")!==0)return null;var t=e.substr(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},r.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},r.getCryptoParameters=function(e,t){return r.matchPrefix(e+t,"a=crypto:").map(r.parseCryptoLine)},r.getIceParameters=function(e,t){var i=r.matchPrefix(e+t,"a=ice-ufrag:")[0],n=r.matchPrefix(e+t,"a=ice-pwd:")[0];return i&&n?{usernameFragment:i.substr(12),password:n.substr(10)}:null},r.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+`\r
86
+ a=ice-pwd:`+e.password+`\r
87
+ `},r.parseRtpParameters=function(e){for(var t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=r.splitLines(e)[0].split(" "),n=3;n<i.length;n++){var a=i[n],c=r.matchPrefix(e,"a=rtpmap:"+a+" ")[0];if(c){var o=r.parseRtpMap(c),l=r.matchPrefix(e,"a=fmtp:"+a+" ");switch(o.parameters=l.length?r.parseFmtp(l[0]):{},o.rtcpFeedback=r.matchPrefix(e,"a=rtcp-fb:"+a+" ").map(r.parseRtcpFb),t.codecs.push(o),o.name.toUpperCase()){case"RED":case"ULPFEC":t.fecMechanisms.push(o.name.toUpperCase())}}}return r.matchPrefix(e,"a=extmap:").forEach(function(d){t.headerExtensions.push(r.parseExtmap(d))}),t},r.writeRtpDescription=function(e,t){var i="";i+="m="+e+" ",i+=t.codecs.length>0?"9":"0",i+=" UDP/TLS/RTP/SAVPF ",i+=t.codecs.map(function(a){return a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType}).join(" ")+`\r
88
+ `,i+=`c=IN IP4 0.0.0.0\r
89
+ `,i+=`a=rtcp:9 IN IP4 0.0.0.0\r
90
+ `,t.codecs.forEach(function(a){i+=r.writeRtpMap(a),i+=r.writeFmtp(a),i+=r.writeRtcpFb(a)});var n=0;return t.codecs.forEach(function(a){a.maxptime>n&&(n=a.maxptime)}),n>0&&(i+="a=maxptime:"+n+`\r
91
+ `),i+=`a=rtcp-mux\r
92
+ `,t.headerExtensions&&t.headerExtensions.forEach(function(a){i+=r.writeExtmap(a)}),i},r.parseRtpEncodingParameters=function(e){var t,i=[],n=r.parseRtpParameters(e),a=n.fecMechanisms.indexOf("RED")!==-1,c=n.fecMechanisms.indexOf("ULPFEC")!==-1,o=r.matchPrefix(e,"a=ssrc:").map(function(u){return r.parseSsrcMedia(u)}).filter(function(u){return u.attribute==="cname"}),l=o.length>0&&o[0].ssrc,d=r.matchPrefix(e,"a=ssrc-group:FID").map(function(u){return u.substr(17).split(" ").map(function(p){return parseInt(p,10)})});d.length>0&&d[0].length>1&&d[0][0]===l&&(t=d[0][1]),n.codecs.forEach(function(u){if(u.name.toUpperCase()==="RTX"&&u.parameters.apt){var p={ssrc:l,codecPayloadType:parseInt(u.parameters.apt,10)};l&&t&&(p.rtx={ssrc:t}),i.push(p),a&&((p=JSON.parse(JSON.stringify(p))).fec={ssrc:l,mechanism:c?"red+ulpfec":"red"},i.push(p))}}),i.length===0&&l&&i.push({ssrc:l});var h=r.matchPrefix(e,"b=");return h.length&&(h=h[0].indexOf("b=TIAS:")===0?parseInt(h[0].substr(7),10):h[0].indexOf("b=AS:")===0?1e3*parseInt(h[0].substr(5),10)*.95-16e3:void 0,i.forEach(function(u){u.maxBitrate=h})),i},r.parseRtcpParameters=function(e){var t={},i=r.matchPrefix(e,"a=ssrc:").map(function(c){return r.parseSsrcMedia(c)}).filter(function(c){return c.attribute==="cname"})[0];i&&(t.cname=i.value,t.ssrc=i.ssrc);var n=r.matchPrefix(e,"a=rtcp-rsize");t.reducedSize=n.length>0,t.compound=n.length===0;var a=r.matchPrefix(e,"a=rtcp-mux");return t.mux=a.length>0,t},r.parseMsid=function(e){var t,i=r.matchPrefix(e,"a=msid:");if(i.length===1)return{stream:(t=i[0].substr(7).split(" "))[0],track:t[1]};var n=r.matchPrefix(e,"a=ssrc:").map(function(a){return r.parseSsrcMedia(a)}).filter(function(a){return a.attribute==="msid"});return n.length>0?{stream:(t=n[0].value.split(" "))[0],track:t[1]}:void 0},r.parseSctpDescription=function(e){var t,i=r.parseMLine(e),n=r.matchPrefix(e,"a=max-message-size:");n.length>0&&(t=parseInt(n[0].substr(19),10)),isNaN(t)&&(t=65536);var a=r.matchPrefix(e,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substr(12),10),protocol:i.fmt,maxMessageSize:t};if(r.matchPrefix(e,"a=sctpmap:").length>0){var c=r.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(c[0],10),protocol:c[1],maxMessageSize:t}}},r.writeSctpDescription=function(e,t){var i=[];return i=e.protocol!=="DTLS/SCTP"?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+`\r
93
+ `,`c=IN IP4 0.0.0.0\r
94
+ `,"a=sctp-port:"+t.port+`\r
95
+ `]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+`\r
96
+ `,`c=IN IP4 0.0.0.0\r
97
+ `,"a=sctpmap:"+t.port+" "+t.protocol+` 65535\r
98
+ `],t.maxMessageSize!==void 0&&i.push("a=max-message-size:"+t.maxMessageSize+`\r
99
+ `),i.join("")},r.generateSessionId=function(){return Math.random().toString().substr(2,21)},r.writeSessionBoilerplate=function(e,t,i){var n=t!==void 0?t:2;return`v=0\r
100
+ o=`+(i||"thisisadapterortc")+" "+(e||r.generateSessionId())+" "+n+` IN IP4 127.0.0.1\r
101
+ s=-\r
102
+ t=0 0\r
103
+ `},r.writeMediaSection=function(e,t,i,n){var a=r.writeRtpDescription(e.kind,t);if(a+=r.writeIceParameters(e.iceGatherer.getLocalParameters()),a+=r.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),i==="offer"?"actpass":"active"),a+="a=mid:"+e.mid+`\r
104
+ `,e.direction?a+="a="+e.direction+`\r
105
+ `:e.rtpSender&&e.rtpReceiver?a+=`a=sendrecv\r
106
+ `:e.rtpSender?a+=`a=sendonly\r
107
+ `:e.rtpReceiver?a+=`a=recvonly\r
108
+ `:a+=`a=inactive\r
109
+ `,e.rtpSender){var c="msid:"+n.id+" "+e.rtpSender.track.id+`\r
110
+ `;a+="a="+c,a+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+c,e.sendEncodingParameters[0].rtx&&(a+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+c,a+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+`\r
111
+ `)}return a+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+r.localCName+`\r
112
+ `,e.rtpSender&&e.sendEncodingParameters[0].rtx&&(a+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+r.localCName+`\r
113
+ `),a},r.getDirection=function(e,t){for(var i=r.splitLines(e),n=0;n<i.length;n++)switch(i[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[n].substr(2)}return t?r.getDirection(t):"sendrecv"},r.getKind=function(e){return r.splitLines(e)[0].split(" ")[0].substr(2)},r.isRejected=function(e){return e.split(" ",2)[1]==="0"},r.parseMLine=function(e){var t=r.splitLines(e)[0].substr(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}},r.parseOLine=function(e){var t=r.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:t[0],sessionId:t[1],sessionVersion:parseInt(t[2],10),netType:t[3],addressType:t[4],address:t[5]}},r.isValidSDP=function(e){if(typeof e!="string"||e.length===0)return!1;for(var t=r.splitLines(e),i=0;i<t.length;i++)if(t[i].length<2||t[i].charAt(1)!=="=")return!1;return!0},s.exports=r})(sc);const Hi=Cr(sc.exports);function Wi(s){if(!s.RTCIceCandidate||s.RTCIceCandidate&&"foundation"in s.RTCIceCandidate.prototype)return;const r=s.RTCIceCandidate;s.RTCIceCandidate=function(e){if(typeof e=="object"&&e.candidate&&e.candidate.indexOf("a=")===0&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const t=new r(e),i=Hi.parseCandidate(e.candidate),n=Object.assign(t,i);return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new r(e)},s.RTCIceCandidate.prototype=r.prototype,$r(s,"icecandidate",e=>(e.candidate&&Object.defineProperty(e,"candidate",{value:new s.RTCIceCandidate(e.candidate),writable:"false"}),e))}function mi(s,r){if(!s.RTCPeerConnection)return;"sctp"in s.RTCPeerConnection.prototype||Object.defineProperty(s.RTCPeerConnection.prototype,"sctp",{get(){return this._sctp===void 0?null:this._sctp}});const e=s.RTCPeerConnection.prototype.setRemoteDescription;s.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,r.browser==="chrome"&&r.version>=76){const{sdpSemantics:t}=this.getConfiguration();t==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(function(t){if(!t||!t.sdp)return!1;const i=Hi.splitSections(t.sdp);return i.shift(),i.some(n=>{const a=Hi.parseMLine(n);return a&&a.kind==="application"&&a.protocol.indexOf("SCTP")!==-1})}(arguments[0])){const t=function(o){const l=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(l===null||l.length<2)return-1;const d=parseInt(l[1],10);return d!=d?-1:d}(arguments[0]),i=function(o){let l=65536;return r.browser==="firefox"&&(l=r.version<57?o===-1?16384:2147483637:r.version<60?r.version===57?65535:65536:2147483637),l}(t),n=function(o,l){let d=65536;r.browser==="firefox"&&r.version===57&&(d=65535);const h=Hi.matchPrefix(o.sdp,"a=max-message-size:");return h.length>0?d=parseInt(h[0].substr(19),10):r.browser==="firefox"&&l!==-1&&(d=2147483637),d}(arguments[0],t);let a;a=i===0&&n===0?Number.POSITIVE_INFINITY:i===0||n===0?Math.max(i,n):Math.min(i,n);const c={};Object.defineProperty(c,"maxMessageSize",{get:()=>a}),this._sctp=c}return e.apply(this,arguments)}}function fi(s){if(!s.RTCPeerConnection||!("createDataChannel"in s.RTCPeerConnection.prototype))return;function r(t,i){const n=t.send;t.send=function(){const a=arguments[0],c=a.length||a.size||a.byteLength;if(t.readyState==="open"&&i.sctp&&c>i.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+i.sctp.maxMessageSize+" bytes)");return n.apply(t,arguments)}}const e=s.RTCPeerConnection.prototype.createDataChannel;s.RTCPeerConnection.prototype.createDataChannel=function(){const t=e.apply(this,arguments);return r(t,this),t},$r(s,"datachannel",t=>(r(t.channel,t.target),t))}function xs(s){if(!s.RTCPeerConnection||"connectionState"in s.RTCPeerConnection.prototype)return;const r=s.RTCPeerConnection.prototype;Object.defineProperty(r,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(r,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{const t=r[e];r[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=i=>{const n=i.target;if(n._lastConnectionState!==n.connectionState){n._lastConnectionState=n.connectionState;const a=new Event("connectionstatechange",i);n.dispatchEvent(a)}return i},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),t.apply(this,arguments)}})}function Vs(s,r){if(!s.RTCPeerConnection||r.browser==="chrome"&&r.version>=71||r.browser==="safari"&&r.version>=605)return;const e=s.RTCPeerConnection.prototype.setRemoteDescription;s.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&t.sdp.indexOf(`
114
+ a=extmap-allow-mixed`)!==-1){const i=t.sdp.split(`
115
+ `).filter(n=>n.trim()!=="a=extmap-allow-mixed").join(`
116
+ `);s.RTCSessionDescription&&t instanceof s.RTCSessionDescription?arguments[0]=new s.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return e.apply(this,arguments)}}function ji(s,r){if(!s.RTCPeerConnection||!s.RTCPeerConnection.prototype)return;const e=s.RTCPeerConnection.prototype.addIceCandidate;e&&e.length!==0&&(s.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(r.browser==="chrome"&&r.version<78||r.browser==="firefox"&&r.version<68||r.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():e.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}const zh=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:Vs,shimAddIceCandidateNullOrEmpty:ji,shimConnectionState:xs,shimMaxMessageSize:mi,shimRTCIceCandidate:Wi,shimSendThrowTypeError:fi},Symbol.toStringTag,{value:"Module"}));(function({window:s}={},r={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const e=Ds,t=function(n){const a={browser:null,version:null};if(n===void 0||!n.navigator)return a.browser="Not a browser.",a;const{navigator:c}=n;if(c.mozGetUserMedia)a.browser="firefox",a.version=pi(c.userAgent,/Firefox\/(\d+)\./,1);else if(c.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection&&!n.RTCIceGatherer)a.browser="chrome",a.version=pi(c.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(c.mediaDevices&&c.userAgent.match(/Edge\/(\d+).(\d+)$/))a.browser="edge",a.version=pi(c.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!n.RTCPeerConnection||!c.userAgent.match(/AppleWebKit\/(\d+)\./))return a.browser="Not a supported browser.",a;a.browser="safari",a.version=pi(c.userAgent,/AppleWebKit\/(\d+)\./,1),a.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype}return a}(s),i={browserDetails:t,commonShim:zh,extractVersion:pi,disableLog:Hh,disableWarnings:Wh};switch(t.browser){case"chrome":if(!Po||!Ms||!r.shimChrome)return e("Chrome shim is not included in this adapter release."),i;if(t.version===null)return e("Chrome shim can not determine version, not shimming."),i;e("adapter.js shimming chrome."),i.browserShim=Po,ji(s,t),Ro(s,t),Eo(s),Ms(s,t),yo(s),Ao(s,t),To(s),Co(s),_o(s),Io(s,t),Wi(s),xs(s),mi(s,t),fi(s),Vs(s,t);break;case"firefox":if(!Jo||!Ls||!r.shimFirefox)return e("Firefox shim is not included in this adapter release."),i;e("adapter.js shimming firefox."),i.browserShim=Jo,ji(s,t),Vo(s,t),Ls(s,t),Uo(s),Ho(s),Bo(s),Fo(s),Wo(s),jo(s),Go(s),zo(s),Ko(s),Wi(s),xs(s),mi(s,t),fi(s);break;case"edge":if(!xo||!Ns||!r.shimEdge)return e("MS edge shim is not included in this adapter release."),i;e("adapter.js shimming edge."),i.browserShim=xo,Oo(s),No(s),Ns(s,t),Lo(s),mi(s,t),fi(s);break;case"safari":if(!ic||!r.shimSafari)return e("Safari shim is not included in this adapter release."),i;e("adapter.js shimming safari."),i.browserShim=ic,ji(s,t),qo(s),tc(s),Zo(s),$o(s),Xo(s),ec(s),Yo(s),rc(s),Wi(s),mi(s,t),fi(s),Vs(s,t);break;default:e("Unsupported browser!")}})({window:typeof window=="undefined"?void 0:window});var nc={exports:{}};(function(s){s.exports=(()=>{var r={622:(n,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BrowserUtil=a.BrowserType=void 0;var o,l=c(101);(function(h){h.IE="IE",h.Chrome="Chrome",h.Safari="Safari",h.Firefox="Firefox",h.Opera="Opera",h.Edge="Edge",h.MicroMessenger="MicroMessenger",h.X5Core="X5Core",h.Quark="Quark",h.QQ="QQ",h.QQBrowser="QQBrowser",h.DingTalk="DingTalk",h.Electron="Electron",h.Sogou="Sogou",h.Vivo="VivoBrowser",h.Oppo="OppoBrowser",h.UC="UCBrowser",h.MI="MiBrowser",h.Lenovo="SLBrowser",h.Maxthon="Maxthon",h.Liebao="Liebao",h.Huawei="Huawei",h.Meizu="MZBrowser",h.Finger="FingerBrowser",h.Samsung="SamsungBrowser",h.WebVeiw="WebVeiw",h.Unknown="unknown"})(o=a.BrowserType||(a.BrowserType={}));var d=function(){function h(){}return Object.defineProperty(h,"isBrowser",{get:function(){return typeof document!="undefined"},enumerable:!1,configurable:!0}),Object.defineProperty(h,"domain",{get:function(){return window.location.protocol+window.location.host},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isHttps",{get:function(){return this.isBrowser&&document.location&&(document.location.protocol=="https:"||document.location.host.indexOf("127.0.0.1:")===0||document.location.host.indexOf("localhost:")===0)},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isSupportScreenShare",{get:function(){return!!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isChrome",{get:function(){return h._getBrowserInfo(),o.Chrome===h._browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isSafari",{get:function(){return h._getBrowserInfo(),o.Safari===h._browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isIE",{get:function(){return h._getBrowserInfo(),o.IE===h._browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isFirefox",{get:function(){return h._getBrowserInfo(),o.Firefox===h._browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isEdge",{get:function(){return h._getBrowserInfo(),o.Edge===h.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isSogou",{get:function(){return h._getBrowserInfo(),o.Sogou===h.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isVivoBroswer",{get:function(){return h._getBrowserInfo(),o.Vivo===h.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isOppoBrowser",{get:function(){return h._getBrowserInfo(),o.Oppo===h.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isMiBrowser",{get:function(){return h._getBrowserInfo(),o.MI===h.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isLenovoBrowser",{get:function(){return h._getBrowserInfo(),o.Lenovo===h.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isMaxthonBrowser",{get:function(){return h._getBrowserInfo(),o.Maxthon===h.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isLiebaoBrowser",{get:function(){return h._getBrowserInfo(),o.Liebao===h.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isHuaweiBrowser",{get:function(){return h._getBrowserInfo(),o.Huawei===h.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isMZBrowser",{get:function(){return h._getBrowserInfo(),o.Meizu===h._browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isSamsungBrowser",{get:function(){return h._getBrowserInfo(),o.Samsung===h._browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isOpera",{get:function(){return h._getBrowserInfo(),o.Opera===h._browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isMicroMessenger",{get:function(){return h._getBrowserInfo(),h._browserName===o.MicroMessenger},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isQQ",{get:function(){return h._getBrowserInfo(),o.QQ===h.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isQQBrowser",{get:function(){return h._getBrowserInfo(),o.QQBrowser===h.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isX5Core",{get:function(){return h._getBrowserInfo(),h._browserName===o.X5Core},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isUCBrowser",{get:function(){return h._getBrowserInfo(),h._browserName===o.UC},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isQuarkBrowser",{get:function(){return h._getBrowserInfo(),h._browserName===o.Quark},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isFingerBrowser",{get:function(){return h._getBrowserInfo(),h._browserName===o.Finger},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isChromeCore",{get:function(){return h._getBrowserInfo(),h._core==="Chrome"},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isWebView",{get:function(){return h._getBrowserInfo(),h._browserName===o.WebVeiw},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isDingTalk",{get:function(){return h._getBrowserInfo(),h._browserName===o.DingTalk},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isUnknown",{get:function(){return h._getBrowserInfo(),o.Unknown===h.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"browserName",{get:function(){return h._getBrowserInfo(),h._browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"browserVersion",{get:function(){return h._getBrowserInfo(),h._browserVersion},enumerable:!1,configurable:!0}),Object.defineProperty(h,"browserMainVersion",{get:function(){return h._getBrowserInfo(),h._browserVersion?parseInt(h._browserVersion.split(".")[0],10):0},enumerable:!1,configurable:!0}),Object.defineProperty(h,"browserCoreVersion",{get:function(){return navigator.userAgent.toLowerCase(),l.SystemUtil.isIos||l.SystemUtil.isMacOS,h.browserMainVersion},enumerable:!1,configurable:!0}),Object.defineProperty(h,"isElectron",{get:function(){return h._getBrowserInfo(),o.Electron===h.browserName},enumerable:!1,configurable:!0}),Object.defineProperty(h,"userAgent",{get:function(){var u=navigator.userAgent.toLowerCase(),p=u.indexOf("gecko");if(p>-1){p=u.indexOf(" ",p);var f=(u=u.substring(p+1,u.length)).split(" ");u="";for(var m=0;m<f.length;++m){var g=f[m].split("/");g&&g.length&&(u+=g[0]+" ")}}return u},enumerable:!1,configurable:!0}),h.compareVersion=function(u){if(h._getBrowserInfo(),h._browserVersion){for(var p=h._browserVersion.split("."),f=u.split("."),m=0,g=0,S=0;S<p.length&&S<f.length;++S){if((m=isNaN(parseInt(p[S],10))?0:parseInt(p[S],10))<(g=isNaN(parseInt(f[S],10))?0:parseInt(f[S],10)))return!1;if(m>g)return!0}return!0}return!0},h._getBrowserInfo=function(){if(!h._browserName||!h._browserVersion)if(navigator&&navigator.userAgent){var u=navigator.userAgent.toLowerCase(),p=void 0;(p=u.match(/edg[e|a]?\/([\d.]+)/))||(p=u.match(/edgios\/([\d.]+)/))?h._updateBrowserInfo(o.Edge,u,p[1]):(p=u.match(/rv:([\d.]+)\) like gecko/))||(p=u.match(/msie ([\d.]+)/))?h._updateBrowserInfo(o.IE,u,p[1]):(p=u.match(/vivobrowser\/([\d.]+)/))?h._updateBrowserInfo(o.Vivo,u,p[1]):(p=u.match(/miuibrowser\/([\d.]+)/))?h._updateBrowserInfo(o.MI,u,p[1]):(p=u.match(/samsungbrowser\/([\d.]+)/))?h._updateBrowserInfo(o.Samsung,u,p[1]):(p=u.match(/heytapbrowser\/([\d.]+)/))?h._updateBrowserInfo(o.Oppo,u,p[1]):(p=u.match(/mzbrowser\/([\d.]+)/))?h._updateBrowserInfo(o.Meizu,u,p[1]):(p=u.match(/ucbrowser\/([\d.]+)/))?h._updateBrowserInfo(o.UC,u,p[1]):(p=u.match(/quark\/([\d.]+)/))?h._updateBrowserInfo(o.Quark,u,p[1]):(p=u.match(/slbrowser\/([\d.]+)/))?h._updateBrowserInfo(o.Lenovo,u,p[1]):(p=u.match(/lbbrowser\/([\d.]+)/))?h._updateBrowserInfo(o.Liebao,u,p[1]):(p=u.match(/fingerbrowser\/([\d.]+)/))?h._updateBrowserInfo(o.Finger,u,p[1]):(p=u.match(/huaweibrowser\/([\d.]+)/))?h._updateBrowserInfo(o.Huawei,u,p[1]):(p=u.match(/maxthon\/([\d.]+)/))?h._updateBrowserInfo(o.Maxthon,u,p[1]):(p=u.match(/firefox\/([\d.]+)/))?h._updateBrowserInfo(o.Firefox,u,p[1]):(p=u.match(/electron\/([\d.]+)/))?h._updateBrowserInfo(o.Electron,u,p[1]):(p=u.match(/chrome\/([\d.]+)/))&&this._isChrome(u)||(p=u.match(/crios\/([\d.]+)/))&&this._isChrome(u)?h._updateBrowserInfo(o.Chrome,u,p[1]):(p=u.match(/metasr\s([\d.]+)/))||(p=u.match(/sogoumobilebrowser\/([\d.]+)/))?h._updateBrowserInfo(o.Sogou,u,p[1]):(p=u.match(/opr.([\d.]+)/))?h._updateBrowserInfo(o.Opera,u,p[1]):(p=u.match(/micromessenger.([\d.]+)/))?h._updateBrowserInfo(o.MicroMessenger,u,p[1]):(p=u.match(/qq\/([\d.]+)/))?h._updateBrowserInfo(o.QQ,u,p[1]):(p=u.match(/m?qqbrowser\/([\d.]+)/))||(p=u.match(/qqbrowserlite\/([\d.]+)/))?h._updateBrowserInfo(o.QQBrowser,u,p[1]):(p=u.match(/dingtalk.([\d.]+)/))?h._updateBrowserInfo(o.DingTalk,u,p[1]):(p=u.match(/tbs\/([\d.]+)/))?h._updateBrowserInfo(o.X5Core,u,p[1]):(p=u.match(/version\/([\d.]+).*safari/))&&this._isSafari(u)&&h._updateBrowserInfo(o.Safari,u,p[1]),h._browserName===o.Unknown&&h._isWebview(u)&&h._updateBrowserInfo(o.WebVeiw,u,"")}else h._browserName=o.Unknown,h._browserVersion="0.0"},h._isChrome=function(u){var p=u.split(/\(|\)/);if(h._core="Chrome",p.length===5){var f=p[4].trim().split(" ");if(f.length===2){if(f[0].indexOf("chrome")>-1&&f[1].indexOf("safari")>-1)return!0}else if(f.length===3){if(f[1].indexOf("mobile")>-1&&f[2].indexOf("safari")>-1&&(f[0].indexOf("chrome")>-1||f[0].indexOf("crios")>-1))return!0}else if(u.indexOf("qianniu")>-1)return!0}return!1},h._isSafari=function(u){var p=u.split(/\(|\)/);if(p.length===5){var f=p[4].trim().split(" ");if(f.length===2){if(f[0].indexOf("version")>-1&&f[1].indexOf("safari")>-1)return!0}else if(f.length===3&&f[0].indexOf("version")>-1&&f[1].indexOf("mobile")>-1&&f[2].indexOf("safari")>-1)return!0}return!1},h._isWebview=function(u){if(u){var p=new RegExp("("+["WebView","(iPhone|iPod|iPad)(?!.*Safari)","Android.*(wv|.0.0.0)","Linux; U; Android"].join("|")+")","ig"),f=new RegExp("("+["VivoBrowser","MZBrowser","MiuiBrowser"].join("|")+")","ig");return!!u.match(p)&&!u.match(f)}},h._updateBrowserInfo=function(u,p,f){h._browserName=u;var m=null;switch(u){case o.QQBrowser:l.SystemUtil.isIos||l.SystemUtil.isMacOS?(m=p.match(/version\/([\d.]+).*safari/),h._browserVersion=m?m[1]:"0.0"):(m=p.match(/chrome\/([\d.]+)/),h._browserVersion=m?m[1]:"0.0");break;case o.Vivo:case o.Oppo:case o.Meizu:case o.Huawei:case o.Sogou:case o.Samsung:m=p.match(/chrome\/([\d.]+)/),h._browserVersion=m?m[1]:"0.0";break;case o.WebVeiw:l.SystemUtil.isAndroid?(m=p.match(/chrome\/([\d.]+)/),h._browserVersion=m?m[1]:"0.0"):l.SystemUtil.isIos&&(h._browserVersion=l.SystemUtil.systemVersion);break;default:h._browserVersion=f}},h._browserName=o.Unknown,h._browserVersion="",h._core="",h}();a.BrowserUtil=d},864:(n,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.Guid=void 0;var c=function(){function o(){}return o.create=function(l,d){d===void 0&&(d=16);var h,u,p="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),f=[];if(d=d||p.length,l)for(h=0;h<l;h++)f[h]=p[0|Math.random()*d];else for(f[8]=f[13]=f[18]=f[23]="-",f[14]="4",h=0;h<36;h++)f[h]||(u=0|16*Math.random(),f[h]=p[h==19?3&u|8:u]);return f.join("")},o}();a.Guid=c},442:(n,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.LocalStorage=void 0;var o=c(864),l=function(){function d(){}return Object.defineProperty(d,"uuid",{get:function(){var h="alirtc_uuid",u=d.get(h);return u||(u=o.Guid.create(32),d.set(h,u)),u},enumerable:!1,configurable:!0}),d.get=function(h){var u="";return window&&window.localStorage&&(u=window.localStorage.getItem(h)||""),u},d.set=function(h,u){h&&window&&window.localStorage&&window.localStorage.setItem(h,u)},d}();a.LocalStorage=l},72:(n,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.ApiRequest=void 0;var c=function(){function o(){}return o.postBody=function(l,d,h){l=o._getUrl(l,d);var u,p={};return p.headers||(p.headers={}),p.headers.Accept="application/json",p.headers["Content-Type"]="application/json",new Promise(function(f,m){o.requestBody("POST",l,h).then(function(g){return u=g,g.ok?g.json():g.text()}).then(function(g){u.ok?g.code?(g=o._intercept(g),m(g)):f(g.data):m(o._httpErrorMessage(u,g))}).catch(function(g){g=o._httpErrorMessage(g),m(g)})})},o.get=function(l,d,h){var u;return h===void 0&&(h={}),l=o._getUrl(l,d),h.headers||(h.headers={}),h.headers["Content-Type"]="application/json",new Promise(function(p,f){o.request("GET",l,h).then(function(m){return u=m,m.ok?m.json():m.text()}).then(function(m){u.ok?m.code?(m=o._intercept(m),f(m)):p(m.data):f(o._httpErrorMessage(u,m))}).catch(function(m){m=o._httpErrorMessage(m),f(m)})})},o.post=function(l,d,h,u){var p;return u===void 0&&(u={}),l=o._getUrl(l,d),u.headers||(u.headers={}),u.body=h,u.headers.Accept="application/json",u.headers["Content-Type"]="application/json",new Promise(function(f,m){o.request("POST",l,u).then(function(g){return p=g,g.ok?g.json():g.text()}).then(function(g){p.ok?g.code?(g=o._intercept(g),m(g)):f(g.data):m(o._httpErrorMessage(p,g))}).catch(function(g){g=o._httpErrorMessage(g),m(g)})})},o.request=function(l,d,h){l===void 0&&(l="GET");var u=new Headers(h.headers),p=new Request(d,{method:l,headers:u});return fetch(p)},o.requestBody=function(l,d,h){return l===void 0&&(l="GET"),fetch(d,{method:l,body:h,headers:new Headers({"Content-Type":"application/json"})})},o.ajaxPost=function(l,d,h,u){return u===void 0&&(u={}),l=o._getUrl(l,d),u.headers||(u.headers={}),u.headers.Accept="application/json",u.headers["Content-Type"]="application/json",o.ajax("POST",l,h,u)},o.ajax=function(l,d,h,u){l===void 0&&(l="GET"),u===void 0&&(u={});var p=new XMLHttpRequest;return new Promise(function(f,m){p.onreadystatechange=function(){if(p.readyState===4)if(p.status===200){var S=JSON.parse(p.responseText);S.code?(S=o._intercept(S),m(S)):f(S)}else m({message:p.responseText||"请求失败:"+d})},p.open(l,d,!0);try{if(u.withCredentials&&(p.withCredentials=!0),u.headers)for(var g in u.headers)p.setRequestHeader(g,u.headers[g])}catch(S){return void m(S)}try{p.send(h)}catch(S){m(S)}})},o._getUrl=function(l,d){var h=[];if(d)for(var u in d)h.push(u+"="+d[u]);var p=h.join("&");return(l.indexOf("?")!=-1?l:l+"?")+p},o._httpErrorMessage=function(l,d){return l.message||(l.message="HTTP "+l.status+"("+l.statusText+") : "+d),l},o._intercept=function(l){var d=l.data;return l.code&&((d=d||{}).data=l.data,d.code=l.code,d.description=l.description,d.message="0x"+Number(l.code).toString(16)+", "+l.description,d.tid&&(d.message+=", tid="+d.tid)),d},o}();a.ApiRequest=c},101:(n,a)=>{var c,o;Object.defineProperty(a,"__esModule",{value:!0}),a.SystemUtil=a.WindowsType=a.SystemType=void 0,function(d){d.Unknown="Unknown",d.MacOS="Mac",d.Windows="Windows",d.Android="Android",d.Iphone="iphone",d.Ipad="ipad",d.iOS="iOS",d.Linux="Linux",d.ChromeOS="ChromeOS"}(c=a.SystemType||(a.SystemType={})),function(d){d.Windows10="Windows 10",d.Windows7="Windows 7",d.WindowsVista="Windows vista",d.WindowsXP="Windows xp"}(o=a.WindowsType||(a.WindowsType={}));var l=function(){function d(){}return Object.defineProperty(d,"isMacOS",{get:function(){return c.MacOS===d.systemName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isWindows",{get:function(){return d.systemName.indexOf(c.Windows)>-1},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isIos",{get:function(){return c.Iphone===d.systemName||c.Ipad===d.systemName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isAndroid",{get:function(){return c.Android===d.systemName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isLinux",{get:function(){return c.Linux===d.systemName||c.Linux===d._platform},enumerable:!1,configurable:!0}),Object.defineProperty(d,"systemName",{get:function(){return d._getSystemInfo(),d._systemName},enumerable:!1,configurable:!0}),Object.defineProperty(d,"systemVersion",{get:function(){return d._getSystemInfo(),d._systemVersion},enumerable:!1,configurable:!0}),Object.defineProperty(d,"platform",{get:function(){return d._getSystemInfo(),d._platform},enumerable:!1,configurable:!0}),Object.defineProperty(d,"isUnknown",{get:function(){return!d.platform||d.platform===c.Unknown},enumerable:!1,configurable:!0}),d.compareVersion=function(h){if(d._getSystemInfo(),d._systemVersion){for(var u=d._systemVersion.split("."),p=h.split("."),f=0,m=0,g=0;g<u.length&&g<p.length;++g){if((f=isNaN(parseInt(u[g],10))?0:parseInt(u[g],10))<(m=isNaN(parseInt(p[g],10))?0:parseInt(p[g],10)))return!1;if(f>m)return!0}return!0}return!0},d._getSystemInfo=function(){if(!d._systemName||!d._systemVersion||!d._platform)if(navigator&&navigator.userAgent){var h=navigator.userAgent.toLowerCase();h.indexOf("ipad")>-1?(d._systemName=c.Ipad,d._platform=c.iOS,d._systemVersion=d._getIosSystemVersion(h)):h.indexOf("iphone")>-1?(d._systemName=c.Iphone,d._platform=c.iOS,d._systemVersion=d._getIosSystemVersion(h)):h.indexOf("android")>-1?(d._platform=c.Android,d._systemName=c.Android,d._systemVersion=d._getAndroidSystemVersion(h)):h.indexOf("win")>-1?h.indexOf("windwos nt 10")>-1||h.indexOf("windows 10")?(d._systemName=o.Windows10,d._platform=c.Windows,d._systemVersion="10"):h.indexOf("windows nt 6.1")>-1||h.indexOf("windows 7")>-1?(d._systemName=o.Windows7,d._platform=c.Windows,d._systemVersion="7"):h.indexOf("windows nt 6.0")>-1||h.indexOf("windows vista")>-1?(d._systemName=o.WindowsVista,d._platform=c.Windows,d._systemVersion="vista"):h.indexOf("widows nt 5.1")>-1||h.indexOf("windows xp")>-1?(d._systemName=o.WindowsXP,d._platform=c.Windows,d._systemVersion="xp"):(d._platform=c.Windows,d._systemName=c.Windows,d._systemVersion="0.0"):h.indexOf("mac")>-1?navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0?(d._systemName=c.Ipad,d._platform=c.iOS,d._systemVersion=d._getIosSystemVersion(h)):(d._platform=c.MacOS,d._systemName=c.MacOS,d._systemVersion=d._getMacSystemVersion(h)):h.indexOf("linux")>-1?(d._platform=c.Linux,d._systemName=c.Linux,d._systemVersion="0.0"):h.indexOf("cros")>-1?(d._platform=c.Linux,d._systemName=c.ChromeOS,d._systemVersion="0.0"):(d._systemName=c.Unknown,d._platform=c.Windows,d._systemVersion="0.0")}else d._systemName=c.Unknown,d._platform=c.Unknown,d._systemVersion="0.0"},d._getIosSystemVersion=function(h){return(h.match(/OS [\d._]*/gi)+"").replace(/[^0-9|_.]/gi,"").replace(/_/gi,".")},d._getMacSystemVersion=function(h){return(h.match(/OS X [\d._]*/gi)+"").replace(/[^0-9|_.]/gi,"").replace(/_/gi,".")},d._getAndroidSystemVersion=function(h){return h.substr(h.indexOf("android")+8,h.indexOf(";",h.indexOf("android"))-h.indexOf("android")-8)},d._systemName="",d._systemVersion="",d._platform=c.Unknown,d}();a.SystemUtil=l}},e={};function t(n){if(e[n])return e[n].exports;var a=e[n]={exports:{}};return r[n](a,a.exports,t),a.exports}var i={};return(()=>{var n=i;Object.defineProperty(n,"__esModule",{value:!0}),n.ApiRequest=n.LocalStorage=n.Guid=n.BrowserUtil=n.SystemUtil=void 0;var a=t(101);Object.defineProperty(n,"SystemUtil",{enumerable:!0,get:function(){return a.SystemUtil}});var c=t(622);Object.defineProperty(n,"BrowserUtil",{enumerable:!0,get:function(){return c.BrowserUtil}});var o=t(864);Object.defineProperty(n,"Guid",{enumerable:!0,get:function(){return o.Guid}});var l=t(442);Object.defineProperty(n,"LocalStorage",{enumerable:!0,get:function(){return l.LocalStorage}});var d=t(72);Object.defineProperty(n,"ApiRequest",{enumerable:!0,get:function(){return d.ApiRequest}}),window&&(window.SystemUtil=a.SystemUtil,window.BrowserUtil=c.BrowserUtil,window.Guid=o.Guid,window.LocalStorage=l.LocalStorage,window.ApiRequest=d.ApiRequest)})(),i})()})(nc);var G=nc.exports;let Lt=class{constructor(){this._eventMap={}}listeners(s){return this._eventMap[s]||[]}emit(s,...r){const e=this._eventMap[s];return!!Array.isArray(e)&&(e.forEach(t=>t.apply(this,r)),!0)}off(s,r){const e=this._eventMap[s];return Array.isArray(e)&&(this._eventMap[s]=e.filter(t=>t!==r)),this}removeAllListeners(s){return s===void 0?this._eventMap={}:this._eventMap[s]&&(this._eventMap[s]=[]),this}on(s,r){return this._eventMap[s]?this._eventMap[s].push(r):this._eventMap[s]=[r],this}once(s,r){const e=(...t)=>{this.off(s,e),r.apply(this,t)};return this.on(s,e),this}};class ac extends Lt{constructor(){super(),this.traceid="",this.id=G.Guid.create(32)}set traceId(r){this.traceid=r}get traceId(){return this.traceid}get mediaElement(){return this.element}setReporter(r){this.reporter=r}play(r){}stop(){this.traceid="",this.reporter=void 0}}var oc={exports:{}};(function(s){s.exports=(()=>{var r={304:(t,i,n)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.BrowserDeviceManager=void 0;var a=n(101),c=n(853),o=n(62),l=n(913),d=n(331),h=n(1),u=n(935),p=n(603),f=function(){function m(){this.systemUtil=new a.SystemUtil,this.deviceManager=this.createDeviceManager()}return m.prototype.getCameraList=function(){return this.deviceManager.getCameraList()},m.prototype.getMicList=function(){return this.deviceManager.getMicList()},m.prototype.getSpeakerList=function(){return this.deviceManager.getSpeakerList()},m.prototype.getAudioTrack=function(g){return this.deviceManager.getAudioTrack(g)},m.prototype.getVideoTrack=function(g){return this.deviceManager.getVideoTrack(g)},m.prototype.getAudioVideoTracks=function(g){return this.deviceManager.getAudioVideoTracks(g)},m.prototype.getScreenTrack=function(g){return this.deviceManager.getScreenTrack(g)},m.prototype.getAudioStream=function(g){return this.deviceManager.getAudioStream(g)},m.prototype.getVideoStream=function(g){return this.deviceManager.getVideoStream(g)},m.prototype.getScreenStream=function(g){return this.deviceManager.getScreenStream(g)},m.prototype.checkSupportScreenShare=function(){return this.deviceManager.checkSupportScreenShare()},m.prototype.createDeviceManager=function(){return this.systemUtil.isWindows?new u.WindowsDeviceManager:this.systemUtil.isAndroid?new c.AndroidDeviceManager:this.systemUtil.isIos?new l.IosDeviceManager:this.systemUtil.isMacOS?new h.MacDeviceManager:this.systemUtil.isLinux?new d.LinuxDeviceManager:new o.BaseDeviceManager},m.isDeviceManagerError=p.DeviceError.isDeviceManagerError,m}();i.BrowserDeviceManager=f},603:(t,i,n)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.DeviceError=i.DeviceErrorDescription=i.DeviceErrorCode=void 0;var a=n(610);(function(o){o[o.ERROR_DEVICE_UNKNOWNERROR=1e4]="ERROR_DEVICE_UNKNOWNERROR",o[o.ERROR_DEVICE_AUDIODEVICE_NOTFOUND=10001]="ERROR_DEVICE_AUDIODEVICE_NOTFOUND",o[o.ERROR_DEVICE_VIDEODEVICE_NOTFOUND=10002]="ERROR_DEVICE_VIDEODEVICE_NOTFOUND",o[o.ERROR_DEVICE_NOTFOUND=10020]="ERROR_DEVICE_NOTFOUND",o[o.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED=10003]="ERROR_DEVICE_AUDIODEVICE_NOTALLOWED",o[o.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED=10004]="ERROR_DEVICE_VIDEODEVICE_NOTALLOWED",o[o.ERROR_DEVICE_NOTALLOWED=10021]="ERROR_DEVICE_NOTALLOWED",o[o.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE=10005]="ERROR_DEVICE_AUDIODEVICE_NOTREADABLE",o[o.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE=10006]="ERROR_DEVICE_VIDEODEVICE_NOTREADABLE",o[o.ERROR_DEVICE_NOTREADABLE=10022]="ERROR_DEVICE_NOTREADABLE",o[o.ERROR_DEIVCE_CONSTRAINEDERROR=10007]="ERROR_DEIVCE_CONSTRAINEDERROR",o[o.ERROR_SCREENSHARE_UNKNOWNERRO=10010]="ERROR_SCREENSHARE_UNKNOWNERRO",o[o.ERROR_SCREENSHARE_NOTALLOWED=10011]="ERROR_SCREENSHARE_NOTALLOWED",o[o.ERROR_SCREENSHARE_ENDED=10012]="ERROR_SCREENSHARE_ENDED",o[o.ERROR_SCREENSHARE_NOPERMISSION=10013]="ERROR_SCREENSHARE_NOPERMISSION",o[o.ERROR_SCREENSHARE_INVALIDACCESS=10014]="ERROR_SCREENSHARE_INVALIDACCESS",o[o.ERROR_SCREENSHARE_NOTSUPPORT=10018]="ERROR_SCREENSHARE_NOTSUPPORT",o[o.ERROR_DEVICE_NOTSUPPORT=10019]="ERROR_DEVICE_NOTSUPPORT"})(i.DeviceErrorCode||(i.DeviceErrorCode={})),function(o){o.ERRORMESSAGE_DEVICENOTFOUND="Requested device not found",o.ERRORMESSAGE_DEVICENOTALLOWED="Permission denied",o.ERRORMESSAGE_MACCHROME_DEVICENOTREADABLE="Permission denied by system",o.ERRORMESSAGE_MACSAFARI_DEVICENOTALLOWED="The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.",o.ERRORMESSAGE_MOBILEDEVICE_NOTALLOWED="video device not allowed",o.ERRORMESSAGE_AUDIODEVICENOTREADABLE="Could not start audio source",o.ERRORMESSAGE_VIDEODEVICENOTREADABLE="Could not start video source",o.ERRORNAME_DEVICENOTFOUND="NotFoundError",o.ERRORNAME_DEVICENOTALLOWED="NotAllowedError",o.ERRORNAME_DEVICENOTREADABLE="NotReadableError",o.ERRORNAME_DEVICEOVERCONSTRAINED="OverconstrainedError",o.ERRORNAME_INVALID_ACCESS="InvalidAccessError"}(i.DeviceErrorDescription||(i.DeviceErrorDescription={}));var c=function(){function o(l,d){this.linkUtil=new a.LinkUtil,this.code=l,this.reason=d,this.relatedLink=this.linkUtil.getRelatedLink(l)}return o.isDeviceManagerError=function(l){return!!(l&&typeof l=="object"&&"code"in l&&"reason"in l)},o}();i.DeviceError=c},873:(t,i)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.DeviceType=i.MobileCameraType=void 0,function(n){n[n.USER=0]="USER",n[n.ENV=1]="ENV"}(i.MobileCameraType||(i.MobileCameraType={})),function(n){n.Camera="videoinput",n.Mic="audioinput",n.Mixed="audiovideoinput",n.Screen="screen",n.Speaker="audiooutput"}(i.DeviceType||(i.DeviceType={}))},853:function(t,i,n){var a,c=this&&this.__extends||(a=function(l,d){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,u){h.__proto__=u}||function(h,u){for(var p in u)Object.prototype.hasOwnProperty.call(u,p)&&(h[p]=u[p])})(l,d)},function(l,d){function h(){this.constructor=l}a(l,d),l.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)});Object.defineProperty(i,"__esModule",{value:!0}),i.AndroidDeviceManager=void 0;var o=function(l){function d(){return l.call(this)||this}return c(d,l),d}(n(583).MobileDeviceManager);i.AndroidDeviceManager=o},62:(t,i,n)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.BaseDeviceManager=void 0;var a=n(603),c=n(873),o=function(){function l(){}return l.prototype.checkSupportScreenShare=function(){return!!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia&&navigator.mediaDevices.getDisplayMedia)},l.prototype.getCameraList=function(){var d=this;return new Promise(function(h,u){d.checkSupport()?d.getDeviceRight(c.DeviceType.Camera).then(function(){d.getDeviceList(c.DeviceType.Camera).then(function(p){h(p)}).catch(function(p){u(d.parseError(c.DeviceType.Camera,p))})}).catch(function(p){u(d.parseError(c.DeviceType.Camera,p))}):u(new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_NOTSUPPORT,"not support navigator.mediaDevices"))})},l.prototype.getMicList=function(){var d=this;return new Promise(function(h,u){d.checkSupport()?d.getDeviceRight(c.DeviceType.Mic).then(function(){d.getDeviceList(c.DeviceType.Mic).then(function(p){h(p)}).catch(function(p){u(d.parseError(c.DeviceType.Mic,p))})}).catch(function(p){u(d.parseError(c.DeviceType.Mic,p))}):u(new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_NOTSUPPORT,"not support navigator.mediaDevices"))})},l.prototype.getSpeakerList=function(){var d=this;return new Promise(function(h,u){d.checkSupport()?d.getDeviceRight(c.DeviceType.Speaker).then(function(){d.getDeviceList(c.DeviceType.Speaker).then(function(p){h(p)}).catch(function(p){u(d.parseError(c.DeviceType.Speaker,p))})}).catch(function(p){u(d.parseError(c.DeviceType.Speaker,p))}):u(new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_NOTSUPPORT,"not support navigator.mediaDevices"))})},l.prototype.getAudioTrack=function(d){return this.getAudioStream(d).then(function(h){return h.getAudioTracks()[0]})},l.prototype.getAudioStream=function(d){var h=this;return new Promise(function(u,p){if(h.checkSupport()){var f=h.createAudioConstraints(d);navigator.mediaDevices.getUserMedia(f).then(function(m){u(m)}).catch(function(m){p(h.parseError(c.DeviceType.Mic,m))})}else p(new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_NOTSUPPORT,"not support navigator.mediaDevices"))})},l.prototype.getVideoTrack=function(d){return this.getVideoStream(d).then(function(h){return h.getVideoTracks()[0]})},l.prototype.getVideoStream=function(d){var h=this;return new Promise(function(u,p){if(h.checkSupport()){var f=h.createVideoConstraints(d);navigator.mediaDevices.getUserMedia(f).then(function(m){u(m)}).catch(function(m){p(h.parseError(c.DeviceType.Camera,m))})}else p(new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_NOTSUPPORT,"not support navigator.mediaDevices"))})},l.prototype.getAudioVideoTracks=function(d){return this.getMixedStream(d).then(function(h){return h.getTracks()})},l.prototype.getMixedStream=function(d){var h=this;return new Promise(function(u,p){if(h.checkSupport()){var f=h.createMixedConstraints(d);navigator.mediaDevices.getUserMedia(f).then(function(m){u(m)}).catch(function(m){p(h.parseError(c.DeviceType.Mixed,m))})}else p(new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_NOTSUPPORT,"not support navigator.mediaDevices"))})},l.prototype.getScreenTrack=function(d){return this.getScreenStream(d).then(function(h){return h.getTracks()})},l.prototype.getScreenStream=function(d){var h=this;return new Promise(function(u,p){h.checkSupportScreenShare()?navigator.mediaDevices.getDisplayMedia(d).then(function(f){u(f)}).catch(function(f){p(h.parseError(c.DeviceType.Screen,f))}):p(new a.DeviceError(a.DeviceErrorCode.ERROR_SCREENSHARE_NOTSUPPORT,"browser not support screenshare"))})},l.prototype.checkSupport=function(){return!!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices&&navigator.mediaDevices.getUserMedia)},l.prototype.getDeviceList=function(d){return new Promise(function(h,u){navigator.mediaDevices.enumerateDevices().then(function(p){var f=[];p.forEach(function(m){m.kind===d&&f.push(m)}),h(f)}).catch(function(p){u(p)})})},l.prototype.getDeviceRight=function(d){return new Promise(function(h,u){var p;c.DeviceType.Camera===d?p={video:!0}:c.DeviceType.Mic!==d&&c.DeviceType.Speaker!==d||(p={audio:!0}),navigator.mediaDevices.getUserMedia(p).then(function(f){f.getTracks().forEach(function(m){m.stop()}),h(void 0)}).catch(function(f){h(void 0)})})},l.prototype.parseError=function(d,h){var u=null;return c.DeviceType.Mic===d?u=this.parseAudioError(h):c.DeviceType.Camera===d?u=this.parseVideoError(h):c.DeviceType.Mixed===d?u=this.parseMixedError(h):c.DeviceType.Screen===d&&(u=this.parseScreenError(h)),u===null?new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_UNKNOWNERROR,""):u},l.prototype.parseAudioError=function(d){return d.message===a.DeviceErrorDescription.ERRORMESSAGE_DEVICENOTFOUND||d.name===a.DeviceErrorDescription.ERRORNAME_DEVICENOTFOUND?new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_AUDIODEVICE_NOTFOUND,"audio device not found"):d.message===a.DeviceErrorDescription.ERRORMESSAGE_DEVICENOTALLOWED||d.message===a.DeviceErrorDescription.ERRORMESSAGE_MACSAFARI_DEVICENOTALLOWED?new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED,"audio device not allowed"):d.message===a.DeviceErrorDescription.ERRORMESSAGE_MACCHROME_DEVICENOTREADABLE||d.message===a.DeviceErrorDescription.ERRORMESSAGE_AUDIODEVICENOTREADABLE||d.message===a.DeviceErrorDescription.ERRORNAME_DEVICENOTREADABLE?new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE,"audio device not readable"):null},l.prototype.parseVideoError=function(d){return d.message===a.DeviceErrorDescription.ERRORMESSAGE_DEVICENOTFOUND||d.name===a.DeviceErrorDescription.ERRORNAME_DEVICENOTFOUND?new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_VIDEODEVICE_NOTFOUND,"video device not found"):d.message===a.DeviceErrorDescription.ERRORMESSAGE_DEVICENOTALLOWED||d.message===a.DeviceErrorDescription.ERRORMESSAGE_MOBILEDEVICE_NOTALLOWED||d.message===a.DeviceErrorDescription.ERRORMESSAGE_MACSAFARI_DEVICENOTALLOWED?new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED,"video device not allowed"):d.message===a.DeviceErrorDescription.ERRORMESSAGE_MACCHROME_DEVICENOTREADABLE||d.message===a.DeviceErrorDescription.ERRORMESSAGE_VIDEODEVICENOTREADABLE||d.name===a.DeviceErrorDescription.ERRORNAME_DEVICENOTREADABLE?new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE,"video device not readable"):null},l.prototype.parseMixedError=function(d){return d.message===a.DeviceErrorDescription.ERRORMESSAGE_DEVICENOTFOUND||d.name===a.DeviceErrorDescription.ERRORNAME_DEVICENOTFOUND?new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_NOTFOUND,"audio or video device not found"):d.message===a.DeviceErrorDescription.ERRORMESSAGE_DEVICENOTALLOWED||d.message===a.DeviceErrorDescription.ERRORMESSAGE_MACSAFARI_DEVICENOTALLOWED?new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_NOTALLOWED,"audio or video device not allowed"):d.message===a.DeviceErrorDescription.ERRORMESSAGE_MOBILEDEVICE_NOTALLOWED?new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED,"video device not allowed"):d.message===a.DeviceErrorDescription.ERRORMESSAGE_MACCHROME_DEVICENOTREADABLE||d.name===a.DeviceErrorDescription.ERRORNAME_DEVICENOTREADABLE?new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_NOTREADABLE,"audio or video device not readable"):d.message===a.DeviceErrorDescription.ERRORMESSAGE_AUDIODEVICENOTREADABLE?new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE,"audio device not readable"):d.message===a.DeviceErrorDescription.ERRORMESSAGE_VIDEODEVICENOTREADABLE?new a.DeviceError(a.DeviceErrorCode.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE,"video device not readable"):null},l.prototype.parseScreenError=function(d){return d.name===a.DeviceErrorDescription.ERRORNAME_DEVICENOTALLOWED?d.message===a.DeviceErrorDescription.ERRORMESSAGE_DEVICENOTALLOWED?new a.DeviceError(a.DeviceErrorCode.ERROR_SCREENSHARE_NOTALLOWED,d.message):new a.DeviceError(a.DeviceErrorCode.ERROR_SCREENSHARE_NOPERMISSION,d.message):d.name===a.DeviceErrorDescription.ERRORNAME_INVALID_ACCESS?new a.DeviceError(a.DeviceErrorCode.ERROR_SCREENSHARE_INVALIDACCESS,d.message):null},l.prototype.createVideoConstraints=function(d){typeof d.deviceId=="string"&&(d.deviceId={exact:d.deviceId});var h={video:d};return Object.keys(d).length===0&&(h={video:!0}),h},l.prototype.createAudioConstraints=function(d){typeof d.deviceId=="string"&&(d.deviceId={exact:d.deviceId});var h={audio:d};return Object.keys(d).length===0&&(h={audio:!0}),h},l.prototype.createMixedConstraints=function(d){if(console.log("createMixedConstraints"),d.video&&typeof d.video=="object"){var h=d.video;typeof h.deviceId=="string"&&(h.deviceId={exact:h.deviceId})}if(d.audio&&typeof d.audio=="object"){var u=d.audio;typeof u.deviceId=="string"&&(u.deviceId={exact:u.deviceId})}return d},l}();i.BaseDeviceManager=o},913:function(t,i,n){var a,c=this&&this.__extends||(a=function(l,d){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,u){h.__proto__=u}||function(h,u){for(var p in u)Object.prototype.hasOwnProperty.call(u,p)&&(h[p]=u[p])})(l,d)},function(l,d){function h(){this.constructor=l}a(l,d),l.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)});Object.defineProperty(i,"__esModule",{value:!0}),i.IosDeviceManager=void 0;var o=function(l){function d(){return l.call(this)||this}return c(d,l),d}(n(583).MobileDeviceManager);i.IosDeviceManager=o},331:function(t,i,n){var a,c=this&&this.__extends||(a=function(l,d){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,u){h.__proto__=u}||function(h,u){for(var p in u)Object.prototype.hasOwnProperty.call(u,p)&&(h[p]=u[p])})(l,d)},function(l,d){function h(){this.constructor=l}a(l,d),l.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)});Object.defineProperty(i,"__esModule",{value:!0}),i.LinuxDeviceManager=void 0;var o=function(l){function d(){return l.call(this)||this}return c(d,l),d}(n(62).BaseDeviceManager);i.LinuxDeviceManager=o},1:function(t,i,n){var a,c=this&&this.__extends||(a=function(l,d){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,u){h.__proto__=u}||function(h,u){for(var p in u)Object.prototype.hasOwnProperty.call(u,p)&&(h[p]=u[p])})(l,d)},function(l,d){function h(){this.constructor=l}a(l,d),l.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)});Object.defineProperty(i,"__esModule",{value:!0}),i.MacDeviceManager=void 0;var o=function(l){function d(){return l.call(this)||this}return c(d,l),d}(n(62).BaseDeviceManager);i.MacDeviceManager=o},583:function(t,i,n){var a,c=this&&this.__extends||(a=function(d,h){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,p){u.__proto__=p}||function(u,p){for(var f in p)Object.prototype.hasOwnProperty.call(p,f)&&(u[f]=p[f])})(d,h)},function(d,h){function u(){this.constructor=d}a(d,h),d.prototype=h===null?Object.create(h):(u.prototype=h.prototype,new u)});Object.defineProperty(i,"__esModule",{value:!0}),i.MobileDeviceManager=void 0;var o=n(603),l=function(d){function h(){return d.call(this)||this}return c(h,d),h.prototype.checkSupportScreenShare=function(){return!1},h.prototype.getScreenTrack=function(u){return new Promise(function(p,f){f(new o.DeviceError(o.DeviceErrorCode.ERROR_SCREENSHARE_NOTSUPPORT,"mobile not support screenshare"))})},h.prototype.getScreenStream=function(u){return new Promise(function(p,f){f(new o.DeviceError(o.DeviceErrorCode.ERROR_SCREENSHARE_NOTSUPPORT,"mobile not support screenshare"))})},h}(n(62).BaseDeviceManager);i.MobileDeviceManager=l},935:function(t,i,n){var a,c=this&&this.__extends||(a=function(l,d){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,u){h.__proto__=u}||function(h,u){for(var p in u)Object.prototype.hasOwnProperty.call(u,p)&&(h[p]=u[p])})(l,d)},function(l,d){function h(){this.constructor=l}a(l,d),l.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)});Object.defineProperty(i,"__esModule",{value:!0}),i.WindowsDeviceManager=void 0;var o=function(l){function d(){return l.call(this)||this}return c(d,l),d}(n(62).BaseDeviceManager);i.WindowsDeviceManager=o},607:function(t,i,n){var a=this&&this.__createBinding||(Object.create?function(l,d,h,u){u===void 0&&(u=h),Object.defineProperty(l,u,{enumerable:!0,get:function(){return d[h]}})}:function(l,d,h,u){u===void 0&&(u=h),l[u]=d[h]}),c=this&&this.__exportStar||function(l,d){for(var h in l)h==="default"||Object.prototype.hasOwnProperty.call(d,h)||a(d,l,h)};Object.defineProperty(i,"__esModule",{value:!0}),i.BrowserDeviceManager=void 0;var o=n(304);Object.defineProperty(i,"BrowserDeviceManager",{enumerable:!0,get:function(){return o.BrowserDeviceManager}}),c(n(873),i),window&&(window.BrowserDeviceManager=o.BrowserDeviceManager)},610:(t,i,n)=>{Object.defineProperty(i,"__esModule",{value:!0}),i.LinkUtil=void 0;var a,c=n(603),o=n(261),l=n(54);(function(f){f[f.Windows=0]="Windows",f[f.MacOS=1]="MacOS",f[f.Other=2]="Other"})(a||(a={}));var d="ms-settings:",h="x-apple.systempreferences:com.apple.preference.security?",u={SYS_MIC:[d+"privacy-microphone",h+"Privacy_Microphone"],SYS_CAMERA:[d+"privacy-webcam",h+"Privacy_Camera"],SYS_SCREENSHARE:["",h+"Privacy_ScreenCapture"]},p=function(){function f(){o||console.error("SystemUtil is not found"),this.systemType=this.getSystemType()}return f.prototype.getRelatedLink=function(m){var g="",S=this.systemType;switch(m){case c.DeviceErrorCode.ERROR_DEVICE_AUDIODEVICE_NOTFOUND:case c.DeviceErrorCode.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE:g=u.SYS_MIC[S];break;case c.DeviceErrorCode.ERROR_DEVICE_VIDEODEVICE_NOTFOUND:case c.DeviceErrorCode.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE:g=u.SYS_CAMERA[S];break;case c.DeviceErrorCode.ERROR_SCREENSHARE_UNKNOWNERRO:case c.DeviceErrorCode.ERROR_SCREENSHARE_NOPERMISSION:g=u.SYS_SCREENSHARE[S];break;case c.DeviceErrorCode.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED:case c.DeviceErrorCode.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED:case c.DeviceErrorCode.ERROR_DEVICE_NOTALLOWED:l.isChrome?g=this.getChromeResetLink():l.isEdge&&(g=this.getEdgeResetLink());break;default:g=""}return g},f.prototype.getSystemType=function(){return o.isWindows?a.Windows:o.isMacOS?a.MacOS:a.Other},f.prototype.getChromeResetLink=function(){return"chrome://settings/content/siteDetails?site="+encodeURIComponent(window.location.origin)},f.prototype.getEdgeResetLink=function(){return"edge://settings/content/siteDetails?site="+encodeURIComponent(window.location.origin)},f}();i.LinkUtil=p},101:(t,i)=>{var n;Object.defineProperty(i,"__esModule",{value:!0}),i.SystemUtil=void 0,function(c){c[c.Unknown=0]="Unknown",c[c.MacOS=1]="MacOS",c[c.Windows=2]="Windows",c[c.Android=3]="Android",c[c.Iphone=4]="Iphone",c[c.Ipad=5]="Ipad",c[c.Linux=6]="Linux"}(n||(n={}));var a=function(){function c(){this.systemType=n.Unknown,this.getSystemInfo()}return Object.defineProperty(c.prototype,"isIos",{get:function(){return this.systemType===n.Ipad||this.systemType===n.Iphone},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"isAndroid",{get:function(){return this.systemType===n.Android},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"isMacOS",{get:function(){return this.systemType===n.MacOS},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"isWindows",{get:function(){return this.systemType===n.Windows},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"isLinux",{get:function(){return this.systemType===n.Linux},enumerable:!1,configurable:!0}),c.prototype.getSystemInfo=function(){if(navigator&&navigator.userAgent){var o=navigator.userAgent.toLocaleLowerCase();o.indexOf("ipad")>-1?this.systemType=n.Ipad:o.indexOf("iphone")>-1?this.systemType=n.Iphone:o.indexOf("android")>-1?this.systemType=n.Android:o.indexOf("win")>-1?this.systemType=n.Windows:o.indexOf("mac")>-1?this.systemType=n.MacOS:o.indexOf("linux")>-1?this.systemType=n.Linux:o.indexOf("")>-1&&(this.systemType=n.Unknown)}},c}();i.SystemUtil=a},54:t=>{t.exports=window.BrowserUtil},261:t=>{t.exports=window.SystemUtil}},e={};return function t(i){if(e[i])return e[i].exports;var n=e[i]={exports:{}};return r[i].call(n.exports,n,n.exports,t),n.exports}(607)})()})(oc);var Gi=oc.exports,H=(s=>(s[s.ERROR_DEVICE_UNKNOWNERROR=1e4]="ERROR_DEVICE_UNKNOWNERROR",s[s.ERROR_DEVICE_AUDIODEVICE_NOTFOUND=10001]="ERROR_DEVICE_AUDIODEVICE_NOTFOUND",s[s.ERROR_DEVICE_VIDEODEVICE_NOTFOUND=10002]="ERROR_DEVICE_VIDEODEVICE_NOTFOUND",s[s.ERROR_DEVICE_NOTFOUND=10020]="ERROR_DEVICE_NOTFOUND",s[s.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED=10003]="ERROR_DEVICE_AUDIODEVICE_NOTALLOWED",s[s.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED=10004]="ERROR_DEVICE_VIDEODEVICE_NOTALLOWED",s[s.ERROR_DEVICE_NOTALLOWED=10021]="ERROR_DEVICE_NOTALLOWED",s[s.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE=10005]="ERROR_DEVICE_AUDIODEVICE_NOTREADABLE",s[s.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE=10006]="ERROR_DEVICE_VIDEODEVICE_NOTREADABLE",s[s.ERROR_DEVICE_NOTREADABLE=10022]="ERROR_DEVICE_NOTREADABLE",s[s.ERROR_DEIVCE_CONSTRAINEDERROR=10007]="ERROR_DEIVCE_CONSTRAINEDERROR",s[s.ERROR_SCREENSHARE_UNKNOWNERRO=10010]="ERROR_SCREENSHARE_UNKNOWNERRO",s[s.ERROR_SCREENSHARE_NOTALLOWED=10011]="ERROR_SCREENSHARE_NOTALLOWED",s[s.ERROR_SCREENSHARE_ENDED=10012]="ERROR_SCREENSHARE_ENDED",s[s.ERROR_SCREENSHARE_NOPERMISSION=10013]="ERROR_SCREENSHARE_NOPERMISSION",s[s.ERROR_SCREENSHARE_INVALIDACCESS=10014]="ERROR_SCREENSHARE_INVALIDACCESS",s[s.ERROR_SCREENSHARE_NOTSUPPORT=10018]="ERROR_SCREENSHARE_NOTSUPPORT",s[s.ERROR_DEVICE_NOTSUPPORT=10019]="ERROR_DEVICE_NOTSUPPORT",s[s.ERROR_SIGNAL_ERROR=10101]="ERROR_SIGNAL_ERROR",s[s.ERROR_PLAY_FAILED=10102]="ERROR_PLAY_FAILED",s[s.ERROR_NOTSUPPORT_WEBRTC=10110]="ERROR_NOTSUPPORT_WEBRTC",s[s.ERROR_BROWSER_NOTSUPPORT=10111]="ERROR_BROWSER_NOTSUPPORT",s[s.ERROR_BROWSER_VERSIONLOW=10112]="ERROR_BROWSER_VERSIONLOW",s[s.ERROR_NOTSUPPORT_H264=10113]="ERROR_NOTSUPPORT_H264",s[s.ERROR_CREATEOFFER=10114]="ERROR_CREATEOFFER",s[s.ERROR_NO_DATACHANNEL=10115]="ERROR_NO_DATACHANNEL",s[s.ERROR_INIT_LOCAL_FAIL=10116]="ERROR_INIT_LOCAL_FAIL",s[s.ERROR_HEMLELEMENT_NOTMATCH=10125]="ERROR_HEMLELEMENT_NOTMATCH",s[s.ERROR_AUTOPLAY_ERROR=10201]="ERROR_AUTOPLAY_ERROR",s[s.ERROR_PLAY_URL=10202]="ERROR_PLAY_URL",s[s.ERROR_SUBSCRIBE_NOTHING=10203]="ERROR_SUBSCRIBE_NOTHING",s[s.ERROR_HTMLELEMENT_ERROR=10204]="ERROR_HTMLELEMENT_ERROR",s[s.ERROR_HTTPREQUEST_ERROR=10205]="ERROR_HTTPREQUEST_ERROR",s[s.ERROR_ANSWER_ERROR=10206]="ERROR_ANSWER_ERROR",s[s.ERROR_INBOUND_TIMEOUT=10207]="ERROR_INBOUND_TIMEOUT",s[s.ERROR_STREAM_ENDED=10208]="ERROR_STREAM_ENDED",s[s.ERROR_PC_DISCONNECTED=10209]="ERROR_PC_DISCONNECTED",s[s.ERROR_TRANSPORT_CLOSED=10210]="ERROR_TRANSPORT_CLOSED",s[s.ERROR_SIGNAL_URL=10211]="ERROR_SIGNAL_URL",s[s.ERROR_IP_MIGRATE=10212]="ERROR_IP_MIGRATE",s[s.ERROR_PUBLISH_URL=10300]="ERROR_PUBLISH_URL",s[s.ERROR_PUBLISH_NOAUDIO=10301]="ERROR_PUBLISH_NOAUDIO",s[s.ERROR_PUBLISH_NOSTREAM=10302]="ERROR_PUBLISH_NOSTREAM",s[s.ERROR_DATACHANNEL_PARAM=10500]="ERROR_DATACHANNEL_PARAM",s[s.ERROR_DATACHANNEL_OPEN=10501]="ERROR_DATACHANNEL_OPEN",s[s.ERROR_MEDIASTREAMTRACK_TYPE_ERROR=11e3]="ERROR_MEDIASTREAMTRACK_TYPE_ERROR",s[s.ERROR_MEDIASTREAMTRACK_KIND_ERROR=11001]="ERROR_MEDIASTREAMTRACK_KIND_ERROR",s[s.ERROR_MEDIASTREAMTRACK_AUDIO_NONE=11002]="ERROR_MEDIASTREAMTRACK_AUDIO_NONE",s[s.ERROR_CUSTOMSTREAM_NONE=11003]="ERROR_CUSTOMSTREAM_NONE",s[s.ERROR_CUSTOMSTREAM_INVALID=11004]="ERROR_CUSTOMSTREAM_INVALID",s[s.ERROR_CUSTOMSTREAM_TRACK_NONE=11005]="ERROR_CUSTOMSTREAM_TRACK_NONE",s[s.ERROR_PREERCONNECTION_UNKNOWN=12e3]="ERROR_PREERCONNECTION_UNKNOWN",s[s.ERROR_SUBADD_NO_RESULT=13e3]="ERROR_SUBADD_NO_RESULT",s[s.ERROR_PUBADD_NO_RESULT=13001]="ERROR_PUBADD_NO_RESULT",s[s.ERROR_SINGLE_PC_STREAM_ERROR=13100]="ERROR_SINGLE_PC_STREAM_ERROR",s[s.ERROR_SINGLE_PC_STREAM_RECONNECT_FAILED=13101]="ERROR_SINGLE_PC_STREAM_RECONNECT_FAILED",s[s.ERROR_SINGLE_PC_FULL_RECONNECT=13102]="ERROR_SINGLE_PC_FULL_RECONNECT",s[s.ERROR_SINGLE_PC_FULL_RECONNECT_HTTP_FAILED=13103]="ERROR_SINGLE_PC_FULL_RECONNECT_HTTP_FAILED",s))(H||{});const Kh=[10207,10208,10209],cc=[10201,10202,10203,10204,10125,10300,10301,10302],Jh=[10209,10210];let ie=class{constructor(s,r,e,t){this.errorCode=s,this.errorCodeName=H[s],this.message=r,this.traceId=e,t&&(this.extraInfo=t)}renameCode(s){this.errorCode=s,this.errorCodeName=H[s]}};const mr=new Map;mr.set("480p_1",{width:640,height:480,frameRate:5,maxBitrate:300}),mr.set("480p_2",{width:640,height:480,frameRate:30,maxBitrate:1e3}),mr.set("720p_1",{width:1280,height:720,frameRate:5,maxBitrate:800}),mr.set("720p_2",{width:1280,height:720,frameRate:30,maxBitrate:2e3}),mr.set("1080p_1",{width:1920,height:1080,frameRate:5,maxBitrate:1e3}),mr.set("1080p_2",{width:1920,height:1080,frameRate:30,maxBitrate:3e3});const me=new Map;me.set("120p_1",{width:160,height:120,frameRate:15,maxBitrate:65}),me.set("120p_3",{width:120,height:120,frameRate:15,maxBitrate:50}),me.set("180p_1",{width:320,height:180,frameRate:15,maxBitrate:140}),me.set("180p_3",{width:180,height:180,frameRate:15,maxBitrate:100}),me.set("180p_4",{width:240,height:180,frameRate:15,maxBitrate:120}),me.set("240p_1",{width:320,height:240,frameRate:15,maxBitrate:200}),me.set("240p_3",{width:240,height:240,frameRate:15,maxBitrate:140}),me.set("240p_4",{width:424,height:240,frameRate:15,maxBitrate:220}),me.set("360p_1",{width:640,height:360,frameRate:15,maxBitrate:400}),me.set("360p_3",{width:360,height:360,frameRate:15,maxBitrate:260}),me.set("360p_4",{width:640,height:360,frameRate:30,maxBitrate:600}),me.set("360p_6",{width:360,height:360,frameRate:30,maxBitrate:400}),me.set("360p_7",{width:480,height:360,frameRate:15,maxBitrate:320}),me.set("360p_8",{width:480,height:360,frameRate:30,maxBitrate:490}),me.set("360p_9",{width:640,height:360,frameRate:15,maxBitrate:800}),me.set("360p_10",{width:640,height:360,frameRate:24,maxBitrate:800}),me.set("360p_11",{width:640,height:360,frameRate:24,maxBitrate:1e3}),me.set("480p_1",{width:640,height:480,frameRate:15,maxBitrate:500}),me.set("480p_2",{width:640,height:480,frameRate:30,maxBitrate:1e3}),me.set("480p_3",{width:480,height:480,frameRate:15,maxBitrate:400}),me.set("480p_4",{width:640,height:480,frameRate:30,maxBitrate:750}),me.set("480p_6",{width:480,height:480,frameRate:30,maxBitrate:600}),me.set("480p_8",{width:848,height:480,frameRate:15,maxBitrate:610}),me.set("480p_9",{width:848,height:480,frameRate:30,maxBitrate:930}),me.set("480p_10",{width:640,height:480,frameRate:10,maxBitrate:400}),me.set("720p_1",{width:1280,height:720,frameRate:15,maxBitrate:1130}),me.set("720p_2",{width:1280,height:720,frameRate:30,maxBitrate:2e3}),me.set("720p_3",{width:1280,height:720,frameRate:30,maxBitrate:1710}),me.set("720p_5",{width:960,height:720,frameRate:15,maxBitrate:910}),me.set("720p_6",{width:960,height:720,frameRate:30,maxBitrate:1380}),me.set("1080p_1",{width:1920,height:1080,frameRate:15,maxBitrate:2080}),me.set("1080p_2",{width:1920,height:1080,frameRate:30,maxBitrate:3e3}),me.set("1080p_3",{width:1920,height:1080,frameRate:30,maxBitrate:3150}),me.set("1080p_5",{width:1920,height:1080,frameRate:60,maxBitrate:4780}),me.set("1440p_1",{width:2560,height:1440,frameRate:30,maxBitrate:4850}),me.set("1440p_2",{width:2560,height:1440,frameRate:60,maxBitrate:7350}),me.set("4K_1",{width:3840,height:2160,frameRate:30,maxBitrate:8910}),me.set("4K_3",{width:3840,height:2160,frameRate:60,maxBitrate:13500});const Xr=new Map;Xr.set("standard",{sampleRate:48e3,channelCount:1,maxBitrate:64}),Xr.set("high",{sampleRate:48e3,channelCount:1,maxBitrate:128}),Xr.set("standard-stereo",{sampleRate:48e3,channelCount:2,maxBitrate:80}),Xr.set("high-stereo",{sampleRate:48e3,channelCount:2,maxBitrate:192});let $h=class{constructor(s){this.useGainNode=!0,this.audioContext=new AudioContext,this.audioDestination=this.audioContext.createMediaStreamDestination(),this.audioSource=[],this.gainNode=null,this.audioTrack=null,this.audioTrackArr=s.trackList||[],this.useGainNode=typeof s.useGainNode!="boolean"||s.useGainNode,this.useGainNode&&(this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.gainNode.gain.value=0),this.getMixedAudioTrack()}destroy(){var s;(s=this.getMixedAudioTrack())==null||s.stop(),this.disconnectSourceNode(),this.audioContext.close(),this.audioTrackArr=[]}updateTrackList(s){s.length&&(this.disconnectSourceNode(),this.audioTrackArr=s,this.connectNode())}getMixedAudioTrack(){return this.audioTrack||(this.connectNode(),this.audioTrack=this.audioDestination.stream.getAudioTracks()[0]),this.audioTrack}connectNode(){this.audioTrackArr.forEach(s=>{let r=new MediaStream;r.addTrack(s);const e=this.audioContext.createMediaStreamSource(r);this.gainNode&&e.connect(this.gainNode),this.audioSource.push(e)}),this.audioSource.forEach(s=>{s.connect(this.audioDestination)})}disconnectSourceNode(){this.audioSource.forEach(s=>{this.gainNode&&s.disconnect(this.gainNode),s.disconnect(this.audioDestination)}),this.audioSource=[]}};class Xh{constructor(r){this.video=r.video,this.canvas=r.canvas,this.ctx=this.canvas.getContext("2d")}render(){var t,i;const r=this.video,e=this.canvas;r&&e&&((t=this.ctx)==null||t.clearRect(0,0,e.width,e.height),(i=this.ctx)==null||i.drawImage(r,0,0,1*r.videoWidth,1*r.videoHeight),this.requestId=requestAnimationFrame(this.render.bind(this)))}stop(){this.requestId&&cancelAnimationFrame(this.requestId)}}class Zh{constructor(r){this.video=r.video,this.canvas=this.initCanvas(),this.activeRenderer=this.initRenderer()}get mediaStream(){var r;return this.ms||(this.ms=((r=this.canvas)==null?void 0:r.captureStream())||void 0),this.ms}start(){this.render()}stop(){this.activeRenderer.stop()}initCanvas(){const r=document.createElement("canvas"),e=this.video;return r.width=1*e.videoWidth,r.height=1*e.videoHeight,r}initRenderer(){let r;return r=new Xh({video:this.video,canvas:this.canvas}),r}render(){this.activeRenderer.render()}resize(r,e){this.canvas&&(this.canvas.width=r,this.canvas.height=e)}}const gi=(s,r)=>s&&r?Number(s)/Number(r)*1e3:-1,Yh=(s,r)=>{let e=s||"";return e=e.replace("@subaudio=no","").replace("@subvideo=no",""),r&&(e=e.split("?")[0]),e},Qh=(s,r,e,t,i)=>{let n=0;if(!navigator.onLine)return n=6,n;const a=[{loss:0,rtt:0,jbd:1},{loss:0,rtt:1,jbd:0},{loss:0,rtt:.5,jbd:.5},{loss:1,rtt:0,jbd:0},{loss:.8,rtt:0,jbd:.2},{loss:.8,rtt:.2,jbd:0},{loss:.6,rtt:.2,jbd:.2}];let c=-1,o=-1,l=-1;if(typeof r=="number"&&r>=0||typeof e=="number"&&e>=0){c=0;let h=!1,u=!1;typeof r=="number"&&r>=0&&(c+=r,h=!0),typeof e=="number"&&e>=0&&(c+=e,u=!0),h&&!u&&(c*=2),u&&!h&&(c*=1.8)}typeof s=="number"&&s>=0&&(l=s),(typeof t=="number"&&t>=0||typeof i=="number"&&i>=0)&&(o=0,typeof t=="number"&&t>=0&&(o+=t),typeof i=="number"&&i>=0&&(o+=i));let d=0;if(d=4*(c!==-1?1:0)+2*(l!==-1?1:0)+(o!==-1?1:0),d>0){let h=1.2*c*a[d-1].loss+l/1500*a[d-1].rtt+o/3e3*a[d-1].jbd;n=h<=.1?1:h<=.23?2:h<=.36?3:h<=.49?4:5}else n=0;return n},Gt=(...s)=>{window.RTS_HEBT_DEBUG&&console.log("[rts hebt]",...s)};function zi(s){return s.replace(/([A-Za-z])/,r=>r.toLowerCase())}function Us(s){return s.replace(/_([a-z])/g,(r,e)=>e.toUpperCase())}class qh extends ac{constructor(){super(),this.screenSurfaceType="",this.VideoProfileMap=new Map(me),this.ScreenProfileMap=new Map(mr),this.AudioProfileMap=new Map(Xr),this.deviceManager=new Gi.BrowserDeviceManager,this.mediastream=new MediaStream,this.hasVideo=!1,this.hasScreen=!1,this.videoProfile="360p_1",this.screenProfile="720p_1",this.audioProfile="standard",this.isCustomStream=!1,this.handleVideoTrackEnded=this.handleVideoTrackEnded.bind(this),this.handleAudioTrackEnded=this.handleAudioTrackEnded.bind(this)}get mediaStream(){return this.mediastream}get audioTrack(){return this.audiotrack}get videoTrack(){return this.videotrack}get hasAudio(){return!!this.audioTrack}getVideoProfile(){if(this.hasVideo)return this.videoProfile}getScreenProfile(){if(this.hasScreen)return this.screenProfile}getAudioProfile(){if(this.hasAudio)return this.audioProfile}init(r){return r.custom?this.createCustomStream(r.mediaStream):this.initWithRetry(r)}initWithRetry(r,e,t){return new Promise((i,n)=>{i=e||i,n=t||n;let a=[];r.audio&&r.video?a.push(this.initMicCamera(r)):(a.push(this.initMicAudio(r)),a.push(this.initCameraVideo(r))),r.video||a.push(this.initScreenVideoAudio(r)),Promise.all(a).then(()=>{this.tryMixMicAndScreenAudio(r),this.initTracks(r),r.skipProfile?i():this.tryToSetProfile(r).then(()=>{i()}).catch(c=>{console.log(c),this.resetLocalStream(),this.initWithRetry(Q(D({},r),{skipProfile:!0}),i,n)})}).catch(c=>{this.stopAllTracks(),n(c)})})}initMicAudio(r){return new Promise((e,t)=>{if(!r||!r.audio)return e();let i=typeof r.audio=="boolean"?{}:r.audio;this.deviceManager.getAudioTrack(i).then(n=>{this.micAudioTrack=n,this.audiotrack=n,e()}).catch(n=>{t(new ie(n.code,n.reason,"",n.relatedLink))})})}initCameraVideo(r){return new Promise((e,t)=>{if(!r||!r.video)return e();let i=typeof r.video=="boolean"?{}:r.video;this.deviceManager.getVideoTrack(i).then(n=>{this.videotrack=n,this.hasVideo=!0,e()}).catch(n=>{t(new ie(n.code,n.reason,"",n.relatedLink))})})}initMicCamera(r){return new Promise((e,t)=>{const i={video:r.video,audio:r.audio};this.deviceManager.getAudioVideoTracks(i).then(n=>{this.videotrack=n.find(a=>a.kind==="video"),this.hasVideo=!!this.videotrack,this.audiotrack=this.micAudioTrack=n.find(a=>a.kind==="audio"),e()}).catch(n=>{t(new ie(n.code,n.reason,"",n.relatedLink))})})}initScreenVideoAudio(r){return new Promise((e,t)=>{if(!r||!r.screen)return e();let i=!0,n=!1,a={};if(typeof r.screen!="boolean"){const c=r.screen,{video:o,audio:l}=c;a=jt(c,["video","audio"]),i=typeof o!="object"||o,typeof l!="boolean"&&typeof l!="object"||(n=l)}G.SystemUtil.isMacOS&&G.BrowserUtil.isSafari&&["16.1","16.2","16.3"].indexOf(G.BrowserUtil.browserVersion)>-1&&typeof i=="object"&&(typeof i.width=="number"&&(i.width={max:i.width}),typeof i.height=="number"&&(i.height={max:i.height})),this.deviceManager.getScreenStream(D({video:i,audio:n},a)).then(o=>{this.videotrack=o.getVideoTracks()[0],this.videotrack&&this.videotrack.getSettings&&(this.screenSurfaceType=this.videotrack.getSettings().displaySurface),this.hasScreen=!0;const l=o.getAudioTracks()[0];l&&(this.screenAudioTrack=l),e()}).catch(o=>{t(new ie(o.code,o.reason,"",o.relatedLink))})})}tryMixMicAndScreenAudio(r){r.audio&&this.micAudioTrack&&this.hasScreenAudioConfig(r)&&this.screenAudioTrack?(this.audioMixer||(this.audioMixer=new $h({useGainNode:!1,trackList:[]})),this.audioMixer.updateTrackList([this.screenAudioTrack,this.micAudioTrack]),this.audiotrack=this.audioMixer.getMixedAudioTrack()):r.audio&&this.micAudioTrack?this.audiotrack=this.micAudioTrack:this.hasScreenAudioConfig(r)&&this.screenAudioTrack&&(this.audiotrack=this.screenAudioTrack)}initTracks(r){this.hasAudioTrackReady(r)&&this.audiotrack&&this.mediastream.addTrack(this.audiotrack),this.hasVideoTrackReady(r)&&this.videotrack&&this.mediastream.addTrack(this.videotrack),this.addTrackListener()}tryToSetProfile(r){return new Promise((e,t)=>_(this,null,function*(){try{r.video?yield this.setVideoProfile(this.videoProfile):r.screen&&this.setScreenProfile(this.screenProfile).catch(i=>{console.log(i)}),e()}catch(i){t(new ie(H.ERROR_DEIVCE_CONSTRAINEDERROR,"apply constraint failed","",{originErr:i,config:r}))}}))}stopAllTracks(){this.screenAudioTrack&&(this.screenAudioTrack.stop(),this.screenAudioTrack=void 0),this.micAudioTrack&&(this.micAudioTrack.stop(),this.micAudioTrack=void 0),this.audioTrack&&(this.audioTrack.stop(),this.audiotrack=void 0),this.videoTrack&&(this.videoTrack.stop(),this.videotrack=void 0)}resetLocalStream(){this.deviceManager=new Gi.BrowserDeviceManager,this.mediastream=new MediaStream,this.hasVideo=!1,this.hasScreen=!1,this.videoProfile="360p_1",this.screenProfile="720p_1",this.isCustomStream=!1,this.stopAllTracks(),this.audioMixer=void 0,this.screenSurfaceType=""}setEncodeParam(r,e){this.pc=r;let t=!1,i=!1;e?e==="video"?t=!0:e==="audio"&&(i=!0):t=i=!0,r.getSenders().forEach(n=>{const{track:a}=n;!a||a.kind!=="video"&&a.kind!=="audio"||(a.kind==="video"&&t&&this.setVideoEncodeParams(n),a.kind==="audio"&&i&&this.setAudioEncodeParams(n))})}setVideoEncodeParams(r){var i,n;if(((i=r.track)==null?void 0:i.id)!==((n=this.videoTrack)==null?void 0:n.id))return;let e;if(this.hasVideo?e=this.VideoProfileMap.get(this.videoProfile):this.hasScreen&&(e=this.ScreenProfileMap.get(this.screenProfile)),!e||!r.setParameters||!r.getParameters)return;let t=r.getParameters();t.degradationPreference="maintain-resolution",t.encodings.forEach(a=>{e!=null&&e.maxBitrate&&(a.maxBitrate=1024*e.maxBitrate),e!=null&&e.frameRate&&(a.maxFramerate=e.frameRate)}),r.setParameters(t)}setAudioEncodeParams(r){var i,n;if(((i=r.track)==null?void 0:i.id)!==((n=this.audioTrack)==null?void 0:n.id))return;const e=this.AudioProfileMap.get(this.audioProfile);if(!e||!r.setParameters||!r.getParameters)return;let t=r.getParameters();t.encodings.forEach(a=>{e.maxBitrate&&(a.maxBitrate=1024*e.maxBitrate)}),r.setParameters(t)}play(r,e){var t;if((t=this.reporter)==null||t.reportPlay(r?r.nodeName:String(r)),r&&(this.element=r,this.mediastream)){if(this.element.srcObject=this.mediastream,(G.SystemUtil.isIos&&G.SystemUtil.systemVersion.indexOf("15.1")===0&&(G.BrowserUtil.isSafari||G.BrowserUtil.isChrome||G.BrowserUtil.isMicroMessenger)||e!=null&&e.canvasStream)&&this.hasVideo){if(this.canvasRenderer)return;this.canvasRenderer=new Zh({video:this.element});let i=this;this.element.addEventListener("loadeddata",function n(){if(!i.element||(i.element.removeEventListener("loadeddata",n),!i.canvasRenderer))return;i.canvasRenderer.start();const a=i.canvasRenderer.mediaStream;a&&(i.mediastream=a,i.videotrack=a.getVideoTracks()[0])}),this.element.addEventListener("resize",()=>{var a;if(!this)return;const n=this.element;n&&((a=this.canvasRenderer)==null||a.resize(n.videoWidth,n.videoHeight))})}if(e&&e.autoplay===!1)return;this.element.play()}}setVideoProfile(r){return new Promise((e,t)=>_(this,null,function*(){var n;(n=this.reporter)==null||n.reportVideoProfile(r);let i=this.VideoProfileMap.get(r);if(i){if(!this.isCustomStream&&this.hasVideo&&this.videotrack&&this.videotrack.applyConstraints)try{yield this.videotrack.applyConstraints(i)}catch(a){return t(a)}this.videoProfile=r,this.pc&&this.setEncodeParam(this.pc,"video"),e(this.videoProfile)}else t("Profile not found")}))}setScreenProfile(r){return new Promise((e,t)=>_(this,null,function*(){var n;(n=this.reporter)==null||n.reportScreenProfile(r);let i=this.ScreenProfileMap.get(r);if(i){if(this.hasScreen&&this.videotrack&&this.videotrack.applyConstraints)try{yield this.videotrack.applyConstraints(i)}catch(a){return t(a)}this.screenProfile=r,this.pc&&this.setEncodeParam(this.pc,"video"),e(this.screenProfile)}else t("Profile not found")}))}setAudioProfile(r){return new Promise((e,t)=>_(this,null,function*(){var n;(n=this.reporter)==null||n.reportAudioProfile(r);let i=this.AudioProfileMap.get(r);if(i){if(!this.isCustomStream&&this.hasAudio&&this.audioTrack&&this.audioTrack.applyConstraints)try{yield this.audioTrack.applyConstraints(i)}catch(a){return t(a)}this.audioProfile=r,this.pc&&this.setEncodeParam(this.pc,"audio"),e(this.audioProfile)}else t("Profile not found")}))}enableAudio(){var r;return(r=this.reporter)==null||r.reportEnableAudio(),!!this.audiotrack&&(this.audiotrack.enabled=!0,!0)}disableAudio(){var r;return(r=this.reporter)==null||r.reportDisableAudio(),!!this.audiotrack&&(this.audiotrack.enabled=!1,!0)}enableVideo(){var r;return(r=this.reporter)==null||r.reportEnableVideo(),!!this.videotrack&&(this.videotrack.enabled=!0,!0)}disableVideo(){var r;return(r=this.reporter)==null||r.reportDisableVideo(),!!this.videotrack&&(this.videotrack.enabled=!1,!0)}stop(){var r;super.stop(),this.hasVideo=!1,this.hasScreen=!1,this.isCustomStream=!1,this.canvasRenderer&&(this.canvasRenderer.stop(),this.canvasRenderer=void 0),this.audiotrack&&(this.audiotrack.stop(),this.audiotrack=void 0),this.videotrack&&(this.videotrack.stop(),this.videotrack=void 0),this.micAudioTrack&&(this.micAudioTrack.stop(),this.micAudioTrack=void 0),this.screenAudioTrack&&(this.screenAudioTrack.stop(),this.screenAudioTrack=void 0),(r=this.reporter)==null||r.reportStop(0)}mergeStream(r){const e=r.videoTrack,t=r.audioTrack;e&&(this.videoTrack&&(this.videoTrack.removeEventListener("ended",this.handleVideoTrackEnded),this.mediaStream.removeTrack(this.videoTrack)),this.mediaStream.addTrack(e),this.videotrack=e,this.listenVideoEnded(),this.hasVideo=r.hasVideo,this.hasScreen=r.hasScreen,this.isCustomStream=r.isCustomStream,this.hasVideo&&(this.videoProfile=r.videoProfile),this.hasScreen&&(this.screenProfile=r.screenProfile)),t&&(this.audioTrack&&(this.audioTrack.removeEventListener("ended",this.handleAudioTrackEnded),this.mediaStream.removeTrack(this.audioTrack)),this.mediaStream.addTrack(t),this.audiotrack=t,this.listenAudioEnded())}deleteTracks(r){r.audio&&this.audioTrack&&(this.mediaStream.removeTrack(this.audioTrack),this.audiotrack=void 0),r.video&&this.videoTrack&&(this.mediaStream.removeTrack(this.videoTrack),this.videotrack=void 0,this.hasScreen=!1,this.hasVideo=!1)}createCustomStream(r){return new Promise((e,t)=>{if(!r)return t(new ie(H.ERROR_CUSTOMSTREAM_NONE,"MediaStream is required.",""));if(!(r instanceof MediaStream))return t(new ie(H.ERROR_CUSTOMSTREAM_INVALID,"MediaStream is invalid.",""));if(r.getTracks().length===0)return t(new ie(H.ERROR_CUSTOMSTREAM_TRACK_NONE,"MediaStream has no track.",""));const i=(a=>a.getVideoTracks()[0])(r),n=(a=>a.getAudioTracks()[0])(r);i&&(this.hasVideo=!0,this.videotrack=i,this.mediastream.addTrack(i)),n&&(this.audiotrack=n,this.mediastream.addTrack(n)),this.isCustomStream=!0,this.setVideoProfile(this.videoProfile),this.addTrackListener(),e()})}releaseMediaStream(){this.mediastream.getTracks().forEach(r=>{r.stop(),this.mediastream.removeTrack(r)})}hasVideoTrackReady(r){return!(!r.video&&!r.screen||!this.videotrack)||!r.video&&!r.screen}hasScreenAudioConfig(r){return typeof r.screen=="object"&&r.screen.audio}hasAudioTrackReady(r){return!(r.audio&&(!this.hasMicAudioAndReady(r)&&!this.hasScreenAudioAndReady(r)||!this.audiotrack))}hasMicAudioAndReady(r){return r.audio&&this.micAudioTrack}hasScreenAudioAndReady(r){return this.hasScreenAudioConfig(r)&&this.screenAudioTrack}addTrackListener(){this.listenVideoEnded(),this.listenAudioEnded()}listenVideoEnded(){this.videotrack&&this.videotrack.addEventListener("ended",this.handleVideoTrackEnded),this.micAudioTrack&&this.micAudioTrack.addEventListener("ended",()=>{var r;this.emit("micAudioTrackEnded"),this.screenAudioTrack&&this.screenAudioTrack.readyState==="ended"&&((r=this.audioMixer)==null||r.destroy(),this.emit("audioTrackEnded"))}),this.screenAudioTrack&&this.screenAudioTrack.addEventListener("ended",()=>{var r;this.emit("screenAudioTrackEnded"),this.micAudioTrack&&this.micAudioTrack.readyState==="ended"&&((r=this.audioMixer)==null||r.destroy(),this.emit("audioTrackEnded"))})}listenAudioEnded(){this.audiotrack&&this.audiotrack.addEventListener("ended",this.handleAudioTrackEnded)}handleVideoTrackEnded(){this.hasScreen=!1,this.hasVideo=!1,this.emit("videoTrackEnded")}handleAudioTrackEnded(){this.emit("audioTrackEnded")}}var Ar=(s=>(s.AUDIO="audio",s.VIDEO="video",s))(Ar||{}),ct=(s=>(s[s.CONNECT_STATUS_DISCONNECTED=0]="CONNECT_STATUS_DISCONNECTED",s[s.CONNECT_STATUS_CONNECTING=1]="CONNECT_STATUS_CONNECTING",s[s.CONNECT_STATUS_CONNECTED=2]="CONNECT_STATUS_CONNECTED",s[s.CONNECT_STATUS_RECONNECTING=3]="CONNECT_STATUS_RECONNECTING",s))(ct||{}),Pt=(s=>(s.Sender="sender",s.Receiver="receiver",s))(Pt||{}),Zr=(s=>(s.Setup="setup",s.InserSEI="insertSEI",s.UpdatePubStats="updatePubStats",s.UpdateSubStats="updateSubStats",s.SwitchCumuDelay="switchCumuDelay",s))(Zr||{});const ke=(s,r)=>{let e=s||"";return e=e.replace("@subaudio=no","").replace("@subvideo=no",""),r&&(e=e.split("?")[0]),e},dc=(s,r)=>s.filter(e=>r.includes(e));var lc={},hc={exports:{}},uc=hc.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(s){return s.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(s){return s.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(s){var r="candidate:%s %d %s %d %s %d typ %s";return r+=s.raddr!=null?" raddr %s rport %d":"%v%v",r+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(r+=" generation %d"),r+=s["network-id"]!=null?" network-id %d":"%v",r+=s["network-cost"]!=null?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(s){var r="ssrc:%d";return s.attribute!=null&&(r+=" %s",s.value!=null&&(r+=":%s")),r}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(s){return s.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(s){return s.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(s){return"imageattr:%s %s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(s){return"simulcast:%s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var r="mediaclk:";return r+=s.id!=null?"id=%s %s":"%v%s",r+=s.mediaClockValue!=null?"=%s":"",r+=s.rateNumerator!=null?" rate=%s":"",r+=s.rateDenominator!=null?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(uc).forEach(function(s){uc[s].forEach(function(r){r.reg||(r.reg=/(.*)/),r.format||(r.format="%s")})});var pc=hc.exports;(function(s){var r=function(a){return String(Number(a))===a?Number(a):a},e=function(a,c,o){var l=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:l&&!c[a.name]&&(c[a.name]={});var d=a.push?{}:l?c[a.name]:c;(function(h,u,p,f){if(f&&!p)u[f]=r(h[1]);else for(var m=0;m<p.length;m+=1)h[m+1]!=null&&(u[p[m]]=r(h[m+1]))})(o.match(a.reg),d,a.names,a.name),a.push&&c[a.push].push(d)},t=pc,i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);s.parse=function(a){var c={},o=[],l=c;return a.split(/(\r\n|\r|\n)/).filter(i).forEach(function(d){var h=d[0],u=d.slice(2);h==="m"&&(o.push({rtp:[],fmtp:[]}),l=o[o.length-1]);for(var p=0;p<(t[h]||[]).length;p+=1){var f=t[h][p];if(f.reg.test(u))return e(f,l,u)}}),c.media=o,c};var n=function(a,c){var o=c.split(/=(.+)/,2);return o.length===2?a[o[0]]=r(o[1]):o.length===1&&c.length>1&&(a[o[0]]=void 0),a};s.parseParams=function(a){return a.split(/;\s?/).reduce(n,{})},s.parseFmtpConfig=s.parseParams,s.parsePayloads=function(a){return a.toString().split(" ").map(Number)},s.parseRemoteCandidates=function(a){for(var c=[],o=a.split(" ").map(r),l=0;l<o.length;l+=3)c.push({component:o[l],ip:o[l+1],port:o[l+2]});return c},s.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(n,{})})},s.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(o){var l,d=!1;return o[0]!=="~"?l=r(o):(l=r(o.substring(1,o.length)),d=!0),{scid:l,paused:d}})})}})(lc);var Bs=pc,eu=/%[sdv%]/g,tu=function(s){var r=1,e=arguments,t=e.length;return s.replace(eu,function(i){if(r>=t)return i;var n=e[r];switch(r+=1,i){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},Si=function(s,r,e){var t=[s+"="+(r.format instanceof Function?r.format(r.push?e:e[r.name]):r.format)];if(r.names)for(var i=0;i<r.names.length;i+=1){var n=r.names[i];r.name?t.push(e[r.name][n]):t.push(e[r.names[i]])}else t.push(e[r.name]);return tu.apply(null,t)},ru=["v","o","s","i","u","e","p","c","b","t","r","z","a"],iu=["i","c","b","a"],su=lc,nu=function(s,r){r=r||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(n){n.payloads==null&&(n.payloads="")});var e=r.outerOrder||ru,t=r.innerOrder||iu,i=[];return e.forEach(function(n){Bs[n].forEach(function(a){a.name in s&&s[a.name]!=null?i.push(Si(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){i.push(Si(n,a,c))})})}),s.media.forEach(function(n){i.push(Si("m",Bs.m[0],n)),t.forEach(function(a){Bs[a].forEach(function(c){c.name in n&&n[c.name]!=null?i.push(Si(a,c,n)):c.push in n&&n[c.push]!=null&&n[c.push].forEach(function(o){i.push(Si(a,c,o))})})})}),i.join(`\r
117
+ `)+`\r
118
+ `},au=nu,ou=su.parse;let Je=class{constructor(s){if(this.rawSdp=s.sdp,!s.sdp)throw new Error("No sdp to parse");this.sdpDetail=this.parse()}get detail(){return this.sdpDetail}removeMedia(s){return this.removeMediaInner(s)}keepMedia(s){return this.removeMediaInner(s,{revert:!0})}removeMediaInner(s,r={revert:!1}){s.length&&this.sdpDetail.media&&this.sdpDetail.media.length&&(r.revert?this.sdpDetail.media=this.sdpDetail.media.filter(e=>s.includes(String(e.mid)||"")):this.sdpDetail.media=this.sdpDetail.media.filter(e=>!s.includes(String(e.mid)||"")),this.updateBundle())}addOrUpdateMedia(s,r={}){s=s.map(t=>Q(D({},t),{setup:"passive"}));let e=[];this.sdpDetail.media=this.sdpDetail.media.map(t=>{const i=s.find(n=>n.mid===t.mid);if(i){e.push(t.mid);let n=i;const a=t;return r.isPublish&&(n.ssrcs=a.ssrcs,n.ssrcGroups=a.ssrcGroups),i}return t}),this.sdpDetail.media=[...this.sdpDetail.media,...s.filter(t=>!e.includes(t.mid))],this.updateBundle()}mungleMsid(){this.sdpDetail.media.forEach(s=>{if(s.msid){let r="";s.msid=s.msid.split(" ").map((e,t)=>t===1?(r=e,e+"_"+s.mid):e).join(" "),r&&s.ssrcs&&s.ssrcs.forEach(e=>{e.value&&(e.value=e.value.replace(r,r+"_"+s.mid))})}})}addMedia(s){var t;s=s.map(i=>Q(D({},i),{setup:"passive"})),this.sdpDetail.media=[...this.sdpDetail.media,...s];const r=s.reduce((i,n)=>i+" "+n.mid,""),e=(t=this.sdpDetail.groups)==null?void 0:t.find(i=>i.type==="BUNDLE");e&&(e.mids+=`${r}`)}setMediaInactive(s){this.sdpDetail.media.forEach(r=>{s.includes(String(r.mid))&&(r.direction="inactive")}),this.updateBundle()}getPublishSsrcs(){const s=[];return this.sdpDetail.media.forEach(r=>{r.direction!=="recvonly"&&r.ssrcs&&s.push({type:r.type,ssrc:r.ssrcs[0].id,mid:String(r.mid)})}),s}getPublishMsids(){const s=[];return this.sdpDetail.media.forEach(r=>{r.direction!=="recvonly"&&r.msid&&s.push({type:r.type,msid:r.msid,mid:String(r.mid)})}),s}generate(){return au(this.sdpDetail)}updateBundle(){var r;const s=(r=this.sdpDetail.groups)==null?void 0:r.find(e=>e.type==="BUNDLE");s&&(s.mids=this.sdpDetail.media.reduce((e,t)=>e+t.mid+" ","").trim())}addNack(){this.sdpDetail.media.forEach(s=>{var r,e,t;if(s.type==="audio"){if((r=s.rtcpFb)!=null&&r.some(n=>n.type==="nack"))return;const i=(e=s.rtp.find(n=>n.codec==="opus"))==null?void 0:e.payload;i&&((t=s.rtcpFb)==null||t.push({payload:i,type:"nack"}))}})}parse(){const s=ou(this.rawSdp);return this.patchMsid(s)}getMids(s){return s!=null&&s.length?s.reduce((r,e)=>[...r,String(e.mid)],[]):[]}patchMsid(s){return s.media.forEach(r=>{var e,t;r.type==="application"||r.msid||(r.msid=(t=(e=r.ssrcs)==null?void 0:e.find(i=>i.attribute==="msid"))==null?void 0:t.value)}),s}};function cu(s){if(!s.mids.length||!s.medias.length||s.mids.length!==s.medias.length)return"";let r=`v=0
119
+ o=- 1710852399 2 IN IP4 127.0.0.1
120
+ s=-
121
+ t=0 0
122
+ a=group:BUNDLE`;const e=`
123
+ a=end-of-candidates`;s.mids.forEach(i=>{r+=` ${i}`});const t=function(i){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a=n.length;let c="";for(let o=0;o<i;o++)c+=n.charAt(Math.floor(Math.random()*a));return c}(24);return s.medias.forEach((i,n)=>{if(i.type==="video"){let a=(1e4*Math.random()).toFixed(0),c=i.msid||"rts video";r+=`
124
+ m=video 9 UDP/TLS/RTP/SAVPF 106 107
125
+ c=IN IP4 0.0.0.0
126
+ a=rtcp:9 IN IP4 0.0.0.0
127
+ a=ice-ufrag:ZmFrZV90b2tlbg==
128
+ a=ice-pwd:${t}
129
+ a=ice-options:ice-lite
130
+ a=fingerprint:SHA-256 C3:E2:CD:1F:B8:E4:DA:77:D1:D2:36:F3:72:EA:83:CA:7A:F2:3B:26:07:C6:E0:3D:96:44:57:59:14:DE:F0:A4
131
+ a=setup:passive
132
+ a=sendonly
133
+ a=mid:${s.mids[n]}
134
+ a=rtcp-mux
135
+ a=rtpmap:106 H264/90000
136
+ a=fmtp:106 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f;sps-pps-idr-in-keyframe=1
137
+ a=rtcp-fb:106 goog-remb
138
+ a=rtcp-fb:106 transport-cc
139
+ a=rtcp-fb:106 ccm fir
140
+ a=rtcp-fb:106 nack
141
+ a=rtcp-fb:106 nack pli
142
+ a=rtpmap:107 rtx/90000
143
+ a=fmtp:107 apt=106
144
+ a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01
145
+ a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
146
+ a=extmap:5 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay`;const o=`
147
+ a=ssrc:${a} cname:defaultcname
148
+ a=ssrc:${a} msid:${c}
149
+ a=ssrc:${a} mslabel:rts
150
+ a=ssrc:${a} label:video`;s.direction==="sub"&&(r+=o),r+=e}else if(i.type==="audio"){let a=(1e4*Math.random()).toFixed(0),c=i.msid||"rts audio";r+=`
151
+ m=audio 9 UDP/TLS/RTP/SAVPF 111
152
+ c=IN IP4 0.0.0.0
153
+ a=rtcp:9 IN IP4 0.0.0.0
154
+ a=ice-ufrag:ZmFrZV90b2tlbg==
155
+ a=ice-pwd:${t}
156
+ a=ice-options:ice-lite
157
+ a=fingerprint:SHA-256 C3:E2:CD:1F:B8:E4:DA:77:D1:D2:36:F3:72:EA:83:CA:7A:F2:3B:26:07:C6:E0:3D:96:44:57:59:14:DE:F0:A4
158
+ a=setup:passive
159
+ a=sendonly
160
+ a=mid:${s.mids[n]}
161
+ a=rtcp-mux
162
+ a=rtpmap:111 opus/48000/2
163
+ a=fmtp:111 minptime=10;stereo=1;useinbandfec=1
164
+ a=rtcp-fb:111 transport-cc
165
+ a=rtcp-fb:111 nack
166
+ a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01
167
+ a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time`;const o=`
168
+ a=ssrc:${a} cname:defaultcname
169
+ a=ssrc:${a} msid:${c}
170
+ a=ssrc:${a} mslabel:rts
171
+ a=ssrc:${a} label:audio`;s.direction==="sub"&&(r+=o),r+=e}}),r}class du{constructor(r){const e=(t=>{let i={subVideo:!0,subAudio:!0};return t&&(t.includes("@subvideo=no")&&(i.subVideo=!1),t.includes("@subaudio=no")&&(i.subAudio=!1)),i})(r.url);this.data={url:r.url,subAudio:e.subAudio,subVideo:e.subVideo},typeof r.subAudio=="boolean"&&(this.data.subAudio=r.subAudio),typeof r.subVideo=="boolean"&&(this.data.subVideo=r.subVideo)}get subVideo(){return this.data.subVideo}get subAudio(){return this.data.subAudio}get url(){return ke(this.data.url)}get originalUrl(){return this.data.url}}var Ye=(s=>(s[s.DATACHANNEL_SIGNAL_ERROR=15e3]="DATACHANNEL_SIGNAL_ERROR",s[s.DATACHANNEL_SET_OFFER_ERROR=15001]="DATACHANNEL_SET_OFFER_ERROR",s[s.DATACHANNEL_SET_ANSWER_ERROR=15002]="DATACHANNEL_SET_ANSWER_ERROR",s[s.DATACHANNEL_CREATE_OFFER_ERROR=15003]="DATACHANNEL_CREATE_OFFER_ERROR",s[s.DATACHANNEL_RESPONSE_ERROR=15004]="DATACHANNEL_RESPONSE_ERROR",s[s.DATACHANNEL_PARSE_ERROR=15005]="DATACHANNEL_PARSE_ERROR",s[s.DATACHANNEL_TIMEOUT_ERROR=15006]="DATACHANNEL_TIMEOUT_ERROR",s[s.CORE_NO_PC_ERROR=15007]="CORE_NO_PC_ERROR",s[s.CORE_PUBLIST_EXCEED_ERROR=15008]="CORE_PUBLIST_EXCEED_ERROR",s[s.CORE_PUB_REPLACE_URL_NOT_FOUND=15009]="CORE_PUB_REPLACE_URL_NOT_FOUND",s[s.CORE_TRANSCEIVERS_NOT_FOUND=15010]="CORE_TRANSCEIVERS_NOT_FOUND",s))(Ye||{});class lt{constructor(r,e,t,i){this.errorCode=r,this.errorCodeName=Ye[r],this.message=e,this.traceId=t,i&&(this.extraInfo=i)}}class Ki{constructor(r){this.data=[],this.tag=r||"unknown",this.maxBufferLength=90}setMaxCapacity(r){this.maxBufferLength=90,r>=0&&(this.maxBufferLength=r),this.maxBufferLength>200&&(this.maxBufferLength=200)}cache(r){this.data.length>this.maxBufferLength&&(this.data.shift(),console.log(this.tag+" CACHE: Reach Max Capacity")),this.data.push(r)}getFirst(){return this.data.shift()}isEmpty(){return this.data.length<=0}}class Ir{constructor(){this._eventMap={}}listeners(r){return this._eventMap[r]||[]}emit(r,...e){const t=this._eventMap[r];return!!Array.isArray(t)&&(t.forEach(i=>i.apply(this,e)),!0)}off(r,e){const t=this._eventMap[r];return Array.isArray(t)&&(this._eventMap[r]=t.filter(i=>i!==e)),this}removeAllListeners(r){return r===void 0?this._eventMap={}:this._eventMap[r]&&(this._eventMap[r]=[]),this}on(r,e){return this._eventMap[r]?this._eventMap[r].push(e):this._eventMap[r]=[e],this}once(r,e){const t=(...i)=>{this.off(r,t),e.apply(this,i)};return this.on(r,t),this}}var Fs={exports:{}},lu=Object.prototype.hasOwnProperty;function mc(s){return"[Throws: "+(s?s.message:"?")+"]"}function fc(s){var r=[];return function e(t){if(t===null||typeof t!="object")return t;if(r.indexOf(t)!==-1)return"[Circular]";if(r.push(t),typeof t.toJSON=="function")try{var i=e(t.toJSON());return r.pop(),i}catch(c){return mc(c)}if(Array.isArray(t)){var n=t.map(e);return r.pop(),n}var a=Object.keys(t).reduce(function(c,o){return c[o]=e(function(l,d){if(lu.call(l,d))try{return l[d]}catch(h){return mc(h)}return l[d]}(t,o)),c},{});return r.pop(),a}(s)}Fs.exports=function(s,r,e){return JSON.stringify(fc(s),r,e)},Fs.exports.ensureProperties=fc;const he=Cr(Fs.exports);var fr=(s=>(s.PRE_PUB="prepub",s.PRE_SUB="presub",s.RECONNECT_ROOM_SERVER="reconnect_roomserver",s.HEBT="hebt",s.NOTI="NOTI",s))(fr||{}),Hs=(s=>(s[s.NGX_RTC_PUBLISH_ALREADY=402]="NGX_RTC_PUBLISH_ALREADY",s[s.NGX_RTC_REQUEST_FORBIDDEN=403]="NGX_RTC_REQUEST_FORBIDDEN",s[s.NGX_RTC_STREAM_NO_FOUND=404]="NGX_RTC_STREAM_NO_FOUND",s[s.NGX_RTC_SUBSCRIBE_ALREADY=410]="NGX_RTC_SUBSCRIBE_ALREADY",s[s.NGX_RTC_NORMAL_CLOSED=200]="NGX_RTC_NORMAL_CLOSED",s[s.NGX_RTC_LIMITED=508]="NGX_RTC_LIMITED",s[s.NGX_RTC_INTERNAL_SERVER_ERROR=500]="NGX_RTC_INTERNAL_SERVER_ERROR",s[s.NGX_RTC_BAD_REQUEST=400]="NGX_RTC_BAD_REQUEST",s[s.NGX_RTC_NEED_RETRY=213]="NGX_RTC_NEED_RETRY",s[s.NGX_RTC_DATACHANNEL_HEBT_MSID_NOT_FOUND=130]="NGX_RTC_DATACHANNEL_HEBT_MSID_NOT_FOUND",s[s.NGX_RTC_ONE_PC_NEED_RETRY_SOON=131]="NGX_RTC_ONE_PC_NEED_RETRY_SOON",s))(Hs||{});class hu extends Ir{constructor(r){super(),this.datachannel=r}sendingProcess(r,e,t){var a,c,o,l;let i=performance.now();const n=this.sign(t);this.datachannel.onmessage=d=>{try{const h=JSON.parse(d.data),u=this.checkResponse(h,n);if(u.ignore)return;if(this.emit("onReceiveData",h),this.log("<<< Received:",`${Math.ceil(performance.now()-i)}ms`,h),u.pass)r(h);else{if(u.code===213)return void setTimeout(()=>{this.log(">>> Send:",t),this.datachannel.send(he(t))},200);e(new lt(Ye.DATACHANNEL_RESPONSE_ERROR,`[code]${u.code}; [msg]${u.msg}`,u.traceId,{parsedData:h}))}}catch(h){e(new lt(Ye.DATACHANNEL_PARSE_ERROR,"datachannel message parse error","",{data:d.data,err:h}))}this.emit("onSendDataDone")};try{this.log(">>> Sent:",`${t.type}-${(a=t.streams)!=null&&a.length?t.streams[0].method:"-"}`,(l=(o=(c=t.streams)==null?void 0:c[0])==null?void 0:o.msid)==null?void 0:l.reduce((d,h)=>d+","+h.name,""),t)}catch(d){}this.emit("onSendData",t),this.datachannel.send(he(t))}dispose(){this.removeAllListeners(),this.datachannel.onmessage=null}checkResponse(r,e){let t={pass:!0,ignore:!1,code:0,msg:"",traceId:""};if(["hebt","NOTI","prepub","presub","reconnect_roomserver"].includes(r.type)||e&&this.sign(r)!==e)return t.ignore=!0,t.pass=!1,t;r.recode!==0&&(t.pass=!1,t.code=r.recode,t.msg=r.msg);const i=r.streams;return i&&i.length>0&&i.forEach(n=>{n.res_code!==200&&(t.pass=!1,t.code=n.res_code,t.msg=n.res_msg,t.traceId=n.traceid)}),t}sign(r){var t,i;let e="";try{e=`${r.msg_id}-${r.type}-${(i=(t=r.streams)==null?void 0:t[0])==null?void 0:i.method}`}catch(n){e=""}return e}log(...r){window.RTS_DATACHANNEL_DEBUG&&console.log(`${this.now()} [datachannel|${this.datachannel.label}|${this.datachannel.id}]`,...r)}now(){const r=new Date;return`${r.getHours()}:${r.getMinutes()}:${r.getSeconds()}.${String(r.getMilliseconds()).padStart(3,"0")}`}}var yt=(s=>(s[s.DATACHANNEL_STATUS_CLOSE=0]="DATACHANNEL_STATUS_CLOSE",s[s.DATACHANNEL_STATUS_OPEN=1]="DATACHANNEL_STATUS_OPEN",s))(yt||{});function uu(){}const gc=class da extends Ir{constructor(r){super(),this.mutexSendData=!1,this.timerSendData=null,this.eventQueue=new Ki("send tasks"),this._assignedId=void 0,this.idle=!1,this.datachannelList=[],this.pc=r.pc,this.eventHandler=r.onDatachannelEvent||uu,this.datachannelList=r.datachannelList||[],this.createDatachannel(r.label,r.assignId,r.delayOpen,r.initOptions)}getWebrtcDatachannel(){return this.datachannel}get isIdle(){return this.idle}markAsIdle(){this.idle=!0}reuse(){this.idle=!1,console.log("REUSEING datachannel",this.datachannel.id,this.datachannel.label,this.datachannel.readyState),setTimeout(()=>{this.emit("statusChange",1)})}getNextId(){let r=0;const e=this.datachannelList.reduce((t,i)=>i.readyState==="open"?t+1:(r||(r=i.id),t),0);return r||2*(e+1)}createDatachannel(r,e,t,i){let n=D({ordered:!0},i);e&&this.pc.connectionState==="connected"&&(this._assignedId=this.getNextId(),n.id=this._assignedId),this.datachannel=this.pc.createDataChannel(r||`GRTN_RTC_DATACHANNEL_${Date.now()}`,n),this.datachannel.addEventListener("open",()=>{t?setTimeout(()=>{this.eventHandler(1),this.emit("statusChange",1)},200):(this.eventHandler(1),this.emit("statusChange",1))}),this.datachannel.addEventListener("close",()=>{this.eventHandler(0),this.emit("statusChange",0)}),this.datachannel.addEventListener("closing",()=>{}),this.datachannel.addEventListener("error",a=>{console.log(">> error",a),this.emit("error",a)}),this.datachannel.addEventListener("bufferedamountlow",()=>{}),this.datachannel.addEventListener("message",a=>{this.emit("message",a.data)})}get assignedId(){return this._assignedId}get id(){return this.datachannel.id}get label(){return this.datachannel.label}get readyState(){return this.datachannel.readyState}send(r){if(this.datachannel.readyState!=="open")throw new Error(`Datachannel(label:${this.datachannel.label},id:${this.datachannel.id}) is closed.`);return this.datachannel.send(r)}sendAsync(r){if(this.datachannel.readyState==="open")return this.datachannel.send(he(r)),!0;console.log(`Async signal message failed. Datachannel(label:${this.datachannel.label},id:${this.datachannel.id}) is closed.`)}sendData(r){return new Promise((e,t)=>{let i=new hu(this.datachannel);if(this.mutexSendData){let n={sender:i,res:e,rej:t,data:r};this.eventQueue.cache(n)}else this.atomSend(i,e,t,r)})}dispose(r=!1){var e;this.emit("dispose"),this.mutexSendData=!1,this.timerSendData!==null&&clearTimeout(this.timerSendData),this.timerSendData=null,this.eventQueue=new Ki("send tasks"),this.markAsIdle(),this.removeAllListeners(),r&&((e=this.datachannel)==null||e.close())}atomSend(r,e,t,i){this.mutexSendData=!0,r.on("onSendData",n=>{this.emit("atomSend",n)}),r.on("onReceiveData",n=>{this.emit("atomReceive",n)}),r.on("onSendDataDone",()=>{if(r.dispose(),this.timerSendData!==null&&clearTimeout(this.timerSendData),this.timerSendData=null,this.mutexSendData=!1,!this.eventQueue.isEmpty()){let n=this.eventQueue.getFirst();this.atomSend(n.sender,n.res,n.rej,n.data)}}),this.timerSendData=setTimeout(()=>{t(new lt(Ye.DATACHANNEL_TIMEOUT_ERROR,`request timeout after ${da.REQUEST_TIMEOUT}ms`,"",i)),this.timerSendData=null,this.mutexSendData=!1,r.emit("onSendDataDone")},da.REQUEST_TIMEOUT),r.sendingProcess(e,t,i)}};gc.REQUEST_TIMEOUT=5e3;let Ws=gc;class pu{constructor(r){this.latestMsgId=0,this.latestSubAddMsgId=0,this.pc=r.pc,this.datachannel=new Ws({pc:this.pc,onDatachannelEvent:r.onDatachannelEvent,delayOpen:r.delayOpen,initOptions:r.initOptions})}getDatachannelCore(){return this.datachannel}joinPubSub(r){return _(this,null,function*(){var o;const{url:e,msid:t,channelId:i,appOpaqueData:n,compress:a}=r,c=Q(D({},this.baseParams({type:"join_pub_sub"})),{compress:a?1:0,streams:[{method:"add",url:e,msid:[{type:"data",name:t,channel:i}],app_opaque_data:n}]});return(o=this.datachannel)==null?void 0:o.sendData(c)})}subscribeAdd(r,e,t){return _(this,null,function*(){var n;const i=Q(D({},this.baseParams({type:"sub",method:"add"})),{streams:r.map((a,c)=>{const{urlData:o}=a;let l=[];return o.subAudio&&!t.isMsidSubPubDone(o.url,{aMsid:a.aMsid[0]})&&l.push({type:"audio",name:a.aMsid[0]}),o.subVideo&&!t.isMsidSubPubDone(o.url,{vMsid:a.vMsid[0]})&&l.push({type:"video",name:a.vMsid[0]}),{method:"add",url:o.url,msid:l,sdp:e[c],ttl:300}})});return yield(n=this.datachannel)==null?void 0:n.sendData(i)})}subscribeActive(r){return _(this,null,function*(){var t;const e=Q(D({},this.baseParams({type:"sub",method:"active"})),{streams:r.map(({urlData:i})=>({method:"active",url:i.url}))});return(t=this.datachannel)==null?void 0:t.sendData(e)})}subscribeDelete(r){return _(this,null,function*(){var t;const e=Q(D({},this.baseParams()),{streams:r.map(({url:i,aMsid:n,vMsid:a})=>{let c=[];return n!=null&&n.length&&(c=[...c,...n.map(o=>({name:o}))]),a!=null&&a.length&&(c=[...c,...a.map(o=>({name:o}))]),{method:"delete",url:ke(i),msid:c}})});return yield(t=this.datachannel)==null?void 0:t.sendData(e)})}subscribeStop(r){return _(this,null,function*(){var t;const e=Q(D({},this.baseParams()),{streams:r.map(({urlData:i})=>({method:"stop",url:i.url}))});return yield(t=this.datachannel)==null?void 0:t.sendData(e)})}subscribeAddDatachannel(r){return _(this,null,function*(){var t;const e=Q(D({},this.baseParams({type:"sub",method:"add"})),{streams:r.map(({url:i,msid:n})=>({method:"add",url:i,msid:[{type:"data",name:n}]}))});return yield(t=this.datachannel)==null?void 0:t.sendData(e)})}subscribeActiveDatachannel(r){return _(this,null,function*(){var t;const e=Q(D({},this.baseParams({type:"sub",method:"active"})),{streams:r.map(({url:i,datachannelId:n,msid:a})=>({method:"active",url:i,msid:[{type:"data",name:a,channel:n}]}))});return yield(t=this.datachannel)==null?void 0:t.sendData(e)})}subscribeDeleteDatachannel(r){return _(this,null,function*(){var t;const e=Q(D({},this.baseParams()),{streams:r.map(({url:i,msid:n})=>({method:"delete",url:i,msid:[{name:n}]}))});return yield(t=this.datachannel)==null?void 0:t.sendData(e)})}subscribeStopDatachannel(r){return _(this,null,function*(){var t;const e=Q(D({},this.baseParams()),{streams:r.map(({url:i})=>({method:"stop",url:i}))});return yield(t=this.datachannel)==null?void 0:t.sendData(e)})}publishAdd(r,e,t,i){return _(this,null,function*(){var a;const n=Q(D({},this.baseParams({type:"pub"})),{streams:r.map((c,o)=>{const l=t[o],d=i[o];let h=[];return l.length&&h.push({type:"video",name:l[0].trim()}),d.length&&h.push({type:"audio",name:d[0].trim()}),{method:"add",url:c,msid:h,sdp:e[o]}})});return(a=this.datachannel)==null?void 0:a.sendData(n)})}publishDelete(r){return _(this,null,function*(){var t;const e=Q(D({},this.baseParams({type:"pub"})),{streams:r.map(({url:i,aMsid:n,vMsid:a})=>{let c=[];return n!=null&&n.length&&(c=[...c,...n.map(o=>({name:o}))]),a!=null&&a.length&&(c=[...c,...a.map(o=>({name:o}))]),{method:"delete",url:ke(i),msid:c}})});return(t=this.datachannel)==null?void 0:t.sendData(e)})}publishStop(r){return _(this,null,function*(){var t;const e=Q(D({},this.baseParams({type:"pub"})),{streams:r.map(i=>({method:"stop",url:i}))});return(t=this.datachannel)==null?void 0:t.sendData(e)})}publishAddDatachannel(r){return _(this,null,function*(){var t;const e=Q(D({},this.baseParams({type:"pub",method:"add"})),{streams:r.map(({url:i,datachannelId:n,msid:a})=>({method:"add",url:i,msid:[{type:"data",name:a,channel:n}]}))});return yield(t=this.datachannel)==null?void 0:t.sendData(e)})}publishDeleteDatachannel(r){return _(this,null,function*(){var t;const e=Q(D({},this.baseParams({type:"pub"})),{streams:r.map(({url:i,msid:n})=>({method:"delete",url:i,msid:[{name:n}]}))});return yield(t=this.datachannel)==null?void 0:t.sendData(e)})}publishStopDatachannel(r){return _(this,null,function*(){var t;const e=Q(D({},this.baseParams({type:"pub"})),{streams:r.map(({url:i})=>({method:"stop",url:i}))});return yield(t=this.datachannel)==null?void 0:t.sendData(e)})}sendHeartbeat(r){r&&!r.map&&(r=void 0);const e=Q(D({},this.baseParams({type:"hebt"})),{streams:r==null?void 0:r.map(({url:t})=>({method:"hebt",url:t}))});if(r||delete e.streams,this.datachannel.sendAsync(e))return e}sendFalseHeartbeat(r){const e=Q(D({},this.baseParams({type:"hebt"})),{streams:r==null?void 0:r.map(({url:t})=>({method:"fake",url:t}))});if(r||delete e.streams,this.datachannel.sendAsync(e))return e}dispose(){this.datachannel.dispose()}baseParams(r={type:"sub"}){let e=0;return r.type==="sub"&&r.method==="add"?(e=++this.latestMsgId,this.latestSubAddMsgId=this.latestMsgId):e=r.type==="sub"&&r.method==="active"?this.latestSubAddMsgId:++this.latestMsgId,{msg_id:e,version:2,type:r.type}}}class mu extends Ir{parseFormat(r){try{return JSON.parse(r)}catch(e){console.warn("PrePubSub parse failed."," Response Data: ",r)}}checkRelated(r,e){return r.type===e}processPrePub(r){const e=this.parseFormat(r);e&&this.checkRelated(e,fr.PRE_PUB)&&this.emit("prePub",{message:e})}processPreSub(r){const e=this.parseFormat(r);e&&this.checkRelated(e,fr.PRE_SUB)&&this.emit("preSub",{message:e})}processReconnectRoomServer(r){const e=this.parseFormat(r);e&&this.checkRelated(e,fr.RECONNECT_ROOM_SERVER)&&this.emit("reconnectRoomServer")}}var js=(s=>(s.Subscribe="sub",s.Publish="pub",s))(js||{});class fu{constructor(r){this.streamMap={},this.streamMapBackup={}}backup(){let r={};Object.keys(this.streamMap).forEach(e=>{let t=this.streamMap[e];r[e]=Q(D({},this.streamMap[e]),{videoInfoList:[...t.videoInfoList],audioInfoList:[...t.audioInfoList],streamList:[...t.streamList]})}),this.streamMapBackup=r}restore(){this.streamMap=D({},this.streamMapBackup)}init(r,e="sub"){const t=ke(r);r=ke(r,!0),this.has(r)||(this.streamMap[r]={type:e,videoInfoList:[],audioInfoList:[],streamList:[],originUrl:t})}remove(r){delete this.streamMap[ke(r,!0)]}update(r,e){const t=this.get(r);if(!t)throw new Error("No url found");if(e.aMsid){let i=t.audioInfoList.find(n=>n.msid===e.aMsid)||this.createMediaItem(e.aMsid,"audio");e.aTransceiver&&(i.transceiver=e.aTransceiver),e.stream&&(i.streamId=e.stream.id),this.updateMediaInfoList(i,t.audioInfoList)}if(e.vMsid){let i=t.videoInfoList.find(n=>n.msid===e.vMsid)||this.createMediaItem(e.vMsid,"video");e.vTransceiver&&(i.transceiver=e.vTransceiver),e.cumuDelay&&(i.cumuDelay=e.cumuDelay),e.stream&&(i.streamId=e.stream.id),this.updateMediaInfoList(i,t.videoInfoList)}e.stream&&(t.streamList.some(i=>i.id===e.stream.id)||(t.streamList=[...t.streamList,e.stream]))}pruneStreamList(r){const e=this.get(r);e&&(e.streamList=e.streamList.filter(t=>{var i;return((i=t.mediaStream)==null?void 0:i.getTracks().length)>0}))}updateSdpInfo(r,e){const t=this.get(r);if(!t)throw new Error("No url found");let i;if(e.aMsid?i=t.audioInfoList.find(n=>n.msid===e.aMsid):e.vMsid&&(i=t.videoInfoList.find(n=>n.msid===e.vMsid)),!i)throw new Error("No target media found");i.ssrc=e.ssrc,i.codec=e.codec,i.pt=e.pt,i.from=e.from}get(r){return this.streamMap[ke(r,!0)]}has(r){return!!this.get(r)}getSize(){return this.getSubOrPubDoneMediaMapSize()}getSubOrPubDoneMediaMapSize(){let r=0;return Object.keys(this.streamMap).forEach(e=>{const t=this.streamMap[e];let i=!1;t.audioInfoList.forEach(n=>{i=i||t.type==="pub"&&n.pubDone||t.type==="sub"&&n.subDone}),t.videoInfoList.forEach(n=>{i=i||t.type==="pub"&&n.pubDone||t.type==="sub"&&n.subDone}),i&&r++}),r}removeMsid(r,e){r=ke(r,!0);const t=this.get(r);t&&(e.vMsid&&(t.videoInfoList=t.videoInfoList.filter(i=>i.msid!==e.vMsid)),e.aMsid&&(t.audioInfoList=t.audioInfoList.filter(i=>i.msid!==e.aMsid)))}getMids(r,e={filterSubDone:!1}){r=ke(r,!0);const t=this.streamMap[r];return t?[...t.audioInfoList.reduce((i,n)=>n.transceiver&&(!e.filterSubDone||e.filterSubDone&&!n.subDone)?[...i,String(n.transceiver.mid)]:i,[]),...t.videoInfoList.reduce((i,n)=>n.transceiver&&(!e.filterSubDone||e.filterSubDone&&!n.subDone)?[...i,String(n.transceiver.mid)]:i,[])]:[]}getAllTransceivers(r){if(!r)return[];r=ke(r,!0);const e=this.get(r);return e?[...e.videoInfoList.map(t=>t.transceiver),...e.audioInfoList.map(t=>t.transceiver)]:[]}getTransceiver(r,e={}){if(!r)return;r=ke(r,!0);const{vMsid:t,aMsid:i}=e,n=this.get(r);if(n){if(t){const a=n.videoInfoList.find(c=>c.msid===t);return a==null?void 0:a.transceiver}if(i){const a=n.audioInfoList.find(c=>c.msid===i);return a==null?void 0:a.transceiver}}}getStreamByMsid(r){var t,i;const e=this.get(r.url);if(e){if(r.vMsid){const n=(t=e.videoInfoList.find(a=>a.msid===r.vMsid))==null?void 0:t.streamId;return e.streamList.find(a=>a.id===n)}if(r.aMsid){const n=(i=e.audioInfoList.find(a=>a.msid===r.aMsid))==null?void 0:i.streamId;return e.streamList.find(a=>a.id===n)}return e.streamList[0]}}hasTransceiver(r,e={}){return!!this.getTransceiver(r,e)}removeTransceiver(r,e){r=ke(r,!0);const t=this.get(r);if(t){if(e.vMsid){const i=t.videoInfoList.find(n=>n.msid===e.vMsid);i&&(i.transceiver=void 0)}if(e.aMsid){const i=t.audioInfoList.find(n=>n.msid===e.aMsid);i&&(i.transceiver=void 0)}}}markAlreadySubPub(r,e={}){r=ke(r,!0);const t=this.streamMap[r];if(t){if(e.vMsid){const i=t.videoInfoList.find(n=>n.msid===e.vMsid);i&&(i[e.isPub?"pubDone":"subDone"]=!e.reset)}if(e.aMsid){const i=t.audioInfoList.find(n=>n.msid===e.aMsid);i&&(i[e.isPub?"pubDone":"subDone"]=!e.reset)}}}isMsidSubPubDone(r,e={}){r=ke(r,!0);const t=this.streamMap[r];if(!t)return!1;if(e.vMsid){const i=t.videoInfoList.find(n=>n.msid===e.vMsid);return e.isPub?i==null?void 0:i.pubDone:i==null?void 0:i.subDone}if(e.aMsid){const i=t.audioInfoList.find(n=>n.msid===e.aMsid);return e.isPub?i==null?void 0:i.pubDone:i==null?void 0:i.subDone}}getAllMediaInfoList(r,e){const t=this.get(r);return t?[...t.audioInfoList.map(({type:i,msid:n,ssrc:a,pt:c,codec:o,from:l,transceiver:d})=>{var u,p,f,m;let h={type:i,msid:n,ssrc:a,pt:c,codec:o,from:l,trackId:t.type==="sub"?(p=(u=d==null?void 0:d.receiver)==null?void 0:u.track)==null?void 0:p.id:(m=(f=d==null?void 0:d.sender)==null?void 0:f.track)==null?void 0:m.id};return e?Q(D({},h),{transceiver:d}):h}),...t.videoInfoList.map(({type:i,msid:n,ssrc:a,pt:c,codec:o,from:l,transceiver:d})=>{var u,p,f,m;let h={type:i,msid:n,ssrc:a,pt:c,codec:o,from:l,trackId:t.type==="sub"?(p=(u=d==null?void 0:d.receiver)==null?void 0:u.track)==null?void 0:p.id:(m=(f=d==null?void 0:d.sender)==null?void 0:f.track)==null?void 0:m.id};return e?Q(D({},h),{transceiver:d}):h})]:[]}getOriginUrl(r){const e=ke(r,!0),t=this.get(e);return t?t.originUrl:r}getAllTrackPairList(r){var t,i,n,a;let e=[];for(const c in this.streamMap){const o=this.streamMap[c];if(o.type!==r)continue;const l=Math.max(o.audioInfoList.length,o.videoInfoList.length);for(let d=0;d<l;d++){const h={url:c,originUrl:o.originUrl};d<o.audioInfoList.length&&(h.aTransceiver=r==="sub"?(t=o.audioInfoList[d].transceiver)==null?void 0:t.receiver:(i=o.audioInfoList[d].transceiver)==null?void 0:i.sender,h.aMsid=o.audioInfoList[d].msid),d<o.videoInfoList.length&&(h.vTransceiver=r==="sub"?(n=o.videoInfoList[d].transceiver)==null?void 0:n.receiver:(a=o.videoInfoList[d].transceiver)==null?void 0:a.sender,h.vMsid=o.videoInfoList[d].msid,h.cumuDelay=o.videoInfoList[d].cumuDelay),e.push(h)}}return e}getAllStreamListWithMsids(){var e;const r=[];for(const t in this.streamMap){const i=this.streamMap[t],n=Math.max(i.audioInfoList.length,i.videoInfoList.length,i.streamList.length),a={url:t,msids:[],type:i.type,latestUrl:i.latestUrl||i.originUrl,streams:[]};for(let c=0;c<n;c++){if(c<i.audioInfoList.length&&i.audioInfoList[c].msid){const o=i.audioInfoList[c];o.msid&&(i.type==="pub"&&o.pubDone||i.type==="sub"&&o.subDone)&&a.msids.push({name:o.msid||"",type:o.type||"audio",streamId:o.streamId})}if(c<i.videoInfoList.length&&i.videoInfoList[c].msid){const o=i.videoInfoList[c];o.msid&&(i.type==="pub"&&o.pubDone||i.type==="sub"&&o.subDone)&&a.msids.push({name:o.msid||"",type:o.type||"video",streamId:o.streamId})}c<i.streamList.length&&i.streamList[c]&&((e=a.streams)==null||e.push(i.streamList[c]))}a.msids.length&&r.push(a)}return r}getSender(r,e,t){var a,c;let i;const n=this.getAllMediaInfoList(r,!0);return t?n.forEach(o=>{var d,h,u;const l=(h=(d=o.transceiver)==null?void 0:d.sender)==null?void 0:h.track;(l==null?void 0:l.kind)===e&&o.msid===t&&(i=(u=o.transceiver)==null?void 0:u.sender)}):i=(c=(a=n==null?void 0:n.find(o=>{var l,d,h;return((h=(d=(l=o.transceiver)==null?void 0:l.sender)==null?void 0:d.track)==null?void 0:h.kind)===e}))==null?void 0:a.transceiver)==null?void 0:c.sender,i}getReceiver(r,e,t){var a,c;let i;const n=this.getAllMediaInfoList(r,!0);return t?n.forEach(o=>{var d,h,u;const l=(h=(d=o.transceiver)==null?void 0:d.receiver)==null?void 0:h.track;(l==null?void 0:l.kind)===e&&o.msid===t&&(i=(u=o.transceiver)==null?void 0:u.receiver)}):i=(c=(a=n==null?void 0:n.find(o=>{var l,d,h;return((h=(d=(l=o.transceiver)==null?void 0:l.receiver)==null?void 0:d.track)==null?void 0:h.kind)===e}))==null?void 0:a.transceiver)==null?void 0:c.receiver,i}dispose(){this.streamMap={},this.streamMapBackup={}}updateMediaInfoList(r,e){const t=e.findIndex(i=>i.msid===r.msid);t!==-1?e.splice(t,1,r):e.push(r)}findMediaItemByMsid(r,e){return e.find(t=>t.msid===r)}createMediaItem(r,e){return{msid:r,ssrc:void 0,transceiver:void 0,subDone:!1,pubDone:!1,type:e,streamId:void 0}}getPubOrSubDoneMediaUrlByIndex(r){let e=0;for(const t in this.streamMap){const i=this.streamMap[t];let n=!1;if(i.audioInfoList.forEach(a=>{n=n||i.type==="pub"&&a.pubDone||i.type==="sub"&&a.subDone}),i.videoInfoList.forEach(a=>{n=n||i.type==="pub"&&a.pubDone||i.type==="sub"&&a.subDone}),n){if(e===r)return t;e++}}}updateLatestUrl(r){const e=this.get(r);return!!e&&(e.latestUrl=r,!0)}}class gu{constructor(r){this.datachannelMap=new Map,this.datachannelMapBackup=new Map}backup(){this.datachannelMapBackup=new Map,this.datachannelMap.forEach((r,e)=>{this.datachannelMapBackup.set(e,Q(D({},r),{msids:[...r.msids],streams:[...r.streams]}))})}restore(){this.datachannelMap=new Map,this.datachannelMapBackup.forEach((r,e)=>{this.datachannelMap.set(e,r)})}update(r){const e=this.datachannelMap.get(r.url);e?r.msids.forEach(t=>{e.msids.find(i=>{if(i.id===t.id&&i.name===t.name)return!0})?console.log("RTS [DATACHANNEL MANAGER]: duplicate msid for datachannel",r):e.msids.push(t)}):this.datachannelMap.set(r.url,r)}remove(r){this.datachannelMap.delete(r.url)}has(r){return this.datachannelMap.has(ke(r,!0))}get(r){return this.datachannelMap.get(ke(r,!0))}getByMsid(r){var t;if(!r.url)return void console.warn("[getByMsid] config.url is required.");const e=this.datachannelMap.get(ke(r.url,!0));return e?r.msid?(t=e.msids.find(i=>i.name===r.msid))==null?void 0:t.datachannel:e.msids[0].datachannel:void 0}getAllList(){const r=[];return this.datachannelMap.forEach(e=>{r.push(Q(D({},e),{latestUrl:e.latestUrl||e.originUrl}))}),r}getSize(){return this.datachannelMap.size}getUrlByIndex(r){let e,t=0;return this.datachannelMap.forEach(i=>{t===r&&(e={url:i.originUrl}),t++}),e}updateLatestUrl(r){const e=this.get(r);return!!e&&(e.latestUrl=r,!0)}dispose(){this.datachannelMap.clear(),this.datachannelMapBackup.clear()}}class Su{constructor(r){this.fakeSdpParams={direction:"sub",mids:[],medias:[]},this.pcCore=r}setFakeSdpMids(r){this.fakeSdpParams.mids=r}setFakeSdpMedias(r,e){this.fakeSdpParams.medias=r,this.fakeSdpParams.direction=e}saveStreamManager(r){var e;this.streamManager=r,(e=this.streamManager)==null||e.backup()}saveDatachannelManager(r){var e;this.datachannelManager=r,(e=this.datachannelManager)==null||e.backup()}rollback(r){return _(this,null,function*(){if(r!=null&&r.trackListnerRollback&&(this.pcCore.removeTrackListener(),this.log("Sub Track Listener Removed")),(r==null?void 0:r.streamManagerRollback)&&this.streamManager){this.streamManager.restore();try{this.log("Stream Manager Restored",JSON.parse(he(this.streamManager)))}catch(e){}}if(r!=null&&r.datachannelManagerRollback&&this.datachannelManager){this.datachannelManager.restore();try{this.log("Datachannel Manager Restored",JSON.parse(he(this.datachannelManager)))}catch(e){}}if(r!=null&&r.pcTransceiversRollback&&(this.fakeSdpParams.medias.forEach(e=>{var t;(t=e.trans)==null||t.receiver.track.stop()}),this.log("Sub Track(s) Stopped",this.fakeSdpParams.medias)),r==null?void 0:r.runSimulateSignal){this.log("SDP Simulating...",this.fakeSdpParams);try{yield this.pcCore.simulateOfferAnswer(this.fakeSdpParams),this.log("SDP Simulation Done")}catch(e){this.log("SDP Simulation Failed",e)}}})}log(...r){window.RTS_DATACHANNEL_DEBUG&&console.log("[PC-Core-Rollback]",...r)}}const bu=[Hs.NGX_RTC_STREAM_NO_FOUND,Hs.NGX_RTC_DATACHANNEL_HEBT_MSID_NOT_FOUND];class vu extends Ir{constructor(r,e){super(),this.latestHeartbeatMsgId=-1,this.streamManager=r,this.datachannelManager=e}process(r){const e=this.parseFormat(r);if(!e)return;if(e.type===fr.HEBT&&e.msg_id<this.latestHeartbeatMsgId)return void console.warn("丢弃过时心跳",e.msg_id,"latest:",this.latestHeartbeatMsgId);const{valid:t,error:i,reason:n}=this.checkRecode(e);if(!t)return e.recode===3?void this.emit("datachannelNotEnabled"):void(i&&this.emit("pcReconnect",{recode:e.recode,reMsg:n}));this.emit("hebtReceived",e),this.checkStreams(e).forEach(a=>{const c={resCode:a.resCode,resMsg:a.resMsg,url:a.url,msids:a.msids,streams:a.streams,type:a.type,latestUrl:a.latestUrl};a.isReconnectable?this.emit("streamReconnect",c):this.emit("streamError",c)})}setLatestHeartbeatMsgId(r){this.latestHeartbeatMsgId=r}dispose(){this.removeAllListeners()}parseFormat(r){try{return JSON.parse(r)}catch(e){console.log("Heartbeat parse failed."," Response Data: ",r)}}checkRecode(r){const e={valid:!1,error:!1,reason:""};return r.type!==fr.HEBT?(e.reason="not heartbeat signal, ignore",e):r.recode!==0?(e.reason=r.msg,e.error=!0,e):(e.valid=!0,e)}checkStreams(r){const e=[];return!r.streams||!r.streams.length||[...this.streamManager.getAllStreamListWithMsids(),...this.datachannelManager.getAllList()].forEach(t=>{var n;let i=-1;if(r.streams.find((a,c)=>{if(a.url===t.url)return i=c,!0})&&i!==-1){const a=r.streams[i];if(a.method===fr.HEBT&&a.res_code===200){a.traceid&&this.emit("traceIdUpdate",{url:a.url,traceId:a.traceid});const c=[];t.msids.forEach(l=>{a.msid.find(d=>d.name===l.name)||c.push(l)});const o=(n=t.streams)==null?void 0:n.filter(l=>!!c.find(d=>d.streamId===l.id));c.length&&e.push({url:t.url,msids:c,streams:o,isReconnectable:!0,resMsg:"RTS heartbeat msid mismatch",resCode:404,type:t.type,latestUrl:t.latestUrl})}else e.push({url:t.url,msids:t.msids,streams:t.streams,isReconnectable:this.isReconnectableErrorCode(a.res_code),resMsg:a.res_msg,resCode:a.res_code,type:t.type,latestUrl:t.latestUrl})}}),e}isReconnectableErrorCode(r){return bu.includes(r)}}let Ru=class{constructor(s){this.switchName=s.switchName,this.displayName=s.displayName}log(...s){window[this.switchName||Math.random()]&&console.log(`${this.now()} [${this.displayName}]`,...s)}now(){const s=new Date;return`${this.padStart(s.getHours())}:${this.padStart(s.getMinutes())}:${this.padStart(s.getSeconds())}.${this.padStart(s.getMilliseconds(),3)}`}padStart(s,r=2,e="0"){return String(s).padStart(r,e)}};class Eu extends Ir{constructor(){super(),this.logger=new Ru({displayName:"NotifyProcessor",switchName:"RTS_NOTIFY_DEBUG"})}processIpMigration(r){var i,n;const e=this.parseFormat(r);if(!e||!this.checkRelated(e))return;this.logger.log("【processIpMigration】parsedData",e),this.emit("message",{message:e});const t=this.parseIP(e.notify_msg);(i=t.pull)!=null&&i.length||(n=t.push)!=null&&n.length?(console.warn("【processIpMigration】需要重连",t),this.emit("pcReconnect",{ips:t})):this.logger.log("【processIpMigration】No valid ip found: ",e.notify_msg)}processSubStreamInfo(r){const e=this.parseFormat(r);if(this.logger.log("【processSubStreamInfo】parsedData",e),e&&this.checkRelated(e,3))return e}processInternalException(r){const e=this.parseFormat(r);if(!e||!this.checkRelated(e,1))return;this.emit("message",{message:e}),this.logger.log("【processInternalException】parsedData",e);let t=Number(e.res_code);t&&![200,204,205,207,221,403,404,405,429,504,616,409,601].includes(t)?(console.warn("【processInternalException】需要重连",t),this.emit("pcReconnect",{})):this.logger.log("【processInternalException】Error code should not retry ",t)}dispose(){this.removeAllListeners()}parseFormat(r){try{return JSON.parse(r)}catch(e){console.warn("Notify parse failed."," Response Data: ",r)}}checkRelated(r,e=2){return r.type===fr.NOTI&&r.notify_type===e}parseIP(r=""){this.logger.log(`Paring IP string: ${r}`);const e=r.split(";"),t=/^(?:\d{1,3}\.){3}\d{1,3}$/,i=/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/,n=/^(push|pull)_ips:(.*)$/;let a={};return e.forEach(c=>{const o=n.exec(c);if(o){const[,l,d]=o;let h=d.split(",").filter(u=>t.test(u)||i.test(u));a[l]=h}}),this.logger.log("Parsed IP:",a),a}}const Sc="rts video",bc="rts audio";class Tt extends Ir{constructor(r){super(),this.PCCore=r}excuteSignal(r,e,t,i){switch(r){case"join pub sub":this.PCCore.proceedJoinPubSub(i.configList).then(n=>{e(n)}).catch(n=>{t(n)}).finally(()=>{this.emit("onSignalDone")});break;case"subsribe add":this.PCCore.proceedSubscribeAdd(i.configList,i.reconnecting,i.preSubAdd).then(n=>{e(n)}).catch(n=>{t(n)}).finally(()=>{this.emit("onSignalDone")});break;case"subscribe delete":this.PCCore.proceedSubscribeDeleteTracks(i.configList,i.skipError).then(n=>{e(n)}).catch(n=>{t(n)}).finally(()=>{this.emit("onSignalDone")});break;case"subscribe active":break;case"subscribe stop":this.PCCore.proceedSubscribeStop(i.configList).then(n=>{e(n)}).catch(n=>{t(n)}).finally(()=>{this.emit("onSignalDone")});break;case"publish add":this.PCCore.proceedPublishAdd(i.configList,i.prePubAdd,i.assignedSsrcs).then(n=>{e(n)}).catch(n=>{t(n)}).finally(()=>{this.emit("onSignalDone")});break;case"publish replace":this.PCCore.proceedPublishReplaceTracks(i.configList).then(n=>{e(n)}).catch(n=>{t(n)}).finally(()=>{this.emit("onSignalDone")});break;case"publish delete":this.PCCore.proceedPublishDeleteTracks(i.configList).then(n=>{e(n)}).catch(n=>{t(n)}).finally(()=>{this.emit("onSignalDone")});break;case"publish stop":this.PCCore.proceedPublishStop(i.configList).then(n=>{e(n)}).catch(n=>{t(n)}).finally(()=>{this.emit("onSignalDone")});break;case"sub add datachannel":this.PCCore.proceedSubscribeAddDatachannel(i.configList).then(n=>{e(n)}).catch(n=>{t(n)}).finally(()=>{this.emit("onSignalDone")});break;case"sub delete datachannel":this.PCCore.proceedSubscribeDeleteDatachannel(i.configList).then(n=>{e(n)}).catch(n=>{t(n)}).finally(()=>{this.emit("onSignalDone")});break;case"sub stop datachannel":this.PCCore.proceedSubscribeStopDatachannel(i.configList).then(n=>{e(n)}).catch(n=>{t(n)}).finally(()=>{this.emit("onSignalDone")});break;case"pub add datachannel":this.PCCore.proceedPublishAddDatachannel(i.configList).then(n=>{e(n)}).catch(n=>{t(n)}).finally(()=>{this.emit("onSignalDone")});break;case"pub delete datachannel":this.PCCore.proceedPublishDeleteDatachannel(i.configList).then(n=>{e(n)}).catch(n=>{t(n)}).finally(()=>{this.emit("onSignalDone")});break;case"pub stop datachannel":this.PCCore.proceedPublishStopDatachannel(i.configList).then(n=>{e(n)}).catch(n=>{t(n)}).finally(()=>{this.emit("onSignalDone")})}}}class yu extends Ir{constructor(r){super(),this.heartbeatTimelineMap=new Map,this.removeTwcc=!1,this.mutex=!1,this.eventQueue=new Ki("signal queue"),this.rollbackController=new Su(this),this.onInnerSubscribeDelete=()=>{},this.receiverCodecPreferences={},this.senderCodecPreferences={},this.removeTrackListener=()=>{},this.heartbeatTimerHandle=null,this.heartbeatTokenRing=0,this.extMap={},this.streamManager=new fu,this.datachannelManager=new gu,r.pc?(this.pc=r.pc,this.signal=new pu({pc:r.pc,onDatachannelEvent:r.onDatachannelEvent,delayOpen:r.delayOpen,initOptions:r.signalDatachannelInitOptions}),this.initSignalListener(),this.heartbeatProcessor=new vu(this.streamManager,this.datachannelManager),this.initHeartbeatListener(),this.notifyProcessor=new Eu,this.initNotifyListener(),this.onePcProcessor=new mu,this.initOnePcListener(),this.onInnerSubscribeDelete=r.onInnerSubscribeDelete||(()=>{}),this.offerSdpHook=r.offerSdpHook,this.answerSdpHook=r.answerSdpHook):console.error("peerconnetion is required")}getStreamManager(){return this.streamManager}getDatachannelManager(){return this.datachannelManager}getSignal(){return this.signal}setPrevOfferSdp(r){this.prevOfferSdp=r}setPrevAnswerSdp(r){this.prevAnswerSdp=r}setStreamManager(r){this.streamManager=r}getTrackIds(r){return r.reduce((e,t)=>[...e,t.id],[])}setRemoveTwcc(r){this.removeTwcc=r}setReceiverCodecPreferences(r){this.receiverCodecPreferences=D({},r)}setSenderCodecPreferences(r){this.senderCodecPreferences=D({},r)}joinPubSub(r){return new Promise((e,t)=>{let i=new Tt(this);if(this.mutex){let n={type:"join pub sub",excuter:i,res:e,rej:t,data:{configList:r}};this.eventQueue.cache(n)}else this.atomSignalExec("join pub sub",i,e,t,{configList:r})})}subscribeAdd(r,e,t){return new Promise((i,n)=>{let a=new Tt(this);if(this.mutex){let c={type:"subsribe add",excuter:a,res:i,rej:n,data:{configList:r,reconnecting:e,preSubAdd:t}};this.eventQueue.cache(c)}else this.atomSignalExec("subsribe add",a,i,n,{configList:r,reconnecting:e,preSubAdd:t})})}subscribeDeleteTracks(r,e){return new Promise((t,i)=>{let n=new Tt(this);if(this.mutex){let a={type:"subscribe delete",excuter:n,res:t,rej:i,data:{configList:r,skipError:e}};this.eventQueue.cache(a)}else this.atomSignalExec("subscribe delete",n,t,i,{configList:r,skipError:e})})}subscribeStop(r){return new Promise((e,t)=>{let i=new Tt(this);if(this.mutex){let n={type:"subscribe stop",excuter:i,res:e,rej:t,data:{configList:r}};this.eventQueue.cache(n)}else this.atomSignalExec("subscribe stop",i,e,t,{configList:r})})}publishAdd(r,e,t){return new Promise((i,n)=>{let a=new Tt(this);if(this.mutex){let c={type:"publish add",excuter:a,res:i,rej:n,data:{configList:r,prePubAdd:e,assignedSsrcs:t}};this.eventQueue.cache(c)}else this.atomSignalExec("publish add",a,i,n,{configList:r,prePubAdd:e,assignedSsrcs:t})})}publishReplaceTracks(r){return new Promise((e,t)=>{let i=new Tt(this);if(this.mutex){let n={type:"publish replace",excuter:i,res:e,rej:t,data:{configList:r}};this.eventQueue.cache(n)}else this.atomSignalExec("publish replace",i,e,t,{configList:r})})}publishDeleteTracks(r){return new Promise((e,t)=>{let i=new Tt(this);if(this.mutex){let n={type:"publish delete",excuter:i,res:e,rej:t,data:{configList:r}};this.eventQueue.cache(n)}else this.atomSignalExec("publish delete",i,e,t,{configList:r})})}publishStop(r){return new Promise((e,t)=>{let i=new Tt(this);if(this.mutex){let n={type:"publish stop",excuter:i,res:e,rej:t,data:{configList:r}};this.eventQueue.cache(n)}else this.atomSignalExec("publish stop",i,e,t,{configList:r})})}subscribeAddDatachannel(r){return new Promise((e,t)=>{let i=new Tt(this);if(this.mutex){let n={type:"sub add datachannel",excuter:i,res:e,rej:t,data:{configList:r}};this.eventQueue.cache(n)}else this.atomSignalExec("sub add datachannel",i,e,t,{configList:r})})}subscribeDeleteDatachannel(r){return new Promise((e,t)=>{let i=new Tt(this);if(this.mutex){let n={type:"sub delete datachannel",excuter:i,res:e,rej:t,data:{configList:r}};this.eventQueue.cache(n)}else this.atomSignalExec("sub delete datachannel",i,e,t,{configList:r})})}subscribeStopDatachannel(r){return new Promise((e,t)=>{let i=new Tt(this);if(this.mutex){let n={type:"sub stop datachannel",excuter:i,res:e,rej:t,data:{configList:r}};this.eventQueue.cache(n)}else this.atomSignalExec("sub stop datachannel",i,e,t,{configList:r})})}publishAddDatachannel(r){return new Promise((e,t)=>{let i=new Tt(this);if(this.mutex){let n={type:"pub add datachannel",excuter:i,res:e,rej:t,data:{configList:r}};this.eventQueue.cache(n)}else this.atomSignalExec("pub add datachannel",i,e,t,{configList:r})})}publishDeleteDatachannel(r){return new Promise((e,t)=>{let i=new Tt(this);if(this.mutex){let n={type:"pub delete datachannel",excuter:i,res:e,rej:t,data:{configList:r}};this.eventQueue.cache(n)}else this.atomSignalExec("pub delete datachannel",i,e,t,{configList:r})})}publishStopDatachannel(r){return new Promise((e,t)=>{let i=new Tt(this);if(this.mutex){let n={type:"pub stop datachannel",excuter:i,res:e,rej:t,data:{configList:r}};this.eventQueue.cache(n)}else this.atomSignalExec("pub stop datachannel",i,e,t,{configList:r})})}atomSignalExec(r,e,t,i,n){this.mutex=!0,e.once("onSignalDone",()=>{this.eventQueue.isEmpty()?this.mutex=!1:setTimeout(()=>{let a=this.eventQueue.getFirst();this.atomSignalExec(a.type,a.excuter,a.res,a.rej,a.data)})}),e.excuteSignal(r,t,i,n)}proceedJoinPubSub(r){return _(this,null,function*(){var e;return(e=this.signal)==null?void 0:e.joinPubSub(r)})}processSubscribeOffer(r){const e=new Je({sdp:r.sdp||""});return e.addNack(),e.updateBundle(),e.generate()}proceedSubscribeAdd(r,e,t){return _(this,null,function*(){this.log("SUB LIST: ",r,e,t);let i=new Date().getTime(),n=new Date().getTime(),a=new Date().getTime();const c=this,o=this.extendUrl(r),l=o.map(h=>{const{urlData:u,vMsid:p,aMsid:f}=h;if(this.streamManager.has(u.url)){const m=this.streamManager.get(u.url),g=m.videoInfoList.map(T=>T.msid),S=m.audioInfoList.map(T=>T.msid),v=dc(g,p),E=dc(S,f);if(E.length||v.length)return{url:u.url,vMsid:v,aMsid:E}}}).filter(h=>h);let d=[];if(l!=null&&l.length)try{d=yield this.proceedSubscribeDeleteTracks(l,!0,e),this.onInnerSubscribeDelete&&this.onInnerSubscribeDelete(l)}catch(h){const u=h;throw u.extraInfo=Q(D({},u.extraInfo),{api:"subscribeAdd",signal_api:"subscribeDeleteTracks",configList:r}),u}return i=new Date().getTime(),new Promise((h,u)=>_(this,null,function*(){var M;if(!this.pc)return u(new lt(Ye.CORE_NO_PC_ERROR,"subscribeAdd: no peerconnection",""));function p(){return _(this,null,function*(){c.removeTrackListener();const I=c.buildUrlStreamMap(o);if(!t)try{const j=yield c.subscribeActive(r);I.forEach((K,B)=>{K.urlTraceId=j.streams[B].url_traceid})}catch(j){return j.extraInfo=Q(D({},j.extraInfo),{api:"subscribeAdd",signal_api:"subscribeActive"}),c.rollbackController.rollback({pcTransceiversRollback:!0,streamManagerRollback:!0}),u(j)}n=new Date().getTime(),h({deleteRspTime:i,subAddRspTime:a,activeRspTime:n,streamList:I})})}this.pc.addEventListener("track",p),this.removeTrackListener=()=>{var I;(I=this.pc)==null||I.removeEventListener("track",p)},this.rollbackController.saveStreamManager(this.streamManager);let f=[];const m={video:void 0,audio:void 0};let g;o.forEach(I=>{var F,X;const{urlData:j,vMsid:K,aMsid:B}=I;if(this.pc){if(this.streamManager.init(j.url),j.subVideo&&!this.streamManager.isMsidSubPubDone(j.url,{vMsid:K[0]})){const $=this.pc.addTransceiver("video",{direction:"recvonly"});f.push({type:"video",msid:K[0],trans:$});let se=(F=d.find(N=>N.vMsid===K[0]))==null?void 0:F.vStream;this.streamManager.update(j.url,{vMsid:K[0],vTransceiver:$,stream:se,cumuDelay:this.cumuDelay}),this.setCodecPreferences($,this.receiverCodecPreferences.video),m.video=$}if(j.subAudio&&!this.streamManager.isMsidSubPubDone(j.url,{aMsid:B[0]})){const $=this.pc.addTransceiver("audio",{direction:"recvonly"});f.push({type:"audio",msid:B[0],trans:$});let se=(X=d.find(N=>N.aMsid===B[0]))==null?void 0:X.aStream;this.streamManager.update(j.url,{aMsid:B[0],aTransceiver:$,stream:se}),this.setCodecPreferences($,this.receiverCodecPreferences.audio),m.audio=$}}}),this.rollbackController.setFakeSdpMedias(f,"sub");try{g=yield this.pc.createOffer()}catch(I){return u(new lt(Ye.DATACHANNEL_CREATE_OFFER_ERROR,`CreateOffer Error: ${I}`,"",{api:"subscribeAdd",err:I}))}const S=new Je({sdp:g.sdp||""});if(this.restorePublishedSsrc(S),S.addNack(),S.updateBundle(),t){const I=new Je({sdp:t.streams[0].sdp});this.alignOfferExtValueWithAnswer(I,S)}g=new RTCSessionDescription({type:"offer",sdp:S.generate()});const v=this.findNewSubPubMids((g==null?void 0:g.sdp)||"",this.prevOfferSdp||"");this.setPrevOfferSdp(g.sdp||""),this.rollbackController.setFakeSdpMids(v);let E=this.avoidMsidConflict(g.sdp);if(this.offerSdpHook)try{E=this.offerSdpHook(E)}catch(I){console.log("offerSdpHook error: ",I)}try{yield this.pc.setLocalDescription(new RTCSessionDescription({type:"offer",sdp:E}))}catch(I){return yield this.rollbackController.rollback({trackListnerRollback:!0,pcTransceiversRollback:!0,streamManagerRollback:!0,runSimulateSignal:!0}),u(new lt(Ye.DATACHANNEL_SET_OFFER_ERROR,`SetLocalDescription error: ${I}`,"",{api:"subscribeAdd",sdp:g}))}let T,R=[],y=[];if(o.forEach(I=>{const j=new Je({sdp:(g==null?void 0:g.sdp)||""});let K=[],B=I.vMsid.length!==0,F=I.aMsid.length!==0,X=!1,$=!1;j.detail.media.forEach(N=>{const V=String(N.mid);v.includes(V)&&(y.includes(V)||(N.type==="video"&&B&&!X?(K.push(String(N.mid)),X=!0):N.type==="audio"&&F&&!$&&(K.push(String(N.mid)),$=!0)))}),y=[...y,...K],j.keepMedia(K);let se=j.generate();this.cumuDelay&&(se=se.replace(/(m=video[^\n]*\n)/,`$1a=cumudelay
172
+ `)),R.push(se)}),this.offerSdpHook)try{R=R.map(I=>this.offerSdpHook(I))}catch(I){console.log("offerSdpHook error: ",I)}try{T=t||(yield(M=this.signal)==null?void 0:M.subscribeAdd(o,R,this.streamManager))}catch(I){return yield this.rollbackController.rollback({trackListnerRollback:!0,pcTransceiversRollback:!0,streamManagerRollback:!0,runSimulateSignal:!0}),I.extraInfo=D({api:"subscribeAdd",signal_api:"subscribeAdd"},I.extraInfo),u(I)}let C=[];T.streams.forEach((I,j)=>{this.log(`Sub TraceId[${j}]: `,I.traceid);const K=new Je({sdp:I.sdp});t&&(K.detail.media=K.detail.media.filter(F=>F.type==="video"&&m.video?(F.mid=m.video.mid,!0):!(F.type!=="audio"||!m.audio)&&(F.mid=m.audio.mid,!0))),C=[...C,...K.detail.media];const B=o.find(F=>F.urlData.url===I.url);B&&(B.traceId=I.traceid,B.urlTraceId=I.url_traceid)});const w=new Je({sdp:this.prevAnswerSdp||""});w.addOrUpdateMedia(C),this.alignAnswerMidsWithOffer(w);const A=w.generate();this.setPrevAnswerSdp(A);let P=this.avoidMsidConflict(A);if(this.answerSdpHook)try{P=this.answerSdpHook(P)}catch(I){console.log("answerSdpHook error: ",I)}try{yield this.pc.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:P})),o.forEach(I=>{this.streamManager.markAlreadySubPub(I.urlData.url,{vMsid:I.vMsid[0],aMsid:I.aMsid[0]})})}catch(I){return yield this.rollbackController.rollback({trackListnerRollback:!0,pcTransceiversRollback:!0,streamManagerRollback:!0}),u(new lt(Ye.DATACHANNEL_SET_ANSWER_ERROR,`SetRemoteDescription error: ${I}`,"",{api:"subscribeAdd",sdp:A}))}a=new Date().getTime()}))})}subscribeActive(r){return _(this,null,function*(){var e;return(e=this.signal)==null?void 0:e.subscribeActive(this.extendUrl(r))})}proceedSubscribeDeleteTracks(r,e,t){return _(this,null,function*(){var d,h,u,p;r.forEach(f=>{f.rawUrl=f.url,f.url=this.streamManager.getOriginUrl(f.url)});let i,n=!1,a=!!e;try{yield(d=this.signal)==null?void 0:d.subscribeDelete(r)}catch(f){i=f,n=i.errorCode===Ye.DATACHANNEL_RESPONSE_ERROR&&((u=(h=i.extraInfo)==null?void 0:h.parsedData)==null?void 0:u.streams)&&((p=i.extraInfo.parsedData.streams[0])==null?void 0:p.res_code)===404}if(i&&!n)throw i.extraInfo=D({api:"subscribeDeleteTracks"},i.extraInfo),i;const c=a&&n;let o=[];const l=r.map(v=>_(this,[v],function*({url:f,vMsid:m,aMsid:g,rawUrl:S}){var w,A;let E,T,R,y;if(f=ke(f),this.streamManager.has(f)){if(m){const P=this.streamManager.getTransceiver(f,{vMsid:m[0]});P&&(T=P.receiver.track,T.stop())}if(g){const P=this.streamManager.getTransceiver(f,{aMsid:g[0]});P&&(E=P.receiver.track,E.stop())}}try{yield this.simulateOfferAnswer()}catch(P){throw P.extraInfo=D({api:"subscribeDeleteTracks"},P.extraInfo),P}T&&(R=this.streamManager.getStreamByMsid({url:f,vMsid:m==null?void 0:m[0]}),(w=R==null?void 0:R.mediastream)==null||w.removeTrack(T)),E&&(y=this.streamManager.getStreamByMsid({url:f,aMsid:g==null?void 0:g[0]}),(A=y==null?void 0:y.mediastream)==null||A.removeTrack(E)),t||this.streamManager.pruneStreamList(f),this.streamManager.removeMsid(f,{vMsid:m!=null&&m.length?this.unifyMsid(m,"video"):void 0,aMsid:g!=null&&g.length?this.unifyMsid(g,"audio"):void 0});let C={url:S||"",stream:this.streamManager.getStreamByMsid({url:f,vMsid:m==null?void 0:m[0],aMsid:g==null?void 0:g[0]})};t&&(C=Q(D({},C),{vStream:R,aStream:y,vMsid:m==null?void 0:m[0],aMsid:g==null?void 0:g[0]})),o.push(C)}));if(yield Promise.all(l),!c&&i)throw i.extraInfo=D({api:"subscribeDeleteTracks"},i.extraInfo),i;return o})}proceedSubscribeStop(r){return _(this,null,function*(){var t;try{yield(t=this.signal)==null?void 0:t.subscribeStop(this.extendUrl(r))}catch(i){throw i.extraInfo=D({api:"subscribeStop"},i.extraInfo),i}r.forEach(i=>{i.rawUrl=i.url,i.url=this.streamManager.getOriginUrl(i.url)});const e=r.map(c=>_(this,[c],function*({url:i,rawUrl:n,targetStreams:a}){i=ke(i),this.streamManager.getAllTransceivers(i).forEach(o=>{var l;(l=o==null?void 0:o.receiver.track)==null||l.stop()}),this.streamManager.get(i).streamList.forEach(o=>o.release()),this.streamManager.remove(i);try{yield this.simulateOfferAnswer()}catch(o){throw o.extraInfo=D({api:"subscribeStop"},o.extraInfo),o}}));yield Promise.all(e)})}processPublishOffer(r,e){const t=this.unifyMsid(e.aMsid,"audio"),i=this.unifyMsid(e.vMsid,"video"),n=new Je({sdp:r.sdp||""}),a=this.parseMsidString(i),c=this.parseMsidString(t);let o,l;return a.stream&&n.detail.msidSemantic&&(n.detail.msidSemantic.token=a.stream),n.detail.media.forEach(d=>{var h,u,p;if(d.direction!=="recvonly"&&d.type!=="application"){const f=d.type==="video"?a:c,m=this.parseMsidString(d.msid);m.stream=f.stream||m.stream,m.track=f.track||m.track;const g=this.stringifyMsid(m);d.msid=g,d.type==="video"?o=(h=d.ssrcs)==null?void 0:h.map(S=>S.id):d.type==="audio"&&(l=(u=d.ssrcs)==null?void 0:u.map(S=>S.id)),(p=d.ssrcs)==null||p.forEach(S=>{switch(S.attribute){case"cname":case"label":S.value=f.track||S.value;break;case"msid":S.value=g;break;case"mslabel":S.value=f.stream||S.value}})}}),n.addNack(),{sdp:n.generate(),videoSsrcs:o,audioSsrcs:l}}proceedPublishAdd(r,e,t){return _(this,null,function*(){var M;if(this.log("PUB LIST: ",r,e,t),r.length>1)throw console.error("Only one stream is supported."),new lt(Ye.CORE_PUBLIST_EXCEED_ERROR,"publishAdd: publishList exceed limit","",{api:"publishAdd"});if(!this.pc)throw new lt(Ye.CORE_NO_PC_ERROR,"publishAdd: no peerconnection","",{api:"publishAdd"});const i=r[0],n=i.stream,a=this.unifyMsid(i.aMsid,"audio"),c=this.unifyMsid(i.vMsid,"video");i.rawUrl=i.url,i.url=this.streamManager.getOriginUrl(i.url),typeof i.updateSourceStream!="boolean"&&(i.updateSourceStream=!0);const o=n.videoTrack,l=n.audioTrack;this.rollbackController.saveStreamManager(this.streamManager);let d=[];const h=this.streamManager.getStreamByMsid({url:i.url,vMsid:c,aMsid:a});this.streamManager.init(i.url,js.Publish);const u={video:void 0,audio:void 0};if(o){const I=this.pc.addTransceiver(n.videoTrack,{direction:"sendonly"});this.streamManager.update(i.url,{vMsid:c,vTransceiver:I,stream:n,cumuDelay:this.cumuDelay}),d.push({type:"video",trans:I,msid:c}),this.setCodecPreferences(I,this.senderCodecPreferences.video),u.video=I}if(l){const I=this.pc.addTransceiver(n.audioTrack,{direction:"sendonly"});this.streamManager.update(i.url,{aMsid:a,aTransceiver:I,stream:n}),d.push({type:"audio",trans:I,msid:a}),this.setCodecPreferences(I,this.senderCodecPreferences.audio),u.audio=I}let p;this.rollbackController.setFakeSdpMedias(d,"pub");try{p=yield this.pc.createOffer()}catch(I){throw new lt(Ye.DATACHANNEL_CREATE_OFFER_ERROR,`CreateOffer Error: ${I}`,"",{api:"publishAdd",err:I})}const f=new Je({sdp:p.sdp||""}),m=this.parseMsidString(c),g=this.parseMsidString(a),S=this.findNewSubPubMids(p.sdp||"",this.prevOfferSdp||"");this.rollbackController.setFakeSdpMids(S),m.stream&&f.detail.msidSemantic&&(f.detail.msidSemantic.token=m.stream);let v=f.detail.media.reduce((I,j)=>j.direction==="inactive"?[...I,String(j.mid)]:I,[]);if(f.detail.media.forEach(I=>{var j,K,B,F;if(I.direction!=="recvonly"&&I.type!=="application"&&S.includes(String(I.mid))){const X=I.type==="video"?m:g,$=this.parseMsidString(I.msid);$.stream=X.stream||$.stream,$.track=X.track||$.track;const se=this.stringifyMsid($);I.msid=se;const N=I.type==="video"?t==null?void 0:t.video:t==null?void 0:t.audio;if(N){if(N.length!==((j=I.ssrcs)==null?void 0:j.length))throw new lt(Ye.CORE_PUBLIST_EXCEED_ERROR,"publishAdd: ssrcs exceed limit","",{api:"publishAdd"});I.ssrcs.forEach((V,x)=>{V.id=N[x]}),(B=(K=I.ssrcGroups)==null?void 0:K[0])!=null&&B.ssrcs&&(I.ssrcGroups[0].ssrcs=Array.from(new Set(N)).join(" "))}(F=I.ssrcs)==null||F.forEach(V=>{switch(V.attribute){case"cname":case"label":V.value=X.track||V.value;break;case"msid":V.value=se;break;case"mslabel":V.value=X.stream||V.value}})}}),this.restorePublishedSsrc(f),this.restorePublishMsid(f),f.addNack(),e){const I=new Je({sdp:e.streams[0].sdp});this.alignOfferExtValueWithAnswer(I,f)}const E=f.generate();this.setPrevOfferSdp(E);let T,R=this.avoidMsidConflict(E);if(this.offerSdpHook)try{R=this.offerSdpHook(R)}catch(I){console.log("offerSdoHook error: ",I)}try{yield this.pc.setLocalDescription(new RTCSessionDescription({type:"offer",sdp:R}))}catch(I){throw this.rollbackController.rollback({streamManagerRollback:!0,runSimulateSignal:!0}),new lt(Ye.DATACHANNEL_SET_OFFER_ERROR,`SetLocalDescription error: ${I}`,"",{api:"publishAdd",sdp:E})}if(f.keepMedia(S),this.updateTrackInfoList({url:i.rawUrl,stream:i.stream,vMsid:c,aMsid:a,sdpMediaList:f.detail.media}),R=f.generate(),this.offerSdpHook)try{R=this.offerSdpHook(R)}catch(I){console.log("offerSdpHook error: ",I)}try{T=e||(yield(M=this.signal)==null?void 0:M.publishAdd([i.url],[R],[o?[this.stringifyMsid(m)]:[]],[l?[this.stringifyMsid(g)]:[]]))}catch(I){const j=I;throw j.extraInfo=D({api:"publishAdd"},j.extraInfo),this.rollbackController.rollback({streamManagerRollback:!0,runSimulateSignal:!0}),u.video&&(u.video.direction="inactive"),u.audio&&(u.audio.direction="inactive"),j}const y=T.streams[0];i.traceId=y.traceid,i.urlTraceId=y.url_traceid,this.log("Pub TraceId: ",i.traceId);const C=new Je({sdp:y.sdp});C.detail.media.forEach(I=>{I.type!=="application"&&I.direction==="sendrecv"&&(I.direction="recvonly")}),e&&(C.detail.media=C.detail.media.filter(I=>I.type==="video"&&u.video?(I.mid=u.video.mid,!0):!(I.type!=="audio"||!u.audio)&&(I.mid=u.audio.mid,!0)));const w=new Je({sdp:this.prevAnswerSdp||""});if(w.detail.media.forEach(I=>{I.type==="application"&&(delete I.candidates,delete I.endOfCandidates)}),w.setMediaInactive(v),w.addOrUpdateMedia(C.detail.media,{isPublish:!0}),this.alignAnswerMidsWithOffer(w),this.removeTwcc){const I=["http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"];w.detail.media.forEach(j=>{var K;j.ext=(K=j.ext)==null?void 0:K.filter(B=>!I.includes(B.uri))})}const A=w.generate();this.setPrevAnswerSdp(A);let P=this.avoidMsidConflict(A);if(this.answerSdpHook)try{P=this.answerSdpHook(P)}catch(I){console.log("answerSdpHook error: ",I)}try{yield this.pc.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:P})),this.streamManager.markAlreadySubPub(i.url,{vMsid:c,aMsid:a,isPub:!0})}catch(I){throw this.rollbackController.rollback({streamManagerRollback:!0}),new lt(Ye.DATACHANNEL_SET_ANSWER_ERROR,`SetRemoteDescription error: ${I}`,"",{api:"publishAdd",sdp:A})}return h&&i.updateSourceStream&&h.mergeStream(n),r.map(I=>({url:I.rawUrl,trackInfoList:this.streamManager.getAllMediaInfoList(i.url),traceId:I.traceId,urlTraceId:I.urlTraceId}))})}proceedPublishDeleteTracks(r){return _(this,null,function*(){var a,c,o,l,d,h,u;r.forEach(p=>{p.rawUrl=p.url,p.url=this.streamManager.getOriginUrl(p.url)});try{yield(a=this.signal)==null?void 0:a.publishDelete(r)}catch(p){throw p.extraInfo=D({api:"publishDeleteTracks"},p.extraInfo),p}const e=r[0],t=ke(e.url);typeof e.updateSourceStream!="boolean"&&(e.updateSourceStream=!0);let i=!1,n=!1;if(this.streamManager.has(t)){if((c=e.vMsid)!=null&&c.length){const m=this.streamManager.getTransceiver(t,{vMsid:e.vMsid[0]});m!=null&&m.sender&&((o=this.pc)==null||o.removeTrack(m==null?void 0:m.sender)),i=!0}if((l=e.aMsid)!=null&&l.length){const m=this.streamManager.getTransceiver(t,{aMsid:e.aMsid[0]});m!=null&&m.sender&&((d=this.pc)==null||d.removeTrack(m==null?void 0:m.sender)),n=!0}try{yield this.simulateOfferAnswer()}catch(m){throw m.extraInfo=D({api:"publishDeleteTracks"},m.extraInfo),m}const p=this.streamManager.getStreamByMsid({url:t,vMsid:(h=e.vMsid)==null?void 0:h[0],aMsid:(u=e.aMsid)==null?void 0:u[0]});p&&e.updateSourceStream&&p.deleteTracks({video:i,audio:n}),this.streamManager.removeMsid(t,{vMsid:i?this.unifyMsid(e.vMsid,"video"):void 0,aMsid:n?this.unifyMsid(e.aMsid,"audio"):void 0}),this.streamManager.pruneStreamList(t);const f=this.streamManager.getAllMediaInfoList(e.url);return r.map(m=>({url:m.rawUrl,trackInfoList:f}))}})}proceedPublishReplaceTracks(r){return _(this,null,function*(){var d,h,u,p,f;const e=r[0],{stream:t,vMsid:i,aMsid:n}=e;if(e.rawUrl=e.url,e.url=this.streamManager.getOriginUrl(e.url),!this.streamManager.has(e.url))throw new lt(Ye.CORE_PUB_REPLACE_URL_NOT_FOUND,`No stream found for this url: ${e.url}`,"",{api:"publishReplaceTracks",configList:r});typeof e.updateSourceStream!="boolean"&&(e.updateSourceStream=!0);const{audioTrack:a,videoTrack:c}=t,o=this.streamManager.getAllMediaInfoList(e.url,!0);if(a){const m=(d=o.find(g=>g.type==="audio"&&(!n||g.msid===n)))==null?void 0:d.transceiver;m&&a.id!==((u=(h=m.sender)==null?void 0:h.track)==null?void 0:u.id)&&(yield m.sender.replaceTrack(a))}if(c){const m=o.find(S=>S.type==="video"&&(!i||S.msid===i)),g=m==null?void 0:m.transceiver;g&&c.id!==((f=(p=g.sender)==null?void 0:p.track)==null?void 0:f.id)&&(yield g.sender.replaceTrack(c),t.isCustomStream||(m.from=t.hasScreen?"screen":"camera"))}const l=this.streamManager.getStreamByMsid({url:e.url,vMsid:i,aMsid:n});return l&&e.updateSourceStream&&l.mergeStream(t),r.map(m=>({url:m.rawUrl,trackInfoList:this.streamManager.getAllMediaInfoList(e.url)}))})}proceedPublishStop(r){return _(this,null,function*(){var t;try{yield(t=this.signal)==null?void 0:t.publishStop(r.map(i=>this.streamManager.getOriginUrl(i.url)))}catch(i){throw i.extraInfo=D({api:"publishStop"},i.extraInfo),i}const e=r.map(n=>_(this,[n],function*({url:i}){i=ke(i),this.streamManager.getAllTransceivers(i).forEach(a=>{var c;a!=null&&a.sender&&((c=this.pc)==null||c.removeTrack(a==null?void 0:a.sender))}),this.streamManager.get(i).streamList.forEach(a=>a.deleteTracks({video:!0,audio:!0})),this.streamManager.remove(i);try{yield this.simulateOfferAnswer()}catch(a){throw a.extraInfo=D({api:"publishStop"},a.extraInfo),a}}));yield Promise.all(e)})}proceedSubscribeAddDatachannel(r){return _(this,null,function*(){const e=r.map(t=>{const i=this.datachannelManager.getByMsid({url:t.url,msid:t.msid});return i?(i.dispose(),{url:t.url,msid:t.msid}):null}).filter(t=>t);if(e.length>0)try{yield this.proceedSubscribeDeleteDatachannel(e)}catch(t){const i=t;throw i.extraInfo=Q(D({},i.extraInfo),{api:"subscribeAddDatachannel",signal_api:"subscribeDeleteDatachannel",configList:r}),i}return this.rollbackController.saveDatachannelManager(this.datachannelManager),new Promise((t,i)=>_(this,null,function*(){var a,c;try{yield(a=this.signal)==null?void 0:a.subscribeAddDatachannel(r)}catch(o){return o.extraInfo=D({api:"subscribeAddDatachannel",signal_api:"subscribeAddDatachannel"},o.extraInfo),r.forEach(l=>l.datachannel.dispose()),this.rollbackController.rollback({datachannelManagerRollback:!0}),i(o)}let n={};try{n=yield(c=this.signal)==null?void 0:c.subscribeActiveDatachannel(r)}catch(o){return o.extraInfo=D({api:"subscribeAddDatachannel",signal_api:"subscribeActiveDatachannel"},o.extraInfo),console.log("Trying to rollback datachannel"),r.forEach(l=>l.datachannel.dispose()),this.rollbackController.rollback({datachannelManagerRollback:!0}),i(o)}r.forEach(o=>{this.datachannelManager.update({type:"sub-data",url:ke(o.url,!0),msids:[{name:o.msid,id:o.datachannelId,type:"data",label:o.label,datachannel:o.datachannel}],originUrl:o.url,streams:[]})}),t(n)}))})}proceedSubscribeDeleteDatachannel(r){return _(this,null,function*(){return new Promise((e,t)=>_(this,null,function*(){var i,n,a,c,o;try{yield(i=this.signal)==null?void 0:i.subscribeDeleteDatachannel(r)}catch(l){const d=l;if(((o=(c=(a=(n=d==null?void 0:d.extraInfo)==null?void 0:n.parsedData)==null?void 0:a.streams)==null?void 0:c[0])==null?void 0:o.res_code)!==404)return d.extraInfo=D({api:"subscribeDeleteDatachannel",signal_api:"subscribeDeleteDatachannel"},d.extraInfo),t(l)}r.forEach(l=>{this.datachannelManager.remove({url:ke(l.url,!0)})}),e()}))})}proceedSubscribeStopDatachannel(r){return _(this,null,function*(){return new Promise((e,t)=>_(this,null,function*(){var i,n,a,c,o;try{yield(i=this.signal)==null?void 0:i.subscribeStopDatachannel(r)}catch(l){const d=l;if(((o=(c=(a=(n=d==null?void 0:d.extraInfo)==null?void 0:n.parsedData)==null?void 0:a.streams)==null?void 0:c[0])==null?void 0:o.res_code)!==404)return d.extraInfo=D({api:"subscribeStopDatachannel",signal_api:"subscribeStopDatachannel"},d.extraInfo),t(l)}r.forEach(l=>{this.datachannelManager.remove({url:ke(l.url,!0)})}),e()}))})}proceedPublishAddDatachannel(r){return _(this,null,function*(){return new Promise((e,t)=>_(this,null,function*(){var n;let i={};try{i=yield(n=this.signal)==null?void 0:n.publishAddDatachannel(r)}catch(a){return a.extraInfo=D({api:"publishAddDatachannel",signal_api:"publishAddDatachannel"},a.extraInfo),t(a)}r.forEach(a=>{this.datachannelManager.update({type:"pub-data",url:ke(a.url,!0),msids:[{name:a.msid,id:a.datachannelId,type:"data",label:a.label,datachannel:a.datachannel}],originUrl:a.url,streams:[]})}),e(i)}))})}proceedPublishDeleteDatachannel(r){return _(this,null,function*(){return new Promise((e,t)=>_(this,null,function*(){var i;try{yield(i=this.signal)==null?void 0:i.publishDeleteDatachannel(r)}catch(n){return n.extraInfo=D({api:"publishDeleteDatachannel",signal_api:"publishDeleteDatachannel"},n.extraInfo),t(n)}r.forEach(n=>{this.datachannelManager.remove({url:ke(n.url,!0)})}),e()}))})}proceedPublishStopDatachannel(r){return _(this,null,function*(){return new Promise((e,t)=>_(this,null,function*(){var i;try{yield(i=this.signal)==null?void 0:i.publishStopDatachannel(r)}catch(n){return n.extraInfo=D({api:"publishStopDatachannel",signal_api:"publishStopDatachannel"},n.extraInfo),t(n)}r.forEach(n=>{this.datachannelManager.remove({url:ke(n.url,!0)})}),e()}))})}buildUrlStreamMap(r){let e=[];return r.forEach(({urlData:t,traceId:i,urlTraceId:n,url:a,vMsid:c,aMsid:o})=>{const{url:l}=t,d=new MediaStream;this.streamManager.getAllMediaInfoList(l,!0).forEach(h=>{var u,p;if(h.type==="video"&&h.msid===c[0]||h.type==="audio"&&h.msid===o[0]){const f=(p=(u=h.transceiver)==null?void 0:u.receiver)==null?void 0:p.track;f&&d.addTrack(f)}}),e.push({url:a,stream:d,traceId:i,urlTraceId:n})}),e}extendUrl(r){return r.map(t=>{const{url:i,subAudio:n,subVideo:a,aMsid:c,vMsid:o}=t,l=this.streamManager.getOriginUrl(i),d=new du({url:l,subAudio:n,subVideo:a});return Q(D({},t),{urlData:d,aMsid:d.subAudio?c||[bc]:[],vMsid:d.subVideo?o||[Sc]:[]})})}parseSdp(r){return new Je({sdp:r})}getTrackInfoList(r=[],e,t){let i=[];return r.forEach(n=>{var p,f,m,g;if(n.type==="application")return;const a=Number(n.ssrcs&&((p=n.ssrcs[0])==null?void 0:p.id))||-1,c=n.rtp.find(S=>{var v;return["opus","h264"].includes((v=S.codec)==null?void 0:v.toLowerCase())}),o=(c==null?void 0:c.codec)||"",l=(c==null?void 0:c.payload)||0;let d;e.isCustomStream||n.type==="video"&&(d=e.hasScreen?"screen":"camera");let h=n.msid;if(t!=null&&t.aMsid||t!=null&&t.vMsid){let S=(n.type==="video"?t.vMsid:t.aMsid)||"";S!=null&&S.trim().includes(" ")||(h=(f=n.msid)==null?void 0:f.split(" ")[1])}const u=n.type==="video"?(m=e.videoTrack)==null?void 0:m.id:(g=e.audioTrack)==null?void 0:g.id;i.push({ssrc:a,codec:o,type:n.type,pt:l,msid:h,from:d,trackId:u})}),i}patchSubscribeStreamManagerRecord(r,e){this.extendUrl([{url:r,vMsid:e.vMsid,aMsid:e.aMsid}]).forEach(t=>{const{urlData:i,vMsid:n,aMsid:a}=t;if(!this.pc||(this.cumuDelay=e.cumuDelay,this.streamManager.remove(i.url),this.streamManager.init(i.url),!this.pc.getTransceivers))return;const c=this.pc.getTransceivers()||[];if(i.subVideo){const o=c.find(l=>l.receiver.track.kind==="video");this.streamManager.update(i.url,{vMsid:n[0],vTransceiver:o,stream:e.stream,cumuDelay:e.cumuDelay})}if(i.subAudio){const o=c.find(l=>l.receiver.track.kind==="audio");this.streamManager.update(i.url,{aMsid:a[0],aTransceiver:o,stream:e.stream})}this.streamManager.markAlreadySubPub(r,{vMsid:n[0],aMsid:a[0],isPub:!1})})}patchPublishStreamManagerRecord(r,e){if(!this.pc)return;const t=e.stream,i=t.videoTrack,n=t.audioTrack,a=this.unifyMsid(e.aMsid,"audio"),c=this.unifyMsid(e.vMsid,"video");if(this.streamManager.init(r,js.Publish),this.cumuDelay=e.cumuDelay,!this.pc.getTransceivers)return;const o=this.pc.getTransceivers()||[];if(i){const l=o.find(d=>{var h,u;return((u=(h=d.sender)==null?void 0:h.track)==null?void 0:u.id)===i.id});l&&this.streamManager.update(r,{vMsid:c,vTransceiver:l,stream:e.stream,cumuDelay:e.cumuDelay})}if(n){const l=o.find(d=>{var h,u;return((u=(h=d.sender)==null?void 0:h.track)==null?void 0:u.id)===n.id});l&&this.streamManager.update(r,{aMsid:a,aTransceiver:l,stream:e.stream})}this.streamManager.markAlreadySubPub(r,{vMsid:c,aMsid:a,isPub:!0})}updateTrackInfoList(r){const{url:e,stream:t,vMsid:i,aMsid:n,sdpMediaList:a}=r;e||console.error("[updateTrackInfoList] url is required");const c=this.getTrackInfoList(a,t,{vMsid:i,aMsid:n}),o=c.find(d=>d.type==="video"),l=c.find(d=>d.type==="audio");return i&&o&&this.streamManager.updateSdpInfo(e,D({vMsid:i},o)),n&&l&&this.streamManager.updateSdpInfo(e,D({aMsid:n},l)),c}unifyMsid(r,e){const t=e==="video"?Sc:bc;return(r==null?void 0:r[0])||t}startSignalHeartbeatTimer(r){r&&r<200?console.warn(`PEER CORE: heartbeat interval ${r} is too small and will not take effect. At least 200ms`):(this.stopSignalHeartbeatTimer(),this.heartbeatTimerHandle=window.setInterval(()=>{let e;const t=this.streamManager.getSubOrPubDoneMediaMapSize(),i=t+this.datachannelManager.getSize();if(this.heartbeatTokenRing%=i,this.heartbeatTokenRing<t){const n=this.heartbeatTokenRing,a=this.streamManager.getPubOrSubDoneMediaUrlByIndex(n);a&&(e=[],e.push({url:a}))}else if(this.heartbeatTokenRing<i){const n=this.heartbeatTokenRing-t,a=this.datachannelManager.getUrlByIndex(n);a&&(e=[],e.push(a))}this.heartbeatTokenRing++,this.heartbeatTokenRing%=i,this.sendOnceHeartbeat(e)},r||2500))}stopSignalHeartbeatTimer(){this.heartbeatTimerHandle!==null&&clearInterval(this.heartbeatTimerHandle),this.heartbeatTimerHandle=null}sendOnceHeartbeat(r){var t,i;const e=(t=this.signal)==null?void 0:t.sendHeartbeat(r);e&&(this.hebtLog(">>> Send: heartbeat",e),this.emit("hebtSent",e),this.heartbeatTimelineMap.set(e.msg_id,performance.now()),(i=this.heartbeatProcessor)==null||i.setLatestHeartbeatMsgId(e.msg_id))}sendFalseHeartbeat(r){var t;const e=(t=this.signal)==null?void 0:t.sendFalseHeartbeat(r);e&&(this.hebtLog(">>> Send: false heartbeat",r),this.heartbeatTimelineMap.set(e.msg_id,performance.now()))}dispose(){var r,e,t,i,n;this.pc=void 0,this.prevOfferSdp=void 0,this.prevAnswerSdp=void 0,(r=this.signal)==null||r.dispose(),(e=this.streamManager)==null||e.dispose(),(t=this.datachannelManager)==null||t.dispose(),(i=this.heartbeatProcessor)==null||i.dispose(),(n=this.notifyProcessor)==null||n.dispose(),this.stopSignalHeartbeatTimer(),this.heartbeatTimelineMap.clear(),this.eventQueue=new Ki("signal queue")}initSignalListener(){var e;const r=(e=this.signal)==null?void 0:e.getDatachannelCore();r&&(r.on("atomSend",t=>{this.emit("signalSent",t)}),r.on("atomReceive",t=>{this.emit("signalReceived",t)}))}initHeartbeatListener(){var r,e,t,i,n,a,c;(r=this.heartbeatProcessor)==null||r.on("pcReconnect",o=>{this.emit("pcReconnect",o)}),(e=this.heartbeatProcessor)==null||e.on("streamError",o=>{this.emit("streamError",o)}),(t=this.heartbeatProcessor)==null||t.on("streamReconnect",o=>{this.emit("streamReconnect",o)}),(i=this.heartbeatProcessor)==null||i.on("traceIdUpdate",o=>{this.emit("traceIdUpdate",o)}),(n=this.heartbeatProcessor)==null||n.on("hebtReceived",o=>{if(o){const l=this.heartbeatTimelineMap.get(o.msg_id)||0;this.heartbeatTimelineMap.delete(o.msg_id),this.hebtLog("<<< Received: heartbeat",`${Math.ceil(performance.now()-l)}ms`,o)}this.emit("hebtReceived",o)}),(a=this.heartbeatProcessor)==null||a.on("datachannelNotEnabled",()=>{this.emit("datachannelNotEnabled")}),(c=this.signal)==null||c.getDatachannelCore().on("message",o=>{var l;(l=this.heartbeatProcessor)==null||l.process(o)})}initNotifyListener(){var r,e,t;(r=this.notifyProcessor)==null||r.on("pcReconnect",i=>{this.emit("pcReconnect",i)}),(e=this.notifyProcessor)==null||e.on("message",i=>{this.emit("message",i)}),(t=this.signal)==null||t.getDatachannelCore().on("message",i=>{var n,a;(n=this.notifyProcessor)==null||n.processIpMigration(i),(a=this.notifyProcessor)==null||a.processInternalException(i)})}initOnePcListener(){var r,e,t,i;(r=this.onePcProcessor)==null||r.on("prePub",n=>_(this,null,function*(){this.emit("prePub",n)})),(e=this.onePcProcessor)==null||e.on("preSub",n=>_(this,null,function*(){this.emit("preSub",n)})),(t=this.onePcProcessor)==null||t.on("reconnectRoomServer",()=>{this.emit("reconnectRoomServer")}),(i=this.signal)==null||i.getDatachannelCore().on("message",n=>{var a,c,o;(a=this.onePcProcessor)==null||a.processPrePub(n),(c=this.onePcProcessor)==null||c.processPreSub(n),(o=this.onePcProcessor)==null||o.processReconnectRoomServer(n)})}findNewSubPubMids(r,e){const t=new Je({sdp:r}),i=new Je({sdp:e}),n=t.detail.media.filter(c=>c.direction!=="inactive").map(c=>c.mid),a=i.detail.media.map(c=>c.mid);return this.findDiff(n,a).map(c=>String(c))}findDiff(r,e){return Array.from(new Set([...r].filter(t=>!e.includes(t))))}parseMsidString(r){let e={stream:"",track:""};if(!r)return e;const[t,i]=r.trim().split(" ");return i?(e.stream=t,e.track=i):e.track=t,e}stringifyMsid(r){const{stream:e,track:t}=r;return`${e}${e?" ":""}${t}`}restorePublishedSsrc(r){const e=new Je({sdp:this.prevOfferSdp||""}).getPublishSsrcs();r.detail.media.forEach(t=>{var i;t.direction!=="recvonly"&&((i=t.ssrcs)==null||i.forEach(n=>{var c;let a=(c=e.find(o=>o.mid===String(t.mid)))==null?void 0:c.ssrc;a&&(n.id=a)}))})}restorePublishMsid(r){const e=new Je({sdp:this.prevOfferSdp||""}).getPublishMsids();e!=null&&e.length&&r.detail.media.forEach(t=>{var i,n;if(t.direction!=="recvonly"){const a=(i=e.find(o=>o.mid===String(t.mid)))==null?void 0:i.msid;if(!a)return;const c=this.parseMsidString(a);t.msid=a||t.msid,(n=t.ssrcs)==null||n.forEach(o=>{switch(o.attribute){case"cname":o.value=c.track||o.value;break;case"msid":o.value=a||o.value}})}})}alignOfferExtValueWithAnswer(r,e){r.detail.media.forEach(t=>{var i;(i=t.ext)==null||i.forEach(n=>{this.extMap[n.uri]=n.value})}),e.detail.media.forEach(t=>{var i;t.ext=(i=t.ext)==null?void 0:i.filter(n=>!!this.extMap[n.uri]&&(n.value=this.extMap[n.uri],!0))})}alignAnswerMidsWithOffer(r){const e=new Je({sdp:this.prevOfferSdp||""}).detail.media.map(a=>String(a.mid)),t=r.detail.media.map(a=>String(a.mid)),i=this.findDiff(t,e);r.removeMedia(i);const n=[];e.forEach(a=>{const c=r.detail.media.find(o=>String(o.mid)===a);c&&n.push(c)}),r.detail.media=n.filter(a=>a)}simulateOfferAnswer(r){return _(this,null,function*(){var t,i,n;try{const a=yield(t=this.pc)==null?void 0:t.createOffer(),c=new Je({sdp:(a==null?void 0:a.sdp)||""}),o=c.detail.media.filter(h=>h.direction==="inactive").map(h=>String(h.mid));this.restorePublishedSsrc(c),this.restorePublishMsid(c),this.prevOfferSdp=c.generate();const l=new Je({sdp:this.prevAnswerSdp||""});if(l.setMediaInactive(o),r){const h=cu(r);if(h){const u=[...new Je({sdp:h}).detail.media];l.addOrUpdateMedia(u),this.alignAnswerMidsWithOffer(l)}}const d=l.generate();this.setPrevAnswerSdp(d)}catch(a){throw new lt(Ye.DATACHANNEL_CREATE_OFFER_ERROR,`CreateOffer error: ${a}`,"",{pc:this.pc})}let e=this.avoidMsidConflict(this.prevOfferSdp);if(this.offerSdpHook)try{e=this.offerSdpHook(e)}catch(a){console.log("offerSdoHook error: ",a)}try{yield(i=this.pc)==null?void 0:i.setLocalDescription(new RTCSessionDescription({type:"offer",sdp:e}))}catch(a){throw new lt(Ye.DATACHANNEL_SET_OFFER_ERROR,`SetLocalDescription error: ${a}`,"",{sdp:this.prevOfferSdp})}try{if(this.prevAnswerSdp){let a=this.avoidMsidConflict(this.prevAnswerSdp);if(this.answerSdpHook)try{a=this.answerSdpHook(a)}catch(c){console.log("answerSdpHook error: ",c)}yield(n=this.pc)==null?void 0:n.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:a}))}}catch(a){throw new lt(Ye.DATACHANNEL_SET_ANSWER_ERROR,`SetRemoteDescription error: ${a}`,"",{sdp:this.prevAnswerSdp})}})}avoidMsidConflict(r){const e=new Je({sdp:r});return e.mungleMsid(),e.generate()}setCodecPreferences(r,e){if(e)try{r.setCodecPreferences(e)}catch(t){console.warn("setCodecPreferences error",t)}}log(...r){window.RTS_DATACHANNEL_DEBUG&&console.log("[PC-Core]",...r)}hebtLog(...r){var e,t;window.RTS_HEBT_DEBUG&&console.log(`${this.now()} [datachannel|${(e=this.signal)==null?void 0:e.getDatachannelCore().label}|${(t=this.signal)==null?void 0:t.getDatachannelCore().id}]`,...r)}now(){const r=new Date;return`${r.getHours()}:${r.getMinutes()}:${r.getSeconds()}.${String(r.getMilliseconds()).padStart(3,"0")}`}}const vc="a=fingerprint";class Rc{constructor(){this.stramId="",this.audioTrackId="",this.videoTrackId="",this.screenTrackId="",this.customTrackId=""}}class Ji{constructor(r){this.sdpLines=new Array,this.localStream=r,this.publishStreamInfo=new Rc}get sdp(){return this.sdpLines.join(`\r
173
+ `)}get videoTrackId(){return this.publishStreamInfo.videoTrackId}get screenTrackId(){return this.publishStreamInfo.videoTrackId}get videoName(){return"rts video"}get screenName(){return"rts screen"}get hasTcpCandidate(){return this.sdpLines.some(r=>r.indexOf("tcptype")!==-1)}init(r){this.sdpLines=r.split(`\r
174
+ `)}addNack(){for(let r=0;r<this.sdpLines.length;++r)if(this.sdpLines[r].indexOf("opus")!=-1&&this.sdpLines[r+1].indexOf("rtcp-fb")!=-1){let e=this.sdpLines[r+1].split(" ");e.length==2&&(this.sdpLines[r+2].indexOf("rtcp-fb")!=-1?this.sdpLines.splice(r+3,0,e[0]+" nack"):this.sdpLines.splice(r+2,0,e[0]+" nack"))}}parseCustomMsid(r){let e={stream:"",track:""};if(!r)return e;let t=r.trim().split(" ");return t.length==2?(e.stream=t[0],e.track=t[1]):e.track=t[0],e}modifyTrackName(r={}){const{vMsid:e,aMsid:t}=r,i=e?this.parseCustomMsid(e):{stream:"rts",track:"video"},n=t?this.parseCustomMsid(t):{stream:"rts",track:"audio"};let a="";if(this.localStream){this.publishStreamInfo.stramId=this.localStream.mediaStream.id,this.localStream.audioTrack&&(this.publishStreamInfo.audioTrackId=this.localStream.audioTrack.id,a=n.stream||"-"),this.localStream.videoTrack&&(this.publishStreamInfo.videoTrackId=this.localStream.videoTrack.id,a=i.stream||"-");let o=!1,l=!1;for(var c=0;c<this.sdpLines.length;++c){let d=this.sdpLines[c],h=d.indexOf(this.publishStreamInfo.stramId);this.publishStreamInfo.stramId&&h!=-1&&(this.sdpLines[c]=this.sdpLines[c].replace(this.publishStreamInfo.stramId,a),G.BrowserUtil.isFirefox&&(o?this.sdpLines[c]=this.sdpLines[c].substring(0,h+a.length+1)+n.track:l&&(this.sdpLines[c]=this.sdpLines[c].substring(0,h+a.length+1)+i.track))),this.publishStreamInfo.audioTrackId&&d.indexOf(this.publishStreamInfo.audioTrackId)!=-1?this.sdpLines[c]=this.sdpLines[c].replace(this.publishStreamInfo.audioTrackId,n.track):this.publishStreamInfo.videoTrackId&&d.indexOf(this.publishStreamInfo.videoTrackId)!=-1&&(this.sdpLines[c]=this.sdpLines[c].replace(this.publishStreamInfo.videoTrackId,i.track)),d.indexOf("m=audio")!=-1?(o=!0,l=!1):d.indexOf("m=video")!=-1&&(l=!0,o=!1),d.indexOf("a=ssrc")!=-1&&(h=d.indexOf("cname:"),h!==-1&&(o?this.sdpLines[c]=d.substr(0,h+6)+n.track:l&&(this.sdpLines[c]=d.substr(0,h+6)+i.track)))}}}getPublishVideoSdp(){let r=-1,e=-1,t=!1;for(let i=0;i<this.sdpLines.length;++i){if(t&&this.sdpLines[i].indexOf("m=application")>-1){e=i-1;break}if(this.sdpLines[i].indexOf("m=video")>-1){if(t){e=i-1;break}r=i}this.sdpLines[i].indexOf("rts video")>-1&&(t=!0)}return t?(e===-1&&(e=this.sdpLines.length-1),this.sdpLines.splice(r,e-r).join(`\r
175
+ `)):""}removeVideoTrack(r){let e="rts "+r,t=-1,i=-1,n=!1;for(let a=0;a<this.sdpLines.length;++a){if(n&&this.sdpLines[a].indexOf("m=application")>-1){i=a-1;break}if(this.sdpLines[a].indexOf("m=video")>-1){if(n){i=a-1;break}t=a}this.sdpLines[a].indexOf(e)>-1&&(n=!0)}return!!n&&(i===-1&&(i=this.sdpLines.length-1),this.sdpLines.splice(t,i-t),!0)}ios15PushHack(){let r=!1,e=-1;if(this.sdpLines.forEach((t,i)=>{t.includes("m=video")&&(r=!0),r&&e===-1&&t.includes("a=")&&(e=i)}),e!==-1){const t=this.getExtmapIds(),i=Math.max(...t)+1;this.sdpLines.splice(e,0,`a=extmap:${i} urn:3gpp:video-orientation`)}}addSps(){this.sdpLines=this.sdpLines.map(r=>r.includes("a=fmtp:")&&r.includes("level-asymmetry-allowed")?r+=";sps-pps-idr-in-keyframe=1":r)}removeTwccRtcpFb(){this.sdpLines=this.sdpLines.filter(r=>!r.includes("http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"))}removeUdpCandidate(){this.sdpLines=this.sdpLines.filter(r=>!r.includes("a=candidate:")||!r.includes("UDP"))}setDirection(r={direction:"recvonly"}){const e=["sendonly","recvonly","sendrecv"].filter(n=>n!==r.direction);let t=!1,i=!1;this.sdpLines=this.sdpLines.map((n,a)=>{if(n.includes("m=video"))t=!0,i=!1;else if(n.includes("m=audio"))i=!0,t=!1;else if(n.includes("m=application"))t=!1,i=!1;else if(t||i){let c;if(e.some(o=>{if(n.includes(o))return c=o,!0})&&c)return n.replace(c,r.direction)}return n})}removeSDES(){const r=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"];this.sdpLines=this.sdpLines.filter(e=>!r.some(t=>e.includes(t)))}getFingerprint(r){const e=r.split(`\r
176
+ `);for(let t=0;t<e.length;++t)if(e[t].indexOf(vc)!==-1)return e[t].split(`${vc}:`)[1]}addStereo(){this.getPayloadType("opus").map(this.getFmtpIndex.bind(this)).filter(r=>r!==void 0).forEach(r=>{this.sdpLines[r].indexOf("stereo=1")>-1||(this.sdpLines[r]=this.sdpLines[r]+";stereo=1")})}setSingleNaluPackMode__legacy(){this.sdpLines=this.sdpLines.filter(r=>!r.includes("a=fmtp:")||!r.includes("packetization-mode=1"))}setSingleNaluPackMode(){let r=[],e=[],t=!1;if(this.sdpLines.forEach(a=>{if(a.includes("packetization-mode=0")&&(t=!0),a.includes("packetization-mode=1")){const c=this.parseFmtpValue(a);r.push(c||"NULL")}if(r.length&&new RegExp(`apt=(${r.join("|")})`).test(a)){const c=this.parseFmtpValue(a);e.push(c||"NULL")}}),!t)return!1;let i=[...r,...e].join("|"),n=new RegExp(`(rtpmap|rtcp-fb|fmtp):.*?(${i})`);this.sdpLines=this.sdpLines.filter(a=>!n.test(a));for(let a=0;a<this.sdpLines.length;a++){let c=this.sdpLines[a];if(c.includes("m=video")){let o=new RegExp(`( ${[...r,...e].join("| ")})`,"g");this.sdpLines[a]=c.replace(o,"");break}}return!0}dispose(){this.localStream&&(this.localStream=void 0),this.sdpLines=new Array,this.publishStreamInfo=new Rc}getExtmapIds(){return this.sdpLines.reduce((r,e)=>{if(e.includes("a=extmap")){const t=Number(e.replace("a=extmap:","").split(" ")[0]);return[...r,t]}return r},[]).filter(r=>r)}getPayloadType(r){let e=[];const t=new RegExp(`a\\=rtpmap\\:(\\d+) ${r}.*`,"i");for(let i=0;i<this.sdpLines.length;i++){const n=this.sdpLines[i];let a=t.exec(n);a!=null&&a.length&&e.push(a[1])}return e}getFmtpIndex(r){const e=new RegExp(`a\\=fmtp\\:${r} .*`,"i");for(let t=0;t<this.sdpLines.length;t++){const i=this.sdpLines[t];if(e.test(i))return t}}parseFmtpValue(r){const e=r.match(/a=fmtp:(\d+)/);return e?e[1]:null}}const bi=new class{constructor(){this.context={},this.subscribers=new Set}setContext(s){this.context=D(D({},this.context),s),this.notifySubscribers()}getContext(){return this.context}subscribe(s){return this.subscribers.add(s),()=>this.subscribers.delete(s)}notifySubscribers(){this.subscribers.forEach(s=>s(this.context))}};class we{}we.CandidatePair="candidate-pair",we.Certificate="certificate",we.Codec="codec",we.Csrc="csrc",we.DataCahnnel="data-channel",we.InboundRtp="inbound-rtp",we.LocalCandidate="local-candidate",we.OutboundRtp="outbound-rtp",we.PeerConnection="peer-connection",we.Receiver="receiver",we.RemoteCandidate="remote-candidate",we.RemoteInboundRtp="remote-inbound-rtp",we.RemoteOutboundRtp="remote-outbound-rtp",we.Sender="sender",we.Stream="stream",we.Track="track",we.Transport="transport",we.MediaSource="media-source";var Gs=(s=>(s.AUDIO="audio",s.VIDEO="video",s))(Gs||{});class Ec extends Lt{constructor(r){super(),this.streamEnded=!1,this.currentTimeGap=0,this.lastTimeStamp=0,this.transportStats={},this.remoteCandidate={},this.localCandidate={},this.inboundRtpStreamStats={},this.inboundRtpStreamStatsDiff={},this.receiver=null,this.pc=null,this.canplay=!1,this.type=r}set rtpReceiver(r){this.receiver=r}set RTCPeerconnection(r){this.pc=r}get isExist(){return this.receiver!=null}get isPlaying(){return this.canplay}get isStreamEnded(){return this.streamEnded}get monitorData(){const r=this.inboundRtpStreamStatsDiff||{};this.inboundRtpStreamStats;const e=this.currentTimeGap;let t=0;return r.nackCount!==void 0&&r.packetsReceived!==void 0&&(t=Math.round(r.nackCount/(r.packetsReceived+r.nackCount)*1e3)/1e3),{inboundRtpStats:this.inboundRtpStreamStats,inboundRtpStatsPerSec:{bytesReceivedPerSecond:r.bytesReceived/e||0,framesDecodedPerSecond:r.framesDecoded/e||0,packetsLostRate:t>0?t:0,decodeTimeAvg:r.totalDecodeTime&&r.framesDecoded?1e3*(r.totalDecodeTime/r.framesDecoded||0):0,jitterBufferDelayAvg:r.jitterBufferDelay&&r.jitterBufferEmittedCount?gi(r.jitterBufferDelay,r.jitterBufferEmittedCount):0,totalProcessingDelayAvg:r.totalProcessingDelay&&r.framesDecoded?r.totalProcessingDelay/r.framesDecoded*1e3:0,totalAssemblyTimeAvg:r.totalAssemblyTime&&r.framesAssembledFromMultiplePackets?r.totalAssemblyTime/r.framesAssembledFromMultiplePackets*1e3:0},transportStats:this.transportStats,remoteCandidate:this.remoteCandidate,localCandidate:this.localCandidate}}getInfo(){if(this.receiver&&this.receiver.transport&&this.receiver.transport.state==="closed"&&this.canplay&&(this.streamEnded=!0,this.emit("streamEnded"),this.canplay=!1),this.receiver&&"getStats"in this.receiver||this.pc&&"getStats"in this.pc)return new Promise((r,e)=>{let t=null,i=!1;this.receiver&&"getStats"in this.receiver?t=this.receiver.getStats():this.pc&&"getStats"in this.pc&&(t=this.pc.getStats(),i=!0),t==null||t.then(n=>{n.forEach(a=>{var c,o;if(a)switch(a.type){case we.CandidatePair:this.onCandidatePair(a);break;case we.InboundRtp:G.SystemUtil.isIos&&i?(c=a.id)!=null&&c.toLowerCase().includes(this.type)&&this.onInBoundRtp(a):G.BrowserUtil.isFirefox?a.kind===this.type&&this.onInBoundRtp(a):this.onInBoundRtp(a);break;case we.RemoteCandidate:this.onRemoteCandidate(a);break;case we.LocalCandidate:this.onLocalCandidate(a);break;case we.Track:if(this.type!=="video")break;G.SystemUtil.isIos&&i?((o=a.id)!=null&&o.toLowerCase().includes(this.type)||a.trackIdentifier.toLowerCase()===this.type)&&this.onTrack(a):this.onTrack(a)}}),r("")}).catch(n=>{e(n)})})}dispose(){this.reset()}onCandidatePair(r){(r.state==="succeeded"||r.bytesReceived)&&(this.transportStats={timestamp:Math.floor(r.timestamp),rtt:r.currentRoundTripTime||-1,bytesReceived:r.bytesReceived,bytesSent:r.bytesSent})}onInBoundRtp(r){this.currentTimeGap=(r.timestamp-this.lastTimeStamp)/1e3,this.lastTimeStamp=r.timestamp,this.inboundRtpStreamStatsDiff=this.calcDiff(r,this.inboundRtpStreamStats,["bytesReceived","framesDecoded","packetsReceived","nackCount","totalDecodeTime","jitterBufferDelay","jitterBufferEmittedCount","totalProcessingDelay","totalAssemblyTime","framesAssembledFromMultiplePackets"]),this.inboundRtpStreamStats=r,!this.canplay&&Number(r.bytesReceived)>0&&(this.canplay=!0,this.emit("canPlay"))}calcDiff(r,e,t){let i={};return t.forEach(n=>{i[n]=Number(r[n]||0)-Number(e[n]||0)}),i}onRemoteCandidate(r){this.remoteCandidate=r||{}}onLocalCandidate(r){this.localCandidate=r||{}}onTrack(r){r.frameWidth&&(this.inboundRtpStreamStats.frameWidth=r.frameWidth,this.inboundRtpStreamStats.frameHeight=r.frameHeight)}reset(){this.currentTimeGap=0,this.lastTimeStamp=0,this.transportStats={},this.remoteCandidate={},this.localCandidate={},this.inboundRtpStreamStats={},this.inboundRtpStreamStatsDiff={},this.receiver=null,this.canplay=!1,this.streamEnded=!1}}class yc extends Ec{constructor(){super(Gs.AUDIO)}}class Tc extends Ec{constructor(){super(Gs.VIDEO)}}class Tu{constructor(){this.trackPairDataList=[]}reset(){this.trackPairDataList=[]}addTrackPair(r,e,t,i,n,a){let c=new yc,o=new Tc;i&&(o.rtpReceiver=i),n&&(c.rtpReceiver=n),a&&(o.RTCPeerconnection=a,c.RTCPeerconnection=a),this.trackPairDataList.push({url:r,vMsid:e,aMsid:t,audioReceiverMonitorData:c,videoReceiverMonitorData:o})}}class Cu extends Lt{constructor(){super(),this.canplay=!1,this.pc=null,this.pcCore=null,this.monitorTimerId=null,this.audioReceiverMonitorData=new yc,this.videoReceiverMonitorData=new Tc,this.receiverMonitorController=new Tu}start(r,e){this.pc=r,this.pcCore=e,this.updateTranceiversController(),this.startMonitorTimer(200)}updateTranceiversController(){if(!this.pc||!this.pcCore)return;const r=this.pcCore.getStreamManager().getAllTrackPairList("sub");this.receiverMonitorController.reset(),r.forEach(e=>{e.url&&this.receiverMonitorController.addTrackPair(e.url,e.vMsid,e.aMsid,e.vTransceiver,e.aTransceiver,this.pc)}),this.receiverMonitorController.trackPairDataList.forEach(e=>{this.initEvent(e)})}resetTimer(r){this.updateTranceiversController(),this.stopMonitorTimer(),this.startMonitorTimer(r)}stop(){this.canplay=!1,this.stopMonitorTimer(),this.audioReceiverMonitorData.dispose(),this.videoReceiverMonitorData.dispose()}startMonitorTimer(r){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>{this.onMonitorTimer()},r))}stopMonitorTimer(){this.monitorTimerId&&clearInterval(this.monitorTimerId),this.monitorTimerId=null}onMonitorTimer(){return _(this,null,function*(){yield this.updateMonitorData();let r=[];this.receiverMonitorController.trackPairDataList.forEach(e=>{var t,i;if(e.url){let n={url:e.url};e.audioReceiverMonitorData.isExist&&(n.audio=(t=e.audioReceiverMonitorData)==null?void 0:t.monitorData,n.aMsid=e.aMsid),e.videoReceiverMonitorData.isExist&&(n.video=(i=e.videoReceiverMonitorData)==null?void 0:i.monitorData,n.vMsid=e.vMsid),r.push(n)}}),this.emit("onMonitorEvent",{eventList:r,type:"sub"})})}initEvent(r){let e={url:r.url||"url unknown",vMsid:r.vMsid||"vMsid unknown",aMsid:r.aMsid||"aMsid unknown"};r.audioReceiverMonitorData.isExist&&(r.audioReceiverMonitorData.on("streamEnded",()=>{r.videoReceiverMonitorData&&!r.videoReceiverMonitorData.isStreamEnded||(this.emit("streamEnded",e),this.stopMonitorTimer())}),r.audioReceiverMonitorData.on("canPlay",()=>{this.emitCanPlay()})),r.videoReceiverMonitorData.isExist&&(r.videoReceiverMonitorData.on("streamEnded",()=>{r.audioReceiverMonitorData&&!r.audioReceiverMonitorData.isStreamEnded||(this.emit("streamEnded",e),this.stopMonitorTimer())}),r.videoReceiverMonitorData.on("canPlay",()=>{this.emitCanPlay()}))}updateMonitorData(){return Promise.all(this.receiverMonitorController.trackPairDataList.reduce((r,e)=>{var t,i;return[...r,(t=e.audioReceiverMonitorData)==null?void 0:t.getInfo(),(i=e.videoReceiverMonitorData)==null?void 0:i.getInfo()]},[]))}emitCanPlay(){this.canplay||(this.canplay=!0,this.emit("canPlay"))}copyMonitorData(){var r,e;(e=(r=this.receiverMonitorController)==null?void 0:r.trackPairDataList)!=null&&e.length&&(this.audioReceiverMonitorData=this.receiverMonitorController.trackPairDataList[0].audioReceiverMonitorData,this.videoReceiverMonitorData=this.receiverMonitorController.trackPairDataList[0].videoReceiverMonitorData)}getTransportStats(){return _(this,null,function*(){yield this.updateMonitorData(),this.copyMonitorData();let r={};return this.videoReceiverMonitorData.isExist?r=this.videoReceiverMonitorData.monitorData.transportStats:this.audioReceiverMonitorData.isExist&&(r=this.audioReceiverMonitorData.monitorData.transportStats),r})}getRemoteVideoStats(){return _(this,null,function*(){yield this.updateMonitorData(),this.copyMonitorData();let r={};if(this.videoReceiverMonitorData.isExist){const{inboundRtpStats:e}=this.videoReceiverMonitorData.monitorData;r={timestamp:Math.floor(e.timestamp||0),framesDecodedPerSecond:e.framesPerSecond,framesDecoded:e.framesDecoded,frameWidth:e.frameWidth,frameHeight:e.frameHeight,bytesReceived:e.bytesReceived,jitter:e.jitter,jitterBufferDelayAvg:Number(e.jitterBufferDelay)/Number(e.jitterBufferEmittedCount),packetsLost:e.packetsLost,packetsReceived:e.packetsReceived}}return r})}getRemoteAudioStats(){return _(this,null,function*(){yield this.updateMonitorData(),this.copyMonitorData();let r={};if(this.audioReceiverMonitorData.isExist){const{inboundRtpStats:e}=this.audioReceiverMonitorData.monitorData;r={timestamp:Math.floor(e.timestamp||0),bytesReceived:e.bytesReceived,jitter:e.jitter,jitterBufferDelayAvg:Number(e.jitterBufferDelay)/Number(e.jitterBufferEmittedCount),packetsLost:e.packetsLost,packetsReceived:e.packetsReceived}}return r})}}class _u{constructor(){this._audiosender=null,this._videosender=null,this.timeStamp=0,this.curTimeStamp=0,this.audioBytesSent=0,this.curAudioBytesSent=0,this.videoBytesSent=0,this.curVideoBytesSent=0,this.audioRetransmittedBytesSent=0,this.curAudioRetransmittedBytesSent=0,this.videoRetransmiitedBytesSent=0,this.curVideoRetransmiitedBytesSent=0,this.framesSent=0,this.curFramesSent=0,this.framesEncoded=0,this.curFramesEncoded=0,this.totalEncodeTime=0,this.curTotalEncodeTime=0,this.totalPacketSendDelay=0,this.curTotalPacketSendDelay=0,this.packetsSent=0,this.curPacketsSent=0,this.rtt=0,this.localProtocol="",this.remoteProtocol="",this.localTransportAddr="",this.remoteTransportAddr="",this.frameHeight=0,this.frameWidth=0,this.efps=0,this.sfps=0,this.timeGap=0,this.abps=0,this.vbps=0,this.rt_abps=0,this.rt_vbps=0,this.encodeTimeAvg=0,this.packetSendDelayAvg=0,this.stashedData={}}set videoSender(r){this._videosender=r}set audioSender(r){this._audiosender=r}get monitorData(){return this.doCalc(),{tt:parseFloat(this.timeGap.toFixed(0)),rtt:this.rtt,cand_re_prot:this.remoteProtocol,cand_lo_prot:this.localProtocol,cand_re_addr:this.remoteTransportAddr,cand_lo_addr:this.localTransportAddr,w:this.frameWidth,h:this.frameHeight,efps:parseFloat(this.efps.toFixed(0)),fps:parseFloat(this.sfps.toFixed(0)),abps:parseFloat(this.abps.toFixed(0)),vbps:parseFloat(this.vbps.toFixed(0)),rt_abps:parseFloat(this.rt_abps.toFixed(0)),rt_vbps:parseFloat(this.rt_vbps.toFixed(0)),v_encode_time_avg:parseFloat(this.encodeTimeAvg.toFixed(2)),v_packet_send_delay_avg:parseFloat(this.packetSendDelayAvg.toFixed(2))}}doCalc(){this.timeStamp!==0&&(this.timeGap=this.curTimeStamp-this.timeStamp,this.timeGap>0&&(this.efps=1e3*(this.curFramesEncoded-this.framesEncoded)/this.timeGap,this.sfps=1e3*(this.curFramesSent-this.framesSent)/this.timeGap,this.abps=1e3*(this.curAudioBytesSent-this.audioBytesSent)/this.timeGap,this.vbps=1e3*(this.curVideoBytesSent-this.videoBytesSent)/this.timeGap,this.rt_abps=1e3*(this.curAudioRetransmittedBytesSent-this.audioRetransmittedBytesSent)/this.timeGap,this.rt_vbps=1e3*(this.curVideoRetransmiitedBytesSent-this.videoRetransmiitedBytesSent)/this.timeGap,this.encodeTimeAvg=(this.curTotalEncodeTime-this.totalEncodeTime)/(this.curFramesEncoded-this.framesEncoded)*1e3,this.packetSendDelayAvg=(this.curTotalPacketSendDelay-this.totalPacketSendDelay)/(this.curPacketsSent-this.packetsSent)*1e3)),this.timeStamp=this.curTimeStamp,this.audioBytesSent=this.curAudioBytesSent,this.videoBytesSent=this.curVideoBytesSent,this.audioRetransmittedBytesSent=this.curAudioRetransmittedBytesSent,this.videoRetransmiitedBytesSent=this.curVideoRetransmiitedBytesSent,this.framesSent=this.curFramesSent,this.framesEncoded=this.curFramesEncoded,this.totalEncodeTime=this.curTotalEncodeTime,this.packetsSent=this.curPacketsSent,this.totalPacketSendDelay=this.curTotalPacketSendDelay}getInfo(){let r=new Promise((t,i)=>{this._videosender&&this._videosender.getStats?this._videosender.getStats().then(n=>{n.forEach(a=>{if(a)switch(a.type){case we.CandidatePair:this.onCandidatePair(a);break;case we.OutboundRtp:this.onOutBoundRtp(a,"video");break;case we.RemoteCandidate:this.onRemoteCandidate(a);break;case we.LocalCandidate:this.onLocalCandidate(a)}}),t()}).catch(n=>{i(n)}):i("no video sender")}),e=new Promise((t,i)=>{this._audiosender&&this._audiosender.getStats?this._audiosender.getStats().then(n=>{n.forEach(a=>{if(a)switch(a.type){case we.CandidatePair:this.onCandidatePair(a);break;case we.OutboundRtp:this.onOutBoundRtp(a,"audio");break;case we.RemoteCandidate:this.onRemoteCandidate(a);break;case we.LocalCandidate:this.onLocalCandidate(a)}}),t()}).catch(n=>{i(n)}):i("no audio sender")});return Promise.all([r,e])}onCandidatePair(r){this.curTimeStamp=r.timestamp,this.rtt=r.currentRoundTripTime}onOutBoundRtp(r,e){this.curTimeStamp=r.timestamp,e==="video"?(this.curVideoBytesSent=r.bytesSent,this.curVideoRetransmiitedBytesSent=r.retransmittedBytesSent,this.curFramesEncoded=r.framesEncoded,this.curFramesSent=r.framesSent,this.frameWidth=r.frameWidth,this.frameHeight=r.frameHeight,this.curTotalEncodeTime=r.totalEncodeTime,this.curTotalPacketSendDelay=r.totalPacketSendDelay,this.curPacketsSent=r.packetsSent):e==="audio"&&(this.curAudioBytesSent=r.bytesSent,this.curAudioRetransmittedBytesSent=r.retransmittedBytesSent)}onRemoteCandidate(r){this.curTimeStamp=r.timestamp,this.remoteProtocol=r.protocol,this.remoteTransportAddr=(r.ip||r.address)+(r.port?":"+r.port.toFixed(0):"")}onLocalCandidate(r){this.curTimeStamp=r.timestamp,this.localProtocol=r.protocol,this.localTransportAddr=(r.ip||r.address)+(r.port?":"+r.port.toFixed(0):"")}}class wu extends Lt{constructor(){super(),this.heartbeatHandle=null,this.pc=null,this.pcCore=null,this.senderMonitorDataList=[]}startHeartbeat(r,e,t){this.pc=r,this.pcCore=e,this.updateSenders(),this.stopHeartbeat(),this.heartbeatHandle=setInterval(()=>{this.emitHeartBeat()},t||1e3)}stopHeartbeat(){this.heartbeatHandle!==null&&clearInterval(this.heartbeatHandle),this.heartbeatHandle=null}addTrackPair(r,e,t,i,n){if(!r)return;let a=new _u;if(e){a.videoSender=e;const c=e.transport;c&&(c.onstatechange=()=>{var o,l,d,h;this.emit("onTransportStateEvent",{url:r,type:"pub",kind:"video",state:c.state,protocol:(h=(d=(l=(o=c.iceTransport)==null?void 0:o.getSelectedCandidatePair)==null?void 0:l.call(o))==null?void 0:d.local)==null?void 0:h.protocol})})}if(t){a.audioSender=t;const c=t.transport;c&&(c.onstatechange=()=>{var o,l,d,h;this.emit("onTransportStateEvent",{url:r,type:"pub",kind:"audio",state:c.state,protocol:(h=(d=(l=(o=c.iceTransport)==null?void 0:o.getSelectedCandidatePair)==null?void 0:l.call(o))==null?void 0:d.local)==null?void 0:h.protocol})})}this.senderMonitorDataList.push({url:r,vMsid:i,aMsid:n,senderData:a})}updateSenders(){var e;const r=(e=this.pcCore)==null?void 0:e.getStreamManager().getAllTrackPairList("pub");this.senderMonitorDataList=[],r==null||r.forEach(t=>{this.addTrackPair(t.url,t.vTransceiver,t.aTransceiver,t.vMsid,t.aMsid)})}emitHeartBeat(){Promise.all(this.senderMonitorDataList.reduce((r,e)=>[...r,e.senderData.getInfo()],[])).then(()=>{}).catch(r=>{}).finally(()=>{let r=this.senderMonitorDataList.map(e=>Q(D({},e.senderData.monitorData),{url:e.url,vMsid:e.vMsid,aMsid:e.aMsid}));this.emit("onMonitorEvent",{eventList:r,type:"pub"})})}}class Au{constructor(r){this.pc=r,this.messageId=1,this.dataChannel=this.pc.createDataChannel("GRTNDataChannel"),this.dataChannel.onopen=e=>{},this.dataChannel.onmessage=e=>{e.data},this.dataChannel.onclose=e=>{},this.dataChannel.onerror=e=>{}}addTrack(r,e){return new Promise((t,i)=>{})}removeTrack(r,e){return new Promise((t,i)=>{})}createPublishPacket(){let r={type:"pub",version:1,msg_id:this.messageId,streams:[]};return++this.messageId,r}}const Cc="dmFyIHJ0PU9iamVjdC5kZWZpbmVQcm9wZXJ0eTt2YXIgWD1PYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzO3ZhciBhdD1PYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LGl0PU9iamVjdC5wcm90b3R5cGUucHJvcGVydHlJc0VudW1lcmFibGU7dmFyIEY9KHksZCxDKT0+ZCBpbiB5P3J0KHksZCx7ZW51bWVyYWJsZTohMCxjb25maWd1cmFibGU6ITAsd3JpdGFibGU6ITAsdmFsdWU6Q30pOnlbZF09QyxWPSh5LGQpPT57Zm9yKHZhciBDIGluIGR8fChkPXt9KSlhdC5jYWxsKGQsQykmJkYoeSxDLGRbQ10pO2lmKFgpZm9yKHZhciBDIG9mIFgoZCkpaXQuY2FsbChkLEMpJiZGKHksQyxkW0NdKTtyZXR1cm4geX07KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2xldCB5PXt2ZXJzaW9uOiI3LjMuMC1iZXRhLjIiLHByb3RvY29sX3ZlcnNpb246MixzZGtfdmVyc2lvbjoiMC4wLjEifTtjb25zdCBkPVszMiwzNiwxNiw5LDE2LDIzLDcsMSwxNTAsMTE3LDI1LDIxMiwyNSwxMjksMyw3XTt2YXIgQz0odD0+KHQuVlRvdGFsQ29zdD0iVlRvdGFsQ29zdCIsdC5WQXNzZW1ibHlDb3N0PSJWQXNzZW1ibHlDb3N0Iix0LlZKaXR0ZXJCdWZmZXJEZWxheT0iVkppdHRlckJ1ZmZlckRlbGF5Iix0LlZEZWNQbHVnQ29zdD0iVkRlY1BsdWdDb3N0Iix0LkRvd25SVFRIYWxmPSJEb3duUlRUSGFsZiIsdCkpKEN8fHt9KTtjb25zdCBqPXtzb3Bob25fYXVkaW9fZHVhbDo0LHNvcGhvbl92aWRlb19jYW1lcmE6NSxzb3Bob25fdmlkZW9fY2FtZXJhX3NtYWxsOjYsc29waG9uX3ZpZGVvX2NhbWVyYV9zdXBlcjo3LHNvcGhvbl92aWRlb19zY3JlZW5fc2hhcmU6OCxzb3Bob25fYXVkaW86OSxzb3Bob25fdmlkZW9fY2FtZXJhX2xhcmdlOjEwLCJydHMgYXVkaW8iOjExLCJydHMgdmlkZW8iOjEyfTt2YXIgdSxvLFQsZixELGgsZyxMPSgodT1MfHx7fSlbdS5WVG90YWxDb3N0PTRdPSJWVG90YWxDb3N0Iix1W3UuQ2FwRGV2aWNlQ29zdD01XT0iQ2FwRGV2aWNlQ29zdCIsdVt1LlB1c2hFeHRDb3N0PTZdPSJQdXNoRXh0Q29zdCIsdVt1LkNhcFBsdWdDb3N0PTddPSJDYXBQbHVnQ29zdCIsdVt1LlByZXBUaHJDb3N0PThdPSJQcmVwVGhyQ29zdCIsdVt1LlByZXBQbHVnQ29zdD05XT0iUHJlcFBsdWdDb3N0Iix1W3UuRGlzcFRockNvc3Q9MTBdPSJEaXNwVGhyQ29zdCIsdVt1LkRpc3BQbHVnQ29zdD0xMV09IkRpc3BQbHVnQ29zdCIsdVt1LlZFbmNUaHJDb3N0PTEyXT0iVkVuY1RockNvc3QiLHVbdS5WRW5jUGx1Z0Nvc3Q9MTNdPSJWRW5jUGx1Z0Nvc3QiLHUpLCQ9KChvPSR8fHt9KVtvLkFUb3RhbENvc3Q9MjRdPSJBVG90YWxDb3N0IixvW28uQVNvdXJjZUNDb3N0PTI1XT0iQVNvdXJjZUNDb3N0IixvW28uQU1peGVyQ29zdD0yNl09IkFNaXhlckNvc3QiLG9bby5BRW5jb2RlQ0Nvc3Q9MjddPSJBRW5jb2RlQ0Nvc3QiLG9bby5BQUlDbGllbnRRdWVzdGlvblRpbWVzdGFtcEhFQUQ9MjhdPSJBQUlDbGllbnRRdWVzdGlvblRpbWVzdGFtcEhFQUQiLG9bby5BQUlDbGllbnRRdWVzdGlvblRpbWVzdGFtcFRBSUw9MjldPSJBQUlDbGllbnRRdWVzdGlvblRpbWVzdGFtcFRBSUwiLG9bby5BQUlDbGllbnRBbnN3ZXJUaW1lc3RhbXBIRUFEPTMwXT0iQUFJQ2xpZW50QW5zd2VyVGltZXN0YW1wSEVBRCIsb1tvLkFBSUNsaWVudEFuc3dlclRpbWVzdGFtcFRBSUw9MzFdPSJBQUlDbGllbnRBbnN3ZXJUaW1lc3RhbXBUQUlMIixvW28uQUFJQ2xpZW50U2NlbnRlbmNlSWQ9MzJdPSJBQUlDbGllbnRTY2VudGVuY2VJZCIsb1tvLkFBSUNsaWVudFNvdXJjZUNvc3Q9MzNdPSJBQUlDbGllbnRTb3VyY2VDb3N0IixvW28uQUFJQ2xpZW50TWl4ZXJDb3N0PTM0XT0iQUFJQ2xpZW50TWl4ZXJDb3N0IixvW28uQUFJQ2xpZW50RW5jb2RlckNvc3Q9MzVdPSJBQUlDbGllbnRFbmNvZGVyQ29zdCIsb1tvLkFBSUxpbnV4UmVjZWl2ZUNvc3Q9MzZdPSJBQUlMaW51eFJlY2VpdmVDb3N0IixvW28uQUFJTGludXhOZXRlcUNvc3Q9MzddPSJBQUlMaW51eE5ldGVxQ29zdCIsb1tvLkFBSUxpbnV4UmVtb3RlU291cmNlQ29zdD0zOF09IkFBSUxpbnV4UmVtb3RlU291cmNlQ29zdCIsb1tvLkFBSUxpbnV4UGxheU1peGVyQ29zdD0zOV09IkFBSUxpbnV4UGxheU1peGVyQ29zdCIsb1tvLkFBSUxpbnV4UGxheUNvc3Q9NDBdPSJBQUlMaW51eFBsYXlDb3N0IixvW28uQUFJQ2xpZW50UXVlc3Rpb25VaWREaWdlc3RIRUFEPTQxXT0iQUFJQ2xpZW50UXVlc3Rpb25VaWREaWdlc3RIRUFEIixvW28uQUFJQ2xpZW50UXVlc3Rpb25VaWREaWdlc3RUQUlMPTQyXT0iQUFJQ2xpZW50UXVlc3Rpb25VaWREaWdlc3RUQUlMIixvW28uQUlDbGluZXRTbWFydERlbm9pc2U9NDNdPSJBSUNsaW5ldFNtYXJ0RGVub2lzZSIsbyksUj0oKFQ9Unx8e30pW1QuTmV0c2RrVGhyQ29zdD00NF09Ik5ldHNka1RockNvc3QiLFRbVC5Rb3NUaHJDb3N0PTQ1XT0iUW9zVGhyQ29zdCIsVFtULlBhY2VyQ29zdD00Nl09IlBhY2VyQ29zdCIsVFtULlVwUlRUSGFsZj00N109IlVwUlRUSGFsZiIsVFtULkFJQ2xpZW50TmV0c2RrVGhyQ29zdD00OF09IkFJQ2xpZW50TmV0c2RrVGhyQ29zdCIsVFtULkFJQ2xpZW50UW9zVGhyQ29zdD00OV09IkFJQ2xpZW50UW9zVGhyQ29zdCIsVFtULkFJQ2xpZW50UGFjZXJDb3N0PTUwXT0iQUlDbGllbnRQYWNlckNvc3QiLFRbVC5BSUNsaWVudFVwUlRUSGFsZj01MV09IkFJQ2xpZW50VXBSVFRIYWxmIixUKSxxPSgoZj1xfHx7fSlbZi5BSUFzckNvc3Q9NjRdPSJBSUFzckNvc3QiLGZbZi5BSUxsbUNvc3Q9NjVdPSJBSUxsbUNvc3QiLGZbZi5BSVR0c0Nvc3Q9NjZdPSJBSVR0c0Nvc3QiLGZbZi5BSU11dGVDb3N0PTY3XT0iQUlNdXRlQ29zdCIsZltmLkFJQWdlbnRUb3RhbENvc3Q9NjhdPSJBSUFnZW50VG90YWxDb3N0IixmW2YuQUlBZ2VudEV4dHJhQXZhdGFyQ29zdD02OV09IkFJQWdlbnRFeHRyYUF2YXRhckNvc3QiLGYpLFA9KChEPVB8fHt9KVtELlB1YlNka1R5cGU9MTAwXT0iUHViU2RrVHlwZSIsRFtELlB1YlNka1ZlcnNpb249MTAxXT0iUHViU2RrVmVyc2lvbiIsRCksSj0oKGg9Snx8e30pW2guTkdYX1JUQ19TRUlfQ1VNVUxBVElWRV9ERUxBWV9LRVlfSU5URVJOQUxfUlRUX0hBTEY9MTIxXT0iTkdYX1JUQ19TRUlfQ1VNVUxBVElWRV9ERUxBWV9LRVlfSU5URVJOQUxfUlRUX0hBTEYiLGhbaC5OR1hfUlRDX1NFSV9DVU1VTEFUSVZFX0RFTEFZX0tFWV9HUlROX05PREVfQkVGX1BBQ0VSPTEyMl09Ik5HWF9SVENfU0VJX0NVTVVMQVRJVkVfREVMQVlfS0VZX0dSVE5fTk9ERV9CRUZfUEFDRVIiLGhbaC5OR1hfUlRDX1NFSV9DVU1VTEFUSVZFX0RFTEFZX0tFWV9HUlROX05PREVfUEFDRVJfQ09TVD0xMjNdPSJOR1hfUlRDX1NFSV9DVU1VTEFUSVZFX0RFTEFZX0tFWV9HUlROX05PREVfUEFDRVJfQ09TVCIsaFtoLk5HWF9SVENfU0VJX0NVTVVMQVRJVkVfREVMQVlfS0VZX0RPV05fUlRUX0hBTEY9MTI0XT0iTkdYX1JUQ19TRUlfQ1VNVUxBVElWRV9ERUxBWV9LRVlfRE9XTl9SVFRfSEFMRiIsaCksVz0oKGc9V3x8e30pW2cuQUlHUlROSW50ZXJuYWxSVFRIYWxmPTEwNF09IkFJR1JUTkludGVybmFsUlRUSGFsZiIsZ1tnLkFJR1JUTkJlZm9yZVBhY2VyPTEwNV09IkFJR1JUTkJlZm9yZVBhY2VyIixnW2cuQUlHUlROUGFjZXJDb3N0PTEwNl09IkFJR1JUTlBhY2VyQ29zdCIsZ1tnLkFJR1JUTkRvd25SVFRIYWxmPTEwN109IkFJR1JUTkRvd25SVFRIYWxmIixnKTtjbGFzcyB6e2NvbnN0cnVjdG9yKHMpe3MubXNpZD0ic29waG9uX2F1ZGlvIjtjb25zdCBuPWpbcy5tc2lkXTtufHxjb25zb2xlLndhcm4oIk5vIG1hcHBlZCBtc2lkIGZvciBjdW11RGVsYXkiLHMubXNpZCk7bGV0IHI9bmV3IEFycmF5QnVmZmVyKHMuc2VuZFRzPzg6NCk7aWYocy5zZW5kVHMpe2xldCBpPU1hdGguZmxvb3IocGVyZm9ybWFuY2Uubm93KCkrcGVyZm9ybWFuY2UudGltZU9yaWdpbi1zLndpbmRvd1RpbWVPcmlnaW4pO2k+PU1hdGgucG93KDIsMzIpLTEmJihpPTApO2xldCBsPW5ldyBEYXRhVmlldyhyKTtsLnNldFVpbnQ4KDAsOCksbC5zZXRVaW50OCgxLDApLGwuc2V0VWludDgoMixuKSxsLnNldFVpbnQ4KDMsNSksbC5zZXRVaW50MzIoNCxpKX1lbHNlIG5ldyBVaW50OEFycmF5KHIpLnNldChbMCwwLG4sMV0pO3Mua3ZbUC5QdWJTZGtUeXBlXT0wLHMua3ZbUC5QdWJTZGtWZXJzaW9uXT1OdW1iZXIoeS52ZXJzaW9uLnNwbGl0KCIuIikuam9pbigiIikuc3BsaXQoIi0iKVswXSk7Y29uc3QgYT1PYmplY3Qua2V5cyhzLmt2KS5sZW5ndGg7YT4yNTYmJmNvbnNvbGUud2FybigiVG9vIG11Y2gga3YiKTtjb25zdCBlPTErMyphKzE7bGV0IGM9bmV3IEFycmF5QnVmZmVyKGUpLHA9bmV3IERhdGFWaWV3KGMpO3Auc2V0SW50OCgwLGEpLE9iamVjdC5rZXlzKHMua3YpLmZvckVhY2goKGksbCk9PntpIGluIFYoVihWKHt9LEwpLFIpLFApfHxjb25zb2xlLndhcm4oYFVua25vd24gQ3VtdURlbGF5IGtleTogJHtpfWApO2NvbnN0IEE9cy5rdltpXSxfPTErMypsO3Auc2V0VWludDgoXyxwYXJzZUludChpKSkscC5zZXRVaW50MTYoXysxLEEpfSkscC5zZXRVaW50OChlLTEsMTI4KSx0aGlzLmJ1ZmZlcj1mdW5jdGlvbihpLGwpe2xldCBBPW5ldyBBcnJheUJ1ZmZlcihpLmJ5dGVMZW5ndGgrbC5ieXRlTGVuZ3RoKSxfPW5ldyBVaW50OEFycmF5KEEpO3JldHVybiBfLnNldChuZXcgVWludDhBcnJheShpKSwwKSxfLnNldChuZXcgVWludDhBcnJheShsKSxpLmJ5dGVMZW5ndGgpLEF9KHIsYyl9fWNvbnN0IGs9KHQscyxuPTUscik9Pntjb25zdCBhPXQuZGF0YSxlPW5ldyBEYXRhVmlldyhhKTtsZXQgYz0wO2Zvcig7Oyl7aWYoZS5nZXRVaW50MzIoYyk9PT0xKXtlLmdldFVpbnQ4KGMrNCk7Y29uc3QgcD1uZXcgWihzLG4scikuYnVmZmVyLGk9bmV3IHR0KHApLmJ1ZmZlcixsPW5ldyBBcnJheUJ1ZmZlcihpLmJ5dGVMZW5ndGgrYS5ieXRlTGVuZ3RoKSxBPW5ldyBVaW50OEFycmF5KGwpLF89bmV3IFVpbnQ4QXJyYXkoaSk7QS5zZXQoXyk7Y29uc3QgRT1uZXcgVWludDhBcnJheShhKTtBLnNldChFLGkuYnl0ZUxlbmd0aCksdC5kYXRhPWwsYys9MTticmVha31pZihjKz0xLGMrND49ZS5ieXRlTGVuZ3RoKWJyZWFrfX07Y2xhc3MgWntjb25zdHJ1Y3RvcihzLG49NSxyKXtjb25zdCBhPU0obik/MTY6MCxlPXMuYnl0ZUxlbmd0aCthLGM9ZXQoZSkscD1jLmJ1ZmZlci5ieXRlTGVuZ3RoLGk9bmV3IEFycmF5QnVmZmVyKDErcCthK3MuYnl0ZUxlbmd0aCksbD1uZXcgVWludDhBcnJheShpKTtsZXQgQT0wO2lmKGxbQSsrXT1uLGwuc2V0KGMsQSksQSs9Yy5ieXRlTGVuZ3RoLE0obikpe3I9KHJ8fCIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiKS5yZXBsYWNlKC8tL2csIiIpO2ZvcihsZXQgUz0wO1M8MTY7UysrKWxbQStTXT1wYXJzZUludChyLnN1YnN0cigyKlMsMiksMTYpO0ErPTE2fWxldCBfPW5ldyBVaW50OEFycmF5KHMpO2wuc2V0KF8sQSk7Y29uc3QgRT1zdChsKTt0aGlzLmJ1ZmZlcj1FLmJ1ZmZlcn19Y2xhc3MgdHR7Y29uc3RydWN0b3Iocyl7Y29uc3Qgbj1uZXcgVWludDhBcnJheShbMCwwLDAsMV0pLHI9bmV3IFVpbnQ4QXJyYXkoWzZdKSxhPW5ldyBBcnJheUJ1ZmZlcihuLmJ5dGVMZW5ndGgrci5ieXRlTGVuZ3RoK3MuYnl0ZUxlbmd0aCksZT1uZXcgVWludDhBcnJheShhKTtlLnNldChuKSxlLnNldChyLG4uYnl0ZUxlbmd0aCksZS5zZXQobmV3IFVpbnQ4QXJyYXkocyksbi5ieXRlTGVuZ3RoK3IuYnl0ZUxlbmd0aCksdGhpcy5idWZmZXI9YX19Y29uc3QgZXQ9dD0+e2lmKHQ8PTApdGhyb3cgbmV3IEVycm9yKCJwYXlsb2FkU2l6ZSBtdXN0IGJlIGEgcG9zaXRpdmUgaW50ZWdlci4iKTtjb25zdCBzPU1hdGguY2VpbCh0LzI1NSksbj1uZXcgQXJyYXlCdWZmZXIocykscj1uZXcgRGF0YVZpZXcobik7Zm9yKGxldCBhPTA7YTxzLTE7YSsrKXIuc2V0VWludDgoYSwyNTUpO3JldHVybiByLnNldFVpbnQ4KHMtMSx0JTI1NSYyNTUpLG5ldyBVaW50OEFycmF5KG4pfSxzdD10PT57Y29uc3Qgcz1uZXcgVWludDhBcnJheSh0KTtsZXQgbj0iIjtmb3IobGV0IGU9MDtlPHMubGVuZ3RoO2UrKyluKz1zW2VdLnRvU3RyaW5nKDIpLnBhZFN0YXJ0KDgsIjAiKTtmb3Iobis9IjEiO24ubGVuZ3RoJTghPTA7KW4rPSIwIjtjb25zdCByPW4ubGVuZ3RoLzgsYT1uZXcgVWludDhBcnJheShyKTtmb3IobGV0IGU9MDtlPHI7ZSsrKWFbZV09cGFyc2VJbnQobi5zbGljZSg4KmUsOCplKzgpLDIpO3JldHVybiBudChhKX0sbnQ9dD0+e2NvbnN0IHM9W107bGV0IG49MDtmb3IobGV0IHI9MDtyPHQubGVuZ3RoO3IrKylzLnB1c2godFtyXSksdFtyXT09PTA/KG4rKyxuPT09MiYmcjx0Lmxlbmd0aC0xJiZ0W3IrMV08PTMmJihzLnB1c2goMyksbj0wKSk6bj0wO3JldHVybiBuZXcgVWludDhBcnJheShzKX0sTT10PT50PT09NXx8dD09PTk5O3ZhciB2PSh0PT4odC5TZW5kZXI9InNlbmRlciIsdC5SZWNlaXZlcj0icmVjZWl2ZXIiLHQpKSh2fHx7fSksVT0odD0+KHQuU2V0dXA9InNldHVwIix0Lkluc2VyU0VJPSJpbnNlcnRTRUkiLHQuVXBkYXRlUHViU3RhdHM9InVwZGF0ZVB1YlN0YXRzIix0LlVwZGF0ZVN1YlN0YXRzPSJ1cGRhdGVTdWJTdGF0cyIsdC5Td2l0Y2hDdW11RGVsYXk9InN3aXRjaEN1bXVEZWxheSIsdCkpKFV8fHt9KTtjb25zdCBOPXNlbGY7bGV0IEksbSxiLEg9ITEseD0wO2NvbnN0IG90PXQ9PntJPXQsSSYmKEkudXVpZD0oKHMsbik9Pntjb25zdCByPSIwMTIzNDU2Nzg5QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5eiIuc3BsaXQoIiIpO2xldCBhLGU9W107aWYobj1ufHxyLmxlbmd0aCxzKWZvcihhPTA7YTxzO2ErKyllW2FdPXJbMHxNYXRoLnJhbmRvbSgpKm5dO2Vsc2V7bGV0IGM7Zm9yKGVbOF09ZVsxM109ZVsxOF09ZVsyM109Ii0iLGVbMTRdPSI0IixhPTA7YTwzNjthKyspZVthXXx8KGM9MHwxNipNYXRoLnJhbmRvbSgpLGVbYV09clthPT0xOT8zJmN8ODpjXSl9cmV0dXJuIGUuam9pbigiIil9KSgpLnRvTG93ZXJDYXNlKCksSS5yZXBlYXRDb3VudD1JLnJlcGVhdENvdW50fHwwKX0sRz0odCxzLG4scik9PntpZih0PT09di5TZW5kZXIpe2NvbnN0IGE9bmV3IFRyYW5zZm9ybVN0cmVhbSh7dHJhbnNmb3JtOihlLGMpPT57bGV0IHA9ZTtpZihlLnR5cGUpe2lmKEkpdHJ5eyghSS5rZXlmcmFtZU9ubHl8fEkua2V5ZnJhbWVPbmx5JiZlLnR5cGU9PT0ia2V5IikmJihrKGUsSS5zZWksSS5wYXlsb2FkVHlwZSxJLnV1aWQpLEkucmVwZWF0Q291bnQ9PT12b2lkIDA/ST1udWxsOkkucmVwZWF0Q291bnQhPT0tMSYmKEkucmVwZWF0Q291bnQtLSxJLnJlcGVhdENvdW50PDAmJihJPW51bGwpKSl9Y2F0Y2goaSl7ZT1wLGNvbnNvbGUubG9nKCJlcnJvciBpbiBpbnNlcnRpbmcgdXNlciBTRUkiLGkpfWVsc2UgaWYoSCl0cnl7aWYoZS50eXBlPT09ImtleSImJm0pe2NvbnN0IGk9e307bS52X2VuY29kZV90aW1lX2F2ZyYmKGlbTC5WRW5jUGx1Z0Nvc3RdPU1hdGguY2VpbChtLnZfZW5jb2RlX3RpbWVfYXZnKSksbS52X3BhY2tldF9zZW5kX2RlbGF5X2F2ZyYmKGlbUi5QYWNlckNvc3RdPU1hdGguY2VpbChtLnZfcGFja2V0X3NlbmRfZGVsYXlfYXZnKSksbS5ydHQmJihpW1IuVXBSVFRIYWxmXT1NYXRoLmNlaWwobS5ydHQvMioxZTMpKSxpW0wuVlRvdGFsQ29zdF09TWF0aC5jZWlsKChpW0wuVkVuY1BsdWdDb3N0XXx8MCkrKGlbUi5QYWNlckNvc3RdfHwwKSksayhlLG5ldyB6KHttc2lkOm0udk1zaWR8fCIiLGt2Omksc2VuZFRzOiEwLHdpbmRvd1RpbWVPcmlnaW46eH0pLmJ1ZmZlciw5OSwobD0+e2lmKGwubGVuZ3RoIT09MTYpdGhyb3cgbmV3IEVycm9yKCJVVUlEIG11c3QgYmUgMTYgYnl0ZXMgbG9uZy4iKTtsZXQgQT1sLnJlZHVjZSgoXyxFKT0+XytFLnRvU3RyaW5nKDE2KS5wYWRTdGFydCgyLCIwIiksIiIpO3JldHVybmAke0Euc2xpY2UoMCw4KX0tJHtBLnNsaWNlKDgsMTIpfS0ke0Euc2xpY2UoMTIsMTYpfS0ke0Euc2xpY2UoMTYsMjApfS0ke0Euc2xpY2UoMjApfWB9KShuZXcgVWludDhBcnJheShkKSkpfX1jYXRjaChpKXtlPXAsY29uc29sZS5sb2coImVycm9yIGluIGluc2VydGluZyBjdW11RGVsYXkgU0VJIixpKX1wPW51bGwsciYmcihlKX1jLmVucXVldWUoZSl9fSk7cy5waXBlVGhyb3VnaChhKS5waXBlVG8obil9ZWxzZSBpZih0PT09di5SZWNlaXZlcil7Y29uc3QgYT1uZXcgVHJhbnNmb3JtU3RyZWFtKHt0cmFuc2Zvcm06KGUsYyk9Pnt2YXIgaSxsLEEsXyxFLFMsTyxZLFEsSztsZXQgcD1lO2lmKGUudHlwZSl7dHJ5e2lmKGIpe2xldCB3PXtbQy5Eb3duUlRUSGFsZl06TWF0aC5jZWlsKCgoKGw9KGk9Yi52aWRlbyk9PW51bGw/dm9pZCAwOmkudHJhbnNwb3J0U3RhdHMpPT1udWxsP3ZvaWQgMDpsLnJ0dCl8fDApLzIqMWUzKSxbQy5WQXNzZW1ibHlDb3N0XTpNYXRoLmNlaWwoKChfPShBPWIudmlkZW8pPT1udWxsP3ZvaWQgMDpBLmluYm91bmRSdHBTdGF0c1BlclNlYyk9PW51bGw/dm9pZCAwOl8udG90YWxBc3NlbWJseVRpbWVBdmcpfHwwKSxbQy5WSml0dGVyQnVmZmVyRGVsYXldOk1hdGguY2VpbCgoKFM9KEU9Yi52aWRlbyk9PW51bGw/dm9pZCAwOkUuaW5ib3VuZFJ0cFN0YXRzUGVyU2VjKT09bnVsbD92b2lkIDA6Uy5qaXR0ZXJCdWZmZXJEZWxheUF2Zyl8fDApLFtDLlZEZWNQbHVnQ29zdF06TWF0aC5jZWlsKCgoWT0oTz1iLnZpZGVvKT09bnVsbD92b2lkIDA6Ty5pbmJvdW5kUnRwU3RhdHNQZXJTZWMpPT1udWxsP3ZvaWQgMDpZLmRlY29kZVRpbWVBdmcpfHwwKSxbQy5WVG90YWxDb3N0XTpNYXRoLmNlaWwoKChLPShRPWIudmlkZW8pPT1udWxsP3ZvaWQgMDpRLmluYm91bmRSdHBTdGF0c1BlclNlYyk9PW51bGw/dm9pZCAwOksudG90YWxQcm9jZXNzaW5nRGVsYXlBdmcpfHwwKX07d1tDLlZUb3RhbENvc3RdfHwod1tDLlZUb3RhbENvc3RdPU1hdGguY2VpbCgod1tDLlZBc3NlbWJseUNvc3RdfHwwKSsod1tDLlZKaXR0ZXJCdWZmZXJEZWxheV18fDApKyh3W0MuVkRlY1BsdWdDb3N0XXx8MCkpKSxlLnN1YlN0YXRzPXd9fWNhdGNoKHcpe2NvbnNvbGUubG9nKCJlcnJvciBpbiBwYXJzaW5nIFNFSSIsdyksZT1wfXA9bnVsbCxyJiZyKGUpfWRlbGV0ZSBlLnN1YlN0YXRzLGMuZW5xdWV1ZShlKX19KTtzLnBpcGVUaHJvdWdoKGEpLnBpcGVUbyhuKX19LEI9dD0+e2xldCBzPXQuZGF0YS5zbGljZSgwKTtOLnBvc3RNZXNzYWdlKHt0eXBlOiJlbmNvZGVkRnJhbWUiLGRhdGE6cyxmcmFtZUluZm86e3R5cGU6dC50eXBlLHRpbWVzdGFtcDp0LnRpbWVzdGFtcH0sc3ViU3RhdHM6dC5zdWJTdGF0c30sW3NdKSxzPW51bGx9O04uUlRDVHJhbnNmb3JtRXZlbnQmJihOLm9ucnRjdHJhbnNmb3JtPXQ9Pntjb25zdHtvcHRpb25zOntzb3VyY2U6c30scmVhZGFibGU6bix3cml0YWJsZTpyfT10LnRyYW5zZm9ybWVyO0cocyxuLHIsYT0+e3M9PT12LlJlY2VpdmVyJiZCKGEpfSl9KSxvbm1lc3NhZ2U9dD0+e3N3aXRjaCh0LmRhdGEub3BlcmF0aW9uKXtjYXNlIFUuU2V0dXA6KG49Pntjb25zdHtzb3VyY2U6cixyZWFkYWJsZTphLHdyaXRhYmxlOmV9PW47RyhyLGEsZSxjPT57cj09PXYuUmVjZWl2ZXImJkIoYyl9KX0pKHQuZGF0YSk7YnJlYWs7Y2FzZSBVLkluc2VyU0VJOm90KHQuZGF0YSk7YnJlYWs7Y2FzZSBVLlVwZGF0ZVB1YlN0YXRzOnM9dC5kYXRhLG09cy5zdGF0czticmVhaztjYXNlIFUuVXBkYXRlU3ViU3RhdHM6KG49PntiPW4uc3RhdHN9KSh0LmRhdGEpO2JyZWFrO2Nhc2UgVS5Td2l0Y2hDdW11RGVsYXk6KG49PntIPW4uZW5hYmxlLHg9bi53aW5kb3dUaW1lT3JpZ2lufSkodC5kYXRhKX12YXIgc319KSgpOwo=",_c=typeof window!="undefined"&&window.Blob&&new Blob([atob(Cc)],{type:"text/javascript;charset=utf-8"});function Iu(){let s;try{if(s=_c&&(window.URL||window.webkitURL).createObjectURL(_c),!s)throw"";return new Worker(s)}catch(r){return new Worker("data:application/javascript;base64,"+Cc)}finally{s&&(window.URL||window.webkitURL).revokeObjectURL(s)}}const $i=window.RTCRtpReceiver&&"createEncodedStreams"in RTCRtpReceiver.prototype,Xi=window.RTCRtpReceiver&&"transform"in RTCRtpReceiver.prototype&&"RTCRtpScriptTransform"in window,wc=class ph extends Lt{constructor(){super(),this.connectingEventSent=!1,this.reused=!1,this.transformWorkerList=new Pu,this.receiverCodecPreferences={},this.senderCodecPreferences={},this.heartbeatTimeoutHandler=null,this.noHeartbeatCount=0,this.subMonitor=new Cu,this.subMonitor.on("onMonitorEvent",r=>{this.emit("onMonitorEvent",r)}),this.subMonitor.on("streamEnded",()=>{this.emit("streamEnded")}),this.subMonitor.on("canPlay",()=>{}),this.pubMonitor=new wu,this.pubMonitor.on("onMonitorEvent",r=>{this.emit("onMonitorEvent",r)}),this.pubMonitor.on("onTransportStateEvent",r=>{this.emit("onTransportStateEvent",r)})}get isConnected(){var r;return((r=this.pc)==null?void 0:r.connectionState)==="connected"}get isReused(){return this.reused}set isReused(r){this.reused=!!r}getWorkerManager(){return this.transformWorkerList}getPc(){return this.pc}getPeerCore(){return this.peerCore}getSubMonitor(){return this.subMonitor}getPubMonitor(){return this.pubMonitor}playStart(){this.subMonitor.resetTimer(1e3)}pushStart(){this.pc&&this.peerCore&&this.pubMonitor.startHeartbeat(this.pc,this.peerCore)}sample(){return _(this,null,function*(){yield this.subMonitor.onMonitorTimer()})}joinPubSub(r){var e;return(e=this.peerCore)==null?void 0:e.joinPubSub(r)}subAdd(r,e,t){var i;return(i=this.peerCore)==null?void 0:i.subscribeAdd(r,e,t)}subActive(r){var e;return(e=this.peerCore)==null?void 0:e.subscribeActive(r)}subStop(r){var e;return(e=this.peerCore)==null?void 0:e.subscribeStop(r)}subDeleteTracks(r){var e;return(e=this.peerCore)==null?void 0:e.subscribeDeleteTracks(r)}pubAdd(r,e,t){var i;return(i=this.peerCore)==null?void 0:i.publishAdd(r,e,t)}pubDeleteTracks(r){var e;return(e=this.peerCore)==null?void 0:e.publishDeleteTracks(r)}pubReplaceTracks(r){var e;return(e=this.peerCore)==null?void 0:e.publishReplaceTracks(r)}pubStop(r){var e;return(e=this.peerCore)==null?void 0:e.publishStop(r)}createOffer(r,e,t,i={publishUrl:""}){return new Promise((n,a)=>{var d;(d=this.cancelable)==null||d.cancel();let c={googCpuOveruseDetection:!1,sdpSemantics:"unified-plan",encodedInsertableStreams:i.encodedInsertableStreams,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"};if(G.BrowserUtil.isChrome&&Number(G.BrowserUtil.browserMainVersion)<=55&&(c.iceServers=[]),this.pc=new RTCPeerConnection(c),this.encodedInsertableStreams=i.encodedInsertableStreams,this.peerCore=new yu({pc:this.pc,onDatachannelEvent:h=>{var u,p,f;this.emit("datachannelStatusChange",{status:h}),i.disableHeartbeat||(h===yt.DATACHANNEL_STATUS_OPEN?(Gt("DATACHANNEL OPEN"," heartbeat send scheduler started"),(p=this.peerCore)==null||p.startSignalHeartbeatTimer((u=i==null?void 0:i.heartbeat)==null?void 0:u.interval)):h===yt.DATACHANNEL_STATUS_CLOSE&&(Gt("DATACHANNEL CLOSE"," heartbeats from now on will fail"),(f=this.peerCore)==null||f.stopSignalHeartbeatTimer()))},onInnerSubscribeDelete:h=>{this.emit("innerSubscribeDeleteTracks",h)},offerSdpHook:i.offerSdpHook,answerSdpHook:i.answerSdpHook,delayOpen:bi.getContext().datachannelDelayOpen,signalDatachannelInitOptions:bi.getContext().signalDatachannelInitOptions}),this.registerPeerCoreListeners(i),this.peerCore.setReceiverCodecPreferences(this.receiverCodecPreferences),this.peerCore.setSenderCodecPreferences(this.senderCodecPreferences),this.pc.onconnectionstatechange=()=>{const{connectionState:h}=this.pc||{};switch(this.connectingEventSent||(this.connectingEventSent=!0,this.emit("connectStatusChange",{status:ct.CONNECT_STATUS_CONNECTING})),h!=="connecting"&&this.clearStatusTimer(),h){case"connected":this.emit("onConnected"),this.emit("connectStatusChange",{status:ct.CONNECT_STATUS_CONNECTED});break;case"disconnected":this.emit("connectStatusChange",{status:ct.CONNECT_STATUS_RECONNECTING});break;case"failed":case"closed":this.handleClosed()}},this.clearStatusTimer(),this.statusTimer=window.setTimeout(()=>{this.handleClosed()},ph.CONNECT_TIMEOUT),t){this.localStream=t,this.sdpUtil=new Ji(this.localStream);let h=this.addStream();if(h!==0)return this.pc=void 0,void a(new ie(h,h===H.ERROR_MEDIASTREAMTRACK_AUDIO_NONE?"need audio track":"",""))}else this.sdpUtil=new Ji;let o={};if(!t){const{added:h}=this.handleSubTransceiver(r,e);o=h?{}:{offerToReceiveAudio:r,offerToReceiveVideo:e}}const l=this.pc.createOffer(o);this.cancelable=(h=>{let u=!1;return{promise:new Promise((p,f)=>{h.then(m=>u?f({isCanceled:!0}):p(m)),h.catch(m=>f(u?{isCanceled:!0}:m))}),cancel(){u=!0}}})(l),this.cancelable.promise.then(h=>{var u,p,f,m,g,S,v;if(this.cancelable=void 0,this.sdpUtil){if(this.sdpUtil.init(String(h.sdp)),this.sdpUtil.addNack(),this.sdpUtil.addSps(),i.disableStereo||this.sdpUtil.addStereo(),i.cumuDelay&&(this.sdpUtil.setSingleNaluPackMode()||this.emit("cumuDelayNotSupported")),t&&this.sdpUtil.modifyTrackName({vMsid:i.vMsid&&i.vMsid[0],aMsid:i.aMsid&&i.aMsid[0]}),this.pc){if(h.sdp=this.sdpUtil.sdp,t&&t.sdpHook&&typeof t.sdpHook=="function")try{h.sdp=t.sdpHook(h.sdp)}catch(T){console.log("Error in sdp hook",T)}(u=this.peerCore)==null||u.setPrevOfferSdp(h.sdp||"");let E=[];if(t)try{(p=this.peerCore)==null||p.patchPublishStreamManagerRecord(i.publishUrl||"",Q(D({},i),{stream:t,cumuDelay:i.cumuDelay}));const T=(f=this.peerCore)==null?void 0:f.parseSdp(h.sdp||"");E=(v=this.peerCore)==null?void 0:v.updateTrackInfoList({url:i.publishUrl||"",stream:t,vMsid:(m=this.peerCore)==null?void 0:m.unifyMsid(i.vMsid,"video"),aMsid:(g=this.peerCore)==null?void 0:g.unifyMsid(i.aMsid,"audio"),sdpMediaList:(S=T==null?void 0:T.detail)==null?void 0:S.media})}catch(T){console.log(T)}if(i.offerSdpHook&&typeof i.offerSdpHook=="function")try{h.sdp=i.offerSdpHook(h.sdp||"")}catch(T){console.log("Error in offerSdpHook",T)}this.pc.setLocalDescription(h).then(()=>{this.pc?n({desp:this.pc.localDescription,publishTrackInfoList:E}):a(new ie(H.ERROR_CREATEOFFER,"no pc",""))}).catch(T=>{a(new ie(H.ERROR_CREATEOFFER,"setLocalDescription error "+T.message,""))})}}else a(new ie(H.ERROR_CREATEOFFER,"no sdp",""))}).catch(h=>{h.isCanceled||a(new ie(H.ERROR_CREATEOFFER,h.message?h.message:"create offer error",""))})})}recvAnswer(r,e={}){var t,i;return(i=this.peerCore)==null||i.setPrevAnswerSdp((t=r==null?void 0:r.jsep)==null?void 0:t.sdp),new Promise((n,a)=>{var c,o,l,d,h,u;if(this.pc){if(this.pc.ontrack=p=>{this.pc&&this.peerCore&&this.subMonitor.start(this.pc,this.peerCore),setTimeout(()=>{this.handleEncodedInsertableStreams({receiver:p.receiver})}),this.isReused||this.emit("onTrackEvent",p)},this.pc.signalingState==="closed")return void a({message:"PeerConnection signalingState is closed"});if((c=r.jsep)!=null&&c.sdp){const p=new Ji;p.init(String((o=r.jsep)==null?void 0:o.sdp)),this.localStream&&(this.localStream.audioTrack&&!this.localStream.videoTrack&&(p.removeTwccRtcpFb(),(l=this.peerCore)==null||l.setRemoveTwcc(!0)),p.setDirection()),e.tcpOnly&&p.hasTcpCandidate&&p.removeUdpCandidate(),r.jsep.sdp=p.sdp,(h=this.peerCore)==null||h.setPrevAnswerSdp((d=r==null?void 0:r.jsep)==null?void 0:d.sdp)}if((u=r.jsep)!=null&&u.sdp&&e.answerSdpHook&&typeof e.answerSdpHook=="function")try{r.jsep.sdp=e.answerSdpHook(r.jsep.sdp)}catch(p){console.log("Error in answerSdpHook",p)}this.pc.setRemoteDescription(new RTCSessionDescription(r.jsep)).then(p=>{var f;this.pc&&this.localStream&&(this.localStream.setEncodeParam(this.pc),(f=this.pc)==null||f.getSenders().forEach(m=>{this.handleEncodedInsertableStreams({sender:m})})),n(p)}).catch(p=>{p.sdp=r.jsep.sdp,a(p)})}else a({message:"no PeerConnection"})})}setReceiverCodecPreferences(r){var e;this.receiverCodecPreferences=D({},r),(e=this.peerCore)==null||e.setReceiverCodecPreferences(this.receiverCodecPreferences)}setSenderCodecPreferences(r){var e;this.senderCodecPreferences=D({},r),(e=this.peerCore)==null||e.setSenderCodecPreferences(this.senderCodecPreferences)}removeTrack(r,e){return new Promise((t,i)=>{this.pc&&this.dataChannel&&this.dataChannel.removeTrack(r,e).then(()=>{}).catch(n=>{i(n)})})}replaceTrack(r,e,t){return new Promise((i,n)=>{t||this.pc&&this.dataChannel&&this.dataChannel.removeTrack(r,e).then(()=>{}).catch(a=>{n(a)})})}sendSEI(r){var e;if(!r.data)throw new Error("No data to send, please check your params.");if(!(r.data instanceof ArrayBuffer))throw new Error("data should be ArrayBuffer, please check your params.");if(!r.url)throw new Error("url is required, please check your params.");if(!r.vMsid)throw new Error("vMsid is required, please check your params.");if($i||Xi){const t=this.transformWorkerList.findByMsid({url:r.url,kind:Ar.VIDEO,source:Pt.Sender,msid:r.vMsid});if(!t)throw new Error("No published stream found, please check your url: "+r.url);(e=t==null?void 0:t.worker)==null||e.postMessage({operation:Zr.InserSEI,payloadType:r.payloadType,repeatCount:r.repeatCount,keyframeOnly:r.keyframeOnly,sei:r.data})}}updateStatsForSEI(r,e){const t=e==="pub";this.encodedInsertableStreams&&($i||Xi)&&r.forEach(i=>{var a;const n=this.transformWorkerList.findByMsid({url:i.url,kind:Ar.VIDEO,source:t?Pt.Sender:Pt.Receiver,msid:i.vMsid});n&&((a=n==null?void 0:n.worker)==null||a.postMessage({operation:t?Zr.UpdatePubStats:Zr.UpdateSubStats,stats:i}))})}reset(){this.cancelable&&(this.cancelable.cancel(),this.cancelable=void 0),this.peerCore&&(this.peerCore.dispose(),this.peerCore=void 0),this.pc&&(this.pc.onconnectionstatechange=()=>{},this.pc.ontrack=()=>{},this.pc.close(),this.pc=void 0,this.clearStatusTimer()),this.sdpUtil&&(this.sdpUtil.dispose(),this.sdpUtil=void 0),this.localStream&&(this.localStream=void 0),this.transformWorkerList.dispose(),this.subMonitor.stop(),this.pubMonitor.stopHeartbeat(),this.isReused=!1,this.encodedInsertableStreams=void 0,this.stopHeartbeatTimeoutChecker()}addStream(){if(this.localStream){if(this.pc){if(this.localStream.audioTrack){let r=this.pc.addTransceiver(this.localStream.audioTrack,{direction:"sendonly",streams:[this.localStream.mediaStream]});if(this.senderCodecPreferences.audio)try{r.setCodecPreferences(this.senderCodecPreferences.audio)}catch(e){console.warn("setCodecPreferences error",e)}}if(this.localStream.videoTrack){let r=this.pc.addTransceiver(this.localStream.videoTrack,{direction:"sendonly",streams:[this.localStream.mediaStream]});if(this.senderCodecPreferences.video)try{r.setCodecPreferences(this.senderCodecPreferences.video)}catch(e){console.warn("setCodecPreferences error",e)}}return 0}return H.ERROR_PREERCONNECTION_UNKNOWN}return H.ERROR_MEDIASTREAMTRACK_AUDIO_NONE}handleEncodedInsertableStreams(r){var e,t;if(this.encodedInsertableStreams){const{receiver:i,sender:n}=r,a=i?Pt.Receiver:Pt.Sender,c=i||n,o=c.track;if(!o)return console.warn("no track in senderReceiver!");const{kind:l}=o,d=(t=(e=this.peerCore)==null?void 0:e.getStreamManager())==null?void 0:t.getAllTrackPairList(a===Pt.Receiver?"sub":"pub"),h=d==null?void 0:d.find(m=>{var g,S;return((S=(g=m[l===Ar.VIDEO?"vTransceiver":"aTransceiver"])==null?void 0:g.track)==null?void 0:S.id)===o.id});if(!h)return console.warn("no existing stream info found");const u=new Iu;if(this.transformWorkerList.removeByMsid({url:h.url||"",kind:l,source:a,msid:(l===Ar.VIDEO?h.vMsid:h.aMsid)||""}),!this.transformWorkerList.add({worker:u,kind:l,source:a,info:h,receiver:i,sender:n}))return console.log("worker existing, skip.",l);const p=Zr.Setup,f=performance.timeOrigin;if($i){const m=c.createEncodedStreams(),{readable:g,writable:S}=m;u.postMessage({source:a,readable:g,writable:S,operation:p},[g,S])}else Xi&&(c.transform=new RTCRtpScriptTransform(u,{source:a,operation:p,windowTimeOrigin:f}));h.cumuDelay&&l==="video"&&(u.postMessage({operation:Zr.SwitchCumuDelay,enable:!0,windowTimeOrigin:f}),$i||Xi||this.emit("cumuDelayNotSupported")),u.onmessage=m=>{const{type:g,data:S,frameInfo:v}=m.data;g==="encodedFrame"&&this.emit("encodedFrame",{kind:l,url:h.originUrl,vMsid:l==="video"?h==null?void 0:h.vMsid:void 0,aMsid:l==="audio"?h==null?void 0:h.aMsid:void 0,frame:D({data:S},v),subStats:m.data.subStats})}}}handleSubTransceiver(r,e){var a;let t,i,n=!1;if((a=this.pc)!=null&&a.addTransceiver){if(r&&(t=this.pc.addTransceiver("audio",{direction:"recvonly"}),this.receiverCodecPreferences.audio))try{t.setCodecPreferences(this.receiverCodecPreferences.audio)}catch(c){console.warn("setCodecPreferences error",c)}if(e&&(i=this.pc.addTransceiver("video",{direction:"recvonly"}),this.receiverCodecPreferences.video))try{i.setCodecPreferences(this.receiverCodecPreferences.video)}catch(c){console.warn("setCodecPreferences error",c)}n=!0}return{added:n,aTransceiver:t,vTransceiver:i}}initDataChannel(){!this.dataChannel&&this.pc&&(this.dataChannel=new Au(this.pc))}handleClosed(){this.subMonitor.stop(),this.emit("connectStatusChange",{status:ct.CONNECT_STATUS_DISCONNECTED}),this.emit("onEnd")}clearStatusTimer(){this.statusTimer&&clearTimeout(this.statusTimer),this.statusTimer=void 0}registerPeerCoreListeners(r){var e;this.peerCore?(r.disableHeartbeat||(Gt("heartbeat [timeout checker] started"),this.startHeartbeatTimeoutChecker((e=r==null?void 0:r.heartbeat)==null?void 0:e.timeout)),this.peerCore.on("message",t=>{this.emit("message",t)}),this.peerCore.on("preSub",t=>{this.emit("preSub",t)}),this.peerCore.on("prePub",t=>{this.emit("prePub",t)}),this.peerCore.on("reconnectRoomServer",()=>{this.emit("reconnectRoomServer")}),this.peerCore.on("signalSent",t=>{this.emit("signalSent",t)}),this.peerCore.on("signalReceived",t=>{this.emit("signalReceived",t)}),this.peerCore.on("hebtSent",t=>{Gt("EVENT: HEBT SENT",t),this.emit("hebtSent",t)}),this.peerCore.on("hebtReceived",t=>{Gt("EVENT: HEBT RECV",t),this.noHeartbeatCount=0,this.emit("hebtReceived",t)}),this.peerCore.on("streamError",t=>{Gt("EVENT: 单路流错误",t),this.emit("streamError",t)}),this.peerCore.on("streamReconnect",t=>{Gt("EVENT: 单路流重连",t),this.emit("streamReconnect",t)}),this.peerCore.on("traceIdUpdate",t=>{this.emit("traceIdUpdate",t)}),this.peerCore.on("pcReconnect",t=>{Gt("EVENT: PC重连",t),this.emit("pcReconnect",t)}),this.peerCore.on("datachannelNotEnabled",()=>{var t;Gt("EVENT: 数据通道未开启"),this.stopHeartbeatTimeoutChecker(),(t=this.peerCore)==null||t.stopSignalHeartbeatTimer()})):Gt("PeerCore listeners registration failed.")}startHeartbeatTimeoutChecker(r){this.stopHeartbeatTimeoutChecker();let e=8;r&&(e=r/1e3),this.heartbeatTimeoutHandler=setInterval(()=>{this.noHeartbeatCount++,this.noHeartbeatCount>=e&&(Gt("EVENT: 心跳超时, PC重连"),this.stopHeartbeatTimeoutChecker(),this.emit("pcReconnect",{recode:"",reMsg:"heartbeat timeout"}))},1e3)}stopHeartbeatTimeoutChecker(){this.heartbeatTimeoutHandler!==null&&clearInterval(this.heartbeatTimeoutHandler),this.heartbeatTimeoutHandler=null,this.noHeartbeatCount=0}};wc.CONNECT_TIMEOUT=1e4;let Zi=wc;class Pu{constructor(){this.workerList=[]}add(r){return!this.findByMsid({url:r.info.url,source:r.source,kind:r.kind,msid:r.kind===Ar.VIDEO?r.info.vMsid:r.info.aMsid})&&(this.workerList.push(r),!0)}removeByUrl(r){this.workerList.filter(e=>e.info.url.split("?")[0]===r.url.split("?")[0]&&e.source===r.source).forEach(e=>{e.worker.terminate(),this.workerList=this.workerList.filter(t=>t!==e)})}removeByMsid(r){const e=this.findByMsid(r);e&&(e.worker.terminate(),this.workerList=this.workerList.filter(t=>t!==e))}findByUrl(r,e){return this.workerList.find(t=>t.info.url.split("?")[0]===r.split("?")[0]&&t.kind===e)}findByMsid(r){const{url:e,kind:t,source:i,msid:n}=r,a=t===Ar.VIDEO?"vMsid":"aMsid";return this.workerList.find(c=>c.info.url.split("?")[0]===e.split("?")[0]&&c.source===i&&c.kind===t&&c.info[a]===n)}dispose(){this.workerList.forEach(r=>{r.worker.terminate()}),this.workerList=[]}}var zs={exports:{}},Ac=function(s,r){return function(){for(var e=new Array(arguments.length),t=0;t<e.length;t++)e[t]=arguments[t];return s.apply(r,e)}},Du=Ac,Pr=Object.prototype.toString;function Ks(s){return Pr.call(s)==="[object Array]"}function Js(s){return s===void 0}function Ic(s){return s!==null&&typeof s=="object"}function Yi(s){if(Pr.call(s)!=="[object Object]")return!1;var r=Object.getPrototypeOf(s);return r===null||r===Object.prototype}function Pc(s){return Pr.call(s)==="[object Function]"}function $s(s,r){if(s!=null)if(typeof s!="object"&&(s=[s]),Ks(s))for(var e=0,t=s.length;e<t;e++)r.call(null,s[e],e,s);else for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&r.call(null,s[i],i,s)}var Dt={isArray:Ks,isArrayBuffer:function(s){return Pr.call(s)==="[object ArrayBuffer]"},isBuffer:function(s){return s!==null&&!Js(s)&&s.constructor!==null&&!Js(s.constructor)&&typeof s.constructor.isBuffer=="function"&&s.constructor.isBuffer(s)},isFormData:function(s){return typeof FormData!="undefined"&&s instanceof FormData},isArrayBufferView:function(s){return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?ArrayBuffer.isView(s):s&&s.buffer&&s.buffer instanceof ArrayBuffer},isString:function(s){return typeof s=="string"},isNumber:function(s){return typeof s=="number"},isObject:Ic,isPlainObject:Yi,isUndefined:Js,isDate:function(s){return Pr.call(s)==="[object Date]"},isFile:function(s){return Pr.call(s)==="[object File]"},isBlob:function(s){return Pr.call(s)==="[object Blob]"},isFunction:Pc,isStream:function(s){return Ic(s)&&Pc(s.pipe)},isURLSearchParams:function(s){return typeof URLSearchParams!="undefined"&&s instanceof URLSearchParams},isStandardBrowserEnv:function(){return(typeof navigator=="undefined"||navigator.product!=="ReactNative"&&navigator.product!=="NativeScript"&&navigator.product!=="NS")&&typeof window!="undefined"&&typeof document!="undefined"},forEach:$s,merge:function s(){var r={};function e(n,a){Yi(r[a])&&Yi(n)?r[a]=s(r[a],n):Yi(n)?r[a]=s({},n):Ks(n)?r[a]=n.slice():r[a]=n}for(var t=0,i=arguments.length;t<i;t++)$s(arguments[t],e);return r},extend:function(s,r,e){return $s(r,function(t,i){s[i]=e&&typeof t=="function"?Du(t,e):t}),s},trim:function(s){return s.trim?s.trim():s.replace(/^\s+|\s+$/g,"")},stripBOM:function(s){return s.charCodeAt(0)===65279&&(s=s.slice(1)),s}},Yr=Dt;function Dc(s){return encodeURIComponent(s).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var kc=function(s,r,e){if(!r)return s;var t;if(e)t=e(r);else if(Yr.isURLSearchParams(r))t=r.toString();else{var i=[];Yr.forEach(r,function(a,c){a!=null&&(Yr.isArray(a)?c+="[]":a=[a],Yr.forEach(a,function(o){Yr.isDate(o)?o=o.toISOString():Yr.isObject(o)&&(o=JSON.stringify(o)),i.push(Dc(c)+"="+Dc(o))}))}),t=i.join("&")}if(t){var n=s.indexOf("#");n!==-1&&(s=s.slice(0,n)),s+=(s.indexOf("?")===-1?"?":"&")+t}return s},ku=Dt;function Qi(){this.handlers=[]}Qi.prototype.use=function(s,r,e){return this.handlers.push({fulfilled:s,rejected:r,synchronous:!!e&&e.synchronous,runWhen:e?e.runWhen:null}),this.handlers.length-1},Qi.prototype.eject=function(s){this.handlers[s]&&(this.handlers[s]=null)},Qi.prototype.forEach=function(s){ku.forEach(this.handlers,function(r){r!==null&&s(r)})};var Xs,Mc,Oc,Nc,Zs,Lc,xc,Vc,Uc,Bc,Fc,Hc,Ys,Wc,jc,Gc,Qs,zc,Mu=Qi,Ou=Dt,Kc=function(s,r,e,t,i){return s.config=r,e&&(s.code=e),s.request=t,s.response=i,s.isAxiosError=!0,s.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code}},s};function Jc(){if(Mc)return Xs;Mc=1;var s=Kc;return Xs=function(r,e,t,i,n){var a=new Error(r);return s(a,e,t,i,n)},Xs}function Nu(){if(Nc)return Oc;Nc=1;var s=Jc();return Oc=function(r,e,t){var i=t.config.validateStatus;t.status&&i&&!i(t.status)?e(s("Request failed with status code "+t.status,t.config,null,t.request,t)):r(t)}}function Lu(){if(Lc)return Zs;Lc=1;var s=Dt;return Zs=s.isStandardBrowserEnv()?{write:function(r,e,t,i,n,a){var c=[];c.push(r+"="+encodeURIComponent(e)),s.isNumber(t)&&c.push("expires="+new Date(t).toGMTString()),s.isString(i)&&c.push("path="+i),s.isString(n)&&c.push("domain="+n),a===!0&&c.push("secure"),document.cookie=c.join("; ")},read:function(r){var e=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove:function(r){this.write(r,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},Zs}function xu(){return Vc?xc:(Vc=1,xc=function(s){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(s)})}function Vu(){return Bc?Uc:(Bc=1,Uc=function(s,r){return r?s.replace(/\/+$/,"")+"/"+r.replace(/^\/+/,""):s})}function Uu(){if(Hc)return Fc;Hc=1;var s=xu(),r=Vu();return Fc=function(e,t){return e&&!s(t)?r(e,t):t}}function Bu(){if(Wc)return Ys;Wc=1;var s=Dt,r=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];return Ys=function(e){var t,i,n,a={};return e&&s.forEach(e.split(`
177
+ `),function(c){if(n=c.indexOf(":"),t=s.trim(c.substr(0,n)).toLowerCase(),i=s.trim(c.substr(n+1)),t){if(a[t]&&r.indexOf(t)>=0)return;a[t]=t==="set-cookie"?(a[t]?a[t]:[]).concat([i]):a[t]?a[t]+", "+i:i}}),a},Ys}function Fu(){if(Gc)return jc;Gc=1;var s=Dt;return jc=s.isStandardBrowserEnv()?function(){var r,e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");function i(n){var a=n;return e&&(t.setAttribute("href",a),a=t.href),t.setAttribute("href",a),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:t.pathname.charAt(0)==="/"?t.pathname:"/"+t.pathname}}return r=i(window.location.href),function(n){var a=s.isString(n)?i(n):n;return a.protocol===r.protocol&&a.host===r.host}}():function(){return!0}}function Hu(){if(zc)return Qs;zc=1;var s=Dt,r=Nu(),e=Lu(),t=kc,i=Uu(),n=Bu(),a=Fu(),c=Jc();return Qs=function(o){return new Promise(function(l,d){var h=o.data,u=o.headers,p=o.responseType;s.isFormData(h)&&delete u["Content-Type"];var f=new XMLHttpRequest;if(o.auth){var m=o.auth.username||"",g=o.auth.password?unescape(encodeURIComponent(o.auth.password)):"";u.Authorization="Basic "+btoa(m+":"+g)}var S=i(o.baseURL,o.url);function v(){if(f){var T="getAllResponseHeaders"in f?n(f.getAllResponseHeaders()):null,R={data:p&&p!=="text"&&p!=="json"?f.response:f.responseText,status:f.status,statusText:f.statusText,headers:T,config:o,request:f};r(l,d,R),f=null}}if(f.open(o.method.toUpperCase(),t(S,o.params,o.paramsSerializer),!0),f.timeout=o.timeout,"onloadend"in f?f.onloadend=v:f.onreadystatechange=function(){f&&f.readyState===4&&(f.status!==0||f.responseURL&&f.responseURL.indexOf("file:")===0)&&setTimeout(v)},f.onabort=function(){f&&(d(c("Request aborted",o,"ECONNABORTED",f)),f=null)},f.onerror=function(){d(c("Network Error",o,null,f)),f=null},f.ontimeout=function(){var T="timeout of "+o.timeout+"ms exceeded";o.timeoutErrorMessage&&(T=o.timeoutErrorMessage),d(c(T,o,o.transitional&&o.transitional.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",f)),f=null},s.isStandardBrowserEnv()){var E=(o.withCredentials||a(S))&&o.xsrfCookieName?e.read(o.xsrfCookieName):void 0;E&&(u[o.xsrfHeaderName]=E)}"setRequestHeader"in f&&s.forEach(u,function(T,R){h===void 0&&R.toLowerCase()==="content-type"?delete u[R]:f.setRequestHeader(R,T)}),s.isUndefined(o.withCredentials)||(f.withCredentials=!!o.withCredentials),p&&p!=="json"&&(f.responseType=o.responseType),typeof o.onDownloadProgress=="function"&&f.addEventListener("progress",o.onDownloadProgress),typeof o.onUploadProgress=="function"&&f.upload&&f.upload.addEventListener("progress",o.onUploadProgress),o.cancelToken&&o.cancelToken.promise.then(function(T){f&&(f.abort(),d(T),f=null)}),h||(h=null),f.send(h)})},Qs}var ht=Dt,$c=function(s,r){Ou.forEach(s,function(e,t){t!==r&&t.toUpperCase()===r.toUpperCase()&&(s[r]=e,delete s[t])})},Wu=Kc,ju={"Content-Type":"application/x-www-form-urlencoded"};function Xc(s,r){!ht.isUndefined(s)&&ht.isUndefined(s["Content-Type"])&&(s["Content-Type"]=r)}var Zc,qi={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:((typeof XMLHttpRequest!="undefined"||typeof process!="undefined"&&Object.prototype.toString.call(process)==="[object process]")&&(Zc=Hu()),Zc),transformRequest:[function(s,r){return $c(r,"Accept"),$c(r,"Content-Type"),ht.isFormData(s)||ht.isArrayBuffer(s)||ht.isBuffer(s)||ht.isStream(s)||ht.isFile(s)||ht.isBlob(s)?s:ht.isArrayBufferView(s)?s.buffer:ht.isURLSearchParams(s)?(Xc(r,"application/x-www-form-urlencoded;charset=utf-8"),s.toString()):ht.isObject(s)||r&&r["Content-Type"]==="application/json"?(Xc(r,"application/json"),function(e,t,i){if(ht.isString(e))try{return(t||JSON.parse)(e),ht.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(i||JSON.stringify)(e)}(s)):s}],transformResponse:[function(s){var r=this.transitional,e=r&&r.silentJSONParsing,t=r&&r.forcedJSONParsing,i=!e&&this.responseType==="json";if(i||t&&ht.isString(s)&&s.length)try{return JSON.parse(s)}catch(n){if(i)throw n.name==="SyntaxError"?Wu(n,this,"E_JSON_PARSE"):n}return s}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(s){return s>=200&&s<300}};qi.headers={common:{Accept:"application/json, text/plain, */*"}},ht.forEach(["delete","get","head"],function(s){qi.headers[s]={}}),ht.forEach(["post","put","patch"],function(s){qi.headers[s]=ht.merge(ju)});var Yc,Qc,qs=qi,Gu=Dt,zu=qs;function qc(){return Qc?Yc:(Qc=1,Yc=function(s){return!(!s||!s.__CANCEL__)})}var ed=Dt,en=function(s,r,e){var t=this||zu;return Gu.forEach(e,function(i){s=i.call(t,s,r)}),s},Ku=qc(),Ju=qs;function tn(s){s.cancelToken&&s.cancelToken.throwIfRequested()}var gt=Dt,td=function(s,r){r=r||{};var e={},t=["url","method","data"],i=["headers","auth","proxy","params"],n=["baseURL","transformRequest","transformResponse","paramsSerializer","timeout","timeoutMessage","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","decompress","maxContentLength","maxBodyLength","maxRedirects","transport","httpAgent","httpsAgent","cancelToken","socketPath","responseEncoding"],a=["validateStatus"];function c(h,u){return gt.isPlainObject(h)&&gt.isPlainObject(u)?gt.merge(h,u):gt.isPlainObject(u)?gt.merge({},u):gt.isArray(u)?u.slice():u}function o(h){gt.isUndefined(r[h])?gt.isUndefined(s[h])||(e[h]=c(void 0,s[h])):e[h]=c(s[h],r[h])}gt.forEach(t,function(h){gt.isUndefined(r[h])||(e[h]=c(void 0,r[h]))}),gt.forEach(i,o),gt.forEach(n,function(h){gt.isUndefined(r[h])?gt.isUndefined(s[h])||(e[h]=c(void 0,s[h])):e[h]=c(void 0,r[h])}),gt.forEach(a,function(h){h in r?e[h]=c(s[h],r[h]):h in s&&(e[h]=c(void 0,s[h]))});var l=t.concat(i).concat(n).concat(a),d=Object.keys(s).concat(Object.keys(r)).filter(function(h){return l.indexOf(h)===-1});return gt.forEach(d,o),e},rd={name:"axios",version:"0.21.4",description:"Promise based HTTP client for the browser and node.js",main:"index.js",scripts:{test:"grunt test",start:"node ./sandbox/server.js",build:"NODE_ENV=production grunt build",preversion:"npm test",version:"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json",postversion:"git push && git push --tags",examples:"node ./examples/server.js",coveralls:"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",fix:"eslint --fix lib/**/*.js"},repository:{type:"git",url:"https://github.com/axios/axios.git"},keywords:["xhr","http","ajax","promise","node"],author:"Matt Zabriskie",license:"MIT",bugs:{url:"https://github.com/axios/axios/issues"},homepage:"https://axios-http.com",devDependencies:{coveralls:"^3.0.0","es6-promise":"^4.2.4",grunt:"^1.3.0","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^23.0.0","grunt-karma":"^4.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^4.0.2","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1",karma:"^6.3.2","karma-chrome-launcher":"^3.1.0","karma-firefox-launcher":"^2.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^4.3.6","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.8","karma-webpack":"^4.0.2","load-grunt-tasks":"^3.5.2",minimist:"^1.2.0",mocha:"^8.2.1",sinon:"^4.5.0","terser-webpack-plugin":"^4.2.3",typescript:"^4.0.5","url-search-params":"^0.10.0",webpack:"^4.44.2","webpack-dev-server":"^3.11.0"},browser:{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},jsdelivr:"dist/axios.min.js",unpkg:"dist/axios.min.js",typings:"./index.d.ts",dependencies:{"follow-redirects":"^1.14.0"},bundlesize:[{path:"./dist/axios.min.js",threshold:"5kB"}]},rn={};["object","boolean","number","function","string","symbol"].forEach(function(s,r){rn[s]=function(e){return typeof e===s||"a"+(r<1?"n ":" ")+s}});var id={},$u=rd.version.split(".");function sd(s,r){for(var e=r?r.split("."):$u,t=s.split("."),i=0;i<3;i++){if(e[i]>t[i])return!0;if(e[i]<t[i])return!1}return!1}rn.transitional=function(s,r,e){var t=r&&sd(r);function i(n,a){return"[Axios v"+rd.version+"] Transitional option '"+n+"'"+a+(e?". "+e:"")}return function(n,a,c){if(s===!1)throw new Error(i(a," has been removed in "+r));return t&&!id[a]&&(id[a]=!0,console.warn(i(a," has been deprecated since v"+r+" and will be removed in the near future"))),!s||s(n,a,c)}};var nd,ad,od,cd,dd,ld,hd,ud,Xu={isOlderVersion:sd,assertOptions:function(s,r,e){if(typeof s!="object")throw new TypeError("options must be an object");for(var t=Object.keys(s),i=t.length;i-- >0;){var n=t[i],a=r[n];if(a){var c=s[n],o=c===void 0||a(c,n,s);if(o!==!0)throw new TypeError("option "+n+" must be "+o)}else if(e!==!0)throw Error("Unknown option "+n)}},validators:rn},pd=Dt,Zu=kc,md=Mu,fd=function(s){return tn(s),s.headers=s.headers||{},s.data=en.call(s,s.data,s.headers,s.transformRequest),s.headers=ed.merge(s.headers.common||{},s.headers[s.method]||{},s.headers),ed.forEach(["delete","get","head","post","put","patch","common"],function(r){delete s.headers[r]}),(s.adapter||Ju.adapter)(s).then(function(r){return tn(s),r.data=en.call(s,r.data,r.headers,s.transformResponse),r},function(r){return Ku(r)||(tn(s),r&&r.response&&(r.response.data=en.call(s,r.response.data,r.response.headers,s.transformResponse))),Promise.reject(r)})},es=td,gd=Xu,Qr=gd.validators;function vi(s){this.defaults=s,this.interceptors={request:new md,response:new md}}function Sd(){if(ad)return nd;function s(r){this.message=r}return ad=1,s.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},s.prototype.__CANCEL__=!0,nd=s}vi.prototype.request=function(s){typeof s=="string"?(s=arguments[1]||{}).url=arguments[0]:s=s||{},(s=es(this.defaults,s)).method?s.method=s.method.toLowerCase():this.defaults.method?s.method=this.defaults.method.toLowerCase():s.method="get";var r=s.transitional;r!==void 0&&gd.assertOptions(r,{silentJSONParsing:Qr.transitional(Qr.boolean,"1.0.0"),forcedJSONParsing:Qr.transitional(Qr.boolean,"1.0.0"),clarifyTimeoutError:Qr.transitional(Qr.boolean,"1.0.0")},!1);var e=[],t=!0;this.interceptors.request.forEach(function(d){typeof d.runWhen=="function"&&d.runWhen(s)===!1||(t=t&&d.synchronous,e.unshift(d.fulfilled,d.rejected))});var i,n=[];if(this.interceptors.response.forEach(function(d){n.push(d.fulfilled,d.rejected)}),!t){var a=[fd,void 0];for(Array.prototype.unshift.apply(a,e),a=a.concat(n),i=Promise.resolve(s);a.length;)i=i.then(a.shift(),a.shift());return i}for(var c=s;e.length;){var o=e.shift(),l=e.shift();try{c=o(c)}catch(d){l(d);break}}try{i=fd(c)}catch(d){return Promise.reject(d)}for(;n.length;)i=i.then(n.shift(),n.shift());return i},vi.prototype.getUri=function(s){return s=es(this.defaults,s),Zu(s.url,s.params,s.paramsSerializer).replace(/^\?/,"")},pd.forEach(["delete","get","head","options"],function(s){vi.prototype[s]=function(r,e){return this.request(es(e||{},{method:s,url:r,data:(e||{}).data}))}}),pd.forEach(["post","put","patch"],function(s){vi.prototype[s]=function(r,e,t){return this.request(es(t||{},{method:s,url:r,data:e}))}});var bd=Dt,Yu=Ac,ts=vi,Qu=td;function vd(s){var r=new ts(s),e=Yu(ts.prototype.request,r);return bd.extend(e,ts.prototype,r),bd.extend(e,r),e}var zt=vd(qs);zt.Axios=ts,zt.create=function(s){return vd(Qu(zt.defaults,s))},zt.Cancel=Sd(),zt.CancelToken=function(){if(cd)return od;cd=1;var s=Sd();function r(e){if(typeof e!="function")throw new TypeError("executor must be a function.");var t;this.promise=new Promise(function(n){t=n});var i=this;e(function(n){i.reason||(i.reason=new s(n),t(i.reason))})}return r.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},r.source=function(){var e;return{token:new r(function(t){e=t}),cancel:e}},od=r}(),zt.isCancel=qc(),zt.all=function(s){return Promise.all(s)},zt.spread=ld?dd:(ld=1,dd=function(s){return function(r){return s.apply(null,r)}}),zt.isAxiosError=ud?hd:(ud=1,hd=function(s){return typeof s=="object"&&s.isAxiosError===!0}),zs.exports=zt,zs.exports.default=zt;const Rd=Cr(zs.exports),sn=Rd.create({baseURL:"",timeout:5e3,headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}});var Ae=(s=>(s.MESSAGE_NOTSUPPORT_WEBRTC="not support webrtc",s.MESSAGE_BROWSER_NOTSUPPORT="browser not support",s.MESSAGE_BROWSER_VERSIONLOW="browser version too low",s.MESSAGE_NOTSUPPORT_H264="not support h264",s.MESSAGE_CREATEOFFER="create offer error",s))(Ae||{});class qu{constructor(){this.errorCode=0,this.message=""}}class Dr{constructor(){this.deviceManager=new Gi.BrowserDeviceManager}isSupport(r){return new Promise((e,t)=>_(this,null,function*(){let i=new qu;if(!this.checkWebRtcSupport())return i.errorCode=H.ERROR_NOTSUPPORT_WEBRTC,i.message=Ae.MESSAGE_NOTSUPPORT_WEBRTC,t(i);if(r.onlyCheckUA){if(!this.checkBrowser(i))return t(i)}else{const[n,a,c,o]=yield this.checkWebrtcAbilities();if(!n)return i.errorCode=H.ERROR_NOTSUPPORT_WEBRTC,i.message=Ae.MESSAGE_NOTSUPPORT_WEBRTC,t(i);if(o)return i.errorCode=H.ERROR_BROWSER_NOTSUPPORT,i.message=Ae.MESSAGE_BROWSER_NOTSUPPORT,t(i)}r.isReceiveVideo?this.checkH264Decode(i).then(()=>{e(i)}).catch(()=>{t(i)}):e(i)}))}checkEncodedTransformSupport(){const r=window.RTCRtpReceiver&&"createEncodedStreams"in RTCRtpReceiver.prototype,e=window.RTCRtpReceiver&&"transform"in RTCRtpReceiver.prototype&&"RTCRtpScriptTransform"in window;return r||e}checkWebrtcAbilities(r){return _(this,null,function*(){const e=window.RTCPeerConnection;let t=!1,i=!1,n=null,a=!1;try{if(e){let c=new e;if(i="createDataChannel"in c,r){const d=this.createBlankStream();d.getTracks().forEach(h=>{c==null||c.addTrack(h,d)})}const o=yield c.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,iceRestart:!0}),{sdp:l}=o||{};n=r?!!(l&&l.indexOf("a=sendrecv")>-1):null,c.close(),c=void 0,t=!0}}catch(c){t=!1,i=!1,n=!1}return a=this.checkBlackList(),[t,i,n,a]})}checkPublishSupport(){return _(this,null,function*(){let r={isWebRTCSupported:!1,isH264EncodeSupported:!1,isMediaDevicesSupported:!1,isScreenCaptureSupported:!1,isAudioMixSupported:!1,cameraList:[],micList:[],speakerList:[]};if(this.checkWebRtcSupport()){const[e,t,i]=yield this.checkWebrtcAbilities(!0);r.isWebRTCSupported=!(!e||!i),r.isWebRTCSupported?r.isH264EncodeSupported=yield this.checkH264Encode():r.isH264EncodeSupported=!1}else r.isWebRTCSupported=!1,r.isH264EncodeSupported=!1;if(r.isMediaDevicesSupported=this.checkMediaDevices(),r.isScreenCaptureSupported=this.checkScreenCapture(),r.isAudioMixSupported=this.checkAudioMix(),r.isMediaDevicesSupported)try{r.cameraList=(yield this.deviceManager.getCameraList()).filter(e=>e.deviceId),r.micList=(yield this.deviceManager.getMicList()).filter(e=>e.deviceId),r.speakerList=(yield this.deviceManager.getSpeakerList()).filter(e=>e.deviceId)}catch(e){}return r})}checkWebRtcSupport(){return!!window.RTCPeerConnection}checkMediaDevices(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)}checkScreenCapture(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)}checkAudioMix(){if(!window.AudioContext)return!1;const r=new AudioContext;return!!r.createMediaStreamDestination&&!!r.createMediaStreamSource}checkBlackList(){let r=!1;if(G.BrowserUtil.isOppoBrowser&&G.SystemUtil.isAndroid){const e=(this.getUa().toLowerCase().match(/heytapbrowser\/([\d.]+)/)||[])[1]||"";r=!this.compareVersion(e,"40.7.39.1")}else(G.BrowserUtil.isUCBrowser||G.BrowserUtil.isQuarkBrowser)&&G.SystemUtil.isIos?r=!0:G.BrowserUtil.isWebView&&G.SystemUtil.isAndroid&&(r=!(G.BrowserUtil.browserMainVersion>=79));return r}checkBrowser(r){if(G.SystemUtil.isIos){if(G.BrowserUtil.isUCBrowser||G.BrowserUtil.isQuarkBrowser)return r.errorCode=H.ERROR_BROWSER_NOTSUPPORT,r.message=Ae.MESSAGE_BROWSER_NOTSUPPORT,!1;if(G.BrowserUtil.isSafari||G.BrowserUtil.isQQBrowser)return G.BrowserUtil.browserMainVersion>=11||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isEdge||G.BrowserUtil.isChrome)return G.BrowserUtil.browserMainVersion>=79||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isMicroMessenger)return!!this.compareVersion(G.SystemUtil.systemVersion,"12.1.4")||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isDingTalk)return!!G.SystemUtil.compareVersion("11.2.5")||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isWebView)return!!this.compareVersion(G.SystemUtil.systemVersion,"14.3")||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1)}else if(G.SystemUtil.isAndroid){if(this.checkPrivateUcWebview())return!0;if(G.BrowserUtil.isChrome||G.BrowserUtil.isQQBrowser||G.BrowserUtil.isHuaweiBrowser||G.BrowserUtil.isSamsungBrowser)return G.BrowserUtil.browserMainVersion>=63||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isEdge)return G.BrowserUtil.browserMainVersion>=79||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isMicroMessenger)return!!this.compareVersion(this.getChromeCoreVersion(),"63")||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isDingTalk)return!!this.compareVersion(this.getChromeCoreVersion(),"69")||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isOppoBrowser){const e=(this.getUa().toLowerCase().match(/heytapbrowser\/([\d.]+)/)||[])[1]||"";return!!this.compareVersion(e,"40.7.39.1")||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1)}if(G.BrowserUtil.isX5Core)return!0;if(G.BrowserUtil.isWebView)return G.BrowserUtil.browserMainVersion>=79||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1)}else if(G.SystemUtil.isMacOS){if(G.BrowserUtil.isElectron)return!0;if(G.BrowserUtil.isSafari)return G.BrowserUtil.browserMainVersion>=11||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isChrome)return G.BrowserUtil.browserMainVersion>=63||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isEdge)return G.BrowserUtil.browserMainVersion>=79||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isFirefox)return G.BrowserUtil.browserMainVersion>=62||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isOpera)return G.BrowserUtil.browserMainVersion>=15||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1)}else if(G.SystemUtil.isWindows){if(G.BrowserUtil.isElectron||G.BrowserUtil.isMicroMessenger)return!0;if(G.BrowserUtil.isChrome||G.BrowserUtil.isQQBrowser)return G.BrowserUtil.browserMainVersion>=63||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isEdge)return G.BrowserUtil.browserMainVersion>=79||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isFirefox)return G.BrowserUtil.browserMainVersion>=62||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isOpera)return G.BrowserUtil.browserMainVersion>=15||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1)}else if(G.SystemUtil.isLinux){if(G.BrowserUtil.isChrome)return G.BrowserUtil.browserMainVersion>=63||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isEdge)return G.BrowserUtil.browserMainVersion>=79||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1);if(G.BrowserUtil.isFirefox)return G.BrowserUtil.browserMainVersion>=62||(r.errorCode=H.ERROR_BROWSER_VERSIONLOW,r.message=Ae.MESSAGE_BROWSER_VERSIONLOW,!1)}return r.errorCode===0&&(r.errorCode=H.ERROR_BROWSER_NOTSUPPORT,r.message=Ae.MESSAGE_BROWSER_NOTSUPPORT),!1}checkH264Decode(r){return new Promise((e,t)=>_(this,null,function*(){let i=yield this.tryFindH264FromSdp(r);if(i)e(!0);else{try{i=yield this.loadH264(3)}catch(n){}i?e(!0):(r&&r.errorCode===0&&(r.errorCode=H.ERROR_NOTSUPPORT_H264,r.message=Ae.MESSAGE_NOTSUPPORT_H264),t(!1))}}))}checkSDPSupportH264(r){return r.indexOf("H264")>0||r.indexOf("h264")>0||r.indexOf("H.264")>0||r.indexOf("h.264")>0}checkPrivateUcWebview(){return this.getUa().indexOf("UniqueCode")>0}getUa(){return navigator&&navigator.userAgent||""}getChromeCoreVersion(){return(this.getUa().toLowerCase().match(/chrome\/([\d.]+)/)||[])[1]||""}compareVersion(r="",e=""){let t=(r||"").split("."),i=(e||"").split("."),n=0,a=0;for(let c=0;c<t.length&&c<i.length;++c){if(n=isNaN(parseInt(t[c],10))?0:parseInt(t[c],10),a=isNaN(parseInt(i[c],10))?0:parseInt(i[c],10),n<a)return!1;if(n>a)return!0}return!0}tryFindH264FromSdp(r){return _(this,null,function*(){let e=!1;if(!RTCPeerConnection)return e;let t,i=new RTCPeerConnection;try{t=yield i.createOffer({offerToReceiveVideo:!0,offerToReceiveAudio:!0}),t&&t.sdp&&(e=this.checkSDPSupportH264(t.sdp))}catch(n){e=!1,r&&(r.errorCode=H.ERROR_CREATEOFFER,r.message=Ae.MESSAGE_CREATEOFFER)}return i.close(),i=void 0,e})}loadH264(r){return new Promise((e,t)=>_(this,null,function*(){if(!G.SystemUtil.isAndroid||!G.BrowserUtil.isChrome&&!G.BrowserUtil.isWebView)return void e(!1);let i=0,n=[],a=0;for(;i<r;){let c=setTimeout(()=>_(this,null,function*(){if(a++,yield this.tryFindH264FromSdp())return n.forEach(o=>{clearTimeout(o)}),n=[],void e(!0);a===r&&e(!1)}),1e3*i);n.push(c),i++}}))}checkH264Encode(){return _(this,null,function*(){yield this.loadH264(3);let r=new RTCPeerConnection;r.addTransceiver("video",{direction:"sendonly"});try{let e=yield r.createOffer();return this.checkSDPSupportH264(e.sdp||"")}catch(e){return!1}})}createBlankStream(){const r=(()=>{const t=new AudioContext,i=t.createOscillator(),n=i.connect(t.createMediaStreamDestination());return i.start(),Object.assign(n.stream.getAudioTracks()[0],{enabled:!1})})();r.stop();const e=(({width:t=160,height:i=90}={})=>{var c;const n=document.createElement("canvas");n.width=t,n.height=i,(c=n.getContext("2d"))==null||c.fillRect(0,0,t,i);const a=n.captureStream();return Object.assign(a.getVideoTracks()[0],{enabled:!1})})();return e.stop(),new MediaStream([r,e])}}const Ed=class la{constructor(r){this.timeout=r.timeout||la.DEFAULT_TIMEOUT,this.handler=r.handler||(()=>{}),this.watchTimer=null}get actTimeout(){return this.timeout}check(r,e,t,i){this.hasNoData(r)?this.watchTimer||(this.watchTimer=window.setTimeout(()=>{this.handler(e,t,i)},this.timeout)):this.watchTimer&&(clearTimeout(this.watchTimer),this.watchTimer=null)}hasNoData(r){return!r||(r.video?!(Number(r.video.bytesReceivedPerSecond)>0):!r.audio||!(Number(r.audio.bytesReceivedPerSecond)>0))}updateConfig(r){this.timeout=r.timeout||this.timeout,this.handler=r.handler||this.handler}reset(){this.watchTimer&&(clearTimeout(this.watchTimer),this.watchTimer=null)}dispose(){this.timeout=la.DEFAULT_TIMEOUT,this.handler=()=>{},this.watchTimer&&(clearTimeout(this.watchTimer),this.watchTimer=null)}};Ed.DEFAULT_TIMEOUT=6e3;let ep=Ed,yd="7.3.0-beta.2",nn=2,an="0.0.1";function Td(s,r,e){Object.defineProperty(s,r,{writable:!0,enumerable:!0,configurable:!0,value:e})}Array(32);let tp=class{constructor(s){var r,e;this.timer=null,this.time=10,this.count=10,this.arr=[],this.time=(r=s.time)!=null?r:10,this.count=(e=s.count)!=null?e:10,s.host.startsWith("http://")||s.host.startsWith("https://")?this.url=s.host+"/logstores/"+s.logstore+"/track":this.url="https://"+s.project+"."+s.host+"/logstores/"+s.logstore+"/track",this.opt=s,s.installUnloadHook&&typeof s.installUnloadHook=="function"&&s.installUnloadHook(()=>{this.sendImmediateInner()})}assemblePayload(s=this.arr){const r={__logs__:s};return this.opt.tags&&(r.__tags__=this.opt.tags),this.opt.topic&&(r.__topic__=this.opt.topic),this.opt.source&&(r.__source__=this.opt.source),JSON.stringify(r)}platformSend(){if(this.opt.sendPayload&&typeof this.opt.sendPayload=="function"){const s=this.assemblePayload();this.opt.sendPayload(this.url,s)}}transString(s){let r={};for(let e in s)typeof s[e]=="object"?r[e]=JSON.stringify(s[e]):r[e]=String(s[e]);return r}sendImmediateInner(){this.arr&&this.arr.length>0&&(this.platformSend(),this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.arr=[])}sendInner(){if(this.timer)this.arr.length>=this.count&&(clearTimeout(this.timer),this.timer=null,this.sendImmediateInner());else{const s=this;this.arr.length>=this.count||this.time<=0?this.sendImmediateInner():this.timer=setTimeout(function(){s.sendImmediateInner()},1e3*this.time)}}send(s){const r=this.transString(s);this.arr.push(r),this.sendInner()}sendImmediate(s){const r=this.transString(s);this.arr.push(r),this.sendImmediateInner()}sendBatchLogs(s){const r=s.map(e=>this.transString(e));this.arr.push(...r),this.sendInner()}sendBatchLogsImmediate(s){const r=s.map(e=>this.transString(e));this.arr.push(...r),this.sendImmediateInner()}};function Cd(s,r){const e=new window.XMLHttpRequest;e.open("POST",`${s}?APIVersion=0.6.0`,!0),e.send(r)}function rp(s,r){try{if(r.length>=32768)return void Cd(s,r);(function(e,t){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${e}?APIVersion=0.6.0`,t)})(s,r)||Cd(s,r)}catch(e){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
178
+ `+e),console.error("Failed log data:",s))}}let _d=class extends tp{constructor(s){super(Object.assign({},s,{installUnloadHook:r=>{window.addEventListener("beforeunload",()=>{r()})},sendPayload:(r,e)=>{rp(r,e)}}))}};(function(s,r,e,t){t?t(()=>{Td(s,r,e)}):Td(s,r,e)})(window,"SLS_Tracker",_d);var wd=(s=>(s[s.UA=101]="UA",s[s.SUB_STATS=107]="SUB_STATS",s[s.PUB_STATS=108]="PUB_STATS",s[s.CONNECT_STATE_CHANGE=109]="CONNECT_STATE_CHANGE",s[s.START_PLAY=120]="START_PLAY",s[s.STOP_PLAY=121]="STOP_PLAY",s[s.SUBSCRIBE_START=125]="SUBSCRIBE_START",s[s.SUBSCRIBE_OK=126]="SUBSCRIBE_OK",s[s.FIRST_FRAME_TIME=137]="FIRST_FRAME_TIME",s[s.DC_HTTP_CONNECT=140]="DC_HTTP_CONNECT",s[s.DC_HTTP_CONNECT_OK=141]="DC_HTTP_CONNECT_OK",s[s.DC_SUB_ADD=142]="DC_SUB_ADD",s[s.DC_SUB_ADD_OK=143]="DC_SUB_ADD_OK",s[s.DC_CONNECT_STATE_CHANGE=144]="DC_CONNECT_STATE_CHANGE",s[s.DC_SUB_STOP=145]="DC_SUB_STOP",s[s.DC_SUB_STOP_OK=146]="DC_SUB_STOP_OK",s[s.DC_DISPOSE=147]="DC_DISPOSE",s[s.DC_SUB_DELETE=148]="DC_SUB_DELETE",s[s.DC_SUB_DELETE_OK=149]="DC_SUB_DELETE_OK",s[s.ERROR_INFO=150]="ERROR_INFO",s[s.DC_PUB_ADD=152]="DC_PUB_ADD",s[s.DC_PUB_ADD_OK=153]="DC_PUB_ADD_OK",s[s.DC_PUB_STOP=155]="DC_PUB_STOP",s[s.DC_PUB_STOP_OK=156]="DC_PUB_STOP_OK",s[s.DC_PUB_DELETE=157]="DC_PUB_DELETE",s[s.DC_PUB_DELETE_OK=158]="DC_PUB_DELETE_OK",s[s.RECONNECT=160]="RECONNECT",s[s.RECONNECT_PARAMS=161]="RECONNECT_PARAMS",s[s.RECONNECT_FINISH=162]="RECONNECT_FINISH",s[s.NOTIFY_MESSAGE=170]="NOTIFY_MESSAGE",s[s.CUMU_DELAY_NOT_SUPPORTED=180]="CUMU_DELAY_NOT_SUPPORTED",s[s.CUMU_DELAY_ANSWER_NOT_FOUND=181]="CUMU_DELAY_ANSWER_NOT_FOUND",s[s.CREATE_CLIENT=200]="CREATE_CLIENT",s[s.LOCALSTREAM_INITED=201]="LOCALSTREAM_INITED",s[s.START_PUBLISH=220]="START_PUBLISH",s[s.STOP_PUBLISH=221]="STOP_PUBLISH",s[s.PUBLISH_OK=222]="PUBLISH_OK",s[s.SET_VIDEOPROFILE=230]="SET_VIDEOPROFILE",s[s.SET_SCREENPROFILE=231]="SET_SCREENPROFILE",s[s.SET_AUDIOPROFILE=238]="SET_AUDIOPROFILE",s[s.ENABLE_AUDIO=232]="ENABLE_AUDIO",s[s.DISABLE_AUDIO=233]="DISABLE_AUDIO",s[s.ENABLE_VIDEO=234]="ENABLE_VIDEO",s[s.DISABLE_VIDEO=235]="DISABLE_VIDEO",s[s.STOP=236]="STOP",s[s.PLAY=237]="PLAY",s))(wd||{});class rs{constructor(r){this.customReporter=r==null?void 0:r.customReporter,this.ct=r&&r.customTag?r.customTag:"",this.enableLog=!r||r.trackLog!=0,this._initParam(),this.slsTracker=new _d({host:"cn-hangzhou.log.aliyuncs.com",project:"videocloud",logstore:"live-client-log",time:10,count:10})}dispose(){this.ct="",this.enableLog=!0,this.slsTracker=null,this.cumuDelayInfo=void 0,this.customReporter=void 0}updateTid(){this.param?this.param.tid=G.Guid.create(32):this._initParam()}updateUrl(r){this.param&&(this.param.pu=r)}reportUA(r){this.reporter({msgid:101,args:he({ua:r})})}reportPullStats(r){let e,t=Q(D({},r),{cumu:""});if(this.cumuDelayInfo)try{e=JSON.parse(this.cumuDelayInfo)}catch(i){}e&&(this.cumuDelayInfo=void 0,t.cumu=e),this.reporter({msgid:107,args:he(D({},t))})}reportPushStats(r){this.reporter({msgid:108,args:he(D({},r))})}reportStartPlay(r){this.reporter({msgid:120,args:he({vurl:r})})}reportStopPlay(){this.reporter({msgid:121})}reportSubscribeStart(r,e,t,i,n){this.reporter({msgid:125,args:he({vurl:r,surl:e,vMsid:t?t.join(", "):"",aMsid:i?i.join(", "):"",isSubAdd:!!n})})}reportSubscribeOk(r={}){this.reporter({msgid:126,args:he({vurl:r.vurl||"",surl:r.surl||"",hrct:r.hrct,tcid:r.traceId,rslt:r.rslt,isSubAdd:!!r.isSubAdd})})}reportFirstFrameTime(r,e,t,i,n,a,c,o,l,d,h,u,p,f){this.reporter({msgid:137,args:he({vurl:r,cpct:t,hrct:i,tcid:e,ffct:n,rslt:a,cnct:c,stats:o,delct:l,addct:d,actct:h,vMsid:u?u.join(", "):"",aMsid:p?p.join(", "):"",isSubAdd:!!f})})}reportErrorInfo(r,e,t,i){r!==H.ERROR_AUTOPLAY_ERROR&&this.reporter({msgid:150,args:he({errorCode:r,message:e,tcid:t,extraInfo:i})})}reportReconnect(r,e,t,i,n){this.reporter({msgid:160,args:he({errorCode:r,message:e,tcid:t,retryTimes:i,useTcp:n})})}reportReconnectParams(r,e,t,i,n,a){this.reporter({msgid:161,args:he({type:r,url:e,vMsid:(t||[]).join(","),aMsid:(i||[]).join(","),useTcp:n,streamId:a})})}reportReconnectFinish(r={}){this.reporter({msgid:162,args:he(D({},r))})}reportCreateClient(){this.reporter({msgid:200})}reportStartPublish(r,e,t){this.reporter({msgid:220,args:he({purl:r,surl:e,isPubAdd:!!t})})}reportPublishOk(r,e,t,i,n,a,c,o){this.reporter({msgid:222,args:he({purl:r,surl:e,coct:t,hrct:i,act:n,tcid:a,totalct:c||t+i+n,isPubAdd:!!o})})}reportStopPublish(r,e){this.reporter({msgid:221,args:he({url:r,isPubStop:!!e})})}reportVideoProfile(r){this.reporter({msgid:230,args:he({vp:r})})}reportScreenProfile(r){this.reporter({msgid:231,args:he({sp:r})})}reportAudioProfile(r){this.reporter({msgid:238,args:he({vp:r})})}reportEnableAudio(){this.reporter({msgid:232})}reportDisableAudio(){this.reporter({msgid:233})}reportEnableVideo(){this.reporter({msgid:234})}reportDisableVideo(){this.reporter({msgid:235})}reportStop(r){this.reporter({msgid:236,args:he({tp:r})})}reportPlay(r){this.reporter({msgid:237,args:he({tp:r})})}reportStreamCreated(r,e){this.reporter({msgid:201,args:he({userConfig:r,localStreamInfo:e})})}reportConnectionChange(r,e){this.reporter({msgid:109,args:he({connectionState:r,direction:e})})}reportDatachannelHttpConnect(r){this.reporter({msgid:140,args:he({url:r})})}reportDatachannelHttpConnectOk(r){this.reporter({msgid:141,args:he(D({},r))})}reportDatachannelSubAdd(r){this.reporter({msgid:142,args:he(D({},r))})}reportDatachannelPubAdd(r){this.reporter({msgid:152,args:he(D({},r))})}reportDatachannelSubAddOk(r){this.reporter({msgid:143,args:he(D({},r))})}reportDatachannelPubAddOk(r){this.reporter({msgid:153,args:he(D({},r))})}reportDatachannelStatusChange(r){this.reporter({msgid:144,args:he(D({},r))})}reportDatachannelSubDelete(r){this.reporter({msgid:148,args:he(D({},r))})}reportDatachannelPubDelete(r){this.reporter({msgid:157,args:he(D({},r))})}reportDatachannelSubDeleteOk(r){this.reporter({msgid:149,args:he(D({},r))})}reportDatachannelPubDeleteOk(r){this.reporter({msgid:158,args:he(D({},r))})}reportDatachannelSubStop(r){this.reporter({msgid:145,args:he(D({},r))})}reportDatachannelPubStop(r){this.reporter({msgid:155,args:he(D({},r))})}reportDatachannelSubStopOk(r){this.reporter({msgid:146,args:he(D({},r))})}reportDatachannelPubStopOk(r){this.reporter({msgid:156,args:he(D({},r))})}reportDatachannelDispose(r){this.reporter({msgid:147,args:he(D({},r))})}reportNotifyMessage(r){this.reporter({msgid:170,args:he(D({},r))})}reportCumuDelayNotSupported(){this.reporter({msgid:180})}reportCumuDelayAnswerNotFound(){this.reporter({msgid:181})}updateCumuDelayInfo(r){this.cumuDelayInfo=r.json}_initParam(){this.param||(this.param={APIVersion:"0.6.0",os:G.SystemUtil.platform,osv:G.SystemUtil.systemVersion,bt:G.BrowserUtil.browserName,bv:G.BrowserUtil.browserVersion,host:window.location.origin,page:window.location.href,uid:G.LocalStorage.uuid,tid:G.Guid.create(32),ver:yd,ct:this.ct,dt:"",lv:"1.0.0",ua:navigator&&navigator.userAgent||"",pu:""})}reporter(r){var t;const e=Q(D(Q(D({},this.param||{}),{tm:new Date().getTime()}),r||{}),{msgname:wd[r.msgid]});if(this.customReporter&&typeof this.customReporter=="function")try{this.customReporter(e)}catch(i){console.error("[Error in customReporter] ",i)}this.enableLog&&((t=this.slsTracker)==null||t.send(e))}data2String(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=t+"="+r[t]);return e}}rs.HEARTHEAT_INTERVAL=4;const Ad="canplay",ip="waiting",sp="playing",np="media",ap="ended",op="timeout";class kr{constructor(r){this.event=r}}class Id extends ac{constructor(){super(),this.recvCanPlay=!1,this.autoplay=!0,this.onCanPlay=this.onCanPlay.bind(this)}set muted(r){this.element&&(this.element.muted=r)}get muted(){return!!this.element&&this.element.muted}get audioTrack(){var r;return(r=this.mediastream)==null?void 0:r.getAudioTracks()[0]}get videoTrack(){var r;return(r=this.mediastream)==null?void 0:r.getVideoTracks()[0]}get hasVideo(){return!!this.videoTrack}get hasAudio(){return!!this.audioTrack}get mediaStream(){return this.mediastream}updateMediaStream(r){let e=this.mediastream||new MediaStream;r.getTracks().forEach(t=>e.addTrack(t)),this.mediastream=e,this.element&&this.play(this.element)}getMediaStream(){return this.mediastream}mergeStream(r){if(!this.mediaStream)return;const e=r.getVideoTracks()[0],t=r.getAudioTracks()[0];e&&(this.videoTrack&&this.mediaStream.removeTrack(this.videoTrack),this.mediaStream.addTrack(e),this.videotrack=e),t&&(this.audioTrack&&this.mediaStream.removeTrack(this.audioTrack),this.mediaStream.addTrack(t),this.audiotrack=t)}play(r,e){if(this.autoplay=!!(!e||e.autoplay),r){if(!(r instanceof HTMLMediaElement))throw new ie(H.ERROR_HTMLELEMENT_ERROR,"Param is not a HTMLMediaElement","",{element:r});this.recvCanPlay=!1,this.emit("mediaElementBinded"),this.element=r,this.element.addEventListener("canplay",this.onCanPlay);let t=this.mediaStream;this.element.addEventListener("playing",function i(){r.removeEventListener("playing",i),G.SystemUtil.isIos&&parseInt(G.SystemUtil.systemVersion)<=13&&!r.muted&&(t!=null&&t.getAudioTracks().length)&&(r.pause(),r.play())}),this.element.nodeName==="VIDEO"&&(this.element.setAttribute("playsinline",""),G.BrowserUtil.isMicroMessenger&&(this.element.setAttribute("x5-video-player-type","h5-page"),this.element.setAttribute("x5-playsinline",""),G.SystemUtil.isAndroid||G.SystemUtil.isIos&&this.element.setAttribute("x-webkit-airplay","allow"))),this.autoplay&&G.BrowserUtil.isSafari&&this.element.setAttribute("autoplay",""),this.mediastream&&this.bindMediaStream(this.mediastream)}else this.release()}disableVideo(){const r=this.getMediaStream();r&&r.getVideoTracks().forEach(e=>{e.enabled&&(e.enabled=!1)})}enableVideo(){const r=this.getMediaStream();r&&r.getVideoTracks().forEach(e=>{e.enabled||(e.enabled=!0)})}disableAudio(){const r=this.getMediaStream();r&&r.getAudioTracks().forEach(e=>{e.enabled&&(e.enabled=!1)})}enableAudio(){const r=this.getMediaStream();r&&r.getAudioTracks().forEach(e=>{e.enabled||(e.enabled=!0)})}stop(){super.stop(),this.release()}onCanPlay(){if(!this.recvCanPlay&&(this.emit("onCanPlay"),this.recvCanPlay=!0,this.autoplay))if(this.element)if(G.BrowserUtil.isMicroMessenger){const r=window.top!==window.self,e=window.WeixinJSBridge||window.top.WeixinJSBridge;e?e.invoke("getNetworkType",{},()=>{this.tryToPlay()}):(r?window.top.document:document).addEventListener("WeixinJSBridgeReady",()=>{e.invoke("getNetworkType",{},()=>{this.tryToPlay()})})}else this.tryToPlay();else this.tryToPlay()}release(){this.element&&(this.element.pause(),this.element.srcObject=null,this.element.load(),this.element.removeEventListener("canplay",this.onCanPlay)),this.recvCanPlay=!1,this.mediastream=void 0}bindMediaStream(r){this.element&&(this.element.nodeName==="AUDIO"&&r.getVideoTracks()[0]&&r.removeTrack(r.getVideoTracks()[0]),this.element.srcObject=r),this.mediastream=r}tryToPlay(){if(this.element){let r=this.element.play();r!==void 0&&r.then(()=>{}).catch(e=>{console.log("playPromise err",e),this.element&&this.element.srcObject&&this.emit("onAutoPlayError")})}}}class cp extends Lt{constructor(r,e){super(),this.monitorStatsHistory=[],this.playTimeIndex=0,this.playCatonIndex=0,this.reportPubFlag=!1,this.state=0,this.subscribeAudio=!0,this.subscribeVideo=!0,this.signalingUrl="",this.pullStreamUrl="",this.noParsePullStreamUrl="",this.subReconnectTimes=0,this.isConnecting=!1,this.reconnectTimerHandle=null,this.reporter=r,this.playTimer=0,this.config=e||{playTimeOut:5e3},this.remoteStream=new Id,this.remoteStream.on("onAutoPlayError",()=>{this.emit("onError",new ie(H.ERROR_AUTOPLAY_ERROR,"auto play failed",""))}),this.remoteStream.on("onCanPlay",()=>_(this,null,function*(){var l,d,h,u;const t=new Date().getTime();yield this.peerconnection.sample();let i=-1,n=[],a=-1;if(this.monitorStatsHistory&&this.monitorStatsHistory.length){const p=this.monitorStatsHistory[this.monitorStatsHistory.length-1];this.monitorStatsHistory.forEach(f=>{const{rtt:m}=f;m&&m>0&&n.push(m)}),i=Number((n.reduce((f,m)=>f+m,0)/n.length).toFixed(3)),a=p.packetsLost,this.monitorStatsHistory=null}this.stopPlayTimer(),this.peerconnection.playStart(),this.subReconnectTimes=0;const c=this._cnend||t;this.reporter.reportFirstFrameTime(this.noParsePullStreamUrl,this.remoteStream.traceId,this._cpend-this._cpstart,this._hrend-this._cpend,t-this._cpstart,0,c-this._hrend,{rttAvg:i,packetsLost:a},-1,-1,-1,(l=this.subscribeConfig)==null?void 0:l.vMsid,(d=this.subscribeConfig)==null?void 0:d.aMsid);let o=new kr(Ad);o.data={url:this.noParsePullStreamUrl,vMsid:(h=this.subscribeConfig)==null?void 0:h.vMsid,aMsid:(u=this.subscribeConfig)==null?void 0:u.aMsid},this.emit("onPlayEvent",o)})),this.peerconnection=new Zi,this.peerconnection.on("onConnected",()=>{this._cnend=new Date().getTime()}),this.peerconnection.on("streamEnded",t=>{let i=new kr(ap);i.data=D({},t),this.emit("onPlayEvent",i),this.emit("onError",new ie(H.ERROR_STREAM_ENDED,"Stream Receiver Transport is Closed",this.remoteStream.traceId))}),this.peerconnection.on("onTrackEvent",t=>{t.streams&&t.streams.length&&(this.remoteStream.updateMediaStream(t.streams[0]),this.onTrackFunction&&this.onTrackFunction())}),this.peerconnection.on("connectStatusChange",t=>{t.status!==ct.CONNECT_STATUS_DISCONNECTED&&t.status!==ct.CONNECT_STATUS_RECONNECTING||!this.hasRetries()?this.emit("connectStatusChange",t):this.emit("onError",new ie(H.ERROR_PC_DISCONNECTED,"PC disconnected",this.remoteStream.traceId))}),this.peerconnection.on("pcReconnect",t=>{let i,n;t.ips?(i=`Migrate with ips: ${he(t.ips)}`,n=H.ERROR_IP_MIGRATE):(i="PC disconnected",n=H.ERROR_PC_DISCONNECTED),this.emit("onError",new ie(n,i,"",{pcErrorInfo:t}))}),this.mediaObserver=new ep({handler:(t,i,n)=>{var l;let a=new kr(op),c={url:t};i&&(c.vMsid=i),n&&(c.aMsid=n),a.data=c,this.emit("onPlayEvent",a);let o=new ie(H.ERROR_INBOUND_TIMEOUT,`Media data timeout after ${(l=this.mediaObserver)==null?void 0:l.actTimeout} ms.`,this.remoteStream.traceId);this.emit("onError",o)}}),this.peerconnection.on("onMonitorEvent",t=>{var c;let i,n=t.eventList;if((c=this.peerconnection)==null||c.updateStatsForSEI(n,t.type),t.type==="pub")return void(this.reportPubFlag&&(this.reportPubFlag=!1));if(!n.length)return;for(let o=0;o<n.length;o++)if(n[o].url===Yh(this.noParsePullStreamUrl,!0)){i=n[o];break}if(i){this.lastMeidaEventData=i;const o=i.video,l=i.audio;o&&this.monitorStatsHistory?this.monitorStatsHistory.push({rtt:o.transportStats.rtt,packetsLost:o.inboundRtpStats.packetsLost}):l&&this.monitorStatsHistory&&this.monitorStatsHistory.push({rtt:l.transportStats.rtt,packetsLost:l.inboundRtpStats.packetsLost}),this.state===1?i.video?i.video.inboundRtpStatsPerSec.framesDecodedPerSecond>1&&(this.state=2):i.audio&&i.audio.inboundRtpStatsPerSec.bytesReceivedPerSecond>0&&(this.state=2):this.state!==2&&this.state!==3||(++this.playTimeIndex,i.video&&(i.video.inboundRtpStatsPerSec.framesDecodedPerSecond<=1?(++this.playCatonIndex,this.state!==3&&(this.state=3,this.emit("onPlayEvent",new kr(ip)))):this.state===3&&(this.state=2,this.emit("onPlayEvent",new kr(sp)))),rs.HEARTHEAT_INTERVAL===this.playTimeIndex&&(this.reportPubFlag=!0,n.forEach(d=>{this.doReportPullStats(d)}),this.playTimeIndex=0,this.playCatonIndex=0))}let a=new kr(np);a.data=[],n.forEach(o=>{let l={};l.url=o.url;const d=this.calcStreamPullStats(o);if(o.audio&&(l.audio={bytesReceivedPerSecond:o.audio.inboundRtpStatsPerSec.bytesReceivedPerSecond,rtt:o.audio.transportStats.rtt,lossRate:d.aloss,jitterBufferDelayAvg:o.audio.inboundRtpStatsPerSec.jitterBufferDelayAvg},l.aMsid=o.aMsid),o.video){const{inboundRtpStats:h,inboundRtpStatsPerSec:u,transportStats:p}=o.video;l.video={bytesReceivedPerSecond:u.bytesReceivedPerSecond,fps:h.framesPerSecond||u.framesDecodedPerSecond,framesDecodedPerSecond:u.framesDecodedPerSecond,rtt:p.rtt,width:h.frameWidth,height:h.frameHeight,lossRate:d.vloss,jitterBufferDelayAvg:u.jitterBufferDelayAvg},l.vMsid=o.vMsid}l.networkQuality=d.net_qual||0,a.data.push(l)}),a.data&&a.data.length&&(a.data.forEach(o=>{var l;(l=this.mediaObserver)==null||l.check({audio:o.audio,video:o.video},o.url,o.vMsid,o.aMsid)}),a.data.length===1&&(a.data[0].audio||a.data[0].video)&&(a.data=D({},a.data[0])),this.emit("onPlayEvent",a))}),this.playTimer=0,this._cpstart=0,this._cpend=0,this._hrend=0,this._cnend=0,this.subscribeConfig={}}getPeerConnection(){return this.peerconnection}subscribe(r,e,t){return new Promise((i,n)=>_(this,null,function*(){var c;this.monitorStatsHistory=[],this.unsubscribe(),e!=null&&e.cumuDelay&&(e.encodedInsertableStreams=!0),this.subscribeConfig=e||{},this.state=1,this.noParsePullStreamUrl=r,this.parseUrl(r),(c=this.mediaObserver)==null||c.updateConfig({timeout:e==null?void 0:e.mediaTimeout});const a=e==null?void 0:e.signalUrl;if(this.signalingUrl=a||this.signalingUrl,this.checkPullUrl())if(this.subscribeAudio||this.subscribeVideo){if(this._cpstart=new Date().getTime(),this.subscribeVideo&&!(e!=null&&e.isH264Checked))try{yield new Dr().loadH264(3)}catch(o){}this.peerconnection.createOffer(this.subscribeAudio,this.subscribeVideo,void 0,{offerSdpHook:e==null?void 0:e.offerSdpHook,answerSdpHook:e==null?void 0:e.answerSdpHook,encodedInsertableStreams:e==null?void 0:e.encodedInsertableStreams,disableStereo:e==null?void 0:e.disableStereo,disableHeartbeat:e==null?void 0:e.disableHeartbeat,cumuDelay:e==null?void 0:e.cumuDelay,heartbeat:e==null?void 0:e.heartbeat}).then(({desp:o})=>{this._cpend=new Date().getTime(),this.reporter.reportSubscribeStart(this.noParsePullStreamUrl,this.signalingUrl,e==null?void 0:e.vMsid,e==null?void 0:e.aMsid),this.excuteSignal(o,{innerTcpOnly:!!(t!=null&&t.innerTcpOnly)}).then(l=>{var d;this.remoteStream.traceId=l,i(this.remoteStream);try{(d=this.peerconnection.getPeerCore())==null||d.patchSubscribeStreamManagerRecord(this.noParsePullStreamUrl,Q(D({},this.subscribeConfig),{stream:this.remoteStream}))}catch(h){console.log(h)}this.peerconnection.getSubMonitor().updateTranceiversController()}).catch(l=>{this._hrend=new Date().getTime();const d=new ie(l.errorCode?l.errorCode:H.ERROR_HTTPREQUEST_ERROR,l.message,l?l.traceid:"",{response:l.response,sdp:l.sdp});n(d)})}).catch(o=>{this._cpend=new Date().getTime();const l=new ie(H.ERROR_CREATEOFFER,o.message,"");n(l)})}else n(new ie(H.ERROR_SUBSCRIBE_NOTHING,"subscribe nothing",""));else n(new ie(H.ERROR_PLAY_URL,"url need artc://",""))}))}unsubscribe(){var r;this.lastMeidaEventData&&this.doReportPullStats(this.lastMeidaEventData),this.stopPlayTimer(),this.peerconnection.reset(),this.remoteStream.stop(),this.subscribeVideo=!0,this.subscribeAudio=!0,this.state=0,this.signalingUrl="",this.pullStreamUrl="",this.noParsePullStreamUrl="",this.onTrackFunction=void 0,this.playTimer=0,this._cpstart=0,this._cpend=0,this._hrend=0,this._cnend=0,this.monitorStatsHistory=[],(r=this.mediaObserver)==null||r.reset()}dispose(){this.removeAllListeners(),this.unsubscribe()}startLiveStream(r,e,t){return console.error("此API可能存在稳定性问题,并将在未来的版本移除。请使用subscribe替代,详细用法请参考官方文档。"),new Promise((i,n)=>{this.unsubscribe(),this.state=1,this.noParsePullStreamUrl=r,this.parseUrl(r);const a=t==null?void 0:t.signalUrl;this.signalingUrl=a||this.signalingUrl,this.pullStreamUrl===""?n(new ie(H.ERROR_PLAY_URL,"url need artc://","")):this.subscribeAudio||this.subscribeVideo?!e||e.nodeName!=="AUDIO"&&e.nodeName!=="VIDEO"?n(new ie(H.ERROR_HTMLELEMENT_ERROR,"need htmlaudioelement or htmlvideoelement","")):(this.subscribeAudio&&this.subscribeVideo?e.nodeName!=="VIDEO"&&this.emit("onError",new ie(H.ERROR_HEMLELEMENT_NOTMATCH,"need htmlvideoelement","")):this.subscribeAudio?e.nodeName!=="AUDIO"&&this.emit("onError",new ie(H.ERROR_HEMLELEMENT_NOTMATCH,"need htmlaudioelement","")):e.nodeName!=="VIDEO"&&this.emit("onError",new ie(H.ERROR_HEMLELEMENT_NOTMATCH,"need htmlvieoelement","")),this._cpstart=new Date().getTime(),this.reporter.updateTid(),this.peerconnection.createOffer(this.subscribeAudio,this.subscribeVideo).then(({desp:c})=>{this._cpend=new Date().getTime(),this.excuteSignal(c).then(o=>{this.remoteStream.traceId=o,this._hrend=new Date().getTime(),this.remoteStream.play(e),i(o)}).catch(o=>{this._hrend=new Date().getTime(),this.reporter.reportFirstFrameTime(this.noParsePullStreamUrl,o?o.traceid:"",this._cpend-this._cpstart,this._hrend-this._cpend,-1,-1,this._cnend-this._hrend),n(new ie(o.errorCode?o.errorCode:H.ERROR_HTTPREQUEST_ERROR,o.message,""))})}).catch(c=>{this._cpend=new Date().getTime(),this.reporter.reportFirstFrameTime(this.noParsePullStreamUrl,c?c.traceid:"",this._cpend-this._cpstart,-1,-1,-1,this._cnend-this._hrend),n(new ie(H.ERROR_CREATEOFFER,c.message,""))})):n(new ie(H.ERROR_SUBSCRIBE_NOTHING,"subscribe nothing",""))})}stopLiveStream(){this.unsubscribe()}muteLiveStream(r){return this.remoteStream.muted=r,!0}excuteSignal(r,e){let t={type:r.type,sdp:r.sdp};return new Promise((i,n)=>{var c,o,l,d,h;let a={url:this.pullStreamUrl,amsid:((c=this.subscribeConfig)==null?void 0:c.aMsid)||["rts audio"],vmsid:((o=this.subscribeConfig)==null?void 0:o.vMsid)||["rts video"]};this.subscribeAudio||delete a.amsid,this.subscribeVideo||delete a.vmsid,(l=this.subscribeConfig)!=null&&l.cumuDelay&&(t.sdp=t.sdp.replace(/(m=video[^\n]*\n)/,`$1a=cumudelay
179
+ `)),sn.post(this.signalingUrl,{version:((d=this.subscribeConfig)==null?void 0:d.signalVersion)||nn,sdk_version:an,mode:((h=this.subscribeConfig)==null?void 0:h.signalMode)||"live",pull_streams:[a],jsep:t}).then(u=>{var p,f,m,g,S,v,E,T,R;if(u&&u.status===200){this._hrend=new Date().getTime();try{(p=this.subscribeConfig)!=null&&p.cumuDelay&&!((m=(f=u.data)==null?void 0:f.jsep)!=null&&m.sdp.includes("a=cumudelay"))&&(console.warn("Not found cumudelay in server sdp"),(g=this.reporter)==null||g.reportCumuDelayAnswerNotFound())}catch(w){}const y=(S=u.data)==null?void 0:S.trace_id;this.reporter.reportSubscribeOk({vurl:this.noParsePullStreamUrl,surl:this.signalingUrl,traceId:y,hrct:this._hrend-this._cpend,rslt:(v=u.data)==null?void 0:v.code});const C=typeof((E=this.subscribeConfig)==null?void 0:E.tcpOnly)=="boolean"?this.subscribeConfig.tcpOnly:e==null?void 0:e.innerTcpOnly;this.peerconnection.recvAnswer(u.data,{answerSdpHook:(T=this.subscribeConfig)==null?void 0:T.answerSdpHook,tcpOnly:C}).then(()=>{i(y)}).catch(w=>{w.traceid=u.data?u.data.trace_id:"",n({errorCode:H.ERROR_ANSWER_ERROR,message:w.message?w.message:"set answer error",traceid:w.traceid,sdp:w.sdp})})}else n({message:u?"response status:"+u.status:"response is null",traceid:(R=u==null?void 0:u.data)==null?void 0:R.trace_id,sdp:r.sdp})}).catch(u=>_(this,null,function*(){var p;if([400,500].includes((p=u.response)==null?void 0:p.status)){u.sdp=r.sdp;try{yield new Dr().isSupport({isReceiveVideo:!0})}catch(f){u.errorCode=f==null?void 0:f.errorCode,u.message=f==null?void 0:f.message,this.subReconnectTimes=1/0}}n(u)}))})}checkPullUrl(){return!!this.noParsePullStreamUrl&&this.noParsePullStreamUrl.indexOf("artc://")===0}parseUrl(r=""){if((r==null?void 0:r.indexOf("artc://"))===0){r.indexOf("@subaudio=no")>-1&&(this.subscribeAudio=!1,r=r.replace("@subaudio=no","")),r.indexOf("@subvideo=no")>-1&&(this.subscribeVideo=!1,r=r.replace("@subvideo=no","")),this.pullStreamUrl=r;const{protocol:e}=window.location;let t=(["http:","https:"].indexOf(e)>-1?e:"https:")+"//";this.signalingUrl=this.pullStreamUrl.replace("artc://",t)}}stopPlayTimer(){this.playTimer&&clearTimeout(this.playTimer),this.playTimer=0}calcStreamPullStats(r){let e={};const{video:t,audio:i}=r;if(t){const{transportStats:n,inboundRtpStats:a,inboundRtpStatsPerSec:c,localCandidate:o,remoteCandidate:l}=t;e=Q(D({},e),{rtt:(n==null?void 0:n.rtt)!==-1?1e3*((n==null?void 0:n.rtt)||0):-1,cand_re_prot:l.protocol,cand_lo_prot:o.protocol,cand_re_addr:`${l.ip||l.address}:${l.port}`,cand_lo_addr:`${o.ip||o.address}:${o.port}`,w:a==null?void 0:a.frameWidth,h:a==null?void 0:a.frameHeight,vbps:Math.floor(8*c.bytesReceivedPerSecond),fps:a==null?void 0:a.framesPerSecond,dfps:Math.floor(c==null?void 0:c.framesDecodedPerSecond),vjb:Math.floor(gi(a==null?void 0:a.jitterBufferDelay,a==null?void 0:a.jitterBufferEmittedCount)),vMsid:r.vMsid,vloss:c.packetsLostRate})}if(i){const{transportStats:n,inboundRtpStats:a,inboundRtpStatsPerSec:c,localCandidate:o,remoteCandidate:l}=i;e=Q(D({},e),{rtt:(n==null?void 0:n.rtt)!==-1?1e3*((n==null?void 0:n.rtt)||0):-1,cand_re_prot:l.protocol,cand_lo_prot:o.protocol,cand_re_addr:`${l.ip||l.address}:${l.port}`,cand_lo_addr:`${o.ip||o.address}:${o.port}`,abps:Math.floor(8*c.bytesReceivedPerSecond),ajb:Math.floor(gi(a==null?void 0:a.jitterBufferDelay,a.jitterBufferEmittedCount)),aMsid:r.aMsid,aloss:c.packetsLostRate})}return e=Q(D({},e),{net_qual:Qh(e.rtt,e.aloss,e.vloss,e.ajb,e.vjb)}),e}doReportPullStats(r){let e=this.calcStreamPullStats(r),t={ct:1e3*this.playCatonIndex,tt:1e3*this.playTimeIndex,url:r.url};t.tt&&(t=D(D({},t),e),this.reporter.reportPullStats(t),this.lastMeidaEventData=void 0)}retrySubscribe(r,e){return _(this,null,function*(){if(r.extraInfo=Q(D({},r.extraInfo),{retryTimes:this.subReconnectTimes}),!this.hasRetries())return!1;const t=this.subscribeConfig;if(typeof(t==null?void 0:t.beforeRetry)=="function")try{const i=yield t.beforeRetry({url:this.noParsePullStreamUrl,vMsid:t.vMsid,aMsid:t.aMsid,useTcp:e==null?void 0:e.innerTcpOnly});if(i){const{url:n,vMsid:a,aMsid:c,useTcp:o}=i;this.reporter.reportReconnectParams("sub",n,a,c,o),this.noParsePullStreamUrl=n,this.subscribeConfig.vMsid=a,this.subscribeConfig.aMsid=c,typeof o=="boolean"&&(e=Q(D({},e),{innerTcpOnly:o})),console.log(`retry with:
180
+ [URL] ${n}
181
+ [VMSID]${a} [AMSID]${c}
182
+ [PROTOCOL] ${o?"TCP":"UDP"}`)}else this.reporter.reportReconnectParams("sub"),this.subReconnectTimes=1/0}catch(i){console.error("Error in beforeRetry",i)}return this.hasRetries()?(this.emit("connectStatusChange",{status:ct.CONNECT_STATUS_RECONNECTING}),this.incrementReconnectTimes(),r.extraInfo.retryTimes=this.subReconnectTimes,r.extraInfo.tcpOnly=e==null?void 0:e.innerTcpOnly,this.subscribeWithReconnect(this.noParsePullStreamUrl,D({innerTcpOnly:e==null?void 0:e.innerTcpOnly},this.subscribeConfig)).catch(i=>{}),!0):(r.extraInfo.retryTimes=this.subReconnectTimes,!1)})}subscribeWithReconnect(r,e,t,i){return new Promise((n,a)=>{n=t||n,a=i||a,this.isConnecting=!0;const{innerTcpOnly:c}=e||{};e==null||delete e.innerTcpOnly,this.subscribe(r,e,{innerTcpOnly:c}).then(o=>{this.isConnecting=!1,n(o)}).catch(o=>{var l;if(this.peerconnection.reset(),!this.isConnecting)return a(o);if(!cc.includes(o.errorCode)&&this.hasRetries(!0)){let d=((l=this.subscribeConfig)==null?void 0:l.retryInterval)||2e3;this.reconnectTimerHandle=setTimeout(()=>{o.extraInfo=Q(D({},o.extraInfo),{retryTimes:this.subReconnectTimes}),this.emit("reconnect",o),this.subscribeWithReconnect(r,e,n,a)},d)}else a(o),o.extraInfo=Q(D({},o.extraInfo),{retryTimes:this.subReconnectTimes}),this.isConnecting=!1,this.emit("onError",o)})})}hasRetries(r){var i,n;let e=5;typeof((i=this.subscribeConfig)==null?void 0:i.retryTimes)=="number"&&(e=Math.floor((n=this.subscribeConfig)==null?void 0:n.retryTimes));let t=this.subReconnectTimes<e;return r&&t&&this.incrementReconnectTimes(),t}resetResubscribeStatus(){this.subReconnectTimes=0,this.isConnecting=!1,this.reporter.updateTid(),this.reconnectTimerHandle!==null&&(clearTimeout(this.reconnectTimerHandle),this.reconnectTimerHandle=null)}handlePubMonitorEvent(r){r.forEach(e=>{this.reporter.reportPushStats(e)})}incrementReconnectTimes(){this.subReconnectTimes++}getSubscribeConfig(){return this.subscribeConfig}}class dp extends Lt{constructor(r){super(),this.publishStartTimeStamp=0,this.pubReconnectTimes=0,this.isConnecting=!1,this.reconnectTimerHandle=null,this.reportMonitorTimes=0,this.reportSubFlag=!1,this.reporter=r,this.peerconnection=new Zi,this.peerconnection.on("connectStatusChange",e=>{e.status!==ct.CONNECT_STATUS_DISCONNECTED&&e.status!==ct.CONNECT_STATUS_RECONNECTING||!this.hasRetries()?this.emit("connectStatusChange",e):this.emit("onError",new ie(H.ERROR_PC_DISCONNECTED,"PC disconnected",""))}),this.peerconnection.on("onMonitorEvent",e=>{var i;let t=e.eventList;(i=this.peerconnection)==null||i.updateStatsForSEI(t,e.type),e.type==="pub"?(this.reportMonitorTimes++,this.reportMonitorTimes%4==0&&(t.forEach(n=>{this.reporter.reportPushStats(n)}),this.reportSubFlag=!0,this.reportMonitorTimes=0)):e.type==="sub"&&this.reportSubFlag&&(this.handleSubMonitorEvent(t),this.reportSubFlag=!1)}),this.peerconnection.on("onTransportStateEvent",e=>{var t;this.peerconnection.isReused||((t=this.peerconnection.getPc())==null?void 0:t.connectionState)!=="closed"&&e.state==="closed"&&this.hasRetries()&&this.emit("onError",new ie(H.ERROR_TRANSPORT_CLOSED,`Transport has been closed. ${e.kind}|${e.type}|${e.url}`,"",{protocol:e.protocol}))}),this.peerconnection.on("pcReconnect",e=>{let t,i;e.ips?(t=`Migrate with ips: ${he(e.ips)}`,i=H.ERROR_IP_MIGRATE):(t="PC disconnected",i=H.ERROR_PC_DISCONNECTED),this.emit("onError",new ie(i,t,"",{pcErrorInfo:e}))}),this.signalingUrl="",this.publishUrl="",this.publishConfig={}}publish(r,e,t){return new Promise((i,n)=>{if(this.unpublish(),t!=null&&t.cumuDelay&&(t.encodedInsertableStreams=!0),this.localStream=e,this.publishUrl=r,this.publishConfig=t||{},this.checkPublishUrl())if(e)if(e.audioTrack===null)n(new ie(H.ERROR_PUBLISH_NOAUDIO,"publish need audiotrack",""));else{const a=t==null?void 0:t.signalUrl;this.signalingUrl=a||this.signalingUrl,this.publishStartTimeStamp=new Date().getTime(),e.setReporter(this.reporter),this.peerconnection.createOffer(e.hasAudio,e.hasVideo||e.hasScreen,e,Q(D({},t),{publishUrl:r})).then(({desp:c,publishTrackInfoList:o})=>{this.publishTrackInfoList=o;let l=new Date().getTime();this.reporter.reportStartPublish(this.publishUrl,this.signalingUrl),this.excuteSignal(c).then(d=>{let h=new Date().getTime();this.peerconnection.recvAnswer(d.data,{answerSdpHook:t==null?void 0:t.answerSdpHook,tcpOnly:t==null?void 0:t.tcpOnly}).then(()=>{this.reporter.reportPublishOk(this.publishUrl,this.signalingUrl,l-this.publishStartTimeStamp,h-l,new Date().getTime()-h,d.data.trace_id),i(d.data.trace_id),this.pubReconnectTimes=0,this.peerconnection.pushStart()}).catch(u=>{u.traceid=d.data?d.data.trace_id:"";const p=new ie(u.errorCode||H.ERROR_ANSWER_ERROR,u.message||"set answer error",u.traceid,{sdp:u.sdp});n(p)})}).catch(d=>{const h=new ie(d.errorCode||H.ERROR_HTTPREQUEST_ERROR,d.message||"","",{response:d.response,sdp:d.sdp});n(h)})}).catch(c=>{const o=new ie(c.errorCode||H.ERROR_CREATEOFFER,c.message||"","");n(o)})}else n(new ie(H.ERROR_PUBLISH_NOSTREAM,"publish stream not found",""));else n(new ie(H.ERROR_PUBLISH_URL,"url need artc://",""))})}unpublish(){this.peerconnection.reset(),this.reporter.reportStopPublish(),this.signalingUrl="",this.publishUrl="",this.publishTrackInfoList=null}dispose(){this.removeAllListeners(),this.unpublish()}getTrackInfoList(){return this.publishTrackInfoList||[]}getPeerConnection(){return this.peerconnection}replaceTrack(r,e){return this.peerconnection.replaceTrack(this.publishUrl,r,e)}excuteSignal(r){var t;let e={type:r.type,sdp:r.sdp};return this.isSingleMsid()&&(e.sdp=e.sdp.replace(/msid\:-? /g,"msid:")),(t=this.publishConfig)!=null&&t.cumuDelay&&(e.sdp=e.sdp.replace(/(m=video[^\n]*\n)/,`$1a=cumudelay
183
+ `)),new Promise((i,n)=>{sn.post(this.signalingUrl,{version:nn,sdk_version:an,mode:"rtc",push_stream:this.publishUrl,jsep:e}).then(a=>{var c,o,l,d;if(a&&a.status===200){i(a);try{(c=this.publishConfig)!=null&&c.cumuDelay&&!((l=(o=a.data)==null?void 0:o.jsep)!=null&&l.sdp.includes("a=cumudelay"))&&(console.warn("Not found cumudelay in server sdp"),(d=this.reporter)==null||d.reportCumuDelayAnswerNotFound())}catch(h){}}else n({message:a?"response status:"+a.status:"response is null",sdp:e.sdp})}).catch(a=>_(this,null,function*(){var c;if([400,500].includes((c=a.response)==null?void 0:c.status)){a.sdp=r.sdp;try{yield new Dr().isSupport({isReceiveVideo:!0})}catch(o){a.errorCode=o==null?void 0:o.errorCode,a.message=o==null?void 0:o.message,this.pubReconnectTimes=1/0}}n(a)}))})}checkPublishUrl(){if(!this.publishUrl||this.publishUrl.indexOf("artc://")!==0)return!1;const{protocol:r}=window.location;let e=(["http:","https:"].indexOf(r)>-1?r:"https:")+"//";return this.signalingUrl=this.publishUrl.replace("artc://",e),!0}isSingleMsid(){if(!this.publishConfig)return!1;const{vMsid:r,aMsid:e}=this.publishConfig;return!(!r||!r[0]||r[0].indexOf(" ")!==-1)||!(!e||!e[0]||e[0].indexOf(" ")!==-1)}retryPublish(r,e){return _(this,null,function*(){if(r.extraInfo=Q(D({},r.extraInfo),{retryTimes:this.pubReconnectTimes}),!this.hasRetries())return!1;const t=this.publishConfig;if(typeof t.beforeRetry=="function")try{const i=yield t.beforeRetry({url:this.publishUrl,stream:this.localStream,vMsid:t.vMsid,aMsid:t.aMsid,useTcp:e});if(i){const{url:n,stream:a,vMsid:c,aMsid:o}=i;a||(console.error("Stream is not returned by beforeRetry function."),this.pubReconnectTimes=1/0),this.reporter.reportReconnectParams("pub",n,c,o,i.useTcp,a==null?void 0:a.id),this.publishUrl=n,this.localStream=a,this.publishConfig.vMsid=c,this.publishConfig.aMsid=o,typeof i.useTcp=="boolean"&&(e=i.useTcp),console.log(`Retry with:
184
+ [URL] ${n}
185
+ [STREAM] ${a==null?void 0:a.id}
186
+ [VMSID]${c} [AMSID]${o}
187
+ [PROTOCOL] ${e?"TCP":"UDP"}`)}else this.reporter.reportReconnectParams("pub"),this.pubReconnectTimes=1/0}catch(i){console.error("Error in beforeRetry",i)}return this.hasRetries()&&this.localStream?(this.emit("connectStatusChange",{status:ct.CONNECT_STATUS_RECONNECTING}),this.incrementReconnectTimes(),r.extraInfo.retryTimes=this.pubReconnectTimes,r.extraInfo.tcpOnly=!!e,this.publishWithReconnect(this.publishUrl,this.localStream,Q(D({},this.publishConfig),{tcpOnly:!!e})).catch(i=>{}),!0):(r.extraInfo.retryTimes=this.pubReconnectTimes,!1)})}publishWithReconnect(r,e,t,i,n){return new Promise((a,c)=>{a=i||a,c=n||c,this.isConnecting=!0,this.publish(r,e,t).then(o=>{this.isConnecting=!1,a(o)}).catch(o=>{var l;if(this.peerconnection.reset(),!this.isConnecting)return c(o);if(!cc.includes(o.errorCode)&&this.hasRetries(!0)){let d=((l=this.publishConfig)==null?void 0:l.retryInterval)||2e3;this.reconnectTimerHandle=setTimeout(()=>{o.extraInfo=Q(D({},o.extraInfo),{retryTimes:this.pubReconnectTimes}),this.emit("reconnect",o),this.publishWithReconnect(r,e,t,a,c)},d)}else c(o),o.extraInfo=Q(D({},o.extraInfo),{retryTimes:this.pubReconnectTimes}),this.isConnecting=!1,this.emit("onError",o)})})}sendSEI(r){var e;(e=this.peerconnection)==null||e.sendSEI(r)}hasRetries(r){var i,n;let e=5;typeof((i=this.publishConfig)==null?void 0:i.retryTimes)=="number"&&(e=Math.floor((n=this.publishConfig)==null?void 0:n.retryTimes));let t=this.pubReconnectTimes<e;return r&&t&&this.incrementReconnectTimes(),t}resetRepublishStatus(){this.pubReconnectTimes=0,this.isConnecting=!1,this.reporter.updateTid(),this.reconnectTimerHandle!==null&&(clearTimeout(this.reconnectTimerHandle),this.reconnectTimerHandle=null)}handleSubMonitorEvent(r){r.forEach(e=>{let t={ct:0,tt:4e3,url:e.url};const{video:i,audio:n}=e;if(i){const{transportStats:a,inboundRtpStats:c,inboundRtpStatsPerSec:o,localCandidate:l,remoteCandidate:d}=i;t=Q(D({},t),{rtt:(a==null?void 0:a.rtt)!==-1?1e3*((a==null?void 0:a.rtt)||0):-1,cand_re_prot:d.protocol,cand_lo_prot:l.protocol,cand_re_addr:`${d.ip||d.address}:${d.port}`,cand_lo_addr:`${l.ip||l.address}:${l.port}`,w:c==null?void 0:c.frameWidth,h:c==null?void 0:c.frameHeight,vbps:Math.floor(8*o.bytesReceivedPerSecond),fps:c==null?void 0:c.framesPerSecond,dfps:Math.floor(o==null?void 0:o.framesDecodedPerSecond),vjb:Math.floor(gi(c==null?void 0:c.jitterBufferDelay,c==null?void 0:c.jitterBufferEmittedCount)),vMsid:e.vMsid})}if(n){const{transportStats:a,inboundRtpStats:c,inboundRtpStatsPerSec:o,localCandidate:l,remoteCandidate:d}=n;t=Q(D({},t),{rtt:(a==null?void 0:a.rtt)!==-1?1e3*((a==null?void 0:a.rtt)||0):-1,cand_re_prot:d.protocol,cand_lo_prot:l.protocol,cand_re_addr:`${d.ip||d.address}:${d.port}`,cand_lo_addr:`${l.ip||l.address}:${l.port}`,abps:Math.floor(8*o.bytesReceivedPerSecond),ajb:Math.floor(gi(c==null?void 0:c.jitterBufferDelay,c.jitterBufferEmittedCount)),aMsid:e.aMsid})}this.reporter.reportPullStats(t)})}incrementReconnectTimes(){this.pubReconnectTimes++}getPublishConfig(){return this.publishConfig}}class lp extends Lt{constructor(r){super(),this.reporter=r,this.peerConnection=new Zi,this.sdpUtil=new Ji,this.peerConnection.on("connectStatusChange",e=>{this.emit("connectStatusChange",e)}),this.peerConnection.on("preSub",e=>{this.emit("preSub",e)}),this.peerConnection.on("prePub",e=>{this.emit("prePub",e)}),this.peerConnection.on("reconnectRoomServer",()=>{this.emit("reconnectRoomServer")})}getPeerConnection(){return this.peerConnection}get peerCore(){return this.peerConnection.getPeerCore()}connect(r){return _(this,null,function*(){const{remoteIp:e,answerFingerprint:t,serverInfo:i,offerSdpHook:n,answerSdpHook:a}=r,c=yield this.peerConnection.createOffer(!1,!1,void 0,{offerSdpHook:n,answerSdpHook:a}),o=this.sdpUtil.getFingerprint(c.desp.sdp),[l,d,h,u,p]=atob(i).split("_"),f=btoa(`${l}_${d}_${h}_${u}_${o}_${p}`),m=`v=0
188
+ o=- ${Math.floor(Date.now()/1e3)} 2 IN IP4 127.0.0.1
189
+ s=-
190
+ t=0 0
191
+ a=group:BUNDLE 0
192
+ m=application 9 UDP/DTLS/SCTP webrtc-datachannel
193
+ c=IN IP4 0.0.0.0
194
+ a=ice-ufrag:${f}
195
+ a=ice-pwd:${u}
196
+ a=ice-options:ice-lite
197
+ a=fingerprint:SHA-256 ${t}
198
+ a=setup:passive
199
+ a=sendrecv
200
+ a=mid:0
201
+ a=sctp-port:5000
202
+ a=candidate:3 1 UDP 511464353 ${e} 1106 typ host
203
+ a=candidate:4 1 TCP 511464352 ${e} 8000 typ host tcptype passive
204
+ a=end-of-candidates
205
+ `.split(`
206
+ `).join(`\r
207
+ `),g=new RTCSessionDescription({type:"answer",sdp:m});return yield this.peerConnection.recvAnswer({jsep:g},{answerSdpHook:r==null?void 0:r.answerSdpHook,tcpOnly:r==null?void 0:r.tcpOnly}),f})}disconnect(){this.peerConnection.reset()}}var $e,pe,ut,kt,Ri,cr,dr,is=(($e=is||{})[$e.VTotalCost=4]="VTotalCost",$e[$e.CapDeviceCost=5]="CapDeviceCost",$e[$e.PushExtCost=6]="PushExtCost",$e[$e.CapPlugCost=7]="CapPlugCost",$e[$e.PrepThrCost=8]="PrepThrCost",$e[$e.PrepPlugCost=9]="PrepPlugCost",$e[$e.DispThrCost=10]="DispThrCost",$e[$e.DispPlugCost=11]="DispPlugCost",$e[$e.VEncThrCost=12]="VEncThrCost",$e[$e.VEncPlugCost=13]="VEncPlugCost",$e),tr=((pe=tr||{})[pe.ATotalCost=24]="ATotalCost",pe[pe.ASourceCCost=25]="ASourceCCost",pe[pe.AMixerCost=26]="AMixerCost",pe[pe.AEncodeCCost=27]="AEncodeCCost",pe[pe.AAIClientQuestionTimestampHEAD=28]="AAIClientQuestionTimestampHEAD",pe[pe.AAIClientQuestionTimestampTAIL=29]="AAIClientQuestionTimestampTAIL",pe[pe.AAIClientAnswerTimestampHEAD=30]="AAIClientAnswerTimestampHEAD",pe[pe.AAIClientAnswerTimestampTAIL=31]="AAIClientAnswerTimestampTAIL",pe[pe.AAIClientScentenceId=32]="AAIClientScentenceId",pe[pe.AAIClientSourceCost=33]="AAIClientSourceCost",pe[pe.AAIClientMixerCost=34]="AAIClientMixerCost",pe[pe.AAIClientEncoderCost=35]="AAIClientEncoderCost",pe[pe.AAILinuxReceiveCost=36]="AAILinuxReceiveCost",pe[pe.AAILinuxNeteqCost=37]="AAILinuxNeteqCost",pe[pe.AAILinuxRemoteSourceCost=38]="AAILinuxRemoteSourceCost",pe[pe.AAILinuxPlayMixerCost=39]="AAILinuxPlayMixerCost",pe[pe.AAILinuxPlayCost=40]="AAILinuxPlayCost",pe[pe.AAIClientQuestionUidDigestHEAD=41]="AAIClientQuestionUidDigestHEAD",pe[pe.AAIClientQuestionUidDigestTAIL=42]="AAIClientQuestionUidDigestTAIL",pe[pe.AIClinetSmartDenoise=43]="AIClinetSmartDenoise",pe),Mr=((ut=Mr||{})[ut.NetsdkThrCost=44]="NetsdkThrCost",ut[ut.QosThrCost=45]="QosThrCost",ut[ut.PacerCost=46]="PacerCost",ut[ut.UpRTTHalf=47]="UpRTTHalf",ut[ut.AIClientNetsdkThrCost=48]="AIClientNetsdkThrCost",ut[ut.AIClientQosThrCost=49]="AIClientQosThrCost",ut[ut.AIClientPacerCost=50]="AIClientPacerCost",ut[ut.AIClientUpRTTHalf=51]="AIClientUpRTTHalf",ut),ss=((kt=ss||{})[kt.AIAsrCost=64]="AIAsrCost",kt[kt.AILlmCost=65]="AILlmCost",kt[kt.AITtsCost=66]="AITtsCost",kt[kt.AIMuteCost=67]="AIMuteCost",kt[kt.AIAgentTotalCost=68]="AIAgentTotalCost",kt[kt.AIAgentExtraAvatarCost=69]="AIAgentExtraAvatarCost",kt),ns=((Ri=ns||{})[Ri.PubSdkType=100]="PubSdkType",Ri[Ri.PubSdkVersion=101]="PubSdkVersion",Ri),as=((cr=as||{})[cr.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_INTERNAL_RTT_HALF=121]="NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_INTERNAL_RTT_HALF",cr[cr.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_GRTN_NODE_BEF_PACER=122]="NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_GRTN_NODE_BEF_PACER",cr[cr.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_GRTN_NODE_PACER_COST=123]="NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_GRTN_NODE_PACER_COST",cr[cr.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_DOWN_RTT_HALF=124]="NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_DOWN_RTT_HALF",cr),os=((dr=os||{})[dr.AIGRTNInternalRTTHalf=104]="AIGRTNInternalRTTHalf",dr[dr.AIGRTNBeforePacer=105]="AIGRTNBeforePacer",dr[dr.AIGRTNPacerCost=106]="AIGRTNPacerCost",dr[dr.AIGRTNDownRTTHalf=107]="AIGRTNDownRTTHalf",dr);class hp{constructor(r){this.pub={},this.grtn={},this.AIPub={},this.AISub={},this.AIAgent={},this.AIGrtn={},this.other={};const e=new up(r);e.readBits(3);const t=e.readBits(),i=e.readBits(),n=e.readBits(),a=e.readBits(),c=e.readBits();if(e.readBits(8),e.readBits(8),e.readBits(8),t===1&&e.readBits(16),i===1){const h=e.readBits(32);this.pub.timestamp=h,this.pub.timestampRecv=Math.floor(performance.now())}let o,l;n===1&&e.readBits(16),a===1&&(o=e.readBits(32)),c===1&&(l=e.readBits(32)),o&&l&&(this.grtn={TOTAL_COST:l-o,ENTER_GRTN_TIMESTAMP:o,LEAVE_GRTN_TIMESTAMP:l});const d=e.readBits(8);for(let h=0;h<d;h++){const u=e.readBits(8),p=e.readBits(16);if(rr(u,[is.VTotalCost,is.VEncPlugCost])||rr(u,[tr.ATotalCost,tr.AEncodeCCost])||rr(u,[Mr.NetsdkThrCost,Mr.UpRTTHalf])||rr(u,[ns.PubSdkType,ns.PubSdkVersion])){let f=is[u]||tr[u]||Mr[u]||ns[u];this.pub[f]=p}else if(rr(u,[tr.AAIClientQuestionTimestampHEAD,tr.AAIClientEncoderCost])||rr(u,[Mr.AIClientNetsdkThrCost,Mr.AIClientUpRTTHalf])){let f=tr[u]||Mr[u];this.AIPub[f]=p}else if(rr(u,[tr.AAILinuxReceiveCost,tr.AIClinetSmartDenoise])){let f=tr[u];this.AISub[f]=p}else if(rr(u,[ss.AIAsrCost,ss.AIAgentExtraAvatarCost])){let f=ss[u];this.AIAgent[f]=p}else if(rr(u,[os.AIGRTNInternalRTTHalf,os.AIGRTNDownRTTHalf])){let f=os[u],m=0,g=`${f}_${m}`;for(;this.AIGrtn.hasOwnProperty(g);)g=`${f}_${m++}`;this.AIGrtn[g]=p}else if(rr(u,[as.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_INTERNAL_RTT_HALF,as.NGX_RTC_SEI_CUMULATIVE_DELAY_KEY_DOWN_RTT_HALF])){let f=as[u],m=0,g=`${f}_${m}`;for(;this.grtn.hasOwnProperty(g);)g=`${f}_${m++}`;this.grtn[g]=p}else this.other[u]=p}}}function rr(s,r){return s>=r[0]&&s<=r[1]}class up{constructor(r){this.byteOffset=0,this.bitOffset=0;const e=new Uint8Array(r);this.buffer=e}readBits(r=1){let e=0,t=0;for(;t<r;){if(this.byteOffset>=this.buffer.byteLength)throw new Error("readBits out of range");const i=8-this.bitOffset,n=Math.min(i,r-t);e=e<<n|this.getBitsFromByte(this.buffer,this.byteOffset,this.bitOffset,this.bitOffset+n-1),this.bitOffset+=n,t+=n,this.bitOffset===8&&(this.byteOffset++,this.bitOffset=0)}return r===32&&(e>>>=0),e}hasNext(){return this.byteOffset<this.buffer.byteLength}getBitsFromByte(r,e,t,i){if(e<0||e>=r.byteLength||t<0||i>7||t>i)throw new Error("Invalid parameters");return r[e]>>7-i&(1<<i-t+1)-1}}const pp=s=>{const r=s.byteLength,e=[];let t=1;for(;t<r-2;)s[t]===0&&s[t+1]===0&&s[t+2]===3?(e.push(t+2),t+=2):t++;if(e.length===0)return s;const i=r-e.length,n=new Uint8Array(i);let a=0;for(t=0;t<i;a++,t++)a===e[0]&&(a++,e.shift()),n[t]=s[a];return n},mp=s=>{if(s.length!==16)throw new Error("UUID must be 16 bytes long.");let r=s.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},Pd=s=>s===5||s===99;class fp extends Lt{constructor(r){super(),this.reporter=r.reporter}get isOpen(){return this.readyState==="open"}get readyState(){var r,e;return((r=this.peerconnection)==null?void 0:r.isConnected)&&((e=this.datachannelCore)==null?void 0:e.readyState)}get datachannelCore(){var r,e,t;return(t=(e=(r=this.peerconnection)==null?void 0:r.getPeerCore())==null?void 0:e.getSignal())==null?void 0:t.getDatachannelCore()}getPeerConnection(){return this.peerconnection}setPeerConnection(r){this.peerconnection=r}createDatachannel(r){return _(this,null,function*(){var c,o,l;const e=r.signalUrl;if(!this.checkUrl(e))throw new ie(H.ERROR_DATACHANNEL_PARAM,"url need artc://","");this.closeDatachannel(),this.createPC(),this.reporter.updateUrl(e),this.reporter.reportDatachannelHttpConnect(e);let t,i,n=performance.now();try{t=yield(c=this.peerconnection)==null?void 0:c.createOffer(!1,!1,void 0,r)}catch(d){this.throwRtsError(new ie(d.errorCode||H.ERROR_CREATEOFFER,d.message||"",""))}let a="";try{i=yield this.excuteSignal(t.desp),a=((o=i==null?void 0:i.data)==null?void 0:o.trace_id)||"",this.reporter.reportDatachannelHttpConnectOk({url:e,hrct:Math.floor(performance.now()-n),tcid:a})}catch(d){this.throwRtsError(new ie(d.errorCode||H.ERROR_HTTPREQUEST_ERROR,d.message||"",a))}try{yield(l=this.peerconnection)==null?void 0:l.recvAnswer(i==null?void 0:i.data,{answerSdpHook:r.answerSdpHook})}catch(d){this.throwRtsError(new ie(d.errorCode||H.ERROR_ANSWER_ERROR,d.message||"set answer error",a))}try{yield this.waitForOpen()}catch(d){this.throwRtsError(new ie(H.ERROR_DATACHANNEL_OPEN,`datachannel open failed: ${d}`,a))}return a})}waitForOpen(){let r;return new Promise((e,t)=>{var n;r=window.setTimeout(()=>{var a;(a=this.peerconnection)==null||a.off("datachannelStatusChange",i),r=void 0,t("timeout")},5e3);const i=a=>{r&&(clearTimeout(r),r=void 0),a.status===yt.DATACHANNEL_STATUS_OPEN?e(!0):t(`status is ${a.status}`)};(n=this.peerconnection)==null||n.once("datachannelStatusChange",i)})}excuteSignal(r){return _(this,null,function*(){const e=yield sn.post(this.signalUrl,{version:nn,sdk_version:an,mode:"live",jsep:r});if((e==null?void 0:e.status)!==200)throw new ie(H.ERROR_SIGNAL_ERROR,e?"response status:"+e.status:"response is null","");return e})}closeDatachannel(){var r;(r=this.peerconnection)==null||r.reset()}dispose(){this.removeAllListeners()}checkUrl(r){const e="artc://";if(!r||r.indexOf(e)!==0)return;const{protocol:t}=window.location;let i=(["http:","https:"].indexOf(t)>-1?t:"https:")+"//";return this.signalUrl=r.replace(e,i),!0}throwRtsError(r){throw this.emit("onError",r),r}createPC(){this.peerconnection=new Zi,this.peerconnection.on("connectStatusChange",r=>{this.emit("connectStatusChange",r)})}}class gp extends Lt{constructor(r){super(),this.datachannelPool=new Sp,this.receiverCodecPreferences={},this.senderCodecPreferences={},this.canAutoAssignDcId=!0,this.reporter=r,this.signalChannel=new fp({reporter:r}),this.proxySignalChannelEvents()}dispose(){var r;this.removeAllListeners(),this.signalChannel.dispose(),this.datachannelPool.dispose(),this.waitForOpenPms=void 0,this.receiverCodecPreferences={},this.senderCodecPreferences={},this.canAutoAssignDcId=!0,this.config=void 0,(r=this.peerconnection)!=null&&r.isConnected&&this.peerconnection.reset()}setConfig(r){this.config=r}setPeerconnection(r){r!==this.peerconnection&&(this.peerconnection&&this.peerconnection.removeAllListeners(),this.peerconnection=r,this.signalChannel.isOpen||(this.waitForOpenPms=new Promise((e,t)=>{this.peerconnection.on("datachannelStatusChange",i=>{var n;this.emit("datachannelStatusChange",i),i.status===yt.DATACHANNEL_STATUS_OPEN&&(this.signalChannel.setPeerConnection(r),this.canAutoAssignDcId=typeof((n=this.signalChannel.datachannelCore)==null?void 0:n.id)=="number",e())})})),this.peerconnection.on("cumuDelayNotSupported",()=>{var e;this.emit("cumuDelayNotSupported"),(e=this.reporter)==null||e.reportCumuDelayNotSupported()}),this.peerconnection.on("innerSubscribeDeleteTracks",e=>{this.handleWorkerSubDelete(e)}),this.peerconnection.on("encodedFrame",e=>{var t;this.emit("encodedFrame",e),e.kind==="video"&&(i=>{let n=[];const a=new DataView(i);let c=0;for(;;){let o=c;const l=a.getUint32(o);if(o+=4,l===1){if((31&a.getUint8(o++))==6){const d=a.getUint8(o++),h=Pd(d)?16:0;let u=0;for(;a.getUint8(o)==255;)o++,u+=255;if(u+=a.getUint8(o++),u>0&&a.byteLength>o+u){let p=new Uint8Array(a.buffer),f="";if(Pd(d)){const g=p.slice(o,o+h);f=mp(pp(g))}let m=p.slice(o+h,o+u);o+=u,n.push({payloadType:d,uuid:f,data:m.buffer})}}c=o}else c+=1;if(c+4>=a.byteLength)break}return n})((t=e.frame)==null?void 0:t.data).forEach(i=>{var n;if(i.payloadType===99){let a,c={pub:{},sub:{},grtn:{},AIPub:{},AISub:{},AIAgent:{},AIGrtn:{},other:{}},o=new hp(i.data);c.pub=o.pub||{},c.sub=e.subStats||{},c.grtn=o.grtn||{},c.AIPub=o.AIPub||{},c.AISub=o.AISub||{},c.AIAgent=o.AIAgent||{},c.AIGrtn=o.AIGrtn||{},c.other=o.other||{},Object.keys(c.pub).forEach(l=>{let d=c.pub[l];delete c.pub[l],c.pub[zi(l)]=d}),Object.keys(c.sub).forEach(l=>{let d=c.sub[l];delete c.sub[l],c.sub[zi(l)]=d}),Object.keys(c.AIPub).forEach(l=>{let d=c.AIPub[l];delete c.AIPub[l],c.AIPub[zi(l)]=d}),Object.keys(c.AISub).forEach(l=>{let d=c.AISub[l];delete c.AISub[l],c.AISub[zi(l)]=d}),Object.keys(c.AIAgent).forEach(l=>{let d=c.AIAgent[l];delete c.AIAgent[l],c.AIAgent[Us(l.toLowerCase())]=d}),Object.keys(c.AIGrtn).forEach(l=>{let d=c.AIGrtn[l];delete c.AIGrtn[l],c.AIGrtn[Us(l.toLowerCase())]=d}),Object.keys(c.grtn).forEach(l=>{let d=c.grtn[l];delete c.grtn[l],c.grtn[Us(l.toLowerCase())]=d});try{a=he(c)}catch(l){console.warn(l,c)}a&&(i.data=new TextEncoder().encode(a),(n=this.reporter)==null||n.updateCumuDelayInfo({json:a}))}this.emit("receivedSEI",{url:e.url,vMsid:e.vMsid,sei:i})})}),this.peerconnection.on("message",e=>{var t;(t=this.reporter)==null||t.reportNotifyMessage(e)}),this.peerconnection.on("signalSent",e=>{this.emit("signalSent",e)}),this.peerconnection.on("signalReceived",e=>{this.emit("signalReceived",e)}),this.peerconnection.on("hebtSent",e=>{this.emit("hebtSent",e)}),this.peerconnection.on("hebtReceived",e=>{this.emit("hebtReceived",e)}),this.peerconnection.on("streamError",e=>{this.emit("onError",new ie(H.ERROR_SINGLE_PC_STREAM_ERROR,e.resMsg,"",D({},e)))}),this.peerconnection.on("streamReconnect",e=>{this.emit("reconnect",{type:e.type,reason:new ie(H.ERROR_SINGLE_PC_STREAM_ERROR,e.resMsg,"",D({},e)),retryTimes:1,extraInfo:D({},e)}),this.singleStreamReconnect(e).then(()=>{this.emit("reconnectFinish",{type:e.type,latestUrl:e.latestUrl,msids:e.msids})}).catch(t=>{this.emit("onError",new ie(H.ERROR_SINGLE_PC_STREAM_RECONNECT_FAILED,"single stream reconnect failed","",{originError:t}))})}),this.peerconnection.on("traceIdUpdate",e=>{this.emit("traceId",e)}),this.peerconnection.on("pcReconnect",e=>{this.emit("reconnect",{type:"pc",reason:new ie(H.ERROR_SINGLE_PC_FULL_RECONNECT,e.reMsg,"",D({},e)),retryTimes:1,extraInfo:D({},e)})}),(this.receiverCodecPreferences.video||this.receiverCodecPreferences.audio)&&this.peerconnection.setReceiverCodecPreferences(this.receiverCodecPreferences),(this.senderCodecPreferences.video||this.senderCodecPreferences.audio)&&this.peerconnection.setSenderCodecPreferences(this.senderCodecPreferences))}get peerCore(){var r;return(r=this.peerconnection)==null?void 0:r.getPeerCore()}get streamManager(){var r;return(r=this.peerCore)==null?void 0:r.getStreamManager()}get datachannelManager(){var r;return(r=this.peerCore)==null?void 0:r.getDatachannelManager()}joinPubSub(r,e){return _(this,null,function*(){var c,o,l,d;if(!r.url||!r.msid){let h=new ie(H.ERROR_DATACHANNEL_PARAM,"url, signalUrl, msid is required by subscribe(publish)AddDatachannel","");throw(c=this.reporter)==null||c.reportErrorInfo(h.errorCode,h.message,h.traceId,h.extraInfo),h}this.waitForOpenPms&&(yield this.waitForOpenPms,this.waitForOpenPms=void 0),this.signalChannel.isOpen||(yield this.initSignalChannel(Q(D({},r),{signalUrl:r.url})),this.setPeerconnection(this.signalChannel.getPeerConnection()),this.canAutoAssignDcId=typeof((o=this.signalChannel.datachannelCore)==null?void 0:o.id)=="number");let t=performance.now();const i={url:r.url,label:r.label,surl:r.url,msid:r.msid};(l=this.reporter)==null||l.reportDatachannelSubAdd(i);const n=(d=this.peerconnection)==null?void 0:d.getPc();if(!n)throw new Error("No available peerconnection");const a=new Ws({pc:n,label:r.label,datachannelList:this.datachannelPool.list,assignId:!0,delayOpen:bi.getContext().datachannelDelayOpen});return a.getWebrtcDatachannel().binaryType="arraybuffer",a.on("message",e),this.datachannelPool.update(a),new Promise((h,u)=>_(this,null,function*(){var S,v,E,T,R;let p="",f=!1,m=!1;a.on("statusChange",y=>{var C;(C=this.reporter)==null||C.reportDatachannelStatusChange({state:yt[y],url:r.url,label:a.label,id:a.id,msid:r.msid}),y===yt.DATACHANNEL_STATUS_OPEN&&(f=!0,m&&h({datachannel:a,traceId:p}))}),a.on("dispose",()=>{var y;(y=this.reporter)==null||y.reportDatachannelDispose({url:r.url,label:a.label,id:a.id,msid:r.msid})});try{const y=yield(S=this.peerconnection)==null?void 0:S.joinPubSub(Q(D({},r),{channelId:a.assignedId}));p=(E=(v=y==null?void 0:y.streams)==null?void 0:v[0])==null?void 0:E.traceid}catch(y){const C=y;return(T=this.reporter)==null||T.reportErrorInfo(C.errorCode,C.message||"datachannel sub add error",C.traceId,C.extraInfo),u(y)}const g={url:r.url,drct:Math.floor(performance.now()-t),tcid:p,label:a.label,id:a.id,msid:r.msid};(R=this.reporter)==null||R.reportDatachannelSubAddOk(g),m=!0,f&&h({datachannel:a,traceId:p})}))})}subscribeAdd(r,e,t){return _(this,null,function*(){var l;if(r.forEach(d=>{var h;(h=this.reporter)==null||h.reportSubscribeStart(d.url,"",d.vMsid,d.aMsid,!0)}),!this.peerconnection)throw this.makeRtsError("subscribeAdd");this.peerconnection.isReused=!0;let i,n=new Date().getTime();try{if(i=yield this.peerconnection.subAdd(r,e,t),!i.streamList)throw new ie(H.ERROR_SUBADD_NO_RESULT,"subAdd streamList not found","",{api:"subscribeAdd",configList:r,response:i})}catch(d){const h=d;throw(l=this.reporter)==null||l.reportErrorInfo(h.errorCode,h.message,h.traceId,h.extraInfo),h}const a=i.deleteRspTime-n,c=i.subAddRspTime-i.deleteRspTime,o=i.activeRspTime-i.subAddRspTime;return i.streamList.forEach((d,h)=>{var E,T,R,y;(E=this.reporter)==null||E.reportSubscribeOk({vurl:d.url||void 0,isSubAdd:!0});const u=r[h],{targetStream:p,vMsid:f,aMsid:m}=u||{},g=d.stream;if(p)return p.mergeStream(g),(T=this.streamManager)==null||T.update(d.url,{stream:p,vMsid:f==null?void 0:f[0],aMsid:m==null?void 0:m[0]}),void(d.stream=p);let S;const v=(R=this.streamManager)==null?void 0:R.getStreamByMsid({url:d.url,vMsid:f==null?void 0:f[0],aMsid:m==null?void 0:m[0]});if(v)v.mergeStream(g),S=v;else{S=new Id,S.updateMediaStream(g),(y=this.streamManager)==null||y.update(d.url,{stream:S,vMsid:f==null?void 0:f[0],aMsid:m==null?void 0:m[0]}),S.on("onCanPlay",()=>{var A,P;let w=new Date().getTime();(A=this.reporter)==null||A.reportFirstFrameTime(d.url,d.traceId,-1,-1,w-n,0,-1,{},a,c,o,f,m,!0),(P=this.peerconnection)==null||P.playStart()});let C=new kr(Ad);C.data={url:d.url,vMsid:(f==null?void 0:f[0])||"vMsid unknown",aMsid:(m==null?void 0:m[0])||"aMsid unknown"},this.emit("onPlayEvent",C)}d.stream=S}),i.streamList})}subscribeActive(r){return _(this,null,function*(){var e;if(!this.peerconnection)throw this.makeRtsError("subscribeActive");return(e=this.peerconnection)==null?void 0:e.subActive(r)})}subscribeStop(r){return _(this,null,function*(){var t;if(!this.peerconnection)throw this.makeRtsError("subscribeStop");let e;try{e=yield this.peerconnection.subStop(r),this.peerconnection.getSubMonitor().updateTranceiversController();const i=this.peerconnection.getWorkerManager();r.forEach(n=>{i.removeByUrl({url:n.url,source:Pt.Receiver})})}catch(i){const n=i;throw(t=this.reporter)==null||t.reportErrorInfo(n.errorCode,n.message,n.traceId,n.extraInfo),i}return e})}subscribeDeleteTracks(r){return _(this,null,function*(){var t;if(!this.peerconnection)throw this.makeRtsError("subscribeDeleteTracks");let e;try{if(e=yield this.peerconnection.subDeleteTracks(r),!e)throw this.makeRtsError("subscribeDeleteTracks");this.peerconnection.getSubMonitor().updateTranceiversController(),this.handleWorkerSubDelete(r)}catch(i){const n=i;throw(t=this.reporter)==null||t.reportErrorInfo(n.errorCode,n.message,n.traceId,n.extraInfo),i}return e})}handleWorkerSubDelete(r){if(!this.peerconnection)return;const e=this.peerconnection.getWorkerManager();r.forEach(t=>{var i,n;(i=t.vMsid)!=null&&i.length&&e.removeByMsid({url:t.url,source:Pt.Receiver,kind:"video",msid:t.vMsid[0]}),(n=t.aMsid)!=null&&n.length&&e.removeByMsid({url:t.url,source:Pt.Receiver,kind:"audio",msid:t.aMsid[0]})})}publishAdd(r,e,t){return _(this,null,function*(){var o,l,d,h;r.forEach(u=>{var p;(p=this.reporter)==null||p.reportStartPublish(u.url,"",!0)});let i,n=new Date().getTime();if(!this.peerconnection)throw this.makeRtsError("publishAdd");try{if(i=yield(o=this.peerconnection)==null?void 0:o.pubAdd(r,e,t),!i)throw new ie(H.ERROR_PUBADD_NO_RESULT,"pubAdd streamList not found","",{api:"publishAdd",publishInfoList:r})}catch(u){const p=u;throw(l=this.reporter)==null||l.reportErrorInfo(p.errorCode,p.message,p.traceId,p.extraInfo),p}this.peerconnection.isReused=!0;const a=new Date().getTime()-n;i.forEach(u=>{var p;(p=this.reporter)==null||p.reportPublishOk(u.url||"","",-1,-1,-1,u.traceId||"",a,!0)});const c=(d=this.peerconnection)==null?void 0:d.getPc();if(c){r.forEach(p=>{this.peerconnection&&p.stream.setEncodeParam(c)}),this.peerCore&&((h=this.peerconnection)==null||h.getPubMonitor().startHeartbeat(c,this.peerCore));const u=new Set;r.forEach(p=>{p.stream.audioTrack&&u.add(p.stream.audioTrack.id),p.stream.videoTrack&&u.add(p.stream.videoTrack.id)}),c.getSenders().forEach(p=>{var f;p.track&&u.has(p.track.id)&&((f=this.peerconnection)==null||f.handleEncodedInsertableStreams({sender:p}))})}return i})}publishDeleteTracks(r){return _(this,null,function*(){var t;if(!this.peerconnection)throw this.makeRtsError("publishDeleteTracks");let e;try{if(e=yield this.peerconnection.pubDeleteTracks(r),!e)throw this.makeRtsError("publishDeleteTracks");this.peerconnection.getPubMonitor().updateSenders();const i=this.peerconnection.getWorkerManager();r.forEach(n=>{var a,c;(a=n.vMsid)!=null&&a.length&&i.removeByMsid({url:n.url,source:Pt.Sender,kind:"video",msid:n.vMsid[0]}),(c=n.aMsid)!=null&&c.length&&i.removeByMsid({url:n.url,source:Pt.Sender,kind:"audio",msid:n.aMsid[0]})})}catch(i){const n=i;throw(t=this.reporter)==null||t.reportErrorInfo(n.errorCode,n.message,n.traceId,n.extraInfo),i}return e})}publishReplaceTracks(r){return _(this,null,function*(){var t;if(!this.peerconnection)throw this.makeRtsError("publishReplaceTracks");let e;try{if(e=yield this.peerconnection.pubReplaceTracks(r),!e)throw this.makeRtsError("publishReplaceTracks");this.peerconnection.getPubMonitor().updateSenders()}catch(i){const n=i;throw(t=this.reporter)==null||t.reportErrorInfo(n.errorCode,n.message,n.traceId,n.extraInfo),i}return e})}publishStop(r){return _(this,null,function*(){var t;if(r.forEach(i=>{var n;(n=this.reporter)==null||n.reportStopPublish(i.url,!0)}),!this.peerconnection)throw this.makeRtsError("publishStop");let e;try{e=yield this.peerconnection.pubStop(r),this.peerconnection.getPubMonitor().updateSenders();const i=this.peerconnection.getWorkerManager();r.forEach(n=>{i.removeByUrl({url:n.url,source:Pt.Sender})})}catch(i){const n=i;throw(t=this.reporter)==null||t.reportErrorInfo(n.errorCode,n.message,n.traceId,n.extraInfo),i}return e})}handleAddDatachannel(r){return _(this,null,function*(){var c,o,l,d,h,u;if(!r.url||!r.signalUrl||!r.msid){let p=new ie(H.ERROR_DATACHANNEL_PARAM,"url, signalUrl, msid is required by subscribe(publish)AddDatachannel","");throw(c=this.reporter)==null||c.reportErrorInfo(p.errorCode,p.message,p.traceId,p.extraInfo),p}const e=r.type==="sub";if(this.waitForOpenPms&&(yield this.waitForOpenPms,this.waitForOpenPms=void 0),!this.signalChannel.isOpen){if(console.warn("Creating a new signal channel"),!r.signalUrl){let p=new ie(H.ERROR_SIGNAL_URL,"signal url is required","");throw(o=this.reporter)==null||o.reportErrorInfo(p.errorCode,p.message,p.traceId,p.extraInfo),p}yield this.initSignalChannel(r),this.setPeerconnection(this.signalChannel.getPeerConnection()),this.canAutoAssignDcId=typeof((l=this.signalChannel.datachannelCore)==null?void 0:l.id)=="number"}let t=performance.now();const i={url:r.url,label:r.label,surl:r.signalUrl,msid:r.msid};e?(d=this.reporter)==null||d.reportDatachannelSubAdd(i):(h=this.reporter)==null||h.reportDatachannelPubAdd(i);const n=(u=this.peerconnection)==null?void 0:u.getPc();if(!n)throw new Error("No avaliable peerconnection");let a=this.datachannelPool.getIdleItem();return a?a.reuse():(a=new Ws({pc:n,label:r.label,datachannelList:this.datachannelPool.list,assignId:!this.canAutoAssignDcId,delayOpen:bi.getContext().datachannelDelayOpen,initOptions:r.initOptions}),this.datachannelPool.update(a)),new Promise((p,f)=>_(this,null,function*(){var E,T,R,y,C,w,A;let m="",g=!1,S=!1;a.on("statusChange",P=>{var M;(M=this.reporter)==null||M.reportDatachannelStatusChange({state:yt[P],url:r.url,label:a.label,id:a.id,msid:r.msid}),P===yt.DATACHANNEL_STATUS_OPEN&&(g=!0,S&&p({datachannel:a,traceId:m}))}),a.on("dispose",()=>{var P;(P=this.reporter)==null||P.reportDatachannelDispose({url:r.url,label:a.label,id:a.id,msid:r.msid})});try{const P=[{url:r.url,msid:r.msid,datachannelId:a.id,label:r.label,datachannel:a}],M=e?yield(E=this.peerCore)==null?void 0:E.subscribeAddDatachannel(P):yield(T=this.peerCore)==null?void 0:T.publishAddDatachannel(P);m=(y=(R=M==null?void 0:M.streams)==null?void 0:R[0])==null?void 0:y.traceid}catch(P){const M=P;return(C=this.reporter)==null||C.reportErrorInfo(M.errorCode,M.message||`datachannel ${e?"sub":"pub"} add error`,M.traceId,M.extraInfo),f(P)}const v={url:r.url,drct:Math.floor(performance.now()-t),tcid:m,label:a.label,id:a.id,msid:r.msid};e?(w=this.reporter)==null||w.reportDatachannelSubAddOk(v):(A=this.reporter)==null||A.reportDatachannelPubAddOk(v),S=!0,g&&p({datachannel:a,traceId:m})}))})}handleDeleteDatachannel(r){return _(this,null,function*(){var n,a,c,o,l,d,h,u;if(!r.url||!r.datachannel){let p=new ie(H.ERROR_DATACHANNEL_PARAM,"url, datachannel is required by subscribe(publish)DeleteDatachannel","");throw(n=this.reporter)==null||n.reportErrorInfo(p.errorCode,p.message,p.traceId,p.extraInfo),p}if(!this.signalChannel.isOpen){let p=new ie(H.ERROR_NO_DATACHANNEL,"Signal channel is closed","");throw(a=this.reporter)==null||a.reportErrorInfo(p.errorCode,p.message,p.traceId,p.extraInfo),p}const e=r.type==="sub",t=[{url:r.url,msid:r.msid}],i={url:r.url,msid:r.msid,label:r.datachannel.label,id:r.datachannel.id};e?(c=this.reporter)==null||c.reportDatachannelSubDelete(i):(o=this.reporter)==null||o.reportDatachannelPubDelete(i);try{e?yield(l=this.peerCore)==null?void 0:l.subscribeDeleteDatachannel(t):yield(d=this.peerCore)==null?void 0:d.publishDeleteDatachannel(t)}catch(p){throw p}e?(h=this.reporter)==null||h.reportDatachannelSubDeleteOk(i):(u=this.reporter)==null||u.reportDatachannelPubDeleteOk(i),r.datachannel.dispose()})}handleStopDatachannel(r){return _(this,null,function*(){var n,a,c,o,l,d,h,u;if(!r.url||!r.datachannel){let p=new ie(H.ERROR_DATACHANNEL_PARAM,"url, datachannel is required by subscribe(publish)StopDatachannel","");throw(n=this.reporter)==null||n.reportErrorInfo(p.errorCode,p.message,p.traceId,p.extraInfo),p}if(!this.signalChannel.isOpen){let p=new ie(H.ERROR_NO_DATACHANNEL,"Signal channel is closed","");throw(a=this.reporter)==null||a.reportErrorInfo(p.errorCode,p.message,p.traceId,p.extraInfo),p}const e=r.type==="sub",t=[{url:r.url}],i={url:r.url,label:r.datachannel.label,id:r.datachannel.id};e?(c=this.reporter)==null||c.reportDatachannelSubStop(i):(o=this.reporter)==null||o.reportDatachannelPubStop(i);try{e?yield(l=this.peerCore)==null?void 0:l.subscribeStopDatachannel(t):yield(d=this.peerCore)==null?void 0:d.publishStopDatachannel(t)}catch(p){throw p}e?(h=this.reporter)==null||h.reportDatachannelSubStopOk(i):(u=this.reporter)==null||u.reportDatachannelPubStopOk(i),r.datachannel.dispose()})}subscribeAddDatachannel(r){return _(this,null,function*(){return this.handleAddDatachannel(Q(D({},r),{type:"sub"}))})}publishAddDatachannel(r){return _(this,null,function*(){return this.handleAddDatachannel(Q(D({},r),{type:"pub"}))})}subscribeDeleteDatachannel(r){return _(this,null,function*(){return this.handleDeleteDatachannel(Q(D({},r),{type:"sub"}))})}publishDeleteDatachannel(r){return _(this,null,function*(){return this.handleDeleteDatachannel(Q(D({},r),{type:"pub"}))})}subscribeStopDatachannel(r){return _(this,null,function*(){return this.handleStopDatachannel(Q(D({},r),{type:"sub"}))})}publishStopDatachannel(r){return _(this,null,function*(){return this.handleStopDatachannel(Q(D({},r),{type:"pub"}))})}getSubscribeVideoStats(r,e){return this.getSubscribeMediaStats(r,"video",e)}getSubscribeAudioStats(r,e){return this.getSubscribeMediaStats(r,"audio",e)}getPublishVideoStats(r,e){return this.getPublishMediaStats(r,"video",e)}getPublishAudioStats(r,e){return this.getPublishMediaStats(r,"audio",e)}sendSEI(r){var e,t;if((e=this.peerconnection)!=null&&e.isReused)return(t=this.peerconnection)==null?void 0:t.sendSEI(r)}setReceiverCodecPreferences(r){this.receiverCodecPreferences=D({},r)}setSenderCodecPreferences(r){this.senderCodecPreferences=D({},r)}getSubscribeMediaStats(r,e,t){return new Promise(i=>_(this,null,function*(){var o,l;if(!this.streamManager)return i({});let n;const a=this.streamManager.getAllMediaInfoList(r,!0);if(t?a.forEach(d=>{var u,p,f;const h=(p=(u=d.transceiver)==null?void 0:u.receiver)==null?void 0:p.track;(h==null?void 0:h.kind)===e&&d.msid===t&&(n=(f=d.transceiver)==null?void 0:f.receiver)}):n=(l=(o=a==null?void 0:a.find(d=>{var h,u,p;return((p=(u=(h=d.transceiver)==null?void 0:h.receiver)==null?void 0:u.track)==null?void 0:p.kind)===e}))==null?void 0:o.transceiver)==null?void 0:l.receiver,!n)return i({});let c=!1;(yield n.getStats()).forEach(d=>{d.type==="inbound-rtp"&&(c=!0,i(d))}),c||i({})}))}getPublishMediaStats(r,e,t){return new Promise(i=>_(this,null,function*(){var c,o;if(!this.streamManager)return i({});let n;const a=this.streamManager.getAllMediaInfoList(r,!0);if(t?a.forEach(l=>{var h,u,p;const d=(u=(h=l.transceiver)==null?void 0:h.sender)==null?void 0:u.track;(d==null?void 0:d.kind)===e&&l.msid===t&&(n=(p=l.transceiver)==null?void 0:p.sender)}):n=(o=(c=a==null?void 0:a.find(l=>{var d,h,u;return((u=(h=(d=l.transceiver)==null?void 0:d.sender)==null?void 0:h.track)==null?void 0:u.kind)===e}))==null?void 0:c.transceiver)==null?void 0:o.sender,!n)return i({});(yield n.getStats()).forEach(l=>{l.type==="outbound-rtp"&&i(l)}),i({})}))}proxySignalChannelEvents(){this.signalChannel.on("connectStatusChange",r=>{this.emit("connectStatusChange",r)}),this.signalChannel.on("onError",r=>{this.emit("onError",r)})}initSignalChannel(r){return this.signalChannel.createDatachannel(r)}makeRtsError(r){var t;let e=new ie(H.ERROR_NO_DATACHANNEL,"No avaliable datachannel, you should subscribe/publish first.","",{api:r});return(t=this.reporter)==null||t.reportErrorInfo(e.errorCode,e.message,e.traceId,e.extraInfo),e}singleStreamReconnect(r){return new Promise((e,t)=>{var a,c;let i,n;switch(r.type){case"sub":(a=r.streams)==null||a.forEach(o=>{const l=[],d=[];let h=!0,u=!0;r.msids.forEach(p=>{p.streamId===o.id&&(p.type==="video"?d.push(p.name):p.type==="audio"&&l.push(p.name))}),l.length||(h=!1),d.length||(u=!1),this.subscribeAddWithRetry({url:r.latestUrl,subAudio:h,subVideo:u,vMsid:d,aMsid:l,targetStream:o}).then(e).catch(t)});break;case"pub":(c=r.streams)==null||c.forEach(o=>{const l=[],d=[];r.msids.forEach(h=>{h.streamId===o.id&&(h.type==="video"?d.push(h.name):h.type==="audio"&&l.push(h.name))}),this.publishAddWithRetry([{url:r.latestUrl,vMsid:d,aMsid:l,stream:o}]).then(e).catch(t)});break;case"pub-data":if(r.msids.forEach(o=>{i=o.name,n=o.label}),i&&n){const o=r.latestUrl;this.publishAddDatachannelWithRetry({url:o,signalUrl:o,msid:i,label:n}).then(e).catch(t)}break;case"sub-data":if(r.msids.forEach(o=>{i=o.name,n=o.label}),i&&n){const o=r.latestUrl;this.subscribeAddDatachannelWithRetry({url:o,signalUrl:o,msid:i,label:n}).then(e).catch(t)}break;default:console.warn("RTS PC STREAM RECONNECT: Unknown signal")}})}updateAuth(r){var i,n;let e=(i=this.streamManager)==null?void 0:i.updateLatestUrl(r),t=(n=this.datachannelManager)==null?void 0:n.updateLatestUrl(r);return e||t}subscribeAddWithRetry(r,e=0){return new Promise((t,i)=>{this.subscribeAdd([r],!0).then(()=>{t()}).catch(n=>_(this,null,function*(){var a,c;if(e<(((a=this.config)==null?void 0:a.retryTimes)||0))return yield cs(((c=this.config)==null?void 0:c.retryInterval)||0),this.subscribeAddWithRetry(r,e+1).then(t).catch(i);i(n)}))})}publishAddWithRetry(r,e=0){return new Promise((t,i)=>{this.publishAdd(r).then(()=>{t()}).catch(n=>_(this,null,function*(){var a,c;if(e<(((a=this.config)==null?void 0:a.retryTimes)||0))return yield cs(((c=this.config)==null?void 0:c.retryInterval)||0),this.publishAddWithRetry(r,e+1).then(t).catch(i);i(n)}))})}subscribeAddDatachannelWithRetry(r,e=0){return new Promise((t,i)=>{this.subscribeAddDatachannel(r).then(()=>{t()}).catch(n=>_(this,null,function*(){var a,c;if(e<(((a=this.config)==null?void 0:a.retryTimes)||0))return yield cs(((c=this.config)==null?void 0:c.retryInterval)||0),this.subscribeAddDatachannelWithRetry(r,e+1).then(t).catch(i);i(n)}))})}publishAddDatachannelWithRetry(r,e=0){return new Promise((t,i)=>{this.publishAddDatachannel(r).then(()=>{t()}).catch(n=>_(this,null,function*(){var a,c;if(e<(((a=this.config)==null?void 0:a.retryTimes)||0))return yield cs(((c=this.config)==null?void 0:c.retryInterval)||0),this.publishAddDatachannelWithRetry(r,e+1).then(t).catch(i);i(n)}))})}}class Sp{constructor(){this._list=[]}get list(){return this._list}update(r){const e=this._list.findIndex(t=>t.id===r.id);e!==-1?this._list.splice(e,1,r):this._list.push(r)}getIdleItem(){return this._list.find(r=>r.isIdle)}dispose(){this._list=[]}}function cs(s=1e3){return new Promise(r=>{setTimeout(r,s)})}class bp extends Lt{constructor(r){super(),this.restoring=!1,this.subscriber=r.subscriber,this.publisher=r.publisher,this.commonController=r.commonController}isReconnecting(){return this.restoring}restore(r){let e;if(!this.restoring)return new Promise((t,i)=>_(this,null,function*(){this.restoring=!0;const n=this.restructureStreams();if(n&&n.length){this.subscriber.unsubscribe(),this.publisher.unpublish();let a=Promise.reject().catch(()=>{});const c=n[0];let o=c.url;switch(r&&(o=this.makeIpQuery(o,r,c.type)),c.type){case"sub":this.commonController.setPeerconnection(this.subscriber.getPeerConnection()),this.subscriber.incrementReconnectTimes(),this.subscriber.getSubscribeConfig().retryTimes,this.subscriber.getSubscribeConfig().retryInterval,a=this.subscriber.subscribeWithReconnect(o,Q(D({},this.subscriber.getSubscribeConfig()),{vMsid:c.vMsid,aMsid:c.aMsid}));break;case"pub":c.targetStream&&(this.commonController.setPeerconnection(this.publisher.getPeerConnection()),this.publisher.incrementReconnectTimes(),this.publisher.getPublishConfig().retryTimes,this.publisher.getPublishConfig().retryInterval,a=this.publisher.publishWithReconnect(o,c.targetStream,Q(D({},this.publisher.getPublishConfig()),{vMsid:c.vMsid,aMsid:c.aMsid})));break;case"sub-data":c.msid&&c.label&&(a=this.commonController.subscribeAddDatachannel({signalUrl:o,url:o,label:c.label,msid:c.msid}));break;case"pub-data":c.msid&&c.label&&(a=this.commonController.publishAddDatachannel({signalUrl:c.url,url:c.url,label:c.label,msid:c.msid}));break;default:console.log("RTS [PC RESTORER] unknown http reconnect type",c.type)}try{let h=yield a;e=typeof h=="string"?h:h==null?void 0:h.traceId}catch(h){return i(h),void(this.restoring=!1)}const l=new Promise((h,u)=>{clearTimeout(this.dcOpenTimer),this.dcOpenTimer=setTimeout(()=>{const p=new ie(H.ERROR_DATACHANNEL_OPEN,"reconnect pc datachannel open timeout after 8000ms","",{});u(p)},8e3),this.commonController.on("datachannelStatusChange",p=>{p.status===yt.DATACHANNEL_STATUS_OPEN&&(clearTimeout(this.dcOpenTimer),h())})});try{yield l}catch(h){return i(h),void(this.restoring=!1)}let d=[];for(let h=1;h<n.length;h++){const u=n[h];if(u)switch(u.type){case"sub":d.push(this.commonController.subscribeAdd([{url:u.url,vMsid:u.vMsid,aMsid:u.aMsid,targetStream:u.targetStream,subAudio:!(!u.aMsid||!u.aMsid.length),subVideo:!(!u.vMsid||!u.vMsid.length)}],!0).catch(p=>{this.emit("onError",this.makeSingleStreamReconnectError(p))}));break;case"pub":d.push(this.commonController.publishAdd([{url:u.url,stream:u.targetStream,vMsid:u.vMsid,aMsid:u.aMsid}]).catch(p=>{this.emit("onError",this.makeSingleStreamReconnectError(p))}));break;case"sub-data":u.label&&u.msid&&d.push(this.commonController.subscribeAddDatachannel({signalUrl:u.url,url:u.url,label:u.label,msid:u.msid}).catch(p=>{this.emit("onError",this.makeSingleStreamReconnectError(p))}));break;case"pub-data":u.label&&u.msid&&d.push(this.commonController.publishAddDatachannel({signalUrl:u.url,url:u.url,label:u.label,msid:u.msid}).catch(p=>{this.emit("onError",this.makeSingleStreamReconnectError(p))}));break;default:console.log("RTS [PC RESTORER] unknown pc reconnect type")}}Promise.allSettled(d).then(h=>{var p,f;let u=h.find(m=>m.status==="fulfilled");e=((f=(p=u==null?void 0:u.value)==null?void 0:p[0])==null?void 0:f.traceId)||e,t({traceId:e,latestUrl:o})})}this.restoring=!1}))}restructureStreams(){var a,c;const r=(a=this.commonController.peerCore)==null?void 0:a.getStreamManager(),e=(c=this.commonController.peerCore)==null?void 0:c.getDatachannelManager(),t=r==null?void 0:r.getAllStreamListWithMsids(),i=e==null?void 0:e.getAllList(),n=[];return t==null||t.forEach(o=>{var l;(l=o.streams)==null||l.forEach(d=>{const h=[],u=[],p=o.type,f=o.latestUrl,m=d;o.msids.forEach(g=>{g.streamId===d.id&&(g.type==="video"?u.push(g.name):g.type==="audio"&&h.push(g.name))}),n.push({aMsid:h,vMsid:u,type:p,url:f,targetStream:m})})}),i==null||i.forEach(o=>{o.msids.forEach(l=>{if(l.name&&l.label){const d=l.name,h=l.label,u=o.type,p=o.latestUrl;n.push({msid:d,type:u,label:h,url:p})}})}),n}dispose(){this.removeAllListeners()}makeSingleStreamReconnectError(r){return new ie(H.ERROR_SINGLE_PC_STREAM_RECONNECT_FAILED,"single stream reconnect failed","",{originError:r})}makeIpQuery(r,e,t){var o,l;const i="ali_prefer_media_server",n="ip_migration";let a=r,c="";if(t.indexOf("sub")===0&&((o=e.pull)!=null&&o.length)?c=e.pull[0]:t.indexOf("pub")===0&&((l=e.push)!=null&&l.length)&&(c=e.push[0]),c){const[d,h]=r.split("?");let u;h?(u=new URLSearchParams(h),u.has(i)?u.set(i,c):u.append(i,c),!u.has(n)&&u.append(n,"on")):u=new URLSearchParams({[i]:c,[n]:"on"}),a=`${d}?${u.toString()}`}return a}}class vp extends Lt{constructor(r){var e;super(),this.pullH264Checked=!1,this.lastProtocol="udp",this.usePcReconnect=!1,this.reporter=new rs(r),this.subscriber=new cp(this.reporter,r?r.playConfig:void 0),this.publisher=new dp(this.reporter),this.onePc=new lp(this.reporter),this.commonController=new gp(this.reporter),this.pcRestorer=new bp({subscriber:this.subscriber,publisher:this.publisher,commonController:this.commonController}),this.usePcReconnect=!!((e=r==null?void 0:r.singlePcConfig)!=null&&e.usePcReconnect),this.onePc.on("preSub",t=>{this.emit("preSub",t)}),this.onePc.on("prePub",t=>{this.emit("prePub",t)}),this.onePc.on("reconnectRoomServer",()=>{this.emit("reconnectRoomServer")}),this.subscriber.on("onError",t=>_(this,null,function*(){var n,a,c,o,l,d,h,u;const i=(n=t.extraInfo)==null?void 0:n.response;if(this.reporter.reportErrorInfo(t.errorCode,t.message,t.traceId,{sdp:(a=t.extraInfo)==null?void 0:a.sdp,response:{status:i==null?void 0:i.status,data:i==null?void 0:i.data},pcErrorInfo:(c=t.extraInfo)==null?void 0:c.pcErrorInfo}),this.usePcReconnect)[H.ERROR_PC_DISCONNECTED,H.ERROR_IP_MIGRATE].includes(t.errorCode)&&(this.pcRestorer.isReconnecting()||(t.extraInfo=Q(D({},t.extraInfo),{retryTimes:1}),this.reporter.reportReconnect(t.errorCode,t.message,t.traceId,(o=t.extraInfo)==null?void 0:o.retryTimes),this.emit("reconnect",this.makeReconnectEvent("sub",t)),this.emit("connectStatusChange",{status:ct.CONNECT_STATUS_RECONNECTING}),(h=(d=this.pcRestorer.restore((l=t.extraInfo.pcErrorInfo)==null?void 0:l.ips))==null?void 0:d.then(p=>{this.reporter.reportReconnectFinish({level:"pc"}),this.emit("reconnectFinish",{type:"all",traceId:p.traceId,latestUrl:p.latestUrl})}))==null||h.catch(p=>{const f=new ie(H.ERROR_SINGLE_PC_FULL_RECONNECT_HTTP_FAILED,"pc full reconnect failed","",{originError:p});this.emit("onError",f),this.reporter.reportErrorInfo(f.errorCode,f.message)})));else if(Kh.includes(t.errorCode)){if(!this.subscriber.isConnecting){const p=this.lastProtocol==="udp";this.lastProtocol=p?"tcp":"udp",console.log("retrying with",this.lastProtocol),(yield this.subscriber.retrySubscribe(t,{innerTcpOnly:p}))?(this.reporter.reportReconnect(t.errorCode,t.message,t.traceId,(u=t.extraInfo)==null?void 0:u.retryTimes,p),this.emit("reconnect",this.makeReconnectEvent("sub",t))):this.emit("onError",t)}}else this.emit("onError",t)})),this.subscriber.on("reconnect",t=>{var i;this.reporter.reportReconnect(t.errorCode,t.message,t.traceId,(i=t.extraInfo)==null?void 0:i.retryTimes),this.emit("reconnect",this.makeReconnectEvent("sub",t))}),this.subscriber.on("onPlayEvent",t=>{this.emit("onPlayEvent",t)}),this.subscriber.on("connectStatusChange",t=>{this.emit("connectStatusChange",t),this.reporter.reportConnectionChange(ct[t.status],"sub")}),this.publisher.on("connectStatusChange",t=>{this.emit("connectStatusChange",t),this.reporter.reportConnectionChange(ct[t.status],"pub")}),this.onePc.on("connectStatusChange",t=>{this.emit("connectStatusChange",t)}),this.publisher.on("onError",t=>_(this,null,function*(){var n,a,c,o,l,d,h,u,p;const i=(n=t.extraInfo)==null?void 0:n.response;if(this.reporter.reportErrorInfo(t.errorCode,t.message,t.traceId,{sdp:(a=t.extraInfo)==null?void 0:a.sdp,response:{status:i==null?void 0:i.status,data:i==null?void 0:i.data},pcErrorInfo:(c=t.extraInfo)==null?void 0:c.pcErrorInfo}),this.usePcReconnect)[H.ERROR_PC_DISCONNECTED,H.ERROR_IP_MIGRATE].includes(t.errorCode)&&(this.pcRestorer.isReconnecting()||(t.extraInfo=Q(D({},t.extraInfo),{retryTimes:1}),this.reporter.reportReconnect(t.errorCode,t.message,t.traceId,(o=t.extraInfo)==null?void 0:o.retryTimes),this.emit("reconnect",this.makeReconnectEvent("pub",t)),this.emit("connectStatusChange",{status:ct.CONNECT_STATUS_RECONNECTING}),(h=(d=this.pcRestorer.restore((l=t.extraInfo.pcErrorInfo)==null?void 0:l.ips))==null?void 0:d.then(f=>{this.reporter.reportReconnectFinish({level:"pc"}),this.emit("reconnectFinish",{type:"all",traceId:f.traceId,latestUrl:f.latestUrl})}))==null||h.catch(f=>{const m=new ie(H.ERROR_SINGLE_PC_FULL_RECONNECT_HTTP_FAILED,"pc full reconnect failed","",{originError:f});this.emit("onError",m),this.reporter.reportErrorInfo(m.errorCode,m.message)})));else if(Jh.includes(t.errorCode)){if(!this.publisher.isConnecting){const f=t.errorCode===H.ERROR_TRANSPORT_CLOSED&&((u=t.extraInfo)==null?void 0:u.protocol)!=="tcp";console.log("Retrying with ",f?"TCP":"UDP"),(yield this.publisher.retryPublish(t,f))?(this.reporter.reportReconnect(t.errorCode,t.message,t.traceId,(p=t.extraInfo)==null?void 0:p.retryTimes,f),this.emit("reconnect",this.makeReconnectEvent("pub",t))):this.emit("onError",t)}}else this.emit("onError",t)})),this.publisher.on("reconnect",t=>{var i;this.reporter.reportReconnect(t.errorCode,t.message,t.traceId,(i=t.extraInfo)==null?void 0:i.retryTimes),this.emit("reconnect",this.makeReconnectEvent("pub",t))}),this.commonController.on("connectStatusChange",t=>{this.emit("connectStatusChange",t),this.reporter.reportConnectionChange(ct[t.status],"signalChannel")}),this.commonController.on("onError",t=>{this.reporter.reportErrorInfo(t.errorCode,t.message,t.traceId),this.emit("onError",t)}),this.commonController.on("datachannelStatusChange",t=>{this.emit("datachannelStatusChange",t),this.reporter.reportDatachannelStatusChange({state:yt[t.status],url:"",label:"SIGNAL",id:-1,msid:""})}),this.commonController.on("encodedFrame",t=>{this.emit("encodedFrame",t)}),this.commonController.on("receivedSEI",t=>{this.emit("receivedSEI",t)}),this.commonController.on("onPlayEvent",t=>{this.emit("onPlayEvent",t)}),this.commonController.on("reconnect",t=>{t.type!=="pc"&&this.emit("reconnect",t)}),this.commonController.on("reconnectFinish",t=>{this.reporter.reportReconnectFinish(t),this.emit("reconnectFinish",t)}),this.commonController.on("traceId",t=>{this.emit("traceId",t)}),this.commonController.on("signalSent",t=>{this.emit("signalSent",t)}),this.commonController.on("signalReceived",t=>{this.emit("signalReceived",t)}),this.commonController.on("hebtSent",t=>{this.emit("hebtSent",t)}),this.commonController.on("hebtReceived",t=>{this.emit("hebtReceived",t)}),this.commonController.on("cumuDelayNotSupported",()=>{this.emit("cumuDelayNotSupported")}),this.reporter.reportCreateClient()}getVersion(){return yd}isSupport(r){let e=new Dr;return this.pullH264Checked=!0,e.isSupport(r)}checkPublishSupport(){return new Dr().checkPublishSupport()}checkEncodedTransformSupport(){return new Dr().checkEncodedTransformSupport()}onePcConnect(r){return this.commonController.setPeerconnection(this.onePc.getPeerConnection()),this.onePc.connect(r)}onePcDisconnect(){this.onePc.disconnect()}subscribe(r,e){return this.reporter.updateUrl(r),this.commonController.setConfig(e),this.commonController.setPeerconnection(this.subscriber.getPeerConnection()),this.subscriber.resetResubscribeStatus(),this.subscriber.subscribeWithReconnect(r,Q(D({},e),{isH264Checked:this.pullH264Checked}))}joinPubSub(r,e){return this.commonController.joinPubSub(r,e)}processPublishOffer(r,e){var t;return(t=this.onePc.peerCore)==null?void 0:t.processPublishOffer(r,e)}processSubscribeOffer(r){var e;return(e=this.onePc.peerCore)==null?void 0:e.processSubscribeOffer(r)}subscribeAdd(r,e){return this.commonController.subscribeAdd(r,void 0,e)}subscribeActive(r){return this.commonController.subscribeActive(r)}subscribeDeleteTracks(r){return this.commonController.subscribeDeleteTracks(r)}subscribeStop(r){return this.commonController.subscribeStop(r)}publishAdd(r,e,t){return this.commonController.publishAdd(r,e,t)}publishDeleteTracks(r){return this.commonController.publishDeleteTracks(r)}publishReplaceTracks(r){return this.commonController.publishReplaceTracks(r)}publishStop(r){return this.commonController.publishStop(r)}subscribeAddDatachannel(r){return this.commonController.subscribeAddDatachannel(r)}subscribeDeleteDatachannel(r){return this.commonController.subscribeDeleteDatachannel(r)}publishDeleteDatachannel(r){return this.commonController.publishDeleteDatachannel(r)}subscribeStopDatachannel(r){return this.commonController.subscribeStopDatachannel(r)}publishAddDatachannel(r){return this.commonController.publishAddDatachannel(r)}publishStopDatachannel(r){return this.commonController.publishStopDatachannel(r)}unsubscribe(){this.subscriber.resetResubscribeStatus(),this.subscriber.unsubscribe()}startLiveStream(r,e,t){return this.reporter.reportStartPlay(r),this.subscriber.startLiveStream(r,e,t)}stopLiveStream(){this.reporter.reportStopPlay(),this.subscriber.stopLiveStream()}muteLiveStream(r){this.subscriber.muteLiveStream(r)}publish(r,e,t){return _(this,null,function*(){return this.reporter.updateUrl(r),this.commonController.setConfig(t),this.commonController.setPeerconnection(this.publisher.getPeerConnection()),this.publisher.resetRepublishStatus(),this.publisher.publishWithReconnect(r,e,t)})}unpublish(){return this.publisher.resetRepublishStatus(),this.publisher.unpublish()}sendSEI(r){this.publisher.sendSEI(r),this.commonController.sendSEI(r)}getPublishTrackInfoList(){return this.publisher.getTrackInfoList()}getTransportStats(){return this.subscriber.getPeerConnection().getSubMonitor().getTransportStats()}getRemoteVideoStats(){return this.subscriber.getPeerConnection().getSubMonitor().getRemoteVideoStats()}getRemoteAudioStats(){return this.subscriber.getPeerConnection().getSubMonitor().getRemoteAudioStats()}getSubscribeVideoStats(r,e){return this.commonController.getSubscribeVideoStats(r,e)}getSubscribeAudioStats(r,e){return this.commonController.getSubscribeAudioStats(r,e)}getPublishVideoStats(r,e){return this.commonController.getPublishVideoStats(r,e)}getPublishAudioStats(r,e){return this.commonController.getPublishAudioStats(r,e)}setReceiverCodecPreferences(r){return this.commonController.setReceiverCodecPreferences(r)}setSenderCodecPreferences(r){return this.commonController.setSenderCodecPreferences(r)}makeReconnectEvent(r,e){const o=e||{},{extraInfo:t}=o,i=jt(o,["extraInfo"]),l=t||{},{retryTimes:n}=l,a=jt(l,["retryTimes"]),c=r;return{type:this.usePcReconnect?"pc":c,reason:i,retryTimes:n,extraInfo:a}}heartbeat(r){var e;(e=this.commonController.peerCore)==null||e.sendOnceHeartbeat(r)}setAutoHeartbeat(r){var e;(e=this.commonController.peerCore)==null||e.startSignalHeartbeatTimer(r)}clearAutoHeartbeat(){var r;(r=this.commonController.peerCore)==null||r.stopSignalHeartbeatTimer()}sendFalseHeartbeat(r){var e;(e=this.commonController.peerCore)==null||e.sendFalseHeartbeat(r)}updateAuth(r){return this.commonController.updateAuth(r)}dispose(){this.removeAllListeners(),this.reporter.dispose(),this.subscriber.dispose(),this.publisher.dispose(),this.commonController.dispose(),this.pcRestorer.dispose()}}const ds=class di{constructor(){this.request=Rd.create({timeout:6e4}),this.offset=0,this.nextAttemptMs=di.DEFAULT_ATTEMPT_INTERVAL,this.attemptCount=0,this.random=Math.random(),this.startSyncClock()}now(){if(this.offset&&!Number.isNaN(this.offset)){let r=Date.now()+this.offset;return Math.round(r)}return Date.now()}syncClock(){return _(this,null,function*(){let r=!1;const e=Date.now(),t=yield this.fetchServerTime(),i=Date.now();if(t){const n=new Date(t).getTime();Number.isNaN(n)||(this.offset=this.calculateOffset(e+this.fixRequestStartTime(),i,n),r=!0)}else console.warn("Failed to fetch server time, should try again");return r})}startSyncClock(){return _(this,null,function*(){let r=yield this.syncClock();this.nextAttemptMs=r?di.DEFAULT_ATTEMPT_INTERVAL:di.DEFAULT_ATTEMPT_RETRY_INTERVAL,this.stopSyncClock(),this.attemptTimer=setTimeout(()=>{this.startSyncClock()},this.nextAttemptMs)})}stopSyncClock(){this.attemptTimer&&clearTimeout(this.attemptTimer),this.attemptTimer=void 0}fetchServerTime(){return _(this,null,function*(){var e;let r;this.attemptCount++;try{r=(e=yield this.request.get(this.attachCount(di.DEFAULT_TIME_SOURCE)))==null?void 0:e.data}catch(t){console.log("GetServerTime error",t)}return r})}calculateOffset(r,e,t){return t-(e-(e-r)/2)}fixRequestStartTime(){let r=0,e=performance.getEntriesByName(this.attachCount(di.DEFAULT_TIME_SOURCE),"resource");if(e!=null&&e.length)if(e.length>1)console.warn("multiple resource entries found");else try{const t=e[0];r=t.requestStart-t.startTime,t.domainLookupEnd,t.domainLookupStart,t.secureConnectionStart,t.connectStart,t.requestStart,t.secureConnectionStart}catch(t){console.log(t)}else console.warn("no resource entry found"),window.RTS_DISABLE_CLEAR_RESOURCE_TIMINGS||performance.clearResourceTimings();return Math.max(0,r||0)}attachCount(r){return`${r}&count=${this.random}_${this.attemptCount}`}};ds.DEFAULT_TIME_SOURCE="https://time.akamai.com/?iso&ms",ds.DEFAULT_ATTEMPT_INTERVAL=3e4,ds.DEFAULT_ATTEMPT_RETRY_INTERVAL=5e3;let Rp=ds;const xt=class Vi{static createClient(r){let e=r||{};return e.customReporter||(e.customReporter=Vi.customReporter),e.trackLog===void 0&&(e.trackLog=Vi.trackLog),bi.setContext(e),new vp(e)}static getMicList(){return new Promise((r,e)=>{this.deviceManager.getMicList().then(t=>{r(t)}).catch(t=>{e(t)})})}static getCameraList(){return new Promise((r,e)=>{this.deviceManager.getCameraList().then(t=>{r(t)}).catch(t=>{e(t)})})}static getSpeakerList(){return new Promise((r,e)=>{this.deviceManager.getSpeakerList().then(t=>{r(t)}).catch(t=>{e(t)})})}static createStream(r){return new Promise((e,t)=>{let i=new qh,n=new rs({customReporter:Vi.customReporter,trackLog:Vi.trackLog});i.init(r).then(()=>{e(i),n.reportStreamCreated(r,{videoTrack:!!i.videoTrack,audioTrack:!!i.audioTrack,screenAudio:!!i.screenAudioTrack,surface:i.screenSurfaceType})}).catch(a=>{const c=Q(D({},a),{relatedLink:a.extraInfo});delete c.extraInfo,t(c),n.reportErrorInfo(H.ERROR_INIT_LOCAL_FAIL,a.message,a.traceId,{config:r,originErr:a})})})}};xt.deviceManager=new Gi.BrowserDeviceManager,xt.BrowserUtil=G.BrowserUtil,xt.SystenUtil=G.SystemUtil,xt.SupportUtil=Dr,xt.Clock=Rp,xt.VideoProfileMap=me,xt.ScreenProfileMap=mr,xt.AudioProfileMap=Xr,xt.ErrorCode=H,xt.customReporter=()=>{},xt.trackLog=!0;let Pe=xt;window&&(window.AliRTS=Pe);for(var on,pt=[],cn=0;cn<256;++cn)pt.push((cn+256).toString(16).slice(1));var Ep=new Uint8Array(16);function yp(){if(!on&&!(on=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return on(Ep)}const Dd={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Vt(s,r,e){if(Dd.randomUUID&&!r&&!s)return Dd.randomUUID();var t=(s=s||{}).random||(s.rng||yp)();if(t[6]=15&t[6]|64,t[8]=63&t[8]|128,r){e=e||0;for(var i=0;i<16;++i)r[e+i]=t[i];return r}return function(n,a=0){return(pt[n[a+0]]+pt[n[a+1]]+pt[n[a+2]]+pt[n[a+3]]+"-"+pt[n[a+4]]+pt[n[a+5]]+"-"+pt[n[a+6]]+pt[n[a+7]]+"-"+pt[n[a+8]]+pt[n[a+9]]+"-"+pt[n[a+10]]+pt[n[a+11]]+pt[n[a+12]]+pt[n[a+13]]+pt[n[a+14]]+pt[n[a+15]]).toLowerCase()}(t)}var Tp=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g,Cp=/\b(?:[A-Z]{1,3}[A-Z][TC])(?:[-+]\d{4})?|((?:Australian )?(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time)\b/g,_p=/[^-+\dA-Z]/g;function dn(s,r,e,t){if(arguments.length!==1||typeof s!="string"||/\d/.test(s)||(r=s,s=void 0),(s=s||s===0?s:new Date)instanceof Date||(s=new Date(s)),isNaN(s))throw TypeError("Invalid date");var i=(r=String(kd[r]||r||kd.default)).slice(0,4);i!=="UTC:"&&i!=="GMT:"||(r=r.slice(4),e=!0,i==="GMT:"&&(t=!0));var n=function(){return e?"getUTC":"get"},a=function(){return s[n()+"Date"]()},c=function(){return s[n()+"Day"]()},o=function(){return s[n()+"Month"]()},l=function(){return s[n()+"FullYear"]()},d=function(){return s[n()+"Hours"]()},h=function(){return s[n()+"Minutes"]()},u=function(){return s[n()+"Seconds"]()},p=function(){return s[n()+"Milliseconds"]()},f=function(){return e?0:s.getTimezoneOffset()},m=function(){return wp(s)},g={d:function(){return a()},dd:function(){return Mt(a())},ddd:function(){return Ct.dayNames[c()]},DDD:function(){return Md({y:l(),m:o(),d:a(),_:n(),dayName:Ct.dayNames[c()],short:!0})},dddd:function(){return Ct.dayNames[c()+7]},DDDD:function(){return Md({y:l(),m:o(),d:a(),_:n(),dayName:Ct.dayNames[c()+7]})},m:function(){return o()+1},mm:function(){return Mt(o()+1)},mmm:function(){return Ct.monthNames[o()]},mmmm:function(){return Ct.monthNames[o()+12]},yy:function(){return String(l()).slice(2)},yyyy:function(){return Mt(l(),4)},h:function(){return d()%12||12},hh:function(){return Mt(d()%12||12)},H:function(){return d()},HH:function(){return Mt(d())},M:function(){return h()},MM:function(){return Mt(h())},s:function(){return u()},ss:function(){return Mt(u())},l:function(){return Mt(p(),3)},L:function(){return Mt(Math.floor(p()/10))},t:function(){return d()<12?Ct.timeNames[0]:Ct.timeNames[1]},tt:function(){return d()<12?Ct.timeNames[2]:Ct.timeNames[3]},T:function(){return d()<12?Ct.timeNames[4]:Ct.timeNames[5]},TT:function(){return d()<12?Ct.timeNames[6]:Ct.timeNames[7]},Z:function(){return t?"GMT":e?"UTC":Ip(s)},o:function(){return(f()>0?"-":"+")+Mt(100*Math.floor(Math.abs(f())/60)+Math.abs(f())%60,4)},p:function(){return(f()>0?"-":"+")+Mt(Math.floor(Math.abs(f())/60),2)+":"+Mt(Math.floor(Math.abs(f())%60),2)},S:function(){return["th","st","nd","rd"][a()%10>3?0:(a()%100-a()%10!=10)*a()%10]},W:function(){return m()},WW:function(){return Mt(m())},N:function(){return Ap(s)}};return r.replace(Tp,function(S){return S in g?g[S]():S.slice(1,S.length-1)})}var kd={default:"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",paddedShortDate:"mm/dd/yyyy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:sso",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",expiresHeaderFormat:"ddd, dd mmm yyyy HH:MM:ss Z"},Ct={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],timeNames:["a","p","am","pm","A","P","AM","PM"]},Mt=function(s){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return String(s).padStart(r,"0")},Md=function(s){var r=s.y,e=s.m,t=s.d,i=s._,n=s.dayName,a=s.short,c=a!==void 0&&a,o=new Date,l=new Date;l.setDate(l[i+"Date"]()-1);var d=new Date;return d.setDate(d[i+"Date"]()+1),o[i+"FullYear"]()===r&&o[i+"Month"]()===e&&o[i+"Date"]()===t?c?"Tdy":"Today":l[i+"FullYear"]()===r&&l[i+"Month"]()===e&&l[i+"Date"]()===t?c?"Ysd":"Yesterday":d[i+"FullYear"]()===r&&d[i+"Month"]()===e&&d[i+"Date"]()===t?c?"Tmw":"Tomorrow":n},wp=function(s){var r=new Date(s.getFullYear(),s.getMonth(),s.getDate());r.setDate(r.getDate()-(r.getDay()+6)%7+3);var e=new Date(r.getFullYear(),0,4);e.setDate(e.getDate()-(e.getDay()+6)%7+3);var t=r.getTimezoneOffset()-e.getTimezoneOffset();r.setHours(r.getHours()-t);var i=(r-e)/6048e5;return 1+Math.floor(i)},Ap=function(s){var r=s.getDay();return r===0&&(r=7),r},Ip=function(s){return(String(s).match(Cp)||[""]).pop().replace(_p,"").replace(/GMT\+0000/g,"UTC")},qr=(s=>(s.prod="rs.rtn.aliyuncs.com",s.pre="prs.rtn.aliyuncs.com",s))(qr||{});const ls="7.3.0-beta.2";class ze{static getVersionNumber(){let r=ls.split("."),e="";return r.forEach(t=>{t.length===1?e+="0"+t:e+=t}),parseInt(e)}static queryingParam(r){let e=[];if(r)for(let t in r)e.push(t+"="+r[t]);return e.join("&")}static getQueryParams(r){const e=window.location.search.substring(1).split("&");for(let t=0;t<e.length;t++){const i=e[t].split("=");if(decodeURIComponent(i[0])===r)return decodeURIComponent(i[1])}}static createCallid(r=""){const e=Vt();return r&&e&&e.length>r.length?`${r}${e.substring(r.length)}`:e}static checkSubOptionsValid(r){if(r){const{audio:e,video:t,screen:i}=r;if(e===!1&&t===!1&&i===!1)return!1}return!0}static isNetworkAvailable(){return _(this,null,function*(){const r=qr.prod,{onLine:e}=navigator;if(!e)return!1;try{return yield fetch(`https://${r}/roomserver/v1/ws/version`),!0}catch(t){return!1}})}static toString(r){let e;if(r instanceof Error)e=r.message;else if(typeof r=="string")e=r;else try{e=JSON.stringify(r)}catch(t){e="undefined"}return e}static paramArrayToString(r){let e="";for(let t=0;t<r.length;t++)e!==""&&(e+=" "),e+=ze.toString(r[t]);return e}static removeQueryString(r){if(!r)return r;let e=r.indexOf("?");return e>0?r.substring(0,e):r}}const{BrowserUtil:Pp}=Pe,Dp="EdgeHTML",Od="Blink",kp="Trident",Mp="Gecko",Op="WebKit",hs=(s,r)=>{const e=r.match(s);return e&&e.length>0&&e[1]||""},Np=[{test:[/\sedg\//i,[/edg([ea]|ios)/i]],describe(s){if(/\sedg\//i.test(s))return{name:Od};const r=hs(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:Dp,version:r}}},{test:[/trident/i],describe(s){const r={name:kp},e=hs(/trident\/(\d+(\.?_?\d+)+)/i,s);return e&&(r.version=e),r}},{test(s){const r=/gecko/i.test(s),e=/like gecko/i.test(s);return r&&!e},describe(s){const r={name:Mp},e=hs(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(r.version=e),r}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:Od})},{test:[/(apple)?webkit/i],describe(s){const r={name:Op},e=hs(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(r.version=e),r}}],ln=(s,r)=>s.find(e=>typeof e.test=="function"?e.test(r):Array.isArray(e.test)?e.test.some(t=>typeof t=="string"?r.indexOf(t)>-1:t instanceof RegExp&&t.test(r)):void 0),Lp=()=>{try{const s=navigator.userAgent||"",r=ln(Np,s);if(r){const e=r.describe(s);return`${e.name}/${e.version||Pp.browserVersion}`}}catch(s){}return navigator.userAgent},xp=[{test:["wow64","win64","x64"],describe:()=>"amd64"},{test:["i686","x86"],describe:()=>"x86"},{test:["aarch64","arm64"],describe:()=>"arm64"},{test:["arm"],describe:()=>"arm"}],Nd=()=>{let s="unknown";try{const r=navigator.userAgent||"",e=ln(xp,r);if(!e)return s;s=e.describe(r)}catch(r){}return s},Vp=[{test:[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],describe:()=>"Samsung"},{test:[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i,/\((ipad);[-\w\),; ]+apple/i,/(macintosh);/i],describe:()=>"Apple"},{test:[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],describe:()=>"Huawei"},{test:[/(?:honor)([-\w ]+)[;\)]/i],describe:()=>"Honor"},{test:[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],describe:()=>"Xiaomi"},{test:[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],describe:()=>"Oppo"},{test:[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],describe:()=>"Vivo"},{test:[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],describe:()=>"Realme"},{test:[/(pixel c)\b/i,/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],describe:()=>"Google"},{test:[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],describe:()=>"ZTE"},{test:[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],describe:()=>"Meizu"}],Up=()=>{let s="Unknown";try{const r=navigator.userAgent||"",e=ln(Vp,r);if(!e)return s;s=e.describe(r)}catch(r){}return s};class Bp{constructor(r){this.total=0,this.count=0,this.peddings=[],this.total=r}append(r){this.peddings.push(r),this.run()}run(){if(!this.peddings.length||this.count>=this.total)return;const r=this.peddings.shift();r&&(this.count++,r().finally(()=>{this.count--,this.run()}))}}class Ld{constructor(r){var e,t,i;this.timer=null,this.time=10,this.count=10,this.arr=[],this.time=(e=r.time)!=null?e:10,this.count=(t=r.count)!=null?t:10,this.ccController=new Bp((i=r.maxReqCount)!=null?i:10),r.host.startsWith("http://")||r.host.startsWith("https://")?this.url=r.host+"/logstores/"+r.logstore+"/track":this.url="https://"+r.project+"."+r.host+"/logstores/"+r.logstore+"/track",this.opt=r,r.installUnloadHook&&typeof r.installUnloadHook=="function"&&r.installUnloadHook(()=>{this.sendImmediateInner()})}assemblePayload(r){const e={__logs__:r};return this.opt.tags&&(e.__tags__=this.opt.tags),this.opt.topic&&(e.__topic__=this.opt.topic),this.opt.source&&(e.__source__=this.opt.source),JSON.stringify(e)}platformSend(){if(this.opt.sendPayload&&typeof this.opt.sendPayload=="function"){const r=this.assemblePayload(this.arr);this.ccController.append(()=>this.opt.sendPayload(this.url,r))}}transString(r){let e={};for(let t in r)typeof r[t]=="object"?e[t]=JSON.stringify(r[t]):e[t]=String(r[t]);return e}sendImmediateInner(){this.arr&&this.arr.length>0&&(this.platformSend(),this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.arr=[])}sendInner(){if(this.timer)this.arr.length>=this.count&&(clearTimeout(this.timer),this.timer=null,this.sendImmediateInner());else{const r=this;this.arr.length>=this.count||this.time<=0?this.sendImmediateInner():this.timer=setTimeout(function(){r.sendImmediateInner()},1e3*this.time)}}send(r){const e=this.transString(r);this.arr.push(e),this.sendInner()}sendImmediate(r){const e=this.transString(r);this.arr.push(e),this.sendImmediateInner()}sendBatchLogs(r){const e=r.map(t=>this.transString(t));this.arr.push(...e),this.sendInner()}sendBatchLogsImmediate(r){const e=r.map(t=>this.transString(t));this.arr.push(...e),this.sendImmediateInner()}overwriteTransString(r){this.transString=r.transString}getOpt(){return this.opt}}function xd(s,r){return new Promise((e,t)=>{const i=new window.XMLHttpRequest;i.onload=()=>{i.status>=200&&i.status<300?e():t(new Error(`HTTP ${i.status}: ${i.statusText}`))},i.onerror=()=>{t(new Error("Network error occurred"))},i.ontimeout=()=>{t(new Error("Request timeout"))},i.timeout=1e4,i.open("POST",`${s}?APIVersion=0.6.0`,!0),i.send(r)})}function Fp(s,r,e=!1){return _(this,null,function*(){try{if(e||r.length>=32768)return void(yield xd(s,r));(function(t,i){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${t}?APIVersion=0.6.0`,i)})(s,r)||(yield xd(s,r))}catch(t){const i=t instanceof Error?t:new Error(String(t));throw window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
208
+ `+i.message),console.error("Failed log data:",s)),i}})}let Hp=class extends Ld{constructor(r){const f=r,{maxRetries:e=10,retryDelay:t=2e3,backoffMultiplier:i=2,maxRetryDelay:n=3e5,enableLocalStorage:a=!0,maxStorageSize:c=1e3,storageKey:o="artc_reliable_logs",enableNetworkMonitor:l=!0,onNetworkChange:d=()=>{},forceXhrMode:h=!0,debug:u=!1}=f,p=jt(f,["maxRetries","retryDelay","backoffMultiplier","maxRetryDelay","enableLocalStorage","maxStorageSize","storageKey","enableNetworkMonitor","onNetworkChange","forceXhrMode","debug"]);super(Object.assign({},p,{installUnloadHook:m=>{window.addEventListener("beforeunload",()=>{this.saveFailedLogs(),m()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.saveFailedLogs()})},sendPayload:(m,g)=>_(this,null,function*(){return Promise.resolve()})}));b(this,"reliableConfig");b(this,"failedLogs",new Map);b(this,"networkStatus","online");b(this,"retryTimer",null);b(this,"originalSendPayload",null);this.reliableConfig={maxRetries:e,retryDelay:t,backoffMultiplier:i,maxRetryDelay:n,enableLocalStorage:a,maxStorageSize:c,storageKey:o,enableNetworkMonitor:l,onNetworkChange:d,forceXhrMode:h,debug:u},this.originalSendPayload=(m,g)=>_(this,null,function*(){return Fp(m,g,h)}),this.getOpt().sendPayload=(m,g)=>_(this,null,function*(){return this.reliableSendAsync(m,g)}),this.initNetworkMonitor(),this.loadFailedLogs(),this.startRetryTimer()}reliableSendAsync(r,e){return _(this,null,function*(){const t=this.generateId();try{yield Promise.resolve(this.originalSendPayload(r,e)),this.debug(`Log ${t} sent successfully`)}catch(i){this.debug(`Log ${t} failed, adding to retry queue:`,i),this.addToFailedQueue(t,r,e,i)}})}addToFailedQueue(r,e,t,i){const n={id:r,data:{error:i.message},timestamp:Date.now(),retryCount:0,lastRetryTime:0,url:e,payload:t};this.failedLogs.set(r,n),this.scheduleRetry(n)}scheduleRetry(r){if(r.retryCount>=this.reliableConfig.maxRetries)return this.debug(`Log ${r.id} exceeded max retries, removing from queue`),void this.failedLogs.delete(r.id);const e=Math.min(this.reliableConfig.retryDelay*Math.pow(this.reliableConfig.backoffMultiplier,r.retryCount),this.reliableConfig.maxRetryDelay);this.debug(`Scheduling retry for log ${r.id} in ${e}ms (attempt ${r.retryCount+1}/${this.reliableConfig.maxRetries})`),setTimeout(()=>{this.retryLog(r)},e)}retryLog(r){return _(this,null,function*(){if(this.failedLogs.has(r.id)){r.retryCount++,r.lastRetryTime=Date.now();try{if(this.networkStatus==="offline")return this.debug(`Log ${r.id} retry skipped - network offline`),void this.scheduleRetry(r);yield this.originalSendPayload(r.url,r.payload),this.debug(`Log ${r.id} retry successful`),this.failedLogs.delete(r.id)}catch(e){this.debug(`Log ${r.id} retry failed:`,e),this.scheduleRetry(r)}}})}initNetworkMonitor(){this.reliableConfig.enableNetworkMonitor&&typeof window!="undefined"&&(this.networkStatus=navigator.onLine?"online":"offline",window.addEventListener("online",()=>{this.handleNetworkChange("online")}),window.addEventListener("offline",()=>{this.handleNetworkChange("offline")}),this.debug(`Network monitor initialized. Current status: ${this.networkStatus}`))}handleNetworkChange(r){const e=this.networkStatus;this.networkStatus=r,this.debug(`Network status changed: ${e} -> ${r}`),this.reliableConfig.onNetworkChange(r==="online"),r==="online"&&e==="offline"&&(this.debug("Network recovered, retrying failed logs"),this.retryAllFailedLogs())}retryAllFailedLogs(){this.failedLogs.size!==0&&(this.debug(`Retrying ${this.failedLogs.size} failed logs after network recovery`),Array.from(this.failedLogs.values()).forEach(r=>{setTimeout(()=>this.retryLog(r),100*Math.random())}))}startRetryTimer(){typeof window!="undefined"&&(this.retryTimer=window.setInterval(()=>{if(this.failedLogs.size>0&&this.networkStatus==="online"){const r=Date.now();Array.from(this.failedLogs.values()).forEach(e=>{r-e.lastRetryTime>this.reliableConfig.retryDelay&&this.retryLog(e)})}},this.reliableConfig.retryDelay),this.debug(`Retry timer started with interval ${this.reliableConfig.retryDelay}ms`))}loadFailedLogs(){if(this.reliableConfig.enableLocalStorage&&typeof localStorage!="undefined")try{const r=localStorage.getItem(this.reliableConfig.storageKey);if(r){const e=JSON.parse(r);e.forEach(t=>{this.failedLogs.set(t.id,t)}),this.debug(`Loaded ${e.length} failed logs from storage`),localStorage.removeItem(this.reliableConfig.storageKey),this.networkStatus==="online"&&this.retryAllFailedLogs()}}catch(r){this.debug("Failed to load failed logs from storage:",r)}}saveFailedLogs(){if(this.reliableConfig.enableLocalStorage&&typeof localStorage!="undefined"&&this.failedLogs.size!==0)try{const r=Array.from(this.failedLogs.values()).slice(-this.reliableConfig.maxStorageSize);localStorage.setItem(this.reliableConfig.storageKey,JSON.stringify(r)),this.debug(`Saved ${r.length} failed logs to storage`)}catch(r){this.debug("Failed to save failed logs to storage:",r)}}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}debug(...r){this.reliableConfig.debug&&typeof console!="undefined"&&console.log("[ReliableWebTracker]",...r)}useStsPlugin(r){this.originalSendPayload=(e,t)=>_(this,null,function*(){return function(i,n,a){return _(this,null,function*(){try{i=i.slice(0,-6);const{data:c,header:o}=yield a.process(i,n);return new Promise((l,d)=>{const h=new window.XMLHttpRequest;h.onload=()=>{h.status>=200&&h.status<300?l():d(new Error(`HTTP ${h.status}: ${h.statusText}`))},h.onerror=()=>{d(new Error("Network error occurred"))},h.ontimeout=()=>{d(new Error("Request timeout"))},h.timeout=1e4,h.open("POST",i,!0);for(let u in o)h.setRequestHeader(u,o[u]);h.send(c)})}catch(c){const o=c instanceof Error?c:new Error(String(c));throw window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
209
+ `+o.message),console.error("Failed log data:",i)),o}})}(e,t,r)}),this.getOpt().sendPayload=(e,t)=>_(this,null,function*(){return this.reliableSendAsync(e,t)}),this.overwriteTransString(r)}getStatus(){return{networkStatus:this.networkStatus,failedLogsCount:this.failedLogs.size,isRetryActive:this.retryTimer!==null,config:this.reliableConfig}}retryAll(){this.debug("Manual retry triggered"),this.retryAllFailedLogs()}clearFailedLogs(){const r=this.failedLogs.size;this.failedLogs.clear(),this.debug(`Cleared ${r} failed logs`)}getFailedLogs(){return Array.from(this.failedLogs.values())}destroy(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),this.saveFailedLogs(),this.failedLogs.clear(),this.debug("WebTrackerBrowser destroyed")}};const{BrowserUtil:Vd,SystenUtil:Ud}=Pe,Wp=Nd(),us=6e5,ps={host:"cn-hangzhou.log.aliyuncs.com",project:"alivc-aio",logstore:"logger",time:10,count:10};function hn(){return dn(new Date,"HH:MM:ss.l")}function Bd(){return dn(new Date,"isoDate")}var un=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.API=2]="API",s[s.WARNING=3]="WARNING",s[s.ERROR=4]="ERROR",s[s.NONE=5]="NONE",s))(un||{});class jp{constructor(){b(this,"tracker");b(this,"stsPlugin");b(this,"stsData");b(this,"stsExpiration",Date.now());b(this,"clientId",Vt());b(this,"bSesid",Vt());b(this,"logLevel",3);b(this,"appId","");b(this,"sessionId","");b(this,"logCache",[]);b(this,"updateTaskTimer");b(this,"endReported",!0);b(this,"logSequence",0);b(this,"sendLogBeforeUnload",r=>_(this,null,function*(){if(!this.stsPlugin)return;this.logSequence+=1,r.unshift(this.getLogParams(710203,{log:`[${Bd()} ${hn()}] [INF] beforeunload`,stat_log_seq:this.logSequence}));const e=`https://${ps.project}.${ps.host}/logstores/${ps.logstore}`,t={__logs__:r.map(a=>this.stsPlugin.transString(a))},{data:i,header:n}=yield this.stsPlugin.process(e,JSON.stringify(t));fetch(e,{keepalive:!0,method:"POST",headers:n,body:i})}));b(this,"logMethod",(r,e=console.log)=>(...t)=>{let i=hn();this.logLevel<=r&&e(i,...t);let n=ze.paramArrayToString(t);r>0&&this.addLog(n)});b(this,"d",this.logMethod(0,console.debug));b(this,"i",this.logMethod(1));b(this,"w",this.logMethod(3,console.warn));b(this,"e",this.logMethod(4,(...r)=>{const[e,...t]=r;console.error(e,"<error>",t)}));b(this,"ev",this.logMethod(2));b(this,"a",this.logMethod(2,(...r)=>{const[e,...t]=r;if(t.length>2){const i=`${t[1]}`;i.startsWith("__g__")&&console.group(`${i.substring(5)}_${t[2]}`)}console.log(e,...t)}));b(this,"ar",this.logMethod(2,(...r)=>{const[e,...t]=r;console.log(e,...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));b(this,"ae",this.logMethod(2,(...r)=>{const[e,...t]=r;console.error(e,"<error>",...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));window.addEventListener("beforeunload",()=>{this.reportEnd(!0)})}init(){this.reset(),this.startSTSUpdateTask()}destroy(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer)}reset(){this.bSesid=Vt(),this.endReported=!0,this.logSequence=0,this.appId="",this.sessionId=""}startSTSUpdateTask(){return _(this,null,function*(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer);try{const r=yield this.refreshSTSToken();this.createTracker(r)}catch(r){}this.updateTaskTimer=setTimeout(()=>{this.startSTSUpdateTask()},us)})}refreshSTSToken(){return _(this,null,function*(){if(!this.stsData||this.stsExpiration<=Date.now()+us){const r=yield this.requestSTSToken(),e=new Date(r==null?void 0:r.Expiration).getTime()||0,t=Date.now()+us;this.stsExpiration=Math.max(e,t),this.stsData=r}return this.stsData})}requestSTSToken(){const r=Date.now(),e=`${this.clientId}|woMMssV6jmyol9fr|${r}`,t={Action:"AssumeSlsRoleV2",AuthInfo:ui.MD5(e).toString(ui.enc.Hex),ClientId:this.clientId,BusinessType:"logger",AppVersion:"1.0",Version:"2017-03-14",AuthTimestamp:`${r}`,TerminalType:"web",DeviceModel:"",Format:"JSON",SignatureMethod:"HMAC-SHA1",SignatureVersion:"1.0",Timestamp:dn(r,"isoUtcDateTime")},i=new URLSearchParams(t).toString();return fetch(`https://slsrole.alicdn.com/?${i}`).then(n=>n.json()).then(n=>JSON.parse(window.atob(n.SlsAuthResult)))}createTracker(r){if(!this.tracker){const e={accessKeyId:r.AccessKeyId,accessKeySecret:r.AccessKeySecret,securityToken:r.SecurityToken,refreshSTSTokenInterval:us,stsTokenFreshTime:void 0,refreshSTSToken:()=>{this.refreshSTSToken().then(n=>{e.accessKeyId=n.AccessKeyId,e.accessKeySecret=n.AccessKeySecret,e.securityToken=n.SecurityToken}).catch(()=>{})}},t=new Hp(ps),i=Ps(e);t.useStsPlugin(i),this.stsPlugin=i,this.tracker=t,this.reportStartAndCache()}}changeConfig(r){r.logLevel!==void 0&&r.logLevel>=0&&r.logLevel<=5&&(this.logLevel=r.logLevel)}setSessionID(r,e){r&&e&&(this.appId=r,this.sessionId=e,this.reportStartAndCache())}reportStartAndCache(){if(!this.tracker||!this.sessionId)return;this.endReported=!1;const r={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},e=[this.getLogParams(710201,r),this.getLogParams(710202,r)];this.tracker.sendBatchLogsImmediate(e),this.logCache.forEach(t=>{this.sendLog(t)})}reportEnd(r=!1){if(!this.tracker||!this.sessionId||this.endReported)return void this.reset();const e={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},t=[this.getLogParams(710204,e),this.getLogParams(710205,e)];r?this.sendLogBeforeUnload(t):(this.tracker.sendBatchLogsImmediate(t),this.endReported=!0),this.reset()}getLogParams(r,e){return D({appid:`${window.location.host}`,appid_list:this.appId,appver:"",b_sesid:this.bSesid,biz_type:"rtc",cpu_info:Wp,db:Vd.browserName,dm:Vd.browserVersion,install_uuid:this.clientId,logger_v:"0.0.1",os:Ud.systemName,osv:Ud.systemVersion,p_sesid:this.bSesid,sdk_version:ls,sdkname:"AliRTCSdk",stm:Date.now(),tar_pf:"web",traceid:this.sessionId,event_id:r},e||{})}sendLog(r){if(!this.tracker||!this.sessionId)return;this.logSequence+=1;const e=this.getLogParams(710203,{log:r,stat_log_seq:this.logSequence});this.tracker.send(e)}addLog(r){const e=hn(),t=`[${Bd()} ${e}] ${r}`;this.sessionId&&this.tracker?this.sendLog(t):(this.logCache.push(t),this.logCache.length>=200&&this.logCache.shift())}}class O{static getLogger(){return this.logger||(this.logger=new jp),this.logger}static init(){this.getLogger().init()}static destroy(){this.getLogger().destroy()}static setLogLevel(r){this.getLogger().changeConfig({logLevel:r})}static setSessionID(r,e){this.getLogger().setSessionID(r,e)}static reportEnd(){this.getLogger().reportEnd()}static interface(...r){this.getLogger().a("[API]",...r)}static interfaceResult(r,e,t,...i){t?this.getLogger().ar("[ARE]",r,e,...i):this.getLogger().ae("[ARE]",r,e,...i)}static event(...r){this.getLogger().ev("[EVT]",...r)}static debug(...r){this.getLogger().d("[DBG]",...r)}static info(...r){this.getLogger().i("[INF]",...r)}static warn(...r){this.getLogger().w("[WARN]",...r)}static error(...r){this.getLogger().e("[ERR]",...r)}}b(O,"logger");var pn={exports:{}};(function(s,r){(function(e,t){var i="function",n="undefined",a="object",c="string",o="major",l="model",d="name",h="type",u="vendor",p="version",f="architecture",m="console",g="mobile",S="tablet",v="smarttv",E="wearable",T="embedded",R="Amazon",y="Apple",C="ASUS",w="BlackBerry",A="Browser",P="Chrome",M="Firefox",I="Google",j="Huawei",K="LG",B="Microsoft",F="Motorola",X="Opera",$="Samsung",se="Sharp",N="Sony",V="Xiaomi",x="Zebra",U="Facebook",ce="Chromium OS",ue="Mac OS",te=" Browser",Re=function(Se){for(var le={},ae=0;ae<Se.length;ae++)le[Se[ae].toUpperCase()]=Se[ae];return le},He=function(Se,le){return typeof Se===c&&Ve(le).indexOf(Ve(Se))!==-1},Ve=function(Se){return Se.toLowerCase()},je=function(Se,le){if(typeof Se===c)return Se=Se.replace(/^\s\s*/,""),typeof le===n?Se:Se.substring(0,500)},_e=function(Se,le){for(var ae,Ie,Ze,Te,at,re,dt=0;dt<le.length&&!at;){var It=le[dt],Ke=le[dt+1];for(ae=Ie=0;ae<It.length&&!at&&It[ae];)if(at=It[ae++].exec(Se))for(Ze=0;Ze<Ke.length;Ze++)re=at[++Ie],typeof(Te=Ke[Ze])===a&&Te.length>0?Te.length===2?typeof Te[1]==i?this[Te[0]]=Te[1].call(this,re):this[Te[0]]=Te[1]:Te.length===3?typeof Te[1]!==i||Te[1].exec&&Te[1].test?this[Te[0]]=re?re.replace(Te[1],Te[2]):t:this[Te[0]]=re?Te[1].call(this,re,Te[2]):t:Te.length===4&&(this[Te[0]]=re?Te[3].call(this,re.replace(Te[1],Te[2])):t):this[Te]=re||t;dt+=2}},Ue=function(Se,le){for(var ae in le)if(typeof le[ae]===a&&le[ae].length>0){for(var Ie=0;Ie<le[ae].length;Ie++)if(He(le[ae][Ie],Se))return ae==="?"?t:ae}else if(He(le[ae],Se))return ae==="?"?t:ae;return le.hasOwnProperty("*")?le["*"]:Se},ye={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Ge={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[p,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[p,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,p],[/opios[\/ ]+([\w\.]+)/i],[p,[d,X+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[p,[d,X+" GX"]],[/\bopr\/([\w\.]+)/i],[p,[d,X]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[p,[d,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[p,[d,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[d,p],[/quark(?:pc)?\/([-\w\.]+)/i],[p,[d,"Quark"]],[/\bddg\/([\w\.]+)/i],[p,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[p,[d,"UC"+A]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[p,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[p,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[p,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[p,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[p,[d,"Smart Lenovo "+A]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+A],p],[/\bfocus\/([\w\.]+)/i],[p,[d,M+" Focus"]],[/\bopt\/([\w\.]+)/i],[p,[d,X+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[p,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[p,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[p,[d,X+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[p,[d,"MIUI"+te]],[/fxios\/([\w\.-]+)/i],[p,[d,M]],[/\bqihoobrowser\/?([\w\.]*)/i],[p,[d,"360"]],[/\b(qq)\/([\w\.]+)/i],[[d,/(.+)/,"$1Browser"],p],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1"+te],p],[/samsungbrowser\/([\w\.]+)/i],[p,[d,$+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[p,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],p],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[d,p],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[d],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[p,d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,U],p],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[d,p],[/\bgsa\/([\w\.]+) .*safari\//i],[p,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[p,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[p,[d,P+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,P+" WebView"],p],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[p,[d,"Android "+A]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,p],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[p,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[p,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[p,Ue,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[d,p],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],p],[/(wolvic|librewolf)\/([\w\.]+)/i],[d,p],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[p,[d,M+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[d,[p,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[d,[p,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[f,"amd64"]],[/(ia32(?=;))/i],[[f,Ve]],[/((?:i[346]|x)86)[;\)]/i],[[f,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[f,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[f,"armhf"]],[/windows (ce|mobile); ppc;/i],[[f,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[f,/ower/,"",Ve]],[/(sun4\w)[;\)]/i],[[f,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[f,Ve]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[l,[u,$],[h,S]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[l,[u,$],[h,g]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[l,[u,y],[h,g]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[l,[u,y],[h,S]],[/(macintosh);/i],[l,[u,y]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[l,[u,se],[h,g]],[/(?:honor)([-\w ]+)[;\)]/i],[l,[u,"Honor"],[h,g]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[l,[u,j],[h,S]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[l,[u,j],[h,g]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[l,/_/g," "],[u,V],[h,g]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[l,/_/g," "],[u,V],[h,S]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[l,[u,"OPPO"],[h,g]],[/\b(opd2\d{3}a?) bui/i],[l,[u,"OPPO"],[h,S]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[l,[u,"Vivo"],[h,g]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[l,[u,"Realme"],[h,g]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[l,[u,F],[h,g]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[l,[u,F],[h,S]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[l,[u,K],[h,S]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[l,[u,K],[h,g]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[l,[u,"Lenovo"],[h,S]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[l,/_/g," "],[u,"Nokia"],[h,g]],[/(pixel c)\b/i],[l,[u,I],[h,S]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[l,[u,I],[h,g]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[l,[u,N],[h,g]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[l,"Xperia Tablet"],[u,N],[h,S]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[l,[u,"OnePlus"],[h,g]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[l,[u,R],[h,S]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[l,/(.+)/g,"Fire Phone $1"],[u,R],[h,g]],[/(playbook);[-\w\),; ]+(rim)/i],[l,u,[h,S]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[l,[u,w],[h,g]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[l,[u,C],[h,S]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[l,[u,C],[h,g]],[/(nexus 9)/i],[l,[u,"HTC"],[h,S]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[u,[l,/_/g," "],[h,g]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[l,[u,"TCL"],[h,S]],[/(itel) ((\w+))/i],[[u,Ve],l,[h,Ue,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[l,[u,"Acer"],[h,S]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[l,[u,"Meizu"],[h,g]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[l,[u,"Ulefone"],[h,g]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[l,[u,"Energizer"],[h,g]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[l,[u,"Cat"],[h,g]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[l,[u,"Smartfren"],[h,g]],[/droid.+; (a(?:015|06[35]|142p?))/i],[l,[u,"Nothing"],[h,g]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[u,l,[h,g]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[u,l,[h,S]],[/(surface duo)/i],[l,[u,B],[h,S]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[l,[u,"Fairphone"],[h,g]],[/(u304aa)/i],[l,[u,"AT&T"],[h,g]],[/\bsie-(\w*)/i],[l,[u,"Siemens"],[h,g]],[/\b(rct\w+) b/i],[l,[u,"RCA"],[h,S]],[/\b(venue[\d ]{2,7}) b/i],[l,[u,"Dell"],[h,S]],[/\b(q(?:mv|ta)\w+) b/i],[l,[u,"Verizon"],[h,S]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[l,[u,"Barnes & Noble"],[h,S]],[/\b(tm\d{3}\w+) b/i],[l,[u,"NuVision"],[h,S]],[/\b(k88) b/i],[l,[u,"ZTE"],[h,S]],[/\b(nx\d{3}j) b/i],[l,[u,"ZTE"],[h,g]],[/\b(gen\d{3}) b.+49h/i],[l,[u,"Swiss"],[h,g]],[/\b(zur\d{3}) b/i],[l,[u,"Swiss"],[h,S]],[/\b((zeki)?tb.*\b) b/i],[l,[u,"Zeki"],[h,S]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[u,"Dragon Touch"],l,[h,S]],[/\b(ns-?\w{0,9}) b/i],[l,[u,"Insignia"],[h,S]],[/\b((nxa|next)-?\w{0,9}) b/i],[l,[u,"NextBook"],[h,S]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[u,"Voice"],l,[h,g]],[/\b(lvtel\-)?(v1[12]) b/i],[[u,"LvTel"],l,[h,g]],[/\b(ph-1) /i],[l,[u,"Essential"],[h,g]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[l,[u,"Envizen"],[h,S]],[/\b(trio[-\w\. ]+) b/i],[l,[u,"MachSpeed"],[h,S]],[/\btu_(1491) b/i],[l,[u,"Rotor"],[h,S]],[/(shield[\w ]+) b/i],[l,[u,"Nvidia"],[h,S]],[/(sprint) (\w+)/i],[u,l,[h,g]],[/(kin\.[onetw]{3})/i],[[l,/\./g," "],[u,B],[h,g]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[l,[u,x],[h,S]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[l,[u,x],[h,g]],[/smart-tv.+(samsung)/i],[u,[h,v]],[/hbbtv.+maple;(\d+)/i],[[l,/^/,"SmartTV"],[u,$],[h,v]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[u,K],[h,v]],[/(apple) ?tv/i],[u,[l,y+" TV"],[h,v]],[/crkey/i],[[l,P+"cast"],[u,I],[h,v]],[/droid.+aft(\w+)( bui|\))/i],[l,[u,R],[h,v]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[l,[u,se],[h,v]],[/(bravia[\w ]+)( bui|\))/i],[l,[u,N],[h,v]],[/(mitv-\w{5}) bui/i],[l,[u,V],[h,v]],[/Hbbtv.*(technisat) (.*);/i],[u,l,[h,v]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[u,je],[l,je],[h,v]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[h,v]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[u,l,[h,m]],[/droid.+; (shield) bui/i],[l,[u,"Nvidia"],[h,m]],[/(playstation [345portablevi]+)/i],[l,[u,N],[h,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[l,[u,B],[h,m]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[l,[u,$],[h,E]],[/((pebble))app/i],[u,l,[h,E]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[l,[u,y],[h,E]],[/droid.+; (glass) \d/i],[l,[u,I],[h,E]],[/droid.+; (wt63?0{2,3})\)/i],[l,[u,x],[h,E]],[/droid.+; (glass) \d/i],[l,[u,I],[h,E]],[/(pico) (4|neo3(?: link|pro)?)/i],[u,l,[h,E]],[/; (quest( \d| pro)?)/i],[l,[u,U],[h,E]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[u,[h,T]],[/(aeobc)\b/i],[l,[u,R],[h,T]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[l,[h,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[l,[h,S]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[h,S]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[h,g]],[/(android[-\w\. ]{0,9});.+buil/i],[l,[u,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[p,[d,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[d,p],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[p,[d,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[d,p],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[p,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,p],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[d,[p,Ue,ye]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[p,Ue,ye],[d,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[p,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,ue],[p,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[p,d],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[d,p],[/\(bb(10);/i],[p,[d,w]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[p,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[p,[d,M+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[p,[d,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[p,[d,"watchOS"]],[/crkey\/([\d\.]+)/i],[p,[d,P+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,ce],p],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[d,p],[/(sunos) ?([\w\.\d]*)/i],[[d,"Solaris"],p],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[d,p]]},Oe=function(Se,le){if(typeof Se===a&&(le=Se,Se=t),!(this instanceof Oe))return new Oe(Se,le).getResult();var ae=typeof e!==n&&e.navigator?e.navigator:t,Ie=Se||(ae&&ae.userAgent?ae.userAgent:""),Ze=ae&&ae.userAgentData?ae.userAgentData:t,Te=le?function(re,dt){var It={};for(var Ke in re)dt[Ke]&&dt[Ke].length%2==0?It[Ke]=dt[Ke].concat(re[Ke]):It[Ke]=re[Ke];return It}(Ge,le):Ge,at=ae&&ae.userAgent==Ie;return this.getBrowser=function(){var re={};return re[d]=t,re[p]=t,_e.call(re,Ie,Te.browser),re[o]=function(dt){return typeof dt===c?dt.replace(/[^\d\.]/g,"").split(".")[0]:t}(re[p]),at&&ae&&ae.brave&&typeof ae.brave.isBrave==i&&(re[d]="Brave"),re},this.getCPU=function(){var re={};return re[f]=t,_e.call(re,Ie,Te.cpu),re},this.getDevice=function(){var re={};return re[u]=t,re[l]=t,re[h]=t,_e.call(re,Ie,Te.device),at&&!re[h]&&Ze&&Ze.mobile&&(re[h]=g),at&&re[l]=="Macintosh"&&ae&&typeof ae.standalone!==n&&ae.maxTouchPoints&&ae.maxTouchPoints>2&&(re[l]="iPad",re[h]=S),re},this.getEngine=function(){var re={};return re[d]=t,re[p]=t,_e.call(re,Ie,Te.engine),re},this.getOS=function(){var re={};return re[d]=t,re[p]=t,_e.call(re,Ie,Te.os),at&&!re[d]&&Ze&&Ze.platform&&Ze.platform!="Unknown"&&(re[d]=Ze.platform.replace(/chrome os/i,ce).replace(/macos/i,ue)),re},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return Ie},this.setUA=function(re){return Ie=typeof re===c&&re.length>500?je(re,500):re,this},this.setUA(Ie),this};Oe.VERSION="1.0.40",Oe.BROWSER=Re([d,p,o]),Oe.CPU=Re([f]),Oe.DEVICE=Re([l,u,h,m,g,v,S,E,T]),Oe.ENGINE=Oe.OS=Re([d,p]),s.exports&&(r=s.exports=Oe),r.UAParser=Oe;var mt=typeof e!==n&&(e.jQuery||e.Zepto);if(mt&&!mt.ua){var At=new Oe;mt.ua=At.getResult(),mt.ua.get=function(){return At.getUA()},mt.ua.set=function(Se){At.setUA(Se);var le=At.getResult();for(var ae in le)mt.ua[ae]=le[ae]}}})(typeof window=="object"?window:Kr)})(pn,pn.exports);var Gp=pn.exports,Qe=(s=>(s.KEEPALIVE="keepalive",s.JOINCHANNEL="joinchannel",s.NOTIFYJOIN="notifyjoin",s.NOTIFYSTATUS="notifystatus",s.STATUSREPORT="statusreport",s.LEAVECHANNEL="leavechannel",s.NOTIFYLEAVE="notifyleave",s.NOTIFYPUBLISH="notifypublish",s.BYE="bye",s.RECONNECT="reconnect",s.PUBLISH="publish",s.REFRESHURL="refreshurl",s.UNSUBSCRIBE="unsubscribe",s.ROLEUPDATE="roleupdate",s))(Qe||{});class Ei{constructor(r,e){b(this,"authInfo");b(this,"userName");b(this,"seqIndex",0);this.authInfo=r,this.userName=typeof e=="number"?e.toString():e}get roleAuth(){if(this.authInfo.role){const{timestamp:r,nonce:e,token:t,role:i}=this.authInfo;return{timestamp:r,nonce:e,token:t,tokenrole:i}}}static get adaptInfo(){var e,t,i,n;let r=new Gp.UAParser().getResult();return{os_name:((e=r.os.name)==null?void 0:e.replace(" ",""))+"_"+((t=r.browser.name)==null?void 0:t.replace(" ","")),device_name:((i=r.device.model)==null?void 0:i.replace(" ",""))||"",brand_name:((n=r.device.vendor)==null?void 0:n.replace(" ",""))||"",device_key:window.navigator.userAgent,os_version:r.browser.version||"",sdk_version:"7.3.0-beta.2",version:"v1"}}refreshAuthInfo(r){this.authInfo=r}getSeqIndex(){return this.seqIndex}createKeepAlivePackage(){return this.createBaseSendPackage("keepalive")}createJoinPackage(r){let e=this.createBaseSendPackage("joinchannel");return e.header.displayName=this.userName,e.header.clientversion=ze.getVersionNumber().toString(),e.header.platform="web",this.roleAuth&&(e.data.auth=this.roleAuth),e.data.adapt=Ei.adaptInfo,r&&(e.data=D(D({},e.data),r)),e}createLeavePackage(){return this.createBaseSendPackage("leavechannel")}createStatusPackage(r){let e=this.createBaseSendPackage("statusreport");return e.header.displayName=this.userName,e.data.status=r,e}createPublishPackage(){let r=this.createBaseSendPackage("publish");return r.data.users=[{}],this.roleAuth&&(r.data.auth=this.roleAuth),r}createRoleUpdatePackage(){let r=this.createBaseSendPackage("roleupdate");return r.header.displayName=this.userName,r}createReconnectPackage(r){let e=this.createBaseSendPackage("reconnect");return e.header.displayName=this.userName,e.header.clientversion=ze.getVersionNumber().toString(),e.header.platform="web",e.data=D(D({},e.data),r!=null?r:{}),this.roleAuth&&(e.data.auth=this.roleAuth),e}createRefreshUrlPackage(){let r=this.createBaseSendPackage("refreshurl");return r.header.displayName=this.userName,r}createResponsePackage(r,e){return{version:1,code:200,tid:r,msgtype:e}}createBaseSendPackage(r){var e;return++this.seqIndex,{version:1,msgtype:r,tid:Vt(),header:{appid:this.authInfo.appId,channelid:this.authInfo.channelId,sessionid:(e=this.authInfo.sessionId)!=null?e:"",userid:this.authInfo.userId},data:{seq:this.seqIndex}}}}var Kt=(s=>(s.pre="pre",s.prod="prod",s))(Kt||{}),Jt=(s=>(s.AliRtcSdkCommunication="communication",s.AliRtcSdkInteractiveLive="interactive_live",s.AliRtcSdkInteractiveWithLowLatencyLive="cdn_live",s))(Jt||{}),gr=(s=>(s.AliRtcSdkInteractive="interactive",s.AliRtcSdkLive="live",s))(gr||{}),ir=(s=>(s[s.AliEngineLocalDeviceTypeUnknown=0]="AliEngineLocalDeviceTypeUnknown",s[s.AliEngineLocalDeviceTypeMic=1]="AliEngineLocalDeviceTypeMic",s[s.AliEngineLocalDeviceTypeSpeaker=2]="AliEngineLocalDeviceTypeSpeaker",s[s.AliEngineLocalDeviceTypeAudioDevice=3]="AliEngineLocalDeviceTypeAudioDevice",s[s.AliEngineLocalDeviceTypeCamera=4]="AliEngineLocalDeviceTypeCamera",s[s.AliEngineLocalDeviceTypeDisplay=5]="AliEngineLocalDeviceTypeDisplay",s[s.AliEngineLocalDeviceTypeVideoDevice=6]="AliEngineLocalDeviceTypeVideoDevice",s))(ir||{}),qe=(s=>(s[s.AliEngineLocalDeviceExceptionTypeUnknown=0]="AliEngineLocalDeviceExceptionTypeUnknown",s[s.AliEngineLocalDeviceExceptionTypeMicOpenFail=1]="AliEngineLocalDeviceExceptionTypeMicOpenFail",s[s.AliEngineLocalDeviceExceptionTypeMicInterrupt=2]="AliEngineLocalDeviceExceptionTypeMicInterrupt",s[s.AliEngineLocalDeviceExceptionTypeMicAuthFail=3]="AliEngineLocalDeviceExceptionTypeMicAuthFail",s[s.AliEngineLocalDeviceExceptionTypeMicNotAvailable=4]="AliEngineLocalDeviceExceptionTypeMicNotAvailable",s[s.AliEngineLocalDeviceExceptionTypeSpeakerOpenFail=5]="AliEngineLocalDeviceExceptionTypeSpeakerOpenFail",s[s.AliEngineLocalDeviceExceptionTypeSpeakerInterrupt=6]="AliEngineLocalDeviceExceptionTypeSpeakerInterrupt",s[s.AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable=7]="AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable",s[s.AliEngineLocalDeviceExceptionTypeAudioDeviceException=8]="AliEngineLocalDeviceExceptionTypeAudioDeviceException",s[s.AliEngineLocalDeviceExceptionTypeCameraOpenFail=9]="AliEngineLocalDeviceExceptionTypeCameraOpenFail",s[s.AliEngineLocalDeviceExceptionTypeCameraInterrupt=10]="AliEngineLocalDeviceExceptionTypeCameraInterrupt",s[s.AliEngineLocalDeviceExceptionTypeCameraAuthFail=11]="AliEngineLocalDeviceExceptionTypeCameraAuthFail",s[s.AliEngineLocalDeviceExceptionTypeDisplayException=12]="AliEngineLocalDeviceExceptionTypeDisplayException",s[s.AliEngineLocalDeviceExceptionTypeVideoDeviceException=13]="AliEngineLocalDeviceExceptionTypeVideoDeviceException",s))(qe||{}),fe=(s=>(s[s.AliRtcConnectionStatusInit=0]="AliRtcConnectionStatusInit",s[s.AliRtcConnectionStatusDisconnected=1]="AliRtcConnectionStatusDisconnected",s[s.AliRtcConnectionStatusConnecting=2]="AliRtcConnectionStatusConnecting",s[s.AliRtcConnectionStatusConnected=3]="AliRtcConnectionStatusConnected",s[s.AliRtcConnectionStatusReconnecting=4]="AliRtcConnectionStatusReconnecting",s[s.AliRtcConnectionStatusFailed=5]="AliRtcConnectionStatusFailed",s))(fe||{}),$t=(s=>(s[s.AliRtcConnectionChangedDummyReason=0]="AliRtcConnectionChangedDummyReason",s[s.AliRtcConnectionMediaPathChanged=1]="AliRtcConnectionMediaPathChanged",s[s.AliRtcConnectionSignalingHeartbeatTimeout=2]="AliRtcConnectionSignalingHeartbeatTimeout",s[s.AliRtcConnectionSignalingHeartbeatAlive=3]="AliRtcConnectionSignalingHeartbeatAlive",s[s.AliRtcConnectionSignalingHttpDnsResolved=4]="AliRtcConnectionSignalingHttpDnsResolved",s[s.AliRtcConnectionSignalingHttpDnsFailure=5]="AliRtcConnectionSignalingHttpDnsFailure",s[s.AliRtcConnectionSignalingGslbFailure=6]="AliRtcConnectionSignalingGslbFailure",s[s.AliRtcConnectionSignalingGslbSuccess=7]="AliRtcConnectionSignalingGslbSuccess",s[s.AliRtcConnectionSignalingJoinRoomFailure=8]="AliRtcConnectionSignalingJoinRoomFailure",s[s.AliRtcConnectionSignalingJoinRoomSuccess=9]="AliRtcConnectionSignalingJoinRoomSuccess",s[s.AliRtcConnectionSignalingLeaveRoom=10]="AliRtcConnectionSignalingLeaveRoom",s[s.AliRtcConnectionSignalingConnecting=11]="AliRtcConnectionSignalingConnecting",s[s.AliRtcConnectionChangedNetworkInterrupted=12]="AliRtcConnectionChangedNetworkInterrupted",s))($t||{}),mn=(s=>(s[s.AliRtcUserOfflineQuit=0]="AliRtcUserOfflineQuit",s[s.AliRtcUserOfflineDropped=1]="AliRtcUserOfflineDropped",s[s.AliRtcUserOfflineBecomeAudience=2]="AliRtcUserOfflineBecomeAudience",s))(mn||{}),Or=(s=>(s[s.AliRtcAudioTrackNo=0]="AliRtcAudioTrackNo",s[s.AliRtcAudioTrackMic=1]="AliRtcAudioTrackMic",s[s.AliRtcAudioTrackDual=2]="AliRtcAudioTrackDual",s))(Or||{}),be=(s=>(s[s.AliRtcVideoTrackNo=0]="AliRtcVideoTrackNo",s[s.AliRtcVideoTrackCamera=1]="AliRtcVideoTrackCamera",s[s.AliRtcVideoTrackScreen=2]="AliRtcVideoTrackScreen",s[s.AliRtcVideoTrackBoth=3]="AliRtcVideoTrackBoth",s))(be||{}),ne=(s=>(s[s.AliRtcStatePublishIdle=0]="AliRtcStatePublishIdle",s[s.AliRtcStateNoPublish=1]="AliRtcStateNoPublish",s[s.AliRtcStatePublishing=2]="AliRtcStatePublishing",s[s.AliRtcStatePublished=3]="AliRtcStatePublished",s[s.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",s))(ne||{}),ge=(s=>(s[s.AliRtcStateSubscribeIdle=0]="AliRtcStateSubscribeIdle",s[s.AliRtcStateNoSubscribe=1]="AliRtcStateNoSubscribe",s[s.AliRtcStateSubscribing=2]="AliRtcStateSubscribing",s[s.AliRtcStateSubscribed=3]="AliRtcStateSubscribed",s[s.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",s))(ge||{}),it=(s=>(s[s.AliRtcVideoStreamTypeNone=0]="AliRtcVideoStreamTypeNone",s[s.AliRtcVideoStreamTypeHigh=1]="AliRtcVideoStreamTypeHigh",s[s.AliRtcVideoStreamTypeLow=2]="AliRtcVideoStreamTypeLow",s))(it||{}),yi=(s=>(s[s.CAMERA_INVALID=-1]="CAMERA_INVALID",s[s.CAMERA_REAR=0]="CAMERA_REAR",s[s.CAMERA_FRONT=1]="CAMERA_FRONT",s))(yi||{});const Fd="ALI_RTC_SDK_ALLOCATE_RESULT",oi=class oi{constructor(r,e,t){b(this,"result",null);b(this,"pms");let i=localStorage.getItem(Fd);if(i){const f=JSON.parse(i);f.appId===e.appId&&f.expireTs-3e5>Date.now()?this.result=f.allocatedData:O.info(`[${oi.logName}]`,"allocate","cached data is invalid")}const{appId:n,channelId:a,sessionId:c,userId:o,timestamp:l,token:d,nonce:h}=e,u=new URLSearchParams({appid:n,channelid:a,session:c,userid:o,timestamp:`${l}`,token:d,nonce:h!=null?h:"",adapt:"true",clitype:"2"});t&&u.set("joinmode",t);const p=r===Kt.pre?qr.pre:qr.prod;this.pms=fetch(`https://${p}/gslb/v1/allocate?${u.toString()}`,{method:"POST",body:JSON.stringify(Ei.adaptInfo)}).then(f=>f.json()).then(f=>{if(f.code===0){const m=f.data;this.result=m;const{ice_ufrag:g}=m.h5auth,[S,v]=atob(g).split("_"),E={appId:n,expireTs:1e3*parseInt(v),allocatedData:m};return O.info(`[${oi.logName}]`,"got allocate result and save",m.h5auth.ice_ufrag),localStorage.setItem(Fd,JSON.stringify(E)),m}return null}).catch(f=>(O.error(`[${oi.logName}]`,"allocate",f),null))}};b(oi,"logName","Allocator");let Ti=oi;var We=(s=>(s.PullStreamStats="remoteStat",s.RtsSubscribeExceeds="rtsSubscribeExceeds",s.UserJoined="userJoined",s.UserLeft="userLeft",s.Bye="bye",s.MuteAudio="muteAudio",s.UnmuteAudio="unmuteAudio",s.MuteVideo="muteVideo",s.UnmuteVideo="unmuteVideo",s.MuteScreen="muteScreen",s.UnmuteScreen="unmuteScreen",s.Error="error",s))(We||{}),bt=(s=>(s.Local="local-device-status-change",s.Remote="remote-device-status-change",s))(bt||{}),L=(s=>(s.Audio="sophon_audio",s.VideoLarge="sophon_video_camera_large",s.VideoSmall="sophon_video_camera_small",s.Screen="sophon_video_screen_share",s.Data="sophon_data",s))(L||{}),fn=(s=>(s.Audio="rts audio",s.VideoLarge="rts video",s))(fn||{}),Sr=(s=>(s.Add="add",s.Delete="delete",s.Replace="replace",s.Stop="stop",s.UnPublish="unpublish",s))(Sr||{}),Ci=(s=>(s[s.Camera=0]="Camera",s[s.Screen=1]="Screen",s[s.Image=2]="Image",s))(Ci||{}),ms=(s=>(s[s.Microphone=0]="Microphone",s[s.Screen=1]="Screen",s[s.Mixed=2]="Mixed",s))(ms||{}),De=(s=>(s.InRoom="inRoom",s.Join="join",s.Publish="publish",s.User="user",s.Resume="resume",s.Retry="retry",s.Reconnect="reconnect",s))(De||{}),Xt=(s=>(s[s.MANUAL=0]="MANUAL",s[s.JOIN_CHANNEL=1]="JOIN_CHANNEL",s[s.ROLE_CHANGE=2]="ROLE_CHANGE",s[s.RECONNECT=3]="RECONNECT",s))(Xt||{});function Hd(s,r){if(r.length===0)return"";const e=[...s];for(const t of r)e.push(t.mLine),e.push(...t.lines);return e.join(`\r
210
+ `)}class zp{constructor(r={sendVideo:!0,sendAudio:!0,recvVideo:!0,recvAudio:!0}){b(this,"sendOffer");b(this,"recvOffer");b(this,"fullOffer");b(this,"ready");b(this,"config");this.config=r;const{sendVideo:e,sendAudio:t,recvVideo:i,recvAudio:n,audioCodecPreferences:a,videoCodecPreferences:c}=r,o=e||t,l=i||n;if(!o&&!l)return void(this.ready=Promise.resolve());const d=new RTCPeerConnection;if(e){const h=d.addTransceiver("video",{direction:"sendonly"});c&&h.setCodecPreferences(c)}if(t){const h=d.addTransceiver("audio",{direction:"sendonly"});a&&h.setCodecPreferences(a)}if(i){const h=d.addTransceiver("video",{direction:"recvonly"});c&&h.setCodecPreferences(c)}if(n){const h=d.addTransceiver("audio",{direction:"recvonly"});a&&h.setCodecPreferences(a)}this.ready=d.createOffer().then(h=>{this.fullOffer=h,d.close();const u=h.sdp||"",{sessionLines:p,mediaSections:f}=function(S){const v=S.split(`\r
211
+ `),E=[],T=[];let R=null;for(const y of v)if(y.startsWith("m=")){R&&T.push(R);const C=y.startsWith("m=audio")?"audio":"video";R={mLine:y,lines:[],direction:null,kind:C}}else R?(R.lines.push(y),y==="a=sendonly"?R.direction="sendonly":y==="a=recvonly"?R.direction="recvonly":y==="a=sendrecv"?R.direction="sendrecv":y==="a=inactive"&&(R.direction="inactive")):E.push(y);return R&&T.push(R),{sessionLines:E,mediaSections:T}}(u),m=f.filter(S=>S.direction==="sendonly"),g=f.filter(S=>S.direction==="recvonly");if(o&&m.length>0){const S=Hd(p,m);this.sendOffer={type:"offer",sdp:S}}if(l&&g.length>0){const S=Hd(p,g);this.recvOffer={type:"offer",sdp:S}}})}}var gn=(s=>(s[s.AliEngineDataMsgNone=0]="AliEngineDataMsgNone",s[s.AliEngineDataMsgMusicProgress=1]="AliEngineDataMsgMusicProgress",s[s.AliEngineDataMsgCustom=2]="AliEngineDataMsgCustom",s))(gn||{});class fs{constructor(r,e,t,i=0){b(this,"msgType");b(this,"msgId");b(this,"protocolVersion");b(this,"tlvVersion");this.msgType=r,this.msgId=e,this.protocolVersion=t,this.tlvVersion=i}build(){const r=new Uint8Array(4);return r.set(Uint8Array.from([this.protocolVersion,this.tlvVersion<<4|15&this.msgType]),0),r.set(Uint16Array.from([this.msgId]),2),r}static parse(r){const e=new DataView(r),t=e.getUint8(0),i=e.getUint8(1)>>4,n=15&e.getUint8(1),a=e.getUint16(2);return new fs(n,a,t,i)}}class gs{constructor(r,e,t){b(this,"_byteArray");if(this._byteArray=new Uint8Array(0),r!==void 0&&e!==void 0&&t!==void 0){const i=new fs(r,e,t).build();this._byteArray=new Uint8Array(i.byteLength+this._byteArray.byteLength),this._byteArray.set(i,0)}}write(r,e){const t=this._byteArray,i=new ArrayBuffer(5),n=new DataView(i);n.setUint8(0,r),n.setUint32(1,e.byteLength);const a=new Uint8Array(t.byteLength+5+e.byteLength);a.set(t,0),a.set(new Uint8Array(i),t.byteLength),a.set(new Uint8Array(e),t.byteLength+5),this._byteArray=a}static parse(r){const e={},t=new DataView(r);let i=0;for(;i<r.byteLength;){const n=t.getUint8(i),a=t.getUint32(i+1);if(!(i+5+a<=r.byteLength))break;{const c=r.slice(i+5,i+5+a);e[n]=c,i+=5+a}}return e}get buffer(){return this._byteArray.buffer}}class Nr{constructor(r=0,e=!0,t=1,i=!1,n=0,a=!1,c=!1,o=3){b(this,"_fin",!0);b(this,"_hasExtension",!1);b(this,"_version",0);b(this,"_frameType",1);b(this,"_isEncrypted",!1);b(this,"_isCompressed",!1);b(this,"_signalType",3);b(this,"_payloadLength",0);this._fin=e,this._hasExtension=i,this._version=n,this._frameType=t,this._isEncrypted=a,this._isCompressed=c,this._signalType=o,this._payloadLength=r}get fin(){return this._fin}get hasExtension(){return this._hasExtension}get version(){return this._version}get frameType(){return this._frameType}get isEncrypted(){return this._isEncrypted}get isCompressed(){return this._isCompressed}get signalType(){return this._signalType}get payloadLength(){return this._payloadLength}toBuffer(){const r=new ArrayBuffer(4),e=new DataView(r);return e.setUint8(0,(this._fin?1:0)<<7|(this._hasExtension?1:0)<<6|this._version<<4|15&this._frameType),e.setUint8(1,(this._isEncrypted?1:0)<<7|(this._isCompressed?1:0)<<6|15&this._signalType),e.setUint16(2,this._payloadLength),r}static parse(r){const e=new DataView(r),t=e.getUint8(0)>>7==1,i=(64&e.getUint8(0))>>6==1,n=(48&e.getUint8(0))>>4,a=15&e.getUint8(0),c=e.getUint8(1)>>7==1,o=(64&e.getUint8(1))>>6==1,l=15&e.getUint8(1),d=e.getUint16(2);return new Nr(d,t,a,i,n,c,o,l)}}class Lr{constructor(r,e){b(this,"_body");b(this,"_header",new Nr);this._header=r,this._body=e}get header(){return this._header}get isFin(){return this._header.fin}get body(){return this._body}toGRTNBuffer(){const r=this._header.toBuffer(),e=this._body,t=new ArrayBuffer(4);new DataView(t).setUint8(0,1*Math.pow(2,4));const i=new Uint8Array(t.byteLength+r.byteLength+e.byteLength);return i.set(new Uint8Array(t),0),i.set(new Uint8Array(r),t.byteLength),i.set(new Uint8Array(e),t.byteLength+r.byteLength),i.buffer}static parse(r){const e=r.slice(0,4),t=Nr.parse(e);let i=new ArrayBuffer(0);return r.byteLength-4>=t.payloadLength&&(i=r.slice(4,4+t.payloadLength)),new Lr(t,i)}}const Sn=s=>{const r=s.byteLength,e=new DataView(s);let t=0;for(let i=0;i<r;i++)t=256*t+e.getUint8(i);return t};let Wd=0;class br{constructor(r,e=0,t=0,i=0){b(this,"data");b(this,"networkTime");b(this,"futureOrProgress");b(this,"type");this.data=r,this.type=e,this.networkTime=t,this.futureOrProgress=i}toBuffer(){const r=new gs(0,0,0);r.write(1,Uint8Array.from([0]).buffer),r.write(2,Uint16Array.from([0]).buffer),Wd++,r.write(3,Uint32Array.from([Wd]).buffer);const e=new gs;return e.write(1,Uint8Array.from([0]).buffer),e.write(2,Uint8Array.from([this.type]).buffer),e.write(3,Uint32Array.from([this.futureOrProgress]).buffer),e.write(4,Uint32Array.from([Number(this.networkTime>>32&4294967295),Number(4294967295&this.networkTime)]).buffer),e.write(5,this.data),r.write(30,e.buffer),r.buffer}static parse(r){if(!r||r.byteLength<4)return;fs.parse(r.slice(0,4));const e=gs.parse(r.slice(4))[30];if(!e)return;const t=gs.parse(e),i=t[2],n=t[3],a=t[4],c=t[5];return c.byteLength!==0?new br(c,Sn(i),Sn(a),Sn(n)):void 0}}var z=(s=>(s[s.ERR_JOIN_ALREADY_JOINED=16843521]="ERR_JOIN_ALREADY_JOINED",s[s.ERR_JOIN_BAD_APPID=33620481]="ERR_JOIN_BAD_APPID",s[s.ERR_JOIN_INVALID_APPID=33620482]="ERR_JOIN_INVALID_APPID",s[s.ERR_JOIN_BAD_CHANNEL=33620484]="ERR_JOIN_BAD_CHANNEL",s[s.ERR_JOIN_INVALID_CHANNEL=33620483]="ERR_JOIN_INVALID_CHANNEL",s[s.ERR_JOIN_BAD_TOKEN=33620485]="ERR_JOIN_BAD_TOKEN",s[s.ERR_JOIN_TIMEOUT=16908804]="ERR_JOIN_TIMEOUT",s[s.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD=16974081]="ERR_JOIN_ERR_JOIN_BAD_PARAMBAD",s[s.ERR_JOIN_CHANNEL_FAILED=16974338]="ERR_JOIN_CHANNEL_FAILED",s[s.ERR_LOG_ALREADY_INIT=16974085]="ERR_LOG_ALREADY_INIT",s[s.ERR_LOG_ROOT_PATH_ERROR=16974086]="ERR_LOG_ROOT_PATH_ERROR",s[s.ERR_MIC_OPEN_FAIL=17040388]="ERR_MIC_OPEN_FAIL",s[s.ERR_SPEAKER_OPEN_FAIL=17040389]="ERR_SPEAKER_OPEN_FAIL",s[s.ERR_MIC_INTERRUPT=17040390]="ERR_MIC_INTERRUPT",s[s.ERR_SPEAKER_INTERRUPT=17040391]="ERR_SPEAKER_INTERRUPT",s[s.ERR_MIC_AUTH_FAIL=17040392]="ERR_MIC_AUTH_FAIL",s[s.ERR_MIC_NOT_AVAILABLE=17040393]="ERR_MIC_NOT_AVAILABLE",s[s.ERR_SPEAKER_NOT_AVAILABLE=17040400]="ERR_SPEAKER_NOT_AVAILABLE",s[s.ERR_CAMERA_OPEN_FAIL=17039620]="ERR_CAMERA_OPEN_FAIL",s[s.ERR_CAMERA_AUTH_FAIL=17039621]="ERR_CAMERA_AUTH_FAIL",s[s.ERR_CAMERA_INTERRUPT=17039622]="ERR_CAMERA_INTERRUPT",s[s.ERR_CAMERA_NOT_AVAILABLE=17039623]="ERR_CAMERA_NOT_AVAILABLE",s[s.ERR_VIDEO_DISPLAY_OPEN_FAIL=17039873]="ERR_VIDEO_DISPLAY_OPEN_FAIL",s[s.ERR_VIDEO_DISPLAY_INTERRUPT=1064992]="ERR_VIDEO_DISPLAY_INTERRUPT",s[s.ERR_ICE_CONNECTION_CONNECT_FAIL=17105409]="ERR_ICE_CONNECTION_CONNECT_FAIL",s[s.ERR_ICE_CONNECTION_RECONNECT_FAI=17105410]="ERR_ICE_CONNECTION_RECONNECT_FAI",s[s.ERR_ICE_CONNECTION_MOBILITY_FAIL=17105411]="ERR_ICE_CONNECTION_MOBILITY_FAIL",s[s.ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT=16908812]="ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT",s[s.ERR_LATENCY_LIVE_COMMUNICATION_FAILED=17235971]="ERR_LATENCY_LIVE_COMMUNICATION_FAILED",s[s.ERR_LATENCY_LIVE_MEIDASETTING_FAILED=17235972]="ERR_LATENCY_LIVE_MEIDASETTING_FAILED",s[s.ERR_LATENCY_LIVE_NONE_BROADCASTER=17235973]="ERR_LATENCY_LIVE_NONE_BROADCASTER",s[s.ERR_LATENCY_LIVE_NEED_RESTART=17235974]="ERR_LATENCY_LIVE_NEED_RESTART",s[s.ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER=17235975]="ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER",s[s.ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE=17235976]="ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE",s[s.ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION=17235977]="ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION",s[s.ERR_SDK_PUBLISH_INVAILD=16974597]="ERR_SDK_PUBLISH_INVAILD",s[s.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL=16843782]="ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL",s[s.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED=16843856]="ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED",s[s.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED=16843857]="ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED",s[s.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED=16843858]="ERR_SDK_PUBLISH_DUAL_STREAM_FAILED",s[s.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED=16843859]="ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED",s[s.ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR=16843860]="ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR",s[s.ERR_SDK_SUBSCRIBE_INVAILD=16974852]="ERR_SDK_SUBSCRIBE_INVAILD",s[s.ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL=16844112]="ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL",s[s.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED=16844113]="ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED=16844114]="ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED=16844115]="ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED=16844116]="ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED",s[s.ERR_SDK_SUBSCRIBE_DATA_FAILED=16844117]="ERR_SDK_SUBSCRIBE_DATA_FAILED",s[s.ERR_SDK_SUBSCRIBE_DATA_ERROR=16844118]="ERR_SDK_SUBSCRIBE_DATA_ERROR",s[s.ERR_SDK_INVALID_STATE=16974340]="ERR_SDK_INVALID_STATE",s[s.ERR_INVALID_ARGUMENTS=16974083]="ERR_INVALID_ARGUMENTS",s[s.ERR_SESSION_REMOVED=33620229]="ERR_SESSION_REMOVED",s[s.ERR_SDK_UPDATE_ROLE_CHANNEL=16908801]="ERR_SDK_UPDATE_ROLE_CHANNEL",s[s.ERR_INNER=-1]="ERR_INNER",s[s.ERR_SDK_MPU_TASK_PUBLISH_OK=0]="ERR_SDK_MPU_TASK_PUBLISH_OK",s[s.ERR_SDK_MPU_TASK_STREAM_NOT_FOUND=17825793]="ERR_SDK_MPU_TASK_STREAM_NOT_FOUND",s[s.ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST=17825794]="ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST",s[s.ERR_SDK_MPU_TASK_INVALID_PARAM=17825795]="ERR_SDK_MPU_TASK_INVALID_PARAM",s[s.ERR_SDK_MPU_TASK_INTERNAL_ERROR=17825796]="ERR_SDK_MPU_TASK_INTERNAL_ERROR",s[s.ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR=17825797]="ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR",s[s.ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR=17825798]="ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR",s[s.ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT=17825799]="ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT",s[s.ERR_SDK_MPU_TASK_NOT_AUTHORIZED=17825800]="ERR_SDK_MPU_TASK_NOT_AUTHORIZED",s[s.ERR_SDK_CHANNEL_RELAY_STATE_ERROR=18874369]="ERR_SDK_CHANNEL_RELAY_STATE_ERROR",s[s.ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW=18874370]="ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW",s[s.ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED=18874371]="ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED",s[s.ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID=18874372]="ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID",s[s.ERR_SDK_CHANNEL_RELAY_ROLE_ERROR=18874373]="ERR_SDK_CHANNEL_RELAY_ROLE_ERROR",s[s.ERR_SDK_CHANNEL_RELAY_INVALID_PARAM=18874374]="ERR_SDK_CHANNEL_RELAY_INVALID_PARAM",s[s.ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR=18874375]="ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR",s))(z||{});class W extends Error{constructor(e,t,i){super(t);b(this,"_code");b(this,"_extra");this._code=e,this._extra=i}static fromRtsError(e){return e instanceof W?e:new W((e==null?void 0:e.errorCode)||-1,(e==null?void 0:e.message)||(e==null?void 0:e.errorCodeName)||"rts error",e)}static fromError(e,t=-1,i=""){return new W(t,(e==null?void 0:e.message)||(e==null?void 0:e.reason)||i||"error",e)}get code(){return this._code}set code(e){this._code=e}get reason(){return this.message}get extra(){return this._extra}}function jd(s){var r;if(((r=s==null?void 0:s.nodeName)==null?void 0:r.toLowerCase())==="video")return s.setAttribute("playsinline",""),s;if(typeof s=="string"){let e=document.getElementById(s);if(e){if(e.nodeName.toLocaleLowerCase()==="video")return e.setAttribute("playsinline",""),e;throw new W(z.ERR_INVALID_ARGUMENTS,"element should be HtmlVideoElement")}throw new W(z.ERR_INVALID_ARGUMENTS,"element not founded")}throw new W(z.ERR_INVALID_ARGUMENTS,"element id should be string")}function bn(s){var e;const r=[];if(Array.isArray(s))s.forEach(t=>{try{r.push(jd(t))}catch(i){}});else if(typeof s=="string"||((e=s==null?void 0:s.nodeName)==null?void 0:e.toLowerCase())==="video")try{r.push(jd(s))}catch(t){}return r}function lr(s){return new Promise(r=>setTimeout(r,s))}function Gd(s,r,e=1e3,t=i=>!0){return _(this,null,function*(){let i=0;for(;i<r;)try{return yield s(i)}catch(n){if(i++,i>=r||!t(n))throw n||void 0;yield new Promise(a=>setTimeout(a,e))}})}function vn(s,r){let e=0;const t=[];for(;e<s.byteLength;){const i=Math.min(r,s.byteLength-e),n=s.slice(e,e+i);t.push(n),e+=i}return t}function zd(s,r){let e=r;return typeof window.__ali_prefer_media_server=="string"&&window.__ali_prefer_media_server!==""&&(e=window.__ali_prefer_media_server),e?`${s}&ali_prefer_media_server=${e}`:s}function xr(s,r){var e;try{const{archCfgs:t}=s;if(!t||!Array.isArray(t))return;const i=t.find(n=>n.arch==="grtn");return i?(e=i.user_specified)==null?void 0:e[r]:void 0}catch(t){return}}function ei(s,r){try{const{config:e}=s;return e?e==null?void 0:e[r]:void 0}catch(e){return}}function Rn(s){return window.btoa(s).replaceAll("+","-").replaceAll("/","_")}function En(s){const r=s.replace(/(a=rtpmap:(\d+).*\r\n)/g,`$1a=rtcp-fb:$2 rrtr\r
212
+ `);return r.includes(`a=rtcp-rsize\r
213
+ `)?r:r.replace(/(m=(video|audio).*\r\n)/g,`$1a=rtcp-rsize\r
214
+ `)}function Kd(s){const r=s.reduce((i,n)=>i+n.byteLength,0),e=new Uint8Array(r);let t=0;return s.forEach(i=>{e.set(new Uint8Array(i),t),t+=i.byteLength}),e.buffer}const rt=class rt extends de{constructor(e,t,i,n,a,c){super();b(this,"rts");b(this,"packageCreator");b(this,"channelProfile");b(this,"clientRole");b(this,"msgPieces",[]);b(this,"preSubInfoMap",{});b(this,"subAddedMark",{});b(this,"preSubAddActiveMap",{});b(this,"prePubPromise");b(this,"prePubSdpInfo");b(this,"pubAddedMark");b(this,"keepAliveTimer");b(this,"roomServerChannel");b(this,"waitingPackages",[]);b(this,"_willPrePub",!1);b(this,"prePubSubConfig");b(this,"startDefaultDevicesPromise");this.authInfo=e,this.userName=t,this.rtsManager=a,this.packageCreator=new Ei(e,t),this.channelProfile=i,this.clientRole=n,this.rts=a.rts,this.rts.on("reconnectRoomServer",()=>{O.info(`[${rt.logName}]`,"reconnectRoomServer")}),this.rts.on("preSub",o=>_(this,null,function*(){var l,d;if(o.message.streams[0].method==="add"){const h=Date.now();O.event(`[${rt.logName}][datachannel]`,"<<< Received: preSub add",o.message);const u=(l=o.message.streams[0].msid.find(E=>E.type==="audio"))==null?void 0:l.name,p=(d=o.message.streams[0].msid.find(E=>E.type==="video"))==null?void 0:d.name,f=this.rts.subscribeAdd([{url:o.message.streams[0].url,subAudio:!!u,subVideo:!!p,vMsid:p?[p]:void 0,aMsid:u?[u]:void 0}],o.message);let m=()=>{};const g=new Promise(E=>{m=E});this.preSubAddActiveMap[o.message.streams[0].url]={subAddPromise:f,subActiveResolve:m},this.updatePreSubAdd(o.message.streams[0],g);const S=yield f,v=Date.now();O.info(`[${rt.logName}][datachannel]`,"preSub add done",v-h,S),this.updatePreSubAddStream(o.message.streams[0].url,S[0].stream)}else{if(O.event(`[${rt.logName}][datachannel]`,"<<< Received: preSub active",o.message),!this.preSubAddActiveMap[o.message.streams[0].url])return void O.error(`[${rt.logName}][datachannel]`,"preSub active no record",o.message.streams[0].url);const{subAddPromise:h,subActiveResolve:u}=this.preSubAddActiveMap[o.message.streams[0].url],p=yield h;p[0].urlTraceId=o.message.streams[0].url_traceid,u(p),this.updatePreSubActive(o.message.streams[0])}})),this.rts.on("prePub",o=>_(this,null,function*(){var l,d,h,u;O.event(`[${rt.logName}][datachannel]`,"<<< Received: prePub add",o),this._willPrePub=!1,this.pubAddedMark!==`${(l=this.prePubSdpInfo)==null?void 0:l.aMsid}-${(d=this.prePubSdpInfo)==null?void 0:d.vMsid}`?this.prePubPromise=(()=>_(this,null,function*(){var m,g,S,v;yield this.startDefaultDevicesPromise;const{audio:p,video:f}=c.publishStreams;if(p||f){let E=p||f;p&&f&&(p.mergeStream(f),E=p);const T=o.message.streams[0];return yield this.rts.publishAdd([{url:T.url,stream:E,updateSourceStream:!1,aMsid:(m=this.prePubSdpInfo)!=null&&m.aMsid?[this.prePubSdpInfo.aMsid]:void 0,vMsid:(g=this.prePubSdpInfo)!=null&&g.vMsid?[this.prePubSdpInfo.vMsid]:void 0}],o.message,{video:(S=this.prePubSdpInfo)==null?void 0:S.vSsrcs,audio:(v=this.prePubSdpInfo)==null?void 0:v.aSsrcs})}throw new Error("no stream to publish")}))():O.info(`[${rt.logName}]`,"prePub add already added",(h=this.prePubSdpInfo)==null?void 0:h.aMsid,(u=this.prePubSdpInfo)==null?void 0:u.vMsid)}))}willPrePub(){return this._willPrePub}willPreSubMsid(e){var i;if(!e)return!0;const t=(i=this.prePubSubConfig)==null?void 0:i.preSub;return e===L.Audio?e===(t==null?void 0:t.aMsid):e===(t==null?void 0:t.vMsid)}updatePreSubAdd(e,t){var i,n;this.preSubInfoMap[e.url]={url:e.url,code:e.res_code,message:e.res_msg,aMsid:(i=e.msid.find(a=>a.type==="audio"))==null?void 0:i.name,vMsid:(n=e.msid.find(a=>a.type==="video"))==null?void 0:n.name,traceId:e.traceid,subAddPromise:t}}updatePreSubAddStream(e,t){this.preSubInfoMap[e]?this.preSubInfoMap[e].stream=t:O.error(`[${rt.logName}]`,"preSub add stream has no record",e)}updatePreSubActive(e){const t=this.preSubInfoMap[e.url];t?this.preSubInfoMap[e.url]=Q(D({},t),{code:e.res_code,message:e.res_msg,urlTraceId:e.url_traceid}):O.error(`[${rt.logName}]`,"preSub active stream has no record",e.url)}processMsgPiece(e){if(e.body&&(this.msgPieces.push(e.body),e.isFin)){const t=String.fromCharCode(...new Uint8Array(Kd(this.msgPieces)));return this.msgPieces=[],t}}connect(e,t,i){this.startDefaultDevicesPromise=i,this.prePubSubConfig=t,this._willPrePub=!!(t.prePub.aMsid||t.prePub.vMsid),O.info(`[${rt.logName}]`,"connect",e,t);const n=new zp({sendVideo:!!t.prePub.vMsid,sendAudio:!!t.prePub.aMsid,recvVideo:!!t.preSub.vMsid,recvAudio:!!t.preSub.aMsid,audioCodecPreferences:this.rtsManager.audioCodecPreferences});return new Promise((a,c)=>{var h,u;const o=(u=(h=window.__ali_prefer_media_server)!=null?h:e.onepc.l1subipwithmode)!=null?u:e.onepc.l1subip;if(O.info(`[${rt.logName}]`,"connect",o),!o)return void c({errorCode:z.ERR_INNER,message:"no remote ip"});const l={remoteIp:o,answerFingerprint:e.h5auth.fingerprint,serverInfo:e.h5auth.ice_ufrag,offerSdpHook:En};this.rts.onePcConnect(l).then(p=>{O.info(`[${rt.logName}]`,"onePcConnect",p)}).catch(p=>{O.error(`[${rt.logName}]`,"onePcConnect",p),c({errorCode:z.ERR_INNER,message:"onePcConnect failed"})});const d=e.onepc.pulldomain;this.rts.on("datachannelStatusChange",p=>_(this,null,function*(){if(O.event(`[${rt.logName}]`,"rts datachannelStatusChange to:",p.status),p.status===yt.DATACHANNEL_STATUS_OPEN){let f,m,g=null,S=null;if(n.sendOffer&&n.recvOffer?(g=n.sendOffer,S=n.recvOffer):(yield n.ready,g=n.sendOffer,S=n.recvOffer),g){const B=this.rts.processPublishOffer(g,{aMsid:t.prePub.aMsid?[t.prePub.aMsid]:void 0,vMsid:t.prePub.vMsid?[t.prePub.vMsid]:void 0});if(B){const{sdp:F,videoSsrcs:X,audioSsrcs:$}=B;f=F,this.prePubSdpInfo={aMsid:t.prePub.aMsid,vMsid:t.prePub.vMsid,aSsrcs:$,vSsrcs:X}}}S&&(m=this.rts.processSubscribeOffer(S),m&&(m=En(m)));const v=[];t.prePub.vMsid&&v.push({name:t.prePub.vMsid,type:"video"}),t.prePub.aMsid&&v.push({name:t.prePub.aMsid,type:"audio"});const E=[];t.preSub.vMsid&&(t.preSub.preferVideoSmall&&E.push({name:L.VideoSmall,type:"video"}),E.push({name:t.preSub.vMsid,type:"video"})),t.preSub.aMsid&&E.push({name:t.preSub.aMsid,type:"audio"});const T=this.packageCreator.createJoinPackage(D(D({auth:{nonce:this.authInfo.nonce,token:this.authInfo.token,timestamp:this.authInfo.timestamp},subdomain:d,clitype:2},f?{prepub:{minisdp:Rn(JSON.stringify({streams:[{method:"add",msid:v,sdp:f}]}))}}:{}),m?{presub:{minisdp:Rn(JSON.stringify({streams:[{method:"add",msid:E,sdp:m}]}))}}:{}));T.data.configure={channelprofile:this.channelProfile},this.channelProfile!==Jt.AliRtcSdkInteractiveLive&&this.channelProfile!==Jt.AliRtcSdkInteractiveWithLowLatencyLive||(T.data.configure.clientrole=this.clientRole);const R=JSON.stringify(T),y=vn(new TextEncoder().encode(R).buffer,1156),C=y.map((B,F)=>new Lr(new Nr(B.byteLength,F===y.length-1,F===0?1:0,void 0,void 0,void 0,void 0,2),B).toGRTNBuffer().slice(4));C.unshift(new Uint8Array([4,0,0,0,0]).buffer);const w=`artc://${d}/roomserver-rtc/${function(B=24){const F="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let X="";for(let $=0;$<B;$++)X+=F.charAt(Math.floor(62*Math.random()));return X}()}_${this.authInfo.sessionId}?rtcAppid=${this.authInfo.appId}&ali_grtn_biz=rtcrooms&ali_grtn_bizaddr=${e.grtnbacksvr}&ali_grtn_bizport=${e.grtnbacksvrport}`;O.info(`[${rt.logName}]`,"joinPubSub start",w);let A=Kd(C);const P=performance.now(),M=typeof CompressionStream!="undefined";M&&(A=yield function(B){return _(this,null,function*(){const F=typeof B=="string"?new TextEncoder().encode(B):new Uint8Array(B),X=new CompressionStream("gzip"),$=X.writable.getWriter();$.write(F),$.close();const se=[],N=X.readable.getReader();for(;;){const{done:ce,value:ue}=yield N.read();if(ce)break;se.push(ue)}const V=se.reduce((ce,ue)=>ce+ue.length,0),x=new Uint8Array(V);let U=0;for(const ce of se)x.set(ce,U),U+=ce.length;return x.buffer})}(A));const I=performance.now();O.info(`[${rt.logName}]`,"joinPubSub","compress",M,"time",I-P);const{datachannel:j,traceId:K}=yield this.rts.joinPubSub({url:w,msid:L.Data,label:"roomServerChannel",compress:M,appOpaqueData:Rn(String.fromCharCode(...new Uint8Array(A)))},B=>{if(B instanceof ArrayBuffer){const F=Lr.parse(B.slice(4)),X=this.processMsgPiece(F);if(X){const $=JSON.parse(X);$.msgtype!=="keepalive"&&O.info("[roomServerChannel] <== ",$),this.emit("onMessage",new MessageEvent("message",{data:X})),$.msgtype==="joinchannel"&&$.code===200?(this.keepAliveTimer=window.setInterval(()=>{const se=this.packageCreator.createKeepAlivePackage();this.send(se)},5e3),a($)):$.msgtype==="bye"&&this.rts.onePcDisconnect()}}});this.roomServerChannel=j,this.waitingPackages.length>0&&(this.waitingPackages.forEach(B=>this.send(B)),this.waitingPackages=[]),O.info(`[${rt.logName}]`,"joinPubSub success",K)}else c({errorCode:z.ERR_INNER,message:"signal datachannel error"})}))})}send(e){if(this.roomServerChannel){e.msgtype!=="keepalive"&&O.info("[roomServerChannel] ==> ",e);const t=JSON.stringify(e),i=vn(new TextEncoder().encode(t).buffer,1156);i.map((n,a)=>new Lr(new Nr(n.byteLength,a===i.length-1,a===0?1:0,void 0,void 0,void 0,void 0,2),n).toGRTNBuffer()).forEach(n=>{var a;(a=this.roomServerChannel)==null||a.send(n)})}else this.waitingPackages.push(e)}leave(){window.clearInterval(this.keepAliveTimer)}};b(rt,"logName","OnePcManager");let yn=rt;class Tn{constructor(r,e){b(this,"originTrack");b(this,"originVideo");b(this,"targetWidth");b(this,"targetHeight");b(this,"targetFrameRate");b(this,"targetCanvas");b(this,"animationFrameId");b(this,"resultTrack");this.targetWidth=e.width,this.targetHeight=e.height,this.targetFrameRate=e.frameRate,this.originTrack=r,this.originVideo=document.createElement("video"),this.originVideo.muted=!0,this.originVideo.autoplay=!0,this.originVideo.controls=!1,this.targetCanvas=document.createElement("canvas"),this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight}updateOptions(r){this.targetWidth=r.width,this.targetHeight=r.height,this.targetFrameRate=r.frameRate,this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight,this.resultTrack&&this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})}dispose(){}getVideoTrack(){return this.resultTrack||(this.resultTrack=this.targetCanvas.captureStream().getVideoTracks()[0],this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})),this.resultTrack}cancelAnimation(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}getPositionAndSize(r,e,t,i){const n=e/r,a=i/t;let c=t,o=i,l=0,d=0;return a>n?(c=Math.round(o/n),l=Math.round((t-c)/2)):a<n&&(o=Math.round(c*n),d=Math.round((i-o)/2)),{x:l,y:d,width:c,height:o}}}class Kp extends Tn{constructor(e,t){super(e,t);b(this,"targetCtx");this.targetCtx=this.targetCanvas.getContext("2d"),this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.initStream(e)}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender)}startRender(){this.cancelAnimation();const e=()=>{if(!this.targetCtx)return;const t=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight);this.targetCtx.drawImage(this.originVideo,0,0,this.originVideo.videoWidth,this.originVideo.videoHeight,t.x,t.y,t.width,t.height),this.originVideo.paused||this.originVideo.ended||(this.animationFrameId=requestAnimationFrame(e))};e()}stopRender(){this.cancelAnimation()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.pause(),this.originVideo.srcObject=null}}function Jd(s,r,e){const t=s.createShader(r);if(t)return s.shaderSource(t,e),s.compileShader(t),s.getShaderParameter(t,s.COMPILE_STATUS)?t:(console.error(`An error occurred compiling the shaders: ${s.getShaderInfoLog(t)}`),s.deleteShader(t),null);console.error("create shader failed")}class $d extends Tn{constructor(e,t){super(e,t);b(this,"targetCtx");b(this,"targetTexture");b(this,"locationMap");this.targetCtx=this.targetCanvas.getContext("webgl2"),this.locationMap={},this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.updateBuffer=this.updateBuffer.bind(this),this.initGL(),this.initStream(e)}static isSupport(){return function(){let e;try{const t=document.createElement("canvas");t.width=1,t.height=1;const i={alpha:!1,depth:!1,stencil:!1,antialias:!1,preferLowPowerToHighPerformance:!0};e=t.getContext("webgl2",i)}catch(t){return!1}return!!e}()}initGL(){const e=this.targetCtx;if(!e)return;this.targetTexture=function(o){const l=o.createTexture();return o.bindTexture(o.TEXTURE_2D,l),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),l}(e);const t=function(o,l,d){const h=Jd(o,o.VERTEX_SHADER,l),u=Jd(o,o.FRAGMENT_SHADER,d),p=o.createProgram();if(p&&h&&u)return o.attachShader(p,h),o.attachShader(p,u),o.linkProgram(p),o.getProgramParameter(p,o.LINK_STATUS)?p:(console.error(`Unable to initialize the shader program: ${o.getProgramInfoLog(p)}`),null)}(e,`
10
215
  attribute vec2 a_position;
11
216
  attribute vec2 a_texCoord;
12
217
 
@@ -36,7 +241,7 @@ uniform sampler2D u_texture;
36
241
  void main() {
37
242
  gl_FragColor = texture2D(u_texture, v_texCoord);
38
243
  }
39
- `);if(!t)return void console.log("[ScalerWebGL] program is null.");e.useProgram(t);const i=e.getAttribLocation(t,"a_position"),r=e.getAttribLocation(t,"a_texCoord"),n=e.getUniformLocation(t,"u_resolution");if(!n)return void console.log("[ScalerWebGL] resolutionLocation is null.");const c=e.getUniformLocation(t,"u_texture");c?(this.locationMap={program:t,positionLocation:i,texCoordLocation:r,resolutionLocation:n,textureLocation:c},this.updateBuffer()):console.log("[ScalerWebGL] textureLocation is null.")}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender),this.originVideo.addEventListener("resize",this.updateBuffer)}startRender(){this.cancelAnimation();const e=()=>{this.targetCtx&&(this.renderTexture(),this.originVideo.paused||this.originVideo.ended||(this.animationFrameId=requestAnimationFrame(e)))};e()}updateBuffer(){const e=this.targetCtx,t=this.locationMap.positionLocation,i=this.locationMap.texCoordLocation,r=this.locationMap.resolutionLocation;if(!e||!this.originVideo.videoWidth||!this.originVideo.videoHeight)return;const n=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight),c=function(l,d,h,p=0,u=0){const f=l.createBuffer();l.bindBuffer(l.ARRAY_BUFFER,f);const m=d+p,b=h+u,S=[p,u,m,u,p,b,p,b,m,u,m,b];return l.bufferData(l.ARRAY_BUFFER,new Float32Array(S),l.STATIC_DRAW),f}(e,n.width,n.height,n.x,n.y);e.enableVertexAttribArray(t),e.bindBuffer(e.ARRAY_BUFFER,c),e.vertexAttribPointer(t,2,e.FLOAT,!1,0,0),e.enableVertexAttribArray(i);const o=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,o),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,o),e.vertexAttribPointer(i,2,e.FLOAT,!1,0,0),e.uniform2f(r,this.targetWidth,this.targetHeight)}renderTexture(){const e=this.targetTexture,t=this.targetCtx,i=this.locationMap.textureLocation;e&&t&&(t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.originVideo),t.useProgram(this.locationMap.program),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e),t.uniform1i(i,0),t.viewport(0,0,t.canvas.width,t.canvas.height),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.drawArrays(t.TRIANGLES,0,6))}stopRender(){this.cancelAnimation()}updateOptions(e){super.updateOptions(e),this.updateBuffer()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.removeEventListener("resize",this.updateBuffer),this.originVideo.pause(),this.originVideo.srcObject=null}}class ba extends dr{constructor(e,t){super(e,t);g(this,"processor");g(this,"trackGenerator");g(this,"worker");this.processor=new MediaStreamTrackProcessor({track:e}),this.trackGenerator=new MediaStreamTrackGenerator({kind:"video"}),this.startTransform()}static isSupport(){return"MediaStreamTrackProcessor"in window&&"MediaStreamTrackGenerator"in window&&"TransformStream"in window&&"VideoFrame"in window}startTransform(){const e=new Blob([`
244
+ `);if(!t)return void console.log("[ScalerWebGL] program is null.");e.useProgram(t);const i=e.getAttribLocation(t,"a_position"),n=e.getAttribLocation(t,"a_texCoord"),a=e.getUniformLocation(t,"u_resolution");if(!a)return void console.log("[ScalerWebGL] resolutionLocation is null.");const c=e.getUniformLocation(t,"u_texture");c?(this.locationMap={program:t,positionLocation:i,texCoordLocation:n,resolutionLocation:a,textureLocation:c},this.updateBuffer()):console.log("[ScalerWebGL] textureLocation is null.")}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender),this.originVideo.addEventListener("resize",this.updateBuffer)}startRender(){this.cancelAnimation();const e=()=>{this.targetCtx&&(this.renderTexture(),this.originVideo.paused||this.originVideo.ended||(this.animationFrameId=requestAnimationFrame(e)))};e()}updateBuffer(){const e=this.targetCtx,t=this.locationMap.positionLocation,i=this.locationMap.texCoordLocation,n=this.locationMap.resolutionLocation;if(!e||!this.originVideo.videoWidth||!this.originVideo.videoHeight)return;const a=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight),c=function(l,d,h,u=0,p=0){const f=l.createBuffer();l.bindBuffer(l.ARRAY_BUFFER,f);const m=d+u,g=h+p,S=[u,p,m,p,u,g,u,g,m,p,m,g];return l.bufferData(l.ARRAY_BUFFER,new Float32Array(S),l.STATIC_DRAW),f}(e,a.width,a.height,a.x,a.y);e.enableVertexAttribArray(t),e.bindBuffer(e.ARRAY_BUFFER,c),e.vertexAttribPointer(t,2,e.FLOAT,!1,0,0),e.enableVertexAttribArray(i);const o=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,o),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,o),e.vertexAttribPointer(i,2,e.FLOAT,!1,0,0),e.uniform2f(n,this.targetWidth,this.targetHeight)}renderTexture(){const e=this.targetTexture,t=this.targetCtx,i=this.locationMap.textureLocation;e&&t&&(t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.originVideo),t.useProgram(this.locationMap.program),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e),t.uniform1i(i,0),t.viewport(0,0,t.canvas.width,t.canvas.height),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.drawArrays(t.TRIANGLES,0,6))}stopRender(){this.cancelAnimation()}updateOptions(e){super.updateOptions(e),this.updateBuffer()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.removeEventListener("resize",this.updateBuffer),this.originVideo.pause(),this.originVideo.srcObject=null}}class Xd extends Tn{constructor(e,t){super(e,t);b(this,"processor");b(this,"trackGenerator");b(this,"worker");this.processor=new MediaStreamTrackProcessor({track:e}),this.trackGenerator=new MediaStreamTrackGenerator({kind:"video"}),this.startTransform()}static isSupport(){return"MediaStreamTrackProcessor"in window&&"MediaStreamTrackGenerator"in window&&"TransformStream"in window&&"VideoFrame"in window}startTransform(){const e=new Blob([`
40
245
  var targetOptions={
41
246
  width: 320,
42
247
  height: 180,
@@ -121,17 +326,15 @@ onmessage = function(evt) {
121
326
  break;
122
327
  }
123
328
  }
124
- `],{type:"text/javascript"}),t=(window.URL||window.webkitURL).createObjectURL(e);this.worker=new Worker(t);const{readable:i}=this.processor,{writable:r}=this.trackGenerator;this.worker.postMessage({type:"startRender",readable:i,writable:r,width:this.targetWidth,height:this.targetHeight,frameRate:this.targetFrameRate},[i,r])}updateOptions(e){super.updateOptions(e),this.worker&&this.worker.postMessage(G({type:"updateOptions"},e))}dispose(){try{this.processor.readable.cancel(),this.trackGenerator.writable.close()}catch(e){}}getVideoTrack(){return this.trackGenerator}}class hr{static isSupport(){return typeof HTMLCanvasElement.prototype.captureStream=="function"}static getInstance(a,e){return ba.isSupport()?new ba(a,e):Sa.isSupport()?new Sa(a,e):new No(a,e)}}var va,ya,xo=Object.defineProperty,Jt=(s,a,e)=>(((t,i,r)=>{i in t?xo(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r})(s,typeof a!="symbol"?a+"":a,e),e),ur={exports:{}},pr={exports:{}};function Ye(){if(ya)return va;ya=1,Date.now=Date.now||function(){return new Date().getTime()};var s=Date.now(),a=function(){},e={noop:a,warn:function(){var t=typeof console=="object"?console.warn:a;try{var i={warn:t};i.warn.call(i)}catch(r){return a}return t}(),key:"__bl",selfErrKey:"ARMS_SDK_ERROR",selfErrPage:"ARMSSDK",win:typeof window=="object"&&window.document?window:void 0,regionMap:{cn:"https://arms-retcode.aliyuncs.com/r.png?",sg:"https://arms-retcode-sg.aliyuncs.com/r.png?",sg_2:"https://retcode-sg-lazada.arms.aliyuncs.com/r.png?",daily:"http://arms-retcode-daily.alibaba.net/r.png?",daily_2:"https://arms-retcode-daily.alibaba.net/r.png?",daily_3:"http://arms-retcode-daily.aliyun.test/r.png?",us:"https://retcode-us-west-1.arms.aliyuncs.com/r.png?",tw:"https://arms-retcode.orientalgame.com.tw/r.png?",tw_sg:"https://arms-retcode-sg.orientalgame.com.tw/r.png?",hz_finance:"https://arms-retcode-hz-finance.aliyuncs.com/r.png?"},defaultImgUrl:"https://arms-retcode.aliyuncs.com/r.png?",createObject:function(t){if(Object.create)return Object.create(t);var i=function(){};return i.prototype=t,new i},each:function(t,i){var r=0,n=t.length;if(this.T(t,"Array"))for(;r<n&&i.call(t[r],t[r],r)!==!1;r++);else for(r in t)if(i.call(t[r],t[r],r)===!1)break;return t},safetyCall:function(t,i,r){if(typeof t!="function")return r;try{return t.apply(this,i)}catch(n){return r}},T:function(t,i){var r=Object.prototype.toString.call(t).substring(8).replace("]","");return i?r===i:r},duration:function(){var t=Date;try{performance&&this.T(performance.now,"Function")&&(t=performance)}catch(r){t=Date}var i=t.now();return function(){return Math.round(t.now()-i)}},filterByRule:function(){var t=[].slice.call(arguments),i=t.length;if(i<2)return t[0];var r=t[i-1],n=t[0];if(!n)return"";if(!r)return n;var c=this,o=c.T(r),l=t.slice(0,i-1);return o==="Function"?c.safetyCall(r,l,n):o==="Array"?(this.each(r,function(d){l[0]=n=c.filterByRule.apply(c,[].concat(l,d))}),n):o==="Object"?n.replace(r.rule,r.target||""):n.replace(r,"")},ignoreByRule:function(t,i){if(!t||!i)return!1;if((this.isString(i)||i.source||this.T(i)==="Function")&&(i=[i]),!this.isArray(i))return this.warn("[arms] invalid rules of ignore config, (list of) String/RegExp/Funcitons are available"),!1;for(var r,n=[],c=0,o=i.length;c<o;c++)if(r=i[c],this.isString(r))n.push(r.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1"));else if(r&&r.source)n.push(r.source);else if(r&&this.T(r)==="Function"&&this.safetyCall(r,[t],!1)===!0)return!0;var l=new RegExp(n.join("|"),"i");return!!(n.length&&l.test&&l.test(t))},J:function(t){if(!t||typeof t!="string")return t;var i=null;try{i=JSON.parse(t)}catch(r){}return i},pick:function(t){return t===1||Math.ceil(Math.random()*t)===1},verifyConfig:function(t){if("sample"in t){var i=t.sample,r=i;i&&/^\d+(\.\d+)?%$/.test(i)&&(r=parseInt(100/parseFloat(i))),0<r&&1>r&&(r=parseInt(1/r)),r>=1&&r<=100?t.sample=r:delete t.sample}return t},on:function(t,i,r,n,c){return t.addEventListener?(c=c||!1,t.addEventListener(i,function o(l){n&&t.removeEventListener(i,o,c),r.call(this,l)},c)):t.attachEvent&&t.attachEvent("on"+i,function o(l){n&&t.detachEvent("on"+i,o),r.call(this,l)}),this},off:function(t,i,r){return r?(t.removeEventListener?t.removeEventListener(i,r):t.detachEvent&&t.detachEvent(i,r),this):this},delay:function(t,i){return i===-1?(t(),null):setTimeout(t,i||0)},ext:function(t){for(var i=1,r=arguments.length;i<r;i++){var n=arguments[i];for(var c in n)Object.prototype.hasOwnProperty.call(n,c)&&(t[c]=n[c])}return t},sub:function(t,i){var r={};return this.each(t,function(n,c){i.indexOf(c)!==-1&&(r[c]=n)}),r},uu:function(){for(var t,i,r=20,n=new Array(r),c=Date.now().toString(36).split("");r-- >0;)i=(t=36*Math.random()|0).toString(36),n[r]=t%3?i:i.toUpperCase();for(var o=0;o<8;o++)n.splice(3*o+2,0,c[o]);return n.join("")},guid:function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var i=16*Math.random()|0;return(t==="x"?i:3&i|8).toString(16)})},seq:function(){return(s++).toString(36)},decode:function(t){try{t=decodeURIComponent(t)}catch(i){}return t},encode:function(t,i){try{t=i?encodeURIComponent(t).replace(/\(/g,"%28").replace(/\)/g,"%29"):encodeURIComponent(t)}catch(r){}return t},serialize:function(t){t=t||{};var i=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&t[r]!==void 0&&i.push(r+"="+this.encode(t[r],r==="msg"));return i.join("&")},checkAPI:function(t,i){if(!t||typeof t!="string")return!1;var r=/arms-retcode[\w-]*\.aliyuncs/.test(t);return!r&&i&&(r=/(alicdn\.com)|(mmstat\.com)/.test(t)),!r},checkAutoError:function(t){return!(!t||!t.message||/failed[\w\s]+fetch/i.test(t.message))},cutUrlSearch:function(t){return t&&typeof t=="string"?t.replace(/^(https?:)?\/\//,"").replace(/\?.*$/,""):""},removeUrlSearch:function(t){return t&&typeof t=="string"?t.replace(/\?.*$/,""):""},createFakeToString:function(t){return function(){return t+"() { [native code] }"}},checkSameOrigin:function(t,i){if(!i||!t)return!1;var r="//"+i.split("/")[2];return t===i||t.slice(0,i.length+1)===i+"/"||t===r||t.slice(0,r.length+1)===r+"/"||!/^(\/\/|http:|https:).*/.test(t)},getRandIP:function(){for(var t=[],i=0;i<4;i++){var r=Math.floor(256*Math.random());t[i]=(r>15?"":"0")+r.toString(16)}return t.join("").replace(/^0/,"1")},getSortNum:function(t){return t?(t+=1)>=1e3&&t<=9999?t:t<1e3?t+1e3:t%1e4+1e3:1e3},getRandNum:function(t){return t&&typeof t=="string"?t.length<5?this.getNum(5):t.substring(t.length-5):this.getNum(5)},getNum:function(t){for(var i=[],r=0;r<t;r++){var n=Math.floor(16*Math.random());i[r]=n.toString(16)}return i.join("")},getCurDomain:function(){return location&&location.hostname||""},getSrcType:function(t,i){var r=location&&location.host||"";if(!r)return"";var n=new URL(t).host;if(n===r)return"self";for(var c=0;c<i.length;c+=1)if(n.includes(i[c]))return"cdn";return"others"},parseFetchHeaders:function(t){if(!t)return{};var i={};try{if(typeof t.keys=="function")for(var r=t.keys(),n=r.next();!n.done;){var c=n.value;i[c]=t.get(c),n=r.next()}else i=t}catch(o){i={}}return i},parseXhrHeaders:function(t){if(!t&&typeof t!="string")return{};var i={};try{i=t.split(`\r
125
- `).reduce(function(r,n){var c=n.split(": ");return r[c[0]]=c[1],r},{})}catch(r){i={}}return i},getQuerys:function(t){if(!t)return"";var i={},r=[],n="",c="";try{var o=[];if(t.indexOf("?")>=0&&(o=t.substring(t.indexOf("?")+1,t.length).split("&")),o.length>0)for(var l in o)n=(r=o[l].split("="))[0],c=r[1],i[n]=c}catch(d){i={}}return i},getURL:function(t){if(!t)return null;var i={},r=t.length,n=t.indexOf("://");if(n<0)return null;i.protocol=t.substring(0,n+1);var c=t.indexOf("#"),o=t.indexOf("?");c<0&&(c=r),o<0&&(o=c),i.search=t.substring(o,c).substring(0,1e3);var l=t.substring(n+3,o),d=l.indexOf("/");return d<0&&(d=l.length),i.domain=l.substring(0,d).split(":")[0],i.path=l.substring(d,l.length).substring(0,1e3),i},getResType:function(t,i){if(["script","img","other"].indexOf(t)>-1)return t;if(["video"].indexOf(t)>-1)return"media";if(["document","iframe"].indexOf(t)>-1)return"doc";var r=i?this.getURL(i):null,n=r&&r.path?r.path.lastIndexOf("."):-1,c=(n>0?r.path.substr(n+1):"").toLowerCase();if(c){if(["eot","woff","woff2","ttf"].indexOf(c)>-1)return"font";if(c==="css")return"css";if(c==="js")return"script"}return["fetch","xmlhttprequest","beacon"].indexOf(t)>-1?"api":"others"},areInOrder:function(){for(var t=1;t<arguments.length;t+=1)if(arguments[t-1]>arguments[t])return!1;return!0},getFetchSnapshot:function(t,i,r){var n,c;try{var o=(t&&typeof t[0]!="string"?t[0].url:t[0])||"",l=(t&&typeof t[0]!="string"?t[0]:t[1])||{},d=l.method.toUpperCase()==="POST"?l.body:this.getQuerys(o);n={originApi:o,method:l.method||"unknown",params:d,response:i||"",reqHeaders:this.parseFetchHeaders(l.headers||null),resHeaders:this.parseFetchHeaders(r)},c=JSON&&JSON.stringify(n)||"{}"}catch(h){c="{}"}return c},getXhrSnapshot:function(t,i,r){if(!t||!i||!r)return{};var n,c;try{var o="";r.responseType===""||r.responseType==="text"?o=r.responseText:r.responseType==="document"&&(o=r.responseXML),n={originApi:t,method:i,params:this.getQuerys(t),response:o,reqHeaders:{},resHeaders:this.parseXhrHeaders(typeof r.getAllResponseHeaders=="function"&&r.getAllResponseHeaders()||"")},c=JSON&&JSON.stringify(n)||"{}"}catch(l){c="{}"}return c},isRobot:function(){var t=["nuhk","googlebot/","googlebot-image","yammybot","openbot","slurp","msnbot","ask jeeves/teoma","ia_archiver","baiduspider","bingbot/","adsbot"];if(!navigator||typeof navigator.userAgent!="string")return!1;try{for(var i=navigator.userAgent.toLowerCase(),r=0;r<t.length;r++){var n=t[r];if(i.lastIndexOf(n)>=0)return!0}}catch(c){this.warn("[arms] useragent parse error")}return!1},isFunction:function(t){return typeof t=="function"},isPlainObject:function(t){return Object.prototype.toString.call(t)==="[object Object]"},isString:function(t){return Object.prototype.toString.call(t)==="[object String]"},isArray:function(t){return Object.prototype.toString.call(t)==="[object Array]"},joinRegExp:function(t){for(var i,r=[],n=0,c=t.length;n<c;n++)i=t[n],this.isString(i)?r.push(i.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")):i&&i.source&&r.push(i.source);return new RegExp(r.join("|"),"i")},reWriteMethod:function(t,i,r){if(t!==null){var n=t[i];t[i]=r(n)}},checkSDKError:function(t,i){return!(!t&&!i)&&(!!new RegExp(this.selfErrKey,"i").test(t)||!!this.ignoreByRule(i,[/retcode.alicdn.com\/retcode\/bl.js/,/g.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/laz-g-cdn.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/local.taobao.com:8880\/build\/bl/]))},sdkError:function(t){return{msg:t,message:this.selfErrKey}},dealParam:function(t,i,r){var n={};try{n=this.isPlainObject(t)?this.ext({key:t.key||"default",val:t.val||t.value||r},t,{begin:Date.now()}):{key:t||"default",val:i||r,begin:Date.now()}}catch(c){this.warn("[retcode] baseLog error: "+c)}return n}};return va=e}var gr,Ra,Aa,_a,mr={exports:{}},fr={exports:{}};function Oo(){if(Aa)return fr.exports;Aa=1;var s=Ye(),a=function(){if(Ra)return gr;Ra=1;var r=Ye();return gr=function(n,c,o){typeof n=="object"&&(n=r.serialize(n));var l=c+n+(o?"&post_res=":"");window&&window.navigator&&typeof window.navigator.sendBeacon=="function"?window.navigator.sendBeacon(l,o||"&post_res="):r.warn("[arms] navigator.sendBeacon not surported")},gr}(),e="aokcdqn3ly@e629dabd48a9933",t=function(r,n){var c;if(n.t==="error"&&(c=r.requestQueue[0])&&c.t==="error"&&n.msg===c.msg)return n.times=c.times+1,void(r.requestQueue[0]=n);if(n.t==="behavior"){var o=r.requestQueue&&r.requestQueue.length;if(o>0&&r.requestQueue[o-1].t==="behavior"){var l=n.behavior||[];r.requestQueue[o-1].behavior.concat(l)}else r.requestQueue.push(n)}else r.requestQueue.unshift(n);return r.onReady(function(){r.requestTimmer=s.delay(function(){r.clear()},r.requestQueue[0]&&r.requestQueue[0].t==="error"?3e3:-1)}),!0},i=function(r){return this.ver="1.8.36-beta.12",this._conf=s.ext({},i.dftCon),this.sampleCache={},this.requestQueue=[],this.selfQueue=[],this.sdkFlag=!0,this.hash=s.seq(),this.resetPageview(),this.setConfig(r),this.rip=s.getRandIP(),this.record=999,this["EagleEye-TraceID"]=this.getTraceId()["EagleEye-TraceID"],this._common={},this};return i.dftCon={sample:1,pvSample:1,tag:"",imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",region:null,ignore:{ignoreUrls:[],ignoreApis:[],ignoreErrors:[/^Script error\.?$/],ignoreResErrors:[],ignoreResources:[/\/(bl|wl)(.debug)?.js$/]},release:void 0,environment:"prod",beforeReport:null,parseTraceId:null},i.prototype={constructor:i,onReady:function(r){return r()},getPage:function(){var r=this._conf.page;return s.safetyCall(r,[],r+"")},setPage:function(){},setConfig:function(r){r&&typeof r=="object"&&(s.verifyConfig(r),r=this.setImgUrl(r),this._conf=s.ext({},this._conf,r))},setImgUrl:function(r){var n=r.region,c=r.imgUrl;if(n){var o=s.regionMap[n];return r.imgUrl=o||s.defaultImgUrl,r}return c&&(r.imgUrl=c),r},checkImgUrl:function(){return!0},sendRequest:function(){},sendBeacon:function(r,n,c){a(r,n||this.getConfig("imgUrl"),c)},postData:function(){},commonInfo:function(){return{}},setCommonInfo:function(r){r&&typeof r=="object"&&(this._common=s.ext({},this._common,r))},resetPageview:function(){this.pageview=s.uu(),this.sBegin=Date.now()},getUsername:function(){if(this.username)return this.username;var r=this._conf,n=r&&r.setUsername;if(typeof n=="function")try{var c=n();typeof c=="string"&&(c=c.substr(0,40),this.username=c)}catch(o){s.warn("[arms] setUsername fail",o)}return this.username},getTraceId:function(){var r=this.rip,n=Date.now(),c=s.getSortNum(this.record),o=r+n+c+s.getRandNum(this._conf.pid);return this["EagleEye-TraceID"]=o,this.record=c,{"EagleEye-TraceID":o}},getUberTraceId:function(r){var n=this.rip,c=Date.now(),o=s.getSortNum(this.record),l=s.getRandNum(this._conf.pid),d=n+c+o+s.getNum(2)+l,h=d.substring(0,16);return r=r?"1":"0",d[0]==="0"&&(d[0]="1"),d[16]==="0"&&(d[16]="1"),{"uber-trace-id":d+":"+h+":0:"+r,traceId:d}},getB3TraceId:function(r){var n=this.rip,c=Date.now(),o=s.getSortNum(this.record),l=s.getRandNum(this._conf.pid),d=n+c+o+s.getNum(2)+l,h=d.substring(0,16);return r=r?"1":"0",d[0]==="0"&&(d[0]="1"),d[16]==="0"&&(d[16]="1"),{b3:d+"-"+h+"-"+r+"-0","X-B3-TraceId":d,"X-B3-ParentSpanId":"0","X-B3-SpanId":h,"X-B3-Sampled":r}},getPageviewId:function(){return{"EagleEye-SessionID":this.pageview}},getConfig:function(r){return r?this._conf[r]:s.ext({},this._conf)},sampling:function(r){return r===1||(typeof this.sampleCache[r]=="boolean"||(this.sampleCache[r]=s.pick(r)),this.sampleCache[r])},clear:function(r){var n;clearTimeout(this.requestTimmer),this.requestTimmer=null;for(var c=this._conf&&typeof this._conf.sendRequest=="function";n=this.requestQueue.pop();)if(n.t==="res")this.postData(n,"res");else if(n.t==="error")this.postData(n,"err");else if(n.t==="api")this.postData(n,"apiSnapshot");else if(n.t==="behavior")this.postData(n,"behavior");else if(n.t==="health"&&!c&&window&&window.navigator&&typeof window.navigator.sendBeacon=="function")this.sendBeacon(n);else if(n.t==="resource"&&!c&&window&&window.navigator&&typeof window.navigator.sendBeacon=="function"){var o=JSON.stringify({resource:n.resource});delete n.resource,this.sendBeacon(n,null,o)}else n.t==="resource"?this.postData(n,"resource"):this.sendRequest(n);return r&&this.clearSelf(),this},clearSelf:function(){var r;for(clearTimeout(this.Timmer),this.Timmer=null;r=this.selfQueue.pop();)this.postData(r,"err");return this},_lg:function(r,n,c,o){var l=this,d=l._conf,h=l.getPage(),p=d.ignore||{},u=p.ignoreErrors,f=p.ignoreResErrors,m=p.ignoreUrls,b=p.ignoreApis;if(l._isRobot||s.ignoreByRule(h,m)||s.ignoreByRule(s.decode(h),m)||r==="error"&&(s.ignoreByRule(n.msg,u)||s.ignoreByRule(s.decode(n.msg),u))||r==="resourceError"&&(s.ignoreByRule(n.src,f)||s.ignoreByRule(s.decode(n.src),f))||r==="api"&&(s.ignoreByRule(n.api,b)||s.ignoreByRule(s.decode(n.api),b))||!l.checkImgUrl(d.imgUrl)||!n||d.disabled||!d.pid||o===0)return l;var S=n.dl;if(delete n.dl,n=s.ext({t:r,times:1,page:h,tag:d.tag||"",release:d.release||"",environment:d.environment,begin:Date.now(),c1:d.c1,c2:d.c2,c3:d.c3},n,l.commonInfo(),l._common,{pid:d.pid,_v:l.ver,pv_id:l.pageview,username:l.getUsername(),sampling:c||1,dl:S,z:s.seq()}),s.T(d.beforeReport)==="Function")try{if(!(n=d.beforeReport(n)))return l}catch(v){return l}return o===1?t(l,n):c&&!l.sampling(c)?l:t(l,n)},_self:function(r,n,c){var o=this,l=o._conf;if(r!=="error"||!o.checkImgUrl(l.imgUrl)||!n||l.disabled||!l.pid||c&&!o.sampling(c))return o;n=s.ext({t:r,times:1,page:s.selfErrPage,tag:l.pid,begin:Date.now()},n,{pid:e,_v:o.ver,sampling:c||1,z:s.seq()});var d=o.selfQueue[0];if(d){d.times++;try{d.err&&n.err&&d.err.msg_raw&&n.err.msg_raw&&d.err.msg_raw.split("&").indexOf(n.err.msg_raw)<0&&d.err.msg_raw.length<1e3&&(d.err.msg_raw+="&"+n.err.msg_raw)}catch(h){}}else o.selfQueue.unshift(n),o.onReady(function(){o.sdkFlag&&(o.sdkFlag=!1,o.Timmer=s.delay(function(){o.clearSelf()},1e4))})},custom:function(r,n){if(!r||typeof r!="object")return this;var c=!1,o={begin:Date.now()};return s.each(r,function(l,d){return!(c=d&&d.length<=20)&&s.warn("[retcode] invalid key: "+d),o["x-"+d]=l,c}),c?this._lg("custom",o,n||1):this}},fr.exports=i,fr.exports}var wa,Sr={exports:{}},Ea,br,Ia,vr={exports:{}};function Vo(){if(Ia)return br;Ia=1;var s=Ye();return br=function(a,e){var t=[],i=null,r=e&&e.location&&e.location.href,n=void 0,c=null,o=function(h,p,u){if(h!==null){var f=h[p];h[p]=u(f)}},l=function(h){var p,u,f,m,b,S=[];if(!h||typeof h.tagName!="string")return"";if(S.push(h.tagName.toLowerCase()),typeof h.id=="string"&&S.push("#".concat(h.id)),typeof(p=h.className)=="string")for(u=p.split(/\s+/),b=0;b<u.length;b++)S.push(".".concat(u[b]));var v=["type","name","title","alt","data-arms-attr"];for(b=0;b<v.length;b++)f=v[b],typeof(m=h.getAttribute(f))=="string"&&S.push("[".concat(f,'="').concat(m,'"]'));return S.join("")},d=function(h,p){return function(u){if(u&&u!==c){var f;c=u;try{f=u.target}catch(b){f="<unknown>"}if(f.length!==0){var m={type:"ui.".concat(h),data:{message:function(b){if(!b||b.nodeType!==1)return"";for(var S=b||null,v=[],R=0,w=0,y="";S&&R++<5&&!((y=l(S))==="html"||R>1&&w+3*v.length+y.length>=80);)v.push(y),w+=y.length,S=S.parentNode;return v.reverse().join(" > ")}(f)},timestamp:Date.now()};h==="click"?i&&i.addBehavior(m):h==="keypress"&&(n||i&&i.addBehavior(m),clearTimeout(n),n=setTimeout(function(){n=void 0},100))}}}};s.ext(a.prototype,{addBehavior:function(h){if(this.getConfig("behavior")&&h&&typeof h=="object"){var p={},u=h.data||{};if(h.type)p=u;else{if(typeof u.name!="string"||typeof u.message!="string")return;p.name=u.name.substr(0,20),p.message=u.message.substr(0,200)}p.message&&(p.message=s.encode(p.message));var f={type:h.type||"custom",data:p||{},timestamp:h.timestamp||Date.now(),page:h.page||e&&e.location&&e.location.pathname};return t.push(f),t=t.slice(-100)}},getBehavior:function(){return t||[]},setBehavior:function(h){return h&&(t=h),t},reportBehavior:function(h){var p=this;p.getConfig("behavior")&&(p.sendBhTimer&&(clearTimeout(p.sendBhTimer),p.sendBhTimer=void 0),p.sendBhTimer=setTimeout(function(){t&&t.length>0&&(p.behavior(t),t=[],p.sendBhTimer=void 0,h&&typeof h=="function"&&h())},0))},initBehavior:function(){if(!this.hasInitBehavior&&!i){try{(function(){if(document&&document.referrer&&document.location){var p=document.referrer,u=document.location.href;if(p!==""){var f={type:"navigation",data:{from:p,to:u}};r=u,i&&i.addBehavior(f)}}})(),e&&e.document&&e.document.addEventListener&&(e.document.addEventListener("click",d("click"),!1),e.document.addEventListener("keypress",d("keypress"),!1)),function(){if(function(){var m=e&&e.chrome,b=m&&m.app&&m.app.runtime,S="history"in e&&!!e.history.pushState&&!!e.history.replaceState;return!b&&S}()){var p=function(m,b){var S={type:"navigation",data:{from:m,to:b}};i&&i.addBehavior(S),r=b},u=e.onpopstate;e.onpopstate=function(){for(var m=arguments.length,b=new Array(m),S=0;S<m;S++)b[S]=arguments[S];var v=e.location.href;if(p(r,v),u)return u.apply(this,b)};var f=function(m){return function(){for(var b=arguments.length,S=new Array(b),v=0;v<b;v++)S[v]=arguments[v];var R=S.length>2?S[2]:void 0;return R&&p(r,String(R)),m.apply(this,S)}};o(e.history,"pushState",f),o(e.history,"replaceState",f)}}();var h=this.getConfig("enableConsole");h&&function(p){if(e&&e.console){var u=["debug","info","warn","log","error","assert"];s.isArray(p)&&(u=p);for(var f=0;f<u.length;f++){var m=u[f];m&&s.isString(m)&&e.console[m]&&typeof e.console[m]=="function"&&o(e.console,m,function(b){var S=m;return function(){for(var v=arguments.length,R=new Array(v),w=0;w<v;w++)R[w]=arguments[w];var y={type:"console",data:{level:S,message:R}};if(i&&i.addBehavior(y),S==="error")for(var A=0;A<R.length;A++){var _=R[A];_&&_.message&&_.stack&&i&&i.errorHandler(new ErrorEvent("error",{error:_,message:_.message}))}b&&Function.prototype.apply.call(b,e.console,R)}})}}}(h)}catch(p){s.warn("[arms] error in initBehavior",p)}i=this,this.hasInitBehavior=!0}return this}})},br}var Ta,yr,Ca,Rr,ka,Pa,Da,Ar,Ma,La,Na,xa,Oa,_r,Va,Ua,Ba,Ha={};function wr(){return Ta||(Ta=1,Ha.TIMING_KEYS=["startTime","fetchStart","domainLookupStart","domainLookupEnd","connectStart","connectEnd","requestStart","responseStart","responseEnd","","domInteractive","","domContentLoadedEventEnd","","loadEventStart","","msFirstPaint","secureConnectionStart","redirectStart","redirectEnd"]),Ha}function Uo(){return Da||(Da=1,Pa=function(s,a,e){var t=Ye(),i=function(){if(Ca)return yr;Ca=1;var m=Ye(),b=wr().TIMING_KEYS;return yr=function(){var S=m.win||{},v=S.performance;if(!v||typeof v!="object"||typeof v.getEntriesByType!="function")return null;var R={},w=v.timing||{},y=v.getEntriesByType("resource")||[];if(R.begin=w[b[1]]||Date.now(),typeof S.PerformanceNavigationTiming=="function"){var A=v.getEntriesByType("navigation")[0];A&&(w=A)}return m.each({dom:[10,8],load:[14,1]},function(_,E){var T=w[b[_[1]]],k=w[b[_[0]]];if(T>0&&k>0){var P=Math.round(k-T);P>=0&&P<6e5&&(R[E]=P)}}),R.res=JSON.stringify(y),R},yr}(),r=function(){if(ka)return Rr;ka=1;var m=Ye(),b=wr().TIMING_KEYS;return Rr=function(){var S=m.win||{},v=S.performance;if(!v||typeof v!="object")return null;var R={},w=v.timing||{},y=Date.now(),A=1;if(typeof S.PerformanceNavigationTiming=="function"){var _=v.getEntriesByType("navigation")[0];_&&(w=_,A=2)}m.each({dns:[3,2],tcp:[5,4],ssl:[5,17],ttfb:[7,6],trans:[8,7],dom:[10,8],res:[14,12],firstbyte:[7,2],fpt:[8,1],tti:[10,1],ready:[12,1],load:[14,1]},function(H,q){var Y=w[b[H[1]]],J=w[b[H[0]]];if(A===2||Y>0&&J>0){var z=Math.round(J-Y);z>=0&&z<6e5&&(R[q]=z)}});var E=S.navigator.connection,T=v.navigation||{};R.ct=E?E.effectiveType||E.type:"";var k=E&&(E.downlink||E.downlinkMax||E.bandwidth)||null;if((k=k>999?999:k)&&(R.bandwidth=k),R.navtype=T.type===1?"Reload":"Other",A===1&&w[b[16]]>0&&w[b[1]]>0){var P=w[b[16]]-w[b[1]];P>=0&&P<36e5&&(R.fpt=P)}return A===1&&w[b[1]]>0?R.begin=w[b[1]]:A===2&&R.load>0?R.begin=y-R.load:R.begin=y,R},Rr}(),n=null,c=e.documentElement,o=a.innerWidth||c.clientWidth||e.body.clientWidth,l=a.innerHeight||c.clientHeight||e.body.clientHeight,d=a.navigator.connection,h={sr:screen.width+"x"+screen.height,vp:o+"x"+l,ct:d?d.effectiveType||d.type:""},p={},u=function(m,b,S,v,R){if(b===void 0){var w,y;if(!p[m]){w=new RegExp(m+"=([^;]+)");try{y=w.exec(e.cookie)}catch(_){return t.warn("[retcode] can not get cookie:",_),null}y&&(p[m]=y[1])}return p[m]}var A=m+"="+b;A+="; path=/",S&&(A+="; max-age="+S);try{return e.cookie=A,!!e.cookie}catch(_){return t.warn("[retcode] can not set cookie: ",_),!1}},f=function(m){var b=m._conf.uid||u("_nk_")||u("_bl_uid");return b||(b=t.uu(),u("_bl_uid",b,15552e3))?b:null};return t.ext(s.prototype,{activeErrHandler:function(m){return n&&!m||(n=this),this},errorHandler:function(m){if(!m)return this;var b=m.type;if(b==="error"){var S=m.target||m.srcElement;!S||!S.tagName||m.message||m.filename||m.lineno||m.colno?this.error(m.error||{message:m.message},m):this.resourceErrorHandler(m)}else b==="unhandledrejection"&&t.T(m.reason,"Error")&&t.checkAutoError(m.reason)&&this.error(m.reason);try{this.getConfig("behavior")&&this.reportBehavior&&this.reportBehavior()}catch(v){}return this},resourceErrorHandler:function(m){var b=this,S=m.target||m.srcElement;try{var v=b.getSrc(S),R=typeof S.tagName=="string"?S.tagName.toLowerCase():"",w=b.getXPath(S,5),y=t.getURL(v),A={src:v&&v.substring(0,1e3),node_name:R,xpath:w,res_type:t.getResType(R,v),res_name:y.path,domain:y.domain};return b._conf.enableResource&&b.fixResourceStatus&&m.timeStamp&&b.fixResourceStatus({src:v,node_name:R,res_type:t.getResType(R,v),timeStamp:m.timeStamp,domain:y.domain}),b._lg("resourceError",A),b}catch(_){return t.warn("[ARMS] resourceErrorHandler error :",_),b}},getSrc:function(m){var b=m.src||m.href;try{if(!b){var S=(typeof m.tagName=="string"?m.tagName.toLowerCase():"")==="object",v=m.getAttribute("classid")&&m.getAttribute("classid").toLowerCase()==="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"||m.getAttribute("type")==="application/x-shockwave-flash";S&&v&&(b=m.getAttribute("data")||m.getAttribute("codebase")),b||(b=m.outerHTML||m.innerHTML)}}catch(R){b=""}return b},getXPath:function(m,b){var S=m.id?"#"+m.id:"",v=typeof m.className=="string"?"."+m.className.split(" ").join("."):"",R=(typeof m.tagName=="string"?m.tagName.toLowerCase():"")+S+v;return m.parentNode&&m.parentNode.tagName&&b-1!=0?this.getXPath(m.parentNode,b-1)+" > "+R:R},sendPerformance:function(m){var b=this;b.onReady(function(){var S=r();S&&S.load&&S.load>0&&(S.page=b.getPage(!0),m&&(S=t.ext(S,m)),S.autoSend=!0,b.performance(S))})},sendResources:function(m){var b=this;b.onReady(function(){var S=i();S&&S.load&&S.load>0&&(S.load&&S.load<=2e3||S.load&&S.load<=8e3&&Math.random()>.05||(S.page=b.getPage(!0),S.dl=location.href,m&&(S=t.ext(S,m)),b._lg("res",S,b.getConfig("sample"))))})},sendPV:function(){var m=this;m.onReady(function(){var b,S,v=(b=f(m),S=a.devicePixelRatio||1,{uid:b,dt:e.title,dl:location.href,dr:e.referrer,dpr:S.toFixed(2),de:(e.characterSet||e.defaultCharset||"").toLowerCase(),ul:c.lang,begin:Date.now()});v&&v.uid&&m._lg("pv",v,m.getConfig("pvSample"))})},commonInfo:function(){return h.uid=f(this),h.sid=function(m){if(m.session)return m.session;var b;try{if(typeof window=="object"&&typeof sessionStorage=="object"&&typeof sessionStorage.getItem=="function")return typeof(b=sessionStorage.getItem("_bl_sid"))=="string"?(m.session=b,b):(b=t.uu(),m.session=b,typeof sessionStorage.setItem=="function"&&sessionStorage.setItem("_bl_sid",b),b)}catch(S){t.warn("[ARMS] getSid error :",S)}return m.session=b=t.uu(),b}(this),h},handleUnload:function(m){var b=Date.now();if(b-this._lastUnload<200)return this;this._lastUnload=b,this.sendHealth(m),this.speedCache&&(this._lg("speed",this.speedCache),this.speedCache=null,clearTimeout(this.speedTimmer)),this._conf&&this._conf.enableResource&&this.resourceComboReport(),this.clear(!0)},bindHashChange:function(m){var b=this;if(!m^b.hashChangeHandler)return b;m?(b.hackHistoryState(),b.hashChangeHandler=function(S){var v=b._conf.parseHash(location.hash);v&&b.setPage(v,S!==!1)},b.stateChangeHandler=function(S){var v=b._conf.parseHash(S.detail);v&&b.setPage(v)},t.on(a,"hashchange",b.hashChangeHandler),t.on(a,"historystatechange",b.stateChangeHandler),b.hashChangeHandler(!1)):(t.off(a,"hashchange",b.hashChangeHandler),t.off(a,"historystatechange",b.stateChangeHandler),b.hashChangeHandler=null,b.stateChangeHandler=null)},initHandler:function(){var m=this;if(m.hasInitHandler)return m;var b=m._conf;return t.on(a,"beforeunload",function(){m.handleUnload(0)}),m.bindHashChange(b.enableSPA),m.activeErrHandler(!1),m.hasInitHandler=!0,m}}),t.on(a,"error",function(m){n&&n.errorHandler(m)},!1,!0).on(a,"unhandledrejection",function(m){n&&n.errorHandler(m)}),s}),Pa}function Bo(){if(Ma)return Ar;Ma=1;var s=Ye();return Ar=function(a,e,t){function i(d,h,p){var u=0,f=d.tagName;if(f!=="SCRIPT"&&f!=="STYLE"&&f!=="META"&&f!=="HEAD"){var m=d.children?d.children.length:0;if(m>0)for(var b=d.children,S=m-1;S>=0;S--)u+=i(b[S],h+1,u>0);if(u<=0&&!p&&!(d.getBoundingClientRect&&d.getBoundingClientRect().top<n))return 0;u+=1+.5*h}return u}function r(d){for(var h=1;h<d.length;h++)if(d[h].score<d[h-1].score)return d.splice(h,1),r(d);return d}var n=e.innerHeight||0,c=[],o=null,l=0;s.ext(a.prototype,{initFmpObserver:function(d){var h=this;if(!h._conf||!h._conf.useFmp)return null;if(!e.MutationObserver)return s.warn("[retcode] first meaningful paint can not be retrieved"),h.sendPerformance(),null;s.on(e,"beforeunload",function(){h.endObserving(0,!0)});var p=e.MutationObserver;return(o=new p(function(){(function(u){var f=Date.now()-u,m=t.querySelector("body");if(m){var b=0;b+=i(m,1,!1),c.push({score:b,t:f})}else c.push({score:0,t:f})})(h._startTime)})).observe(document,{childList:!0,subtree:!0}),l=1,h.onReady(function(){h.endObserving(d)}),o},endObserving:function(d,h){var p,u,f,m=this;if(o&&l)if(m.fmpTimmer&&(clearTimeout(m.fmpTimmer),m.fmpTimmer=null),h||(p=m._startTime,u=d,(f=Date.now()-p)>u||f-(c&&c.length&&c[c.length-1].t||0)>1e3)){o.disconnect(),l=0,c=r(c);for(var b=null,S=1;S<c.length;S++)if(c[S].t>=c[S-1].t){var v=c[S].score-c[S-1].score;(!b||b.rate<=v)&&(b={t:c[S].t,rate:v})}b&&b.t>0&&b.t<36e5?m.sendPerformance({fmp:b.t}):m.sendPerformance()}else m.fmpTimmer=s.delay(function(){m.endObserving(d)},500)}})},Ar}function Ho(){if(Ua)return pr.exports;Ua=1;var s=Ye(),a=function(){if(_a)return mr.exports;_a=1;var o=Ye(),l=Oo(),d=["api","success","time","code","msg","trace","traceId","begin","pv_id","sid","seq","domain","flag","apiSnapshot","tag","c1","c2","c3"],h=function(u){var f=(u.key||"default").split("::");return f.length>1?o.ext(u,{group:f[0],key:f[1]}):o.ext(u,{group:"default_group",key:f[0]})},p=function(u){var f;l.call(this,u);try{f=typeof performance=="object"?performance.timing.fetchStart:Date.now()}catch(m){f=Date.now()}return this._startTime=f,this};return p.prototype=o.createObject(l.prototype),o.ext(l.dftCon,{startTime:null}),o.ext(p.prototype,{constructor:p,_super:l,sum:function(u,f,m){try{var b=o.dealParam(u,f,1);return this._lg("sum",h(b),m)}catch(S){o.warn("[retcode] can not get parseStatData: "+S)}},avg:function(u,f,m){try{var b=o.dealParam(u,f,0);return this._lg("avg",h(b),m)}catch(S){o.warn("[retcode] can not get parseStatData: "+S)}},percent:function(u,f,m,b){try{return this._lg("percent",h({key:u,subkey:f,val:m||0,begin:Date.now()}),b)}catch(S){o.warn("[retcode] can not get parseStatData: "+S)}},msg:function(u,f){if(u&&!(u.length>180))return this.custom({msg:u},f)},error:function(u,f){if(!u)return o.warn("[retcode] invalid param e: "+u),this;arguments.length===1?(typeof u=="string"&&(u={message:u},f={}),typeof u=="object"&&(f=u=u.error||u)):(typeof u=="string"&&(u={message:u}),typeof f!="object"&&(f={}));var m=u.name||"CustomError",b=u.message||"",S=u.stack||"";f=f||{};var v=typeof location=="object"&&typeof location.href=="string"&&location.href.substring(0,500)||"";if(o.checkSDKError(b,f.filename)){var R=/^Script error\.?$/,w=u.msg||u.message;if(o.ignoreByRule(w,R)||o.ignoreByRule(o.decode(w),R))return this;var y={msg:o.selfErrKey,err:{msg_raw:o.encode(u.msg||u.message)}};return this._self("error",y,1)}for(var A={begin:Date.now(),cate:m,msg:b&&b.substring(0,1e3),stack:S&&S.substring(0,1e3),file:o.removeUrlSearch(f.filename||""),line:f.lineno||"",col:f.colno||"",err:{msg_raw:o.encode(b),stack_raw:o.encode(S)},dl:v},_=["tag","c1","c2","c3"],E=0;E<_.length;E++){var T=_[E];f[T]&&(A[T]=f[T])}var k=(this.getConfig("ignore")||{}).ignoreErrors;return o.ignoreByRule(A.msg,k)||o.ignoreByRule(o.decode(A.msg),k)?this:(this.beforeSend&&this.beforeSend("error",A),this._lg("error",A,1))},behavior:function(u){if(u){var f=typeof u=="object"&&u.behavior?u:{behavior:u};return this.beforeSend&&this.beforeSend("behavior",f),this._lg("behavior",f,1)}},api:function(u,f,m,b,S,v,R,w,y,A,_,E,T,k,P,H){if(!u)return o.warn("[retcode] api is null"),this;if(u=typeof u=="string"?{api:u,success:f,time:m,code:b,msg:S,begin:v,traceId:R,pv_id:w,apiSnapshot:y,domain:A,flag:E,tag:T,c1:k,c2:P,c3:H}:o.sub(u,d),!o.checkAPI(u.api,!0))return this;u.code=u.code||"";var q=u.msg||"";if(q=typeof q=="string"?q.substring(0,1e3):q,u.msg=q,u.success=u.success?1:0,u.time=+u.time,u.begin=u.begin,u.traceId=u.traceId||"",u.pv_id=u.pv_id||"",u.domain=u.domain||"",u.flag=u.flag,u.dl=typeof location=="object"&&typeof location.href=="string"&&location.href.substring(0,500)||"",u.apiSnapshot&&(typeof u.apiSnapshot=="object"&&(u.apiSnapshot=JSON.stringify(u.apiSnapshot)),typeof u.apiSnapshot!="string"&&delete u.apiSnapshot,u.apiSnapshot.length>2e3&&(u.apiSnapshot=u.apiSnapshot.substring(0,2e3))),_&&(u.traceOrigin=_),!u.api||isNaN(u.time))return o.warn("[retcode] invalid time or api"),this;var Y=(this.getConfig("ignore")||{}).ignoreApis;return o.ignoreByRule(u.api,Y)||o.ignoreByRule(o.decode(u.api),Y)||u.time<0?this:(this.beforeSend&&this.beforeSend("api",u),this._lg("api",u,u.success&&this.getConfig("sample"),u.flag))},speed:function(u,f,m){var b=this,S=this.getConfig("startTime")||this._startTime;return/^s(\d|1[0])$/.test(u)?(f=typeof f!="number"?Date.now()-S:f>=S?f-S:f,b.speedCache=b.speedCache||{},b.speedCache[u]=f,b.speedCache.begin=S,clearTimeout(b.speedTimmer),b.speedTimmer=setTimeout(function(){m||(b.speedCache.page=b.getPage(!0)),b._lg("speed",b.speedCache),b.speedCache=null},5e3),b):(o.warn("[retcode] invalid point: "+u),b)},performance:function(u){if(u&&typeof u=="object"&&!this.hasSendPerf){var f={},m={},b=this.getConfig("autoSendPerf");if(u.autoSend&&b)return m=o.ext(this.perfData||{},u),this.hasSendPerf=!0,this._lg("perf",m,this.getConfig("sample"));if(u.autoSend&&!b)return delete u.autoSend,this.perfData?(m=o.ext(this.perfData||{},u),this.hasSendPerf=!0,this._lg("perf",m,this.getConfig("sample"))):void(this.perfData=u);for(var S in u)(/^t([1-9]|1[0])$/.test(S)||S==="ctti"||S==="cfpt")&&(f[S]=u[S]);if(u.autoSend===!0||!b&&(b||this.perfData))return u.autoSend!==!0&&b===!1&&this.perfData?(f=o.ext(this.perfData||{},f),this.hasSendPerf=!0,this._lg("perf",f,this.getConfig("sample"))):void 0;this.perfData=o.ext(this.perfData||{},f)}},resource:function(u,f){if(!u||!o.isPlainObject(u))return o.warn("[arms] invalid param data: "+u),this;var m=Object.keys(u),b=["begin","dom","load","res","dl"],S=!1;for(var v in b)if(m.indexOf(b[v])<0){S=!0;break}if(S)return o.warn("[arms] lack param data: "+u),this;var R={begin:u.begin||Date.now(),dom:u.dom||"",load:u.load||"",res:o.isArray(u.res)?JSON.stringify(u.res):JSON.stringify([]),dl:u.dl||""};return this._lg("res",R,f)},event:function(u,f){if(typeof u=="object"&&u&&u.key){var m={},b=["key","success","time","c1","c2","c3"];for(var S in u)b.indexOf(S)>-1&&(m[S]=u[S]);m.success=u.success===!1?0:1,this._lg("event",m,f)}}}),p._super=l,p._root=l,l.Reporter=p,mr.exports=p,mr.exports}(),e=function(){if(wa)return Sr.exports;wa=1;var o=Ye(),l=typeof window=="object"?window:{},d=l.__oFetch_||l.fetch;return d=typeof d=="function"?d:void 0,Sr.exports=function(h,p){var u=-1;typeof h=="object"&&(u=h.z,h=o.serialize(h));var f=p+h;if(d)return d(f,{method:"HEAD",mode:"no-cors"}).catch(o.noop);if(l.document&&l.document.createElement){var m="__request_hold_"+u,b=l[m]=new Image;b.onload=b.onerror=function(){l[m]=void 0},b.src=f,b=null}},Sr.exports}(),t=function(){if(Ea)return vr.exports;Ea=1;var o=Ye(),l=typeof window=="object"?window:{},d=l.__oXMLHttpRequest_||l.XMLHttpRequest;return d=typeof d=="function"?d:void 0,vr.exports=function(h,p){try{var u=new d;u.open("POST",p,!0),u.setRequestHeader("Content-Type","text/plain"),u.send(JSON.stringify(h))}catch(f){o.warn(`[retcode] Failed to log, exception is :
126
- `+f)}},vr.exports}(),i=s.win,r=i.document,n=/^(error|api|speed|sum|avg|percent|custom|msg|setPage|setConfig|behavior|performance)$/,c=function(o){var l=this;return a.call(l,o),l._initialPage=o.page&&s.safetyCall(o.page,[],o.page+"")||null,l._isRobot=s.isRobot(),l._health={errcount:0,apisucc:0,apifail:0},l.beforeSend=function(d,h){d==="error"?l._health.errcount++:d==="api"&&l._health[h.success?"apisucc":"apifail"]++},o.enableInstanceAutoSend!==!1&&(l.initHandler(),l.initHook(),l.initFmpObserver(1e4),l._conf&&l._conf.behavior&&typeof l.initBehavior=="function"&&l.initBehavior(),l._conf&&l._conf.enableResource&&typeof l.initResource=="function"&&l.initResource()),Object.defineProperty&&i.addEventListener&&Object.defineProperty(l,"pipe",{set:l.sendPipe}),l};return c.prototype=s.createObject(a.prototype),s.ext(a._root.dftCon,{uid:null,setUsername:null,ignoreUrlPath:null,ignoreApiPath:null,urlHelper:[{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},/\/$/],resourceHelper:[],apiHelper:{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},ignoreUrlCase:!0,imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",cdnHostList:[],resourceTypes:["css","script","img","font"],resourceSlow:2e3,disableHook:!1,autoSendPv:!0,autoSendPerf:!0,enableSPA:!1,enableLinkTrace:!1,linkType:"arms",enableApiCors:!1,sendResource:!0,behavior:!0,enableConsole:!1,parseHash:function(o){return(o?s.cutUrlSearch(o.replace(/^#\/?/,"")):"")||"[index]"},parseResponse:function(o){if(!o||typeof o!="object")return{};var l=o.code,d=o.msg||o.message||o.subMsg||o.errorMsg||o.ret||o.errorResponse||"";return typeof d=="object"&&(l=l||d.code,d=d.msg||d.message||d.info||d.ret||JSON.stringify(d)),{msg:d,code:l,success:!0}}}),s.ext(c.prototype,{constructor:c,_super:a,onReady:function(o){var l=this;if(l.hasReady)return o();r.readyState==="complete"?(l.hasReady=!0,o()):s.on(i,"load",function(){l.hasReady=!0,o()},!0)},getPage:function(o){var l=this._conf,d=l.page,h=location,p=h.host+h.pathname;return d&&!o?s.safetyCall(d,[],d+""):this._initialPage||s.filterByRule(l.ignoreUrlCase?p.toLowerCase():p,h.href,l.ignoreUrlPath?l.ignoreUrlPath:l.urlHelper)},setPage:function(o,l){var d=this,h=d.prevPage;if(l!==!1){if(!o||o===h)return d;d.prevPage=o,clearTimeout(d.sendPVTimmer),d.handleUnload(1),d.resetPageview(),d.sendPVTimmer=setTimeout(function(){d.sendPV()},10)}else d.prevPage=o;return d._conf.page=o,d},setConfig:function(o,l){if(o&&typeof o=="object"){s.verifyConfig(o),o=this.setImgUrl(o);var d=this._conf;if(this._conf=s.ext({},d,o),!l){var h="disableHook";h in o&&d[h]!==o[h]&&(o[h]?this.removeHook():this.addHook()),(h="enableSPA")in o&&d[h]!==o[h]&&this.bindHashChange(o[h])}}},sendRequest:function(o){e(o,this.getConfig("imgUrl"))},postData:function(o,l){var d={};d[l]=o[l],delete o[l];var h="";typeof o=="object"&&(h=s.serialize(o)),t(d,this.getConfig("imgUrl")+h+"&post_res=")},sendPipe:function(o){var l=this;if(!o||!o.length)return l;try{if(s.T(o[0])==="Array")return s.each(o,function(h){return l.sendPipe(h)});if(s.T(o)!=="Array")return l;var d=o.shift();if(!n.test(d))return l;l[d].apply(l,o)}catch(h){return s.warn("[retcode] error in sendPipe",h),l}},sendHealth:function(){var o=s.ext({},this._health);o.healthy=o.errcount>0?0:1,o.begin=Date.now();var l=o.begin-this.sBegin;o.stay=l,this._lg("health",o,1),this._health={errcount:0,apisucc:0,apifail:0}},createInstance:function(o){o=s.ext({pid:this._conf.pid},o);var l=this.__proto__.constructor(o);return o.page&&l.sendPV(),l}}),Vo()(c,i),Uo()(c,i,r),Bo()(c,i,r),(Na||(Na=1,La=function(o,l){var d=Ye(),h=null,p=d.getCurDomain(),u=function(v,R,w,y,A,_,E,T,k,P,H,q,Y){var J=d.J(A)||null,z=d.safetyCall(R,[J,y],null);if(!z)return!1;var Z=z.code||_,ee=!("success"in z)||z.success;v.api(w,ee,E,Z,z.msg,T,k,P,ee?{}:H,p,q,Y)},f="fetch",m="__oFetch_",b="__oXMLHttpRequest_",S="XMLHttpRequest";return d.ext(o.prototype,{removeHook:function(v,R){return h&&(R||this===h)?(l[m]&&(l[f]=l[m],delete l[m]),l[b]&&(l[S]=l[b],delete l[b]),h=null,this):this},addHook:function(v){return!v&&h||(h||(function(){if(typeof l[f]=="function"){var R=l[f];l[m]=R,l[f]=function(w,y){var A=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),_=h;if(!_||!_.api||y&&(y.method==="HEAD"||y.mode==="no-cors"))return R.apply(l,A);y||(y={});var E=Date.now(),T=_._conf,k=d.duration(),P=(w&&typeof w!="string"?w.url:w)||"",H=P;P=d.cutUrlSearch(P);var q=(T.ignore||{}).ignoreApis,Y=T.parseTraceId;if(!d.checkAPI(P,!0)||d.ignoreByRule(P,q))return R.apply(l,A);P=d.filterByRule(P,H,T.ignoreApiPath?T.ignoreApiPath:T.apiHelper);var J=T.enableLinkTrace,z="",Z="",ee=_.getConfig("pid"),ge=null,D=_.getConfig("sample"),x=_.getConfig("linkType"),L=1;if(D&&!_.sampling(D)&&(L=0),J){var O="";try{O=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(he){O=""}var de=d.checkSameOrigin(H,O);if(_.getConfig("enableApiCors")||de)if(w&&typeof w!="string")try{if(A[0].headers&&typeof A[0].headers.get=="function"&&typeof A[0].headers.append=="function")switch(x){case"arms":var Pe=A[0].headers.get("EagleEye-TraceID"),K=A[0].headers.get("EagleEye-SessionID"),me=A[0].headers.get("EagleEye-pAppName");Pe?z=Pe:(z=_.getTraceId()["EagleEye-TraceID"],A[0].headers.append("EagleEye-TraceID",z)),K?Z=K:(Z=_.getPageviewId()["EagleEye-SessionID"],A[0].headers.append("EagleEye-SessionID",Z)),me||A[0].headers.append("EagleEye-pAppName",ee);break;case"b3":var Me=A[0].headers.get("X-B3-TraceId");if(Me)z=Me;else{var _e=_.getB3TraceId(L);A[0].headers.append("X-B3-TraceId",_e["X-B3-TraceId"]),A[0].headers.append("X-B3-ParentSpanId",_e["X-B3-ParentSpanId"]),A[0].headers.append("X-B3-SpanId",_e["X-B3-SpanId"]),A[0].headers.append("X-B3-Sampled",_e["X-B3-Sampled"]),A[0].headers.append("X-Request-ID",d.guid()),z=_e["X-B3-TraceId"]}Z=_.pageview;break;default:var ke=A[0].headers.get("uber-trace-id");ke?z=ke.split(":")[0]:(ke=_.getUberTraceId(L),A[0].headers.append("uber-trace-id",ke["uber-trace-id"]),z=ke.traceId),Z=_.pageview}}catch(he){d.warn(`[retcode] fetch failed to set header, exception is :
127
- `+he)}else switch(y.headers=y.headers?y.headers:{},x){case"arms":y.headers["EagleEye-TraceID"]?z=y.headers["EagleEye-TraceID"]:(z=_.getTraceId()["EagleEye-TraceID"],y.headers["EagleEye-TraceID"]=z),y.headers["EagleEye-SessionID"]?Z=y.headers["EagleEye-SessionID"]:(Z=_.getPageviewId()["EagleEye-SessionID"],y.headers["EagleEye-SessionID"]=Z),y.headers["EagleEye-pAppName"]||(y.headers["EagleEye-pAppName"]=ee);break;case"b3":if(y.headers["X-B3-TraceId"])z=y.headers["X-B3-TraceId"];else{var fe=_.getB3TraceId(L);y.headers["X-B3-TraceId"]=fe["X-B3-TraceId"],y.headers["X-B3-ParentSpanId"]=fe["X-B3-ParentSpanId"],y.headers["X-B3-SpanId"]=fe["X-B3-SpanId"],y.headers["X-B3-Sampled"]=fe["X-B3-Sampled"],y.headers["X-Request-ID"]=d.guid(),z=fe["X-B3-TraceId"]}Z=_.getPageviewId()["EagleEye-SessionID"];break;default:if(y.headers["uber-trace-id"])z=y.headers["uber-trace-id"].split(":")[0];else{var we=_.getUberTraceId(L);y.headers["uber-trace-id"]=we["uber-trace-id"],z=we.traceId}Z=_.getPageviewId()["EagleEye-SessionID"]}}return R.apply(l,A).then(function(he){if(!_||!_.api)return he;try{if(!he||typeof he.clone!="function")return he;var De=he.clone(),ye=De.headers;if(ye&&typeof ye.get=="function"){var qe=ye.get("content-type");if(qe&&!/(text)|(json)/.test(qe))return he;if(!z){var st=d.parseFetchHeaders(ye);typeof st=="object"&&st["eagleeye-traceid"]&&(z=st["eagleeye-traceid"],ge="response")}}var ne=k();return De.text().then(function(re){if(!z&&d.isFunction(Y)){var ie=Y(De,re);ie&&d.isString(ie)&&(z=ie)}var Se=d.getFetchSnapshot(A,re,ye);De.ok?u(_,T.parseResponse,P,H,re,De.status||200,ne,E,z,Z,Se,ge,L):(_.api(P,!1,ne,De.status||404,De.statusText,E,z,Z,Se,p,ge,L),T.enableResource&&h.fixResourceStatus&&h.fixResourceStatus({src:De.url,res_type:"api"}))}),he}catch(re){return d.warn("[ARMS] fetch response error :",re),he}}).catch(function(he){if(!_||!_.api)throw he;var De=k();throw _.api(P,!1,De,he.name||"Error",he.message,E,z,Z,{},p),T.enableResource&&h.fixResourceStatus&&h.fixResourceStatus({src:H,res_type:"api"}),he})},l[f].toString=d.createFakeToString(f)}}(),function(){if(typeof l[S]=="function"){var R,w=l[S];l[b]=w;var y=function(A){var _=new w(A),E=h;if(!E||!E.api||!_.addEventListener)return _;var T,k,P,H,q=_.send,Y=_.open,J=_.setRequestHeader,z=E._conf,Z=(z.ignore||{}).ignoreApis,ee=z.parseTraceId,ge=E.getConfig("enableLinkTrace"),D="",x="",L="",O=null,de=E.getConfig("sample"),Pe=E.getConfig("linkType"),K=1;return de&&!E.sampling(de)&&(K=0),_.open=function(me,Me){R=me;var _e=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);Y.apply(_,_e),H=Me||"",P=d.cutUrlSearch(H);var ke=!d.checkAPI(P,!0)||d.ignoreByRule(P,Z);if(P=P?d.filterByRule(P,H,z.ignoreApiPath?z.ignoreApiPath:z.apiHelper):"",!ke&&ge){var fe="";try{fe=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(ye){fe=""}var we=d.checkSameOrigin(H,fe);if((E.getConfig("enableApiCors")||we)&&J&&typeof J=="function")switch(Pe){case"arms":D=E.getTraceId()["EagleEye-TraceID"],J.apply(_,["EagleEye-TraceID",D]),x=E.getPageviewId()["EagleEye-SessionID"],J.apply(_,["EagleEye-SessionID",x]),L=E.getConfig("pid"),J.apply(_,["EagleEye-pAppName",L]);break;case"b3":var he=E.getB3TraceId(K);J.apply(_,["X-B3-TraceId",he["X-B3-TraceId"]]),J.apply(_,["X-B3-ParentSpanId",he["X-B3-ParentSpanId"]]),J.apply(_,["X-B3-SpanId",he["X-B3-SpanId"]]),J.apply(_,["X-B3-Sampled",he["X-B3-Sampled"]]),J.apply(_,["X-Request-ID",d.guid()]),D=he["X-B3-TraceId"],x=E.getPageviewId()["EagleEye-SessionID"];break;default:var De=E.getUberTraceId(K);J.apply(_,["uber-trace-id",De["uber-trace-id"]]),D=De.traceId,x=E.getPageviewId()["EagleEye-SessionID"]}}},_.send=function(){T=Date.now(),k=d.duration();var me=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);q.apply(_,me)},d.on(_,"readystatechange",function(){if(P&&_.readyState===4){var me=k(),Me=d.getXhrSnapshot(H,R,_);if(!D){var _e=d.parseXhrHeaders(typeof _.getAllResponseHeaders=="function"&&_.getAllResponseHeaders()||"");typeof _e=="object"&&_e["eagleeye-traceid"]&&(D=_e["eagleeye-traceid"],O="response")}if(!D&&d.isFunction(ee)){var ke=ee(_);ke&&d.isString(ke)&&(D=ke)}if(_.status>=200&&_.status<=299){var fe=_.status||200;if(typeof _.getResponseHeader=="function"){var we=_.getResponseHeader("Content-Type");if(we&&!/(text)|(json)/.test(we))return}_.responseType&&_.responseType!=="text"?E.api(P,!0,me,fe,"",T,D,x,{},p,O,K):u(E,z.parseResponse,P,H,_.responseText,fe,me,T,D,x,Me,O,K)}else E.api(P,!1,me,_.status||"FAILED",_.statusText,T,D,x,Me,p,O,K),z.enableResource&&h.fixResourceStatus&&h.fixResourceStatus({src:_.responseURL||H,res_type:"api"})}}),_};y.prototype=w.prototype,d.each(Object.keys(w),function(A){y[A]=w[A]}),l[S]=y,l[S].toString=d.createFakeToString(S)}}()),h=this),this},initHook:function(){return this.hasInitHook||(this.getConfig("disableHook")||this.addHook(),this.hasInitHook=!0),this}}),o}),La)(c,i),(Oa||(Oa=1,xa=function(o,l){var d=Ye(),h=l.history||{},p=l.document,u=function(m,b){var S;l.CustomEvent?S=new CustomEvent(m,{detail:b}):((S=p.createEvent("HTMLEvents")).initEvent(m,!1,!0),S.detail=b),l.dispatchEvent(S)},f=function(m){var b=h[m];typeof b=="function"&&(h[m]=function(S,v,R){var w=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),y=location.href,A=b.apply(h,w);if(!R||typeof R!="string"||R===y)return A;try{var _=y.split("#"),E=R.split("#"),T=d.cutUrlSearch(_[0]),k=d.cutUrlSearch(E[0]),P=_[1]&&_[1].replace(/^\/?(.*)/,"$1"),H=E[1]&&E[1].replace(/^\/?(.*)/,"$1");P!==H?u("historystatechange",H):T!==k&&u("historystatechange",k)}catch(q){d.warn("[retcode] error in "+m+": "+q)}return A},h[m].toString=d.createFakeToString(m))};d.ext(o.prototype,{hackHistoryState:function(){return this.hasHackedHistoryState||(f("pushState"),f("replaceState"),this.hasHackedHistoryState=!0),this}})}),xa)(c,i),function(){if(Va)return _r;Va=1;var o=Ye(),l=wr().TIMING_KEYS;return _r=function(d,h){function p(m,b,S){if(m instanceof h.PerformanceResourceTiming&&m.initiatorType){var v=o.getResType(m.initiatorType,m.name),R=b.resourceTypes||[],w=(b.ignore||{}).ignoreResources;if(v&&R.includes(v)&&!o.ignoreByRule(m.name,w)&&!o.ignoreByRule(o.decode(m.name),w)){var y=m[l[0]],A=m[l[1]],_=m[l[2]],E=m[l[3]],T=m[l[4]],k=m[l[5]],P=m[l[6]],H=m[l[7]],q=m[l[8]],Y=m[l[18]],J=m[l[19]];if(!S.has(m)&&(!o.areInOrder(y,A,_,E,T,k,P,H,q)||y>H))return;if(Y<y&&(Y=y),J<y&&(J=A),o.areInOrder(y,Y,J,A))return{domain:o.getURL(m.name).domain,res_type:v,src_type:o.getSrcType(m.name,b.cdnHostList),success:1,size:Math.round(m.decodedBodySize),duration:Math.round(m.duration),timeStamp:m.responseEnd,timing:m}}}}var u="_resource-"+Date.now(),f="_resource_error-"+Date.now();o.ext(d.prototype,{initResource:function(){var m=this,b=h.performance,S=h.PerformanceObserver;if(m[f]||(m[f]=new WeakMap),!b||!S||typeof b!="object"||typeof b.getEntriesByType!="function")return null;var v=b.getEntriesByType("resource")||[];return setTimeout(function(){m.setResource(v)},10),new S(function(R){setTimeout(function(){m.setResource(R.getEntries())},10)}).observe({entryTypes:["resource"]}),this.onReady(function(){setTimeout(m.resourceComboReport.bind(m),5e3)}),m},setResource:function(m){var b=this._conf,S=this[f];if(o.isArray(m)&&m.length){this[u]||(this[u]={});for(var v=this[u],R=0,w=m.length;R<w;R+=1){var y=m[R];if(o.checkAPI(y.name,!1)){var A=p(y,b,S);if(A){var _=A.res_type+"-"+A.domain;_ in v||(v[_]=[]),v[_].push(A)}}}return this}},fixResourceStatus:function(m){var b=h.performance;if(!b||typeof b.getEntriesByName!="function")return null;var S=this[f];if(!m.src||!o.checkAPI(m.src,!1))return this;var v=m.timeStamp||b.now(),R=b.getEntriesByName(m.src,"resource");return o.each(R,function(w){S.has(w)||v-w.responseEnd<100&&S.set(w,{success:0})}),this},resourceComboReport:function(){var m=this[u]||{},b=this._conf.resourceSlow||2e3,S=this[f];this[u]={};var v=Object.keys(m);if(v.length!==0){var R=[];o.each(v,function(_){var E=m[_],T={domain:"",res_type:"",src_type:"",size:0,duration:0,count:0,err_count:0,err_duration:0,slow_count:0,slow_duration:0,timings:[]};o.each(E,function(k){var P=k.timing||{},H=S.get(k.timing),q=H?H.success:1,Y=k.duration>b?1:0;T.domain=k.domain,T.res_type=k.res_type,T.src_type=k.src_type,T.count+=1,T.duration+=k.duration,T.size+=k.size,q||(T.err_count+=1,T.err_duration+=k.duration),Y&&(T.slow_count+=1,T.slow_duration+=k.duration);try{var J=JSON.parse(JSON.stringify(P));J.success=q,J.resourceSlow=b,J.isSlow=Y,T.timings.push(J)}catch(z){}}),T.count&&(T.size=Math.round(T.size/T.count),T.duration=Math.round(T.duration/T.count)),T.slow_count&&(T.slow_duration=Math.round(T.slow_duration/T.slow_count)),T.err_count&&(T.err_duration=Math.round(T.err_duration/T.err_count)),T.timings.length>20&&(T.timings.sort(function(k,P){return P.duration-k.duration}),T.timings.length=20),T.timings=encodeURIComponent(JSON.stringify(T.timings)),R.push(T)});var w={_combo:1,resource:JSON.stringify(R)},y=h.navigator.connection;w.ct=y?y.effectiveType||y.type:"";var A=y&&(y.downlink||y.downlinkMax||y.bandwidth)||null;(A=A>999?999:A)&&(w.bandwidth=A),this._lg("resource",w,this.getConfig("sample"))}}})},_r}()(c,i),c._super=a,c._root=a._root,a.Browser=c,pr.exports=c,pr.exports}var Fo={getArmsLogger:function(){return function(){if(Ba)return ur.exports;function s(r,n){var c=a[t]=new e(r);c.sendPipe(n);var o=c._conf;return o.autoSendPv!==!1&&c.sendPV(),o&&o.useFmp||c.sendPerformance(),o&&o.sendResource&&c.sendResources(),a[i]=!0,c}Ba=1;var a=window,e=a.BrowserLogger=Ho(),t=Ye().key,i="__hasInitBlSdk";return e.singleton=function(r,n){return a[i]?a[t]:s(r,n)},e.createExtraInstance=function(r){r&&typeof r=="object"&&r.enableInstanceAutoSend!==!0&&(r.enableInstanceAutoSend=!1);var n=new e(r),c=n._conf;return c.enableInstanceAutoSend&&(c.autoSendPv!==!1&&n.sendPV(),c&&c.useFmp||n.sendPerformance(),c&&c.sendResource&&n.sendResources()),n},typeof window=="object"&&window.navigator&&a[t]&&(e.bl=function(){if(a[i])return a[t];var r={},n=[];return t in a&&(r=a[t].config||{},n=a[t].pipe||[]),s(r,n)}()),ur.exports=e,ur.exports}()}};const Fa="https://arms-retcode.aliyuncs.com/r.png?",ja="https://arms-retcode-sg.aliyuncs.com/r.png?",za="https://retcode-us-west-1.arms.aliyuncs.com/r.png?",Wa="e1iftji1w7@7ec1cef2cc88733",$a="e1iftji1w7@10a06d1ec260adc",Ka="e1iftji1w7@10a06d1ec260adc",Er={cn:{reportUrl:Fa,pid:Wa},"cn-hangzhou":{reportUrl:Fa,pid:Wa},sg:{reportUrl:ja,pid:$a},"ap-southeast-1":{reportUrl:ja,pid:$a},usw:{reportUrl:za,pid:Ka},"us-west-1":{reportUrl:za,pid:Ka}},jo=s=>!!Object.isExtensible(s)&&(a=>Object.prototype.toString.call(a).slice(8,-1))(s)==="Object";function Ja(s,a){if(typeof s!="string")return!1;const e=s.indexOf(a);if(e<0)return!1;const t=s.indexOf(`
128
- `);return t<0||e<t}function Pt(s,a,e){return typeof s=="function"?function(t,i,r){const n={MediaboxWrapperFunctionApply(c,o,l){let d;try{d=Reflect.apply(c,o,l)}catch(h){throw r(h),h}return Pt(d,i,r)},MediaboxWrapperFunctionGet(c,o){const l=Object.getOwnPropertyDescriptor(c,o);return!l||l.writable||l.configurable?Pt(c[o],i,r):c[o]},MediaboxWrapperClassConstructor(c,o){let l;try{l=new c(...o)}catch(d){throw r(d),d}return Pt(l,i,r)}};return new Proxy(t,{apply:n.MediaboxWrapperFunctionApply,get:n.MediaboxWrapperFunctionGet,construct:n.MediaboxWrapperClassConstructor})}(s,a+1,e):s instanceof Promise?s.then(t=>Pt(t,a+1,e)).catch(t=>(e(t),Promise.reject(t))):Array.isArray(s)?(s.forEach((t,i)=>{s[i]=Pt(t,a+1,e)}),s):(t=>t!==null&&typeof t=="object")(s)&&jo(s)?function(t,i,r){var l;if(Reflect.get(t,"__v_skip")===!0)return t;const n=[],c=typeof Object.getOwnPropertyDescriptors=="function"?Object.getOwnPropertyDescriptors((l=Object.getPrototypeOf(t))!=null?l:{}):{};for(const d of Object.keys(c))c[d].get&&n.push(d);const o={MediaboxWrapperObjectGetter(d,h){if(typeof h=="string"&&n.indexOf(h)>-1){let p;try{p=d[h]}catch(u){throw r(u),u}return Pt(p,i,r)}return i>10?d[h]:Pt(d[h],i,r)},MediaboxWrapperObjectSetter:(d,h,p)=>(d[h]=Pt(p,i,r),!0)};return Object.defineProperty(t,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(t,{get:o.MediaboxWrapperObjectGetter,set:o.MediaboxWrapperObjectSetter})}(s,a+1,e):s}function Ga(s){return typeof s=="string"&&(s.indexOf("g.alicdn.com/apsara-media-")>-1||s.indexOf("g.alicdn.com/thor-server")>-1||s.indexOf("MediaboxWrapper")>-1)}class qa extends Error{constructor(a){super(a),this.name="MQTError"}}let zo=1;class Ir{constructor(a){var e,t;Jt(this,"armsLogger"),Jt(this,"isReady",!1),Jt(this,"isDestroyed",!1),Jt(this,"options"),Jt(this,"queue",[]),Jt(this,"marker"),Jt(this,"helper",{MediaboxWrapperQueue:i=>new qa(i),MediaboxWrapperInitiative:i=>new qa(i)}),this.options=yt(G({},a),{region:a.deferRegionSet?void 0:(e=a.region)!=null?e:"cn",env:(t=a.env)!=null?t:"prod"}),this.marker=`-${zo++}-`,this.initArmsLogger()}static get version(){return"0.23.0"}initArmsLogger(a){const{region:e,env:t,disabled:i}=this.options;if(i||this.armsLogger)return;if(a&&!e)throw new Error("region is required");if(!e)return;if(!Er[e])throw new Error(`region ${e} is not supported`);const r=Fo.getArmsLogger();this.armsLogger=r.createExtraInstance({enableInstanceAutoSend:!0,pid:Er[e].pid,tag:this.options.businessName,release:`${this.options.businessName}_${this.options.version}`,imgUrl:Er[e].reportUrl,behavior:!0,sample:1,disableHook:!0,environment:t,beforeReport:n=>{var c;if(this.isDestroyed||Ja(n.stack,this.marker)||n.t!=="pv"&&n.t!=="error")return!1;if(n.c1=(c=this.options.cid)!=null?c:window.location.host,n.c2=Ir.version,this.options.customData&&(n.c3=new URLSearchParams(this.options.customData).toString()),n.t==="error"){if(function(o){return typeof o=="string"&&(o.indexOf("g.alicdn.com/apsara-media-")>-1||o.indexOf("g.alicdn.com/thor-server")>-1)}(n.file)||Ga(n.stack)){let o=n;return this.options.beforeSend&&(o=this.options.beforeSend(n)),this.isReady?o:(o&&this.queue.push(o),!1)}return!1}return n}})}wrap(a){return this.options.disabled||typeof Proxy>"u"?a:Pt(a,0,e=>{var t;e instanceof Error&&typeof e.stack=="string"&&Ga(e.stack)&&((t=this.armsLogger)==null||t.error(e),e.stack=function(i,r){if(typeof i!="string")return r;if(Ja(i,r))return i;const n=i.indexOf(`
129
- `);return n<0?`${i}${r}`:`${i.slice(0,n)}${r}${i.slice(n)}`}(e.stack,this.marker))})}updateOptions(a){this.options=G(G({},this.options),a)}setReady(){this.initArmsLogger(!0),this.isReady=!0,this.queue.length&&this.queue.forEach(a=>{var e;(e=this.armsLogger)==null||e.error(this.helper.MediaboxWrapperQueue(a.msg),{filename:a.file,lineno:a.line,colno:a.col})})}report(a,e){var t;(t=this.armsLogger)==null||t.error(this.helper.MediaboxWrapperInitiative(a),e)}destroy(){this.isDestroyed=!0}}var Ce=(s=>(s.PullStreamStats="remoteStat",s.RtsSubscribeExceeds="rtsSubscribeExceeds",s.UserJoined="userJoined",s.UserLeft="userLeft",s.Bye="bye",s.MuteAudio="muteAudio",s.UnmuteAudio="unmuteAudio",s.MuteVideo="muteVideo",s.UnmuteVideo="unmuteVideo",s.MuteScreen="muteScreen",s.UnmuteScreen="unmuteScreen",s.Error="error",s))(Ce||{}),Qe=(s=>(s.Local="local-device-status-change",s.Remote="remote-device-status-change",s))(Qe||{}),M=(s=>(s.Audio="sophon_audio",s.VideoLarge="sophon_video_camera_large",s.VideoSmall="sophon_video_camera_small",s.Screen="sophon_video_screen_share",s.Data="sophon_data",s))(M||{}),Tr=(s=>(s.Audio="rts audio",s.VideoLarge="rts video",s))(Tr||{}),Ot=(s=>(s.Add="add",s.Delete="delete",s.Replace="replace",s.Stop="stop",s.UnPublish="unpublish",s))(Ot||{}),Si=(s=>(s[s.Camera=0]="Camera",s[s.Screen=1]="Screen",s[s.Image=2]="Image",s))(Si||{}),Bi=(s=>(s[s.Microphone=0]="Microphone",s[s.Screen=1]="Screen",s[s.Mixed=2]="Mixed",s))(Bi||{}),be=(s=>(s.InRoom="inRoom",s.Join="join",s.Publish="publish",s.User="user",s.Resume="resume",s.Retry="retry",s.Reconnect="reconnect",s))(be||{}),_t=(s=>(s[s.MANUAL=0]="MANUAL",s[s.JOIN_CHANNEL=1]="JOIN_CHANNEL",s[s.ROLE_CHANGE=2]="ROLE_CHANGE",s[s.RECONNECT=3]="RECONNECT",s))(_t||{});function ai(){}const Qt=class Qt{static getInstance(){var a;return Qt.instance||(Qt.instance=new AudioContext),(a=Qt.instance.resume())==null||a.then(ai,ai).catch(ai),Qt.instance}};g(Qt,"instance");let Gt=Qt;const Hi=()=>{var a;const s=Gt.getInstance();s.state!=="running"&&s.state!=="closed"&&((a=s.resume())==null||a.then(ai,ai).catch(ai)),window.removeEventListener("mousedown",Hi),window.removeEventListener("touchstart",Hi)};window.addEventListener("mousedown",Hi),window.addEventListener("touchstart",Hi);class Wo extends se{constructor(){super();g(this,"audioContext");g(this,"stream");g(this,"sourceNode");g(this,"analyser");this.audioContext=Gt.getInstance(),this.stream=new MediaStream}getLevel(){return this.analyser?this.analyser.getLevel():0}start(e,t=1e3){this.sourceNode&&this.stop(),this.stream.addTrack(e),this.sourceNode=this.audioContext.createMediaStreamSource(this.stream);const i=this.audioContext.createMediaStreamDestination();this.analyser=function(r,n,c,o,l){let d,h=o,p=0;const u=r.createAnalyser();u.fftSize=256;const f=new Uint8Array(u.frequencyBinCount);n.connect(u),u.connect(c);const m=()=>{d&&window.clearInterval(d)},b=()=>{r.state==="suspended"&&r.resume(),d=window.setInterval(()=>{u.getByteFrequencyData(f);let S=Math.round(f.reduce((v,R)=>v+R)/f.length);S=Math.min(100,S),p=S,l&&l(S)},h)};return b(),{updateInterval:S=>{m(),h=S,b()},getLevel:()=>p,dispose:()=>{m(),n.disconnect(),u.disconnect()}}}(this.audioContext,this.sourceNode,i,t,r=>{this.emit("audioLevel",r)})}stop(){this.analyser&&this.analyser.dispose(),this.analyser=void 0,this.sourceNode=void 0,this.stream.getAudioTracks().forEach(e=>{this.stream.removeTrack(e)})}dispose(){this.stop()}}class Xa extends se{constructor(e,t,i,r){super();g(this,"uid");g(this,"name");g(this,"rtsManager");g(this,"callId","");g(this,"audioLevelMonitor");g(this,"audioVolumeIndicationInterval",0);this.uid=e,this.name=t,this.rtsManager=i,this.audioVolumeIndicationInterval=r,this.audioLevelMonitor=new Wo}get userId(){return this.uid}get displayname(){return this.name}createCallId(e=!1){this.callId&&!e||(this.callId=Ne.createCallid())}setUserInfo(e,t){this.uid=e,this.name=t}refreshUserInfo(e){this.uid=e}getAudioLevel(){return this.audioLevelMonitor.getLevel()}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval=e}clear(){this.audioLevelMonitor.dispose()}}class Ya{static getCurrentStatus(a){let e=0;a.micOpen&&(e+=1),a.micInterrupted&&(e+=2),a.cameraOpen&&(e+=4),a.screenShare&&(e+=128),a.audioDisable&&(e+=8),a.videoDisable&&(e+=16),a.screenDisable&&(e+=256);let t=e.toString(16);for(;t.length<16;)t="0"+t;return t}static parseStatus(a){let e=parseInt(a,16);return{micOpen:!!(1&e),micInterrupted:!!(2&e),cameraOpen:!!(4&e),screenShare:!!(128&e),audioDisable:!!(8&e),videoDisable:!!(16&e),screenDisable:!!(256&e),backgroundMode:!!(32&e),accompanyPlaying:!!(64&e)}}}const C=(s,a)=>(e,t,i)=>{const r=i.value;return i.value=function(...n){var h;const c=`[${((h=e.constructor)==null?void 0:h.logName)||""}]`,o=Date.now();let l=[];if(s)try{l=s(n)}catch(p){}N.interface(c,t,...l);const d=r.apply(this,n);return Promise.resolve(d).then(p=>p).catch(p=>p).then(p=>{var b;let u="";const f=p instanceof Error,m=f&&((b=e.constructor)==null?void 0:b.logError);if(a||f){if(m)u=p;else if(f)u=p.message||"";else{if(!a)return;if(p===void 0)u="";else try{u=a(p)}catch(S){}}N.interfaceResult(c,t,!(f&&m),Date.now()-o+"ms",u)}}),d},i},B=s=>s,Qa="customVideoProfile",Za="customScreenProfile",Cr={width:1280,height:720,frameRate:30,maxBitrate:2e3},en={width:1920,height:1080,frameRate:30,maxBitrate:2600};var bi=(s=>(s[s.ERROR_DEVICE_UNKNOWNERROR=1e4]="ERROR_DEVICE_UNKNOWNERROR",s[s.ERROR_DEVICE_AUDIODEVICE_NOTFOUND=10001]="ERROR_DEVICE_AUDIODEVICE_NOTFOUND",s[s.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED=10002]="ERROR_DEVICE_AUDIODEVICE_NOTALLOWED",s[s.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE=10003]="ERROR_DEVICE_AUDIODEVICE_NOTREADABLE",s[s.ERROR_DEVICE_VIDEODEVICE_NOTFOUND=10004]="ERROR_DEVICE_VIDEODEVICE_NOTFOUND",s[s.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED=10005]="ERROR_DEVICE_VIDEODEVICE_NOTALLOWED",s[s.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE=10006]="ERROR_DEVICE_VIDEODEVICE_NOTREADABLE",s[s.ERROR_SCREENSHARE_NOTSUPPORT=10010]="ERROR_SCREENSHARE_NOTSUPPORT",s[s.ERROR_SCREENSHARE_NOTALLOWED=10011]="ERROR_SCREENSHARE_NOTALLOWED",s[s.ERROR_SCREENSHARE_ENDED=10012]="ERROR_SCREENSHARE_ENDED",s[s.ERROR_SCREENSHARE_NOPERMISSION=10013]="ERROR_SCREENSHARE_NOPERMISSION",s[s.ERROR_SCREENSHARE_SAFARI_INVALIDACCESS=10014]="ERROR_SCREENSHARE_SAFARI_INVALIDACCESS",s[s.ERROR_SCREENSHARE_UNKNOWNERRO=10019]="ERROR_SCREENSHARE_UNKNOWNERRO",s[s.ERROR_DEVICE_NOTALLOWED=10021]="ERROR_DEVICE_NOTALLOWED",s[s.ERROR_DEVICE_NOTSUPPORT=2e4]="ERROR_DEVICE_NOTSUPPORT",s))(bi||{});const $o={1e4:Be.AliEngineLocalDeviceExceptionTypeUnknown,2e4:Be.AliEngineLocalDeviceExceptionTypeUnknown,10001:Be.AliEngineLocalDeviceExceptionTypeMicNotAvailable,10002:Be.AliEngineLocalDeviceExceptionTypeMicAuthFail,10003:Be.AliEngineLocalDeviceExceptionTypeMicOpenFail,10005:Be.AliEngineLocalDeviceExceptionTypeCameraAuthFail,10004:Be.AliEngineLocalDeviceExceptionTypeVideoDeviceException,10006:Be.AliEngineLocalDeviceExceptionTypeCameraOpenFail,10010:Be.AliEngineLocalDeviceExceptionTypeDisplayException,10011:Be.AliEngineLocalDeviceExceptionTypeDisplayException,10012:Be.AliEngineLocalDeviceExceptionTypeDisplayException,10013:Be.AliEngineLocalDeviceExceptionTypeDisplayException,10014:Be.AliEngineLocalDeviceExceptionTypeDisplayException,10019:Be.AliEngineLocalDeviceExceptionTypeDisplayException};var ot=(s=>(s.CREATE_ENGINE="create_engine",s.JOIN="join",s.WANT_INSERT_PUB_TASK="wantInsertPubTask",s.INSERT_PUB_TASK="InsertPubTask",s.HANDLE_PUB_TASK="HandlePubTask",s.RECV_NOTIFY_PUBLISH="RecvNotifyPublish",s.INSERT_SUB_TASK="InsertSubTask",s.HANDLE_SUB_TASK="HandleSubTask",s.FIRST_REMOTE="first_remote",s))(ot||{}),dt=(s=>(s.START="start",s.SEND_SIG="send_sig",s.RECV_RST="recv_rst",s.END="end",s.RECEIVED="received",s.DECODED="decoded",s.PLAYED="played",s))(dt||{});const tn=(s,a,e=!1)=>{const t=()=>(s.muted=!0,Promise.race([xt(500),s._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{let i;return e&&s.srcObject===a?i=Promise.resolve():(s.load(),s.srcObject=a,i=s.play(),s._playPromise=i),i}));return new Promise(i=>{if(X.AliRTS.BrowserUtil.isMicroMessenger){const r=window.top!==window.self,n=window.WeixinJSBridge||window.top.WeixinJSBridge;n?n.invoke("getNetworkType",{},()=>{i(t())}):(r?window.top.document:document).addEventListener("WeixinJSBridgeReady",()=>{n.invoke("getNetworkType",{},()=>{i(t())})}),setTimeout(()=>{i(t())},1e3)}else setTimeout(()=>{i(t())},0)})},wt=s=>{Promise.race([xt(100),s._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{s.srcObject=null,s._playPromise=void 0})};var kr=(s=>(s[s.AliEngineDataMsgNone=0]="AliEngineDataMsgNone",s[s.AliEngineDataMsgMusicProgress=1]="AliEngineDataMsgMusicProgress",s[s.AliEngineDataMsgCustom=2]="AliEngineDataMsgCustom",s))(kr||{});class Fi{constructor(a,e,t,i=0){g(this,"msgType");g(this,"msgId");g(this,"protocolVersion");g(this,"tlvVersion");this.msgType=a,this.msgId=e,this.protocolVersion=t,this.tlvVersion=i}build(){const a=new Uint8Array(4);return a.set(Uint8Array.from([this.protocolVersion,this.tlvVersion<<4|15&this.msgType]),0),a.set(Uint16Array.from([this.msgId]),2),a}static parse(a){const e=new DataView(a),t=e.getUint8(0),i=e.getUint8(1)>>4,r=15&e.getUint8(1),n=e.getUint16(2);return new Fi(r,n,t,i)}}class ji{constructor(a,e,t){g(this,"_byteArray");if(this._byteArray=new Uint8Array(0),a!==void 0&&e!==void 0&&t!==void 0){const i=new Fi(a,e,t).build();this._byteArray=new Uint8Array(i.byteLength+this._byteArray.byteLength),this._byteArray.set(i,0)}}write(a,e){const t=this._byteArray,i=new ArrayBuffer(5),r=new DataView(i);r.setUint8(0,a),r.setUint32(1,e.byteLength);const n=new Uint8Array(t.byteLength+5+e.byteLength);n.set(t,0),n.set(new Uint8Array(i),t.byteLength),n.set(new Uint8Array(e),t.byteLength+5),this._byteArray=n}static parse(a){const e={},t=new DataView(a);let i=0;for(;i<a.byteLength;){const r=t.getUint8(i),n=t.getUint32(i+1);if(!(i+5+n<=a.byteLength))break;{const c=a.slice(i+5,i+5+n);e[r]=c,i+=5+n}}return e}get buffer(){return this._byteArray.buffer}}class vi{constructor(a=0,e=!0,t=1,i=!1,r=0,n=!1,c=!1,o=3){g(this,"_fin",!0);g(this,"_hasExtension",!1);g(this,"_version",0);g(this,"_frameType",1);g(this,"_isEncrypted",!1);g(this,"_isCompressed",!1);g(this,"_signalType",3);g(this,"_payloadLength",0);this._fin=e,this._hasExtension=i,this._version=r,this._frameType=t,this._isEncrypted=n,this._isCompressed=c,this._signalType=o,this._payloadLength=a}get fin(){return this._fin}get hasExtension(){return this._hasExtension}get version(){return this._version}get frameType(){return this._frameType}get isEncrypted(){return this._isEncrypted}get isCompressed(){return this._isCompressed}get signalType(){return this._signalType}get payloadLength(){return this._payloadLength}toBuffer(){const a=new ArrayBuffer(4),e=new DataView(a);return e.setUint8(0,(this._fin?1:0)<<7|(this._hasExtension?1:0)<<6|this._version<<4|15&this._frameType),e.setUint8(1,(this._isEncrypted?1:0)<<7|(this._isCompressed?1:0)<<6|15&this._signalType),e.setUint16(2,this._payloadLength),a}static parse(a){const e=new DataView(a),t=e.getUint8(0)>>7==1,i=(64&e.getUint8(0))>>6==1,r=(48&e.getUint8(0))>>4,n=15&e.getUint8(0),c=e.getUint8(1)>>7==1,o=(64&e.getUint8(1))>>6==1,l=15&e.getUint8(1),d=e.getUint16(2);return new vi(d,t,n,i,r,c,o,l)}}class zi{constructor(a,e){g(this,"_body");g(this,"_header",new vi);this._header=a,this._body=e}get header(){return this._header}get isFin(){return this._header.fin}get body(){return this._body}toGRTNBuffer(){const a=this._header.toBuffer(),e=this._body,t=new ArrayBuffer(4);new DataView(t).setUint8(0,1*Math.pow(2,4));const i=new Uint8Array(t.byteLength+a.byteLength+e.byteLength);return i.set(new Uint8Array(t),0),i.set(new Uint8Array(a),t.byteLength),i.set(new Uint8Array(e),t.byteLength+a.byteLength),i.buffer}static parse(a){const e=a.slice(0,4),t=vi.parse(e);let i=new ArrayBuffer(0);return a.byteLength-4>=t.payloadLength&&(i=a.slice(4,4+t.payloadLength)),new zi(t,i)}}const Pr=s=>{const a=s.byteLength,e=new DataView(s);let t=0;for(let i=0;i<a;i++)t=256*t+e.getUint8(i);return t};let rn=0;class Vt{constructor(a,e=0,t=0,i=0){g(this,"data");g(this,"networkTime");g(this,"futureOrProgress");g(this,"type");this.data=a,this.type=e,this.networkTime=t,this.futureOrProgress=i}toBuffer(){const a=new ji(0,0,0);a.write(1,Uint8Array.from([0]).buffer),a.write(2,Uint16Array.from([0]).buffer),rn++,a.write(3,Uint32Array.from([rn]).buffer);const e=new ji;return e.write(1,Uint8Array.from([0]).buffer),e.write(2,Uint8Array.from([this.type]).buffer),e.write(3,Uint32Array.from([this.futureOrProgress]).buffer),e.write(4,Uint32Array.from([Number(this.networkTime>>32&4294967295),Number(4294967295&this.networkTime)]).buffer),e.write(5,this.data),a.write(30,e.buffer),a.buffer}static parse(a){if(!a||a.byteLength<4)return;Fi.parse(a.slice(0,4));const e=ji.parse(a.slice(4))[30];if(!e)return;const t=ji.parse(e),i=t[2],r=t[3],n=t[4],c=t[5];return c.byteLength!==0?new Vt(c,Pr(i),Pr(n),Pr(r)):void 0}}var Ko=Object.defineProperty,Jo=Object.getOwnPropertyDescriptor,Ee=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Jo(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&Ko(a,e,r),r};class yi extends se{constructor(){super();g(this,"_state");g(this,"time");this._state=te.AliRtcStatePublishIdle,this.time=Date.now()}get state(){return this._state}setState(e){const t=this._state,i=this.time;this._state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-i)/1e3))}}const Re=(St=class extends Xa{constructor(e){const{rtsManager:t,localStreamManager:i,slsReporter:r,signalingManager:n,audioVolumeIndicationInterval:c,parameter:o}=e;super("","",t,c);g(this,"sessionId","");g(this,"traceId","");g(this,"_url","");g(this,"joinTime",0);g(this,"publishPromise",Promise.resolve({traceId:"",l1ip:void 0}));g(this,"previewElements",[]);g(this,"screenPreviewElements",[]);g(this,"streamManager");g(this,"dc");g(this,"streamTracks");g(this,"publishId",lt());g(this,"signalingManager");g(this,"shouldPublish",!1);g(this,"monitorTimerId");g(this,"monitorDataCache",{});g(this,"candidateDataCache",[]);g(this,"pcMediaStatsMap",{});g(this,"slsReporter");g(this,"audioPubState");g(this,"videoPubState");g(this,"videoSmallPubState");g(this,"screenPubState");g(this,"dataPubState");g(this,"parameter",{});g(this,"onTrackEnd",e=>{this.emit(e)});this.streamManager=i,this.signalingManager=n,this.slsReporter=r,this.parameter=o,this.streamManager.on("trackended",l=>{this.onTrackEnd(l)}),this.streamManager.on("publishupdate",()=>{this.publishUpdate()}),this.audioPubState=new yi,this.audioPubState.on("change",(l,d,h)=>{this.emit("audioPublishStateChanged",l,d,h)}),this.videoPubState=new yi,this.videoPubState.on("change",(l,d,h)=>{this.emit("videoPublishStateChanged",l,d,h)}),this.videoSmallPubState=new yi,this.videoSmallPubState.on("change",(l,d,h)=>{this.emit("dualStreamPublishStateChanged",l,d,h)}),this.screenPubState=new yi,this.screenPubState.on("change",(l,d,h)=>{this.emit("screenPublishStateChanged",l,d,h)}),this.dataPubState=new yi,this.dataPubState.on("change",(l,d,h)=>{this.emit("dataPublishStateChanged",l,d,h)}),this.startStreamMonitor(),this.createCallId()}get url(){return this._url}set url(e){this._url=e,this.rtsManager.updateAuth(e)}get joined(){return!!this.uid}get isPublishing(){return this.rtsManager.publishingTracks.length>0}get publishStreams(){return this.streamManager.publishStreams}get cameraTrack(){return this.streamManager.cameraStreamInfo.originVideoTrack}get screenTrack(){return this.streamManager.screenStreamInfo.originVideoTrack}get audioTrack(){return this.streamManager.cameraStreamInfo.originAudioTrack}get hasCamera(){return!!this.streamManager.cameraStreamInfo.originVideoTrack}get hasMicrophone(){return!!this.streamManager.cameraStreamInfo.originAudioTrack}get hasScreenShare(){return!!this.streamManager.screenStreamInfo.originVideoTrack}get hasCameraTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:r})=>i==="video"&&t&&r===M.VideoLarge))}get hasCameraDualTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:r})=>i==="video"&&t&&r===M.VideoSmall))}get hasScreenTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:r})=>i==="video"&&t&&r===M.Screen))}get hasAudioTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:r})=>i==="audio"&&t&&r===M.Audio))}get cameraDirection(){var e,t;return(t=(e=this.streamManager.cameraStreamInfo)==null?void 0:e.cameraVideoConstraints)==null?void 0:t.facingMode}get audioCaptureDisabled(){return this.streamManager.audioCaptureDisabled}get cameraCaptureDisabled(){return this.streamManager.cameraCaptureDisabled}get publishLocalVideoStreamEnabled(){return this.streamManager.publishLocalVideoStreamEnabled}get publishLocalAudioStreamEnabled(){return this.streamManager.publishLocalAudioStreamEnabled}get publishLocalScreenStreamEnabled(){return this.streamManager.publishLocalScreenStreamEnabled}setPublishLocalAudioStreamEnabled(e){this.streamManager.publishLocalAudioStreamEnabled=e}setPublishLocalVideoStreamEnabled(e){this.streamManager.publishLocalVideoStreamEnabled=e}setPublishLocalScreenStreamEnabled(e){this.streamManager.publishLocalScreenStreamEnabled=e}initInfo(e,t){this.joinTime=Date.now(),this.rtsManager.localJoinTime=this.joinTime,this.setUserInfo(e.userId,e.userId),this.url=t,this.sessionId=e.sessionId||Ne.createCallid("web"),this.updatePubId()}setVideoProfile(e){return I(this,null,function*(){yield this.streamManager.setVideoProfile(Qa,e)})}setVideoContentHint(e){this.streamManager.setVideoContentHint(e)}setScreenContentHint(e){this.streamManager.setScreenContentHint(e)}setAudioProfile(e){return I(this,null,function*(){yield this.streamManager.setAudioProfile(e)})}setScreenProfile(e){return I(this,null,function*(){yield this.streamManager.setScreenProfile(Za,e)})}setCameraDirection(e){if(e===mi.CAMERA_FRONT)this.streamManager.setCameraVideoConstraints({facingMode:"user"});else{if(e!==mi.CAMERA_REAR)throw new V(U.ERR_CAMERA_OPEN_FAIL,`camera direction set to ${e} failed`);this.streamManager.setCameraVideoConstraints({facingMode:"environment"})}}setCameraDeviceId(e){this.streamManager.setCameraVideoConstraints({deviceId:e})}muteLocalCamera(e){this.streamManager.setCameraMuted(e),this.slsReporter.reportMute(this.callId,!e,"video")}muteLocalMic(e){this.streamManager.setAudioMuted(e),this.slsReporter.reportMute(this.callId,!e,"audio")}muteLocalScreen(e){this.streamManager.setScreenMuted(e),this.slsReporter.reportMute(this.callId,!e,"screen")}setMicrophoneDeviceId(e){this.streamManager.setMicAudioConstraints({deviceId:e})}setMicrophoneConstraints(e){this.streamManager.setMicAudioConstraints(e)}updatePubId(){this.publishId=lt()}clearPublishState(){this.streamTracks=void 0}leave(){return I(this,null,function*(){this.shouldPublish=!1,this.isPublishing&&(yield this.unPublish()),this.joinTime=0,this.dc=void 0})}clear(){return I(this,null,function*(){Zr(St.prototype,this,"clear").call(this),this.stopPreview(),this.resetPreviewElements(),this.resetSecondayPreviewElements(),this.clearStream(),yield this.leave(),this.streamManager.cameraCaptureDisabled=!1})}resetElement(e){this.previewElements.includes(e)&&(wt(e),this.previewElements.splice(this.previewElements.indexOf(e),1)),this.screenPreviewElements.includes(e)&&(wt(e),this.screenPreviewElements.splice(this.screenPreviewElements.indexOf(e),1))}setPreviewElement(e){const{videoElement:t,screen:i}=e;i?this.screenPreviewElements.includes(t)||(this.screenPreviewElements.push(t),this.preview(e)):this.previewElements.includes(t)||(this.previewElements.push(t),this.preview(e))}startDefaultCameraAndMic(e){return I(this,null,function*(){const{hasCamera:t,cameraCaptureDisabled:i,publishLocalVideoStreamEnabled:r}=this,{hasMicrophone:n,audioCaptureDisabled:c,publishLocalAudioStreamEnabled:o}=this,l=!t&&!e&&!i&&r,d=!n&&!c&&o;try{l&&d?yield this.startCameraAndMic():l?yield this.startCameraCapture():d&&(yield this.startAudioCapture())}catch(h){const p=h.errorCode;let u=U.ERR_CAMERA_OPEN_FAIL;throw l?((p===bi.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED||bi.ERROR_DEVICE_NOTALLOWED)&&(u=U.ERR_CAMERA_AUTH_FAIL),u=U.ERR_CAMERA_OPEN_FAIL):((p===bi.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED||bi.ERROR_DEVICE_NOTALLOWED)&&(u=U.ERR_MIC_AUTH_FAIL),u=U.ERR_MIC_OPEN_FAIL),new V(u,`auto open fail: ${h.message}`)}})}setViewConfig(e,t){if(e){if(![ce.AliRtcVideoTrackCamera,ce.AliRtcVideoTrackScreen].includes(t))throw new V(U.ERR_INVALID_ARGUMENTS,"set view config invalid track",{track:t});e.forEach(i=>{this.setPreviewElement({videoElement:i,screen:t===ce.AliRtcVideoTrackScreen})})}else t===ce.AliRtcVideoTrackCamera?this.stopPreview({primary:!0,screen:!1}):this.stopPreview({primary:!1,screen:!0})}startCameraCapture(){return I(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,yield this.createLocalStream({video:!0})})}stopCameraCapture(){return I(this,null,function*(){this.streamManager.cameraCaptureDisabled=!0,yield this.stopLocalStream({video:!0})})}startAudioCapture(){return I(this,null,function*(){return this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({audio:!0})})}stopAudioCapture(){return I(this,null,function*(){this.streamManager.audioCaptureDisabled=!0,yield this.stopLocalStream({audio:!0})})}startCameraAndMic(){return I(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({video:!0,audio:!0})})}preview(e){return I(this,null,function*(){const{videoElement:t,screen:i}=e!=null?e:{};try{let r=i?this.streamManager.screenStreamInfo.previewStream:this.streamManager.cameraStreamInfo.previewStream;if(!t)throw new V(U.ERR_INVALID_ARGUMENTS,"no video element found",{videoElement:t});return r?(tn(t,r.mediaStream),this.setPreviewElement(e),r.mediaStream):void N.info(`[${St.logName}]`,"preview no stream founded")}catch(r){const n=U.ERR_INNER;throw V.fromError(r,n,"preview failed")}})}previewAll(e){return I(this,null,function*(){const{primary:t=!0,screen:i=!0}=e!=null?e:{};if(t&&this.previewElements.length)for(let r=0;r<this.previewElements.length;r++){const n=this.previewElements[r];yield this.preview({videoElement:n})}if(i&&this.screenPreviewElements.length)for(let r=0;r<this.screenPreviewElements.length;r++){const n=this.screenPreviewElements[r];yield this.preview({videoElement:n,screen:!0})}})}stopPreview(e){const{videoElement:t,primary:i=!0,screen:r=!0}=e||{};if(t){const n=this.previewElements.findIndex(c=>c===t);if(n>=0)this.previewElements.splice(n,1),wt(t);else{const c=this.screenPreviewElements.findIndex(o=>o===t);c>=0&&(this.screenPreviewElements.splice(c,1),wt(t))}}else i&&(this.previewElements.forEach(n=>{wt(n)}),this.previewElements=[]),r&&(this.screenPreviewElements.forEach(n=>{wt(n)}),this.screenPreviewElements=[])}resumePublish(){return I(this,null,function*(){this.shouldPublish&&(this.createCallId(!0),yield this.startPublish(!0))})}createLocalStream(e){return I(this,null,function*(){try{if(e.video)for(let i=0;i<this.previewElements.length;i++){const r=this.previewElements[i];wt(r)}else if(e.screen)for(let i=0;i<this.screenPreviewElements.length;i++){const r=this.screenPreviewElements[i];wt(r)}const t=yield this.streamManager.createLocalStream(e);return t!=null&&t.audioTrack&&this.audioVolumeIndicationInterval>0&&this.audioLevelMonitor.start(t.audioTrack,this.audioVolumeIndicationInterval),e.video?this.previewAll({primary:!0}):e.screen&&this.previewAll({screen:!0}),t}catch(t){const i=$o[t.errorCode];throw i&&(e.audio?this.emit("localDeviceException",Rt.AliEngineLocalDeviceTypeMic,i,""):e.video?this.emit("localDeviceException",Rt.AliEngineLocalDeviceTypeCamera,i,""):e.screen?this.emit("localDeviceException",Rt.AliEngineLocalDeviceTypeDisplay,i,""):this.emit("localDeviceException",Rt.AliEngineLocalDeviceTypeUnknown,i,"")),t}})}stopLocalStream(e){return I(this,null,function*(){e.audio&&this.audioLevelMonitor.stop(),yield this.streamManager.stopLocalStream(e)})}compareAndPublish(e,t,i){return I(this,null,function*(){var n,c;if(!e&&!t)return;if(e&&!t){const o={};return i===M.Audio?o.audio=!0:i===M.VideoLarge||i===M.VideoSmall?(o.video=!0,o.vMsid=i):i===M.Screen&&(o.screen=!0),yield this.publishDeleteTracks(o)}const r={};if(t!=null&&t.hasVideo&&(r.isScreen=i===M.Screen,r.vMsid=i),t!=null&&t.hasAudio&&(r.aMsid=i),!e&&t)return yield this.publishAdd(t,r,!1);if(e&&t&&e.trackId!==(((n=t.videoTrack)==null?void 0:n.id)||((c=t.audioTrack)==null?void 0:c.id)))return yield this.publishReplace(t,r)})}reportAudioProfile(){const e=this.streamManager.cameraStreamInfo.audioProfile||"standard",t=X.AliRTS.AudioProfileMap.get(e);this.slsReporter.reportPublishProfile(M.Audio,{a_profile:e,bits:(t==null?void 0:t.maxBitrate)||0,samplerate:(t==null?void 0:t.sampleRate)||0,channel:(t==null?void 0:t.channelCount)||0})}reportVideoProfile(){const e=this.streamManager.cameraStreamInfo.videoProfile||"",t=X.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(M.VideoLarge,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}reportScreenProfile(){const e=this.streamManager.screenStreamInfo.videoProfile||"",t=X.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(M.Screen,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}updateDataChannel(e){e&&(this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"))}publishDataChannel(){return I(this,null,function*(){if(this.dataPubState.state!==te.AliRtcStatePublishing){this.dataPubState.setState(te.AliRtcStatePublishing);try{const e=yield this.rtsManager.publishAddDataChannel(this.url);e?(this.updateDataChannel(e),this.dataPubState.setState(te.AliRtcStatePublished)):(this.dataPubState.setState(te.AliRtcStateNoPublish),this.emit("publishDataError",new V(U.ERR_INNER,"publishDataError")))}catch(e){N.error("[LocalUser]","publishDataChannel error",e),this.dataPubState.setState(te.AliRtcStateNoPublish)}}})}startPublish(){return I(this,arguments,function*(e=!1,t=_t.MANUAL){var l;if(!this.joined)return;this.shouldPublish=!0;const i=this.streamManager.publishStreams,{audio:r,video:n,videoSmall:c,screen:o}=i;if(r||n||c||o)try{const d=new Date().getTime();r&&this.audioPubState.setState(te.AliRtcStatePublishing),n&&this.videoPubState.setState(te.AliRtcStatePublishing),c&&this.videoSmallPubState.setState(te.AliRtcStatePublishing),o&&this.screenPubState.setState(te.AliRtcStatePublishing),this.publishPromise=this.rtsManager.publish(this,e,t);const{traceId:h,l1ip:p}=yield this.publishPromise;this.streamTracks=this.rtsManager.publishingTracks,this.traceId=h;const u={type:Ot.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,resume:e,subscribe:{signal:"",pullstreamurl:this.url},l1ip:this.parameter.reportL1IP?p:void 0,callid:this.callId,tracks:this.streamTracks,traceid:h};(l=this.parameter.data)!=null&&l.enablePubDataChannel&&this.publishDataChannel().then(()=>{this.syncPublishToRoomServer(u,i,d)}),h&&(this.traceId=h),r&&this.reportAudioProfile(),n&&this.reportVideoProfile(),o&&this.reportScreenProfile(),yield this.syncPublishToRoomServer(u,i,d),r&&this.audioPubState.setState(te.AliRtcStatePublished),n&&this.videoPubState.setState(te.AliRtcStatePublished),c&&this.videoSmallPubState.setState(te.AliRtcStatePublished),o&&this.screenPubState.setState(te.AliRtcStatePublished)}catch(d){throw r&&this.audioPubState.setState(te.AliRtcStateNoPublish),n&&this.videoPubState.setState(te.AliRtcStateNoPublish),c&&this.videoSmallPubState.setState(te.AliRtcStateNoPublish),o&&this.screenPubState.setState(te.AliRtcStateNoPublish),d}else N.event(`[${St.logName}]`,"startPublish no stream founded")})}updateStreams(){return I(this,null,function*(){yield this.streamManager.updateStreams()})}publishUpdate(e){return I(this,null,function*(){var n,c,o,l,d;if(N.info(`[${St.logName}]`,"publishUpdate",e||"-",this.shouldPublish),!this.shouldPublish)return;if(!this.rtsManager.isConnecting&&!this.rtsManager.isConnected)return void(yield this.startPublish());yield this.publishPromise;const t=this.streamManager.publishStreams;let i;const r=new Date().getTime();try{const h=(n=this.streamTracks)==null?void 0:n.find(({ssrc:R,type:w,msid:y})=>w==="audio"&&R&&y===M.Audio),p=yield this.compareAndPublish(h,t.audio,M.Audio);p&&(i=p);const u=(c=this.streamTracks)==null?void 0:c.find(({ssrc:R,type:w,msid:y})=>w==="video"&&R&&y===M.VideoLarge),f=yield this.compareAndPublish(u,t.video,M.VideoLarge);f&&(i=f);const m=(o=this.streamTracks)==null?void 0:o.find(({ssrc:R,type:w,msid:y})=>w==="video"&&R&&y===M.VideoSmall),b=yield this.compareAndPublish(m,t.videoSmall,M.VideoSmall);b&&(i=b);const S=(l=this.streamTracks)==null?void 0:l.find(({ssrc:R,type:w,msid:y})=>w==="video"&&R&&y===M.Screen),v=yield this.compareAndPublish(S,t.screen,M.Screen);v&&(i=v),(d=this.parameter.data)!=null&&d.enablePubDataChannel&&!this.dc&&(yield this.publishDataChannel()),i||e!==_t.RECONNECT?i&&(yield this.syncPublishToRoomServer(i,t,r)):this.syncPublishToRoomServer({type:Ot.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.rtsManager.publishingTracks,traceid:this.traceId},t,Date.now())}catch(h){const{code:p}=h!=null?h:{},u=this.url;throw p===403&&u&&(yield this.refreshPushStreamUrl(),i=yield this.publishUpdate()),h}return i})}syncPublishToRoomServer(e,t,i){return I(this,null,function*(){var o;if(!e)return void N.event(`[${St.logName}]`,"sync publish to room server failed because no publishInfo");let r=e;if(this.dc){const c=e,{tracks:l}=c,d=Mt(c,["tracks"]);r=yt(G({},d),{tracks:[...l,{type:"data",msid:M.Data,ssrc:`web_${this.callId.substring(0,8)}_${((o=this.dc.datachannel)==null?void 0:o.id)||"0"}`,codec:"text"}]})}const n=yield this.signalingManager.publish(r);e.signaltid=n.tid})}refreshPushStreamUrl(){return I(this,null,function*(){const e=new V(U.ERR_INNER,"refresh push stream url error"),t=this.url;if(!t)throw e;const i=yield this.signalingManager.refreshUrl({pushstreamurl:t});if(!(i!=null&&i.pushstreamurl))throw e;this.url=i.pushstreamurl})}publishAdd(e,t,i=!1,r=0){return I(this,null,function*(){const n=(t==null?void 0:t.aMsid)===M.Audio,c=(t==null?void 0:t.vMsid)===M.VideoLarge,o=(t==null?void 0:t.vMsid)===M.VideoSmall,l=(t==null?void 0:t.vMsid)===M.Screen;n&&this.audioPubState.setState(te.AliRtcStatePublishing),c&&this.videoPubState.setState(te.AliRtcStatePublishing),o&&this.videoSmallPubState.setState(te.AliRtcStatePublishing),l&&this.screenPubState.setState(te.AliRtcStatePublishing);try{const d=yield this.rtsManager.publishAdd(this,e,t,!1,!0);d&&(this.traceId=d),n&&(this.audioPubState.setState(te.AliRtcStatePublished),this.reportAudioProfile()),c&&(this.videoPubState.setState(te.AliRtcStatePublished),this.reportVideoProfile()),o&&this.videoSmallPubState.setState(te.AliRtcStatePublished),l&&(this.screenPubState.setState(te.AliRtcStatePublished),this.reportScreenProfile()),this.streamTracks=this.rtsManager.publishingTracks;const h={type:Ot.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:i,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks,traceid:d};return this.reportSelfDeviceStatus(),this.monitorTimerId||this.startStreamMonitor(),h}catch(d){let h=U.ERR_SDK_PUBLISH_INVAILD;if(n&&(this.audioPubState.setState(te.AliRtcStateNoPublish),h=U.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),c&&(this.videoPubState.setState(te.AliRtcStateNoPublish),h=U.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),o&&(this.videoSmallPubState.setState(te.AliRtcStateNoPublish),h=U.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED),l&&(this.screenPubState.setState(te.AliRtcStateNoPublish),h=U.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED),d.errorCode===15006&&r<3)return this.publishAdd(e,t,i,r+1);throw V.fromError(d,h,"publish add failed")}})}publishReplace(e,t){return I(this,null,function*(){try{yield this.rtsManager.publishReplace(this.url,e,t),this.streamTracks=this.rtsManager.publishingTracks;const i=(t==null?void 0:t.vMsid)===M.VideoLarge,r=(t==null?void 0:t.vMsid)===M.Screen;i&&this.streamManager.setVideoProfile(void 0,void 0,!0),r&&this.streamManager.setScreenProfile(void 0,void 0);const n={type:Ot.Replace,userid:this.userId,sessionid:"",pubid:this.publishId,displayname:this.name,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks};return this.reportSelfDeviceStatus(),n}catch(i){throw V.fromError(i,U.ERR_INNER,`publish replace failed, vMsid: ${t==null?void 0:t.vMsid} aMsid: ${t==null?void 0:t.aMsid}`)}})}publishDeleteTracks(e){return I(this,null,function*(){const t={type:Ot.Delete,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{return yield this.rtsManager.publishDelete(this.url,e),this.streamTracks=this.rtsManager.publishingTracks,e.audio&&this.audioPubState.setState(te.AliRtcStateNoPublish),e.video&&(e.vMsid===M.VideoSmall?this.videoSmallPubState.setState(te.AliRtcStateNoPublish):this.videoPubState.setState(te.AliRtcStateNoPublish)),e.screen&&this.screenPubState.setState(te.AliRtcStateNoPublish),t.tracks=this.streamTracks,this.reportSelfDeviceStatus(),t}catch(i){throw V.fromError(i,U.ERR_INNER,"publish delete tracks failed")}})}publishStop(){return I(this,null,function*(){N.info(`[${St.logName}]`,"publishStop",{url:this.url});const e=new Date().getTime();try{const t=this.hasAudioTrackInMS,i=this.hasCameraTrackInMS,r=this.hasCameraDualTrackInMS,n=this.hasScreenTrackInMS;yield this.rtsManager.publishStop(this.url),t&&this.audioPubState.setState(te.AliRtcStateNoPublish),i&&this.videoPubState.setState(te.AliRtcStateNoPublish),r&&this.videoSmallPubState.setState(te.AliRtcStateNoPublish),n&&this.screenPubState.setState(te.AliRtcStateNoPublish),this.traceId="",Object.keys(this.monitorDataCache).forEach(o=>{this.reportPublishMonitor(o)}),this.streamTracks=[];const c={type:Ot.Stop,userid:this.userId,sessionid:this.sessionId,displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};return this.syncPublishToRoomServer(c,{},e),c}catch(t){throw V.fromError(t,U.ERR_INNER,"publish stop failed")}})}unPublish(){return I(this,null,function*(){this.shouldPublish=!1;const e=new Date().getTime();let t={type:Ot.UnPublish,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{if(this.isPublishing){const i=this.hasAudioTrackInMS,r=this.hasCameraTrackInMS,n=this.hasCameraDualTrackInMS,c=this.hasScreenTrackInMS;yield this.rtsManager.unpublish(),this.streamTracks=[],this.stopStreamMonitor(),i&&this.audioPubState.setState(te.AliRtcStateNoPublish),r&&this.videoPubState.setState(te.AliRtcStateNoPublish),n&&this.videoSmallPubState.setState(te.AliRtcStateNoPublish),c&&this.screenPubState.setState(te.AliRtcStateNoPublish),this.traceId="",this.clearStream()}return this.dc&&(this.rtsManager.publishStopDataChannel(this.url,this.dc),this.dataPubState.setState(te.AliRtcStateNoPublish),this.dc=void 0),this.slsReporter.reportUnpublish(this.callId||"",e,0,""),t}catch(i){throw V.fromError(i,U.ERR_INNER,"unpublish failed")}})}reportSelfDeviceStatus(){this.emit(Qe.Local,this.getDeviceStatus())}getDeviceStatus(){var t,i,r,n;let e={micOpen:!1,micInterrupted:!1,cameraOpen:!1,screenShare:!1,audioDisable:!0,videoDisable:!0,screenDisable:!0,backgroundMode:!1,accompanyPlaying:!1};return e.cameraOpen=this.hasCameraTrackInMS,e.videoDisable=this.hasCamera&&!((t=this.streamManager.cameraStreamInfo.originVideoTrack)!=null&&t.enabled),e.micOpen=this.hasAudioTrackInMS,e.audioDisable=this.hasMicrophone&&!((i=this.streamManager.cameraStreamInfo.originAudioTrack)!=null&&i.enabled),e.screenShare=this.hasScreenTrackInMS,e.screenDisable=this.hasScreenShare&&!((n=(r=this.streamManager.screenStreamInfo)==null?void 0:r.originVideoTrack)!=null&&n.enabled),Ya.getCurrentStatus(e)}resetPreviewElements(){this.previewElements.forEach(e=>{e.srcObject=null,e._playPromise=void 0},[]),this.previewElements=[]}resetSecondayPreviewElements(){this.screenPreviewElements.forEach(e=>{e.srcObject=null,e._playPromise=void 0},[]),this.screenPreviewElements=[]}getMediaStats(e){return this.pcMediaStatsMap[e]}reportPublishMonitor(e){if(!e)return;let t;try{t=e===M.Audio?this.rtsManager.getStreamByMsid({url:this.url,aMsid:e}).audioTrack:this.rtsManager.getStreamByMsid({url:this.url,vMsid:e}).videoTrack}catch(i){}this.slsReporter.reportPublishMonitor(this.callId,this.traceId||"",e,t,this.monitorDataCache[e]),this.monitorDataCache[e]=[]}reportNetwork(){this.slsReporter.reportNetworkMonitor(this.candidateDataCache),this.candidateDataCache=[]}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>I(this,null,function*(){var e,i;try{const r=yield this.rtsManager.getPCStats();let n,c;if(r==null||r.forEach(l=>{l.type==="media-source"||l.type==="media-playout"?l.id&&(this.pcMediaStatsMap[l.id]=l):l.type==="candidate-pair"&&l.state==="succeeded"&&(n=l)}),((e=this.candidateDataCache)==null?void 0:e.length)>0){const l=this.candidateDataCache[this.candidateDataCache.length-1]||{},t=l,{_last:d}=t;c=Mt(t,["_last"])}((i=this.candidateDataCache)==null?void 0:i.length)>=30&&this.reportNetwork(),n&&(n._last=c,this.candidateDataCache.push(n));let o=Object.keys(this.monitorDataCache).filter(l=>{var d;return((d=this.monitorDataCache[l])==null?void 0:d.length)>0});(this.streamTracks||[]).forEach(l=>{const d=l.msid;if(!d)return;let h;o.includes(d)&&(o=o.filter(p=>p!==d)),h=d===M.Audio?this.rtsManager.getPublishAudioStats(this.url):this.rtsManager.getPublishVideoStats(this.url,d),h.then(p=>{if(!p.timestamp)return;this.monitorDataCache[d]||(this.monitorDataCache[d]=[]);const u=this.getMediaStats(p.mediaSourceId);p._source=u;const f=this.monitorDataCache[d];let m;if((f==null?void 0:f.length)>0){const S=f[f.length-1]||{},b=S,{_last:v}=b;m=Mt(b,["_last"])}(f==null?void 0:f.length)>=30&&this.reportPublishMonitor(d),p._last=m,p._codec=l.codec||"",this.monitorDataCache[d].push(p)})}),o.forEach(l=>{this.reportPublishMonitor(l)})}catch(r){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportPublishMonitor(e)})}clearStream(){this.streamManager.stop(),this.audioPubState.setState(te.AliRtcStatePublishIdle),this.videoPubState.setState(te.AliRtcStatePublishIdle),this.videoSmallPubState.setState(te.AliRtcStatePublishIdle),this.screenPubState.setState(te.AliRtcStatePublishIdle)}getCurrentCameraDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originVideoTrack)==null?void 0:e.getSettings().deviceId}getCurrentMicDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originAudioTrack)==null?void 0:e.getSettings().deviceId}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.streamManager.cameraStreamInfo.originAudioTrack&&this.audioLevelMonitor.start(this.streamManager.cameraStreamInfo.originAudioTrack,e),this.audioVolumeIndicationInterval=e)}sendSEI(e,t,i){return I(this,null,function*(){if(!this.url)return;let r=0;return r=!t||t<1?1:t-1,this.rtsManager.sendSEI(this.url,e,r,i)})}sendDataChannelMessage(e){var i;if(!((i=this.parameter.data)!=null&&i.enablePubDataChannel))throw new V(U.ERR_INNER,"data channel publish is not enabled");if(!this.dc)throw new V(U.ERR_INNER,"data channel is not ready");const t=function(r,n){let c=0;const o=[];for(;c<r.byteLength;){const l=Math.min(n,r.byteLength-c),d=r.slice(c,c+l);o.push(d),c+=l}return o}(e.toBuffer(),1156);t.forEach((r,n)=>{const c=new zi(new vi(r.byteLength,n===t.length-1,n===0?1:0),r);this.dc.send(c.toGRTNBuffer())})}getStats(){return I(this,null,function*(){const e=[];if(this.hasAudioTrackInMS){const n=yield this.rtsManager.getPublishAudioStats(this.url);n&&e.push({stats:n,track:$t.AliRtcAudioTrackMic})}const t=[];if(this.hasCameraTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.VideoLarge);n&&t.push({track:ce.AliRtcVideoTrackCamera,streamType:Ke.AliRtcVideoStreamTypeHigh,stats:n})}if(this.hasCameraDualTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.VideoSmall);n&&t.push({track:ce.AliRtcVideoTrackCamera,streamType:Ke.AliRtcVideoStreamTypeLow,stats:n})}if(this.hasScreenTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.Screen);n&&t.push({track:ce.AliRtcVideoTrackScreen,stats:n})}let i;const r=yield this.rtsManager.getPCStats();return r==null||r.forEach(n=>{n.type==="candidate-pair"&&n.state==="succeeded"&&(i=n)}),{audio:e,video:t,candidate:i}})}markReconnect(e){const t=[],i=this.streamManager.publishStreams;!i.audio||e&&!e.includes(M.Audio)||t.push(this.audioPubState),!i.video||e&&!e.includes(M.VideoLarge)||t.push(this.videoPubState),!i.screen||e&&!e.includes(M.Screen)||t.push(this.screenPubState),!this.dc||e&&!e.includes(M.Data)||t.push(this.dataPubState),t.forEach(r=>{r.setState(te.AliRtcStateReconnecting)})}markReconnected(e){var r;const t=[],i=this.streamManager.publishStreams;if(!i.audio||e&&!e.includes(M.Audio)||t.push(this.audioPubState),!i.video||e&&!e.includes(M.VideoLarge)||t.push(this.videoPubState),!i.screen||e&&!e.includes(M.Screen)||t.push(this.screenPubState),this.dc&&(!e||e.includes(M.Data))&&(t.push(this.dataPubState),(r=this.parameter.data)==null?void 0:r.enablePubDataChannel)){const n=this.rtsManager.getDatachannelByMsid({url:this.url,msid:M.Data});this.updateDataChannel(n)}this.publishUpdate(_t.RECONNECT),t.forEach(n=>{n.setState(te.AliRtcStatePublished)})}},g(St,"logName","LocalUser"),St);Ee([C()],Re.prototype,"clearPublishState",1),Ee([C()],Re.prototype,"clear",1),Ee([C(B)],Re.prototype,"startDefaultCameraAndMic",1),Ee([C()],Re.prototype,"setViewConfig",1),Ee([C()],Re.prototype,"startCameraCapture",1),Ee([C()],Re.prototype,"stopCameraCapture",1),Ee([C()],Re.prototype,"startAudioCapture",1),Ee([C()],Re.prototype,"stopAudioCapture",1),Ee([C()],Re.prototype,"startCameraAndMic",1),Ee([C()],Re.prototype,"stopPreview",1),Ee([C()],Re.prototype,"resumePublish",1),Ee([C()],Re.prototype,"createLocalStream",1),Ee([C()],Re.prototype,"stopLocalStream",1),Ee([C()],Re.prototype,"updateDataChannel",1),Ee([C(B)],Re.prototype,"startPublish",1),Ee([C()],Re.prototype,"updateStreams",1),Ee([C(([s])=>[s])],Re.prototype,"syncPublishToRoomServer",1),Ee([C()],Re.prototype,"refreshPushStreamUrl",1),Ee([C(([s,a,e])=>[JSON.stringify(e)])],Re.prototype,"publishAdd",1),Ee([C(([s,a])=>[JSON.stringify(a)])],Re.prototype,"publishReplace",1),Ee([C(B)],Re.prototype,"publishDeleteTracks",1),Ee([C()],Re.prototype,"publishStop",1),Ee([C()],Re.prototype,"unPublish",1),Ee([C(([s,a,e])=>[s.length,a,e])],Re.prototype,"sendSEI",1),Ee([C(B)],Re.prototype,"markReconnect",1),Ee([C(B)],Re.prototype,"markReconnected",1);let Go=Re;var ht=(s=>(s.OPUS="opus",s.H264="H264",s.H265="H265",s.AV1="AV1",s.UNKNOWN="",s))(ht||{}),le=(s=>(s[s.NotSubscribe=0]="NotSubscribe",s[s.Subscribing=1]="Subscribing",s[s.Subscribed=2]="Subscribed",s))(le||{}),qt=(s=>(s.VideoTrackEnded="videoTrackEnded",s.AudioTrackEnded="audioTrackEnded",s.ScreenTrackEnded="screenTrackEnded",s))(qt||{});const sn=s=>I(this,null,function*(){return yield X.AliRTS.createStream({custom:!0,mediaStream:s})}),Ri=s=>I(this,null,function*(){const a=(e=>{const t=new MediaStream;return t.addTrack(e),t})(s);return yield sn(a)});var qo=Object.defineProperty,Xo=Object.getOwnPropertyDescriptor;class Dr extends se{constructor(){super();g(this,"audioInfo",{subscribeState:le.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:ht.UNKNOWN});g(this,"videoLargeInfo",{subscribeState:le.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:ht.UNKNOWN});g(this,"videoSmallInfo",{subscribeState:le.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:ht.UNKNOWN});g(this,"screenInfo",{subscribeState:le.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:ht.UNKNOWN});g(this,"dataInfo",{subscribeState:le.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:ht.UNKNOWN});g(this,"audioVolume",1);g(this,"audioMuted",!1);g(this,"userStatus")}getAudioInfo(){return this.audioInfo}getVideoSmallInfo(){return this.videoSmallInfo}getVideoLargeInfo(){return this.videoLargeInfo}getScreenInfo(){return this.screenInfo}getDataInfo(){return this.dataInfo}get subscribingInfos(){return[this.audioInfo,this.videoLargeInfo,this.videoSmallInfo,this.screenInfo].filter(e=>e.msid&&e.subscribeState===le.Subscribed)}get hasTrack(){return this.hasAudio||this.hasVideo||this.hasScreen||this.hasData}get hasAudio(){return this.audioInfo.ssrc!==""}get hasVideo(){return this.videoLargeInfo.ssrc!==""||this.videoSmallInfo.ssrc!==""}get hasVideoLarge(){return this.videoLargeInfo.ssrc!==""}get hasVideoSmall(){return this.videoSmallInfo.ssrc!==""}get hasScreen(){return this.screenInfo.ssrc!==""}get hasData(){return this.dataInfo.ssrc!==""}get isAudioSubscribed(){return this.audioInfo.subscribeState===le.Subscribed}get isAudioSubscribing(){return this.audioInfo.subscribeState===le.Subscribing}get isVideoSubscribed(){return this.isVideoLargeSubscribed||this.isVideoSmallSubscribed}get isVideoSubscribing(){return this.isVideoLargeSubscribing||this.isVideoSmallSubscribing}get isVideoLargeSubscribed(){return this.videoLargeInfo.subscribeState===le.Subscribed}get isVideoLargeSubscribing(){return this.videoLargeInfo.subscribeState===le.Subscribing}get isVideoSmallSubscribed(){return this.videoSmallInfo.subscribeState===le.Subscribed}get isVideoSmallSubscribing(){return this.videoSmallInfo.subscribeState===le.Subscribing}get isScreenSubscribed(){return this.screenInfo.subscribeState===le.Subscribed}get isScreenSubscribing(){return this.screenInfo.subscribeState===le.Subscribing}get isDataSubscribed(){return this.dataInfo.subscribeState===le.Subscribed}get isDataSubscribing(){return this.dataInfo.subscribeState===le.Subscribing}get audioCodec(){return this.audioInfo.codec}get videoCodec(){return this.hasVideoLarge?this.videoLargeInfo.codec:this.hasVideoSmall?this.videoSmallInfo.codec:this.hasScreen?this.screenInfo.codec:ht.UNKNOWN}get audioTrackInfo(){return this.hasAudio?$t.AliRtcAudioTrackMic:$t.AliRtcAudioTrackNo}get videoTrackInfo(){return this.hasVideo&&this.hasScreen?ce.AliRtcVideoTrackBoth:this.hasVideo?ce.AliRtcVideoTrackCamera:this.hasScreen?ce.AliRtcVideoTrackScreen:ce.AliRtcVideoTrackNo}updateTracks(e){let t="",i="",r="",n="",c="";return e?(e.forEach(o=>{var p;let l=ht.UNKNOWN;const d=((p=o==null?void 0:o.attr)==null?void 0:p.reason)==="reconnect";if(o.userdata){const{codec:u}=JSON.parse(o.userdata);u&&(l=u)}var h;(h=o.msid)===M.Audio||h===Tr.Audio?(t=o.ssrc,this.audioInfo.msid=o.msid,this.audioInfo.codec=l,(d||this.audioInfo.ssrc!==t)&&(this.audioInfo.subscribeState=le.NotSubscribe)):(u=>u===M.VideoSmall)(o.msid)?(r=o.ssrc,this.videoSmallInfo.msid=o.msid,this.videoSmallInfo.codec=l,(d||this.videoSmallInfo.ssrc!==r)&&(this.videoSmallInfo.subscribeState=le.NotSubscribe)):(u=>u===M.VideoLarge||u===Tr.VideoLarge)(o.msid)?(i=o.ssrc,this.videoLargeInfo.msid=o.msid,this.videoLargeInfo.codec=l,(d||this.videoLargeInfo.ssrc!==i)&&(this.videoLargeInfo.subscribeState=le.NotSubscribe)):(u=>u===M.Screen)(o.msid)?(n=o.ssrc,this.screenInfo.msid=o.msid,this.screenInfo.codec=l,(d||this.screenInfo.ssrc!==n)&&(this.screenInfo.subscribeState=le.NotSubscribe)):(u=>u===M.Data)(o.msid)&&(c=o.ssrc,this.dataInfo.msid=o.msid,this.dataInfo.codec=l,(d||this.dataInfo.ssrc!==c)&&(this.dataInfo.subscribeState=le.NotSubscribe))}),this.updateRemoteTrackSsrc(t,i,r,n,c)):this.updateRemoteTrackSsrc(t,i,r,n,c),{}}updateRemoteTrackSsrc(e,t,i,r,n){this.audioInfo.ssrc=e,this.videoSmallInfo.ssrc=i,this.videoLargeInfo.ssrc=t,this.screenInfo.ssrc=r,this.dataInfo.ssrc=n}markRemoteTrackSubscribing(e){return e.video&&(e.vMsid===this.videoSmallInfo.msid&&(this.videoSmallInfo.subscribeState=le.Subscribing),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=le.Subscribing)),e.screen&&(this.screenInfo.subscribeState=le.Subscribing),e.audio&&(this.audioInfo.subscribeState=le.Subscribing),e.data&&(this.dataInfo.subscribeState=le.Subscribing),{videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo}}updateRemoteTrackSubState(e){return e.video!==void 0&&(e.vMsid!==this.videoSmallInfo.msid&&e.vMsid||(this.videoSmallInfo.subscribeState=e.video?le.Subscribed:le.NotSubscribe),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=e.video?le.Subscribed:le.NotSubscribe)),e.screen!==void 0&&(this.screenInfo.subscribeState=e.screen?le.Subscribed:le.NotSubscribe),e.audio!==void 0&&(this.audioInfo.subscribeState=e.audio?le.Subscribed:le.NotSubscribe),e.data!==void 0&&(this.dataInfo.subscribeState=e.data?le.Subscribed:le.NotSubscribe),{audioInfo:this.audioInfo,videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo,screenInfo:this.screenInfo,dataInfo:this.dataInfo}}updateRemoteUserDeviceStatus(e){let t=Ya.parseStatus(e);const{audioDisable:i,videoDisable:r,screenDisable:n}=t;return this.userStatus?(this.userStatus.audioDisable!=i&&(this.userStatus.audioDisable=i,this.emit(Qe.Remote,i?Ce.MuteAudio:Ce.UnmuteAudio)),this.userStatus.videoDisable!=r&&(this.userStatus.videoDisable=r,this.emit(Qe.Remote,r?Ce.MuteVideo:Ce.UnmuteVideo)),this.userStatus.screenDisable!=n&&(this.userStatus.screenDisable=n,this.emit(Qe.Remote,n?Ce.MuteScreen:Ce.UnmuteScreen))):(this.userStatus=t,this.emit(Qe.Remote,i?Ce.MuteAudio:Ce.UnmuteAudio),this.emit(Qe.Remote,r?Ce.MuteVideo:Ce.UnmuteVideo),this.emit(Qe.Remote,n?Ce.MuteScreen:Ce.UnmuteScreen)),!1}}g(Dr,"logName","RemoteStreamInfo"),((s,a,e,t)=>{for(var i,r=t>1?void 0:t?Xo(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);t&&r&&qo(a,e,r)})([C()],Dr.prototype,"updateRemoteTrackSubState",1);class an{constructor(a){g(this,"remoteUser");this.remoteUser=a}get userId(){return this.remoteUser.userId}get displayName(){return this.remoteUser.displayname}get isMuteAudioPlaying(){return this.remoteUser.getAudioMuted()}get hasAudio(){return this.remoteUser.hasAudioTrack}get hasCamera(){return this.remoteUser.hasVideoTrack}get hasCameraLarge(){return this.remoteUser.hasVideoLargeTrack}get hasCameraSmall(){return this.remoteUser.hasVideoSmallTrack}get hasScreenShare(){return this.remoteUser.hasScreenTrack}get isAudioSubscribing(){return this.remoteUser.isAudioSubscribing}get isVideoSubscribing(){return this.remoteUser.isVideoSubscribing}get isVideoLargeSubscribing(){return this.remoteUser.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.remoteUser.isVideoSmallSubscribing}get isScreenSubscribing(){return this.remoteUser.isScreenSubscribing}get audioElement(){return this.remoteUser.getAudioElement()}}var Yo=Object.defineProperty,Qo=Object.getOwnPropertyDescriptor,je=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Qo(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&Yo(a,e,r),r};class ni extends se{constructor(){super();g(this,"state");g(this,"time");g(this,"_enabled");this.state=ae.AliRtcStateSubscribeIdle,this.time=Date.now(),this._enabled=!0}setState(e){if(this.state===e)return;const t=this.state,i=this.time;this.state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-i)/1e3))}get currentState(){return this.state}getEnabled(){return this._enabled}setEnabled(e){this._enabled=e}}const He=(Ge=class extends Xa{constructor(e){var u;const{userId:t,displayName:i,rtsManager:r,usersViewMap:n,slsReporter:c,signalingManager:o,localUser:l,audioVolumeIndicationInterval:d,playoutVolume:h,parameter:p}=e;super(t,i,r,d);g(this,"remoteCallId","");g(this,"remoteUserInfo");g(this,"localUser");g(this,"lastPubId","");g(this,"stream");g(this,"screenStream");g(this,"viewMap");g(this,"audioTrack");g(this,"audioElement");g(this,"subscribed",!1);g(this,"mediaStream");g(this,"secondaryMediaStream");g(this,"prevSubConfig");g(this,"signalingManager");g(this,"slsReporter");g(this,"wantSubAudio",!1);g(this,"wantSubVideo",!1);g(this,"wantSubScreen",!1);g(this,"defaultVideoStreamType",Ke.AliRtcVideoStreamTypeHigh);g(this,"audioMuted",!1);g(this,"playoutVolume",1);g(this,"playoutGainNode");g(this,"audioSubState");g(this,"videoSubState");g(this,"videoLargeSubState",new ni);g(this,"videoSmallSubState",new ni);g(this,"screenSubState");g(this,"dataSubState");g(this,"dc");g(this,"dcMsgWaitingPieces",[]);g(this,"streamInfo");g(this,"_streamUrl","");g(this,"parameter",{});g(this,"monitorTimerId");g(this,"monitorDataCache",{});g(this,"traceId","");g(this,"handleAudioContextSuspended",e=>{e.target.state==="suspended"&&this.emit("remoteAudioPlayError",this.uid,"AudioContext suspended")});g(this,"onDataChannelMessage",e=>{var r;const t=zi.parse(e.slice(4));let i;if(t.body){if(!t.isFin)return t.header.frameType===1&&(this.dcMsgWaitingPieces=[]),void this.dcMsgWaitingPieces.push(t.body);if(this.dcMsgWaitingPieces.length>0){const n=this.dcMsgWaitingPieces.reduce((c,o)=>c+o.byteLength,t.body.byteLength);try{const c=new ArrayBuffer(n);let o=0;for(let l=0;l<this.dcMsgWaitingPieces.length;l++){const d=this.dcMsgWaitingPieces[l];new Uint8Array(c,o,d.byteLength).set(new Uint8Array(d)),o+=d.byteLength}new Uint8Array(c,o,t.body.byteLength).set(new Uint8Array(t.body)),i=Vt.parse(c)}catch(c){}this.dcMsgWaitingPieces=[],i||(i=Vt.parse(t.body))}else i=Vt.parse(t.body);i||N.event(`[${Ge.logName}]`,`parse data channel message fail, piece count: ${this.dcMsgWaitingPieces.length+1}`)}i&&(N.event(`[${Ge.logName}]`,`receive dc message, length(${(r=i.data)==null?void 0:r.byteLength})`),this.emit("remoteDataChannelMessage",this.uid,i))});g(this,"onDataChannelError",e=>{this.emit("occurError",V.fromError(e,U.ERR_SDK_SUBSCRIBE_DATA_ERROR))});g(this,"dataChannelConnected",e=>{e&&(this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"),this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dc.on("message",this.onDataChannelMessage),this.dc.on("error",this.onDataChannelError))});g(this,"handleAudioPaused",()=>{this.emit("remoteAudioPlayError",this.uid,"paused")});this.streamInfo=new Dr,this.remoteUserInfo=new an(this),this.parameter=p,this.streamInfo.on(Qe.Remote,f=>{this.emit(Qe.Remote,f,this.userId)}),this.signalingManager=o,this.viewMap=(u=n[t])!=null?u:{cameraViews:[],screenViews:[]},n[t]=this.viewMap,this.slsReporter=c,this.localUser=l,this.audioSubState=new ni,this.audioSubState.on("change",(f,m,b)=>{this.emit("audioSubscribeStateChanged",this.uid,f,m,b)}),this.videoSubState=new ni,this.videoSubState.on("change",(f,m,b)=>{this.emit("videoSubscribeStateChanged",this.uid,f,m,b)}),this.screenSubState=new ni,this.screenSubState.on("change",(f,m,b)=>{this.emit("screenSubscribeStateChanged",this.uid,f,m,b)}),this.dataSubState=new ni,this.dataSubState.on("change",(f,m,b)=>{this.emit("dataSubscribeStateChanged",this.uid,f,m,b)}),this.playoutVolume=h}get streamUrl(){return this._streamUrl}set streamUrl(e){this._streamUrl=e,this.rtsManager.updateAuth(e)}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e}setRemoteDefaultVideoStreamType(e){e!==this.defaultVideoStreamType&&(this.defaultVideoStreamType=e,this.updateSubscribe(be.User))}setAudioMuted(e){this.audioMuted=e,this.toggleAudio(!e)}getAudioElement(){return this.audioElement}setPlayoutVolume(e){if(this.playoutVolume=e,this.audioElement)if(this.parameter.enableAudioContextPlayoutVolume)if(this.playoutGainNode)this.playoutGainNode.gain.value=e;else{const t=this.audioElement.srcObject;if(t){const i=Gt.getInstance();i.addEventListener("statechange",this.handleAudioContextSuspended);const r=i.createMediaStreamSource(t);this.audioElement.muted=!0,this.playoutGainNode=i.createGain(),r.connect(this.playoutGainNode),this.playoutGainNode.gain.value=e,this.playoutGainNode.connect(i.destination)}}else this.audioElement.volume=e}getAudioMuted(){return this.audioMuted}get hasAudioTrack(){return this.streamInfo.hasAudio}get hasVideoTrack(){return this.streamInfo.hasVideo}get hasVideoLargeTrack(){return this.streamInfo.hasVideoLarge}get hasVideoSmallTrack(){return this.streamInfo.hasVideoSmall}get hasScreenTrack(){return this.streamInfo.hasScreen}get isAudioSubscribing(){return this.streamInfo.isAudioSubscribed||this.streamInfo.isAudioSubscribing}get isVideoSubscribing(){return this.streamInfo.isVideoSubscribed||this.streamInfo.isVideoSubscribing}get isVideoLargeSubscribing(){return this.streamInfo.isVideoLargeSubscribed||this.streamInfo.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing}get isScreenSubscribing(){return this.streamInfo.isScreenSubscribed||this.streamInfo.isScreenSubscribing}get isDataSubscribing(){return this.streamInfo.isDataSubscribed||this.streamInfo.isDataSubscribing}get audioEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.audioTrack)!=null&&t.enabled)}get videoEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get screenEnabled(){var e,t;return!!((t=(e=this.screenStream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get getAudioTrack(){return this.audioTrack}get getCameraStream(){return this.stream}get getScreenStream(){return this.screenStream}setViewConfig(e,t){if(t!==ce.AliRtcVideoTrackScreen&&t!==ce.AliRtcVideoTrackCamera)throw new V(U.ERR_INVALID_ARGUMENTS,"track is not AliRtcVideoTrackScreen or AliRtcVideoTrackCamera");e?cr(e).forEach(i=>{i.setAttribute("playsinline",""),X.AliRTS.BrowserUtil.isMicroMessenger&&(i.setAttribute("x5-video-player-type","h5-page"),i.setAttribute("x5-playsinline",""),X.AliRTS.SystenUtil.isAndroid||X.AliRTS.SystenUtil.isIos&&i.setAttribute("x-webkit-airplay","allow")),t===ce.AliRtcVideoTrackScreen?this.viewMap.screenViews.push(i):this.viewMap.cameraViews.push(i),this.play(i,t===ce.AliRtcVideoTrackScreen)}):(this.stopPlayAll(t===ce.AliRtcVideoTrackScreen),t===ce.AliRtcVideoTrackScreen?this.viewMap.screenViews=[]:this.viewMap.cameraViews=[])}clear(e=!0){return I(this,null,function*(){Zr(Ge.prototype,this,"clear").call(this),this.stopPlayAudio(),this.stopStreamMonitor(),e&&this.subscribeDeleteAllTracks(this.streamUrl).catch(t=>{N.event(`[${Ge.logName}]`,`stopSubscribeAllTracks error: ${t.message||t}`)}),this.clearStream(),this.clearScreenStream(),this.playoutGainNode&&(this.playoutGainNode.disconnect(),this.playoutGainNode=void 0,Gt.getInstance().removeEventListener("statechange",this.handleAudioContextSuspended)),this.streamInfo.removeAllListeners(Qe.Remote)})}updateRemoteUserDeviceStatus(e){this.streamInfo.updateRemoteUserDeviceStatus(e)}updateRemoteTracks(e,t,i,r){return I(this,null,function*(){return this.remoteCallId=e,this.streamUrl&&this.streamInfo.hasTrack||(this.streamUrl=t),this.streamInfo.updateTracks(r)})}subscribe(r,n){return I(this,arguments,function*(e,t,i=Date.now()){var u,f;let c=e;if(!c){const{hasAudio:m,hasVideo:b,hasScreen:S,hasData:v}=(u=this.streamInfo)!=null?u:{};c={audio:this.wantSubAudio&&m,video:this.wantSubVideo&&b,screen:this.wantSubScreen&&S,data:((f=this.parameter.data)==null?void 0:f.enableSubDataChannel)&&v}}this.streamInfo.markRemoteTrackSubscribing(c);const{screen:o,audio:l,video:d,vMsid:h}=c,p=[];(d||l)&&p.push({audio:l,video:d,vMsid:h}),o&&p.push({screen:o}),(p.length!==0||e!=null&&e.data)&&(yield Promise.all(p.map(m=>this.subscribeProxy(m,t||be.User,i))),e!=null&&e.data&&this.subscribeDataChannel())})}subscribeProxy(e,t,i){return I(this,null,function*(){var c,o;let r=new Date().getTime(),n="";try{e.audio&&this.audioSubState.setState(ae.AliRtcStateSubscribing),e.video&&(this.videoSubState.currentState!==ae.AliRtcStateSubscribeIdle&&this.videoSubState.currentState!==ae.AliRtcStateNoSubscribe||this.videoSubState.setState(ae.AliRtcStateSubscribing)),e.screen&&this.screenSubState.setState(ae.AliRtcStateSubscribing);const l=yield this.rtsManager.subscribe({remoteUser:this,options:e},t,((c=this.localUser)==null?void 0:c.callId)||"",this.callId,i);this.streamInfo.updateRemoteTrackSubState(e),n=l.traceId||"";const{stream:d}=l;if(n&&(this.traceId=n),e.audio){const u=d.audioTrack;u&&(this.audioTrack=u,(o=d.mediaStream)==null||o.removeTrack(u),this.playAudio(),this.audioVolumeIndicationInterval&&this.audioLevelMonitor.start(u,this.audioVolumeIndicationInterval)),this.audioSubState.getEnabled()||this.toggleAudio(!1),this.audioSubState.setState(ae.AliRtcStateSubscribed)}e.video&&(this.updateStream(d,this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing),this.videoSubState.getEnabled()||this.toggleVideo(!1),this.videoSubState.setState(ae.AliRtcStateSubscribed),e.vMsid===M.VideoSmall?this.videoSmallSubState.setState(ae.AliRtcStateSubscribed):this.videoLargeSubState.setState(ae.AliRtcStateSubscribed)),e.screen&&(this.updateScreenStream(d),this.videoSubState.getEnabled()||this.toggleScreen(!1),this.screenSubState.setState(ae.AliRtcStateSubscribed));const h=new Date().getTime()-r,p=Date.now();setTimeout(()=>{this.slsReporter.reportSubscribe(this.callId,this.remoteCallId,!!e.video&&e.vMsid===M.VideoLarge,!!e.video&&e.vMsid===M.VideoSmall,!!e.screen,!!e.audio,0,"",h,{pctid:this.rtsManager.pcTraceId,subtid:this.traceId,ajsub:t===be.Join?1:0,url:this.streamUrl,est:r},p)},6e3),this.startStreamMonitor(),l.isHTTP&&l.statsCheckPromise&&(yield Promise.race([l.statsCheckPromise,xt(1500)]))}catch(l){const d=new Date().getTime()-r;e.audio&&this.audioSubState.setState(ae.AliRtcStateNoSubscribe),e.video&&this.videoSubState.setState(ae.AliRtcStateNoSubscribe),e.screen&&this.screenSubState.setState(ae.AliRtcStateNoSubscribe),l&&(l.message=`user(${this.uid}) subscribe error, ${(l==null?void 0:l.message)||""}`);let h=U.ERR_INNER;e.audio&&(h=U.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED),e.video&&(h=e.vMsid===M.VideoSmall?U.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED:U.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED),e.screen&&(h=U.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED),this.slsReporter.reportSubscribe(this.callId,this.remoteCallId,!!e.video&&e.vMsid===M.VideoLarge,!!e.video&&e.vMsid===M.VideoSmall,!!e.screen,!!e.audio,h,"",d,{pctid:this.rtsManager.pcTraceId,subtid:"",ajsub:t===be.Join?1:0,url:this.streamUrl,est:r});const p=V.fromError(l,h);throw this.emit("remoteSubscribeError",p),p}})}subscribeDeleteTracks(e){return I(this,null,function*(){const{audio:t,video:i,screen:r,data:n,vMsid:c}=e,o=[];(t||i||n)&&o.push({audio:t,video:i,vMsid:c}),r&&o.push({screen:r}),o.length!==0&&(yield Promise.all(o.map(l=>this.subscribeDeleteProxy(l))),e.data&&this.subscribeDeleteDataChannel())})}subscribeDeleteProxy(e){return I(this,null,function*(){try{const t=yield this.rtsManager.subscribeDelete({remoteUser:this,options:e}),{stream:i}=t!=null?t:{},r={};e.audio===!0&&(r.audio=!1,this.audioSubState.setState(ae.AliRtcStateNoSubscribe)),e.video===!0&&(r.video=!1,e.vMsid===M.VideoSmall?(this.videoSmallSubState.setState(ae.AliRtcStateNoSubscribe),this.videoLargeSubState.currentState!==ae.AliRtcStateNoSubscribe&&this.videoLargeSubState.currentState!==ae.AliRtcStateSubscribeIdle||this.videoSubState.setState(ae.AliRtcStateNoSubscribe)):(this.videoLargeSubState.setState(ae.AliRtcStateNoSubscribe),this.videoSmallSubState.currentState!==ae.AliRtcStateNoSubscribe&&this.videoSmallSubState.currentState!==ae.AliRtcStateSubscribeIdle||this.videoSubState.setState(ae.AliRtcStateNoSubscribe))),e.screen===!0&&(r.screen=!1,this.screenSubState.setState(ae.AliRtcStateNoSubscribe));const{callId:n,remoteCallId:c}=this,o={callid:n,remoteCallid:c,remoteStream:i};return e.audio&&(this.audioLevelMonitor.stop(),this.stopPlayAudio(),this.audioTrack=void 0),this.streamInfo.updateRemoteTrackSubState({audio:e.audio!==!0&&void 0,video:e.video!==!0&&void 0,screen:e.screen!==!0&&void 0,vMsid:e.vMsid}),o}catch(t){throw V.fromError(t,U.ERR_INNER,"subscribe delete failed")}})}restore(){this.callId="",this.clearStream(),this.clearScreenStream(),this.audioTrack=void 0,this.streamInfo.updateRemoteTrackSubState({audio:!1,video:!1,screen:!1,data:!1}),this.audioElement&&this.audioElement.removeEventListener("pause",this.handleAudioPaused)}resumeAudio(){return I(this,null,function*(){const e=Gt.getInstance();return e.state!=="running"&&e.resume(),this.audioElement?this.audioElement.play():this.playAudio()})}resumeVideo(e){return I(this,null,function*(){return e&&e!==ce.AliRtcVideoTrackCamera&&e!==ce.AliRtcVideoTrackBoth?e&&e!==ce.AliRtcVideoTrackScreen&&e!==ce.AliRtcVideoTrackBoth?void 0:this.playAll(!0):this.playAll()})}resumePlay(){this.playAudio(),this.playAll(),this.playAll(!0)}stopSubscribe(e){return I(this,null,function*(){let t=new Date().getTime();try{e?yield this.subscribeDeleteTracks(e):yield this.subscribeDeleteAllTracks(this.streamUrl),this.slsReporter.reportUnsubscribe(this.callId,this.remoteCallId,new Date().getTime()-t,0,"")}catch(i){throw this.slsReporter.reportUnsubscribe(this.callId,this.remoteCallId,new Date().getTime()-t,0,""),i}})}subscribeDeleteAllTracks(e){return I(this,null,function*(){var r,n,c,o;const{callId:t,remoteCallId:i}=this;if((this.isAudioSubscribing||this.isVideoSubscribing||this.isScreenSubscribing||this.dc)&&e)try{yield this.subscribeDeleteTracks({audio:this.isAudioSubscribing,video:this.isVideoSubscribing,screen:this.isScreenSubscribing,data:!!this.dc}),this.restore();const l={callid:t,remoteCallid:i,remoteStream:this.stream};return this.callId="",l}catch(l){if(((o=(c=(n=(r=l==null?void 0:l.extraInfo)==null?void 0:r.parsedData)==null?void 0:n.streams)==null?void 0:c[0])==null?void 0:o.res_code)!==404)throw V.fromError(l,U.ERR_INNER,"subscribe stop failed")}})}updateStream(e,t=!1){return I(this,null,function*(){this.stream&&this.stream.videoTrack&&e.mediaStream&&t&&(yield new Promise(i=>{let r,n;if(e.mediaStream){n=document.createElement("video");const c=()=>{N.event(`[${Ge.logName}]`,`uid: ${this.userId} new mediaStream canplay`),n&&n.removeEventListener("canplaythrough",c,!1),n=void 0,clearTimeout(r),i(!0)};n.addEventListener("canplaythrough",c,!1),(n._playPromise||Promise.resolve()).then(()=>{n&&e.mediaStream&&(n.srcObject=e.mediaStream)})}else i(!0);r=window.setTimeout(()=>{N.event(`[${Ge.logName}]`,`uid: ${this.userId} new mediaStream timeout`),n=void 0,i(!0)},3e3)}),this.updateSubscribe(be.User)),this.stream=e,this.playAll(!1,t),!this.subscribed&&e&&(this.subscribed=!0),e.hasAudio&&this.isAudioSubscribing&&e.enableAudio(),e.hasVideo&&this.isVideoSubscribing&&e.enableVideo()})}updateScreenStream(e){this.screenStream=e,this.playAll(!0),!this.subscribed&&e&&(this.subscribed=!0),e.hasVideo&&this.isScreenSubscribing&&e.enableVideo()}clearStream(){var e;(e=this.stream)==null||e.stop(),this.stream=void 0}clearScreenStream(){var e;(e=this.screenStream)==null||e.stop(),this.screenStream=void 0}subscribeDataChannel(){if(this.dc)try{this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc=void 0}catch(e){}(this.streamInfo.hasAudio||this.streamInfo.hasVideo||this.streamInfo.hasScreen)&&(this.dataSubState.setState(ae.AliRtcStateSubscribing),this.rtsManager.subscribeAddDataChannel(this.streamUrl).then(e=>{if(e)return this.dataChannelConnected(e),this.dataSubState.setState(ae.AliRtcStateSubscribed),void this.streamInfo.updateRemoteTrackSubState({data:!0});throw new Error("no dc founded")}).catch(e=>{const t=V.fromError(e,U.ERR_INNER,"subscribe data failed");this.emit("remoteSubscribeError",t),this.dataSubState.setState(ae.AliRtcStateNoSubscribe)}))}subscribeDeleteDataChannel(){if(this.dc){try{this.rtsManager.subscribeDeleteDatachannel(this.streamUrl,this.dc)}catch(e){}this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dataSubState.setState(ae.AliRtcStateNoSubscribe),this.dc=void 0,this.streamInfo.updateRemoteTrackSubState({data:!1})}}getRetryOptions(){var i,r;const e={};this.wantSubAudio&&this.streamInfo.hasAudio&&(e.audio=!0,e.aMsid=((i=this.streamInfo.getAudioInfo())==null?void 0:i.msid)||M.Audio),this.wantSubVideo&&this.streamInfo.hasVideo&&(this.defaultVideoStreamType===Ke.AliRtcVideoStreamTypeLow&&this.streamInfo.hasVideoSmall?(e.video=!0,e.vMsid=M.VideoSmall):this.streamInfo.hasVideoLarge&&(e.video=!0,e.vMsid=((r=this.streamInfo.getVideoLargeInfo())==null?void 0:r.msid)||M.VideoLarge)),this.wantSubScreen&&this.streamInfo.hasScreen&&(e.screen=!0);let t={};if(e.audio||e.video)t={audio:e.audio,video:e.video},this.streamInfo.updateRemoteTrackSubState({screen:!1,data:!1});else{if(!e.screen)return;t={screen:e.screen},this.streamInfo.updateRemoteTrackSubState({data:!1})}return{remoteUser:this,options:t}}updateSubscribe(e){var n,c,o,l,d,h;const t=Date.now(),i={},r={};return this.wantSubAudio&&!this.isAudioSubscribing&&this.streamInfo.hasAudio&&this.audioSubState.currentState!==ae.AliRtcStateReconnecting?(i.audio=!0,i.aMsid=((n=this.streamInfo.getAudioInfo())==null?void 0:n.msid)||M.Audio):this.wantSubAudio&&this.streamInfo.hasAudio||!this.isAudioSubscribing||(r.audio=!0,r.aMsid=((c=this.streamInfo.getAudioInfo())==null?void 0:c.msid)||M.Audio),this.wantSubVideo&&this.streamInfo.hasVideo?(this.defaultVideoStreamType===Ke.AliRtcVideoStreamTypeLow&&!this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall&&this.videoSmallSubState.currentState!==ae.AliRtcStateReconnecting?(i.video=!0,i.vMsid=M.VideoSmall):this.isVideoLargeSubscribing||!this.streamInfo.hasVideoLarge||this.defaultVideoStreamType===Ke.AliRtcVideoStreamTypeLow&&this.isVideoSmallSubscribing||this.videoLargeSubState.currentState===ae.AliRtcStateReconnecting||(i.video=!0,i.vMsid=((o=this.streamInfo.getVideoLargeInfo())==null?void 0:o.msid)||M.VideoLarge),this.defaultVideoStreamType===Ke.AliRtcVideoStreamTypeLow&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall?(r.video=!0,r.vMsid=M.VideoLarge):this.defaultVideoStreamType===Ke.AliRtcVideoStreamTypeHigh&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&(r.video=!0,r.vMsid=M.VideoSmall)):this.wantSubVideo&&this.streamInfo.hasVideo||!this.isVideoSubscribing||(r.video=!0,r.vMsid=this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?M.VideoSmall:((l=this.streamInfo.getVideoLargeInfo())==null?void 0:l.msid)||M.VideoLarge),this.wantSubScreen&&!this.isScreenSubscribing&&this.streamInfo.hasScreen&&this.screenSubState.currentState!==ae.AliRtcStateReconnecting?i.screen=!0:this.wantSubScreen&&this.streamInfo.hasScreen||!this.isScreenSubscribing||(r.screen=!0),(d=this.parameter.data)!=null&&d.enableSubDataChannel&&!this.isDataSubscribing&&this.streamInfo.hasData&&this.dataSubState.currentState!==ae.AliRtcStateReconnecting?i.data=!0:(h=this.parameter.data)!=null&&h.enableSubDataChannel&&this.streamInfo.hasData||!this.isDataSubscribing||(r.data=!0),this.dc&&i.data&&this.subscribeDeleteDataChannel(),(i.audio||i.video||i.screen||i.data)&&(this.createCallId(),this.subscribe(i,e,t)),(r.audio||r.video||r.screen)&&this.subscribeDeleteTracks(r),{addOption:i,deleteOption:r}}handleAutoPlayFailed(){N.event(`[${Ge.logName}]`,"auto play failed"),this.emit("remoteAudioAutoPlayFail",this.uid);const e=()=>{this.resumeAudio().then(()=>{document.removeEventListener("click",e,!1),document.removeEventListener("touchstart",e,!1)})};document.addEventListener("click",e,!1),document.addEventListener("touchstart",e,!1)}handleVideoPlayFailded(e,t){this.emit("remoteVideoAutoPlayFail",this.uid,t);const i=()=>{var n;const r=(n=t===ce.AliRtcVideoTrackScreen?this.screenStream:this.stream)==null?void 0:n.mediaStream;e.srcObject===r&&this.play(e,t===ce.AliRtcVideoTrackScreen),document.removeEventListener("click",i,!1),document.removeEventListener("touchstart",i,!1)};document.addEventListener("click",i,!1),document.addEventListener("touchstart",i,!1)}playAudio(){return I(this,null,function*(){var e,t;if(this.audioTrack){if(this.toggleAudio(!this.audioMuted),this.audioElement||(N.event(`[${Ge.logName}]`,this.userId,"create audio element"),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("autoplay","autoplay"),this.audioElement.addEventListener("pause",this.handleAudioPaused),this.setPlayoutVolume(this.playoutVolume)),((t=(e=this.audioElement.srcObject)==null?void 0:e.getAudioTracks())==null?void 0:t[0])!==this.audioTrack){let i=this.audioElement.srcObject;i?i.getAudioTracks().forEach(r=>{i.removeTrack(r)}):(i=new MediaStream,this.audioElement.srcObject=i),i.addTrack(this.audioTrack)}if(X.AliRTS.SystenUtil.isIos&&parseInt(X.AliRTS.SystenUtil.systemVersion)<=13){N.event(`[${Ge.logName}]`,"play audio for iOS 13-");const i=this.audioElement;i.setAttribute("autoplay","");const r=()=>{i.removeEventListener("playing",r),i.pause(),i.play().catch(()=>{this.handleAutoPlayFailed()})};this.audioElement.addEventListener("playing",r)}else(()=>{var i;N.event(`[${Ge.logName}]`,"try play audio"),(i=this.audioElement)==null||i.play().then(()=>{N.event(`[${Ge.logName}]`,"play audio success")}).catch(()=>{this.handleAutoPlayFailed()})})()}else N.event(`[${Ge.logName}]`,this.userId,"audio track is null")})}stopPlayAudio(){this.audioElement&&(this.audioElement.pause(),this.audioElement.removeEventListener("pause",this.handleAudioPaused))}playAll(e=!1,t=!1){e?(this.viewMap.screenViews||[]).forEach(i=>{this.play(i,e,t)}):(this.viewMap.cameraViews||[]).forEach(i=>{this.play(i,e,t)})}play(e,t=!1,i=!1){const r=t?this.screenStream:this.stream;e&&r&&r.mediaStream&&tn(e,r.mediaStream,i).catch(n=>{n.code!==20&&n.name!=="AbortError"&&this.handleVideoPlayFailded(e,t?ce.AliRtcVideoTrackScreen:ce.AliRtcVideoTrackCamera)})}stopPlayAll(e=!1){e?this.viewMap.screenViews.forEach(t=>{wt(t)}):this.viewMap.cameraViews.forEach(t=>{wt(t)})}toggleAudio(e=!0){this.audioSubState.setEnabled(e),this.audioElement&&(this.audioElement.muted=!e)}toggleVideo(e=!0){this.videoSubState.setEnabled(e),this.stream&&(e?this.stream.enableVideo():this.stream.disableVideo())}toggleScreen(e=!0){this.screenSubState.setEnabled(e),this.screenStream&&(e?this.screenStream.enableVideo():this.screenStream.disableVideo())}getStats(){return I(this,null,function*(){var i,r,n;const e=[];if(this.isAudioSubscribing){const c=yield this.rtsManager.getSubscribeAudioStats(this.streamUrl);c&&e.push({uid:this.uid,track:$t.AliRtcAudioTrackMic,stats:c})}const t=[];if(this.streamInfo.isVideoLargeSubscribed){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((i=this.streamInfo.getVideoLargeInfo())==null?void 0:i.msid)||M.VideoLarge);c&&t.push({uid:this.uid,track:ce.AliRtcVideoTrackCamera,streamType:Ke.AliRtcVideoStreamTypeHigh,stats:c})}if(this.streamInfo.isVideoSmallSubscribed){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((r=this.streamInfo.getVideoSmallInfo())==null?void 0:r.msid)||M.VideoSmall);c&&t.push({uid:this.uid,track:ce.AliRtcVideoTrackCamera,streamType:Ke.AliRtcVideoStreamTypeLow,stats:c})}if(this.isScreenSubscribing){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((n=this.streamInfo.getScreenInfo())==null?void 0:n.msid)||M.Screen);c&&t.push({uid:this.uid,track:ce.AliRtcVideoTrackScreen,stats:c})}return{audio:e,video:t}})}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.audioTrack&&this.audioLevelMonitor.start(this.audioTrack,e),this.audioVolumeIndicationInterval=e)}reportSubscribeMonitor(e){e&&(this.slsReporter.reportSubscribeMonitor(this.callId,this.remoteCallId,this.traceId,e,this.monitorDataCache[e]),this.monitorDataCache[e]=[])}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>I(this,null,function*(){try{if(this.streamInfo.subscribingInfos.length===0)return void this.stopStreamMonitor();let e=Object.keys(this.monitorDataCache).filter(t=>{var i;return((i=this.monitorDataCache[t])==null?void 0:i.length)>0});this.streamInfo.subscribingInfos.forEach(t=>{const i=t.msid;if(!i)return;let r;e.includes(i)&&(e=e.filter(c=>c!==i));const n=i===M.Audio;r=n?this.rtsManager.getSubscribeAudioStats(this.streamUrl):this.rtsManager.getSubscribeVideoStats(this.streamUrl,i),r.then(c=>{var h;if(!c.timestamp)return;this.monitorDataCache[i]||(this.monitorDataCache[i]=[]);const o=this.monitorDataCache[i];let l;if((o==null?void 0:o.length)>0){const p=o[o.length-1]||{},d=p,{_last:u}=d;l=Mt(d,["_last"])}(o==null?void 0:o.length)>=30&&this.reportSubscribeMonitor(i),c._last=l,c._codec=t.codec,n&&(c._source=(h=this.localUser)==null?void 0:h.getMediaStats(c.playoutId)),this.monitorDataCache[i].push(c)})}),e.forEach(t=>{this.reportSubscribeMonitor(t)})}catch(e){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportSubscribeMonitor(e)})}markReconnect(e){const t=[];!this.isAudioSubscribing||e&&!e.includes(this.streamInfo.getAudioInfo().msid)||t.push(this.audioSubState),this.isVideoSubscribing&&(!e||e.includes(this.streamInfo.getVideoLargeInfo().msid)||e.includes(this.streamInfo.getVideoSmallInfo().msid))&&t.push(this.videoSubState),!this.isScreenSubscribing||e&&!e.includes(this.streamInfo.getScreenInfo().msid)||t.push(this.screenSubState),!this.isDataSubscribing||e&&!e.includes(M.Data)||t.push(this.dataSubState),t.forEach(i=>{i.setState(ae.AliRtcStateReconnecting)})}markReconnected(e){const t=[],i=this.streamInfo.getAudioInfo().msid||M.Audio;if(this.isAudioSubscribing&&(!e||e.includes(i))){t.push(this.audioSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,aMsid:i});o&&o.audioTrack&&(this.audioTrack=o.audioTrack,this.audioVolumeIndicationInterval>0&&(this.audioLevelMonitor.stop(),this.audioLevelMonitor.start(this.audioTrack,this.audioVolumeIndicationInterval)),this.playAudio())}const r=this.streamInfo.getVideoLargeInfo().msid||M.VideoLarge,n=this.streamInfo.getVideoSmallInfo().msid||M.VideoSmall;if(this.isVideoSubscribing&&(!e||e.includes(r)||e.includes(n))){t.push(this.videoSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?n:r});o&&o.mediaStream&&(this.stream=o,this.playAll(!1))}const c=this.streamInfo.getScreenInfo().msid||M.Screen;if(this.isScreenSubscribing&&(!e||e.includes(c))){t.push(this.screenSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:c});o&&o.mediaStream&&(this.screenStream=o,this.playAll(!0))}if(this.isDataSubscribing&&(!e||e.includes(this.streamInfo.getDataInfo().msid))){t.push(this.dataSubState);const o=this.rtsManager.getDatachannelByMsid({url:this.streamUrl,msid:this.streamInfo.getDataInfo().msid||M.Data});this.dataChannelConnected(o)}t.forEach(o=>{o.setState(ae.AliRtcStateSubscribed)}),e||this.updateSubscribe(be.Reconnect)}},g(Ge,"logName","RemoteUser"),Ge);je([C()],He.prototype,"clear",1),je([C()],He.prototype,"updateRemoteUserDeviceStatus",1),je([C()],He.prototype,"updateRemoteTracks",1),je([C(B)],He.prototype,"subscribe",1),je([C()],He.prototype,"subscribeProxy",1),je([C(B)],He.prototype,"subscribeDeleteProxy",1),je([C()],He.prototype,"restore",1),je([C(B)],He.prototype,"resumeAudio",1),je([C(B)],He.prototype,"stopSubscribe",1),je([C(B)],He.prototype,"subscribeDeleteAllTracks",1),je([C()],He.prototype,"clearStream",1),je([C()],He.prototype,"clearScreenStream",1),je([C()],He.prototype,"updateSubscribe",1),je([C()],He.prototype,"playAudio",1),je([C()],He.prototype,"stopPlayAudio",1),je([C((s,a,e)=>[typeof s=="string"?s:s==null?void 0:s.nodeType,a||"-",e||"-"])],He.prototype,"play",1),je([C()],He.prototype,"stopPlayAll",1),je([C(B)],He.prototype,"markReconnect",1),je([C(B)],He.prototype,"markReconnected",1);let Zo=He;var Ut=(s=>(s[s.AliRtcPluginErrorCodeSuccess=0]="AliRtcPluginErrorCodeSuccess",s[s.AliRtcPluginErrorCodeFailed=-1]="AliRtcPluginErrorCodeFailed",s[s.AliRtcPluginErrorNoFindPlugin=-2]="AliRtcPluginErrorNoFindPlugin",s[s.AliRtcPluginErrorParameterError=-3]="AliRtcPluginErrorParameterError",s[s.AliRtcPluginErrorLoadError=-4]="AliRtcPluginErrorLoadError",s[s.AliRtcPluginErrorCreateError=-5]="AliRtcPluginErrorCreateError",s[s.AliRtcPluginErrorInitError=-6]="AliRtcPluginErrorInitError",s[s.AliRtcPluginErrorInitTokenError=-7]="AliRtcPluginErrorInitTokenError",s))(Ut||{});class ec extends se{constructor(){super(...arguments);g(this,"plugins",new Map)}add(e,t){if(this.plugins.has(e.name))throw new V(Ut.AliRtcPluginErrorCreateError,`Plugin ${e.name} already exists`);this.plugins.set(e.name,e),t&&e.setOptions(t),this.emit("added",e),e.on("enabled",()=>this.emit("added",e)),e.on("disabled",()=>this.emit("removed",e)),e.on("updated",()=>this.emit("updated",e))}remove(e){const t=this.plugins.get(e);if(!t)throw new V(Ut.AliRtcPluginErrorNoFindPlugin,`Plugin ${e} not founded`);this.plugins.delete(e),t.removeAllListeners(),this.emit("removed",t)}removeAll(){this.plugins.forEach(e=>{this.remove(e.name)})}get(e){return this.plugins.get(e)}has(e){return!!this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}}var tc=Object.defineProperty,ic=Object.getOwnPropertyDescriptor,ze=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?ic(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&tc(a,e,r),r};const Wi=([s])=>{const{remoteUser:a,options:e}=s;return[`user(${a.userId})`,e]},Fe=(Te=class extends se{constructor(e,t,i){var r,n;super();g(this,"rts");g(this,"encodedInsertableStreams",!0);g(this,"audioRedEnabled",!1);g(this,"localStreamManager");g(this,"slsReporter");g(this,"_rtsPeerConnectionType","publish");g(this,"connecting",!1);g(this,"connected",!1);g(this,"rtsDisconnected",!1);g(this,"_pcTraceId","");g(this,"_localJoinTime",0);g(this,"connectionResolve");g(this,"connectingPromise");g(this,"dcResolve");g(this,"dcReject");g(this,"dcConnectingPromise");g(this,"_publishingTracks",[]);g(this,"parameter",{});g(this,"preferredPubL1Ip");g(this,"preferredSubL1Ip");g(this,"traceIdMap",{});this.localStreamManager=e,this.slsReporter=t,this.parameter=i,this.rts=X.AliRTS.createClient({singlePcConfig:{usePcReconnect:!0},datachannelDelayOpen:!0,signalDatachannelInitOptions:(r=i==null?void 0:i.net)!=null&&r.datachannelInitOptions?(n=i==null?void 0:i.net)==null?void 0:n.datachannelInitOptions:void 0}),this.addRTSListener()}addRTSListener(){this.rts.on("connectStatusChange",e=>{var t,i,r,n;if(N.event(`[${Te.logName}]`,"rts connectStatusChange to:",e.status),e.status===X.EConnectStatus.CONNECT_STATUS_DISCONNECTED)this.dcReject&&this.dcReject(),this.setConnected(!1),this.rtsDisconnected=!0,this.slsReporter.reportWarning("rts disconnected"),this.emit("disconnected");else if(e.status===X.EConnectStatus.CONNECT_STATUS_CONNECTED){if(this.rtsDisconnected){const c=(n=(r=(i=(t=this.rts.commonController)==null?void 0:t.peerCore)==null?void 0:i.getSignal())==null?void 0:r.getDatachannelCore())==null?void 0:n.readyState;N.event(`[${Te.logName}]`,"dcReadyState:",c),c==="open"&&this.dcResolve&&this.dcResolve(!0)}this.rtsDisconnected=!1,this.setConnected(!0)}}),this.rts.on("reconnect",e=>{var t,i,r;N.debug(`[${Te.logName}]`,"reconnect",e),this.emit("reconnect",e.type,(t=e.extraInfo)==null?void 0:t.url,(r=(i=e.extraInfo)==null?void 0:i.msids)==null?void 0:r.map(n=>n.name))}),this.rts.on("reconnectFinish",e=>{var t;N.debug(`[${Te.logName}]`,"reconnectFinish",e),this.emit("reconnectFinish",(e==null?void 0:e.type)||"pc",e==null?void 0:e.latestUrl,(t=e==null?void 0:e.msids)==null?void 0:t.map(i=>i.name));try{this.emit("connected",!0,this._rtsPeerConnectionType)}catch(i){N.error(`[${Te.logName}]`,"emit connected error:",i)}}),this.rts.on("datachannelStatusChange",e=>{N.event(`[${Te.logName}]`,"rts datachannelStatusChange to:",e.status),e.status===X.EDatachannelStatus.DATACHANNEL_STATUS_OPEN?this.dcResolve&&this.dcResolve(!0):e.status===X.EDatachannelStatus.DATACHANNEL_STATUS_CLOSE&&(this.dcReject&&this.dcReject(),this.dcConnectingPromise=new Promise((t,i)=>{this.dcResolve=t,this.dcReject=i}))}),this.rts.on("receivedSEI",e=>{var t;if(this.emit("seimessage",e.url,e.sei.payloadType,e.sei.data),e.sei.payloadType===99)try{const i=JSON.parse(new TextDecoder().decode(e.sei.data));this.slsReporter.reportLoopAudioDelay(((t=this.publishingTracks.find(r=>r.type==="audio"))==null?void 0:t.ssrc)||"",i)}catch(i){}}),this.rts.on("onError",e=>{N.event(`[${Te.logName}]`,"rts onError event:",e)}),this.rts.on("reconnect",e=>{N.event(`[${Te.logName}]`,"rts reconnect event:",e)}),this.rts.on("traceId",({url:e,traceId:t})=>{e&&t&&this.traceIdMap[e]!==t&&(this.traceIdMap[e]=t,this.emit("traceIdUpdated",e,t))})}updateAuth(e){this.rts.updateAuth(e)}get pcTraceId(){return this._pcTraceId}set localJoinTime(e){this._localJoinTime=e}setEncodedInsertableStreams(e){this.encodedInsertableStreams=e}setReceiverPreferredVideoCodecH265(){var r;let e=(r=RTCRtpReceiver.getCapabilities("video"))==null?void 0:r.codecs;if(!e||e.length===0)return;const t=e.filter(n=>n.mimeType.toLowerCase()!=="video/rtx");let i=t.findIndex(n=>n.mimeType==="video/H265");if(i+1){let n=t[i];t.splice(i,1),t.unshift(n),this.rts.setReceiverCodecPreferences({video:t})}}setSenderPreferredVideoCodecH265(){var r;let e=(r=RTCRtpSender.getCapabilities("video"))==null?void 0:r.codecs;if(!e||e.length===0)return;const t=e.filter(n=>n.mimeType.toLowerCase()!=="video/rtx");let i=t.findIndex(n=>n.mimeType==="video/H265");if(i+1){let n=t[i];t.splice(i,1),t.unshift(n),this.rts.setSenderCodecPreferences({video:t})}}supportVideoCodec(e){var t,i,r;return e===ht.H265?(t=RTCRtpSender.getCapabilities("video"))==null?void 0:t.codecs.some(n=>n.mimeType==="video/H265"):e===ht.H264?(i=RTCRtpSender.getCapabilities("video"))==null?void 0:i.codecs.some(n=>n.mimeType==="video/H264"):e===ht.AV1&&((r=RTCRtpSender.getCapabilities("video"))==null?void 0:r.codecs.some(n=>n.mimeType==="video/AV1"))}changeVideoCodec(e){this.supportVideoCodec(e)?(N.info(`[${Te.logName}]`,"changeVideoCodec to:",e),ht.H265===e&&(this.setSenderPreferredVideoCodecH265(),this.setReceiverPreferredVideoCodecH265())):N.warn(`[${Te.logName}]`,`not support video codec: ${e}`)}setAudioRedEnabled(e){var t;if(e!==this.audioRedEnabled){try{const i=[...((t=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:t.codecs)||[]];if(i.length>0){if(e){const r=i.findIndex(c=>c.mimeType==="audio/red"),n=i.findIndex(c=>c.mimeType==="audio/opus");if(r>-1&&n>-1&&r>n){const c=i[n];i[n]=i[r],i[r]=c}}this.rts.setSenderCodecPreferences({audio:i}),this.rts.setReceiverCodecPreferences({audio:i})}}catch(i){}this.audioRedEnabled=e}}clear(){this.setConnected(!1),this.rtsDisconnected=!1,this._publishingTracks=[];try{this.rts.removeAllListeners(),this.rts.unpublish(),this.rts.unsubscribe()}catch(e){}this.rts=X.AliRTS.createClient(),this.addRTSListener()}startConnect(){this.connecting=!0,this.connectingPromise=new Promise(e=>{this.connectionResolve=e}),this.dcConnectingPromise=new Promise((e,t)=>{this.dcResolve=e,this.dcReject=t})}setConnected(e){var t;this.connected=e,this.connecting=!1,(t=this.connectionResolve)==null||t.call(this,!0)}get isConnecting(){return this.connecting}get isConnected(){return this.connected}get publishingTracks(){return this._publishingTracks}getPubMsid(e,t){const{aMsid:i,vMsid:r}=t!=null?t:{},n={};return e.hasAudio&&(n.aMsid=[i!=null?i:M.Audio]),e.hasScreen&&(n.vMsid=[M.Screen]),e.hasVideo&&(n.vMsid=[r!=null?r:t!=null&&t.isScreen?M.Screen:M.VideoLarge]),n}updatePublishingTracks(e){e&&(this._publishingTracks=e.map(({msid:t,from:i,ssrc:r,codec:n,type:c,trackId:o})=>({msid:t,from:i,type:c,ssrc:`${r}`,codec:n!=null?n:"",trackId:o})))}httpPublish(r){return I(this,arguments,function*(e,t=!1,i=_t.MANUAL){let n;const c=Date.now(),o=e.url,l=e.callId;this.startConnect();const{publishStream:d,videoSmallStream:h,screenStream:p,vMsid:u}=yield this.localStreamManager.createHTTPPublishStream();if(!d)return N.warn(`[${Te.logName}]`,"publishStream is null"),{traceId:"",l1ip:n};const f=this.getPubMsid(d,{vMsid:u});f.answerSdpHook=w=>{const y=/\d+\.\d+\.\d+\.\d+(?=\s+1106|\s+8000)/.exec(w);return y!=null&&y[0]&&(n=y[0]),w},this.handleHTTPConfig(f),this._rtsPeerConnectionType="publish";let m=!d.hasVideo,b=u,S="";const v=Date.now();try{S=yield this.rts.publish(lr(o,this.preferredPubL1Ip),d,f)}catch(w){this.setConnected(!1);const y=2e3-(Date.now()-v);throw y<=0?this.emit("disconnected"):setTimeout(()=>{this.emit("disconnected")},y),this.slsReporter.reportPublish(t,o,l,d.hasVideo&&(!u||u===M.VideoLarge),d.hasVideo&&u===M.VideoSmall,d.hasVideo&&u===M.Screen,d.hasAudio,(w==null?void 0:w.errorCode)||-1,this.pcTraceId,"",v,v),V.fromRtsError(w)}S&&(this._pcTraceId=S),N.event(`[${Te.logName}]`,"rts publish success",S);const R=Date.now();setTimeout(()=>{this.slsReporter.reportPublish(t,o,l,d.hasVideo&&(!u||u===M.VideoLarge),d.hasVideo&&u===M.VideoSmall,d.hasVideo&&u===M.Screen,d.hasAudio,0,this.pcTraceId,e.traceId,v,R)},6e3),this.slsReporter.reportConnectionLatencyEvent(ot.HANDLE_PUB_TASK,dt.START,l,S,c),this.slsReporter.reportConnectionLatencyEvent(ot.HANDLE_PUB_TASK,dt.END,l,S,Date.now());try{const w=Date.now();return this._pcTraceId=S,this.setConnected(!0),this._publishingTracks=this.rts.getPublishTrackInfoList(),h&&(yield this.publishAdd(e,h,{vMsid:M.VideoSmall},t),m=!1,b=M.VideoSmall),p&&(yield this.publishAdd(e,p,{vMsid:M.Screen},t),m=!1,b=M.Screen),yield this.waitPublishSender(o,m,b),this.slsReporter.reportPublishFirstPacket(t,l,v,w,this._localJoinTime,m?M.Audio:f.vMsid,S||"",S||"",i),{traceId:S,l1ip:n}}catch(w){throw this.setConnected(!1),V.fromError(w)}})}waitPublishSender(e,t=!1,i){return I(this,null,function*(){return Promise.race([xt(1e3),((r,n)=>{let c=0;const o=()=>(t?this.rts.getPublishAudioStats(e,i):this.rts.getPublishVideoStats(e,i)).then(l=>!(l.bytesSent>0)&&c<r?(c++,new Promise(d=>setTimeout(()=>d(o()),n))):Promise.resolve());return o()})(5,100)]).catch(()=>{})})}getPublishVideoStats(e,t){return I(this,null,function*(){return yield this.rts.getPublishVideoStats(e,t)})}getPublishAudioStats(e,t){return I(this,null,function*(){return yield this.rts.getPublishAudioStats(e,t)})}publishAdd(o,l,d){return I(this,arguments,function*(e,t,i,r=!1,n=!1,c=_t.MANUAL){var m,b,S,v;const h=e.url,p=e.callId;yield this.dcConnectingPromise;const u=Date.now(),f=this.getPubMsid(t,i);try{const R=yield ma(w=>I(this,null,function*(){return w>0&&N.event(`[${Te.logName}]`,`publishAdd retry times: ${w}`),this.isConnected?(yield this.dcConnectingPromise,this.rts.publishAdd([G({url:h,stream:t,updateSourceStream:!1},f)])):Promise.reject(new V(U.ERR_INNER,"rts not connected"))}),10,0,w=>(w==null?void 0:w.errorCode)===15006);if(R){const w=Date.now(),[y]=R,A=Date.now();return setTimeout(()=>{var _,E,T,k;this.slsReporter.reportPublish(!1,h,p,((_=f.vMsid)==null?void 0:_[0])===M.VideoLarge,((E=f.vMsid)==null?void 0:E[0])===M.VideoSmall,((T=f.vMsid)==null?void 0:T[0])===M.Screen,((k=f.aMsid)==null?void 0:k[0])===M.Audio,0,this.pcTraceId,y.traceId||"",u,A)},6e3),y.traceId&&(this._pcTraceId=y.traceId),this.updatePublishingTracks(y.trackInfoList),n&&(yield this.waitPublishSender(h,!t.hasVideo,t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)),this.slsReporter.reportPublishFirstPacket(r,p,u,w,this._localJoinTime,(t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)||"",this.pcTraceId,y.traceId||"",c),y.traceId||""}}catch(R){throw this.slsReporter.reportPublish(!1,h,p,((m=f.vMsid)==null?void 0:m[0])===M.VideoLarge,((b=f.vMsid)==null?void 0:b[0])===M.VideoSmall,((S=f.vMsid)==null?void 0:S[0])===M.Screen,((v=f.aMsid)==null?void 0:v[0])===M.Audio,(R==null?void 0:R.errorCode)||-1,this.pcTraceId,"",u),R!=null&&R.errorCode?V.fromRtsError(R):V.fromError(R)}return""})}publishDelete(e,t){return I(this,null,function*(){var l,d,h,p,u,f,m,b;yield this.dcConnectingPromise;const i=(d=(l=this.publishingTracks)==null?void 0:l.find(({msid:S})=>S===M.Audio))==null?void 0:d.msid,r=(p=(h=this.publishingTracks)==null?void 0:h.find(({msid:S})=>S===M.VideoLarge))==null?void 0:p.msid,n=(f=(u=this.publishingTracks)==null?void 0:u.find(({msid:S})=>S===M.Screen))==null?void 0:f.msid,c=[];t.screen&&n?c.push(n):t.video&&c.push(t.vMsid||r);const o=[];t.audio&&i&&o.push(i),N.event(Te.logName,"publishDelete",{streamUrl:e,aMsid:o,vMsid:c});try{const[S]=(yield this.rts.publishDeleteTracks([{url:e,aMsid:o,vMsid:c}]))||[];return N.event(Te.logName,"publishDelete",{result:S}),S&&this.updatePublishingTracks(S.trackInfoList),((b=(m=S==null?void 0:S.trackInfoList)==null?void 0:m[0])==null?void 0:b.trackId)||""}catch(S){throw V.fromRtsError(S)}})}publishReplace(e,t,i){return I(this,null,function*(){var c,o;yield this.dcConnectingPromise;const{vMsid:r,aMsid:n}=i!=null?i:{};try{const l=yield this.rts.publishReplaceTracks([{url:e,stream:t,vMsid:r,aMsid:n}]),[d]=l;return this.updatePublishingTracks(d.trackInfoList),((o=(c=d==null?void 0:d.trackInfoList)==null?void 0:c[0])==null?void 0:o.trackId)||""}catch(l){throw V.fromRtsError(l)}})}publishStop(e){return I(this,null,function*(){return yield this.rts.publishStop([{url:e}]),this._publishingTracks=[],""})}publishAddDataChannel(e){return I(this,null,function*(){yield this.dcConnectingPromise;const t=yield this.rts.publishAddDatachannel({signalUrl:e,url:lr(e,this.preferredPubL1Ip),label:M.Data,msid:M.Data}),i=t==null?void 0:t.datachannel;if(i&&i.send){const r=new ArrayBuffer(4);new DataView(r).setUint8(0,240),i.datachannel.send(r)}return i})}publishStopDataChannel(e,t){return I(this,null,function*(){return yield this.rts.publishStopDatachannel({url:e,datachannel:t})})}unpublish(){return I(this,null,function*(){yield this.rts.unpublish(),this._publishingTracks=[],this.connecting=!1,this.connected=!1})}getSubConfig(e,t){let i=t!=null?t:{};t||(i={audio:!0,video:!0,screen:!0});const r={};return i.audio&&(r.aMsid=[(e==null?void 0:e.getAudioInfo().msid)||M.Audio]),i.video?i.vMsid?r.vMsid=[i.vMsid]:r.vMsid=e!=null&&e.hasVideoLarge?[(e==null?void 0:e.getVideoLargeInfo().msid)||M.VideoLarge]:e!=null&&e.hasVideoSmall?[(e==null?void 0:e.getVideoSmallInfo().msid)||M.VideoSmall]:[M.VideoLarge]:i.screen&&(r.vMsid=[(e==null?void 0:e.getScreenInfo().msid)||M.Screen]),r}handleHTTPConfig(e){var t,i,r,n,c,o,l,d,h,p;if(this.encodedInsertableStreams&&(e.encodedInsertableStreams=!0),(i=(t=this.parameter)==null?void 0:t.net)!=null&&i.useTCP&&(e.tcpOnly=!0),(n=(r=this.parameter)==null?void 0:r.net)!=null&&n.cumuDelay&&(e.cumuDelay=!0),(o=(c=this.parameter)==null?void 0:c.net)!=null&&o.disableHeartbeat&&(e.disableHeartbeat=!0),(d=(l=this.parameter)==null?void 0:l.net)==null?void 0:d.mediaTimeout){const u=(p=(h=this.parameter)==null?void 0:h.net)==null?void 0:p.mediaTimeout;u>1e3&&u<1e5&&(e.mediaTimeout=u)}e.retryTimes=17,e.retryInterval=5e3}httpSubscribe(e){return I(this,null,function*(){var c,o;const{remoteUser:t,options:i}=e;let r=t.streamUrl;i.video||i.screen?i!=null&&i.audio||(r+="@subaudio=no"):r+="@subvideo=no";const n=this.getSubConfig(t.streamInfo,i);this.handleHTTPConfig(n),this._rtsPeerConnectionType="subscribe",(o=(c=this.parameter)==null?void 0:c.net)!=null&&o.rrtr&&(n.offerSdpHook=l=>{const d=l.replace(/(a=rtpmap:(\d+).*\r\n)/g,`$1a=rtcp-fb:$2 rrtr\r
130
- `);return d.includes(`a=rtcp-rsize\r
131
- `)?d:d.replace(/(m=(video|audio).*\r\n)/g,`$1a=rtcp-rsize\r
132
- `)});try{this.startConnect();const l=yield this.rts.subscribe(lr(r,this.preferredSubL1Ip),n);return this._pcTraceId=l.traceId,this.setConnected(!0),{traceId:l.traceId,stream:l}}catch(l){throw this.setConnected(!1),this.emit("disconnected"),V.fromRtsError(l)}})}subscribeAdd(e){return I(this,null,function*(){var n,c,o,l;const{remoteUser:t,options:i}=e,r=yt(G({url:t.streamUrl,subAudio:!!i.audio,subVideo:!(!i.screen&&!i.video)},this.getSubConfig(t.streamInfo,i)),{targetStream:i.screen?t.getScreenStream:t.getCameraStream});yield this.dcConnectingPromise;try{return(yield ma(d=>I(this,null,function*(){return yield this.dcConnectingPromise,d>0&&N.event(`[${Te.logName}]`,`subscribeAdd retry times: ${d}`),this.isConnected?this.rts.subscribeAdd([r]):Promise.reject()}),10,100,d=>{var h,p,u,f;return(d==null?void 0:d.errorCode)===15006||(d==null?void 0:d.errorCode)===15004&&((f=(u=(p=(h=d.extraInfo)==null?void 0:h.parsedData)==null?void 0:p.streams)==null?void 0:u[0])==null?void 0:f.res_code)===404}))[0]}catch(d){if(((l=(o=(c=(n=d==null?void 0:d.extraInfo)==null?void 0:n.parsedData)==null?void 0:c.streams)==null?void 0:o[0])==null?void 0:l.res_code)===508)return this.emit("subscribeexceeds"),null;throw V.fromRtsError(d)}})}subscribeDelete(e){return I(this,null,function*(){var n,c,o,l;const{remoteUser:t,options:i}=e,r=yt(G({url:t.streamUrl,subAudio:!!i.audio,subVideo:!(!i.screen&&!i.video)},this.getSubConfig(t.streamInfo,i)),{targetStream:i.screen?t.getScreenStream:t.getCameraStream});yield this.dcConnectingPromise;try{return N.event(`[${Te.logName}]`,"subscribeDeleteTracks",JSON.stringify({url:r.url,subAudio:r.subAudio,subVideo:r.subVideo,aMsid:r.aMsid,vMsid:r.vMsid})),(yield this.rts.subscribeDeleteTracks([r]))[0]}catch(d){if(((l=(o=(c=(n=d==null?void 0:d.extraInfo)==null?void 0:n.parsedData)==null?void 0:c.streams)==null?void 0:o[0])==null?void 0:l.res_code)===404)return;throw V.fromRtsError(d)}})}subscribeAddDataChannel(e){return I(this,null,function*(){yield this.dcConnectingPromise;const t=yield this.rts.subscribeAddDatachannel({signalUrl:e,url:e,label:M.Data,msid:M.Data}),i=t==null?void 0:t.datachannel;if(i&&i.send){const r=new ArrayBuffer(4);new DataView(r).setUint8(0,240),i.send(r)}return i})}subscribeDeleteDatachannel(e,t){return I(this,null,function*(){let i;try{i=yield this.rts.subscribeDeleteDatachannel({url:e,msid:M.Data,datachannel:t})}catch(r){}return i})}publish(r){return I(this,arguments,function*(e,t=!1,i=_t.MANUAL){const n=e.url;let c,o="";if(this.connecting&&(yield this.connectingPromise),this.connected){yield this.dcConnectingPromise;let l,d=!1;const{audio:h,video:p,videoSmall:u,screen:f}=this.localStreamManager.publishStreams;h&&(o=yield this.publishAdd(e,h,{aMsid:M.Audio},t),d=!0,l=M.Audio,yield xt(100)),p&&(o=yield this.publishAdd(e,p,{vMsid:M.VideoLarge},t),d=!1,l=M.VideoLarge,yield xt(100)),u&&(o=yield this.publishAdd(e,u,{vMsid:M.VideoSmall},t),d=!1,l=M.VideoSmall,yield xt(100)),f&&(o=yield this.publishAdd(e,f,{isScreen:!0,vMsid:M.Screen},t),d=!1,l=M.Screen),l&&(yield this.waitPublishSender(n,d,l))}else{const l=yield this.httpPublish(e,t,i);o=l.traceId,c=l.l1ip}return{traceId:o,l1ip:c}})}reportSubscribeLatency(e,t,i,r){const n=[];e.audio&&n.push(e.aMsid||M.Audio),e.video?n.push(e.vMsid||M.VideoLarge):e.screen&&n.push(M.Screen),n.forEach(c=>{this.slsReporter.reportConnectionLatencyEvent(ot.HANDLE_SUB_TASK,dt.START,t,c,i,0,r),this.slsReporter.reportConnectionLatencyEvent(ot.HANDLE_SUB_TASK,dt.END,t,c,Date.now(),0,r)})}subscribe(e,t,i,r,n){return I(this,null,function*(){let c=!1;const{options:o,remoteUser:l}=e;if(o.video&&o.screen)throw new V(U.ERR_INNER,"subscribe error, video and screen cannot be subscribed at the same time");let d;this.connecting&&(yield this.connectingPromise);let h=Date.now();this.connected?d=yield this.subscribeAdd(e):(c=!0,d=yield this.httpSubscribe(e)),this.reportSubscribeLatency(o,i,h,c);const p=Date.now();let u=M.VideoLarge,f=o.video||o.screen,m=o.audio;o.video&&o.vMsid?u=o.vMsid:o.screen&&(u=M.Screen);let b=0,S=0,v=0;const R=((w,y)=>{let A=0;const _=()=>{let E;return m&&!b&&(E=this.rts.getSubscribeAudioStats(l.streamUrl).then(T=>{if(T.packetsReceived>0)b=Date.now(),N.debug(`[${Te.logName}]`,l.userId,"Stats 音频首包");else if(!f)return A<w&&(A++,new Promise(k=>setTimeout(()=>k(_()),y)));return!0})),f&&!v&&(E=this.rts.getSubscribeVideoStats(l.streamUrl,u).then(T=>(!S&&T.packetsReceived>0&&(S=Date.now(),N.debug(`[${Te.logName}]`,l.userId,"Stats 视频首包")),T.framesDecoded>0?(v=Date.now(),N.debug(`[${Te.logName}]`,l.userId,"Stats 视频首帧数据"),!0):A<w?(A++,new Promise(k=>setTimeout(()=>k(_()),y))):(N.event(`[${Te.logName}]`,l.userId,"尝试获取首帧数据失败"),!1)))),Promise.resolve(E)};return _()})(20,100);return R.then(()=>{S&&this.slsReporter.reportSubscribeFirstPacket(t===be.Resume,i,r,u,{fprt:S-h,ifsprtc:v?v-h:0,ajsub:t===be.Join?1:0,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",sstc:p-h}),v&&this.slsReporter.reportSubscribeFirstFrame(t===be.Resume,i,r,u,{fvfrt:v-h,fp2fftc:v-S,ajsub:t===be.Join?1:0,tffrtc:t===be.Join?v-this.localJoinTime:v-n,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",fvfdtc:v-h}),b&&(this.slsReporter.reportConnectionLatencyEvent(ot.FIRST_REMOTE,dt.DECODED,i,M.Audio,b),this.slsReporter.reportSubscribeFirstPacket(t===be.Resume,i,r,M.Audio,{fprt:b-h,ifsprtc:b-h,ajsub:t===be.Join?1:0,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",sstc:p-h}))}),d&&(d.isHTTP=c,d.statsCheckPromise=R),d})}getSubscribeVideoStats(e,t){return I(this,null,function*(){return yield this.rts.getSubscribeVideoStats(e,t)})}getSubscribeAudioStats(e,t){return I(this,null,function*(){return yield this.rts.getSubscribeAudioStats(e,t)})}getStreamByMsid(e){return this.rts.commonController.streamManager.getStreamByMsid(e)}getDatachannelByMsid(e){var t;return(t=this.rts.commonController.datachannelManager)==null?void 0:t.getByMsid(e)}getPCStats(){return I(this,null,function*(){var e,t;return(t=(e=this.rts.commonController.peerCore)==null?void 0:e.pc)==null?void 0:t.getStats()})}sendSEI(e,t,i,r){return I(this,null,function*(){return this.rts.sendSEI({url:e,vMsid:M.VideoLarge,data:t,repeatCount:i,payloadType:r})})}},g(Te,"logName","RtsManager"),Te);ze([C(B)],Fe.prototype,"startConnect",1),ze([C()],Fe.prototype,"updatePublishingTracks",1),ze([C(B,B)],Fe.prototype,"httpPublish",1),ze([C(B,B)],Fe.prototype,"waitPublishSender",1),ze([C(([s,a,e])=>[s,JSON.stringify(e)],B)],Fe.prototype,"publishAdd",1),ze([C(B,B)],Fe.prototype,"publishDelete",1),ze([C(([s,a,e])=>[s,JSON.stringify(e)])],Fe.prototype,"publishReplace",1),ze([C(B)],Fe.prototype,"publishStop",1),ze([C(B)],Fe.prototype,"publishAddDataChannel",1),ze([C(B)],Fe.prototype,"publishStopDataChannel",1),ze([C()],Fe.prototype,"unpublish",1),ze([C(Wi,({traceId:s})=>s)],Fe.prototype,"httpSubscribe",1),ze([C(Wi,({traceId:s})=>s)],Fe.prototype,"subscribeAdd",1),ze([C(Wi)],Fe.prototype,"subscribeDelete",1),ze([C(B)],Fe.prototype,"subscribeAddDataChannel",1),ze([C(B)],Fe.prototype,"subscribeDeleteDatachannel",1),ze([C(B)],Fe.prototype,"publish",1),ze([C(Wi)],Fe.prototype,"subscribe",1),ze([C()],Fe.prototype,"sendSEI",1);let rc=Fe;class Mr{constructor(a=Cr){g(this,"defaultProfile");g(this,"profile");g(this,"profileMap",new Map);g(this,"audioProfile");g(this,"contentHint");this.defaultProfile=G({},a)}updateProfile(a,e){this.profileMap.set(a,G(G(G({},this.defaultProfile),this.profileMap.get(a)||{}),e||{})),this.profile=a}get videoProfile(){return this.profile}updateAudioProfile(a){this.audioProfile=a}setContentHint(a,e){e&&(this.contentHint=e),this.contentHint&&a&&(a.contentHint=this.contentHint)}setVideoProfile(a,e,t=!1){return I(this,null,function*(){if(!this.profile)return;const i=this.profileMap.get(this.profile)||(e==null?void 0:e.VideoProfileMap.get(this.profile));if(i){if(!t&&a&&a.readyState==="live"&&a.applyConstraints)try{yield a.applyConstraints(i)}catch(r){}if(e){const r=G({},i);i.maxSendFrameRate&&(r.frameRate=i.maxSendFrameRate),e==null||e.VideoProfileMap.set(this.profile,r),yield e.setVideoProfile(this.profile)}}})}}var Oe=(s=>(s[s.AliRtcSdkStreamTypeCapture=0]="AliRtcSdkStreamTypeCapture",s[s.AliRtcSdkStreamTypeScreen=1]="AliRtcSdkStreamTypeScreen",s))(Oe||{});class Lr extends se{constructor(e){super();g(this,"type");g(this,"originVideoTrack");g(this,"videoSource");g(this,"_videoMuted",!1);g(this,"originAudioTrack");g(this,"audioSource");g(this,"_audioMuted",!1);g(this,"_targetVideoTrack");g(this,"_targetDualVideoTrack");g(this,"_targetAudioTrack");g(this,"_publishVideoStream");g(this,"_publishDualVideoStream");g(this,"_publishAudioStream");g(this,"_previewStream");g(this,"plugins",[]);g(this,"_profileManager");g(this,"cameraVideoConstraints");g(this,"micAudioConstraints");g(this,"onVideoTrackEnded",()=>{this.emit("videotrackended")});g(this,"onAudioTrackEnded",()=>{this.emit("audiotrackended")});this.type=e}get profileManager(){return this._profileManager}get audioProfile(){var e;return(e=this.profileManager)==null?void 0:e.audioProfile}updateSource(e,t,i){return I(this,null,function*(){var c,o,l,d,h,p;const{videoTrack:r,audioTrack:n}=e;r&&((c=this.originVideoTrack)==null||c.removeEventListener("ended",this.onVideoTrackEnded)),n&&((o=this.originAudioTrack)==null||o.removeEventListener("ended",this.onAudioTrackEnded)),this.type===Oe.AliRtcSdkStreamTypeScreen?this.stop():(r&&((l=this.originVideoTrack)==null||l.stop()),n&&((d=this.originAudioTrack)==null||d.stop())),r&&(this.originVideoTrack=r,(h=this.originVideoTrack)==null||h.addEventListener("ended",this.onVideoTrackEnded),this.videoSource=t||Si.Camera,this.updateVideoTrack(r)),n&&(this.originAudioTrack=n,(p=this.originAudioTrack)==null||p.addEventListener("ended",this.onAudioTrackEnded),this.audioSource=i||Bi.Microphone,this.updateAudioTrack(n))})}get currentProfile(){var e;return(e=this.profileManager)==null?void 0:e.profile}get currentVideoTrack(){return this._targetVideoTrack}get currentDualVideoTrack(){return this._targetDualVideoTrack}get publishVideoStream(){return this._publishVideoStream}get publishDualVideoStream(){return this._publishDualVideoStream}get currentAudioTrack(){return this._targetAudioTrack}get publishAudioStream(){return this._publishAudioStream}get previewStream(){return this._previewStream}updateVideoTrack(e,t=!1){return I(this,null,function*(){(this._targetVideoTrack!==e||t)&&(this._targetVideoTrack=e)})}updateDualVideoTrack(e,t=!1){return I(this,null,function*(){(this._targetDualVideoTrack!==e||t)&&(this._targetDualVideoTrack=e)})}updateAudioTrack(e,t=!1){return I(this,null,function*(){(this._targetAudioTrack!==e||t)&&(this._targetAudioTrack=e)})}setAudioMuted(e){var t,i;this._audioMuted=e,e?(t=this.publishAudioStream)==null||t.disableAudio():(i=this.publishAudioStream)==null||i.enableAudio()}get isAudioMuted(){return this._audioMuted}setVideoMuted(e){var t,i;this._videoMuted=e,e?(t=this.publishVideoStream)==null||t.disableVideo():(i=this.publishVideoStream)==null||i.enableVideo()}get isVideoMuted(){return this._videoMuted}process(e){return I(this,null,function*(){var t,i,r,n,c,o,l,d,h,p,u,f;this._targetAudioTrack=this.originAudioTrack,this._targetVideoTrack=this.originVideoTrack;for(const m of this.plugins)try{yield m.execute(this,e)}catch(b){console.error(`error in plugin-${m.name}, error: ${b}`)}this._targetVideoTrack?((i=(t=this._publishVideoStream)==null?void 0:t.videoTrack)==null?void 0:i.id)!==this._targetVideoTrack.id&&(this._publishVideoStream=yield Ri(this._targetVideoTrack),this.setVideoMuted(this._videoMuted),(r=this.profileManager)==null||r.setVideoProfile(this.originVideoTrack,this._publishVideoStream,!0),(n=this.profileManager)==null||n.setContentHint(this._targetVideoTrack),this.previewStream?(c=this.previewStream)==null||c.mergeStream(this._publishVideoStream):this._previewStream=yield Ri(this._targetVideoTrack)):(this._publishVideoStream=void 0,(o=this.previewStream)==null||o.deleteTracks({video:!0})),this._targetDualVideoTrack?((d=(l=this._publishDualVideoStream)==null?void 0:l.videoTrack)==null?void 0:d.id)!==this._targetDualVideoTrack.id&&(this._publishDualVideoStream=yield Ri(this._targetDualVideoTrack),this._videoMuted?this._publishDualVideoStream.disableVideo():this._publishDualVideoStream.enableVideo()):this._publishDualVideoStream=void 0,this._targetAudioTrack?((p=(h=this._publishAudioStream)==null?void 0:h.audioTrack)==null?void 0:p.id)!==this._targetAudioTrack.id&&(this._publishAudioStream=yield Ri(this._targetAudioTrack),this.setAudioMuted(this._audioMuted),this.previewStream?(u=this.previewStream)==null||u.mergeStream(this._publishAudioStream):this._previewStream=yield Ri(this._targetAudioTrack)):(this._publishAudioStream=void 0,(f=this.previewStream)==null||f.deleteTracks({audio:!0}))})}stopVideo(){var e,t;this.originVideoTrack&&((e=this.originVideoTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originVideoTrack)==null||t.stop(),this.originVideoTrack=void 0),this.updateVideoTrack(void 0)}stopAudio(){var e,t;this.originAudioTrack&&((e=this.originAudioTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originAudioTrack)==null||t.stop(),this.originAudioTrack=void 0),this.updateAudioTrack(void 0)}stop(){this.stopVideo(),this.stopAudio()}updateVideoProfile(e,t,i=!1){return I(this,null,function*(){this._profileManager||(this._profileManager=new Mr(this.type===Oe.AliRtcSdkStreamTypeScreen?en:Cr)),e&&this._profileManager.updateProfile(e,t),yield this._profileManager.setVideoProfile(this.originVideoTrack,this._publishVideoStream,i)})}get videoProfile(){var e;return(e=this.profileManager)==null?void 0:e.videoProfile}setVideoContentHint(e){this._profileManager||(this._profileManager=new Mr(this.type===Oe.AliRtcSdkStreamTypeScreen?en:Cr)),this._profileManager.setContentHint(this.currentVideoTrack,e)}updateAudioProfile(e){return I(this,null,function*(){this._profileManager||(this._profileManager=new Mr),this._profileManager.updateAudioProfile(e)})}cloneVideoProfile(e){return I(this,null,function*(){var t;yield(t=this.profileManager)==null?void 0:t.setVideoProfile(void 0,e)})}addPlugin(e){const t=this.plugins.findIndex(i=>i.zIndex>e.zIndex);t>-1?this.plugins.splice(t,0,e):this.plugins.push(e)}removePlugin(e){const t=this.plugins.indexOf(e);return t>-1&&(e.clear(this),this.plugins.splice(t,1),!0)}}var sc=Object.defineProperty,ac=Object.getOwnPropertyDescriptor,ft=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?ac(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&sc(a,e,r),r};const ut=(Ht=class extends se{constructor(e,t){super();g(this,"pluginManager");g(this,"slsReporter");g(this,"publishingCameraVideoStream");g(this,"publishingScreenVideoStream");g(this,"cameraStreamInfo",new Lr(Oe.AliRtcSdkStreamTypeCapture));g(this,"screenStreamInfo",new Lr(Oe.AliRtcSdkStreamTypeScreen));g(this,"streamInfos",[this.cameraStreamInfo,this.screenStreamInfo]);g(this,"_audioCaptureDisabled",!1);g(this,"_cameraCaptureDisabled",!1);g(this,"_publishLocalAudioStreamEnabled",!0);g(this,"_publishLocalVideoStreamEnabled",!0);g(this,"_publishLocalScreenStreamEnabled",!0);this.screenStreamInfo.setVideoContentHint("motion"),this.pluginManager=e,this.slsReporter=t,this.cameraStreamInfo.on("videotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({video:!0}),this.emit("trackended",qt.VideoTrackEnded)})),this.cameraStreamInfo.on("audiotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({audio:!0}),this.emit("trackended",qt.AudioTrackEnded)})),this.screenStreamInfo.on("videotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({screen:!0}),this.emit("trackended",qt.ScreenTrackEnded)})),this.pluginManager.on("added",i=>I(this,null,function*(){if(N.info(`[${Ht.logName}]`,"plugin added",i.name),!i.isSupported("7.2.1"))return console.warn(`${i.name} is not supported!!!`),void i.emit("unsupported");try{yield i.init()}catch(r){i.emit("error",V.fromError(r,Ut.AliRtcPluginErrorInitError))}i.streamType===Oe.AliRtcSdkStreamTypeCapture&&(this.cameraStreamInfo.addPlugin(i),yield this.cameraStreamInfo.process(this.streamInfos)),i.streamType===Oe.AliRtcSdkStreamTypeScreen&&(this.screenStreamInfo.addPlugin(i),yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("removed",i=>I(this,null,function*(){this.cameraStreamInfo.removePlugin(i)&&(yield this.cameraStreamInfo.process(this.streamInfos)),this.screenStreamInfo.removePlugin(i)&&(yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("updated",()=>I(this,null,function*(){yield this.updateStreams()}))}get hasCamera(){return!!this.cameraStreamInfo.originVideoTrack}get audioCaptureDisabled(){return this._audioCaptureDisabled}set audioCaptureDisabled(e){this._audioCaptureDisabled=e}get cameraCaptureDisabled(){return this._cameraCaptureDisabled}set cameraCaptureDisabled(e){this._cameraCaptureDisabled=e}setAudioMuted(e){this.cameraStreamInfo.setAudioMuted(e)}get isAudioMuted(){return this.cameraStreamInfo.isAudioMuted}setCameraMuted(e){this.cameraStreamInfo.setVideoMuted(e)}get isCameraMuted(){return this.cameraStreamInfo.isVideoMuted}setScreenMuted(e){this.screenStreamInfo.setVideoMuted(e)}get isScreenMuted(){return this.screenStreamInfo.isVideoMuted}get publishLocalAudioStreamEnabled(){return this._publishLocalAudioStreamEnabled}set publishLocalAudioStreamEnabled(e){this._publishLocalAudioStreamEnabled=e}get publishLocalVideoStreamEnabled(){return this._publishLocalVideoStreamEnabled}set publishLocalVideoStreamEnabled(e){this._publishLocalVideoStreamEnabled=e}get publishLocalScreenStreamEnabled(){return this._publishLocalScreenStreamEnabled}set publishLocalScreenStreamEnabled(e){this._publishLocalScreenStreamEnabled=e}updateStreams(){return I(this,null,function*(){yield this.cameraStreamInfo.process(this.streamInfos),yield this.screenStreamInfo.process(this.streamInfos),this.emit("publishupdate")})}setAvailableCameraDeviceId(){return I(this,null,function*(){var e,t,i,r;if((e=this.cameraStreamInfo.cameraVideoConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.cameraVideoConstraints)==null?void 0:t.deviceId;const c=yield X.AliRTS.getCameraList();c.find(o=>o.deviceId===n)||(n=(r=(i=c.find(o=>!!o.deviceId))==null?void 0:i.deviceId)!=null?r:""),this.cameraStreamInfo.cameraVideoConstraints.deviceId=n}})}setAvailableMicrophoneDeviceId(){return I(this,null,function*(){var e,t,i,r;if((e=this.cameraStreamInfo.micAudioConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.micAudioConstraints)==null?void 0:t.deviceId;const c=yield X.AliRTS.getMicList();c.find(o=>o.deviceId===n)||(n=(r=(i=c.find(o=>!!o.deviceId))==null?void 0:i.deviceId)!=null?r:""),this.cameraStreamInfo.micAudioConstraints.deviceId=n}})}createLocalStream(e){return I(this,null,function*(){var h;const{screen:t,mediaStream:i,videoProfile:r,screenProfile:n}=e;let{video:c,audio:o}=e;const l=(p=>{const{audio:u,video:f,screen:m}=p;if(f&&m)throw new V(U.ERR_INNER,"create stream error, cannot create video && screen together");return!!(f||u||m)})(e);let d;if(l){i||(c===!0&&this.cameraStreamInfo.cameraVideoConstraints?(yield this.setAvailableCameraDeviceId(),c=G({},this.cameraStreamInfo.cameraVideoConstraints)):typeof c=="object"&&(yield this.setAvailableCameraDeviceId(),c=G(G({},c),this.cameraStreamInfo.cameraVideoConstraints)),o===void 0&&this.audioCaptureDisabled?o=!1:o&&(o===!0&&this.cameraStreamInfo.micAudioConstraints?(yield this.setAvailableMicrophoneDeviceId(),o=G({},this.cameraStreamInfo.micAudioConstraints)):typeof o=="object"&&(yield this.setAvailableMicrophoneDeviceId(),o=G(G({},o),this.cameraStreamInfo.micAudioConstraints)),this._audioCaptureDisabled=!1));const p=Date.now();try{d=yield X.AliRTS.createStream({audio:o,video:c,screen:t,custom:!!i,mediaStream:i,skipProfile:!0}),N.info(`[${Ht.logName}]`,"createLocalStream",{audio:o,video:c,screen:t,custom:!!i,time:Date.now()-p}),o&&!i&&this.slsReporter.reportAudio(null,Date.now()-p,((h=d==null?void 0:d.audioTrack)==null?void 0:h.label)||""),t&&!i&&this.slsReporter.reportScreen(null,Date.now()-p)}catch(u){throw o&&!i&&this.slsReporter.reportAudio(u,Date.now()-p,""),t&&!i&&this.slsReporter.reportScreen(null,Date.now()-p),u}if(t)yield this.screenStreamInfo.updateSource(d,Si.Screen,Bi.Screen),yield this.setScreenProfile(n||Za),this.setScreenContentHint(),this.publishingScreenVideoStream=void 0;else if(yield this.cameraStreamInfo.updateSource(d,Si.Camera,Bi.Microphone),d.hasVideo&&(yield this.setVideoProfile(r||Qa),this.setVideoContentHint(),this.publishingCameraVideoStream=void 0),d.hasAudio&&typeof o=="boolean"){const u=this.cameraStreamInfo.audioProfile;u&&(yield d.setAudioProfile(u))}}return X.AliRTS.SystenUtil.isIos&&X.AliRTS.SystenUtil.compareVersion("15.1")&&!X.AliRTS.SystenUtil.compareVersion("15.2")&&(yield xt(1e3)),yield this.updateStreams(),d})}stopLocalStream(e){return I(this,null,function*(){const{screen:t,video:i,audio:r}=e!=null?e:{};let n=!1;i&&this.cameraStreamInfo.originVideoTrack&&(n=!0,this.cameraStreamInfo.stopVideo(),this.publishingCameraVideoStream=void 0),r&&this.cameraStreamInfo.originAudioTrack&&(n=!0,this.cameraStreamInfo.stopAudio()),t&&this.screenStreamInfo.originVideoTrack&&(n=!0,this.screenStreamInfo.stop(),this.publishingScreenVideoStream=void 0,this.slsReporter.reportScreenStop(null)),n&&(yield this.updateStreams())})}get publishStreams(){const{publishLocalVideoStreamEnabled:e,publishLocalAudioStreamEnabled:t,publishLocalScreenStreamEnabled:i}=this;return{video:e?this.cameraStreamInfo.publishVideoStream:void 0,videoSmall:e?this.cameraStreamInfo.publishDualVideoStream:void 0,audio:t?this.cameraStreamInfo.publishAudioStream:void 0,screen:i?this.screenStreamInfo.publishVideoStream:void 0}}createHTTPPublishStream(){return I(this,null,function*(){var o,l,d,h;let e,t,i,r,n=!1;const c=this.publishStreams;try{if(!(c.audio||c.video||c.videoSmall||c.screen))throw N.error(`[${Ht.logName}]`,"no tracks founded"),new V(U.ERR_SDK_PUBLISH_INVAILD,"no tracks founded");const p=new MediaStream;(o=c.audio)!=null&&o.audioTrack&&p.addTrack(c.audio.audioTrack),(l=c.video)!=null&&l.videoTrack?(p.addTrack(c.video.videoTrack),i=c.videoSmall,r=c.screen):(d=c.screen)!=null&&d.videoTrack&&(t=M.Screen,p.addTrack((h=c.screen)==null?void 0:h.videoTrack),n=!0),e=yield sn(p),n?(this.screenStreamInfo.cloneVideoProfile(e),this.publishingScreenVideoStream=e):(this.cameraStreamInfo.cloneVideoProfile(e),this.publishingCameraVideoStream=e)}catch(p){}return{publishStream:e,videoSmallStream:i,screenStream:r,vMsid:t}})}stop(){this.cameraStreamInfo.stop(),this.screenStreamInfo.stop(),this.updateStreams()}setVideoProfile(e,t,i=!1){return I(this,null,function*(){yield this.cameraStreamInfo.updateVideoProfile(e,t,i),this.publishingCameraVideoStream&&this.cameraStreamInfo.cloneVideoProfile(this.publishingCameraVideoStream)})}setVideoContentHint(e){this.cameraStreamInfo.setVideoContentHint(e)}setAudioProfile(e){return I(this,null,function*(){var t;yield this.cameraStreamInfo.updateAudioProfile(e),yield(t=this.publishingCameraVideoStream)==null?void 0:t.setAudioProfile(e)})}setScreenProfile(e,t){return I(this,null,function*(){yield this.screenStreamInfo.updateVideoProfile(e,t),this.publishingScreenVideoStream&&this.screenStreamInfo.cloneVideoProfile(this.publishingScreenVideoStream)})}setScreenContentHint(e){this.screenStreamInfo.setVideoContentHint(e)}setCameraVideoConstraints(e){var t;this.cameraStreamInfo.cameraVideoConstraints=G(G({},(t=this.cameraStreamInfo.cameraVideoConstraints)!=null?t:{}),e)}setMicAudioConstraints(e){var t;this.cameraStreamInfo.micAudioConstraints=G(G({},(t=this.cameraStreamInfo.micAudioConstraints)!=null?t:{}),e)}},g(Ht,"logName","LocalStreamManager"),Ht);ft([C(([s])=>{const{audio:a,video:e,screen:t,custom:i,skipProfile:r,videoProfile:n,screenProfile:c}=s;return[{audio:a,video:e,screen:t,custom:i,skipProfile:r,videoProfile:n,screenProfile:c}]})],ut.prototype,"createLocalStream",1),ft([C(B)],ut.prototype,"stopLocalStream",1),ft([C()],ut.prototype,"createHTTPPublishStream",1),ft([C()],ut.prototype,"stop",1),ft([C(B)],ut.prototype,"setVideoProfile",1),ft([C(B)],ut.prototype,"setVideoContentHint",1),ft([C(B)],ut.prototype,"setAudioProfile",1),ft([C(B)],ut.prototype,"setScreenProfile",1),ft([C(B)],ut.prototype,"setScreenContentHint",1),ft([C(B)],ut.prototype,"setCameraVideoConstraints",1),ft([C(B)],ut.prototype,"setMicAudioConstraints",1);let nc=ut;const oc=s=>I(this,null,function*(){const a=new X.AliRTS.SupportUtil;window.isSecureContext||console.warn("WebRTC 需要 HTTPS 安全上下文,细节可参考:https://developer.mozilla.org/zh-CN/docs/Web/Security/Secure_Contexts");let e={support:!1,detail:{isWebRTCSupported:a.checkMediaDevices()&&a.checkWebRtcSupport(),isH264DecodeSupported:!1,isH264EncodeSupported:!1,isScreenShareSupported:!1,isSendMediaExtensionMsgSupported:!1,isBrowserSupported:!0}},t=!1;try{e.detail.isWebRTCSupported?(yield a.isSupport({isReceiveVideo:!0}),t=!0):console.warn("当前浏览器不支持 WebRTC")}catch(i){t=!1,e.detail.isBrowserSupported=a.checkBrowser({errorCode:0,message:""})}if(e.support=t,a.checkWebRtcSupport()&&s!=="sendonly"){const i=yield a.checkH264Decode();e.detail.isH264DecodeSupported=i,e.support=e.support&&i}if(a.checkWebRtcSupport()&&s!=="recvonly"){const i=yield a.checkH264Encode();e.detail.isH264EncodeSupported=i,e.support=e.support&&i}return e.detail.isScreenShareSupported=a.checkWebRtcSupport()&&a.checkScreenCapture()&&!X.AliRTS.SystenUtil.isAndroid&&!X.AliRTS.SystenUtil.isIos,e.detail.isSendMediaExtensionMsgSupported=a.checkWebRtcSupport()&&a.checkEncodedTransformSupport(),e});var nn=(s=>(s[s.PRE_PROCESSOR=0]="PRE_PROCESSOR",s[s.POST_PROCESSOR=1]="POST_PROCESSOR",s))(nn||{}),oi=(s=>(s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO",s[s.BOTH=2]="BOTH",s))(oi||{});class Dt extends se{constructor(e,t=Oe.AliRtcSdkStreamTypeCapture,i=1){super();g(this,"name");g(this,"options");g(this,"type",0);g(this,"streamType");g(this,"trackType");g(this,"zIndex",1);g(this,"_isEnable",!0);g(this,"shouldCache",!0);g(this,"lastInputAudioTrack");g(this,"lastOutputAudioTrack");g(this,"lastInputVideoTrack");g(this,"lastOutputVideoTrack");g(this,"_hasCleared",!0);this.name=e,this.streamType=t,this.trackType=i,this.options=this.initOptions}get initOptions(){return{}}getOptions(){return this.options}init(){return I(this,null,function*(){})}enable(){this._isEnable||(this._isEnable=!0,this.init(),this.emit("enabled"))}disable(){this._isEnable&&(this._isEnable=!1,this.clear(),this.emit("disabled"))}get isEnable(){return this._isEnable}audioUpdated(e){var t,i;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((i=e.currentAudioTrack)==null?void 0:i.id)}videoUpdated(e){var t,i;return((t=this.lastInputVideoTrack)==null?void 0:t.id)!==((i=e.currentVideoTrack)==null?void 0:i.id)}execute(e,t){return I(this,null,function*(){const i=this.shouldUpdate(e,t);this.lastInputAudioTrack=e.currentAudioTrack,this.lastInputVideoTrack=e.currentVideoTrack,this._hasCleared||i?(yield this.process(e,t),this._hasCleared=!1):this.shouldCache&&(!this.lastOutputAudioTrack||this.trackType!==2&&this.trackType!==0||this.lastOutputAudioTrack&&e.updateAudioTrack(this.lastOutputAudioTrack),!this.lastOutputVideoTrack||this.trackType!==2&&this.trackType!==1||this.lastOutputVideoTrack&&e.updateVideoTrack(this.lastOutputVideoTrack)),this.lastOutputAudioTrack=e.currentAudioTrack,this.lastOutputVideoTrack=e.currentVideoTrack})}clear(e){this._hasCleared=!0,this.lastInputAudioTrack=void 0,this.lastInputVideoTrack=void 0,this.lastOutputAudioTrack=void 0,this.lastOutputVideoTrack=void 0}}class cc extends Dt{constructor(){super("AliRtcScreenStandardize",Oe.AliRtcSdkStreamTypeScreen);g(this,"canvas");g(this,"lastWidth");g(this,"lastHeight");g(this,"isProcessingScreenTrack",!1);this.shouldCache=!1}get initOptions(){return{base:4}}setOptions(e){this.options=e}isSupported(){return!(typeof TransformStream=="undefined"||typeof MediaStreamTrackProcessor=="undefined"||typeof MediaStreamTrackGenerator=="undefined")}updateProcessCanvas(e,t){if(this.canvas&&this.lastWidth===e&&this.lastHeight===t)return;const i=Math.ceil(e/this.options.base)*this.options.base,r=Math.ceil(t/this.options.base)*this.options.base;if(this.canvas||(this.canvas=document.createElement("canvas")),this.canvas.width=i,this.canvas.height=r,this.lastWidth&&e>this.lastWidth||this.lastHeight&&t>this.lastHeight){const n=this.canvas.getContext("2d");n&&n.clearRect(0,0,i,r)}this.lastWidth=e,this.lastHeight=t}shouldProcess(e){var i;let t=!1;if(e.originVideoTrack&&e.videoSource===Si.Screen){const r=(i=e.originVideoTrack)==null?void 0:i.getSettings();if(r){const{width:n,height:c}=r;t=!n||!c||!(n%this.options.base===0&&c%this.options.base===0)}}return t}shouldUpdate(e){return this.shouldProcess(e)!==this.isProcessingScreenTrack}handleFrame(e){return I(this,null,function*(){var n;const{displayWidth:t,displayHeight:i}=e;if(!t||!i||t%this.options.base===0&&i%this.options.base===0)return e;this.updateProcessCanvas(t,i);const r=(n=this.canvas)==null?void 0:n.getContext("2d");if(this.canvas&&r){r.drawImage(e,0,0,t,i);const c=new VideoFrame(this.canvas,{timestamp:e.timestamp});return e.close(),c}return e})}process(e){return I(this,null,function*(){var d;if(!this.shouldProcess(e))return this.clear(e),void(this.isProcessingScreenTrack=!1);if(e.originVideoTrack){const h=e.originVideoTrack.getSettings();if(h){const{width:p,height:u}=h;if(!(!p||!u||!(p%this.options.base===0&&u%this.options.base===0)))return void this.clear(e)}}const t=new MediaStreamTrackProcessor({track:e.originVideoTrack}),i=new MediaStreamTrackGenerator({kind:"video"}),r=new MediaStream([i]),n=this,c=new TransformStream({transform(h,p){return I(this,null,function*(){const u=yield n.handleFrame(h);yield p.enqueue(u),u==null||u.close()})}});t.readable.pipeThrough(c).pipeTo(i.writable);const o=(d=r.getVideoTracks())==null?void 0:d[0];e.updateVideoTrack(o),this.isProcessingScreenTrack=!0})}clear(e){this.canvas=void 0,this.lastWidth=void 0,this.lastHeight=void 0,super.clear(e)}}class lc extends Dt{constructor(){super("blankAudio",Oe.AliRtcSdkStreamTypeCapture,oi.BOTH);g(this,"hasTrack",!1);g(this,"oscillator",null);g(this,"audioTrack",null);g(this,"createAudioTrack",()=>{const e=new AudioContext;this.oscillator=e.createOscillator();const t=e.createGain();t.gain.value=0;const i=e.createMediaStreamDestination();this.oscillator.connect(t),t.connect(i),this.oscillator.start();const r=i.stream;return this.audioTrack=r.getAudioTracks()[0],this.audioTrack});this.zIndex=9}isSupported(){return!0}setOptions(){throw new Error("Method not implemented.")}shouldUpdate(e,t){return this.hasTrack!==t.some(i=>i.originVideoTrack||i.originAudioTrack)}process(e,t){return I(this,null,function*(){var r;const i=t.some(n=>n.originVideoTrack||n.originAudioTrack);this.hasTrack=i,i?this.audioTrack&&((r=this.oscillator)==null||r.stop(),this.oscillator=null,this.audioTrack.stop(),this.audioTrack=null):(this.audioTrack||(this.audioTrack=this.createAudioTrack()),e.updateAudioTrack(this.audioTrack))})}}class on{constructor(a){g(this,"name","COMMON");this.name=a||this.name}info(...a){}warn(...a){}print(a,...e){const t=a.toLowerCase();t&&console[t](`[${a}][${this.name}]`,...e)}}g(on,"LEVEL",0);class dc{constructor(){g(this,"logger",new on("AudioMixer"));g(this,"audioContext",new AudioContext);g(this,"audioDestination",this.audioContext.createMediaStreamDestination());g(this,"audioTrack",(a=>a.getAudioTracks()[0])(this.audioDestination.stream));g(this,"sourceNodeMap",{})}get sourceNodeList(){return Object.values(this.sourceNodeMap).map(a=>a.sourceNode).filter(a=>!!a)}get gainNodeList(){return Object.values(this.sourceNodeMap).map(a=>a.gainNode).filter(a=>!!a)}get sourceCount(){return this.sourceNodeList.length}resume(){var a;return(a=this.audioContext)==null?void 0:a.resume()}addTrack(a){this.connectTrack(a)}hasTrack(a){return!!this.sourceNodeMap[a]}removeTrack(a){const{sourceNode:e,gainNode:t}=this.sourceNodeMap[a]||{};t==null||t.disconnect(),e==null||e.disconnect(),delete this.sourceNodeMap[a],e?this.logger.info("SourceNode disconnected. Active source node:",this.sourceNodeList.length):this.logger.warn(`SourceNode ${a} does not exit. Active source node: ${this.sourceNodeList.length}`)}getAudioTrack(){return this.audioTrack}setVolume(a,e){const{gainNode:t}=this.sourceNodeMap[e]||{};t?(this.logger.info(`Setting node(${e}) volume to ${this.scale(a)}`),t.gain.value=this.scale(a)):this.logger.warn(`GainNode ${e} does not exit.`)}reset(){this.disconnectSourceNode(),this.sourceNodeMap={}}dispose(){var a;this.reset(),(a=this.audioTrack)==null||a.stop(),this.audioDestination.disconnect(),this.audioContext.close()}connectTrack(a){if(!this.audioContext)return this.logger.warn("AudioContext not initialized");let e=new MediaStream;e.addTrack(a);const t=this.audioContext.createMediaStreamSource(e),i=this.audioContext.createGain();i.gain.value=1,t.connect(i),i.connect(this.audioDestination),this.sourceNodeMap[a.id]={track:a,sourceNode:t,gainNode:i},this.logger.info("New sourceNode connected. Active source node:",this.sourceNodeList.length)}disconnectSourceNode(){this.sourceNodeList.forEach(a=>a.disconnect()),this.gainNodeList.forEach(a=>a.disconnect())}scale(a){return a/100}}class hc extends Dt{constructor(){super("audioMixer",Oe.AliRtcSdkStreamTypeCapture,oi.AUDIO);g(this,"audioMixer");g(this,"primaryAudioTrackId");g(this,"screenAudioTrackId");g(this,"dirty",!1);this.zIndex=8}get initOptions(){return{audio:1,screen:1}}setOptions(e){Object.entries(e).forEach(([t,i])=>{this.isValidVolume(i)&&(this.options[t]=i)}),this.dirty=!0,this.emit("updated")}isSupported(){return"AudioContext"in window}shouldUpdate(e,t){var n,c;if(e.type!==Oe.AliRtcSdkStreamTypeCapture)return!1;const i=t.find(o=>o.type===Oe.AliRtcSdkStreamTypeCapture),r=t.find(o=>o.type===Oe.AliRtcSdkStreamTypeScreen);return!(this.primaryAudioTrackId===((n=i==null?void 0:i.currentAudioTrack)==null?void 0:n.id)&&this.screenAudioTrackId===((c=r==null?void 0:r.currentAudioTrack)==null?void 0:c.id)&&!this.dirty)}process(e,t){return I(this,null,function*(){var c,o;this.dirty=!1;const i=t.find(l=>l.type===Oe.AliRtcSdkStreamTypeScreen),r=e.currentAudioTrack,n=i==null?void 0:i.currentAudioTrack;if(!n&&this.options.audio===1)return this.audioMixer&&(this.audioMixer.dispose(),this.audioMixer=void 0),this.primaryAudioTrackId=r==null?void 0:r.id,void e.updateAudioTrack(r);this.audioMixer||(this.audioMixer=new dc),yield this.audioMixer.resume(),this.primaryAudioTrackId&&(r==null?void 0:r.id)!==this.primaryAudioTrackId&&((c=this.audioMixer)==null||c.removeTrack(this.primaryAudioTrackId)),r&&!this.audioMixer.hasTrack(r==null?void 0:r.id)&&this.audioMixer.addTrack(r),this.primaryAudioTrackId=r==null?void 0:r.id,this.screenAudioTrackId&&(n==null?void 0:n.id)!==this.screenAudioTrackId&&((o=this.audioMixer)==null||o.removeTrack(this.screenAudioTrackId)),n&&!this.audioMixer.hasTrack(n==null?void 0:n.id)&&this.audioMixer.addTrack(n),this.screenAudioTrackId=n==null?void 0:n.id,this.updateVolume(),e.updateAudioTrack(this.audioMixer.getAudioTrack())})}isValidVolume(e){return e!==void 0&&e>=0&&e<=4}updateVolume(){this.audioMixer&&(this.primaryAudioTrackId&&this.audioMixer.setVolume(100*this.options.audio,this.primaryAudioTrackId),this.screenAudioTrackId&&this.audioMixer.setVolume(100*this.options.screen,this.screenAudioTrackId))}clear(e){var t;(t=this.audioMixer)==null||t.dispose(),super.clear(e)}}class uc extends Dt{constructor(){super(...arguments);g(this,"isProcessing",!1);g(this,"videoScaler")}get initOptions(){return{width:320,height:180,frameRate:15}}setOptions(e){var t;this.options=e,(t=this.videoScaler)==null||t.updateOptions(e)}isSupported(){return hr.isSupport()}shouldUpdate(e){const t=!!e.currentVideoTrack;return this.isProcessing!==t}process(e){return I(this,null,function*(){if(e.currentVideoTrack){if(this.isProcessing=!0,!this.videoScaler){const i=this.options||this.initOptions;this.videoScaler=hr.getInstance(e.currentVideoTrack,i)}const t=this.videoScaler.getVideoTrack();t&&e.updateDualVideoTrack(t)}else this.isProcessing&&this.clear()})}clear(e){var t;super.clear(e),this.isProcessing=!1,e==null||e.updateDualVideoTrack(),(t=this.videoScaler)==null||t.dispose()}}function ci(s,a,e,t){return new(e||(e=Promise))(function(i,r){function n(l){try{o(t.next(l))}catch(d){r(d)}}function c(l){try{o(t.throw(l))}catch(d){r(d)}}function o(l){var d;l.done?i(l.value):(d=l.value,d instanceof e?d:new e(function(h){h(d)})).then(n,c)}o((t=t.apply(s,a||[])).next())})}var Bt,Et;function cn(){return ci(this,void 0,void 0,function*(){let s=!1;try{s=yield(()=>I(this,null,function*(){return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}))()}catch(a){s=!1}return console.log("isSupportedSIMD",s),s})}typeof SuppressedError=="function"&&SuppressedError,(Et=Bt||(Bt={}))[Et.ERROR=0]="ERROR",Et[Et.WARN=1]="WARN",Et[Et.INFO=2]="INFO",Et[Et.LOG=3]="LOG",Et[Et.DEBUG=4]="DEBUG";class ve{static error(...a){var e;ve.logLevel>=Bt.ERROR&&((e=console.error)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static warn(...a){var e;ve.logLevel>=Bt.WARN&&((e=console.warn)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static info(...a){var e;ve.logLevel>=Bt.INFO&&((e=console.info)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static log(...a){var e;ve.logLevel>=Bt.LOG&&((e=console.log)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static debug(...a){var e;ve.logLevel>=Bt.DEBUG&&((e=console.debug)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}}ve.logLevel=Bt.WARN,ve.logTag="aliyun-audio-3a";class pc{}class ln extends pc{static isSupported(){return function(){if(typeof window=="object"&&window!==null){const a="AudioWorklet"in window,e="WebAssembly"in window;return a&&e}return!1}()}static isSupportedSIMD(){return ci(this,void 0,void 0,function*(){return yield cn()})}static setLogger(a){ve.logLevel=a}constructor(a){super(),this.channelCount=1,this.sampleRate=48e3,this.collectDumpOutputData=[],this.collectDumpNearInputData=[],this.collectDumpFarInputData=[],this.collectDumpMetaData=[],this.statUpdateTimer=0,this.statUpdateInterval=5e3,this.options=Object.assign({aecOn:!0,ansOn:!0,agcOn:!0,hdOn:!1,ansMode:1,dumpOn:!1,aiaecOn:!1,wasmCdnPath:"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"},a||{})}initWASM(a,e,t){return ci(this,void 0,void 0,function*(){ve.log("initWASM",a,e,t);const i=n=>ci(this,void 0,void 0,function*(){try{const c=yield fetch(n,{credentials:"same-origin"});return c.ok||this.onLoadError(new Error(`Failed to fetch WASM: ${c.status}:${c.statusText}, url:${n}`)),c.arrayBuffer()}catch(c){return this.onLoadError(new Error("WASM load error")),ve.error("Error fetching WASM:",c),new Uint8Array(0)}}),r=n=>ci(this,void 0,void 0,function*(){return fetch(n).then(c=>c.text())});try{const n=yield cn(),c=this.options.wasmCdnPath+"audio_module_v2.wasm",o=this.options.wasmCdnPath+"audio_module_v2_simd.wasm",d=yield i(n?o:c),h=this.options.wasmCdnPath+"audio_module_v2.js",p=this.options.wasmCdnPath+"audio_module_v2_simd.js",u=n?p:h,f=yield r(u);a.port.postMessage(Object.assign({type:"init",channelCount:e,sampleRate:t,wasmBuffer:d,isSupportSIMD:n,audioModuleScript:f,logLevel:ve.logLevel},this.options),[d])}catch(n){ve.error("Error initializing WASM:",n),this.onLoadError(new Error("WASM init error"))}a.port.onmessage=n=>{n.data.type==="init_done"&&this.onLoadSuccess(void 0),n.data.type==="dump_output_data"&&this.onDumpOutputData(n.data.data),n.data.type==="dump_near_data"&&this.onDumpNearInputData(n.data.data),n.data.type==="dump_far_data"&&this.onDumpFarInputData(n.data.data),n.data.type==="dump_meta_data"&&this.onDumpMeatData(n.data.data),n.data.type==="output_log"&&this.onOutputLog(n.data.data),n.data.type==="apm_stat_data"&&this.onStatData(n.data.data)}})}createProcessor(a,e,t,i,r){return ci(this,void 0,void 0,function*(){this.audioContext=a,this.audioContext.resume(),this.channelCount=t,this.sampleRate=i;try{const o=new Blob(['!function(){"use strict";var $c=Object.defineProperty,Kc=Object.defineProperties;var Jc=Object.getOwnPropertyDescriptors;var Xi=Object.getOwnPropertySymbols,Gc=Object.getPrototypeOf,xn=Object.prototype.hasOwnProperty,On=Object.prototype.propertyIsEnumerable,qc=Reflect.get;var Qr=(W,X,se)=>X in W?$c(W,X,{enumerable:!0,configurable:!0,writable:!0,value:se}):W[X]=se,G=(W,X)=>{for(var se in X||(X={}))xn.call(X,se)&&Qr(W,se,X[se]);if(Xi)for(var se of Xi(X))On.call(X,se)&&Qr(W,se,X[se]);return W},yt=(W,X)=>Kc(W,Jc(X));var Mt=(W,X)=>{var se={};for(var et in W)xn.call(W,et)&&X.indexOf(et)<0&&(se[et]=W[et]);if(W!=null&&Xi)for(var et of Xi(W))X.indexOf(et)<0&&On.call(W,et)&&(se[et]=W[et]);return se};var g=(W,X,se)=>(Qr(W,typeof X!="symbol"?X+"":X,se),se);var Zr=(W,X,se)=>qc(Gc(W),se,X);var I=(W,X,se)=>new Promise((et,ui)=>{var Mi=Ct=>{try{pi(se.next(Ct))}catch(ii){ui(ii)}},ti=Ct=>{try{pi(se.throw(Ct))}catch(ii){ui(ii)}},pi=Ct=>Ct.done?et(Ct.value):Promise.resolve(Ct.value).then(Mi,ti);pi((se=se.apply(W,X)).next())});function t(t,e,a,n){return new(a||(a=Promise))((function(s,i){function o(t){try{h(n.next(t))}catch(t){i(t)}}function r(t){try{h(n.throw(t))}catch(t){i(t)}}function h(t){var e;t.done?s(t.value):(e=t.value,e instanceof a?e:new a((function(t){t(e)}))).then(o,r)}h((n=n.apply(t,e||[])).next())}))}var e;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.ERROR=0]="ERROR",t[t.WARN=1]="WARN",t[t.INFO=2]="INFO",t[t.LOG=3]="LOG",t[t.DEBUG=4]="DEBUG"}(e||(e={}));class a{static error(...t){var n;a.logLevel>=e.ERROR&&(null===(n=console.error)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static warn(...t){var n;a.logLevel>=e.WARN&&(null===(n=console.warn)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static info(...t){var n;a.logLevel>=e.INFO&&(null===(n=console.info)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static log(...t){var n;a.logLevel>=e.LOG&&(null===(n=console.log)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static debug(...t){var n;a.logLevel>=e.DEBUG&&(null===(n=console.debug)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}}a.logLevel=e.WARN,a.logTag="aliyun-audio-3a";const n=Float32Array.BYTES_PER_ELEMENT,s=Uint16Array.BYTES_PER_ELEMENT;class i{constructor(t,e,a,n,s){this._channelData=[],this._name=t,this._isInitialized=!1,this._module=e,this._length=a,this._ringLength=2*a,this._maxChannelCount=s?Math.min(s,32):n,this._channelCount=n,this._allocateHeap(),this._isInitialized=!0,this._readIndex=0,this._writeIndex=0,this._framesAvailable=0,this._channelDataLocal=[];for(let t=0;t<this._channelCount;++t)this._channelDataLocal[t]=new Float32Array(this._ringLength)}_allocateHeap(){const t=this._length*n,e=this._channelCount*t;this._dataPtr=this._module._malloc(e),this._channelData=[];for(let e=0;e<this._channelCount;++e){const a=this._dataPtr+e*t,n=a+t;this._channelData[e]=this._module.HEAPF32.subarray(a>>s,n>>s)}}adaptChannel(t){t<this._maxChannelCount&&(this._channelCount=t)}get length(){return this._isInitialized?this._length:null}get numberOfChannels(){return this._isInitialized?this._channelCount:null}get maxChannelCount(){return this._isInitialized?this._maxChannelCount:null}getChannelData(t){return void 0!==t&&t>=this._channelCount?null:void 0===t?this._channelData:this._channelData[t]}getHeapAddress(){return this._dataPtr}getPointer(){return this._dataPtr}free(){this._isInitialized=!1,null!==this._dataPtr&&this._module._free(this._dataPtr),this._channelData=[]}get framesAvailable(){return this._framesAvailable}push(t){const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)this._channelDataLocal[e][this._writeIndex]=t[e][a];this._writeIndex=(this._writeIndex+1)%this._ringLength}this._framesAvailable+=e,this._framesAvailable>this._ringLength&&(console.warn(this._name,"Too many frames available, overflow"),this._framesAvailable=this._ringLength,this._writeIndex=0)}pull(t){if(0===this._framesAvailable)return void console.warn(this._name,"No frames available");const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)t[e][a]=this._channelDataLocal[e][this._readIndex];this._readIndex=(this._readIndex+1)%this._ringLength}this._framesAvailable-=e,this._framesAvailable<0&&(this._framesAvailable=0,this._readIndex=0)}}class o{constructor(t){this.inited=!1,this.handle=null,this.channelCount=1,this.isEnable=!0,this.dumpAudioData=!1,this.kernelBufferSize=512,this.node=t,this.onDumpOutputDataFunction=null,this.onDumpNearDataFunction=null,this.onDumpFarDataFunction=null,this.onDumpMetaDataFunction=null,this.wasmInvoker=null,this._nearAudioBuffer={},this._outputAudioBuffer={}}destructor(){this.wasmInvoker=null,this.handle=null}init(n){return t(this,void 0,void 0,(function*(){const{wasmBuffer:t,audioModuleScript:s,channelCount:o=1,sampleRate:r=44100,dumpAudioData:h=!1,logLevel:l=e.DEBUG}=n;a.logLevel=l,a.log("AudioAPM init",JSON.stringify(n)),this.channelCount=o,this.dumpAudioData=h;try{const e=new Function(`let module={};let exports={};${s}; return module`)();this.wasmInvoker=yield e.exports({wasmBinary:t})}catch(t){this.node.port.postMessage({type:"error",message:"audioModule init error"}),a.error(t)}this._nearAudioBuffer=new i("inBuffer",this.wasmInvoker,this.kernelBufferSize,2*this.channelCount,32),this._outputAudioBuffer=new i("outBuffer",this.wasmInvoker,this.kernelBufferSize,this.channelCount,32);const u=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=String.fromCharCode.apply(null,a);this.node&&this.node.port&&this.node.port.postMessage({type:"output_log",message:"output_log",data:n})}),"vii");if(this.wasmInvoker.__apm_log_callback(u),this.handle=this.wasmInvoker.__apm_create(n.aecOn?1:0,n.ansOn?1:0,n.agcOn?1:0,n.hdOn?1:0,r,o,n.dumpOn?1:0,this.kernelBufferSize),n.aiaecOn){const t=102;this.wasmInvoker.__apm_set_param(this.handle,t,7)}if(n.useHardOnly){const t=108;this.wasmInvoker.__apm_set_param(this.handle,t,1)}this.node.port.postMessage({type:"init_done",message:"init done"}),this.inited=!0}))}getStatData(){if(this.wasmInvoker&&this.isEnable){let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);this.wasmInvoker._free(t),this.node&&this.node.port&&this.node.port.postMessage({type:"apm_stat_data",message:"apm_stat_data",data:e})}}onOutputLog(t){console.log("[WASM_LOG]",t)}destory(){return t(this,void 0,void 0,(function*(){var t;try{null===(t=this.wasmInvoker)||void 0===t||t.__apm_destory(this.handle),this.inited=!1}catch(t){a.error(t)}finally{this.handle=null}}))}enable(){this.isEnable=!0,a.log("APM enable")}disable(){this.isEnable=!1,a.log("APM disable")}getStat(){if(null==this.wasmInvoker||null==this.handle)return"";let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);return this.wasmInvoker._free(t),e}startDump(){this.onDumpOutputDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_output_data",message:"dump_output_data",data:n})}),"vii"),this.onDumpNearDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_near_data",message:"dump_near_data",data:n})}),"vii"),this.onDumpFarDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_far_data",message:"dump_far_data",data:n})}),"vii"),this.onDumpMetaDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_meta_data",message:"dump_meta_data",data:n})}),"vii"),this.wasmInvoker.__apm_dump_start(this.handle,this.onDumpOutputDataFunction,this.onDumpNearDataFunction,this.onDumpFarDataFunction,this.onDumpMetaDataFunction)}stopDump(){this.wasmInvoker.__apm_dump_stop(this.handle),this.wasmInvoker&&(this.wasmInvoker.removeFunction(this.onDumpOutputDataFunction),this.wasmInvoker.removeFunction(this.onDumpNearDataFunction),this.wasmInvoker.removeFunction(this.onDumpFarDataFunction),this.wasmInvoker.removeFunction(this.onDumpMetaDataFunction))}process(t,e,a){if(!this.inited||!this.isEnable){for(let e=0;e<this.channelCount;e++){a[e].set(t[e])}return}const n=this.channelCount;let s=0;if(this.handle&&this.isEnable){const i=t[0].length,o=[];for(let a=0;a<n;a++)e[a]&&e[a].length>0&&(s=1),o.push(t[a]||new Float32Array(i).fill(0)),o.push(e[a]||new Float32Array(i).fill(0));if(this._nearAudioBuffer.push(o),this._nearAudioBuffer.framesAvailable>=this.kernelBufferSize){this._nearAudioBuffer.pull(this._nearAudioBuffer.getChannelData()),this.wasmInvoker.__apm_process_new(this.handle,this._nearAudioBuffer.getHeapAddress(),this._outputAudioBuffer.getHeapAddress(),n,s);const t=this._outputAudioBuffer.getChannelData();this._outputAudioBuffer.push(t)}this._outputAudioBuffer.pull(a)}}}class r extends AudioWorkletProcessor{constructor(){super(),this.apm=new o(this),this.port.onmessage=t=>{const e=t.data||{};switch(a.log("onmessage data",e),e.type){case"init":this.apm.init(e);break;case"destroy":this.apm.destory();break;case"enable":this.apm.enable();break;case"disable":this.apm.disable();break;case"start_dump":this.apm.startDump();break;case"stop_dump":this.apm.stopDump();break;case"get_stat_data":this.apm.getStatData();break;default:a.warn("Unknown message type:",e.type)}}}process(t,e){const a=t[0],n=t.length>1?t[1]:[],s=e[0];return this.apm.process(a,n,s),!0}}registerProcessor("aliyun-web-3a-processor",r)}();\n'],{type:"application/javascript"}),l=URL.createObjectURL(o);yield this.audioContext.audioWorklet.addModule(l)}catch(o){ve.error("Failed to add module to audio worklet:",o)}let n=new AudioWorkletNode(this.audioContext,"aliyun-web-3a-processor",{numberOfInputs:2,outputChannelCount:[t]});this.workletNode=n,e.connect(n),r&&(this.farNode=r,r.connect(n,0,1));const c=this.audioContext.createMediaStreamDestination();n.connect(c),this.targetMediaTrack=c.stream.getAudioTracks()[0],yield this.initWASM(n,t,i),this.statUpdateTimer=window.setInterval(()=>{this.getStatData()},this.statUpdateInterval)})}addFarNode(a){this.workletNode&&(this.farNode&&this.farNode.disconnect(this.workletNode),a&&(this.farNode=a,a.connect(this.workletNode,0,1)))}getStatData(){var a;try{(a=this.workletNode)===null||a===void 0||a.port.postMessage({type:"get_stat_data"})}catch(e){ve.error("Failed to post message to worklet node:",e)}}destroy(){if(this.statUpdateTimer&&window.clearInterval(this.statUpdateTimer),this.audioContext&&this.workletNode&&this.workletNode.port)try{this.workletNode.port.postMessage({type:"destroy"}),this.workletNode.port.onmessage=null,this.workletNode.disconnect(),ve.log("postMessage destroy")}catch(a){ve.error("Failed to post message to worklet node:",a)}}startDump(){var a;try{(a=this.workletNode)===null||a===void 0||a.port.postMessage({type:"start_dump"})}catch(e){ve.error("Failed to post message to worklet node:",e)}}stopDump(){var a;try{(a=this.workletNode)===null||a===void 0||a.port.postMessage({type:"stop_dump"})}catch(e){ve.error("Failed to post message to worklet node:",e)}setTimeout(()=>{this.onDumpOutputData(null,!0),this.onDumpNearInputData(null,!0),this.onDumpFarInputData(null,!0),this.onDumpMeatData(null,!0)},3e3)}onDumpOutputData(a,e=!1){if(a&&a.length>0&&this.collectDumpOutputData.push(a),e&&this.collectDumpOutputData.length>0||1024*this.collectDumpOutputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpOutputData);this.onDumpData(t,"output_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpOutputData=[]}}onDumpNearInputData(a,e=!1){if(a&&a.length>0&&this.collectDumpNearInputData.push(a),e&&this.collectDumpNearInputData.length>0||1024*this.collectDumpNearInputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpNearInputData);this.onDumpData(t,"near_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpNearInputData=[]}}onDumpFarInputData(a,e=!1){if(a&&a.length>0&&this.collectDumpFarInputData.push(a),e&&this.collectDumpFarInputData.length>0||1024*this.collectDumpFarInputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpFarInputData);this.onDumpData(t,"far_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpFarInputData=[]}}onDumpMeatData(a,e=!1){if(a&&a.length>0&&this.collectDumpMetaData.push(a),e&&this.collectDumpMetaData.length>0||1024*this.collectDumpMetaData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpMetaData);this.onDumpData(t,"meta_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpMetaData=[]}}getMaxDumpBytes(){return 600*Number(this.sampleRate.toFixed(0))*Number(this.channelCount.toFixed(0))*2}enable(){var a;if(!((a=this.workletNode)===null||a===void 0)&&a.port)try{this.workletNode.port.postMessage({type:"enable"}),ve.log("postMessage enable")}catch(e){ve.error("Failed to post message to worklet node:",e)}}disable(){var a;if(!((a=this.workletNode)===null||a===void 0)&&a.port)try{ve.log("postMessage disable"),this.workletNode.port.postMessage({type:"disable"})}catch(e){ve.error("Failed to post message to worklet node:",e)}}on(a,e){a==="loaderror"&&(this.onLoadError=e),a==="loadsuccess"&&(this.onLoadSuccess=e),a==="dumpdata"&&(this.onDumpData=e),a==="outputlog"&&(this.onOutputLog=e),a==="statdata"&&(this.onStatData=e)}onLoadError(a){console.log("onLoadError",a)}onLoadSuccess(a){console.log("onLoadSuccess",a)}onDumpData(a,e){console.log("onDumpData",a,e)}onOutputLog(a){console.log("[WASM]",a)}onStatData(a){console.log("onStatData:",a)}}class gc extends Dt{constructor(e){super("AliRtcAudioProcessPlugin",Oe.AliRtcSdkStreamTypeCapture,oi.AUDIO);g(this,"audioProcessor");g(this,"slsReporter");g(this,"enableSoft3ACheck",!1);g(this,"useHardOnly",!1);g(this,"lastDiffOutputLog","");g(this,"audioContext",new AudioContext({sampleRate:48e3}));g(this,"farNode");g(this,"createNode",e=>this.audioContext.createMediaStreamSource(new MediaStream([e])));this.options=e,this.slsReporter=e==null?void 0:e.slsReporter,this.enableSoft3ACheck=(e==null?void 0:e.enableSoft3ACheck)||!1,this.useHardOnly=(e==null?void 0:e.useHardOnly)||!1,this.zIndex=7,document.addEventListener("click",this.activeAudioContext)}activeAudioContext(){var e;(e=this.audioContext)==null||e.resume(),document.removeEventListener("click",this.activeAudioContext)}audioUpdated(e){var t,i;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((i=e.currentAudioTrack)==null?void 0:i.id)}videoUpdated(e){return console.log("videoUpdated",e),!1}setOptions(e){var t;!this.farNode&&e.farMediaStream&&(this.farNode=this.audioContext.createMediaStreamSource(e.farMediaStream),this.audioProcessor&&((t=this.audioProcessor)==null||t.addFarNode(this.farNode)),this.options=G(G({},this.options),e))}isSupported(){return ln.isSupported()}shouldUpdate(e){return!!(e.originAudioTrack&&!this.audioProcessor||!e.originAudioTrack&&this.audioProcessor)}process(e){return I(this,null,function*(){var t;if(!e.currentAudioTrack)return e.updateAudioTrack(),void this.clear(e);if(!this.audioProcessor){this.audioProcessor=new ln({aecOn:!0,ansOn:!0,agcOn:!0,dumpOn:((t=this.options)==null?void 0:t.dumpAudioData)||!1,aiaecOn:this.options.aiaecOn||!1,useHardOnly:this.useHardOnly,wasmCdnPath:this.options.wasmCdnPath||"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"}),this.audioProcessor.on("dumpdata",(r,n)=>{let c=3e3;n.includes("far")?c=5e3:n.includes("output")?c=1e4:n.includes("meta")&&(c=8e3),setTimeout(()=>{const o=URL.createObjectURL(r),l=document.createElement("a");l.href=o,l.download=n,document.body.appendChild(l),l.click(),document.body.removeChild(l)},c)}),this.audioProcessor.on("loadsuccess",()=>{var r,n;this.enableSoft3ACheck||e.updateAudioTrack((r=this.audioProcessor)==null?void 0:r.targetMediaTrack),this.options.dumpAudioData&&((n=this.audioProcessor)==null||n.startDump())}),this.audioProcessor.on("loaderror",r=>{this.emit("error",r)}),this.audioProcessor.on("outputlog",r=>{r!=null&&r.includes("diff")&&(this.lastDiffOutputLog=r||"")}),this.audioProcessor.on("statdata",r=>{var n;if(r)try{let c=r;if(this.lastDiffOutputLog){const o=this.extractDiffValue(this.lastDiffOutputLog),l=JSON.parse(r);o!==null&&(l.diff=o);const d=this.extractLeakValue(this.lastDiffOutputLog);d!==null&&(l.leak=d),c=JSON.stringify(l)}(n=this.slsReporter)==null||n.reportPublishAudio3A("","","",c)}catch(c){}});const i=this.createNode(e.currentAudioTrack);yield this.audioProcessor.createProcessor(this.audioContext,i,1,48e3,this.farNode)}})}extractDiffValue(e){if(!e)return null;const t=e.match(/diff\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}extractLeakValue(e){if(!e)return null;const t=e.match(/leak\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}clear(e){var t,i,r;this.options.dumpAudioData&&((t=this.audioProcessor)==null||t.stopDump()),super.clear(e),(i=this.audioProcessor)==null||i.destroy(),this.audioProcessor=void 0,document.removeEventListener("click",this.activeAudioContext),(r=this.farNode)==null||r.disconnect(),this.farNode=void 0}dump(){var e;(e=this.audioProcessor)==null||e.stopDump()}}var Ai=(s=>(s[s.Default=0]="Default",s[s.Human=1]="Human",s[s.Robot=2]="Robot",s))(Ai||{}),mc=Object.defineProperty,fc=Object.getOwnPropertyDescriptor,dn=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?fc(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&mc(a,e,r),r};const Nr=(Ft=class extends se{constructor(e,t){super();g(this,"self");g(this,"remoteUser");g(this,"sendReadyMsg",!1);g(this,"hasPubDataChannel",!1);g(this,"hasSubDataChannel",!1);g(this,"readyMsgSuccess",!1);g(this,"sendReadyMsgTimer");g(this,"startReadyMsgTime");g(this,"robotUserId");g(this,"onSubscribeDataChannel",e=>{!this.remoteUser&&e&&(this.robotUserId&&this.robotUserId!==e.userId||(this.hasSubDataChannel=!0,this.remoteUser=e,this.remoteUser.on("remoteDataChannelMessage",this.onCheckReadyMsg),this.trySendReadyMsg()))});g(this,"onCheckReadyMsg",(e,t)=>{var i,r;if(this.sendReadyMsg&&!this.readyMsgSuccess)try{const n=new TextDecoder().decode(t.data),c=JSON.parse(n);c.key==="aliyun_aigc"&&c.type==="ready_resp"&&((i=c.data)==null?void 0:i.ready)===!0&&(N.event(`[${Ft.logName}]`,"onCheckReadyMsg success"),this.readyMsgSuccess=!0,this.emit("dcready",e),(r=this.remoteUser)==null||r.off("remoteDataChannelMessage",this.onCheckReadyMsg),window.clearTimeout(this.sendReadyMsgTimer))}catch(n){}});g(this,"onDataPublishStateChange",(e,t)=>{t===te.AliRtcStatePublished&&(this.hasPubDataChannel=!0,this.trySendReadyMsg())});this.self=e,this.self.on("dataPublishStateChanged",this.onDataPublishStateChange),this.robotUserId=t}destroy(){this.self.off("dataPublishStateChanged",this.onDataPublishStateChange),window.clearTimeout(this.sendReadyMsgTimer),this.remoteUser=void 0,this.sendReadyMsg=!1,this.hasPubDataChannel=!1,this.hasSubDataChannel=!1,this.readyMsgSuccess=!1,this.startReadyMsgTime=0}trySendReadyMsg(){N.event(`[${Ft.logName}]`,`trySendReadyMsg: pub(${this.hasPubDataChannel}, sub: ${this.hasSubDataChannel})`),this.hasPubDataChannel&&this.hasSubDataChannel&&(this.sendReadyMsg=!0,this.sendReadyMsgLoop())}sendReadyMsgLoop(e=0){return I(this,null,function*(){const t=JSON.stringify({key:"aliyun_aigc",version:"1.0",type:"ready_req",data:{ready:!0}});try{this.self.sendDataChannelMessage(new Vt(new TextEncoder().encode(t).buffer))}catch(n){}this.startReadyMsgTime||(this.startReadyMsgTime=Date.now());let i=50;const r=Date.now()-this.startReadyMsgTime;i=r<1e3?50:r<2e3?100:r<3e3?500:2e3,e>30?N.event(`[${Ft.logName}]`,"sendReadyMsgLoop fail after 30 times"):this.sendReadyMsgTimer=window.setTimeout(()=>{this.sendReadyMsgLoop(e+1)},i)})}},g(Ft,"logName","DataChannelReadyHelper"),Ft);dn([C()],Nr.prototype,"destroy",1),dn([C()],Nr.prototype,"sendReadyMsgLoop",1);let Sc=Nr;class bc{constructor(a){g(this,"_useSysEchoCancellation",!0);g(this,"_useSysNoiseSuppression",!0);g(this,"_useSysAutoGainControl",!0);g(this,"_useAIAEC",!1);g(this,"_enableSoft3A",!1);g(this,"_enableSoft3ACheck",!1);g(this,"_useHardOnly",!1);g(this,"_dumpAudioData",!1);g(this,"_useAudio3AConfigFromServer",!0);a&&Object.assign(this,a)}get useSysEchoCancellation(){return this._useSysEchoCancellation}set useSysEchoCancellation(a){this._useSysEchoCancellation=a}get useSysNoiseSuppression(){return this._useSysNoiseSuppression}set useSysNoiseSuppression(a){this._useSysNoiseSuppression=a}get useSysAutoGainControl(){return this._useSysAutoGainControl}set useSysAutoGainControl(a){this._useSysAutoGainControl=a}get useAIAEC(){return this._useAIAEC}set useAIAEC(a){this._useAIAEC=a}get enableSoft3A(){return this._enableSoft3A}set enableSoft3A(a){this._enableSoft3A=a}get enableSoft3ACheck(){return this._enableSoft3ACheck}set enableSoft3ACheck(a){this._enableSoft3ACheck=a}get useHardOnly(){return this._useHardOnly}set useHardOnly(a){this._useHardOnly=a}get dumpAudioData(){return this._dumpAudioData}set dumpAudioData(a){this._dumpAudioData=a}get useAudio3AConfigFromServer(){return this._useAudio3AConfigFromServer}set useAudio3AConfigFromServer(a){this._useAudio3AConfigFromServer=a}loadFromLocalConfig(a){var e,t,i,r,n,c,o,l,d;this.useAudio3AConfigFromServer=(e=a.useAudio3AConfigFromServer)!=null?e:this.useAudio3AConfigFromServer,this.useSysEchoCancellation=(t=a.useSysEchoCancellation)!=null?t:this.useSysEchoCancellation,this.useSysNoiseSuppression=(i=a.useSysNoiseSuppression)!=null?i:this.useSysNoiseSuppression,this.useSysAutoGainControl=(r=a.useSysAutoGainControl)!=null?r:this.useSysAutoGainControl,this.useAIAEC=(n=a.useAIAEC)!=null?n:this.useAIAEC,this.enableSoft3A=(c=a.enableSoft3A)!=null?c:this.enableSoft3A,this.dumpAudioData=(o=a.dumpAudioData)!=null?o:this.dumpAudioData,this.enableSoft3ACheck=(l=a.enableSoft3ACheck)!=null?l:this.enableSoft3ACheck,this.useHardOnly=(d=a.useHardOnly)!=null?d:this.useHardOnly}loadFromServerConfig(a){if(a&&typeof a=="object"){const e=Kt(a,"enableSoft3A"),t=si(a,"enableSoft3A");if(e===!0&&t===!0&&(this.enableSoft3A=!0),this.enableSoft3A){if(a.archCfgs){const i=Kt(a,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const r=Kt(a,"useAIAEC");r!==void 0&&(this.useAIAEC=r);const n=Kt(a,"useSysNoiseSuppression");n!==void 0&&(this.useSysNoiseSuppression=n);const c=Kt(a,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=Kt(a,"useSysAutoGainControl");o!==void 0&&(this.useSysAutoGainControl=o)}if(a.config){const i=si(a,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const r=si(a,"useAIAEC");r!==void 0&&(this.useAIAEC=r);const n=si(a,"useSysNoiseSuppression");n!==void 0&&(this.useSysNoiseSuppression=n);const c=si(a,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=si(a,"useSysAutoGainControl");o!==void 0&&(this.useSysAutoGainControl=o)}N.info("setAudio3AConfig:","enableSoft3A",this.enableSoft3A,", enableSoft3ACheck",this.enableSoft3ACheck,", useAIAEC",this.useAIAEC,", useSysNoiseSuppression",this.useSysNoiseSuppression,", useSysEchoCancellation",this.useSysEchoCancellation,", useSysAutoGainControl",this.useSysAutoGainControl)}}}}var vc=Object.defineProperty,yc=Object.getOwnPropertyDescriptor,it=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?yc(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&vc(a,e,r),r};class Xe extends se{constructor(e){super();g(this,"self");g(this,"userMap",{});g(this,"usersViewMap",{});g(this,"rtsManager");g(this,"localStreamManager");g(this,"authInfo");g(this,"signalingManager");g(this,"pluginManager");g(this,"audioMixerPlugin");g(this,"dualVideoPlugin");g(this,"blankAudioPlugin");g(this,"audioProcessorPlugin");g(this,"slsReporter");g(this,"statsMonitorId");g(this,"autoSubAudio",!0);g(this,"autoSubVideo",!0);g(this,"autoSubScreen",!0);g(this,"wantSubAudio",!0);g(this,"wantSubVideo",!0);g(this,"wantSubScreen",!0);g(this,"defaultStreamType",Ke.AliRtcVideoStreamTypeHigh);g(this,"audioMuted",!1);g(this,"playoutVolume",1);g(this,"refreshUrlTimer");g(this,"audioVolumeIndicationInterval",0);g(this,"indicationTimer",0);g(this,"parameter",{});g(this,"audio3AConfig",new bc);g(this,"dcReadyHelper");const{signalingManager:t,slsReporter:i,parameter:r}=e;this.signalingManager=t,this.addSignalingManagerListener(),this.slsReporter=i,r&&(this.parameter=r),this.pluginManager=new ec,this.localStreamManager=new nc(this.pluginManager,this.slsReporter),this.rtsManager=new rc(this.localStreamManager,this.slsReporter,this.parameter),this.addRTSListener(),this.self=new Go({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,slsReporter:this.slsReporter,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,parameter:this.parameter}),this.audioMixerPlugin=new hc,this.pluginManager.add(this.audioMixerPlugin),this.dualVideoPlugin=new uc("dualVideoPlugin"),new X.AliRTS.SupportUtil().checkScreenCapture()&&this.pluginManager.add(new cc)}addSignalingManagerListener(){this.signalingManager.on("onNotifyPublish",e=>{e.forEach(t=>{var i;(i=t==null?void 0:t.tracks)==null||i.forEach(r=>{var n;if(r.msid===M.Audio&&r.userdata)try{const c=JSON.parse(r.userdata);c.agent_instance&&((n=this.slsReporter)==null||n.setCustomFields({ageniid:c.agent_instance}))}catch(c){console.error("Failed to parse userdata:",c)}})}),this.slsReporter.reportConnectionLatencyEvent(ot.RECV_NOTIFY_PUBLISH,"","",""),N.event("[Signaling] Notify Publish ",e),e.forEach(t=>{this.onRemotePublishStateChange(t)})}),this.signalingManager.stsManager.on("onTokenUpdate",(e,t)=>{this.slsReporter.updateToken(t,e)})}addRTSListener(){this.rtsManager.on("traceIdUpdated",(e,t)=>{if(Ne.removeQueryString(this.self.url)===Ne.removeQueryString(e))return void(this.self.traceId=t);const i=this.remoteUsers.find(r=>Ne.removeQueryString(r.streamUrl)===Ne.removeQueryString(e));i&&(i.traceId=t)}),this.rtsManager.on("reconnect",(e,t,i)=>{if(!e||e==="pc"||e==="all")return this.self.markReconnect(),void this.remoteUsers.forEach(n=>{n.markReconnect()});if(e==="pub"||e==="pub-data")return void this.self.markReconnect(i);const r=this.remoteUsers.find(n=>Ne.removeQueryString(n.streamUrl)===Ne.removeQueryString(t||""));r==null||r.markReconnect(i)}),this.rtsManager.on("reconnectFinish",(e,t,i)=>{if(N.event("[RtsManager]","reconnectFinish",e,t,i),!e||e==="pc"||e==="all")return this.self.markReconnected(),void this.remoteUsers.forEach(n=>{n.markReconnected()});if(e==="pub"||e==="pub-data")return void this.self.markReconnected(i);const r=this.remoteUsers.find(n=>Ne.removeQueryString(n.streamUrl)===Ne.removeQueryString(t||""));r==null||r.markReconnected(i)})}isAutoSubAudio(){return this.autoSubAudio}setAutoSubAudio(e){this.autoSubAudio=e}isAutoSubVideo(){return this.autoSubVideo}setAutoSubVideo(e){this.autoSubVideo=e}isAutoSubScreen(){return this.autoSubScreen}setAutoSubScreen(e){this.autoSubScreen=e}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e,this.remoteUsers.forEach(t=>{t.setWantSubAudio(e),t.updateSubscribe(be.User)})}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e,this.remoteUsers.forEach(t=>{t.setWantSubVideo(e),t.updateSubscribe(be.User)})}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e,this.remoteUsers.forEach(t=>{t.setWantSubScreen(e),t.updateSubscribe(be.User)})}setRemoteDefaultVideoStreamType(e){this.defaultStreamType=e,this.remoteUsers.forEach(t=>{t.setRemoteDefaultVideoStreamType(e)})}setRemoteUserVideoStreamType(e,t){var i;(i=this.getRemoteUser(e))==null||i.setRemoteDefaultVideoStreamType(t)}setAudioMuted(e){this.audioMuted=e,this.remoteUsers.forEach(t=>{t.setAudioMuted(e)})}setLocalViewConfig(e,t){if(!e)return this.publisher.setViewConfig(null,t);const i=cr(e);i.length!==0&&i.forEach(r=>{this.publisher.resetElement(r),Object.values(this.usersViewMap).forEach(({cameraViews:n=[],screenViews:c=[]})=>{n.includes(r)&&n.splice(n.indexOf(r),1),c.includes(r)&&c.splice(c.indexOf(r),1)}),this.publisher.setViewConfig(i,t)})}setRemoteViewConfig(e,t,i){var n,c;if(!t)return(n=this.userMap[e])==null?void 0:n.setViewConfig(null,i);const r=cr(t);r.length!==0&&(r.forEach(o=>{this.publisher.resetElement(o),Object.values(this.usersViewMap).forEach(({cameraViews:l=[],screenViews:d=[]})=>{l.includes(o)&&l.splice(l.indexOf(o),1),d.includes(o)&&d.splice(d.indexOf(o),1)})}),(c=this.userMap[e])==null||c.setViewConfig(r,i))}get channel(){var e;return(e=this.authInfo)==null?void 0:e.channelId}get userId(){var e;return(e=this.authInfo)==null?void 0:e.userId}get remoteUsers(){return Object.values(this.userMap)}get publisher(){return this.self}get isSubscribing(){var e;return((e=this.remoteUsers)!=null?e:[]).some(t=>{const{isAudioSubscribing:i,isVideoSubscribing:r,isScreenSubscribing:n}=t;return i||r||n})}onRemotePublishStateChange(e,t=!0){var u;const{userid:i,callid:r,subscribe:n,pubid:c="",tracks:o}=e,l=(u=n==null?void 0:n.pullstreamurl)!=null?u:"";let d=this.getRemoteUser(i);if(!d)return;const h=d.streamInfo.audioTrackInfo,p=d.streamInfo.videoTrackInfo;d.updateRemoteTracks(r,l,c,o),h===d.streamInfo.audioTrackInfo&&p===d.streamInfo.videoTrackInfo||this.emit("remoteTrackAvailableChange",i,d.streamInfo.audioTrackInfo,d.streamInfo.videoTrackInfo),t&&d.updateSubscribe(be.Publish)}setTimeoutToUpdateAllStreamUrls(e){var r;if(!e)return;let t=354e4;const i=(r=function(n){var c,o;try{const l=new URL(n),[d,h]=l.pathname.slice(1).split("/"),p=/(\w+)(web\w{5}-\w{4}-\w{4}-\w{4}-\w{12})/.exec(h),u=p==null?void 0:p[1],f=p==null?void 0:p[2],m=new URLSearchParams(l.search);return{appId:d,channelId:u,sessionId:f,timeoutTs:1e3*parseInt((o=(c=m.get("auth_key"))==null?void 0:c.split("-")[0])!=null?o:"0")}}catch(l){return null}}(e))==null?void 0:r.timeoutTs;i&&(t=i-Date.now()-6e4),this.refreshUrlTimer=window.setTimeout(()=>I(this,null,function*(){var c;const n=yield this.signalingManager.refreshUrl({pushstreamurl:this.self.url,users:this.remoteUsers.map(o=>({userid:o.userId,subscribe:{pullstreamurl:o.streamUrl}}))});n.pushstreamurl&&(this.self.url=n.pushstreamurl),(c=n.users)==null||c.forEach(o=>{var d;const l=this.getRemoteUser(o.userid);l&&((d=o.subscribe)!=null&&d.pullstreamurl)&&(l.streamUrl=o.subscribe.pullstreamurl)}),this.setTimeoutToUpdateAllStreamUrls(n.pushstreamurl)}),t)}init(e,t,i){var r;this.authInfo=e,this.self.enableAudioVolumeIndication(this.audioVolumeIndicationInterval),this.self.initInfo(e,t.pushstreamurl),this.audio3AConfig.useAudio3AConfigFromServer&&this.audio3AConfig.loadFromServerConfig((r=t==null?void 0:t.config)==null?void 0:r.data),this.setupAudioProcessingPluginIfNeeded(),i.capabilityProfile===Ai.Human&&(this.dcReadyHelper=new Sc(this.self,i.robotUserId),this.dcReadyHelper.on("dcready",n=>{var c;this.emit("remoteUserSubscribedDataChannel",n),(c=this.dcReadyHelper)==null||c.destroy(),this.dcReadyHelper=void 0})),this.setTimeoutToUpdateAllStreamUrls(t.pushstreamurl),t.users.forEach(n=>{this.addUser(n,be.InRoom)}),this.startStatsMonitor()}leave(){return I(this,null,function*(){var e;this.stopStatsMonitor(),this.refreshUrlTimer!==void 0&&(window.clearTimeout(this.refreshUrlTimer),this.refreshUrlTimer=void 0),Object.values(this.usersViewMap).forEach(({cameraViews:t=[],screenViews:i=[]})=>{t.forEach(r=>{r.srcObject=null,r._playPromise=void 0}),i.forEach(r=>{r.srcObject=null,r._playPromise=void 0})}),this.usersViewMap={};for(let t in this.userMap)this.userMap[t]&&(this.userMap[t].clear(),delete this.userMap[t]);this.self.leave(),(e=this.dcReadyHelper)==null||e.destroy(),this.dcReadyHelper=void 0,this.localStreamManager.stop(),this.rtsManager.clear(),this.authInfo=void 0})}clear(){return I(this,null,function*(){yield this.leave(),this.self.clear(),this.pluginManager.removeAll()})}startStatsMonitor(){this.statsMonitorId=window.setInterval(()=>I(this,null,function*(){if(this.publisher){const{audio:i,video:r,candidate:n}=yield this.publisher.getStats();i&&i.length>0&&this.emit("rtcLocalAudioStats",i),r&&r.length>0&&this.emit("rtcLocalVideoStats",r),n&&this.emit("rtcStats",n)}const e=[],t=[];for(const i of this.remoteUsers){const{audio:r,video:n}=yield i.getStats();r&&r.forEach(c=>{e.push(c)}),n&&n.forEach(c=>{t.push(c)})}e.length>0&&this.emit("rtcRemoteAudioStats",e),t.length>0&&this.emit("rtcRemoteVideoStats",t)}),2e3)}stopStatsMonitor(){this.statsMonitorId&&clearInterval(this.statsMonitorId)}addUser(e,t){const i=e.userid;let r=this.userMap[i];return r||(r=this.executeAddUser(i,e.displayname||"",t),this.userMap[i]=r,this.emit("remoteUserJoin",i,0)),this.onRemotePublishStateChange(e,t!==be.InRoom),r}executeAddUser(e,t,i){const r=new Zo({userId:e,displayName:t,rtsManager:this.rtsManager,signalingManager:this.signalingManager,usersViewMap:this.usersViewMap,slsReporter:this.slsReporter,localUser:this.self,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,playoutVolume:this.playoutVolume,parameter:this.parameter});return r.on(Qe.Remote,this.onRemoteDeviceStatusChange.bind(this)),r.on(Ce.PullStreamStats,this.onRemoteStatReport.bind(this)),r.on(Ce.RtsSubscribeExceeds,this.onSubscribeExceeds.bind(this)),r.on("audioSubscribeStateChanged",(n,c,o,l)=>{this.emit("audioSubscribeStateChanged",n,c,o,l,this.channel||"")}),r.on("videoSubscribeStateChanged",(n,c,o,l)=>{this.emit("videoSubscribeStateChanged",n,c,o,l,this.channel||"")}),r.on("screenSubscribeStateChanged",(n,c,o,l)=>{this.emit("screenSubscribeStateChanged",n,c,o,l,this.channel||"")}),r.on("dataSubscribeStateChanged",(n,c,o,l)=>{var d;o===ae.AliRtcStateSubscribed&&((d=this.dcReadyHelper)==null||d.onSubscribeDataChannel(this.userMap[n])),this.emit("dataSubscribeStateChanged",n,c,o,l,this.channel||"")}),r.on("remoteAudioAutoPlayFail",n=>{this.emit("remoteAudioAutoPlayFail",n)}),r.on("remoteVideoAutoPlayFail",(n,c)=>{this.emit("remoteVideoAutoPlayFail",n,c)}),r.on("remoteAudioPlayError",(n,c)=>{this.emit("remoteAudioPlayError",n,c)}),r.on("remoteVideoPlayError",(n,c)=>{this.emit("remoteVideoPlayError",n,c)}),r.on("remoteSubscribeError",n=>{this.emit("remoteSubscribeError",n,r.userId)}),r.on("occurError",n=>{this.emit("occurError",n,r.userId)}),r.on("remoteDataChannelMessage",(n,c)=>{this.emit("remoteDataChannelMessage",n,c)}),r.setWantSubAudio(this.autoSubAudio&&this.wantSubAudio),r.setWantSubVideo(this.autoSubVideo&&this.wantSubVideo),r.setWantSubScreen(this.autoSubScreen&&this.wantSubScreen),r.setRemoteDefaultVideoStreamType(this.defaultStreamType),r.setAudioMuted(this.audioMuted),(this.autoSubAudio||this.autoSubVideo||this.autoSubScreen)&&r.updateSubscribe(i),r}onRemoteDeviceStatusChange(e,t){e===Ce.MuteAudio?this.emit("userAudioMuted",t,!0):e===Ce.UnmuteAudio?this.emit("userAudioMuted",t,!1):e===Ce.MuteVideo?this.emit("userVideoMuted",t,!0):e===Ce.UnmuteVideo?this.emit("userVideoMuted",t,!1):e===Ce.MuteScreen?this.emit("userScreenMuted",t,!0):e===Ce.UnmuteScreen&&this.emit("userScreenMuted",t,!1)}onRemoteStatReport(e,t,i){this.emit(Ce.PullStreamStats,e,t,i)}onSubscribeExceeds(e,t){this.emit(Ce.RtsSubscribeExceeds,e,t)}removeLeftUser(e){return I(this,null,function*(){e.userid&&this.userMap[e.userid]&&(yield this.userMap[e.userid].clear(!1),delete this.userMap[e.userid])})}diffUsers(e){const t=[],i=[];e.forEach(n=>{n.userid&&(this.userMap[n.userid]?i.push(n):t.push(n))});const r=Object.keys(this.userMap).filter(n=>!e.find(c=>c.userid===n)).map(n=>({userid:n,reason:"",leavecode:or.AliRtcUserOfflineQuit}));return{joinList:t,leaveList:r,presentList:i}}getRemoteUser(e){return this.userMap[e]}updateRemoteUserDeviceStatus(e){e&&e.userid&&this.userMap[e.userid]&&this.userMap[e.userid].updateRemoteUserDeviceStatus(e.status)}updateAudioWant(e,t){const i=this.userMap[e];if(!i)throw new V(U.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubAudio(t),t?i.updateSubscribe(be.User):i.stopSubscribe({audio:!0})}updateVideoWant(e,t){const i=this.userMap[e];if(!i)throw new V(U.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubVideo(t),t?i.updateSubscribe(be.User):i.stopSubscribe({video:!0})}updateScreenWant(e,t){const i=this.userMap[e];if(!i)throw new V(U.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubScreen(t),t?i.updateSubscribe(be.User):i.stopSubscribe({screen:!0})}stopIndication(){this.indicationTimer&&window.clearInterval(this.indicationTimer)}startIndication(e){this.stopIndication(),this.indicationTimer=window.setInterval(()=>{const t=this.remoteUsers.map(i=>({userId:i.userId,volume:i.getAudioLevel()||0}));t.unshift({userId:"",volume:this.self.getAudioLevel()||0}),this.emit("audioVolume",t)},e)}setEnableDualVideoStream(e,t){if(!this.dualVideoPlugin)return;t&&this.dualVideoPlugin.setOptions(t);const i=this.pluginManager.has(this.dualVideoPlugin.name);e?!i&&this.pluginManager.add(this.dualVideoPlugin):i&&this.pluginManager.remove(this.dualVideoPlugin.name)}setAudioVolume(e){var t;(t=this.audioMixerPlugin)==null||t.setOptions(e)}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.stopIndication(),e>0&&this.startIndication(e),this.audioVolumeIndicationInterval=e,this.remoteUsers.forEach(t=>{t.enableAudioVolumeIndication(e)}),this.self.enableAudioVolumeIndication(e))}setPlayoutVolume(e){this.playoutVolume=e,this.remoteUsers.forEach(t=>{t.setPlayoutVolume(e)})}refreshAuthInfo(e){this.authInfo&&(this.authInfo=G(G({},this.authInfo),e)),e.userId&&this.self.refreshUserInfo(e.userId)}setEnableMediaExtensionMsg(e){this.rtsManager.setEncodedInsertableStreams(e)}setAudioRedEnabled(e){this.rtsManager.setAudioRedEnabled(e)}setVideoCodec(e){this.rtsManager.changeVideoCodec(e)}setParameter(e){var i,r,n,c;const t=JSON.parse(e);Object.keys(t).forEach(o=>{const l=this.parameter[o],d=t[o];this.parameter[o]=typeof l=="object"&&typeof d=="object"?G(G({},l),d):d}),t.enableBlankAudio===!0?(this.blankAudioPlugin||(this.blankAudioPlugin=new lc),this.pluginManager.has((i=this.blankAudioPlugin)==null?void 0:i.name)||this.pluginManager.add(this.blankAudioPlugin)):t.enableBlankAudio===!1&&(this.blankAudioPlugin&&this.pluginManager.remove((r=this.blankAudioPlugin)==null?void 0:r.name),(n=this.blankAudioPlugin)==null||n.clear(),this.blankAudioPlugin=void 0),t.audio&&((c=this.audio3AConfig)==null||c.loadFromLocalConfig(t.audio))}setupAudioProcessingPluginIfNeeded(){if(this.audio3AConfig.enableSoft3A){let e=0;this.audio3AConfig.enableSoft3ACheck&&(e=1e4),setTimeout(()=>{this.audioProcessorPlugin||(this.audioProcessorPlugin=new gc({dumpAudioData:this.audio3AConfig.dumpAudioData,aiaecOn:this.audio3AConfig.useAIAEC,slsReporter:this.slsReporter,enableSoft3ACheck:this.audio3AConfig.enableSoft3ACheck,useHardOnly:this.audio3AConfig.useHardOnly})),this.audioProcessorPlugin&&!this.pluginManager.has(this.audioProcessorPlugin.name)&&(this.audioProcessorPlugin.on("error",({message:t})=>{var i;N.error("audioProcessorPlugin error:",t),(i=this.self.audioTrack)==null||i.applyConstraints({echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0})}),this.pluginManager.add(this.audioProcessorPlugin))},e)}else this.audioProcessorPlugin&&(this.pluginManager.remove(this.audioProcessorPlugin.name),this.audioProcessorPlugin=void 0);this.self.setMicrophoneConstraints({echoCancellation:this.audio3AConfig.useSysEchoCancellation,noiseSuppression:this.audio3AConfig.useSysNoiseSuppression,autoGainControl:this.audio3AConfig.useSysAutoGainControl})}getParameter(){return JSON.stringify(this.parameter)}sendDataChannelMessage(e){return this.self.sendDataChannelMessage(e)}}g(Xe,"logName","BizControl"),it([C()],Xe.prototype,"init",1),it([C()],Xe.prototype,"leave",1),it([C()],Xe.prototype,"clear",1),it([C(B)],Xe.prototype,"addUser",1),it([C()],Xe.prototype,"removeLeftUser",1),it([C()],Xe.prototype,"diffUsers",1),it([C(B)],Xe.prototype,"updateAudioWant",1),it([C(B)],Xe.prototype,"updateVideoWant",1),it([C(B)],Xe.prototype,"updateScreenWant",1),it([C()],Xe.prototype,"stopIndication",1),it([C()],Xe.prototype,"startIndication",1),it([C(B)],Xe.prototype,"setEnableDualVideoStream",1),it([C(B)],Xe.prototype,"setAudioVolume",1),it([C()],Xe.prototype,"enableAudioVolumeIndication",1);var _i=(s=>(s[s.LiveTranscodingSingle=0]="LiveTranscodingSingle",s[s.LiveTranscodingMix=1]="LiveTranscodingMix",s))(_i||{}),xr=(s=>(s[s.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",s[s.LiveTranscodingAudio=1]="LiveTranscodingAudio",s[s.LiveTranscodingVideo=2]="LiveTranscodingVideo",s))(xr||{}),li=(s=>(s[s.LiveTranscodingCamera=0]="LiveTranscodingCamera",s[s.LiveTranscodingShareScreen=1]="LiveTranscodingShareScreen",s))(li||{});const wi={0:"camera",1:"shareScreen"};var Or=(s=>(s[s.LiveTranscoding_Profile_1IN_1080P=0]="LiveTranscoding_Profile_1IN_1080P",s[s.LiveTranscoding_Profile_1IN_720P=1]="LiveTranscoding_Profile_1IN_720P",s[s.LiveTranscoding_Profile_1IN_360P=2]="LiveTranscoding_Profile_1IN_360P",s[s.LiveTranscoding_Profile_2IN_1080P=3]="LiveTranscoding_Profile_2IN_1080P",s[s.LiveTranscoding_Profile_2IN_720P=4]="LiveTranscoding_Profile_2IN_720P",s[s.LiveTranscoding_Profile_2IN_360P=5]="LiveTranscoding_Profile_2IN_360P",s[s.LiveTranscoding_Profile_4IN_1080P=6]="LiveTranscoding_Profile_4IN_1080P",s[s.LiveTranscoding_Profile_4IN_720P=7]="LiveTranscoding_Profile_4IN_720P",s[s.LiveTranscoding_Profile_4IN_360P=8]="LiveTranscoding_Profile_4IN_360P",s[s.LiveTranscoding_Profile_9IN_1080P=9]="LiveTranscoding_Profile_9IN_1080P",s[s.LiveTranscoding_Profile_9IN_720P=10]="LiveTranscoding_Profile_9IN_720P",s[s.LiveTranscoding_Profile_9IN_360P=11]="LiveTranscoding_Profile_9IN_360P",s[s.LiveTranscoding_Profile_12IN_1080P=12]="LiveTranscoding_Profile_12IN_1080P",s[s.LiveTranscoding_Profile_12IN_720P=13]="LiveTranscoding_Profile_12IN_720P",s[s.LiveTranscoding_Profile_12IN_360P=14]="LiveTranscoding_Profile_12IN_360P",s[s.LiveTranscoding_Profile_16IN_1080P=15]="LiveTranscoding_Profile_16IN_1080P",s[s.LiveTranscoding_Profile_16IN_720P=16]="LiveTranscoding_Profile_16IN_720P",s[s.LiveTranscoding_Profile_16IN_360P=17]="LiveTranscoding_Profile_16IN_360P",s[s.LiveTranscoding_Profile_Mixed=9999]="LiveTranscoding_Profile_Mixed",s))(Or||{});const Rc={0:"1IN_1080P",1:"1IN_720P",2:"1IN_360P",3:"2IN_1080P",4:"2IN_720P",5:"2IN_360P",6:"4IN_1080P",7:"4IN_720P",8:"4IN_360P",9:"9IN_1080P",10:"9IN_720P",11:"9IN_360P",12:"12IN_1080P",13:"12IN_720P",14:"12IN_360P",15:"16IN_1080P",16:"16IN_720P",17:"16IN_360P",9999:"Mixed_Audio"};var $i=(s=>(s[s.LiveTranscoding_HZ_48000=48e3]="LiveTranscoding_HZ_48000",s[s.LiveTranscoding_HZ_44100=44100]="LiveTranscoding_HZ_44100",s[s.LiveTranscoding_HZ_32000=32e3]="LiveTranscoding_HZ_32000",s[s.LiveTranscoding_HZ_16000=16e3]="LiveTranscoding_HZ_16000",s[s.LiveTranscoding_HZ_8000=8e3]="LiveTranscoding_HZ_8000",s))($i||{}),Ei=(s=>(s[s.LiveTranscodingNoBody=0]="LiveTranscodingNoBody",s[s.LiveTranscodingBody=1]="LiveTranscodingBody",s))(Ei||{}),Ii=(s=>(s[s.NOTO_SERIF_CJKSC_REGULAR=0]="NOTO_SERIF_CJKSC_REGULAR",s[s.ALIBABA_PUHUITI_REGULAR=1]="ALIBABA_PUHUITI_REGULAR",s[s.ALIBABA_PUHUITI_BOLD=2]="ALIBABA_PUHUITI_BOLD",s[s.ALIBABA_PUHUITI_Heavy=3]="ALIBABA_PUHUITI_Heavy",s[s.ALIBABA_PUHUITI_LIGHT=4]="ALIBABA_PUHUITI_LIGHT",s[s.ALIBABA_PUHUITI_MEDIUM=5]="ALIBABA_PUHUITI_MEDIUM",s))(Ii||{}),Vr=(s=>(s[s.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",s[s.LiveTranscodingCrop=1]="LiveTranscodingCrop",s[s.LiveTranscodingFill=2]="LiveTranscodingFill",s))(Vr||{}),Ki=(s=>(s[s.LiveTranscodingNormal=0]="LiveTranscodingNormal",s[s.LiveTranscodingVirtualBackground=1]="LiveTranscodingVirtualBackground",s))(Ki||{}),Ur=(s=>(s[s.LiveTranscodingState_IDLE=0]="LiveTranscodingState_IDLE",s[s.LiveTranscodingState_CONNNECT=1]="LiveTranscodingState_CONNNECT",s[s.LiveTranscodingState_RUNNING=2]="LiveTranscodingState_RUNNING",s[s.LiveTranscodingState_RECOVERING=3]="LiveTranscodingState_RECOVERING",s[s.LiveTranscodingState_FAILURE=4]="LiveTranscodingState_FAILURE",s[s.LiveTranscodingState_END=5]="LiveTranscodingState_END",s))(Ur||{}),It=(s=>(s[s.LiveTranscodingErrorPublishOk=0]="LiveTranscodingErrorPublishOk",s[s.LiveTranscodingErrorStreamNotFound=17825793]="LiveTranscodingErrorStreamNotFound",s[s.LiveTranscodingErrorStreamAlreadyExist=17825794]="LiveTranscodingErrorStreamAlreadyExist",s[s.LiveTranscodingErrorInvalidParam=17825795]="LiveTranscodingErrorInvalidParam",s[s.LiveTranscodingErrorInternalError=17825796]="LiveTranscodingErrorInternalError",s[s.LiveTranscodingErrorRtmpServerError=17825797]="LiveTranscodingErrorRtmpServerError",s[s.LiveTranscodingErrorRtmpStreamUrlError=17825798]="LiveTranscodingErrorRtmpStreamUrlError",s[s.LiveTranscodingErrorPublishTimeout=17825799]="LiveTranscodingErrorPublishTimeout",s[s.LiveTranscodingErrorNotAuthorized=17825800]="LiveTranscodingErrorNotAuthorized",s))(It||{}),Br=(s=>(s[s.TrascodingPublishTaskStatusStart=0]="TrascodingPublishTaskStatusStart",s[s.TrascodingPublishTaskStatusUpdate=1]="TrascodingPublishTaskStatusUpdate",s[s.TrascodingPublishTaskStatusStop=2]="TrascodingPublishTaskStatusStop",s))(Br||{}),rt=(s=>(s[s.MPU_TASK_TRANSACTION_START=0]="MPU_TASK_TRANSACTION_START",s[s.MPU_TASK_TRANSACTION_UPDATE=1]="MPU_TASK_TRANSACTION_UPDATE",s[s.MPU_TASK_TRANSACTION_STOP=2]="MPU_TASK_TRANSACTION_STOP",s[s.MPU_TASK_TRANSACTION_LIST=3]="MPU_TASK_TRANSACTION_LIST",s[s.MPU_TASK_TRANSACTION_POLLING=4]="MPU_TASK_TRANSACTION_POLLING",s[s.MPU_TASK_TRANSACTION_ACKNOWLEDGE=5]="MPU_TASK_TRANSACTION_ACKNOWLEDGE",s[s.MPU_TASK_TRANSACTION_END=6]="MPU_TASK_TRANSACTION_END",s))(rt||{});const Ac={0:"/libra/v1/sdk/start-task",1:"/libra/v1/sdk/update-task",2:"/libra/v1/sdk/stop-task",3:"/libra/v1/sdk/list-task",4:"/libra/v1/sdk/polling",5:"/libra/v1/sdk/acknowledge",6:"/"};class Hr{constructor(a,e,t,i,r,n,c,o){g(this,"videoWidth");g(this,"videoHeight");g(this,"videoFramerate",20);g(this,"videoBitrate",2e3);g(this,"videoGop",30);g(this,"audioSamplerate",$i.LiveTranscoding_HZ_44100);g(this,"audioBitrate",500);g(this,"audioChannels",1);this.videoWidth=a,this.videoHeight=e,t&&(this.videoFramerate=t),i&&(this.videoBitrate=i),r&&(this.videoGop=r),n&&(this.audioSamplerate=n),c&&(this.audioBitrate=c),o&&(this.audioChannels=o)}}const Fr=s=>((16711680&s)>>16)+(65280&s)+((255&s)<<16),pt=(s=0,a)=>{if(a==0)return 0;let e=s/a;return e<0&&(e=0),e>1&&(e=1),e};class Ji{constructor(a,e,t){g(this,"mixMode",_i.LiveTranscodingSingle);g(this,"singleParam");g(this,"mixParam");a&&(this.mixMode=a),e&&(this.singleParam=e),t&&(this.mixParam=t)}toJson(a,e,t,i,r){const n={appid:e.appId,channelid:e.channelId};if(a===rt.MPU_TASK_TRANSACTION_POLLING||a===rt.MPU_TASK_TRANSACTION_LIST||a===rt.MPU_TASK_TRANSACTION_ACKNOWLEDGE)return a===rt.MPU_TASK_TRANSACTION_ACKNOWLEDGE&&(n.messageid=r),n;if(n.taskid=t,a!==rt.MPU_TASK_TRANSACTION_STOP){if(n.mixmode=this.mixMode,i&&(n.streamurl=i),this.mixMode===_i.LiveTranscodingSingle){const c=this.singleParam;if(c){n.streamtype=c.streamType,c.sourceType===li.LiveTranscodingShareScreen?n.sourcetype=wi[c.sourceType]:n.sourcetype=wi[li.LiveTranscodingCamera];const o=[];c.userId&&o.push(c.userId),n.subspecusers=o}}else if(a===rt.MPU_TASK_TRANSACTION_START||a===rt.MPU_TASK_TRANSACTION_UPDATE){const c=this.mixParam;if(c){c.taskProfile&&(n.taskprofile=Rc[c.taskProfile]);const o=c.encodeParam||new Hr(1280,720);let l=o.videoWidth,d=o.videoHeight;const h={};Object.keys(o).forEach(u=>{const f=o[u];f>0&&(h[u.toLowerCase()]=f)}),h.lowbitratehighquality=0,n.encodeparam=h,n.backgrounds=c.backgrounds.map(u=>u.toJson(l,d)),n.watermarks=c.watermarks.map(u=>u.toJson(l,d)),n.clockwidgets=c.clockWidgets.map(u=>u.toJson(l,d));const p=c.users.map(u=>u.userId);n.subspecusers=[...new Set(p)],n.layouts=[{audiomixcount:c.users.length,panes:c.users.map((u,f)=>u.toJson(f,l,d,c.mediaProcessMode))}],n.layoutids=["0"],n.cropmode=c.cropMode,n.backgroundcolor=Fr(c.backgroundColor),n.taskmode=c.mediaProcessMode}}}return n}}const jr=s=>I(this,null,function*(){const a=new Uint8Array(160).fill(170),e=new TextEncoder().encode(s),t=yield window.crypto.subtle.importKey("raw",a,{name:"HMAC",hash:{name:"SHA-1"}},!1,["sign"]),i=yield window.crypto.subtle.sign("HMAC",t,e);return Array.from(new Uint8Array(i)).map(r=>r.toString(16).padStart(2,"0")).join("")});class _c{constructor(a){g(this,"authInfo");g(this,"slsReporter");this.slsReporter=a}doRequest(a,e){var c;const t=this.authInfo;if(!t)return Promise.reject(It.LiveTranscodingErrorInvalidParam);const i=Ac[a],r={appid:t.appId,userid:t.userId,channelid:t.channelId,timestamp:t.timestamp,token:t.token,nonce:t.nonce?t.nonce:"",requestid:Ne.createCallid(),tokensid:!1,session:(c=t.sessionId)!=null?c:Ne.createCallid()},n=Object.keys(r).map(o=>`${o}=${encodeURIComponent(r[o])}`).join("&");return fetch(`https://gw.rtn.aliyuncs.com${i}?${n}`,{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:JSON.stringify(e)}).then(o=>o.status!==200?(this.slsReporter.reportTranscodingError(o.status,e.taskid||""),Promise.reject(new V(U.ERR_INNER,`transcoding request failed, status: ${o.status}`))):o).catch(o=>Promise.reject(new V(U.ERR_INNER,`transcoding request failed, err: ${o.message}`)))}setAuthInfo(a){this.authInfo=a}clear(){this.authInfo=void 0}startPublishLiveStream(a,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(It.LiveTranscodingErrorInvalidParam);const t=yield jr(a.split("?")[0]),i=rt.MPU_TASK_TRANSACTION_UPDATE,r=e.toJson(i,this.authInfo,t,a);return this.doRequest(i,r)})}startPublishLiveStreamWithTaskId(a,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(It.LiveTranscodingErrorInvalidParam);const t=rt.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(t,this.authInfo,a);return this.doRequest(t,i)})}updatePublishLiveStream(a,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(It.LiveTranscodingErrorInvalidParam);const t=yield jr(a.split("?")[0]),i=rt.MPU_TASK_TRANSACTION_UPDATE,r=e.toJson(i,this.authInfo,t,a);return this.doRequest(i,r)})}updatePublishLiveStreamWithTaskId(a,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(It.LiveTranscodingErrorInvalidParam);const t=rt.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(t,this.authInfo,a);return this.doRequest(t,i)})}stopPublishLiveStream(a){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(It.LiveTranscodingErrorInvalidParam);const e=yield jr(a.split("?")[0]),t=rt.MPU_TASK_TRANSACTION_STOP,i=new Ji().toJson(t,this.authInfo,e,a);return this.doRequest(t,i)})}stopPublishLiveStreamWithTaskId(a){if(!this.authInfo)return Promise.reject(It.LiveTranscodingErrorInvalidParam);const e=rt.MPU_TASK_TRANSACTION_STOP,t=new Ji().toJson(e,this.authInfo,a);return this.doRequest(e,t)}refreshAuthInfo(a){this.authInfo&&this.setAuthInfo(G(G({},this.authInfo),a))}}function hn(s,a){const e=new window.XMLHttpRequest;e.open("POST",`${s}?APIVersion=0.6.0`,!0),e.send(a)}function wc(s,a){try{if(a.length>=32768)return void hn(s,a);(function(e,t){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${e}?APIVersion=0.6.0`,t)})(s,a)||hn(s,a)}catch(e){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
133
- `+e),console.error("Failed log data:",s))}}function Ec(s,a,e){return t=this,i=null,r=function*(){try{s=s.slice(0,-6);const{data:n,header:c}=yield e.process(s,a),o=new window.XMLHttpRequest;o.open("POST",s,!0);for(let l in c)o.setRequestHeader(l,c[l]);o.send(n)}catch(n){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
134
- `+n),console.error("Failed log data:",s))}},new Promise((n,c)=>{var o=h=>{try{d(r.next(h))}catch(p){c(p)}},l=h=>{try{d(r.throw(h))}catch(p){c(p)}},d=h=>h.done?n(h.value):Promise.resolve(h.value).then(o,l);d((r=r.apply(t,i)).next())});var t,i,r}class un extends ca{constructor(a){super(Object.assign({},a,{installUnloadHook:e=>{window.addEventListener("beforeunload",()=>{e()})},sendPayload:(e,t)=>{wc(e,t)}}))}useStsPlugin(a){this.getOpt().sendPayload=(e,t)=>{Ec(e,t,a)},this.overwriteTransString(a)}}Mi(window,"SLS_Tracker",un);const Zt=class Zt{constructor(){g(this,"ntpClock");this.ntpClock=new X.AliRTS.Clock}static getInstance(){return Zt.instance||(Zt.instance=new Zt),Zt.instance}now(){return this.ntpClock.now()}};g(Zt,"instance");let zr=Zt;const pn=()=>zr.getInstance(),{BrowserUtil:Wr,SystenUtil:gn}=X.AliRTS;class mn{constructor(){g(this,"tracker");g(this,"param");g(this,"msgCacheArr",[]);g(this,"index",0);g(this,"stsOpt");g(this,"slsToken");g(this,"ossToken");g(this,"ntpClock");this.ntpClock=pn()}createTracker(){if(!this.tracker&&this.slsToken&&this.param){const a=this.slsToken;this.ossToken&&(this.param.ossbn=this.ossToken.bucket_name,this.param.ossep=this.ossToken.region_endpoint);const e=new un({host:a.region_endpoint,project:a.project,logstore:a.log_store_stats}),t={accessKeyId:a.access_key_id,accessKeySecret:a.access_key_secret,securityToken:a.security_token,refreshSTSToken:()=>{this.slsToken&&(t.accessKeyId=this.slsToken.access_key_id,t.accessKeySecret=this.slsToken.access_key_secret,t.securityToken=this.slsToken.security_token)}};this.stsOpt=t;const i=Zi(t);e.useStsPlugin(i),this.tracker=e,this.msgCacheArr.forEach((r,n)=>{var c,o;(o=this.tracker)==null||o.send(G(yt(G({},this.param),{stat_log_id:`${((c=this.param)==null?void 0:c.sesid)||"nosession"}-${n}`}),r))}),this.index=this.index+this.msgCacheArr.length,this.msgCacheArr=[]}}start(a){this.initParam(a),this.createTracker()}updateToken(a,e){this.slsToken=a,this.ossToken=e,this.createTracker()}stop(){this.tracker=void 0,this.param=void 0,this.msgCacheArr=[],this.index=0,this.stsOpt=void 0,this.slsToken=void 0,this.ossToken=void 0}sendReport(a){var t,i;let e;a.tm=Date.now();try{e=JSON.parse(JSON.stringify(G(yt(G({bt:Wr.browserName||"unknown",ntptm:this.ntpClock.now(),ntpofs:this.ntpClock.now()-Date.now()},this.param),{stat_log_id:`${((t=this.param)==null?void 0:t.sesid)||"nosession"}-${this.index}`}),a)))}catch(r){}e&&(this.tracker?((i=this.tracker)==null||i.send(e),this.index++):this.msgCacheArr.push(e))}initParam(a){let e="";try{e=(localStorage==null?void 0:localStorage.getItem("AliRtcUUID"))||"",e||(e=lt(),localStorage==null||localStorage.setItem("AliRtcUUID",e))}catch(t){}this.param||(this.param={apid:a.appId,usrid:a.userId,statsvrs:"0.6.1",evetid:0,sesid:a.sessionId,sessionId:a.sessionId,channelid:a.channelId,usrn:a.userId,osn:gn.systemName,osv:gn.systemVersion,deb:Co(),den:Eo(),udid:e,sdkvrs:Ni,acs:"Unknown",cput:oa(),dm:`${window.location.protocol}//${window.location.host}`,bt:Wr.browserName,bv:Wr.browserVersion,envir:"PRODUCT",args:"",instid:lt()})}}const Ae=(s,a=1,e=6e4,t=0)=>{let i=s;return i||(i=0),Math.min(e,Math.max(t,Math.round(i*a)))},gt=(s,a,e=2e7,t=0)=>{let i=a;(!a||a<0||a>1e4)&&(i=1e3);let r=s;return r||(r=0),Math.min(e,Math.max(t,Math.round(r/(i/1e3))))},Xt=(s,a)=>{if(a===0||!a)return"0.00";let e=s;return(!e||e<0)&&(e=0),(e/a*100).toFixed(2)},fn=s=>s>=0&&s<=1?Ae(Math.floor(32767*s),1,32767):0,Ie=(s,a)=>{var t,i,r;let e=((t=s._last)==null?void 0:t[a])||0;return s.ssrc&&((i=s._last)!=null&&i.ssrc)&&s.ssrc!==((r=s._last)==null?void 0:r.ssrc)&&(e=0),((s==null?void 0:s[a])||0)-e},Sn=(s,a)=>Ae(Ie(s,a),1e3,1e4),Yt=(s,a=2e7)=>Ae(s,1,a),Ci=class Ci{constructor(a){g(this,"engine");g(this,"logClient");g(this,"authInfo");g(this,"ntpClock");g(this,"customFields",{});this.logClient=new mn,this.engine=a,this.ntpClock=pn()}static getLogClient(){return this.staticClient||(this.staticClient=new mn),this.staticClient}static reportOSSUpload(a,e,t=0){Ci.getLogClient().sendReport({errmsg:`${e}/${a}.log`,errtype:t,evetid:70017,sesid:a,sessionId:a,stat_log_id:`${a}-70017`})}setCustomFields(a){this.customFields=G(G({},this.customFields),a)}getCustomField(a){return this.customFields[a]}start(a){this.authInfo=a,this.logClient.start(a)}updateToken(a,e){this.logClient.updateToken(a,e),Ci.getLogClient().updateToken(a,e)}stop(){this.logClient.stop()}reportPublishAudio3A(a,e,t,i){const r={};let n=JSON.parse(i);r.publevel=n.capture_audio_cur_level_db||0,r.eleakrate=n.echo_leak_rate||0,r.playbw=n.render_bandwidth||-1,r.capbw=n.capture_bandwidth||-1,r.diff=n.diff||0,r.leak=n.leak||0,this.log({evetid:10070,traceid:t,calid:a,rmtid:"",args:this.data2String(G({calid:a,tckid:e||"audio3a",rmtid:"",traceid:t},r))})}reportPublishMonitor(a,e,t,i,r){if(!t||r.length<=0)return;const n=t===M.Audio,c={ctm:Math.floor(r[0].timestamp||0),src:r[0].ssrc||"",codec:r[0]._codec||""},o=[],l=[],d=[],h=[],p=[],u=[],f=[],m=[],b=[],S=[],v=[],R=[],w=[],y=[],A=[],_=[],E=[],T=[],k=[];try{if(r.forEach(P=>{var O,de,Pe,K,me,Me;if(!P||!P.timestamp)return;const H=(O=P._last)!=null&&O.timestamp?P.timestamp-P._last.timestamp:1e3,q=Ie(P,"bytesSent"),Y=Ie(P,"headerBytesSent"),J=gt(Ae(q+Y,8,2e7),H);o.push(J);const z=gt(Ae(q,8,2e7),H);l.push(z);const Z=gt(Ae(Y,8,2e7),H);d.push(Z);const ee=Ie(P,"packetsSent"),ge=gt(ee,H);h.push(ge);const D=Ie(P,"packetsLost"),x=gt(D,H);p.push(x);const L=Xt(D,ee);if(u.push(L),n)(de=P._source)!=null&&de.audioLevel&&f.push(fn(P._source.audioLevel)),m.push(0);else{b.push(Sn(P,"totalEncodeTime")),S.push(Yt((Pe=P._source)==null?void 0:Pe.framesPerSecond,100)),v.push(Yt((K=P._source)==null?void 0:K.framesPerSecond,100)),R.push(Yt(P.framesPerSecond,100)),w.push(Yt((me=P._source)==null?void 0:me.height,4400)),y.push(Yt((Me=P._source)==null?void 0:Me.width,7700)),A.push(Yt(P.frameHeight,4400)),_.push(Yt(P.frameWidth,7700));const _e=Ie(P,"totalPacketSendDelay");E.push(Ae(_e,1/(D||1),2e3));const ke=Ie(P,"qpSum");T.push(Ae(ke,1/(P.framesPerSecond||1),51)),k.push(0)}}),c.sbr=o.join(","),c.mbrs=l.join(","),c.pbrs=d.join(","),c.ps=h.join(","),c.pl=p.join(","),c.plr=u.join(","),n){const P=(i==null?void 0:i.getSettings().sampleRate)||0;c.ailevel=f.join(","),c.arpc=m.join(","),c.arsr=P,c.aesr=P,c.publevel=-90,c.rawlevel=-90}else c.em=b.join(","),c.cfps=S.join(","),c.ifps=v.join(","),c.sfps=R.join(","),c.ih=w.join(","),c.iw=y.join(","),c.sh=A.join(","),c.sw=_.join(","),c.sd=E.join(","),c.aqp=T.join(","),c.caf=k.join(","),c.can=k.join(","),c.cav=l.join(","),c.ifimax=k.join(","),c.ifimin=k.join(","),c.efimax=k.join(","),c.efimin=k.join(","),c.sfimax=k.join(","),c.sfimin=k.join(","),c.apsnr=k.join(",")}catch(P){}this.log({evetid:10070,traceid:e,calid:a,rmtid:"",args:this.data2String(G({calid:a,tckid:t,rmtid:"",traceid:e},c))})}reportSubscribeMonitor(a,e,t,i,r){if(!i||!r||r.length<=0)return;const n=i===M.Audio,c={ctm:Math.floor(r[0].timestamp||0),src:r[0].ssrc||"",codec:r[0]._codec||""},o=[],l=[],d=[],h=[],p=[],u=[],f=[],m=[],b=[],S=[],v=[],R=[],w=[],y=[],A=[],_=[],E=[],T=[],k=[],P=[],H=[],q=[],Y=[],J=[],z=[],Z=[],ee=[],ge=[],D=[],x=[],L=[],O=[],de=[],Pe=[];try{r.forEach(K=>{var ue,We;if(!K||!K.timestamp)return;const me=(ue=K._last)!=null&&ue.timestamp?K.timestamp-K._last.timestamp:1e3,Me=Ie(K,"bytesReceived"),_e=Ie(K,"headerBytesReceived"),ke=gt(Ae(Me+_e,8,2e7),me);o.push(ke);const fe=gt(Ae(Me,8,2e7),me);l.push(fe);const we=gt(Ae(_e,8,2e7),me);d.push(we);const he=Ie(K,"packetsReceived"),De=gt(he,me);h.push(De);const ye=Ie(K,"packetsLost"),qe=gt(ye,me);p.push(qe);const st=Xt(ye,he);u.push(st);const ne=Ie(K,"jitterBufferDelay"),re=Ie(K,"jitterBufferEmittedCount");if(K.jitterBufferDelay&&K.jitterBufferEmittedCount){const Q=Ae(ne,1e3/re,1e4);f.push(Q)}else f.push(0);const ie=Ie(K,"fecPacketsReceived");R.push(Xt(ie,he));const Se=Ie(K,"retransmittedPacketsReceived"),Ve=he+ye-Se;if(b.push(Xt(he-Se,Ve)),S.push(Xt(ye,Ve)),m.push(Xt(Se,Ve)),v.push(Ve),de.push(0),Pe.push(""),n){y.push(fn(K.audioLevel));const Q=((xe,bt)=>{var Tt,vt,jt;return(((Tt=xe==null?void 0:xe._source)==null?void 0:Tt[bt])||0)-(((jt=(vt=xe==null?void 0:xe._last)==null?void 0:vt._source)==null?void 0:jt[bt])||0)})(K,"synthesizedSamplesEvents");A.push(Q);const Le=Sn(K,"synthesizedSamplesDuration");_.push(Le);const at=Xt(Le,me);w.push(at),E.push(0)}else{const Q=(We=K._last)!=null&&We.totalInterFrameDelay?K.totalInterFrameDelay-K._last.totalInterFrameDelay:0;T.push(Ae(Q,1e3/(K.framesDecoded||30),500)),k.push(Ae(K.framesPerSecond,1,100)),P.push(Ie(K,"framesReceived")),O.push(Ie(K,"framesRendered")),H.push(Ae(K.frameHeight,1,4400)),q.push(Ae(K.frameWidth,1,7700));const Le=Ie(K,"totalProcessingDelay");Y.push(Ae(Le,1e3/(K.framesDecoded||30),12e4));const at=Ie(K,"nackCount");z.push(at);const xe=Ie(K,"pliCount");J.push(xe);const bt=Ie(K,"qpSum");Z.push(Ae(bt,1/(K.framesPerSecond||1),51)),ee.push(Ae(K.framesDropped));const Tt=Ie(K,"totalFreezesDuration");ge.push(Ae(Tt,1e3,3e4));const vt=Ie(K,"jitterBufferEmittedCount"),jt=Ie(K,"jitterBufferDelay");jt&&vt?D.push(Ae(jt,1e3/vt,3e4)):D.push(0);const Pi=Ie(K,"jitterBufferTargetDelay");Pi&&vt?x.push(Ae(Pi,1e3/vt,3e4)):x.push(0);const qi=Ie(K,"jitterBufferMinimumDelay");qi&&vt?L.push(Ae(qi,1e3/vt,3e4)):L.push(0)}}),c.rbr=o.join(","),c.mbrs=l.join(","),c.pbrs=d.join(","),c.pr=h.join(","),c.pl=p.join(","),c.plr=u.join(","),c.jd=f.join(","),c.fecr=R.join(","),c.retransr=m.join(","),c.baser=b.join(","),c.basel=S.join(","),c.recoverr=de.join(","),c.alll=S.join(","),c.totalc=v.join(","),n?(c.er=w.join(","),c.aolevel=y.join(","),c.asrc=E.join(","),c.scnt=A.join(","),c.sdura=_.join(",")):(c.dm=T.join(","),c.dfps=k.join(","),c.rfps=P.join(","),c.rh=H.join(","),c.rw=q.join(","),c.fpt=Pe.join(","),c.ns=z.join(","),c.pliss=J.join(","),c.aqp=Z.join(","),c.ofimax=de.join(","),c.ofimin=de.join(","),c.dfimax=de.join(","),c.dfimin=de.join(","),c.rfimax=de.join(","),c.rfimin=de.join(","),c.vrstutter=ge.join(","),c.cdm=D.join(","),c.tdm=x.join(","),c.pdm=L.join(","),c.ofps=O.join(","),c.dfbd=ee.join(","))}catch(K){}this.log({evetid:10080,traceid:t,rmtid:e,calid:a,args:this.data2String(G({calid:a,rmtid:e,tckid:i,traceid:t},c))})}reportNetworkMonitor(a){if(a.length<=0)return;const e=[],t=[],i=[],r=[],n=[],c=[],o=[],l=[],d=[],h=[];a.forEach((u,f)=>{var b;if(!u.timestamp)return;const m=(b=u._last)!=null&&b.timestamp?u.timestamp-u._last.timestamp:1e3;e.push(Ae(u.currentRoundTripTime,1e3)),t.push(Ae(u.availableOutgoingBitrate,8,2e8)),i.push(gt(Ae(u.bytesSent,8,2e7),m,25e6)),r.push(gt(Ae(u.bytesReceived,8,2e7),m,25e6)),n.push(0),c.push(0),f%5==0&&(o.push(""),l.push(""),d.push(""),h.push(""))});const p={ctm:Math.floor(a[0].timestamp||0),rtt:e.join(","),bsps:i.join(","),brps:r.join(","),cpu:o.join(","),mem:l.join(","),sysmem:d.join(","),systotalmem:h.join(","),audioonly:this.engine.isAudioOnly()?1:0};this.log({evetid:10071,args:this.data2String(G({asb:t.join(","),abms:n.join(","),vbms:c.join(",")},p))}),this.log({evetid:10081,args:this.data2String(G({},p))})}reportLoopAudioDelay(a,e){var f;const{AIAgent:t={},AIGrtn:i={},AIPub:r={},AISub:n={},pub:c={},sub:o={},grtn:l={}}=e||{};if(Object.keys(t).length===0)return;let d=0;d=Object.keys(l).length?(c.vTotalCost||0)+(c.upRTTHalf||0)+(l.totalCost||0)+(o.downRTTHalf||0)+(o.vTotalCost||0):(c.vEncPlugCost||0)+((c.timestampRecv||0)-(c.timestamp||0))+(o.vJitterBufferDelay||0)+(o.vDecPlugCost||0);const h={};let p=0;for(let m=0;m<10;m++){const b=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${m}`,S=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${m}`,v=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${m}`;if(!l.hasOwnProperty(b))break;p+=l[b]||0,p+=l[S]||0,p+=l[v]||0,h[`_gnd${m}`]=`gnd[${m}]: {${this.data2String({gnirh:l[b]||0,gnbp:l[S]||0,gnpc:l[v]||0})}}`}const u={};for(let m=0;m<10;m++){const b=`aigrtninternalrtthalf_${m}`,S=`aigrtnbeforepacer_${m}`,v=`aigrtnpacercost_${m}`;if(!i.hasOwnProperty(b))break;u[`_lgnd${m}`]=`lgnd[${m}]: {${this.data2String({gnirh:i[b]||0,gnbp:i[S]||0,gnpc:i[v]||0})}}`}this.log({evetid:10073,args:this.data2String(yt(G({tdlms:d+(t.aiagenttotalcost||0),_:`aiqud:{${this.data2String(yt(G({uid:((f=this.authInfo)==null?void 0:f.userId)||"",sid:r.aAIClientScentenceId||0,quct:65535*(r.aAIClientQuestionTimestampHEAD||0)+(r.aAIClientQuestionTimestampTAIL||0),anct:65535*(r.aAIClientAnswerTimestampHEAD||0)+(r.aAIClientAnswerTimestampTAIL||0),casc:r.aAIClientSourceCost||0,camc:r.aAIClientMixerCost||0,caec:r.aAIClientEncoderCost||0,cantc:r.aIClientNetsdkThrCost||0,caqtc:r.aIClientQosThrCost||0,capc:r.aIClientPacerCost||0,cuphr:r.aIClientUpRTTHalf||0},u),{qgac:0,ldhr:l.ngxRtcSeiCumulativeDelayKeyDownRttHalf_0||0,larc:n.aAILinuxReceiveCost||0,lanqc:n.aAILinuxNeteqCost||0,larsc:n.aAILinuxRemoteSourceCost||0,lapmc:n.aAILinuxPlayMixerCost||0,lapc:n.aAILinuxPlayCost||0,lsdnc:n.aIClinetSmartDenoise||0,asrc:t.aiasrcost||0,llmc:t.aillmcost||0,ttsc:t.aittscost||0,aamc:t.aimutecost||0,aatc:t.aiagenttotalcost||0}))}};`,ssrc:a,tpd:0,scc:r.aAIClientSourceCost||0,mxc:r.aAIClientMixerCost||0,encc:r.aAIClientEncoderCost||0,netc:r.aIClientNetsdkThrCost||0,qostc:r.aIClientQosThrCost||0,pacerc:r.aIClientPacerCost||0,uphr:r.aIClientUpRTTHalf||0},h),{agac:p,dnhr:o.downRTTHalf||0,tsd:o.vTotalCost||0,rcc:n.aAILinuxReceiveCost||0,nqc:n.aAILinuxNeteqCost||0,rscc:n.aAILinuxRemoteSourceCost||0,plmxc:n.aAILinuxPlayMixerCost||0,plc:n.aAILinuxPlayCost||0,dvd:0}))})}reportJoin(a,e,t=""){var h,p;const{start:i,rs:r=0,re:n=0}=e,c=Date.now()-i,o=n-r;let l=0;r&&(l=r-i);let d=0;n&&(d=n-r),this.log({evetid:10010,args:this.data2String({sesid:((h=this.authInfo)==null?void 0:h.sessionId)||"",joitm:c,rslt:a,gslbtm:0,dnstm:0,avcftm:0,gslbrslt:0,dnsrslt:0,avcfrslt:0,mode:2,jrtc:o,usrn:(p=this.authInfo)==null?void 0:p.userId,mgt:"cdn",cttc:l,iptc:d,ndn:1,gslbloc:1,ccag:0,ucag:0,cpg:0,upg:0,tid:t})})}reportJoinConnection(a){this.log({evetid:20002,args:this.data2String(G({transretrynum:0,ldnstc:0,tcptc:0,ssltc:0,url:""},a))})}reportLeave(a,e,t){this.log({evetid:10020,args:this.data2String({lvetm:a,rslt:e,tid:t})})}reportPublish(a,e,t,i,r,n,c,o,l,d,h,p){this.log({evetid:a?10032:10030,calid:t,tm:p,args:this.data2String({calid:t,url:e,isvl:i?1:0,isvs:r?1:0,isvss:n?1:0,isaudio:c?1:0,rslt:o,tid:"123",pubtm:Date.now()-h,pctid:l,pubtid:d,isvp:0,isarecording:0,isad:0,isdc:0,pubretry:0,pbrttimes:0})})}reportPublishFirstPacket(a,e,t,i,r,n,c,o,l){const d=Date.now();this.log({evetid:a?10033:10031,calid:e,args:this.data2String({calid:e,fpst:d-t,tckid:n,est:t,pctid:c,pubtid:o,totaltm:d-r,jorm:l===_t.JOIN_CHANNEL?1:0,cptc:0,sptc:i-t,iptc:0,ipc2fptc:0,dctc:0,patc:0})})}reportUnpublish(a,e,t,i){var r;this.log({evetid:10040,args:this.data2String({calid:a,unpubtm:e,rslt:t,tid:i,sesid:((r=this.authInfo)==null?void 0:r.sessionId)||""})})}reportSubscribe(a,e,t,i,r,n,c,o,l,d,h){this.log({evetid:10050,calid:a,rmtid:e,tm:h,args:this.data2String(G({calid:a,rmtid:e,isvl:t?1:0,isvs:i?1:0,isvss:r?1:0,isaudio:n?1:0,rslt:c,tid:o,subtm:l,isvp:0,isaplaying:0,isad:0,isdc:0,subretry:0,sbrttimes:0},d))})}reportSubscribeFirstPacket(a,e,t,i,r){this.log({evetid:a?10054:10051,calid:e,rmtid:t,args:this.data2String(G({calid:e,rmtid:t,tckid:i,cptc:0,iptc:0,ipc2fptc:0,dctc:0,patc:0},r))})}reportSubscribeFirstFrame(a,e,t,i,r){this.log({evetid:a?10055:10052,calid:e,rmtid:t,args:this.data2String(G({calid:e,rmtid:t,tckid:i},r))}),this.log({evetid:a?10058:10057,args:this.data2String(G({calid:e,rmtid:t,tckid:i},r))})}reportUnsubscribe(a,e,t,i,r){this.log({evetid:10060,calid:a,args:this.data2String({calid:a,rmtid:e,unsubtm:t,rslt:i,tid:r})})}reportMute(a,e,t){this.log({evetid:11030,args:this.data2String({calid:a,rmtid:"",enable:e?1:0,mt:t})})}reportRoleUpdate(a,e){this.log({evetid:11040,args:this.data2String({or:a||"",nr:e,ctm:Date.now(),rslt:0})})}reportRoleUpdateResult(a,e,t,i){this.log({evetid:11041,args:this.data2String({or:a||"",nr:e,ctm:t,rslt:i})})}reportVideoProfile(a){this.log({evetid:20074,args:this.data2String({pf:a,tckid:"sophon_camera_large"})})}reportScreenProfile(a){this.log({evetid:20074,args:this.data2String({pf:a,tckid:"sophon_screenshare"})})}reportError(a){this.log({evetid:10091,args:this.data2String({rslt:(a==null?void 0:a.code)||-1})})}reportWarning(a){this.log({evetid:10092,args:this.data2String({rslt:-1,errmsg:a})})}reportRoomServerEvent(a,e,t,i){this.log({evetid:20005,args:this.data2String({calid:"",rmtid:"",rt:a?0:1,dr:a?"s":"r",mt:e,ri:t,cs:1,srt:Date.now(),rspc:(i==null?void 0:i.code)||"",mc:JSON.stringify(i)})})}reportTranscodingError(a,e){this.log({evetid:10101,args:this.data2String({rslt:a,taskid:e})})}reportBye(a){var e;this.log({evetid:10093,args:this.data2String({rslt:a,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportAudio(a,e,t){var i;this.log({evetid:80013,args:this.data2String({rslt:a?-1:0,adm:1,adt:0,adr:a?2:0,acms:e,adrpn:t})}),this.log({evetid:80014,args:this.data2String({sesid:((i=this.authInfo)==null?void 0:i.sessionId)||"",rslt:a?-1:0,adm:1,adt:0,adr:a?2:0,acms:e,adrpn:t})})}reportScreen(a,e){var t,i,r,n;this.log({evetid:90013,args:this.data2String({rslt:a?-1:0,vcms:e,vde:(t=a==null?void 0:a.code)!=null?t:-1,sesid:((i=this.authInfo)==null?void 0:i.sessionId)||""})}),this.log({evetid:90014,args:this.data2String({rslt:a?-1:0,vcms:e,vde:(r=a==null?void 0:a.code)!=null?r:-1,sesid:((n=this.authInfo)==null?void 0:n.sessionId)||""})})}reportScreenStop(a){this.log({evetid:90019,args:this.data2String({rslt:a?a.code||-1:0})}),this.log({evetid:90020,args:this.data2String({rslt:a?a.code||-1:0})})}reportSwitchCamera(a){var e;this.log({evetid:90025,args:this.data2String({rslt:0,td:a,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportPublishProfile(a,e){this.log({evetid:10201,args:this.data2String(G({tckid:a},e))})}reportSDKCreated(a){this.log({evetid:70011,createtm:Date.now()-a,tm:a})}reportJoinInvoked(a){this.log({evetid:70012,jnnonce:a.nonce||"",jntoken:a.token||"",jntm:a.timestamp||""})}reportJoinResult(a){this.log({evetid:70013,rslt:a?a.code||-1:0,dnsrslt:0})}reportSTSResult(a,e){this.log({evetid:70014,rslt:a,asty:1,reqtm:Date.now()-e})}reportLeaveInvoked(){this.log({evetid:70015})}reportSEIMessage(a,e,t,i,r){this.log({evetid:40301,args:this.data2String({tm:Date.now(),sei_pt:a,sei_len:e,sei_rep:t,sei_delay:i,sei_key:r})})}reportConnectionLatencyEvent(a,e,t,i,r,n,c=!1){const o={ageniid:this.getCustomField("ageniid")},l=G({tm:r||Date.now(),ntptm:n||this.ntpClock.now(),stage:a,status:e,calid:t,tckid:i,cltp:1,http:c?1:0},o);this.log({evetid:12001,args:this.data2String(l)})}log(a){a&&(a.tm=a.tm||new Date().getTime(),N.debug("[ConsoleLogger]","log",a),this.logClient.sendReport(a))}data2String(a){let e="";for(let t in a)e.length&&(e+="&"),e+=t.startsWith("_")?a[t]:`${t}=${a[t]}`;return e}};g(Ci,"staticClient");let $r=Ci;const hi=class hi extends se{constructor(e){super();g(this,"ws");g(this,"socketStatus",0);g(this,"wsUrl","");g(this,"lastConnectStartTime",0);g(this,"connectRetryMinTimeGap",5e3);g(this,"shouldReconnect",!0);g(this,"connectRetryCount",0);g(this,"gotErr",!1);g(this,"closedByInvoke",!0);g(this,"isReconnecting",!1);g(this,"networkAvailableChecked",!0);g(this,"reconnectTimeoutId",0);e&&(this.connectRetryMinTimeGap=e),this.onOpen=this.onOpen.bind(this),this.onMessage=this.onMessage.bind(this),this.onError=this.onError.bind(this),this.onClose=this.onClose.bind(this)}get connectUrl(){return this.wsUrl}get connectStatus(){return this.socketStatus}start(e){this.wsUrl=e,this.initWebSocket()}send(e){return!(!this.ws||this.socketStatus!==2)&&(this.ws.send(JSON.stringify(e)),!0)}close(){this.closedByInvoke=!0,this.uninitWebsocket()}markShouldReconnect(e){this.shouldReconnect=e}reconnect(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.emit("onWillReconnect"),this.shouldReconnect?(this.emit("onReconnectStart"),this.isReconnecting=!0,this.initWebSocket()):this.emit("onConnectFail")}onOpen(e){N.info(`[${hi.logName}]`,"onOpen"),this.socketStatus=2,this.connectRetryCount=0,this.shouldReconnect=!0,this.networkAvailableChecked=!1,this.closedByInvoke=!1,this.gotErr=!1,this.isReconnecting=!1,this.emit("onOpen",e)}onMessage(e){this.emit("onMessage",e)}onError(e){this.isReconnecting&&this.emit("onReconnectFail",e),this.emit("onError",e),this.isReconnecting=!1,this.socketStatus!==2&&Ne.isNetworkAvailable().then(t=>{t&&console.error(hi.logName,"onError, Network is available, token may be invalid")})}onClose(e){return I(this,null,function*(){if(this.closedByInvoke)this.socketStatus=0;else{if(N.info(`[${hi.logName}]`,`onClose, code: ${e.code}, reason: ${e.reason}, status: ${status}, retryCount: ${this.connectRetryCount}`),(yield Ne.isNetworkAvailable())&&!this.networkAvailableChecked)return this.reconnect(),void(this.networkAvailableChecked=!0);if(this.connectRetryCount||this.emit("onNetworkError"),!this.reconnectTimeoutId){this.connectRetryCount+=1;const t=Date.now()-this.lastConnectStartTime;t>=this.connectRetryMinTimeGap?this.reconnect():this.reconnectTimeoutId=window.setTimeout(()=>{this.reconnect()},this.connectRetryMinTimeGap-Math.max(0,t))}this.socketStatus=0,this.emit("onClose",e)}})}initWebSocket(){this.uninitWebsocket(),this.socketStatus=1,this.lastConnectStartTime=Date.now(),this.ws=new WebSocket(this.wsUrl),this.ws.addEventListener("open",this.onOpen),this.ws.addEventListener("message",this.onMessage),this.ws.addEventListener("error",this.onError),this.ws.addEventListener("close",this.onClose)}uninitWebsocket(){this.ws&&(this.ws.removeEventListener("open",this.onOpen),this.ws.removeEventListener("message",this.onMessage),this.ws.removeEventListener("error",this.onError),this.ws.removeEventListener("close",this.onClose),this.ws.readyState!==WebSocket.CLOSED&&this.ws.close(),this.ws=void 0,this.socketStatus=0)}};g(hi,"logName","Socket");let Kr=hi;const ct=class ct extends se{constructor(e,t,i,r,n,c){super();g(this,"authInfo");g(this,"userName");g(this,"channelProfile");g(this,"clientRole");g(this,"slsReporter");g(this,"wsClient");g(this,"packageCreator");g(this,"keepAliveTimer",0);g(this,"lastKeepAliveResponseTime",0);g(this,"maxConnectRetryDuration",90);g(this,"packageCache",new Map);g(this,"isFirstConnect",!0);g(this,"aliveChecker",0);g(this,"reconnectData");g(this,"joinChannelExtraData");this.authInfo=e,this.userName=t,this.packageCreator=new Ui(e,t),this.channelProfile=i,this.clientRole=r,this.slsReporter=n,c&&(this.maxConnectRetryDuration=c),this.wsClient=new Kr,this.wsClient.on("onOpen",this.onOpen.bind(this)),this.wsClient.on("onMessage",this.onMessage.bind(this)),this.wsClient.on("onError",this.onError.bind(this)),this.wsClient.on("onClose",this.onClose.bind(this)),this.wsClient.on("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.on("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.on("onNetworkError",this.onNetworkError.bind(this)),this.wsClient.on("onWillReconnect",this.onWillReconnect.bind(this)),this.wsClient.on("onReconnectStart",this.onReconnectStart.bind(this)),this.wsClient.on("onReconnectFail",this.onReconnectFail.bind(this))}get retryCount(){return this.wsClient.connectRetryCount}destroy(){this.lastKeepAliveResponseTime=0,this.close()}start(e,t){this.joinChannelExtraData=t,this.wsClient.start(e)}startKeepAlive(){this.keepAliveTimer===0&&(this.keepAliveTimer=window.setInterval(()=>{let e=this.packageCreator.createKeepAlivePackage();this.sendPackage(e)},5e3)),this.checkAlive()}stopKeepAlive(){this.keepAliveTimer!==0&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=0),this.aliveChecker&&(window.clearTimeout(this.aliveChecker),this.aliveChecker=0)}sendPkgCache(){this.packageCache.forEach(e=>{this.wsClient.send(e)})}leave(){let e=this.packageCreator.createLeavePackage();this.sendPackage(e)}reportStatus(e){let t=this.packageCreator.createStatusPackage(e);this.sendPackage(t)}publish(e){const l=e,{l1ip:t}=l,i=Mt(l,["l1ip"]);let r=this.packageCreator.createPublishPackage();r.data.users=[],r.data.l1ip=t,i.subscribe.signal=this.wsClient.connectUrl;const{tracks:n,resume:c}=i;let o="7.2.1";o&&(o=o.split("-")[0]),n.forEach(d=>{const{codec:h,ssrc:p}=d;d.userdata=JSON.stringify({sdk_version:o,codec:h}),d.ssrc=`${p}`,c&&(d.attr={reason:"reconnect"})}),r.data.users.push(i),this.sendPackage(r)}roleUpdate(e){let t=this.packageCreator.createRoleUpdatePackage();t.data.clientrole=e,this.sendPackage(t)}refreshUrl(e){const t=this.packageCreator.createRefreshUrlPackage();t.data=G(yt(G({},t.data),{sessionid:t.header.sessionid}),e),this.sendPackage(t)}refreshAuthInfo(e){this.authInfo=e,this.packageCreator.refreshAuthInfo(e)}close(){N.info(`[${ct.logName}] close`),this.stopKeepAlive(),this.wsClient.off("onOpen",this.onOpen.bind(this)),this.wsClient.off("onMessage",this.onMessage.bind(this)),this.wsClient.off("onError",this.onError.bind(this)),this.wsClient.off("onClose",this.onClose.bind(this)),this.wsClient.off("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.off("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.off("onReconnectStart"),this.wsClient.off("onReconnectFail"),this.wsClient.close()}sendPackage(e){[Ue.KEEPALIVE,Ue.RECONNECT,Ue.JOINCHANNEL].includes(e.msgtype)||this.packageCache.set(e.tid,e),this.wsClient.send(e),e.msgtype!==Ue.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!0,e.msgtype,e.tid,e)}updateReconnectData(e){this.reconnectData=e}onOpen(){if(N.info(`[${ct.logName}] onOpen`),this.isFirstConnect){let e=this.packageCreator.createJoinPackage(this.joinChannelExtraData);e.data.configure={channelprofile:this.channelProfile},this.channelProfile!==kt.AliRtcSdkInteractiveLive&&this.channelProfile!==kt.AliRtcSdkInteractiveWithLowLatencyLive||(e.data.configure.clientrole=this.clientRole),this.sendPackage(e)}else{this.stopKeepAlive();const e=this.packageCreator.createReconnectPackage(this.reconnectData);this.sendPackage(e)}}onMessage(e){try{let t=JSON.parse(e.data);this.packageCache.delete(t.tid),this.onRecvMessage(t),t!=null&&t.msgtype&&(t==null?void 0:t.msgtype)!==Ue.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!1,t.msgtype,t.tid,t)}catch(t){N.warn(`[${ct.logName}] onMessage err`,t,e)}}onError(e){N.warn(`[${ct.logName}] onError`,e),this.isFirstConnect&&this.onConnectFail()}onConnectFail(){N.warn(`[${ct.logName}] onConnectFail`);const e=new V(U.ERR_INNER,"Signaling connect failed.");this.isFirstConnect?this.emit("onJoinChannelResult",e):this.emit("onConnectFail",e)}onAuthInvalid(){N.warn(`[${ct.logName}] onAuthInvalid`),this.isFirstConnect&&this.emit("onAuthInvalid")}onNetworkError(){N.warn(`[${ct.logName}] onNetworkError`);const e=new V(U.ERR_INNER,"Network error, signaling connect failed.");this.emit("onNetworkError",e)}onClose(e){N.info(`[${ct.logName}] onClose`,e),this.stopKeepAlive()}onKeepAliveRsp(){this.emit("onKeepAliveRsp"),this.lastKeepAliveResponseTime=Date.now(),this.checkAlive()}onWillReconnect(){this.lastKeepAliveResponseTime||(this.lastKeepAliveResponseTime=Date.now()),Date.now()-this.lastKeepAliveResponseTime>1e3*this.maxConnectRetryDuration&&this.wsClient.markShouldReconnect(!1)}onReconnectStart(){this.emit("onReconnectStart")}onReconnectFail(){this.emit("onReconnectFail",new V(U.ERR_INNER,"signaling reconnect failed."))}checkAlive(){window.clearTimeout(this.aliveChecker),this.aliveChecker=window.setTimeout(()=>{N.info(`[${ct.logName}] not alive, reconnect`),this.stopKeepAlive(),this.emit("onReconnectStart"),this.wsClient.reconnect()},15e3)}onRecvMessage(e){switch(e.msgtype!==Ue.KEEPALIVE&&N.info(`[${ct.logName}] recv msg: ${e.msgtype}`),e.msgtype){case Ue.JOINCHANNEL:this.onJoinResult(e);break;case Ue.KEEPALIVE:this.onKeepAliveRsp();break;case Ue.PUBLISH:this.onPublishResult(e);break;case Ue.NOTIFYJOIN:this.onNotifyJoin(e);break;case Ue.NOTIFYSTATUS:this.onNotifyStatus(e);break;case Ue.LEAVECHANNEL:this.onLeaveResult(e);break;case Ue.NOTIFYLEAVE:this.onNotifyLeave(e);break;case Ue.NOTIFYPUBLISH:this.onNotifyPublish(e);break;case Ue.STATUSREPORT:this.onStatusReport(e);break;case Ue.BYE:this.onBye(e);break;case Ue.ROLEUPDATE:this.onRoleUpdateResult(e);break;case Ue.REFRESHURL:this.onRefreshUrlResult(e);break;case Ue.RECONNECT:this.onReconnectResult(e);break;default:this.onUnknownMessage(e)}}onJoinResult(e){this.isFirstConnect=!1,this.emit("onJoinChannelResult",e)}onLeaveResult(e){this.emit("onLeaveResult",e.code,e.tid)}onPublishResult(e){this.emit("onPublishResult",e.code,e.tid,e.description)}onRoleUpdateResult(e){this.emit("onRoleUpdateResult",e.code,e.tid,e.description)}onRefreshUrlResult(e){this.emit("onRefreshUrlResult",e)}onReconnectResult(e){if(e.code===200)this.sendPkgCache(),this.startKeepAlive(),this.emit("onReconnectSuccess",e.data.users);else{const t=new V(U.ERR_INNER,`reconnect failed, code: ${e.code};description: ${e.description}`);e.code===403&&(t.code=403),this.emit("onReconnectFail",t),this.close()}}onNotifyJoin(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e&&e.data&&e.data.users&&this.emit("onNotifyJoin",e.data.users)}onNotifyStatus(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.status&&e.data.status.length&&this.emit("onNotifyStatus",e.data.status)}onNotifyLeave(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyLeave",e.data.users)}onNotifyPublish(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyPublish",e.data.users)}onStatusReport(e){this.emit("onStatusReport",e.code,e.tid,e.description)}onBye(e){this.stopKeepAlive(),this.emit("onBye",e.reason,e.description)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}};g(ct,"logName","RSMessageCenter");let Jr=ct;var Ic=Object.defineProperty,Tc=Object.getOwnPropertyDescriptor,Gr=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Tc(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&Ic(a,e,r),r};const Gi=(Ze=class extends se{constructor(e,t,i,r=mt.prod){super();g(this,"messageCenter");g(this,"authInfo");g(this,"userName");g(this,"channelProfile");g(this,"clientRole");g(this,"slsReporter");g(this,"reconnectData");g(this,"roomServerUri","");this.channelProfile=e,this.clientRole=t,this.slsReporter=i,this.reconnectData={role:{channelprofile:e,clientrole:t}};const n=r===mt.pre?ri.pre:ri.prod;this.roomServerUri=`wss://${n}/roomserver/v1/ws`}updateReconnectData(e){var t;this.reconnectData=e,(t=this.messageCenter)==null||t.updateReconnectData(this.reconnectData)}reset(){N.info("[roomsig] reset"),this.messageCenter&&(this.messageCenter.destroy(),this.messageCenter=void 0),this.authInfo=void 0}join(e,t,i,r){return I(this,null,function*(){return new Promise((n,c)=>{const o={};this.authInfo=e,this.userName=t,this.messageCenter=new Jr(e,t,this.channelProfile,this.clientRole,this.slsReporter,i),this.initMessageCenter(),this.messageCenter.once("onJoinChannelResult",d=>{var h,p,u;if(N.info(`[${Ze.logName}]`,"join result: ",d),o.taskretrynum=((h=this.messageCenter)==null?void 0:h.retryCount)||0,d.code==200){(p=this.messageCenter)==null||p.sendPkgCache(),(u=this.messageCenter)==null||u.startKeepAlive();let f=d.data;f.tid=d.tid,f.users=d.data.users,f.timestamp=d.timestamp,o.est&&(o.joinconnecttc=Date.now()-o.est),this.slsReporter.reportJoinConnection(o),n(f)}else this.reset(),c(this.handleSignalError(d.code,d.reason,U.ERR_JOIN_CHANNEL_FAILED))}),this.messageCenter.once("onAuthInvalid",()=>{this.reset(),c(new V(U.ERR_JOIN_BAD_TOKEN,"join failed because authentication failed"))}),N.info(`[${Ze.logName}]`,"start ws connecting roomserver and auto join when connected");const l={appid:this.authInfo.appId,channelid:this.authInfo.channelId,userid:this.authInfo.userId,nonce:this.authInfo.nonce||"",timestamp:this.authInfo.timestamp,token:this.authInfo.token,authtype:"app",tid:lt()};e.role&&(l.tokenrole=e.role),o.est=Date.now(),this.messageCenter.start(this.roomServerUri+"?"+Ne.queryingParam(l),r)})})}leave(){return N.info("[roomsig] leave .."),new Promise((e,t)=>{this.messageCenter?(this.messageCenter.on("onLeaveResult",(i,r)=>{N.info(`[${Ze.logName}]`,"recv leave response "+i),i===200?(this.updateReconnectData(),this.reset(),e({tid:r})):t(this.handleSignalError(i,"leave error"))}),N.info(`[${Ze.logName}]`,"send leave request"),this.messageCenter.leave()):(N.info(`[${Ze.logName}]`,"no message center, ok to leave"),e({tid:""}))})}publish(e){return new Promise((t,i)=>{var r;this.messageCenter?(this.messageCenter.once("onPublishResult",(n,c,o)=>{N.info(`[${Ze.logName}]`,"recv pubish response "+n),n===200?(this.updateReconnectData(yt(G({},this.reconnectData),{publish:{users:[e]}})),t({tid:c})):i(this.handleSignalError(n,`publish error, ${o}`))}),this.authInfo&&(e.sessionid=(r=this.authInfo.sessionId)!=null?r:""),e.callid||(e.callid=lt()),N.info(`[${Ze.logName}]`,"assign callid "+e.callid+" and send publish request"),this.messageCenter.publish(e)):i(this.handleSignalError(-1,"publish error, no message center"))})}roleUpdate(e){return new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRoleUpdateResult",(r,n,c)=>{var o,l;N.info(`[${Ze.logName}]`,"recv role update response "+r),r===200?((l=(o=this.reconnectData)==null?void 0:o.role)!=null&&l.clientrole&&(this.reconnectData.role.clientrole=e,this.updateReconnectData(this.reconnectData)),t({tid:n})):i(this.handleSignalError(r,`role update error, ${c}`))}),this.messageCenter.roleUpdate(e)):i(this.handleSignalError(-1,"role update error, no message center"))})}setChannelProfile(e){this.channelProfile=e}refreshUrl(e){return N.info(`[${Ze.logName}]`,"refreshUrl .."),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRefreshUrlResult",r=>{const{code:n,description:c,data:o={}}=r||{};N.info("recv refresh url response "+n),n===200?t(o):i(this.handleSignalError(n,`refresh url error, ${c}`))}),N.info("send refresh url request"),this.messageCenter.refreshUrl(e)):i(this.handleSignalError(-1,"refresh url error, no message center"))})}reportStatus(e){return N.info(`[${Ze.logName}]`,"reportStatus "+e),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.once("onStatusReport",(r,n)=>{r===200?t():i(new V(r,n))}),this.messageCenter.reportStatus(e)):i(new V(-1,"No messageCenter"))})}handleSignalError(e,t,i=U.ERR_INNER){return new V(i,`signal error: code - ${e}; description - ${t}`)}refreshAuthInfo(e){return I(this,null,function*(){var t;this.authInfo&&(this.authInfo=e,(t=this.messageCenter)==null||t.refreshAuthInfo(this.authInfo))})}initMessageCenter(){var e,t,i,r,n,c,o,l,d,h,p,u,f;(e=this.messageCenter)==null||e.on("onKeepAliveRsp",()=>{this.emit("onKeepAliveRsp")}),(t=this.messageCenter)==null||t.on("onNotifyJoin",m=>{this.emit("onNotifyJoin",m)}),(i=this.messageCenter)==null||i.on("onNotifyStatus",m=>{this.emit("onNotifyStatus",m)}),(r=this.messageCenter)==null||r.on("onNotifyLeave",m=>{this.emit("onNotifyLeave",m)}),(n=this.messageCenter)==null||n.on("onNotifyPublish",m=>{this.emit("onNotifyPublish",m)}),(c=this.messageCenter)==null||c.on("onBye",(m,b)=>{this.emit("onBye",m,b)}),(o=this.messageCenter)==null||o.on("onReconnectStart",()=>{this.emit("onReconnectStart")}),(l=this.messageCenter)==null||l.on("onReconnectSuccess",m=>{this.emit("onReconnectSuccess",m)}),(d=this.messageCenter)==null||d.on("onReconnectFail",m=>{this.emit("onReconnectFail",m)}),(h=this.messageCenter)==null||h.on("onConnectFail",m=>{this.emit("onConnectFail",m),this.reset()}),(p=this.messageCenter)==null||p.on("onNetworkError",m=>{this.emit("onNetworkError",m)}),(u=this.messageCenter)==null||u.on("onAuthInvalid",()=>{this.emit("onAuthInvalid")}),(f=this.messageCenter)==null||f.on("onUnknownMessage",m=>{this.emit("onUnknownMessage",m)})}},g(Ze,"logName","RoomServerSignaling"),Ze);Gr([C()],Gi.prototype,"join",1),Gr([C()],Gi.prototype,"publish",1),Gr([C()],Gi.prototype,"roleUpdate",1);let Cc=Gi;const kc=6e5,ki=class ki extends se{constructor(e,t){super();g(this,"env");g(this,"authInfo");g(this,"timer");g(this,"slsReporter");g(this,"expiration",0);g(this,"skipTime",0);g(this,"requestToken",()=>I(this,null,function*(){if(this.skipTime=0,!this.authInfo)return;const{appId:e,channelId:t,userId:i,nonce:r="",token:n,timestamp:c,sessionId:o,role:l}=this.authInfo;let d="https://gw.rtn.aliyuncs.com";this.env===mt.pre&&(d="https://pgw.rtn.aliyuncs.com");const h=`${d}/gslb/v1/stsupdate?appid=${e}&channelid=${t}&userid=${i}&nonce=${r}&token=${n}&timestamp=${c}&session=${o}${l?`&tokenrole=${l}`:""}&slstoken=true&osstoken=true&tokensid=false`,p=Date.now();fetch(h).then(u=>u.json()).then(u=>{var f,m;if(u.code!==0)throw new Error;{const b=(f=u.data)==null?void 0:f.oss,S=(m=u.data)==null?void 0:m.sls;this.expiration=b.expiration||S.expiration,this.emit("onTokenUpdate",b,S),N.event(`[${ki.logName}]`,"getToken",b,S)}this.slsReporter.reportSTSResult(200,p)}).catch(u=>{this.slsReporter.reportSTSResult(-1,p),N.error(`[${ki.logName}]`,"getToken",u.message)})}));this.slsReporter=e,this.env=t}refreshAuthInfo(e){this.authInfo=e}startSTSUpdate(e){this.authInfo=e,this.requestToken(),this.timer&&clearInterval(this.timer),this.timer=window.setInterval(()=>{this.expiration&&Math.floor((Date.now()+9e5)/1e3)<this.expiration&&this.skipTime<12?this.skipTime+=1:this.requestToken()},kc)}clear(){this.timer&&clearInterval(this.timer)}};g(ki,"logName","StsManager");let qr=ki;var Pc=Object.defineProperty,Dc=Object.getOwnPropertyDescriptor;class Xr extends se{constructor(e,t,i,r=mt.prod){super();g(this,"signaling");g(this,"authInfo");g(this,"userName");g(this,"channelProfile");g(this,"clientRole");g(this,"env",mt.prod);g(this,"maxSignalingReconnectDuration");g(this,"stsManager");g(this,"slsReporter");this.channelProfile=e,this.clientRole=t,this.env=r,this.slsReporter=i,this.stsManager=new qr(i,r)}reset(){var e;N.info("[signalingmanager] reset"),(e=this.signaling)==null||e.reset(),this.stsManager.clear(),this.signaling=void 0,this.authInfo=void 0}join(e,t=e.userId,i,r,n){return this.maxSignalingReconnectDuration=i,this.userName=t,new Promise((c,o)=>{this.signaling?o(new V(U.ERR_JOIN_ALREADY_JOINED,"already joined")):(N.info("[signalingmanager] create signaling"),this.signaling=new Cc(this.channelProfile,this.clientRole,this.slsReporter,this.env),this.initSignaling(),r&&(r.rs=Date.now()),this.signaling.join(e,t,i,n).then(l=>{this.authInfo=e,r&&(r.re=Date.now()),c(l)}).catch(l=>{this.reset(),o(l)}),this.stsManager.startSTSUpdate(e))})}retryJoin(){const e=this.authInfo;this.reset(),e&&this.join(e,this.userName,this.maxSignalingReconnectDuration)}leave(){return new Promise((e,t)=>{this.signaling?this.signaling.leave().then(i=>{this.reset(),e(i)}).catch(i=>{t(i)}):e({tid:""})})}publish(e){return new Promise((t,i)=>{var r;this.signaling&&this.authInfo?(e.userid=this.authInfo.userId,e.displayname=(r=this.userName)!=null?r:this.authInfo.userId,this.signaling.publish(e).then(n=>{t(n)}).catch(n=>{i(n)})):i(new V(U.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL,"no signaling"))})}reportStatus(e){return new Promise((t,i)=>{this.signaling?this.signaling.reportStatus(e).then(()=>{t()}).catch(r=>{i(r)}):i(new V(-1,"no signaling"))})}setClientRole(e){return I(this,null,function*(){const t=this.clientRole;if(!this.signaling)return void(this.clientRole=e);const i=Date.now();try{const r=yield this.signaling.roleUpdate(e);return this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-i,0),r}catch(r){this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-i,r.code||-1)}})}setChannelProfile(e){this.signaling?this.signaling.setChannelProfile(e):this.channelProfile=e}refreshUrl(e){return this.signaling?this.signaling.refreshUrl(e):Promise.reject(new V(U.ERR_SDK_INVALID_STATE,"should join first"))}refreshAuthInfo(e){return I(this,null,function*(){var t;try{this.authInfo&&(this.authInfo=G(G({},this.authInfo),e),(t=this.signaling)==null||t.refreshAuthInfo(this.authInfo),this.stsManager.refreshAuthInfo(this.authInfo))}catch(i){throw i}})}initSignaling(){var e,t,i,r,n,c,o,l,d,h,p,u,f,m;(e=this.signaling)==null||e.on("onKeepAliveRsp",this.onKeepAliveRsp.bind(this)),(t=this.signaling)==null||t.on("onNotifyJoin",this.onNotifyJoin.bind(this)),(i=this.signaling)==null||i.on("onNotifyStatus",this.onNotifyStatus.bind(this)),(r=this.signaling)==null||r.on("onNotifyLeave",this.onNotifyLeave.bind(this)),(n=this.signaling)==null||n.on("onNotifyPublish",this.onNotifyPublish.bind(this)),(c=this.signaling)==null||c.on("onBye",this.onBye.bind(this)),(o=this.signaling)==null||o.on("onReconnectStart",this.onReconnectStart.bind(this)),(l=this.signaling)==null||l.on("onReconnectSuccess",this.onReconnectSuccess.bind(this)),(d=this.signaling)==null||d.on("onReconnectFail",this.onReconnectFail.bind(this)),(h=this.signaling)==null||h.on("onConnectFail",this.onConnectFail.bind(this)),(p=this.signaling)==null||p.on("onNetworkError",this.onNetworkError.bind(this)),(u=this.signaling)==null||u.on("onAuthInvalid",this.onAuthInvalid.bind(this)),(f=this.signaling)==null||f.on("onError",this.onError.bind(this)),(m=this.signaling)==null||m.on("onUnknownMessage",this.onUnknownMessage.bind(this))}onKeepAliveRsp(){this.emit("onKeepAliveRsp")}onNotifyJoin(e){this.emit("onNotifyJoin",e)}onNotifyStatus(e){this.emit("onNotifyStatus",e)}onNotifyLeave(e){this.emit("onNotifyLeave",e)}onNotifyPublish(e){this.emit("onNotifyPublish",e)}onBye(e,t){this.emit("onBye",e,t)}onConnectFail(e){this.reset(),this.emit("onConnectFail",e)}onNetworkError(e){this.emit("onNetworkError",e)}onAuthInvalid(){}onReconnectStart(){this.emit("onReconnectStart")}onReconnectSuccess(e){this.emit("onReconnectSuccess",e)}onReconnectFail(e){this.emit("onReconnectFail",e)}onError(e){this.emit("onError",e)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}}g(Xr,"logName","SignalingManager"),((s,a,e,t)=>{for(var i,r=t>1?void 0:t?Dc(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);t&&r&&Pc(a,e,r)})([C(B)],Xr.prototype,"publish",1);class bn{constructor(a){g(this,"taskProfile");g(this,"encodeParam");g(this,"users",[]);g(this,"backgroundColor",0);g(this,"backgrounds",[]);g(this,"watermarks",[]);g(this,"clockWidgets",[]);g(this,"cropMode");g(this,"mediaProcessMode");this.taskProfile=a}}class vn{constructor(a,e,t){g(this,"userId");g(this,"streamType");g(this,"sourceType");this.userId=a,this.streamType=e,this.sourceType=t}}class yn{constructor(a,e,t,i=0,r=16777215,n=Ii.NOTO_SERIF_CJKSC_REGULAR){g(this,"x");g(this,"y");g(this,"fontSize");g(this,"zOrder");g(this,"fontColor");g(this,"fontType");this.x=a,this.y=e,this.fontSize=t,this.zOrder=i,this.fontColor=r,this.fontType=n}toJson(a,e){return{x:pt(this.x,a),y:pt(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:Fr(this.fontColor),zorder:this.zOrder}}}var Rn=(s=>(s[s.NOT_DISPLAY=0]="NOT_DISPLAY",s[s.ALWAYS=1]="ALWAYS",s[s.WHEN_NO_VIDEO=2]="WHEN_NO_VIDEO",s))(Rn||{});class Yr{constructor(a,e,t,i,r,n=0,c=1,o=1){g(this,"url");g(this,"x");g(this,"y");g(this,"width");g(this,"height");g(this,"alpha");g(this,"display",1);g(this,"zOrder");this.url=a,this.x=e,this.y=t,this.width=i,this.height=r,this.zOrder=n,this.alpha=c,this.display=o}toJson(a,e){return{url:this.url,alpha:this.alpha,display:this.display,x:pt(this.x,a),y:pt(this.y,e),width:pt(this.width,a),height:pt(this.height,e),zorder:this.zOrder}}}g(Yr,"DisplayType",Rn);class An{constructor(a,e,t,i,r=0,n=16777215,c=Ii.NOTO_SERIF_CJKSC_REGULAR){g(this,"text");g(this,"x");g(this,"y");g(this,"fontSize");g(this,"zOrder");g(this,"fontColor");g(this,"fontType");this.text=a,this.x=e,this.y=t,this.fontSize=i,this.zOrder=r,this.fontColor=n,this.fontType=c}toJson(a,e){return{text:this.text,x:pt(this.x,a),y:pt(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:Fr(this.fontColor),zorder:this.zOrder}}}class _n{constructor(a,e,t,i,r,n=0,c){g(this,"userId");g(this,"x");g(this,"y");g(this,"width");g(this,"height");g(this,"zOrder");g(this,"sourceType");g(this,"segmentType",Ei.LiveTranscodingNoBody);g(this,"images",[]);g(this,"texts",[]);this.userId=typeof a=="number"?a.toString():a,this.x=e,this.y=t,this.width=i,this.height=r,this.zOrder=n,c&&(this.sourceType=c)}toJson(a,e,t,i){const r={paneid:a,majorpane:0,x:pt(this.x,e),y:pt(this.y,t),width:pt(this.width,e),height:pt(this.height,t),zorder:this.zOrder,userid:this.userId,images:this.images.map(n=>n.toJson(e,t)),texts:this.texts.map(n=>n.toJson(e,t))};return this.sourceType&&wi[this.sourceType]?r.sourcetype=wi[this.sourceType]:r.sourcetype=wi[li.LiveTranscodingCamera],this.segmentType&&i===Ki.LiveTranscodingVirtualBackground?r.segmenttype=this.segmentType:r.segmenttype=Ei.LiveTranscodingNoBody,r}}class Mc{constructor(a){g(this,"_updateables");g(this,"_useWebworker");g(this,"_inited");g(this,"_active");g(this,"_previousRAFTime");g(this,"_previousWorkerTime");g(this,"_webWorkerString");g(this,"_webWorker");g(this,"_intervalThreshold");g(this,"_rafId");this._updateables=[],this._useWebworker=!1,this._inited=!1,this._active=!1,this._previousRAFTime=void 0,this._previousWorkerTime=void 0,this._intervalThreshold=a&&a>0&&a<=60?1/a:.1,this._webWorkerString=`
329
+ `],{type:"text/javascript"}),t=(window.URL||window.webkitURL).createObjectURL(e);this.worker=new Worker(t);const{readable:i}=this.processor,{writable:n}=this.trackGenerator;this.worker.postMessage({type:"startRender",readable:i,writable:n,width:this.targetWidth,height:this.targetHeight,frameRate:this.targetFrameRate},[i,n])}updateOptions(e){super.updateOptions(e),this.worker&&this.worker.postMessage(D({type:"updateOptions"},e))}dispose(){try{this.processor.readable.cancel(),this.trackGenerator.writable.close()}catch(e){}}getVideoTrack(){return this.trackGenerator}}class Cn{static isSupport(){return typeof HTMLCanvasElement.prototype.captureStream=="function"}static getInstance(r,e){return Xd.isSupport()?new Xd(r,e):$d.isSupport()?new $d(r,e):new Kp(r,e)}}var Zd,Yd,Jp=Object.defineProperty,Vr=(s,r,e)=>(((t,i,n)=>{i in t?Jp(t,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[i]=n})(s,typeof r!="symbol"?r+"":r,e),e),_n={exports:{}},wn={exports:{}};function vt(){if(Yd)return Zd;Yd=1,Date.now=Date.now||function(){return new Date().getTime()};var s=Date.now(),r=function(){},e={noop:r,warn:function(){var t=typeof console=="object"?console.warn:r;try{var i={warn:t};i.warn.call(i)}catch(n){return r}return t}(),key:"__bl",selfErrKey:"ARMS_SDK_ERROR",selfErrPage:"ARMSSDK",win:typeof window=="object"&&window.document?window:void 0,regionMap:{cn:"https://arms-retcode.aliyuncs.com/r.png?",sg:"https://arms-retcode-sg.aliyuncs.com/r.png?",sg_2:"https://retcode-sg-lazada.arms.aliyuncs.com/r.png?",daily:"http://arms-retcode-daily.alibaba.net/r.png?",daily_2:"https://arms-retcode-daily.alibaba.net/r.png?",daily_3:"http://arms-retcode-daily.aliyun.test/r.png?",us:"https://retcode-us-west-1.arms.aliyuncs.com/r.png?",tw:"https://arms-retcode.orientalgame.com.tw/r.png?",tw_sg:"https://arms-retcode-sg.orientalgame.com.tw/r.png?",hz_finance:"https://arms-retcode-hz-finance.aliyuncs.com/r.png?"},defaultImgUrl:"https://arms-retcode.aliyuncs.com/r.png?",createObject:function(t){if(Object.create)return Object.create(t);var i=function(){};return i.prototype=t,new i},each:function(t,i){var n=0,a=t.length;if(this.T(t,"Array"))for(;n<a&&i.call(t[n],t[n],n)!==!1;n++);else for(n in t)if(i.call(t[n],t[n],n)===!1)break;return t},safetyCall:function(t,i,n){if(typeof t!="function")return n;try{return t.apply(this,i)}catch(a){return n}},T:function(t,i){var n=Object.prototype.toString.call(t).substring(8).replace("]","");return i?n===i:n},duration:function(){var t=Date;try{performance&&this.T(performance.now,"Function")&&(t=performance)}catch(n){t=Date}var i=t.now();return function(){return Math.round(t.now()-i)}},filterByRule:function(){var t=[].slice.call(arguments),i=t.length;if(i<2)return t[0];var n=t[i-1],a=t[0];if(!a)return"";if(!n)return a;var c=this,o=c.T(n),l=t.slice(0,i-1);return o==="Function"?c.safetyCall(n,l,a):o==="Array"?(this.each(n,function(d){l[0]=a=c.filterByRule.apply(c,[].concat(l,d))}),a):o==="Object"?a.replace(n.rule,n.target||""):a.replace(n,"")},ignoreByRule:function(t,i){if(!t||!i)return!1;if((this.isString(i)||i.source||this.T(i)==="Function")&&(i=[i]),!this.isArray(i))return this.warn("[arms] invalid rules of ignore config, (list of) String/RegExp/Funcitons are available"),!1;for(var n,a=[],c=0,o=i.length;c<o;c++)if(n=i[c],this.isString(n))a.push(n.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1"));else if(n&&n.source)a.push(n.source);else if(n&&this.T(n)==="Function"&&this.safetyCall(n,[t],!1)===!0)return!0;var l=new RegExp(a.join("|"),"i");return!!(a.length&&l.test&&l.test(t))},J:function(t){if(!t||typeof t!="string")return t;var i=null;try{i=JSON.parse(t)}catch(n){}return i},pick:function(t){return t===1||Math.ceil(Math.random()*t)===1},verifyConfig:function(t){if("sample"in t){var i=t.sample,n=i;i&&/^\d+(\.\d+)?%$/.test(i)&&(n=parseInt(100/parseFloat(i))),0<n&&1>n&&(n=parseInt(1/n)),n>=1&&n<=100?t.sample=n:delete t.sample}return t},on:function(t,i,n,a,c){return t.addEventListener?(c=c||!1,t.addEventListener(i,function o(l){a&&t.removeEventListener(i,o,c),n.call(this,l)},c)):t.attachEvent&&t.attachEvent("on"+i,function o(l){a&&t.detachEvent("on"+i,o),n.call(this,l)}),this},off:function(t,i,n){return n?(t.removeEventListener?t.removeEventListener(i,n):t.detachEvent&&t.detachEvent(i,n),this):this},delay:function(t,i){return i===-1?(t(),null):setTimeout(t,i||0)},ext:function(t){for(var i=1,n=arguments.length;i<n;i++){var a=arguments[i];for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(t[c]=a[c])}return t},sub:function(t,i){var n={};return this.each(t,function(a,c){i.indexOf(c)!==-1&&(n[c]=a)}),n},uu:function(){for(var t,i,n=20,a=new Array(n),c=Date.now().toString(36).split("");n-- >0;)i=(t=36*Math.random()|0).toString(36),a[n]=t%3?i:i.toUpperCase();for(var o=0;o<8;o++)a.splice(3*o+2,0,c[o]);return a.join("")},guid:function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var i=16*Math.random()|0;return(t==="x"?i:3&i|8).toString(16)})},seq:function(){return(s++).toString(36)},decode:function(t){try{t=decodeURIComponent(t)}catch(i){}return t},encode:function(t,i){try{t=i?encodeURIComponent(t).replace(/\(/g,"%28").replace(/\)/g,"%29"):encodeURIComponent(t)}catch(n){}return t},serialize:function(t){t=t||{};var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&t[n]!==void 0&&i.push(n+"="+this.encode(t[n],n==="msg"));return i.join("&")},checkAPI:function(t,i){if(!t||typeof t!="string")return!1;var n=/arms-retcode[\w-]*\.aliyuncs/.test(t);return!n&&i&&(n=/(alicdn\.com)|(mmstat\.com)/.test(t)),!n},checkAutoError:function(t){return!(!t||!t.message||/failed[\w\s]+fetch/i.test(t.message))},cutUrlSearch:function(t){return t&&typeof t=="string"?t.replace(/^(https?:)?\/\//,"").replace(/\?.*$/,""):""},removeUrlSearch:function(t){return t&&typeof t=="string"?t.replace(/\?.*$/,""):""},createFakeToString:function(t){return function(){return t+"() { [native code] }"}},checkSameOrigin:function(t,i){if(!i||!t)return!1;var n="//"+i.split("/")[2];return t===i||t.slice(0,i.length+1)===i+"/"||t===n||t.slice(0,n.length+1)===n+"/"||!/^(\/\/|http:|https:).*/.test(t)},getRandIP:function(){for(var t=[],i=0;i<4;i++){var n=Math.floor(256*Math.random());t[i]=(n>15?"":"0")+n.toString(16)}return t.join("").replace(/^0/,"1")},getSortNum:function(t){return t?(t+=1)>=1e3&&t<=9999?t:t<1e3?t+1e3:t%1e4+1e3:1e3},getRandNum:function(t){return t&&typeof t=="string"?t.length<5?this.getNum(5):t.substring(t.length-5):this.getNum(5)},getNum:function(t){for(var i=[],n=0;n<t;n++){var a=Math.floor(16*Math.random());i[n]=a.toString(16)}return i.join("")},getCurDomain:function(){return location&&location.hostname||""},getSrcType:function(t,i){var n=location&&location.host||"";if(!n)return"";var a=new URL(t).host;if(a===n)return"self";for(var c=0;c<i.length;c+=1)if(a.includes(i[c]))return"cdn";return"others"},parseFetchHeaders:function(t){if(!t)return{};var i={};try{if(typeof t.keys=="function")for(var n=t.keys(),a=n.next();!a.done;){var c=a.value;i[c]=t.get(c),a=n.next()}else i=t}catch(o){i={}}return i},parseXhrHeaders:function(t){if(!t&&typeof t!="string")return{};var i={};try{i=t.split(`\r
330
+ `).reduce(function(n,a){var c=a.split(": ");return n[c[0]]=c[1],n},{})}catch(n){i={}}return i},getQuerys:function(t){if(!t)return"";var i={},n=[],a="",c="";try{var o=[];if(t.indexOf("?")>=0&&(o=t.substring(t.indexOf("?")+1,t.length).split("&")),o.length>0)for(var l in o)a=(n=o[l].split("="))[0],c=n[1],i[a]=c}catch(d){i={}}return i},getURL:function(t){if(!t)return null;var i={},n=t.length,a=t.indexOf("://");if(a<0)return null;i.protocol=t.substring(0,a+1);var c=t.indexOf("#"),o=t.indexOf("?");c<0&&(c=n),o<0&&(o=c),i.search=t.substring(o,c).substring(0,1e3);var l=t.substring(a+3,o),d=l.indexOf("/");return d<0&&(d=l.length),i.domain=l.substring(0,d).split(":")[0],i.path=l.substring(d,l.length).substring(0,1e3),i},getResType:function(t,i){if(["script","img","other"].indexOf(t)>-1)return t;if(["video"].indexOf(t)>-1)return"media";if(["document","iframe"].indexOf(t)>-1)return"doc";var n=i?this.getURL(i):null,a=n&&n.path?n.path.lastIndexOf("."):-1,c=(a>0?n.path.substr(a+1):"").toLowerCase();if(c){if(["eot","woff","woff2","ttf"].indexOf(c)>-1)return"font";if(c==="css")return"css";if(c==="js")return"script"}return["fetch","xmlhttprequest","beacon"].indexOf(t)>-1?"api":"others"},areInOrder:function(){for(var t=1;t<arguments.length;t+=1)if(arguments[t-1]>arguments[t])return!1;return!0},getFetchSnapshot:function(t,i,n){var a,c;try{var o=(t&&typeof t[0]!="string"?t[0].url:t[0])||"",l=(t&&typeof t[0]!="string"?t[0]:t[1])||{},d=l.method.toUpperCase()==="POST"?l.body:this.getQuerys(o);a={originApi:o,method:l.method||"unknown",params:d,response:i||"",reqHeaders:this.parseFetchHeaders(l.headers||null),resHeaders:this.parseFetchHeaders(n)},c=JSON&&JSON.stringify(a)||"{}"}catch(h){c="{}"}return c},getXhrSnapshot:function(t,i,n){if(!t||!i||!n)return{};var a,c;try{var o="";n.responseType===""||n.responseType==="text"?o=n.responseText:n.responseType==="document"&&(o=n.responseXML),a={originApi:t,method:i,params:this.getQuerys(t),response:o,reqHeaders:{},resHeaders:this.parseXhrHeaders(typeof n.getAllResponseHeaders=="function"&&n.getAllResponseHeaders()||"")},c=JSON&&JSON.stringify(a)||"{}"}catch(l){c="{}"}return c},isRobot:function(){var t=["nuhk","googlebot/","googlebot-image","yammybot","openbot","slurp","msnbot","ask jeeves/teoma","ia_archiver","baiduspider","bingbot/","adsbot"];if(!navigator||typeof navigator.userAgent!="string")return!1;try{for(var i=navigator.userAgent.toLowerCase(),n=0;n<t.length;n++){var a=t[n];if(i.lastIndexOf(a)>=0)return!0}}catch(c){this.warn("[arms] useragent parse error")}return!1},isFunction:function(t){return typeof t=="function"},isPlainObject:function(t){return Object.prototype.toString.call(t)==="[object Object]"},isString:function(t){return Object.prototype.toString.call(t)==="[object String]"},isArray:function(t){return Object.prototype.toString.call(t)==="[object Array]"},joinRegExp:function(t){for(var i,n=[],a=0,c=t.length;a<c;a++)i=t[a],this.isString(i)?n.push(i.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")):i&&i.source&&n.push(i.source);return new RegExp(n.join("|"),"i")},reWriteMethod:function(t,i,n){if(t!==null){var a=t[i];t[i]=n(a)}},checkSDKError:function(t,i){return!(!t&&!i)&&(!!new RegExp(this.selfErrKey,"i").test(t)||!!this.ignoreByRule(i,[/retcode.alicdn.com\/retcode\/bl.js/,/g.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/laz-g-cdn.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/local.taobao.com:8880\/build\/bl/]))},sdkError:function(t){return{msg:t,message:this.selfErrKey}},dealParam:function(t,i,n){var a={};try{a=this.isPlainObject(t)?this.ext({key:t.key||"default",val:t.val||t.value||n},t,{begin:Date.now()}):{key:t||"default",val:i||n,begin:Date.now()}}catch(c){this.warn("[retcode] baseLog error: "+c)}return a}};return Zd=e}var An,Qd,qd,el,In={exports:{}},Pn={exports:{}};function $p(){if(qd)return Pn.exports;qd=1;var s=vt(),r=function(){if(Qd)return An;Qd=1;var n=vt();return An=function(a,c,o){typeof a=="object"&&(a=n.serialize(a));var l=c+a+(o?"&post_res=":"");window&&window.navigator&&typeof window.navigator.sendBeacon=="function"?window.navigator.sendBeacon(l,o||"&post_res="):n.warn("[arms] navigator.sendBeacon not surported")},An}(),e="aokcdqn3ly@e629dabd48a9933",t=function(n,a){var c;if(a.t==="error"&&(c=n.requestQueue[0])&&c.t==="error"&&a.msg===c.msg)return a.times=c.times+1,void(n.requestQueue[0]=a);if(a.t==="behavior"){var o=n.requestQueue&&n.requestQueue.length;if(o>0&&n.requestQueue[o-1].t==="behavior"){var l=a.behavior||[];n.requestQueue[o-1].behavior.concat(l)}else n.requestQueue.push(a)}else n.requestQueue.unshift(a);return n.onReady(function(){n.requestTimmer=s.delay(function(){n.clear()},n.requestQueue[0]&&n.requestQueue[0].t==="error"?3e3:-1)}),!0},i=function(n){return this.ver="1.8.36-beta.12",this._conf=s.ext({},i.dftCon),this.sampleCache={},this.requestQueue=[],this.selfQueue=[],this.sdkFlag=!0,this.hash=s.seq(),this.resetPageview(),this.setConfig(n),this.rip=s.getRandIP(),this.record=999,this["EagleEye-TraceID"]=this.getTraceId()["EagleEye-TraceID"],this._common={},this};return i.dftCon={sample:1,pvSample:1,tag:"",imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",region:null,ignore:{ignoreUrls:[],ignoreApis:[],ignoreErrors:[/^Script error\.?$/],ignoreResErrors:[],ignoreResources:[/\/(bl|wl)(.debug)?.js$/]},release:void 0,environment:"prod",beforeReport:null,parseTraceId:null},i.prototype={constructor:i,onReady:function(n){return n()},getPage:function(){var n=this._conf.page;return s.safetyCall(n,[],n+"")},setPage:function(){},setConfig:function(n){n&&typeof n=="object"&&(s.verifyConfig(n),n=this.setImgUrl(n),this._conf=s.ext({},this._conf,n))},setImgUrl:function(n){var a=n.region,c=n.imgUrl;if(a){var o=s.regionMap[a];return n.imgUrl=o||s.defaultImgUrl,n}return c&&(n.imgUrl=c),n},checkImgUrl:function(){return!0},sendRequest:function(){},sendBeacon:function(n,a,c){r(n,a||this.getConfig("imgUrl"),c)},postData:function(){},commonInfo:function(){return{}},setCommonInfo:function(n){n&&typeof n=="object"&&(this._common=s.ext({},this._common,n))},resetPageview:function(){this.pageview=s.uu(),this.sBegin=Date.now()},getUsername:function(){if(this.username)return this.username;var n=this._conf,a=n&&n.setUsername;if(typeof a=="function")try{var c=a();typeof c=="string"&&(c=c.substr(0,40),this.username=c)}catch(o){s.warn("[arms] setUsername fail",o)}return this.username},getTraceId:function(){var n=this.rip,a=Date.now(),c=s.getSortNum(this.record),o=n+a+c+s.getRandNum(this._conf.pid);return this["EagleEye-TraceID"]=o,this.record=c,{"EagleEye-TraceID":o}},getUberTraceId:function(n){var a=this.rip,c=Date.now(),o=s.getSortNum(this.record),l=s.getRandNum(this._conf.pid),d=a+c+o+s.getNum(2)+l,h=d.substring(0,16);return n=n?"1":"0",d[0]==="0"&&(d[0]="1"),d[16]==="0"&&(d[16]="1"),{"uber-trace-id":d+":"+h+":0:"+n,traceId:d}},getB3TraceId:function(n){var a=this.rip,c=Date.now(),o=s.getSortNum(this.record),l=s.getRandNum(this._conf.pid),d=a+c+o+s.getNum(2)+l,h=d.substring(0,16);return n=n?"1":"0",d[0]==="0"&&(d[0]="1"),d[16]==="0"&&(d[16]="1"),{b3:d+"-"+h+"-"+n+"-0","X-B3-TraceId":d,"X-B3-ParentSpanId":"0","X-B3-SpanId":h,"X-B3-Sampled":n}},getPageviewId:function(){return{"EagleEye-SessionID":this.pageview}},getConfig:function(n){return n?this._conf[n]:s.ext({},this._conf)},sampling:function(n){return n===1||(typeof this.sampleCache[n]=="boolean"||(this.sampleCache[n]=s.pick(n)),this.sampleCache[n])},clear:function(n){var a;clearTimeout(this.requestTimmer),this.requestTimmer=null;for(var c=this._conf&&typeof this._conf.sendRequest=="function";a=this.requestQueue.pop();)if(a.t==="res")this.postData(a,"res");else if(a.t==="error")this.postData(a,"err");else if(a.t==="api")this.postData(a,"apiSnapshot");else if(a.t==="behavior")this.postData(a,"behavior");else if(a.t==="health"&&!c&&window&&window.navigator&&typeof window.navigator.sendBeacon=="function")this.sendBeacon(a);else if(a.t==="resource"&&!c&&window&&window.navigator&&typeof window.navigator.sendBeacon=="function"){var o=JSON.stringify({resource:a.resource});delete a.resource,this.sendBeacon(a,null,o)}else a.t==="resource"?this.postData(a,"resource"):this.sendRequest(a);return n&&this.clearSelf(),this},clearSelf:function(){var n;for(clearTimeout(this.Timmer),this.Timmer=null;n=this.selfQueue.pop();)this.postData(n,"err");return this},_lg:function(n,a,c,o){var l=this,d=l._conf,h=l.getPage(),u=d.ignore||{},p=u.ignoreErrors,f=u.ignoreResErrors,m=u.ignoreUrls,g=u.ignoreApis;if(l._isRobot||s.ignoreByRule(h,m)||s.ignoreByRule(s.decode(h),m)||n==="error"&&(s.ignoreByRule(a.msg,p)||s.ignoreByRule(s.decode(a.msg),p))||n==="resourceError"&&(s.ignoreByRule(a.src,f)||s.ignoreByRule(s.decode(a.src),f))||n==="api"&&(s.ignoreByRule(a.api,g)||s.ignoreByRule(s.decode(a.api),g))||!l.checkImgUrl(d.imgUrl)||!a||d.disabled||!d.pid||o===0)return l;var S=a.dl;if(delete a.dl,a=s.ext({t:n,times:1,page:h,tag:d.tag||"",release:d.release||"",environment:d.environment,begin:Date.now(),c1:d.c1,c2:d.c2,c3:d.c3},a,l.commonInfo(),l._common,{pid:d.pid,_v:l.ver,pv_id:l.pageview,username:l.getUsername(),sampling:c||1,dl:S,z:s.seq()}),s.T(d.beforeReport)==="Function")try{if(!(a=d.beforeReport(a)))return l}catch(v){return l}return o===1?t(l,a):c&&!l.sampling(c)?l:t(l,a)},_self:function(n,a,c){var o=this,l=o._conf;if(n!=="error"||!o.checkImgUrl(l.imgUrl)||!a||l.disabled||!l.pid||c&&!o.sampling(c))return o;a=s.ext({t:n,times:1,page:s.selfErrPage,tag:l.pid,begin:Date.now()},a,{pid:e,_v:o.ver,sampling:c||1,z:s.seq()});var d=o.selfQueue[0];if(d){d.times++;try{d.err&&a.err&&d.err.msg_raw&&a.err.msg_raw&&d.err.msg_raw.split("&").indexOf(a.err.msg_raw)<0&&d.err.msg_raw.length<1e3&&(d.err.msg_raw+="&"+a.err.msg_raw)}catch(h){}}else o.selfQueue.unshift(a),o.onReady(function(){o.sdkFlag&&(o.sdkFlag=!1,o.Timmer=s.delay(function(){o.clearSelf()},1e4))})},custom:function(n,a){if(!n||typeof n!="object")return this;var c=!1,o={begin:Date.now()};return s.each(n,function(l,d){return!(c=d&&d.length<=20)&&s.warn("[retcode] invalid key: "+d),o["x-"+d]=l,c}),c?this._lg("custom",o,a||1):this}},Pn.exports=i,Pn.exports}var tl,Dn={exports:{}},rl,kn,il,Mn={exports:{}};function Xp(){if(il)return kn;il=1;var s=vt();return kn=function(r,e){var t=[],i=null,n=e&&e.location&&e.location.href,a=void 0,c=null,o=function(h,u,p){if(h!==null){var f=h[u];h[u]=p(f)}},l=function(h){var u,p,f,m,g,S=[];if(!h||typeof h.tagName!="string")return"";if(S.push(h.tagName.toLowerCase()),typeof h.id=="string"&&S.push("#".concat(h.id)),typeof(u=h.className)=="string")for(p=u.split(/\s+/),g=0;g<p.length;g++)S.push(".".concat(p[g]));var v=["type","name","title","alt","data-arms-attr"];for(g=0;g<v.length;g++)f=v[g],typeof(m=h.getAttribute(f))=="string"&&S.push("[".concat(f,'="').concat(m,'"]'));return S.join("")},d=function(h,u){return function(p){if(p&&p!==c){var f;c=p;try{f=p.target}catch(g){f="<unknown>"}if(f.length!==0){var m={type:"ui.".concat(h),data:{message:function(g){if(!g||g.nodeType!==1)return"";for(var S=g||null,v=[],E=0,T=0,R="";S&&E++<5&&!((R=l(S))==="html"||E>1&&T+3*v.length+R.length>=80);)v.push(R),T+=R.length,S=S.parentNode;return v.reverse().join(" > ")}(f)},timestamp:Date.now()};h==="click"?i&&i.addBehavior(m):h==="keypress"&&(a||i&&i.addBehavior(m),clearTimeout(a),a=setTimeout(function(){a=void 0},100))}}}};s.ext(r.prototype,{addBehavior:function(h){if(this.getConfig("behavior")&&h&&typeof h=="object"){var u={},p=h.data||{};if(h.type)u=p;else{if(typeof p.name!="string"||typeof p.message!="string")return;u.name=p.name.substr(0,20),u.message=p.message.substr(0,200)}u.message&&(u.message=s.encode(u.message));var f={type:h.type||"custom",data:u||{},timestamp:h.timestamp||Date.now(),page:h.page||e&&e.location&&e.location.pathname};return t.push(f),t=t.slice(-100)}},getBehavior:function(){return t||[]},setBehavior:function(h){return h&&(t=h),t},reportBehavior:function(h){var u=this;u.getConfig("behavior")&&(u.sendBhTimer&&(clearTimeout(u.sendBhTimer),u.sendBhTimer=void 0),u.sendBhTimer=setTimeout(function(){t&&t.length>0&&(u.behavior(t),t=[],u.sendBhTimer=void 0,h&&typeof h=="function"&&h())},0))},initBehavior:function(){if(!this.hasInitBehavior&&!i){try{(function(){if(document&&document.referrer&&document.location){var u=document.referrer,p=document.location.href;if(u!==""){var f={type:"navigation",data:{from:u,to:p}};n=p,i&&i.addBehavior(f)}}})(),e&&e.document&&e.document.addEventListener&&(e.document.addEventListener("click",d("click"),!1),e.document.addEventListener("keypress",d("keypress"),!1)),function(){if(function(){var m=e&&e.chrome,g=m&&m.app&&m.app.runtime,S="history"in e&&!!e.history.pushState&&!!e.history.replaceState;return!g&&S}()){var u=function(m,g){var S={type:"navigation",data:{from:m,to:g}};i&&i.addBehavior(S),n=g},p=e.onpopstate;e.onpopstate=function(){for(var m=arguments.length,g=new Array(m),S=0;S<m;S++)g[S]=arguments[S];var v=e.location.href;if(u(n,v),p)return p.apply(this,g)};var f=function(m){return function(){for(var g=arguments.length,S=new Array(g),v=0;v<g;v++)S[v]=arguments[v];var E=S.length>2?S[2]:void 0;return E&&u(n,String(E)),m.apply(this,S)}};o(e.history,"pushState",f),o(e.history,"replaceState",f)}}();var h=this.getConfig("enableConsole");h&&function(u){if(e&&e.console){var p=["debug","info","warn","log","error","assert"];s.isArray(u)&&(p=u);for(var f=0;f<p.length;f++){var m=p[f];m&&s.isString(m)&&e.console[m]&&typeof e.console[m]=="function"&&o(e.console,m,function(g){var S=m;return function(){for(var v=arguments.length,E=new Array(v),T=0;T<v;T++)E[T]=arguments[T];var R={type:"console",data:{level:S,message:E}};if(i&&i.addBehavior(R),S==="error")for(var y=0;y<E.length;y++){var C=E[y];C&&C.message&&C.stack&&i&&i.errorHandler(new ErrorEvent("error",{error:C,message:C.message}))}g&&Function.prototype.apply.call(g,e.console,E)}})}}}(h)}catch(u){s.warn("[arms] error in initBehavior",u)}i=this,this.hasInitBehavior=!0}return this}})},kn}var sl,On,nl,Nn,al,ol,cl,Ln,dl,ll,hl,ul,pl,xn,ml,fl,gl,Sl={};function Vn(){return sl||(sl=1,Sl.TIMING_KEYS=["startTime","fetchStart","domainLookupStart","domainLookupEnd","connectStart","connectEnd","requestStart","responseStart","responseEnd","","domInteractive","","domContentLoadedEventEnd","","loadEventStart","","msFirstPaint","secureConnectionStart","redirectStart","redirectEnd"]),Sl}function Zp(){return cl||(cl=1,ol=function(s,r,e){var t=vt(),i=function(){if(nl)return On;nl=1;var m=vt(),g=Vn().TIMING_KEYS;return On=function(){var S=m.win||{},v=S.performance;if(!v||typeof v!="object"||typeof v.getEntriesByType!="function")return null;var E={},T=v.timing||{},R=v.getEntriesByType("resource")||[];if(E.begin=T[g[1]]||Date.now(),typeof S.PerformanceNavigationTiming=="function"){var y=v.getEntriesByType("navigation")[0];y&&(T=y)}return m.each({dom:[10,8],load:[14,1]},function(C,w){var A=T[g[C[1]]],P=T[g[C[0]]];if(A>0&&P>0){var M=Math.round(P-A);M>=0&&M<6e5&&(E[w]=M)}}),E.res=JSON.stringify(R),E},On}(),n=function(){if(al)return Nn;al=1;var m=vt(),g=Vn().TIMING_KEYS;return Nn=function(){var S=m.win||{},v=S.performance;if(!v||typeof v!="object")return null;var E={},T=v.timing||{},R=Date.now(),y=1;if(typeof S.PerformanceNavigationTiming=="function"){var C=v.getEntriesByType("navigation")[0];C&&(T=C,y=2)}m.each({dns:[3,2],tcp:[5,4],ssl:[5,17],ttfb:[7,6],trans:[8,7],dom:[10,8],res:[14,12],firstbyte:[7,2],fpt:[8,1],tti:[10,1],ready:[12,1],load:[14,1]},function(I,j){var K=T[g[I[1]]],B=T[g[I[0]]];if(y===2||K>0&&B>0){var F=Math.round(B-K);F>=0&&F<6e5&&(E[j]=F)}});var w=S.navigator.connection,A=v.navigation||{};E.ct=w?w.effectiveType||w.type:"";var P=w&&(w.downlink||w.downlinkMax||w.bandwidth)||null;if((P=P>999?999:P)&&(E.bandwidth=P),E.navtype=A.type===1?"Reload":"Other",y===1&&T[g[16]]>0&&T[g[1]]>0){var M=T[g[16]]-T[g[1]];M>=0&&M<36e5&&(E.fpt=M)}return y===1&&T[g[1]]>0?E.begin=T[g[1]]:y===2&&E.load>0?E.begin=R-E.load:E.begin=R,E},Nn}(),a=null,c=e.documentElement,o=r.innerWidth||c.clientWidth||e.body.clientWidth,l=r.innerHeight||c.clientHeight||e.body.clientHeight,d=r.navigator.connection,h={sr:screen.width+"x"+screen.height,vp:o+"x"+l,ct:d?d.effectiveType||d.type:""},u={},p=function(m,g,S,v,E){if(g===void 0){var T,R;if(!u[m]){T=new RegExp(m+"=([^;]+)");try{R=T.exec(e.cookie)}catch(C){return t.warn("[retcode] can not get cookie:",C),null}R&&(u[m]=R[1])}return u[m]}var y=m+"="+g;y+="; path=/",S&&(y+="; max-age="+S);try{return e.cookie=y,!!e.cookie}catch(C){return t.warn("[retcode] can not set cookie: ",C),!1}},f=function(m){var g=m._conf.uid||p("_nk_")||p("_bl_uid");return g||(g=t.uu(),p("_bl_uid",g,15552e3))?g:null};return t.ext(s.prototype,{activeErrHandler:function(m){return a&&!m||(a=this),this},errorHandler:function(m){if(!m)return this;var g=m.type;if(g==="error"){var S=m.target||m.srcElement;!S||!S.tagName||m.message||m.filename||m.lineno||m.colno?this.error(m.error||{message:m.message},m):this.resourceErrorHandler(m)}else g==="unhandledrejection"&&t.T(m.reason,"Error")&&t.checkAutoError(m.reason)&&this.error(m.reason);try{this.getConfig("behavior")&&this.reportBehavior&&this.reportBehavior()}catch(v){}return this},resourceErrorHandler:function(m){var g=this,S=m.target||m.srcElement;try{var v=g.getSrc(S),E=typeof S.tagName=="string"?S.tagName.toLowerCase():"",T=g.getXPath(S,5),R=t.getURL(v),y={src:v&&v.substring(0,1e3),node_name:E,xpath:T,res_type:t.getResType(E,v),res_name:R.path,domain:R.domain};return g._conf.enableResource&&g.fixResourceStatus&&m.timeStamp&&g.fixResourceStatus({src:v,node_name:E,res_type:t.getResType(E,v),timeStamp:m.timeStamp,domain:R.domain}),g._lg("resourceError",y),g}catch(C){return t.warn("[ARMS] resourceErrorHandler error :",C),g}},getSrc:function(m){var g=m.src||m.href;try{if(!g){var S=(typeof m.tagName=="string"?m.tagName.toLowerCase():"")==="object",v=m.getAttribute("classid")&&m.getAttribute("classid").toLowerCase()==="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"||m.getAttribute("type")==="application/x-shockwave-flash";S&&v&&(g=m.getAttribute("data")||m.getAttribute("codebase")),g||(g=m.outerHTML||m.innerHTML)}}catch(E){g=""}return g},getXPath:function(m,g){var S=m.id?"#"+m.id:"",v=typeof m.className=="string"?"."+m.className.split(" ").join("."):"",E=(typeof m.tagName=="string"?m.tagName.toLowerCase():"")+S+v;return m.parentNode&&m.parentNode.tagName&&g-1!=0?this.getXPath(m.parentNode,g-1)+" > "+E:E},sendPerformance:function(m){var g=this;g.onReady(function(){var S=n();S&&S.load&&S.load>0&&(S.page=g.getPage(!0),m&&(S=t.ext(S,m)),S.autoSend=!0,g.performance(S))})},sendResources:function(m){var g=this;g.onReady(function(){var S=i();S&&S.load&&S.load>0&&(S.load&&S.load<=2e3||S.load&&S.load<=8e3&&Math.random()>.05||(S.page=g.getPage(!0),S.dl=location.href,m&&(S=t.ext(S,m)),g._lg("res",S,g.getConfig("sample"))))})},sendPV:function(){var m=this;m.onReady(function(){var g,S,v=(g=f(m),S=r.devicePixelRatio||1,{uid:g,dt:e.title,dl:location.href,dr:e.referrer,dpr:S.toFixed(2),de:(e.characterSet||e.defaultCharset||"").toLowerCase(),ul:c.lang,begin:Date.now()});v&&v.uid&&m._lg("pv",v,m.getConfig("pvSample"))})},commonInfo:function(){return h.uid=f(this),h.sid=function(m){if(m.session)return m.session;var g;try{if(typeof window=="object"&&typeof sessionStorage=="object"&&typeof sessionStorage.getItem=="function")return typeof(g=sessionStorage.getItem("_bl_sid"))=="string"?(m.session=g,g):(g=t.uu(),m.session=g,typeof sessionStorage.setItem=="function"&&sessionStorage.setItem("_bl_sid",g),g)}catch(S){t.warn("[ARMS] getSid error :",S)}return m.session=g=t.uu(),g}(this),h},handleUnload:function(m){var g=Date.now();if(g-this._lastUnload<200)return this;this._lastUnload=g,this.sendHealth(m),this.speedCache&&(this._lg("speed",this.speedCache),this.speedCache=null,clearTimeout(this.speedTimmer)),this._conf&&this._conf.enableResource&&this.resourceComboReport(),this.clear(!0)},bindHashChange:function(m){var g=this;if(!m^g.hashChangeHandler)return g;m?(g.hackHistoryState(),g.hashChangeHandler=function(S){var v=g._conf.parseHash(location.hash);v&&g.setPage(v,S!==!1)},g.stateChangeHandler=function(S){var v=g._conf.parseHash(S.detail);v&&g.setPage(v)},t.on(r,"hashchange",g.hashChangeHandler),t.on(r,"historystatechange",g.stateChangeHandler),g.hashChangeHandler(!1)):(t.off(r,"hashchange",g.hashChangeHandler),t.off(r,"historystatechange",g.stateChangeHandler),g.hashChangeHandler=null,g.stateChangeHandler=null)},initHandler:function(){var m=this;if(m.hasInitHandler)return m;var g=m._conf;return t.on(r,"beforeunload",function(){m.handleUnload(0)}),m.bindHashChange(g.enableSPA),m.activeErrHandler(!1),m.hasInitHandler=!0,m}}),t.on(r,"error",function(m){a&&a.errorHandler(m)},!1,!0).on(r,"unhandledrejection",function(m){a&&a.errorHandler(m)}),s}),ol}function Yp(){if(dl)return Ln;dl=1;var s=vt();return Ln=function(r,e,t){function i(d,h,u){var p=0,f=d.tagName;if(f!=="SCRIPT"&&f!=="STYLE"&&f!=="META"&&f!=="HEAD"){var m=d.children?d.children.length:0;if(m>0)for(var g=d.children,S=m-1;S>=0;S--)p+=i(g[S],h+1,p>0);if(p<=0&&!u&&!(d.getBoundingClientRect&&d.getBoundingClientRect().top<a))return 0;p+=1+.5*h}return p}function n(d){for(var h=1;h<d.length;h++)if(d[h].score<d[h-1].score)return d.splice(h,1),n(d);return d}var a=e.innerHeight||0,c=[],o=null,l=0;s.ext(r.prototype,{initFmpObserver:function(d){var h=this;if(!h._conf||!h._conf.useFmp)return null;if(!e.MutationObserver)return s.warn("[retcode] first meaningful paint can not be retrieved"),h.sendPerformance(),null;s.on(e,"beforeunload",function(){h.endObserving(0,!0)});var u=e.MutationObserver;return(o=new u(function(){(function(p){var f=Date.now()-p,m=t.querySelector("body");if(m){var g=0;g+=i(m,1,!1),c.push({score:g,t:f})}else c.push({score:0,t:f})})(h._startTime)})).observe(document,{childList:!0,subtree:!0}),l=1,h.onReady(function(){h.endObserving(d)}),o},endObserving:function(d,h){var u,p,f,m=this;if(o&&l)if(m.fmpTimmer&&(clearTimeout(m.fmpTimmer),m.fmpTimmer=null),h||(u=m._startTime,p=d,(f=Date.now()-u)>p||f-(c&&c.length&&c[c.length-1].t||0)>1e3)){o.disconnect(),l=0,c=n(c);for(var g=null,S=1;S<c.length;S++)if(c[S].t>=c[S-1].t){var v=c[S].score-c[S-1].score;(!g||g.rate<=v)&&(g={t:c[S].t,rate:v})}g&&g.t>0&&g.t<36e5?m.sendPerformance({fmp:g.t}):m.sendPerformance()}else m.fmpTimmer=s.delay(function(){m.endObserving(d)},500)}})},Ln}function Qp(){if(fl)return wn.exports;fl=1;var s=vt(),r=function(){if(el)return In.exports;el=1;var o=vt(),l=$p(),d=["api","success","time","code","msg","trace","traceId","begin","pv_id","sid","seq","domain","flag","apiSnapshot","tag","c1","c2","c3"],h=function(p){var f=(p.key||"default").split("::");return f.length>1?o.ext(p,{group:f[0],key:f[1]}):o.ext(p,{group:"default_group",key:f[0]})},u=function(p){var f;l.call(this,p);try{f=typeof performance=="object"?performance.timing.fetchStart:Date.now()}catch(m){f=Date.now()}return this._startTime=f,this};return u.prototype=o.createObject(l.prototype),o.ext(l.dftCon,{startTime:null}),o.ext(u.prototype,{constructor:u,_super:l,sum:function(p,f,m){try{var g=o.dealParam(p,f,1);return this._lg("sum",h(g),m)}catch(S){o.warn("[retcode] can not get parseStatData: "+S)}},avg:function(p,f,m){try{var g=o.dealParam(p,f,0);return this._lg("avg",h(g),m)}catch(S){o.warn("[retcode] can not get parseStatData: "+S)}},percent:function(p,f,m,g){try{return this._lg("percent",h({key:p,subkey:f,val:m||0,begin:Date.now()}),g)}catch(S){o.warn("[retcode] can not get parseStatData: "+S)}},msg:function(p,f){if(p&&!(p.length>180))return this.custom({msg:p},f)},error:function(p,f){if(!p)return o.warn("[retcode] invalid param e: "+p),this;arguments.length===1?(typeof p=="string"&&(p={message:p},f={}),typeof p=="object"&&(f=p=p.error||p)):(typeof p=="string"&&(p={message:p}),typeof f!="object"&&(f={}));var m=p.name||"CustomError",g=p.message||"",S=p.stack||"";f=f||{};var v=typeof location=="object"&&typeof location.href=="string"&&location.href.substring(0,500)||"";if(o.checkSDKError(g,f.filename)){var E=/^Script error\.?$/,T=p.msg||p.message;if(o.ignoreByRule(T,E)||o.ignoreByRule(o.decode(T),E))return this;var R={msg:o.selfErrKey,err:{msg_raw:o.encode(p.msg||p.message)}};return this._self("error",R,1)}for(var y={begin:Date.now(),cate:m,msg:g&&g.substring(0,1e3),stack:S&&S.substring(0,1e3),file:o.removeUrlSearch(f.filename||""),line:f.lineno||"",col:f.colno||"",err:{msg_raw:o.encode(g),stack_raw:o.encode(S)},dl:v},C=["tag","c1","c2","c3"],w=0;w<C.length;w++){var A=C[w];f[A]&&(y[A]=f[A])}var P=(this.getConfig("ignore")||{}).ignoreErrors;return o.ignoreByRule(y.msg,P)||o.ignoreByRule(o.decode(y.msg),P)?this:(this.beforeSend&&this.beforeSend("error",y),this._lg("error",y,1))},behavior:function(p){if(p){var f=typeof p=="object"&&p.behavior?p:{behavior:p};return this.beforeSend&&this.beforeSend("behavior",f),this._lg("behavior",f,1)}},api:function(p,f,m,g,S,v,E,T,R,y,C,w,A,P,M,I){if(!p)return o.warn("[retcode] api is null"),this;if(p=typeof p=="string"?{api:p,success:f,time:m,code:g,msg:S,begin:v,traceId:E,pv_id:T,apiSnapshot:R,domain:y,flag:w,tag:A,c1:P,c2:M,c3:I}:o.sub(p,d),!o.checkAPI(p.api,!0))return this;p.code=p.code||"";var j=p.msg||"";if(j=typeof j=="string"?j.substring(0,1e3):j,p.msg=j,p.success=p.success?1:0,p.time=+p.time,p.begin=p.begin,p.traceId=p.traceId||"",p.pv_id=p.pv_id||"",p.domain=p.domain||"",p.flag=p.flag,p.dl=typeof location=="object"&&typeof location.href=="string"&&location.href.substring(0,500)||"",p.apiSnapshot&&(typeof p.apiSnapshot=="object"&&(p.apiSnapshot=JSON.stringify(p.apiSnapshot)),typeof p.apiSnapshot!="string"&&delete p.apiSnapshot,p.apiSnapshot.length>2e3&&(p.apiSnapshot=p.apiSnapshot.substring(0,2e3))),C&&(p.traceOrigin=C),!p.api||isNaN(p.time))return o.warn("[retcode] invalid time or api"),this;var K=(this.getConfig("ignore")||{}).ignoreApis;return o.ignoreByRule(p.api,K)||o.ignoreByRule(o.decode(p.api),K)||p.time<0?this:(this.beforeSend&&this.beforeSend("api",p),this._lg("api",p,p.success&&this.getConfig("sample"),p.flag))},speed:function(p,f,m){var g=this,S=this.getConfig("startTime")||this._startTime;return/^s(\d|1[0])$/.test(p)?(f=typeof f!="number"?Date.now()-S:f>=S?f-S:f,g.speedCache=g.speedCache||{},g.speedCache[p]=f,g.speedCache.begin=S,clearTimeout(g.speedTimmer),g.speedTimmer=setTimeout(function(){m||(g.speedCache.page=g.getPage(!0)),g._lg("speed",g.speedCache),g.speedCache=null},5e3),g):(o.warn("[retcode] invalid point: "+p),g)},performance:function(p){if(p&&typeof p=="object"&&!this.hasSendPerf){var f={},m={},g=this.getConfig("autoSendPerf");if(p.autoSend&&g)return m=o.ext(this.perfData||{},p),this.hasSendPerf=!0,this._lg("perf",m,this.getConfig("sample"));if(p.autoSend&&!g)return delete p.autoSend,this.perfData?(m=o.ext(this.perfData||{},p),this.hasSendPerf=!0,this._lg("perf",m,this.getConfig("sample"))):void(this.perfData=p);for(var S in p)(/^t([1-9]|1[0])$/.test(S)||S==="ctti"||S==="cfpt")&&(f[S]=p[S]);if(p.autoSend===!0||!g&&(g||this.perfData))return p.autoSend!==!0&&g===!1&&this.perfData?(f=o.ext(this.perfData||{},f),this.hasSendPerf=!0,this._lg("perf",f,this.getConfig("sample"))):void 0;this.perfData=o.ext(this.perfData||{},f)}},resource:function(p,f){if(!p||!o.isPlainObject(p))return o.warn("[arms] invalid param data: "+p),this;var m=Object.keys(p),g=["begin","dom","load","res","dl"],S=!1;for(var v in g)if(m.indexOf(g[v])<0){S=!0;break}if(S)return o.warn("[arms] lack param data: "+p),this;var E={begin:p.begin||Date.now(),dom:p.dom||"",load:p.load||"",res:o.isArray(p.res)?JSON.stringify(p.res):JSON.stringify([]),dl:p.dl||""};return this._lg("res",E,f)},event:function(p,f){if(typeof p=="object"&&p&&p.key){var m={},g=["key","success","time","c1","c2","c3"];for(var S in p)g.indexOf(S)>-1&&(m[S]=p[S]);m.success=p.success===!1?0:1,this._lg("event",m,f)}}}),u._super=l,u._root=l,l.Reporter=u,In.exports=u,In.exports}(),e=function(){if(tl)return Dn.exports;tl=1;var o=vt(),l=typeof window=="object"?window:{},d=l.__oFetch_||l.fetch;return d=typeof d=="function"?d:void 0,Dn.exports=function(h,u){var p=-1;typeof h=="object"&&(p=h.z,h=o.serialize(h));var f=u+h;if(d)return d(f,{method:"HEAD",mode:"no-cors"}).catch(o.noop);if(l.document&&l.document.createElement){var m="__request_hold_"+p,g=l[m]=new Image;g.onload=g.onerror=function(){l[m]=void 0},g.src=f,g=null}},Dn.exports}(),t=function(){if(rl)return Mn.exports;rl=1;var o=vt(),l=typeof window=="object"?window:{},d=l.__oXMLHttpRequest_||l.XMLHttpRequest;return d=typeof d=="function"?d:void 0,Mn.exports=function(h,u){try{var p=new d;p.open("POST",u,!0),p.setRequestHeader("Content-Type","text/plain"),p.send(JSON.stringify(h))}catch(f){o.warn(`[retcode] Failed to log, exception is :
331
+ `+f)}},Mn.exports}(),i=s.win,n=i.document,a=/^(error|api|speed|sum|avg|percent|custom|msg|setPage|setConfig|behavior|performance)$/,c=function(o){var l=this;return r.call(l,o),l._initialPage=o.page&&s.safetyCall(o.page,[],o.page+"")||null,l._isRobot=s.isRobot(),l._health={errcount:0,apisucc:0,apifail:0},l.beforeSend=function(d,h){d==="error"?l._health.errcount++:d==="api"&&l._health[h.success?"apisucc":"apifail"]++},o.enableInstanceAutoSend!==!1&&(l.initHandler(),l.initHook(),l.initFmpObserver(1e4),l._conf&&l._conf.behavior&&typeof l.initBehavior=="function"&&l.initBehavior(),l._conf&&l._conf.enableResource&&typeof l.initResource=="function"&&l.initResource()),Object.defineProperty&&i.addEventListener&&Object.defineProperty(l,"pipe",{set:l.sendPipe}),l};return c.prototype=s.createObject(r.prototype),s.ext(r._root.dftCon,{uid:null,setUsername:null,ignoreUrlPath:null,ignoreApiPath:null,urlHelper:[{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},/\/$/],resourceHelper:[],apiHelper:{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},ignoreUrlCase:!0,imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",cdnHostList:[],resourceTypes:["css","script","img","font"],resourceSlow:2e3,disableHook:!1,autoSendPv:!0,autoSendPerf:!0,enableSPA:!1,enableLinkTrace:!1,linkType:"arms",enableApiCors:!1,sendResource:!0,behavior:!0,enableConsole:!1,parseHash:function(o){return(o?s.cutUrlSearch(o.replace(/^#\/?/,"")):"")||"[index]"},parseResponse:function(o){if(!o||typeof o!="object")return{};var l=o.code,d=o.msg||o.message||o.subMsg||o.errorMsg||o.ret||o.errorResponse||"";return typeof d=="object"&&(l=l||d.code,d=d.msg||d.message||d.info||d.ret||JSON.stringify(d)),{msg:d,code:l,success:!0}}}),s.ext(c.prototype,{constructor:c,_super:r,onReady:function(o){var l=this;if(l.hasReady)return o();n.readyState==="complete"?(l.hasReady=!0,o()):s.on(i,"load",function(){l.hasReady=!0,o()},!0)},getPage:function(o){var l=this._conf,d=l.page,h=location,u=h.host+h.pathname;return d&&!o?s.safetyCall(d,[],d+""):this._initialPage||s.filterByRule(l.ignoreUrlCase?u.toLowerCase():u,h.href,l.ignoreUrlPath?l.ignoreUrlPath:l.urlHelper)},setPage:function(o,l){var d=this,h=d.prevPage;if(l!==!1){if(!o||o===h)return d;d.prevPage=o,clearTimeout(d.sendPVTimmer),d.handleUnload(1),d.resetPageview(),d.sendPVTimmer=setTimeout(function(){d.sendPV()},10)}else d.prevPage=o;return d._conf.page=o,d},setConfig:function(o,l){if(o&&typeof o=="object"){s.verifyConfig(o),o=this.setImgUrl(o);var d=this._conf;if(this._conf=s.ext({},d,o),!l){var h="disableHook";h in o&&d[h]!==o[h]&&(o[h]?this.removeHook():this.addHook()),(h="enableSPA")in o&&d[h]!==o[h]&&this.bindHashChange(o[h])}}},sendRequest:function(o){e(o,this.getConfig("imgUrl"))},postData:function(o,l){var d={};d[l]=o[l],delete o[l];var h="";typeof o=="object"&&(h=s.serialize(o)),t(d,this.getConfig("imgUrl")+h+"&post_res=")},sendPipe:function(o){var l=this;if(!o||!o.length)return l;try{if(s.T(o[0])==="Array")return s.each(o,function(h){return l.sendPipe(h)});if(s.T(o)!=="Array")return l;var d=o.shift();if(!a.test(d))return l;l[d].apply(l,o)}catch(h){return s.warn("[retcode] error in sendPipe",h),l}},sendHealth:function(){var o=s.ext({},this._health);o.healthy=o.errcount>0?0:1,o.begin=Date.now();var l=o.begin-this.sBegin;o.stay=l,this._lg("health",o,1),this._health={errcount:0,apisucc:0,apifail:0}},createInstance:function(o){o=s.ext({pid:this._conf.pid},o);var l=this.__proto__.constructor(o);return o.page&&l.sendPV(),l}}),Xp()(c,i),Zp()(c,i,n),Yp()(c,i,n),(hl||(hl=1,ll=function(o,l){var d=vt(),h=null,u=d.getCurDomain(),p=function(v,E,T,R,y,C,w,A,P,M,I,j,K){var B=d.J(y)||null,F=d.safetyCall(E,[B,R],null);if(!F)return!1;var X=F.code||C,$=!("success"in F)||F.success;v.api(T,$,w,X,F.msg,A,P,M,$?{}:I,u,j,K)},f="fetch",m="__oFetch_",g="__oXMLHttpRequest_",S="XMLHttpRequest";return d.ext(o.prototype,{removeHook:function(v,E){return h&&(E||this===h)?(l[m]&&(l[f]=l[m],delete l[m]),l[g]&&(l[S]=l[g],delete l[g]),h=null,this):this},addHook:function(v){return!v&&h||(h||(function(){if(typeof l[f]=="function"){var E=l[f];l[m]=E,l[f]=function(T,R){var y=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),C=h;if(!C||!C.api||R&&(R.method==="HEAD"||R.mode==="no-cors"))return E.apply(l,y);R||(R={});var w=Date.now(),A=C._conf,P=d.duration(),M=(T&&typeof T!="string"?T.url:T)||"",I=M;M=d.cutUrlSearch(M);var j=(A.ignore||{}).ignoreApis,K=A.parseTraceId;if(!d.checkAPI(M,!0)||d.ignoreByRule(M,j))return E.apply(l,y);M=d.filterByRule(M,I,A.ignoreApiPath?A.ignoreApiPath:A.apiHelper);var B=A.enableLinkTrace,F="",X="",$=C.getConfig("pid"),se=null,N=C.getConfig("sample"),V=C.getConfig("linkType"),x=1;if(N&&!C.sampling(N)&&(x=0),B){var U="";try{U=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(ye){U=""}var ce=d.checkSameOrigin(I,U);if(C.getConfig("enableApiCors")||ce)if(T&&typeof T!="string")try{if(y[0].headers&&typeof y[0].headers.get=="function"&&typeof y[0].headers.append=="function")switch(V){case"arms":var ue=y[0].headers.get("EagleEye-TraceID"),te=y[0].headers.get("EagleEye-SessionID"),Re=y[0].headers.get("EagleEye-pAppName");ue?F=ue:(F=C.getTraceId()["EagleEye-TraceID"],y[0].headers.append("EagleEye-TraceID",F)),te?X=te:(X=C.getPageviewId()["EagleEye-SessionID"],y[0].headers.append("EagleEye-SessionID",X)),Re||y[0].headers.append("EagleEye-pAppName",$);break;case"b3":var He=y[0].headers.get("X-B3-TraceId");if(He)F=He;else{var Ve=C.getB3TraceId(x);y[0].headers.append("X-B3-TraceId",Ve["X-B3-TraceId"]),y[0].headers.append("X-B3-ParentSpanId",Ve["X-B3-ParentSpanId"]),y[0].headers.append("X-B3-SpanId",Ve["X-B3-SpanId"]),y[0].headers.append("X-B3-Sampled",Ve["X-B3-Sampled"]),y[0].headers.append("X-Request-ID",d.guid()),F=Ve["X-B3-TraceId"]}X=C.pageview;break;default:var je=y[0].headers.get("uber-trace-id");je?F=je.split(":")[0]:(je=C.getUberTraceId(x),y[0].headers.append("uber-trace-id",je["uber-trace-id"]),F=je.traceId),X=C.pageview}}catch(ye){d.warn(`[retcode] fetch failed to set header, exception is :
332
+ `+ye)}else switch(R.headers=R.headers?R.headers:{},V){case"arms":R.headers["EagleEye-TraceID"]?F=R.headers["EagleEye-TraceID"]:(F=C.getTraceId()["EagleEye-TraceID"],R.headers["EagleEye-TraceID"]=F),R.headers["EagleEye-SessionID"]?X=R.headers["EagleEye-SessionID"]:(X=C.getPageviewId()["EagleEye-SessionID"],R.headers["EagleEye-SessionID"]=X),R.headers["EagleEye-pAppName"]||(R.headers["EagleEye-pAppName"]=$);break;case"b3":if(R.headers["X-B3-TraceId"])F=R.headers["X-B3-TraceId"];else{var _e=C.getB3TraceId(x);R.headers["X-B3-TraceId"]=_e["X-B3-TraceId"],R.headers["X-B3-ParentSpanId"]=_e["X-B3-ParentSpanId"],R.headers["X-B3-SpanId"]=_e["X-B3-SpanId"],R.headers["X-B3-Sampled"]=_e["X-B3-Sampled"],R.headers["X-Request-ID"]=d.guid(),F=_e["X-B3-TraceId"]}X=C.getPageviewId()["EagleEye-SessionID"];break;default:if(R.headers["uber-trace-id"])F=R.headers["uber-trace-id"].split(":")[0];else{var Ue=C.getUberTraceId(x);R.headers["uber-trace-id"]=Ue["uber-trace-id"],F=Ue.traceId}X=C.getPageviewId()["EagleEye-SessionID"]}}return E.apply(l,y).then(function(ye){if(!C||!C.api)return ye;try{if(!ye||typeof ye.clone!="function")return ye;var Ge=ye.clone(),Oe=Ge.headers;if(Oe&&typeof Oe.get=="function"){var mt=Oe.get("content-type");if(mt&&!/(text)|(json)/.test(mt))return ye;if(!F){var At=d.parseFetchHeaders(Oe);typeof At=="object"&&At["eagleeye-traceid"]&&(F=At["eagleeye-traceid"],se="response")}}var Se=P();return Ge.text().then(function(le){if(!F&&d.isFunction(K)){var ae=K(Ge,le);ae&&d.isString(ae)&&(F=ae)}var Ie=d.getFetchSnapshot(y,le,Oe);Ge.ok?p(C,A.parseResponse,M,I,le,Ge.status||200,Se,w,F,X,Ie,se,x):(C.api(M,!1,Se,Ge.status||404,Ge.statusText,w,F,X,Ie,u,se,x),A.enableResource&&h.fixResourceStatus&&h.fixResourceStatus({src:Ge.url,res_type:"api"}))}),ye}catch(le){return d.warn("[ARMS] fetch response error :",le),ye}}).catch(function(ye){if(!C||!C.api)throw ye;var Ge=P();throw C.api(M,!1,Ge,ye.name||"Error",ye.message,w,F,X,{},u),A.enableResource&&h.fixResourceStatus&&h.fixResourceStatus({src:I,res_type:"api"}),ye})},l[f].toString=d.createFakeToString(f)}}(),function(){if(typeof l[S]=="function"){var E,T=l[S];l[g]=T;var R=function(y){var C=new T(y),w=h;if(!w||!w.api||!C.addEventListener)return C;var A,P,M,I,j=C.send,K=C.open,B=C.setRequestHeader,F=w._conf,X=(F.ignore||{}).ignoreApis,$=F.parseTraceId,se=w.getConfig("enableLinkTrace"),N="",V="",x="",U=null,ce=w.getConfig("sample"),ue=w.getConfig("linkType"),te=1;return ce&&!w.sampling(ce)&&(te=0),C.open=function(Re,He){E=Re;var Ve=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);K.apply(C,Ve),I=He||"",M=d.cutUrlSearch(I);var je=!d.checkAPI(M,!0)||d.ignoreByRule(M,X);if(M=M?d.filterByRule(M,I,F.ignoreApiPath?F.ignoreApiPath:F.apiHelper):"",!je&&se){var _e="";try{_e=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(Oe){_e=""}var Ue=d.checkSameOrigin(I,_e);if((w.getConfig("enableApiCors")||Ue)&&B&&typeof B=="function")switch(ue){case"arms":N=w.getTraceId()["EagleEye-TraceID"],B.apply(C,["EagleEye-TraceID",N]),V=w.getPageviewId()["EagleEye-SessionID"],B.apply(C,["EagleEye-SessionID",V]),x=w.getConfig("pid"),B.apply(C,["EagleEye-pAppName",x]);break;case"b3":var ye=w.getB3TraceId(te);B.apply(C,["X-B3-TraceId",ye["X-B3-TraceId"]]),B.apply(C,["X-B3-ParentSpanId",ye["X-B3-ParentSpanId"]]),B.apply(C,["X-B3-SpanId",ye["X-B3-SpanId"]]),B.apply(C,["X-B3-Sampled",ye["X-B3-Sampled"]]),B.apply(C,["X-Request-ID",d.guid()]),N=ye["X-B3-TraceId"],V=w.getPageviewId()["EagleEye-SessionID"];break;default:var Ge=w.getUberTraceId(te);B.apply(C,["uber-trace-id",Ge["uber-trace-id"]]),N=Ge.traceId,V=w.getPageviewId()["EagleEye-SessionID"]}}},C.send=function(){A=Date.now(),P=d.duration();var Re=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);j.apply(C,Re)},d.on(C,"readystatechange",function(){if(M&&C.readyState===4){var Re=P(),He=d.getXhrSnapshot(I,E,C);if(!N){var Ve=d.parseXhrHeaders(typeof C.getAllResponseHeaders=="function"&&C.getAllResponseHeaders()||"");typeof Ve=="object"&&Ve["eagleeye-traceid"]&&(N=Ve["eagleeye-traceid"],U="response")}if(!N&&d.isFunction($)){var je=$(C);je&&d.isString(je)&&(N=je)}if(C.status>=200&&C.status<=299){var _e=C.status||200;if(typeof C.getResponseHeader=="function"){var Ue=C.getResponseHeader("Content-Type");if(Ue&&!/(text)|(json)/.test(Ue))return}C.responseType&&C.responseType!=="text"?w.api(M,!0,Re,_e,"",A,N,V,{},u,U,te):p(w,F.parseResponse,M,I,C.responseText,_e,Re,A,N,V,He,U,te)}else w.api(M,!1,Re,C.status||"FAILED",C.statusText,A,N,V,He,u,U,te),F.enableResource&&h.fixResourceStatus&&h.fixResourceStatus({src:C.responseURL||I,res_type:"api"})}}),C};R.prototype=T.prototype,d.each(Object.keys(T),function(y){R[y]=T[y]}),l[S]=R,l[S].toString=d.createFakeToString(S)}}()),h=this),this},initHook:function(){return this.hasInitHook||(this.getConfig("disableHook")||this.addHook(),this.hasInitHook=!0),this}}),o}),ll)(c,i),(pl||(pl=1,ul=function(o,l){var d=vt(),h=l.history||{},u=l.document,p=function(m,g){var S;l.CustomEvent?S=new CustomEvent(m,{detail:g}):((S=u.createEvent("HTMLEvents")).initEvent(m,!1,!0),S.detail=g),l.dispatchEvent(S)},f=function(m){var g=h[m];typeof g=="function"&&(h[m]=function(S,v,E){var T=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),R=location.href,y=g.apply(h,T);if(!E||typeof E!="string"||E===R)return y;try{var C=R.split("#"),w=E.split("#"),A=d.cutUrlSearch(C[0]),P=d.cutUrlSearch(w[0]),M=C[1]&&C[1].replace(/^\/?(.*)/,"$1"),I=w[1]&&w[1].replace(/^\/?(.*)/,"$1");M!==I?p("historystatechange",I):A!==P&&p("historystatechange",P)}catch(j){d.warn("[retcode] error in "+m+": "+j)}return y},h[m].toString=d.createFakeToString(m))};d.ext(o.prototype,{hackHistoryState:function(){return this.hasHackedHistoryState||(f("pushState"),f("replaceState"),this.hasHackedHistoryState=!0),this}})}),ul)(c,i),function(){if(ml)return xn;ml=1;var o=vt(),l=Vn().TIMING_KEYS;return xn=function(d,h){function u(m,g,S){if(m instanceof h.PerformanceResourceTiming&&m.initiatorType){var v=o.getResType(m.initiatorType,m.name),E=g.resourceTypes||[],T=(g.ignore||{}).ignoreResources;if(v&&E.includes(v)&&!o.ignoreByRule(m.name,T)&&!o.ignoreByRule(o.decode(m.name),T)){var R=m[l[0]],y=m[l[1]],C=m[l[2]],w=m[l[3]],A=m[l[4]],P=m[l[5]],M=m[l[6]],I=m[l[7]],j=m[l[8]],K=m[l[18]],B=m[l[19]];if(!S.has(m)&&(!o.areInOrder(R,y,C,w,A,P,M,I,j)||R>I))return;if(K<R&&(K=R),B<R&&(B=y),o.areInOrder(R,K,B,y))return{domain:o.getURL(m.name).domain,res_type:v,src_type:o.getSrcType(m.name,g.cdnHostList),success:1,size:Math.round(m.decodedBodySize),duration:Math.round(m.duration),timeStamp:m.responseEnd,timing:m}}}}var p="_resource-"+Date.now(),f="_resource_error-"+Date.now();o.ext(d.prototype,{initResource:function(){var m=this,g=h.performance,S=h.PerformanceObserver;if(m[f]||(m[f]=new WeakMap),!g||!S||typeof g!="object"||typeof g.getEntriesByType!="function")return null;var v=g.getEntriesByType("resource")||[];return setTimeout(function(){m.setResource(v)},10),new S(function(E){setTimeout(function(){m.setResource(E.getEntries())},10)}).observe({entryTypes:["resource"]}),this.onReady(function(){setTimeout(m.resourceComboReport.bind(m),5e3)}),m},setResource:function(m){var g=this._conf,S=this[f];if(o.isArray(m)&&m.length){this[p]||(this[p]={});for(var v=this[p],E=0,T=m.length;E<T;E+=1){var R=m[E];if(o.checkAPI(R.name,!1)){var y=u(R,g,S);if(y){var C=y.res_type+"-"+y.domain;C in v||(v[C]=[]),v[C].push(y)}}}return this}},fixResourceStatus:function(m){var g=h.performance;if(!g||typeof g.getEntriesByName!="function")return null;var S=this[f];if(!m.src||!o.checkAPI(m.src,!1))return this;var v=m.timeStamp||g.now(),E=g.getEntriesByName(m.src,"resource");return o.each(E,function(T){S.has(T)||v-T.responseEnd<100&&S.set(T,{success:0})}),this},resourceComboReport:function(){var m=this[p]||{},g=this._conf.resourceSlow||2e3,S=this[f];this[p]={};var v=Object.keys(m);if(v.length!==0){var E=[];o.each(v,function(C){var w=m[C],A={domain:"",res_type:"",src_type:"",size:0,duration:0,count:0,err_count:0,err_duration:0,slow_count:0,slow_duration:0,timings:[]};o.each(w,function(P){var M=P.timing||{},I=S.get(P.timing),j=I?I.success:1,K=P.duration>g?1:0;A.domain=P.domain,A.res_type=P.res_type,A.src_type=P.src_type,A.count+=1,A.duration+=P.duration,A.size+=P.size,j||(A.err_count+=1,A.err_duration+=P.duration),K&&(A.slow_count+=1,A.slow_duration+=P.duration);try{var B=JSON.parse(JSON.stringify(M));B.success=j,B.resourceSlow=g,B.isSlow=K,A.timings.push(B)}catch(F){}}),A.count&&(A.size=Math.round(A.size/A.count),A.duration=Math.round(A.duration/A.count)),A.slow_count&&(A.slow_duration=Math.round(A.slow_duration/A.slow_count)),A.err_count&&(A.err_duration=Math.round(A.err_duration/A.err_count)),A.timings.length>20&&(A.timings.sort(function(P,M){return M.duration-P.duration}),A.timings.length=20),A.timings=encodeURIComponent(JSON.stringify(A.timings)),E.push(A)});var T={_combo:1,resource:JSON.stringify(E)},R=h.navigator.connection;T.ct=R?R.effectiveType||R.type:"";var y=R&&(R.downlink||R.downlinkMax||R.bandwidth)||null;(y=y>999?999:y)&&(T.bandwidth=y),this._lg("resource",T,this.getConfig("sample"))}}})},xn}()(c,i),c._super=r,c._root=r._root,r.Browser=c,wn.exports=c,wn.exports}var qp={getArmsLogger:function(){return function(){if(gl)return _n.exports;function s(n,a){var c=r[t]=new e(n);c.sendPipe(a);var o=c._conf;return o.autoSendPv!==!1&&c.sendPV(),o&&o.useFmp||c.sendPerformance(),o&&o.sendResource&&c.sendResources(),r[i]=!0,c}gl=1;var r=window,e=r.BrowserLogger=Qp(),t=vt().key,i="__hasInitBlSdk";return e.singleton=function(n,a){return r[i]?r[t]:s(n,a)},e.createExtraInstance=function(n){n&&typeof n=="object"&&n.enableInstanceAutoSend!==!0&&(n.enableInstanceAutoSend=!1);var a=new e(n),c=a._conf;return c.enableInstanceAutoSend&&(c.autoSendPv!==!1&&a.sendPV(),c&&c.useFmp||a.sendPerformance(),c&&c.sendResource&&a.sendResources()),a},typeof window=="object"&&window.navigator&&r[t]&&(e.bl=function(){if(r[i])return r[t];var n={},a=[];return t in r&&(n=r[t].config||{},a=r[t].pipe||[]),s(n,a)}()),_n.exports=e,_n.exports}()}};const bl="https://arms-retcode.aliyuncs.com/r.png?",vl="https://arms-retcode-sg.aliyuncs.com/r.png?",Rl="https://retcode-us-west-1.arms.aliyuncs.com/r.png?",El="e1iftji1w7@7ec1cef2cc88733",yl="e1iftji1w7@10a06d1ec260adc",Tl="e1iftji1w7@10a06d1ec260adc",Un={cn:{reportUrl:bl,pid:El},"cn-hangzhou":{reportUrl:bl,pid:El},sg:{reportUrl:vl,pid:yl},"ap-southeast-1":{reportUrl:vl,pid:yl},usw:{reportUrl:Rl,pid:Tl},"us-west-1":{reportUrl:Rl,pid:Tl}},em=s=>!!Object.isExtensible(s)&&(r=>Object.prototype.toString.call(r).slice(8,-1))(s)==="Object";function Cl(s,r){if(typeof s!="string")return!1;const e=s.indexOf(r);if(e<0)return!1;const t=s.indexOf(`
333
+ `);return t<0||e<t}function hr(s,r,e){return typeof s=="function"?function(t,i,n){const a={MediaboxWrapperFunctionApply(c,o,l){let d;try{d=Reflect.apply(c,o,l)}catch(h){throw n(h),h}return hr(d,i,n)},MediaboxWrapperFunctionGet(c,o){const l=Object.getOwnPropertyDescriptor(c,o);return!l||l.writable||l.configurable?hr(c[o],i,n):c[o]},MediaboxWrapperClassConstructor(c,o){let l;try{l=new c(...o)}catch(d){throw n(d),d}return hr(l,i,n)}};return new Proxy(t,{apply:a.MediaboxWrapperFunctionApply,get:a.MediaboxWrapperFunctionGet,construct:a.MediaboxWrapperClassConstructor})}(s,r+1,e):s instanceof Promise?s.then(t=>hr(t,r+1,e)).catch(t=>(e(t),Promise.reject(t))):Array.isArray(s)?(s.forEach((t,i)=>{s[i]=hr(t,r+1,e)}),s):(t=>t!==null&&typeof t=="object")(s)&&em(s)?function(t,i,n){var l;if(Reflect.get(t,"__v_skip")===!0)return t;const a=[],c=typeof Object.getOwnPropertyDescriptors=="function"?Object.getOwnPropertyDescriptors((l=Object.getPrototypeOf(t))!=null?l:{}):{};for(const d of Object.keys(c))c[d].get&&a.push(d);const o={MediaboxWrapperObjectGetter(d,h){if(typeof h=="string"&&a.indexOf(h)>-1){let u;try{u=d[h]}catch(p){throw n(p),p}return hr(u,i,n)}return i>10?d[h]:hr(d[h],i,n)},MediaboxWrapperObjectSetter:(d,h,u)=>(d[h]=hr(u,i,n),!0)};return Object.defineProperty(t,"__v_skip",{configurable:!0,enumerable:!1,writable:!1,value:!0}),new Proxy(t,{get:o.MediaboxWrapperObjectGetter,set:o.MediaboxWrapperObjectSetter})}(s,r+1,e):s}function _l(s){return typeof s=="string"&&(s.indexOf("g.alicdn.com/apsara-media-")>-1||s.indexOf("g.alicdn.com/thor-server")>-1||s.indexOf("MediaboxWrapper")>-1)}class wl extends Error{constructor(r){super(r),this.name="MQTError"}}let tm=1;class Bn{constructor(r){var e,t;Vr(this,"armsLogger"),Vr(this,"isReady",!1),Vr(this,"isDestroyed",!1),Vr(this,"options"),Vr(this,"queue",[]),Vr(this,"marker"),Vr(this,"helper",{MediaboxWrapperQueue:i=>new wl(i),MediaboxWrapperInitiative:i=>new wl(i)}),this.options=Q(D({},r),{region:r.deferRegionSet?void 0:(e=r.region)!=null?e:"cn",env:(t=r.env)!=null?t:"prod"}),this.marker=`-${tm++}-`,this.initArmsLogger()}static get version(){return"0.23.0"}initArmsLogger(r){const{region:e,env:t,disabled:i}=this.options;if(i||this.armsLogger)return;if(r&&!e)throw new Error("region is required");if(!e)return;if(!Un[e])throw new Error(`region ${e} is not supported`);const n=qp.getArmsLogger();this.armsLogger=n.createExtraInstance({enableInstanceAutoSend:!0,pid:Un[e].pid,tag:this.options.businessName,release:`${this.options.businessName}_${this.options.version}`,imgUrl:Un[e].reportUrl,behavior:!0,sample:1,disableHook:!0,environment:t,beforeReport:a=>{var c;if(this.isDestroyed||Cl(a.stack,this.marker)||a.t!=="pv"&&a.t!=="error")return!1;if(a.c1=(c=this.options.cid)!=null?c:window.location.host,a.c2=Bn.version,this.options.customData&&(a.c3=new URLSearchParams(this.options.customData).toString()),a.t==="error"){if(function(o){return typeof o=="string"&&(o.indexOf("g.alicdn.com/apsara-media-")>-1||o.indexOf("g.alicdn.com/thor-server")>-1)}(a.file)||_l(a.stack)){let o=a;return this.options.beforeSend&&(o=this.options.beforeSend(a)),this.isReady?o:(o&&this.queue.push(o),!1)}return!1}return a}})}wrap(r){return this.options.disabled||typeof Proxy>"u"?r:hr(r,0,e=>{var t;e instanceof Error&&typeof e.stack=="string"&&_l(e.stack)&&((t=this.armsLogger)==null||t.error(e),e.stack=function(i,n){if(typeof i!="string")return n;if(Cl(i,n))return i;const a=i.indexOf(`
334
+ `);return a<0?`${i}${n}`:`${i.slice(0,a)}${n}${i.slice(a)}`}(e.stack,this.marker))})}updateOptions(r){this.options=D(D({},this.options),r)}setReady(){this.initArmsLogger(!0),this.isReady=!0,this.queue.length&&this.queue.forEach(r=>{var e;(e=this.armsLogger)==null||e.error(this.helper.MediaboxWrapperQueue(r.msg),{filename:r.file,lineno:r.line,colno:r.col})})}report(r,e){var t;(t=this.armsLogger)==null||t.error(this.helper.MediaboxWrapperInitiative(r),e)}destroy(){this.isDestroyed=!0}}function ti(){}const Wr=class Wr{static getInstance(){var r;return Wr.instance||(Wr.instance=new AudioContext),(r=Wr.instance.resume())==null||r.then(ti,ti).catch(ti),Wr.instance}};b(Wr,"instance");let Ur=Wr;const Ss=()=>{var r;const s=Ur.getInstance();s.state!=="running"&&s.state!=="closed"&&((r=s.resume())==null||r.then(ti,ti).catch(ti)),window.removeEventListener("mousedown",Ss),window.removeEventListener("touchstart",Ss)};window.addEventListener("mousedown",Ss),window.addEventListener("touchstart",Ss);class rm extends de{constructor(){super();b(this,"audioContext");b(this,"stream");b(this,"sourceNode");b(this,"analyser");this.audioContext=Ur.getInstance(),this.stream=new MediaStream}getLevel(){return this.analyser?this.analyser.getLevel():0}start(e,t=1e3){this.sourceNode&&this.stop(),this.stream.addTrack(e),this.sourceNode=this.audioContext.createMediaStreamSource(this.stream);const i=this.audioContext.createMediaStreamDestination();this.analyser=function(n,a,c,o,l){let d,h=o,u=0;const p=n.createAnalyser();p.fftSize=256;const f=new Uint8Array(p.frequencyBinCount);a.connect(p),p.connect(c);const m=()=>{d&&window.clearInterval(d)},g=()=>{n.state==="suspended"&&n.resume(),d=window.setInterval(()=>{p.getByteFrequencyData(f);let S=Math.round(f.reduce((v,E)=>v+E)/f.length);S=Math.min(100,S),u=S,l&&l(S)},h)};return g(),{updateInterval:S=>{m(),h=S,g()},getLevel:()=>u,dispose:()=>{m(),a.disconnect(),p.disconnect()}}}(this.audioContext,this.sourceNode,i,t,n=>{this.emit("audioLevel",n)})}stop(){this.analyser&&this.analyser.dispose(),this.analyser=void 0,this.sourceNode=void 0,this.stream.getAudioTracks().forEach(e=>{this.stream.removeTrack(e)})}dispose(){this.stop()}}class Al extends de{constructor(e,t,i,n){super();b(this,"uid");b(this,"name");b(this,"rtsManager");b(this,"callId","");b(this,"audioLevelMonitor");b(this,"audioVolumeIndicationInterval",0);this.uid=e,this.name=t,this.rtsManager=i,this.audioVolumeIndicationInterval=n,this.audioLevelMonitor=new rm}get userId(){return this.uid}get displayname(){return this.name}createCallId(e=!1){this.callId&&!e||(this.callId=ze.createCallid())}setUserInfo(e,t){this.uid=e,this.name=t}refreshUserInfo(e){this.uid=e}getAudioLevel(){return this.audioLevelMonitor.getLevel()}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval=e}clear(){this.audioLevelMonitor.dispose()}}class Il{static getCurrentStatus(r){let e=0;r.micOpen&&(e+=1),r.micInterrupted&&(e+=2),r.cameraOpen&&(e+=4),r.screenShare&&(e+=128),r.audioDisable&&(e+=8),r.videoDisable&&(e+=16),r.screenDisable&&(e+=256);let t=e.toString(16);for(;t.length<16;)t="0"+t;return t}static parseStatus(r){let e=parseInt(r,16);return{micOpen:!!(1&e),micInterrupted:!!(2&e),cameraOpen:!!(4&e),screenShare:!!(128&e),audioDisable:!!(8&e),videoDisable:!!(16&e),screenDisable:!!(256&e),backgroundMode:!!(32&e),accompanyPlaying:!!(64&e)}}}const k=(s,r)=>(e,t,i)=>{const n=i.value;return i.value=function(...a){var h;const c=`[${((h=e.constructor)==null?void 0:h.logName)||""}]`,o=Date.now();let l=[];if(s)try{l=s(a)}catch(u){}O.interface(c,t,...l);const d=n.apply(this,a);return Promise.resolve(d).then(u=>u).catch(u=>u).then(u=>{var g;let p="";const f=u instanceof Error,m=f&&((g=e.constructor)==null?void 0:g.logError);if(r||f){if(m)p=u;else if(f)p=u.message||"";else{if(!r)return;if(u===void 0)p="";else try{p=r(u)}catch(S){}}O.interfaceResult(c,t,!(f&&m),Date.now()-o+"ms",p)}}),d},i},J=s=>s,Pl="customVideoProfile",Dl="customScreenProfile",Fn={width:1280,height:720,frameRate:30,maxBitrate:2e3},kl={width:1920,height:1080,frameRate:30,maxBitrate:2600};var _i=(s=>(s[s.ERROR_DEVICE_UNKNOWNERROR=1e4]="ERROR_DEVICE_UNKNOWNERROR",s[s.ERROR_DEVICE_AUDIODEVICE_NOTFOUND=10001]="ERROR_DEVICE_AUDIODEVICE_NOTFOUND",s[s.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED=10002]="ERROR_DEVICE_AUDIODEVICE_NOTALLOWED",s[s.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE=10003]="ERROR_DEVICE_AUDIODEVICE_NOTREADABLE",s[s.ERROR_DEVICE_VIDEODEVICE_NOTFOUND=10004]="ERROR_DEVICE_VIDEODEVICE_NOTFOUND",s[s.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED=10005]="ERROR_DEVICE_VIDEODEVICE_NOTALLOWED",s[s.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE=10006]="ERROR_DEVICE_VIDEODEVICE_NOTREADABLE",s[s.ERROR_SCREENSHARE_NOTSUPPORT=10010]="ERROR_SCREENSHARE_NOTSUPPORT",s[s.ERROR_SCREENSHARE_NOTALLOWED=10011]="ERROR_SCREENSHARE_NOTALLOWED",s[s.ERROR_SCREENSHARE_ENDED=10012]="ERROR_SCREENSHARE_ENDED",s[s.ERROR_SCREENSHARE_NOPERMISSION=10013]="ERROR_SCREENSHARE_NOPERMISSION",s[s.ERROR_SCREENSHARE_SAFARI_INVALIDACCESS=10014]="ERROR_SCREENSHARE_SAFARI_INVALIDACCESS",s[s.ERROR_SCREENSHARE_UNKNOWNERRO=10019]="ERROR_SCREENSHARE_UNKNOWNERRO",s[s.ERROR_DEVICE_NOTALLOWED=10021]="ERROR_DEVICE_NOTALLOWED",s[s.ERROR_DEVICE_NOTSUPPORT=2e4]="ERROR_DEVICE_NOTSUPPORT",s))(_i||{});const im={1e4:qe.AliEngineLocalDeviceExceptionTypeUnknown,2e4:qe.AliEngineLocalDeviceExceptionTypeUnknown,10001:qe.AliEngineLocalDeviceExceptionTypeMicNotAvailable,10002:qe.AliEngineLocalDeviceExceptionTypeMicAuthFail,10003:qe.AliEngineLocalDeviceExceptionTypeMicOpenFail,10005:qe.AliEngineLocalDeviceExceptionTypeCameraAuthFail,10004:qe.AliEngineLocalDeviceExceptionTypeVideoDeviceException,10006:qe.AliEngineLocalDeviceExceptionTypeCameraOpenFail,10010:qe.AliEngineLocalDeviceExceptionTypeDisplayException,10011:qe.AliEngineLocalDeviceExceptionTypeDisplayException,10012:qe.AliEngineLocalDeviceExceptionTypeDisplayException,10013:qe.AliEngineLocalDeviceExceptionTypeDisplayException,10014:qe.AliEngineLocalDeviceExceptionTypeDisplayException,10019:qe.AliEngineLocalDeviceExceptionTypeDisplayException};var Ot=(s=>(s.CREATE_ENGINE="create_engine",s.JOIN="join",s.WANT_INSERT_PUB_TASK="wantInsertPubTask",s.INSERT_PUB_TASK="InsertPubTask",s.HANDLE_PUB_TASK="HandlePubTask",s.RECV_NOTIFY_PUBLISH="RecvNotifyPublish",s.INSERT_SUB_TASK="InsertSubTask",s.HANDLE_SUB_TASK="HandleSubTask",s.FIRST_REMOTE="first_remote",s))(Ot||{}),Ut=(s=>(s.START="start",s.SEND_SIG="send_sig",s.RECV_RST="recv_rst",s.END="end",s.RECEIVED="received",s.DECODED="decoded",s.PLAYED="played",s))(Ut||{});const Ml=(s,r,e=!1)=>{const t=()=>(s.muted=!0,Promise.race([lr(500),s._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{let i;return e&&s.srcObject===r?i=Promise.resolve():(s.load(),s.srcObject=r,i=s.play(),s._playPromise=i),i}));return new Promise(i=>{if(Pe.BrowserUtil.isMicroMessenger){const n=window.top!==window.self,a=window.WeixinJSBridge||window.top.WeixinJSBridge;a?a.invoke("getNetworkType",{},()=>{i(t())}):(n?window.top.document:document).addEventListener("WeixinJSBridgeReady",()=>{a.invoke("getNetworkType",{},()=>{i(t())})}),setTimeout(()=>{i(t())},1e3)}else setTimeout(()=>{i(t())},0)})},sr=s=>{Promise.race([lr(100),s._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{s.srcObject=null,s._playPromise=void 0})};var sm=Object.defineProperty,nm=Object.getOwnPropertyDescriptor,Be=(s,r,e,t)=>{for(var i,n=t>1?void 0:t?nm(r,e):r,a=s.length-1;a>=0;a--)(i=s[a])&&(n=(t?i(r,e,n):i(n))||n);return t&&n&&sm(r,e,n),n};class wi extends de{constructor(){super();b(this,"_state");b(this,"time");this._state=ne.AliRtcStatePublishIdle,this.time=Date.now()}get state(){return this._state}setState(e){const t=this._state,i=this.time;this._state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-i)/1e3))}}const Le=(Yt=class extends Al{constructor(e){const{rtsManager:t,localStreamManager:i,slsReporter:n,signalingManager:a,audioVolumeIndicationInterval:c,parameter:o}=e;super("","",t,c);b(this,"sessionId","");b(this,"traceId","");b(this,"_url","");b(this,"joinTime",0);b(this,"publishPromise",Promise.resolve({traceId:"",l1ip:void 0}));b(this,"previewElements",[]);b(this,"screenPreviewElements",[]);b(this,"streamManager");b(this,"dc");b(this,"streamTracks");b(this,"publishId",Vt());b(this,"signalingManager");b(this,"shouldPublish",!1);b(this,"monitorTimerId");b(this,"monitorDataCache",{});b(this,"candidateDataCache",[]);b(this,"pcMediaStatsMap",{});b(this,"slsReporter");b(this,"audioPubState");b(this,"videoPubState");b(this,"videoSmallPubState");b(this,"screenPubState");b(this,"dataPubState");b(this,"parameter",{});b(this,"onTrackEnd",e=>{this.emit(e)});this.streamManager=i,this.signalingManager=a,this.slsReporter=n,this.parameter=o,this.streamManager.on("trackended",l=>{this.onTrackEnd(l)}),this.streamManager.on("publishupdate",()=>{this.publishUpdate()}),this.audioPubState=new wi,this.audioPubState.on("change",(l,d,h)=>{this.emit("audioPublishStateChanged",l,d,h)}),this.videoPubState=new wi,this.videoPubState.on("change",(l,d,h)=>{this.emit("videoPublishStateChanged",l,d,h)}),this.videoSmallPubState=new wi,this.videoSmallPubState.on("change",(l,d,h)=>{this.emit("dualStreamPublishStateChanged",l,d,h)}),this.screenPubState=new wi,this.screenPubState.on("change",(l,d,h)=>{this.emit("screenPublishStateChanged",l,d,h)}),this.dataPubState=new wi,this.dataPubState.on("change",(l,d,h)=>{this.emit("dataPublishStateChanged",l,d,h)}),this.startStreamMonitor(),this.createCallId()}get url(){return this._url}set url(e){this._url=e,this.rtsManager.updateAuth(e)}get joined(){return!!this.uid}get isPublishing(){return this.rtsManager.publishingTracks.length>0}get publishStreams(){return this.streamManager.publishStreams}get cameraTrack(){return this.streamManager.cameraStreamInfo.originVideoTrack}get screenTrack(){return this.streamManager.screenStreamInfo.originVideoTrack}get audioTrack(){return this.streamManager.cameraStreamInfo.originAudioTrack}get hasCamera(){return!!this.streamManager.cameraStreamInfo.originVideoTrack}get hasMicrophone(){return!!this.streamManager.cameraStreamInfo.originAudioTrack}get hasScreenShare(){return!!this.streamManager.screenStreamInfo.originVideoTrack}get hasCameraTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:n})=>i==="video"&&t&&n===L.VideoLarge))}get hasCameraDualTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:n})=>i==="video"&&t&&n===L.VideoSmall))}get hasScreenTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:n})=>i==="video"&&t&&n===L.Screen))}get hasAudioTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:n})=>i==="audio"&&t&&n===L.Audio))}get cameraDirection(){var e,t;return(t=(e=this.streamManager.cameraStreamInfo)==null?void 0:e.cameraVideoConstraints)==null?void 0:t.facingMode}get audioCaptureDisabled(){return this.streamManager.audioCaptureDisabled}get cameraCaptureDisabled(){return this.streamManager.cameraCaptureDisabled}get publishLocalVideoStreamEnabled(){return this.streamManager.publishLocalVideoStreamEnabled}get publishLocalAudioStreamEnabled(){return this.streamManager.publishLocalAudioStreamEnabled}get publishLocalScreenStreamEnabled(){return this.streamManager.publishLocalScreenStreamEnabled}setPublishLocalAudioStreamEnabled(e){this.streamManager.publishLocalAudioStreamEnabled=e}setPublishLocalVideoStreamEnabled(e){this.streamManager.publishLocalVideoStreamEnabled=e}setPublishLocalScreenStreamEnabled(e){this.streamManager.publishLocalScreenStreamEnabled=e}initInfo(e,t){this.joinTime=Date.now(),this.rtsManager.localJoinTime=this.joinTime,this.setUserInfo(e.userId,e.userId),this.url=t,this.sessionId=e.sessionId||ze.createCallid("web"),this.updatePubId()}setVideoProfile(e){return _(this,null,function*(){yield this.streamManager.setVideoProfile(Pl,e)})}setVideoContentHint(e){this.streamManager.setVideoContentHint(e)}setScreenContentHint(e){this.streamManager.setScreenContentHint(e)}setAudioProfile(e){return _(this,null,function*(){yield this.streamManager.setAudioProfile(e)})}setScreenProfile(e){return _(this,null,function*(){yield this.streamManager.setScreenProfile(Dl,e)})}setCameraDirection(e){if(e===yi.CAMERA_FRONT)this.streamManager.setCameraVideoConstraints({facingMode:"user"});else{if(e!==yi.CAMERA_REAR)throw new W(z.ERR_CAMERA_OPEN_FAIL,`camera direction set to ${e} failed`);this.streamManager.setCameraVideoConstraints({facingMode:"environment"})}}setCameraDeviceId(e){this.streamManager.setCameraVideoConstraints({deviceId:e})}muteLocalCamera(e){this.streamManager.setCameraMuted(e),this.slsReporter.reportMute(this.callId,!e,"video")}muteLocalMic(e){this.streamManager.setAudioMuted(e),this.slsReporter.reportMute(this.callId,!e,"audio")}muteLocalScreen(e){this.streamManager.setScreenMuted(e),this.slsReporter.reportMute(this.callId,!e,"screen")}setMicrophoneDeviceId(e){this.streamManager.setMicAudioConstraints({deviceId:e})}setMicrophoneConstraints(e){this.streamManager.setMicAudioConstraints(e)}updatePubId(){this.publishId=Vt()}clearPublishState(){this.streamTracks=void 0}leave(){return _(this,null,function*(){this.shouldPublish=!1,this.isPublishing&&(yield this.unPublish()),this.joinTime=0,this.dc=void 0})}clear(){return _(this,null,function*(){ca(Yt.prototype,this,"clear").call(this),this.stopPreview(),this.resetPreviewElements(),this.resetSecondayPreviewElements(),this.clearStream(),yield this.leave(),this.streamManager.cameraCaptureDisabled=!1})}resetElement(e){this.previewElements.includes(e)&&(sr(e),this.previewElements.splice(this.previewElements.indexOf(e),1)),this.screenPreviewElements.includes(e)&&(sr(e),this.screenPreviewElements.splice(this.screenPreviewElements.indexOf(e),1))}setPreviewElement(e){const{videoElement:t,screen:i}=e;i?this.screenPreviewElements.includes(t)||(this.screenPreviewElements.push(t),this.preview(e)):this.previewElements.includes(t)||(this.previewElements.push(t),this.preview(e))}startDefaultCameraAndMic(e){return _(this,null,function*(){const{hasCamera:t,cameraCaptureDisabled:i,publishLocalVideoStreamEnabled:n}=this,{hasMicrophone:a,audioCaptureDisabled:c,publishLocalAudioStreamEnabled:o}=this,l=!t&&!e&&!i&&n,d=!a&&!c&&o;try{l&&d?yield this.startCameraAndMic():l?yield this.startCameraCapture():d&&(yield this.startAudioCapture())}catch(h){const u=h.errorCode;let p=z.ERR_CAMERA_OPEN_FAIL;throw l?((u===_i.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED||_i.ERROR_DEVICE_NOTALLOWED)&&(p=z.ERR_CAMERA_AUTH_FAIL),p=z.ERR_CAMERA_OPEN_FAIL):((u===_i.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED||_i.ERROR_DEVICE_NOTALLOWED)&&(p=z.ERR_MIC_AUTH_FAIL),p=z.ERR_MIC_OPEN_FAIL),new W(p,`auto open fail: ${h.message}`)}})}setViewConfig(e,t){if(e){if(![be.AliRtcVideoTrackCamera,be.AliRtcVideoTrackScreen].includes(t))throw new W(z.ERR_INVALID_ARGUMENTS,"set view config invalid track",{track:t});e.forEach(i=>{this.setPreviewElement({videoElement:i,screen:t===be.AliRtcVideoTrackScreen})})}else t===be.AliRtcVideoTrackCamera?this.stopPreview({primary:!0,screen:!1}):this.stopPreview({primary:!1,screen:!0})}startCameraCapture(){return _(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,yield this.createLocalStream({video:!0})})}stopCameraCapture(){return _(this,null,function*(){this.streamManager.cameraCaptureDisabled=!0,yield this.stopLocalStream({video:!0})})}startAudioCapture(){return _(this,null,function*(){return this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({audio:!0})})}stopAudioCapture(){return _(this,null,function*(){this.streamManager.audioCaptureDisabled=!0,yield this.stopLocalStream({audio:!0})})}startCameraAndMic(){return _(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({video:!0,audio:!0})})}preview(e){return _(this,null,function*(){const{videoElement:t,screen:i}=e!=null?e:{};try{let n=i?this.streamManager.screenStreamInfo.previewStream:this.streamManager.cameraStreamInfo.previewStream;if(!t)throw new W(z.ERR_INVALID_ARGUMENTS,"no video element found",{videoElement:t});return n?(Ml(t,n.mediaStream),this.setPreviewElement(e),n.mediaStream):void O.info(`[${Yt.logName}]`,"preview no stream founded")}catch(n){const a=z.ERR_INNER;throw W.fromError(n,a,"preview failed")}})}previewAll(e){return _(this,null,function*(){const{primary:t=!0,screen:i=!0}=e!=null?e:{};if(t&&this.previewElements.length)for(let n=0;n<this.previewElements.length;n++){const a=this.previewElements[n];yield this.preview({videoElement:a})}if(i&&this.screenPreviewElements.length)for(let n=0;n<this.screenPreviewElements.length;n++){const a=this.screenPreviewElements[n];yield this.preview({videoElement:a,screen:!0})}})}stopPreview(e){const{videoElement:t,primary:i=!0,screen:n=!0}=e||{};if(t){const a=this.previewElements.findIndex(c=>c===t);if(a>=0)this.previewElements.splice(a,1),sr(t);else{const c=this.screenPreviewElements.findIndex(o=>o===t);c>=0&&(this.screenPreviewElements.splice(c,1),sr(t))}}else i&&(this.previewElements.forEach(a=>{sr(a)}),this.previewElements=[]),n&&(this.screenPreviewElements.forEach(a=>{sr(a)}),this.screenPreviewElements=[])}resumePublish(){return _(this,null,function*(){this.shouldPublish&&(this.createCallId(!0),yield this.startPublish(!0))})}createLocalStream(e){return _(this,null,function*(){try{if(e.video)for(let i=0;i<this.previewElements.length;i++){const n=this.previewElements[i];sr(n)}else if(e.screen)for(let i=0;i<this.screenPreviewElements.length;i++){const n=this.screenPreviewElements[i];sr(n)}const t=yield this.streamManager.createLocalStream(e);return t!=null&&t.audioTrack&&this.audioVolumeIndicationInterval>0&&this.audioLevelMonitor.start(t.audioTrack,this.audioVolumeIndicationInterval),e.video?this.previewAll({primary:!0}):e.screen&&this.previewAll({screen:!0}),t}catch(t){const i=im[t.errorCode];throw i&&(e.audio?this.emit("localDeviceException",ir.AliEngineLocalDeviceTypeMic,i,""):e.video?this.emit("localDeviceException",ir.AliEngineLocalDeviceTypeCamera,i,""):e.screen?this.emit("localDeviceException",ir.AliEngineLocalDeviceTypeDisplay,i,""):this.emit("localDeviceException",ir.AliEngineLocalDeviceTypeUnknown,i,"")),t}})}stopLocalStream(e){return _(this,null,function*(){e.audio&&this.audioLevelMonitor.stop(),yield this.streamManager.stopLocalStream(e)})}compareAndPublish(e,t,i){return _(this,null,function*(){var a,c;if(!e&&!t)return;if(e&&!t){const o={};return i===L.Audio?o.audio=!0:i===L.VideoLarge||i===L.VideoSmall?(o.video=!0,o.vMsid=i):i===L.Screen&&(o.screen=!0),yield this.publishDeleteTracks(o)}const n={};if(t!=null&&t.hasVideo&&(n.isScreen=i===L.Screen,n.vMsid=i),t!=null&&t.hasAudio&&(n.aMsid=i),!e&&t)return yield this.publishAdd(t,n,!1);if(e&&t&&e.trackId!==(((a=t.videoTrack)==null?void 0:a.id)||((c=t.audioTrack)==null?void 0:c.id)))return yield this.publishReplace(t,n)})}reportAudioProfile(){const e=this.streamManager.cameraStreamInfo.audioProfile||"standard",t=Pe.AudioProfileMap.get(e);this.slsReporter.reportPublishProfile(L.Audio,{a_profile:e,bits:(t==null?void 0:t.maxBitrate)||0,samplerate:(t==null?void 0:t.sampleRate)||0,channel:(t==null?void 0:t.channelCount)||0})}reportVideoProfile(){const e=this.streamManager.cameraStreamInfo.videoProfile||"",t=Pe.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(L.VideoLarge,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}reportScreenProfile(){const e=this.streamManager.screenStreamInfo.videoProfile||"",t=Pe.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(L.Screen,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}updateDataChannel(e){e&&(this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"))}publishDataChannel(){return _(this,null,function*(){if(this.dataPubState.state!==ne.AliRtcStatePublishing){this.dataPubState.setState(ne.AliRtcStatePublishing);try{const e=yield this.rtsManager.publishAddDataChannel(this.url);e?(this.updateDataChannel(e),this.dataPubState.setState(ne.AliRtcStatePublished)):(this.dataPubState.setState(ne.AliRtcStateNoPublish),this.emit("publishDataError",new W(z.ERR_INNER,"publishDataError")))}catch(e){O.error("[LocalUser]","publishDataChannel error",e),this.dataPubState.setState(ne.AliRtcStateNoPublish)}}})}startPublish(){return _(this,arguments,function*(e=!1,t=Xt.MANUAL){var l;if(!this.joined)return;this.shouldPublish=!0;const i=this.streamManager.publishStreams,{audio:n,video:a,videoSmall:c,screen:o}=i;if(n||a||c||o)try{const d=new Date().getTime();n&&this.audioPubState.setState(ne.AliRtcStatePublishing),a&&this.videoPubState.setState(ne.AliRtcStatePublishing),c&&this.videoSmallPubState.setState(ne.AliRtcStatePublishing),o&&this.screenPubState.setState(ne.AliRtcStatePublishing),this.publishPromise=this.rtsManager.publish(this,e,t);const{traceId:h,l1ip:u}=yield this.publishPromise;this.streamTracks=this.rtsManager.publishingTracks,this.traceId=h;const p={type:Sr.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,resume:e,subscribe:{signal:"",pullstreamurl:this.url},l1ip:this.parameter.reportL1IP?u:void 0,callid:this.callId,tracks:this.streamTracks,traceid:h};(l=this.parameter.data)!=null&&l.enablePubDataChannel&&this.publishDataChannel().then(()=>{this.syncPublishToRoomServer(p,i,d)}),h&&(this.traceId=h),n&&this.reportAudioProfile(),a&&this.reportVideoProfile(),o&&this.reportScreenProfile(),yield this.syncPublishToRoomServer(p,i,d),n&&this.audioPubState.setState(ne.AliRtcStatePublished),a&&this.videoPubState.setState(ne.AliRtcStatePublished),c&&this.videoSmallPubState.setState(ne.AliRtcStatePublished),o&&this.screenPubState.setState(ne.AliRtcStatePublished)}catch(d){throw n&&this.audioPubState.setState(ne.AliRtcStateNoPublish),a&&this.videoPubState.setState(ne.AliRtcStateNoPublish),c&&this.videoSmallPubState.setState(ne.AliRtcStateNoPublish),o&&this.screenPubState.setState(ne.AliRtcStateNoPublish),d}else O.event(`[${Yt.logName}]`,"startPublish no stream founded")})}updateStreams(){return _(this,null,function*(){yield this.streamManager.updateStreams()})}publishUpdate(e){return _(this,null,function*(){var a,c,o,l,d;if(O.info(`[${Yt.logName}]`,"publishUpdate",e||"-",this.shouldPublish),!this.shouldPublish)return;if(!this.rtsManager.isConnecting&&!this.rtsManager.isConnected)return void(yield this.startPublish());yield this.publishPromise;const t=this.streamManager.publishStreams;let i;const n=new Date().getTime();try{const h=(a=this.streamTracks)==null?void 0:a.find(({ssrc:E,type:T,msid:R})=>T==="audio"&&E&&R===L.Audio),u=yield this.compareAndPublish(h,t.audio,L.Audio);u&&(i=u);const p=(c=this.streamTracks)==null?void 0:c.find(({ssrc:E,type:T,msid:R})=>T==="video"&&E&&R===L.VideoLarge),f=yield this.compareAndPublish(p,t.video,L.VideoLarge);f&&(i=f);const m=(o=this.streamTracks)==null?void 0:o.find(({ssrc:E,type:T,msid:R})=>T==="video"&&E&&R===L.VideoSmall),g=yield this.compareAndPublish(m,t.videoSmall,L.VideoSmall);g&&(i=g);const S=(l=this.streamTracks)==null?void 0:l.find(({ssrc:E,type:T,msid:R})=>T==="video"&&E&&R===L.Screen),v=yield this.compareAndPublish(S,t.screen,L.Screen);v&&(i=v),(d=this.parameter.data)!=null&&d.enablePubDataChannel&&!this.dc&&(yield this.publishDataChannel()),i||e!==Xt.RECONNECT?i&&(yield this.syncPublishToRoomServer(i,t,n)):this.syncPublishToRoomServer({type:Sr.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.rtsManager.publishingTracks,traceid:this.traceId},t,Date.now())}catch(h){const{code:u}=h!=null?h:{},p=this.url;throw u===403&&p&&(yield this.refreshPushStreamUrl(),i=yield this.publishUpdate()),h}return i})}syncPublishToRoomServer(e,t,i){return _(this,null,function*(){var o;if(!e)return void O.event(`[${Yt.logName}]`,"sync publish to room server failed because no publishInfo");let n=e;if(this.dc){const c=e,{tracks:l}=c,d=jt(c,["tracks"]);n=Q(D({},d),{tracks:[...l,{type:"data",msid:L.Data,ssrc:`web_${this.callId.substring(0,8)}_${((o=this.dc.datachannel)==null?void 0:o.id)||"0"}`,codec:"text"}]})}const a=yield this.signalingManager.publish(n);e.signaltid=a.tid})}refreshPushStreamUrl(){return _(this,null,function*(){const e=new W(z.ERR_INNER,"refresh push stream url error"),t=this.url;if(!t)throw e;const i=yield this.signalingManager.refreshUrl({pushstreamurl:t});if(!(i!=null&&i.pushstreamurl))throw e;this.url=i.pushstreamurl})}publishAdd(e,t,i=!1,n=0){return _(this,null,function*(){const a=(t==null?void 0:t.aMsid)===L.Audio,c=(t==null?void 0:t.vMsid)===L.VideoLarge,o=(t==null?void 0:t.vMsid)===L.VideoSmall,l=(t==null?void 0:t.vMsid)===L.Screen;a&&this.audioPubState.setState(ne.AliRtcStatePublishing),c&&this.videoPubState.setState(ne.AliRtcStatePublishing),o&&this.videoSmallPubState.setState(ne.AliRtcStatePublishing),l&&this.screenPubState.setState(ne.AliRtcStatePublishing);try{const d=yield this.rtsManager.publishAdd(this,e,t,!1,!0);d&&(this.traceId=d),a&&(this.audioPubState.setState(ne.AliRtcStatePublished),this.reportAudioProfile()),c&&(this.videoPubState.setState(ne.AliRtcStatePublished),this.reportVideoProfile()),o&&this.videoSmallPubState.setState(ne.AliRtcStatePublished),l&&(this.screenPubState.setState(ne.AliRtcStatePublished),this.reportScreenProfile()),this.streamTracks=this.rtsManager.publishingTracks;const h={type:Sr.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:i,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks,traceid:d};return this.reportSelfDeviceStatus(),this.monitorTimerId||this.startStreamMonitor(),h}catch(d){let h=z.ERR_SDK_PUBLISH_INVAILD;if(a&&(this.audioPubState.setState(ne.AliRtcStateNoPublish),h=z.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),c&&(this.videoPubState.setState(ne.AliRtcStateNoPublish),h=z.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),o&&(this.videoSmallPubState.setState(ne.AliRtcStateNoPublish),h=z.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED),l&&(this.screenPubState.setState(ne.AliRtcStateNoPublish),h=z.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED),d.errorCode===15006&&n<3)return this.publishAdd(e,t,i,n+1);throw W.fromError(d,h,"publish add failed")}})}publishReplace(e,t){return _(this,null,function*(){try{yield this.rtsManager.publishReplace(this.url,e,t),this.streamTracks=this.rtsManager.publishingTracks;const i=(t==null?void 0:t.vMsid)===L.VideoLarge,n=(t==null?void 0:t.vMsid)===L.Screen;i&&this.streamManager.setVideoProfile(void 0,void 0,!0),n&&this.streamManager.setScreenProfile(void 0,void 0);const a={type:Sr.Replace,userid:this.userId,sessionid:"",pubid:this.publishId,displayname:this.name,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks};return this.reportSelfDeviceStatus(),a}catch(i){throw W.fromError(i,z.ERR_INNER,`publish replace failed, vMsid: ${t==null?void 0:t.vMsid} aMsid: ${t==null?void 0:t.aMsid}`)}})}publishDeleteTracks(e){return _(this,null,function*(){const t={type:Sr.Delete,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{return yield this.rtsManager.publishDelete(this.url,e),this.streamTracks=this.rtsManager.publishingTracks,e.audio&&this.audioPubState.setState(ne.AliRtcStateNoPublish),e.video&&(e.vMsid===L.VideoSmall?this.videoSmallPubState.setState(ne.AliRtcStateNoPublish):this.videoPubState.setState(ne.AliRtcStateNoPublish)),e.screen&&this.screenPubState.setState(ne.AliRtcStateNoPublish),t.tracks=this.streamTracks,this.reportSelfDeviceStatus(),t}catch(i){throw W.fromError(i,z.ERR_INNER,"publish delete tracks failed")}})}publishStop(){return _(this,null,function*(){O.info(`[${Yt.logName}]`,"publishStop",{url:this.url});const e=new Date().getTime();try{const t=this.hasAudioTrackInMS,i=this.hasCameraTrackInMS,n=this.hasCameraDualTrackInMS,a=this.hasScreenTrackInMS;yield this.rtsManager.publishStop(this.url),t&&this.audioPubState.setState(ne.AliRtcStateNoPublish),i&&this.videoPubState.setState(ne.AliRtcStateNoPublish),n&&this.videoSmallPubState.setState(ne.AliRtcStateNoPublish),a&&this.screenPubState.setState(ne.AliRtcStateNoPublish),this.traceId="",Object.keys(this.monitorDataCache).forEach(o=>{this.reportPublishMonitor(o)}),this.streamTracks=[];const c={type:Sr.Stop,userid:this.userId,sessionid:this.sessionId,displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};return this.syncPublishToRoomServer(c,{},e),c}catch(t){throw W.fromError(t,z.ERR_INNER,"publish stop failed")}})}unPublish(){return _(this,null,function*(){this.shouldPublish=!1;const e=new Date().getTime();let t={type:Sr.UnPublish,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{if(this.isPublishing){const i=this.hasAudioTrackInMS,n=this.hasCameraTrackInMS,a=this.hasCameraDualTrackInMS,c=this.hasScreenTrackInMS;yield this.rtsManager.unpublish(),this.streamTracks=[],this.stopStreamMonitor(),i&&this.audioPubState.setState(ne.AliRtcStateNoPublish),n&&this.videoPubState.setState(ne.AliRtcStateNoPublish),a&&this.videoSmallPubState.setState(ne.AliRtcStateNoPublish),c&&this.screenPubState.setState(ne.AliRtcStateNoPublish),this.traceId="",this.clearStream()}return this.dc&&(this.rtsManager.publishStopDataChannel(this.url,this.dc),this.dataPubState.setState(ne.AliRtcStateNoPublish),this.dc=void 0),this.slsReporter.reportUnpublish(this.callId||"",e,0,""),t}catch(i){throw W.fromError(i,z.ERR_INNER,"unpublish failed")}})}reportSelfDeviceStatus(){this.emit(bt.Local,this.getDeviceStatus())}getDeviceStatus(){var t,i,n,a;let e={micOpen:!1,micInterrupted:!1,cameraOpen:!1,screenShare:!1,audioDisable:!0,videoDisable:!0,screenDisable:!0,backgroundMode:!1,accompanyPlaying:!1};return e.cameraOpen=this.hasCameraTrackInMS,e.videoDisable=this.hasCamera&&!((t=this.streamManager.cameraStreamInfo.originVideoTrack)!=null&&t.enabled),e.micOpen=this.hasAudioTrackInMS,e.audioDisable=this.hasMicrophone&&!((i=this.streamManager.cameraStreamInfo.originAudioTrack)!=null&&i.enabled),e.screenShare=this.hasScreenTrackInMS,e.screenDisable=this.hasScreenShare&&!((a=(n=this.streamManager.screenStreamInfo)==null?void 0:n.originVideoTrack)!=null&&a.enabled),Il.getCurrentStatus(e)}resetPreviewElements(){this.previewElements.forEach(e=>{e.srcObject=null,e._playPromise=void 0},[]),this.previewElements=[]}resetSecondayPreviewElements(){this.screenPreviewElements.forEach(e=>{e.srcObject=null,e._playPromise=void 0},[]),this.screenPreviewElements=[]}getMediaStats(e){return this.pcMediaStatsMap[e]}reportPublishMonitor(e){if(!e)return;let t;try{t=e===L.Audio?this.rtsManager.getStreamByMsid({url:this.url,aMsid:e}).audioTrack:this.rtsManager.getStreamByMsid({url:this.url,vMsid:e}).videoTrack}catch(i){}this.slsReporter.reportPublishMonitor(this.callId,this.traceId||"",e,t,this.monitorDataCache[e]),this.monitorDataCache[e]=[]}reportNetwork(){this.slsReporter.reportNetworkMonitor(this.candidateDataCache),this.candidateDataCache=[]}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>_(this,null,function*(){var e,i;try{const n=yield this.rtsManager.getPCStats();let a,c;if(n==null||n.forEach(l=>{l.type==="media-source"||l.type==="media-playout"?l.id&&(this.pcMediaStatsMap[l.id]=l):l.type==="candidate-pair"&&l.state==="succeeded"&&(a=l)}),((e=this.candidateDataCache)==null?void 0:e.length)>0){const l=this.candidateDataCache[this.candidateDataCache.length-1]||{},t=l,{_last:d}=t;c=jt(t,["_last"])}((i=this.candidateDataCache)==null?void 0:i.length)>=30&&this.reportNetwork(),a&&(a._last=c,this.candidateDataCache.push(a));let o=Object.keys(this.monitorDataCache).filter(l=>{var d;return((d=this.monitorDataCache[l])==null?void 0:d.length)>0});(this.streamTracks||[]).forEach(l=>{const d=l.msid;if(!d)return;let h;o.includes(d)&&(o=o.filter(u=>u!==d)),h=d===L.Audio?this.rtsManager.getPublishAudioStats(this.url):this.rtsManager.getPublishVideoStats(this.url,d),h.then(u=>{if(!u.timestamp)return;this.monitorDataCache[d]||(this.monitorDataCache[d]=[]);const p=this.getMediaStats(u.mediaSourceId);u._source=p;const f=this.monitorDataCache[d];let m;if((f==null?void 0:f.length)>0){const S=f[f.length-1]||{},g=S,{_last:v}=g;m=jt(g,["_last"])}(f==null?void 0:f.length)>=30&&this.reportPublishMonitor(d),u._last=m,u._codec=l.codec||"",this.monitorDataCache[d].push(u)})}),o.forEach(l=>{this.reportPublishMonitor(l)})}catch(n){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportPublishMonitor(e)})}clearStream(){this.streamManager.stop(),this.audioPubState.setState(ne.AliRtcStatePublishIdle),this.videoPubState.setState(ne.AliRtcStatePublishIdle),this.videoSmallPubState.setState(ne.AliRtcStatePublishIdle),this.screenPubState.setState(ne.AliRtcStatePublishIdle)}getCurrentCameraDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originVideoTrack)==null?void 0:e.getSettings().deviceId}getCurrentMicDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originAudioTrack)==null?void 0:e.getSettings().deviceId}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.streamManager.cameraStreamInfo.originAudioTrack&&this.audioLevelMonitor.start(this.streamManager.cameraStreamInfo.originAudioTrack,e),this.audioVolumeIndicationInterval=e)}sendSEI(e,t,i){return _(this,null,function*(){if(!this.url)return;let n=0;return n=!t||t<1?1:t-1,this.rtsManager.sendSEI(this.url,e,n,i)})}sendDataChannelMessage(e){var i;if(!((i=this.parameter.data)!=null&&i.enablePubDataChannel))throw new W(z.ERR_INNER,"data channel publish is not enabled");if(!this.dc)throw new W(z.ERR_INNER,"data channel is not ready");const t=vn(e.toBuffer(),1156);t.forEach((n,a)=>{const c=new Lr(new Nr(n.byteLength,a===t.length-1,a===0?1:0),n);this.dc.send(c.toGRTNBuffer())})}getStats(){return _(this,null,function*(){const e=[];if(this.hasAudioTrackInMS){const a=yield this.rtsManager.getPublishAudioStats(this.url);a&&e.push({stats:a,track:Or.AliRtcAudioTrackMic})}const t=[];if(this.hasCameraTrackInMS){const a=yield this.rtsManager.getPublishVideoStats(this.url,L.VideoLarge);a&&t.push({track:be.AliRtcVideoTrackCamera,streamType:it.AliRtcVideoStreamTypeHigh,stats:a})}if(this.hasCameraDualTrackInMS){const a=yield this.rtsManager.getPublishVideoStats(this.url,L.VideoSmall);a&&t.push({track:be.AliRtcVideoTrackCamera,streamType:it.AliRtcVideoStreamTypeLow,stats:a})}if(this.hasScreenTrackInMS){const a=yield this.rtsManager.getPublishVideoStats(this.url,L.Screen);a&&t.push({track:be.AliRtcVideoTrackScreen,stats:a})}let i;const n=yield this.rtsManager.getPCStats();return n==null||n.forEach(a=>{a.type==="candidate-pair"&&a.state==="succeeded"&&(i=a)}),{audio:e,video:t,candidate:i}})}markReconnect(e){const t=[],i=this.streamManager.publishStreams;!i.audio||e&&!e.includes(L.Audio)||t.push(this.audioPubState),!i.video||e&&!e.includes(L.VideoLarge)||t.push(this.videoPubState),!i.screen||e&&!e.includes(L.Screen)||t.push(this.screenPubState),!this.dc||e&&!e.includes(L.Data)||t.push(this.dataPubState),t.forEach(n=>{n.setState(ne.AliRtcStateReconnecting)})}markReconnected(e){var n;const t=[],i=this.streamManager.publishStreams;if(!i.audio||e&&!e.includes(L.Audio)||t.push(this.audioPubState),!i.video||e&&!e.includes(L.VideoLarge)||t.push(this.videoPubState),!i.screen||e&&!e.includes(L.Screen)||t.push(this.screenPubState),this.dc&&(!e||e.includes(L.Data))&&(t.push(this.dataPubState),(n=this.parameter.data)==null?void 0:n.enablePubDataChannel)){const a=this.rtsManager.getDatachannelByMsid({url:this.url,msid:L.Data});this.updateDataChannel(a)}this.publishUpdate(Xt.RECONNECT),t.forEach(a=>{a.setState(ne.AliRtcStatePublished)})}},b(Yt,"logName","LocalUser"),Yt);Be([k()],Le.prototype,"clearPublishState",1),Be([k()],Le.prototype,"clear",1),Be([k(J)],Le.prototype,"startDefaultCameraAndMic",1),Be([k()],Le.prototype,"setViewConfig",1),Be([k()],Le.prototype,"startCameraCapture",1),Be([k()],Le.prototype,"stopCameraCapture",1),Be([k()],Le.prototype,"startAudioCapture",1),Be([k()],Le.prototype,"stopAudioCapture",1),Be([k()],Le.prototype,"startCameraAndMic",1),Be([k()],Le.prototype,"stopPreview",1),Be([k()],Le.prototype,"resumePublish",1),Be([k()],Le.prototype,"createLocalStream",1),Be([k()],Le.prototype,"stopLocalStream",1),Be([k()],Le.prototype,"updateDataChannel",1),Be([k(J)],Le.prototype,"startPublish",1),Be([k()],Le.prototype,"updateStreams",1),Be([k(([s])=>[s])],Le.prototype,"syncPublishToRoomServer",1),Be([k()],Le.prototype,"refreshPushStreamUrl",1),Be([k(([s,r,e])=>[JSON.stringify(e)])],Le.prototype,"publishAdd",1),Be([k(([s,r])=>[JSON.stringify(r)])],Le.prototype,"publishReplace",1),Be([k(J)],Le.prototype,"publishDeleteTracks",1),Be([k()],Le.prototype,"publishStop",1),Be([k()],Le.prototype,"unPublish",1),Be([k(([s,r,e])=>[s.length,r,e])],Le.prototype,"sendSEI",1),Be([k(J)],Le.prototype,"markReconnect",1),Be([k(J)],Le.prototype,"markReconnected",1);let am=Le;var Bt=(s=>(s.OPUS="opus",s.H264="H264",s.H265="H265",s.AV1="AV1",s.UNKNOWN="",s))(Bt||{}),ve=(s=>(s[s.NotSubscribe=0]="NotSubscribe",s[s.Subscribing=1]="Subscribing",s[s.Subscribed=2]="Subscribed",s))(ve||{}),Br=(s=>(s.VideoTrackEnded="videoTrackEnded",s.AudioTrackEnded="audioTrackEnded",s.ScreenTrackEnded="screenTrackEnded",s))(Br||{});const Ol=s=>_(this,null,function*(){return yield Pe.createStream({custom:!0,mediaStream:s})}),Ai=s=>_(this,null,function*(){const r=(e=>{const t=new MediaStream;return t.addTrack(e),t})(s);return yield Ol(r)});var om=Object.defineProperty,cm=Object.getOwnPropertyDescriptor;class Hn extends de{constructor(){super();b(this,"audioInfo",{subscribeState:ve.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:Bt.UNKNOWN});b(this,"videoLargeInfo",{subscribeState:ve.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:Bt.UNKNOWN});b(this,"videoSmallInfo",{subscribeState:ve.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:Bt.UNKNOWN});b(this,"screenInfo",{subscribeState:ve.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:Bt.UNKNOWN});b(this,"dataInfo",{subscribeState:ve.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:Bt.UNKNOWN});b(this,"audioVolume",1);b(this,"audioMuted",!1);b(this,"userStatus")}getAudioInfo(){return this.audioInfo}getVideoSmallInfo(){return this.videoSmallInfo}getVideoLargeInfo(){return this.videoLargeInfo}getScreenInfo(){return this.screenInfo}getDataInfo(){return this.dataInfo}get subscribingInfos(){return[this.audioInfo,this.videoLargeInfo,this.videoSmallInfo,this.screenInfo].filter(e=>e.msid&&e.subscribeState===ve.Subscribed)}get hasTrack(){return this.hasAudio||this.hasVideo||this.hasScreen||this.hasData}get hasAudio(){return this.audioInfo.ssrc!==""}get hasVideo(){return this.videoLargeInfo.ssrc!==""||this.videoSmallInfo.ssrc!==""}get hasVideoLarge(){return this.videoLargeInfo.ssrc!==""}get hasVideoSmall(){return this.videoSmallInfo.ssrc!==""}get hasScreen(){return this.screenInfo.ssrc!==""}get hasData(){return this.dataInfo.ssrc!==""}get hasMediaSubscribed(){return this.isAudioSubscribed||this.isVideoSubscribed||this.isScreenSubscribed}get isAudioSubscribed(){return this.audioInfo.subscribeState===ve.Subscribed}get isAudioSubscribing(){return this.audioInfo.subscribeState===ve.Subscribing}get isVideoSubscribed(){return this.isVideoLargeSubscribed||this.isVideoSmallSubscribed}get isVideoSubscribing(){return this.isVideoLargeSubscribing||this.isVideoSmallSubscribing}get isVideoLargeSubscribed(){return this.videoLargeInfo.subscribeState===ve.Subscribed}get isVideoLargeSubscribing(){return this.videoLargeInfo.subscribeState===ve.Subscribing}get isVideoSmallSubscribed(){return this.videoSmallInfo.subscribeState===ve.Subscribed}get isVideoSmallSubscribing(){return this.videoSmallInfo.subscribeState===ve.Subscribing}get isScreenSubscribed(){return this.screenInfo.subscribeState===ve.Subscribed}get isScreenSubscribing(){return this.screenInfo.subscribeState===ve.Subscribing}get isDataSubscribed(){return this.dataInfo.subscribeState===ve.Subscribed}get isDataSubscribing(){return this.dataInfo.subscribeState===ve.Subscribing}get audioCodec(){return this.audioInfo.codec}get videoCodec(){return this.hasVideoLarge?this.videoLargeInfo.codec:this.hasVideoSmall?this.videoSmallInfo.codec:this.hasScreen?this.screenInfo.codec:Bt.UNKNOWN}get audioTrackInfo(){return this.hasAudio?Or.AliRtcAudioTrackMic:Or.AliRtcAudioTrackNo}get videoTrackInfo(){return this.hasVideo&&this.hasScreen?be.AliRtcVideoTrackBoth:this.hasVideo?be.AliRtcVideoTrackCamera:this.hasScreen?be.AliRtcVideoTrackScreen:be.AliRtcVideoTrackNo}updateTracks(e){let t="",i="",n="",a="",c="";return e?(e.forEach(o=>{var u;let l=Bt.UNKNOWN;const d=((u=o==null?void 0:o.attr)==null?void 0:u.reason)==="reconnect";if(o.userdata){const{codec:p}=JSON.parse(o.userdata);p&&(l=p)}var h;(h=o.msid)===L.Audio||h===fn.Audio?(t=o.ssrc,this.audioInfo.msid=o.msid,this.audioInfo.codec=l,(d||this.audioInfo.ssrc!==t)&&(this.audioInfo.subscribeState=ve.NotSubscribe)):(p=>p===L.VideoSmall)(o.msid)?(n=o.ssrc,this.videoSmallInfo.msid=o.msid,this.videoSmallInfo.codec=l,(d||this.videoSmallInfo.ssrc!==n)&&(this.videoSmallInfo.subscribeState=ve.NotSubscribe)):(p=>p===L.VideoLarge||p===fn.VideoLarge)(o.msid)?(i=o.ssrc,this.videoLargeInfo.msid=o.msid,this.videoLargeInfo.codec=l,(d||this.videoLargeInfo.ssrc!==i)&&(this.videoLargeInfo.subscribeState=ve.NotSubscribe)):(p=>p===L.Screen)(o.msid)?(a=o.ssrc,this.screenInfo.msid=o.msid,this.screenInfo.codec=l,(d||this.screenInfo.ssrc!==a)&&(this.screenInfo.subscribeState=ve.NotSubscribe)):(p=>p===L.Data)(o.msid)&&(c=o.ssrc,this.dataInfo.msid=o.msid,this.dataInfo.codec=l,(d||this.dataInfo.ssrc!==c)&&(this.dataInfo.subscribeState=ve.NotSubscribe))}),this.updateRemoteTrackSsrc(t,i,n,a,c)):this.updateRemoteTrackSsrc(t,i,n,a,c),{}}updateRemoteTrackSsrc(e,t,i,n,a){this.audioInfo.ssrc=e,this.videoSmallInfo.ssrc=i,this.videoLargeInfo.ssrc=t,this.screenInfo.ssrc=n,this.dataInfo.ssrc=a}markRemoteTrackSubscribing(e){return e.video&&(e.vMsid===this.videoSmallInfo.msid&&(this.videoSmallInfo.subscribeState=ve.Subscribing),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=ve.Subscribing)),e.screen&&(this.screenInfo.subscribeState=ve.Subscribing),e.audio&&(this.audioInfo.subscribeState=ve.Subscribing),e.data&&(this.dataInfo.subscribeState=ve.Subscribing),{videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo}}updateRemoteTrackSubState(e){return e.video!==void 0&&(e.vMsid!==this.videoSmallInfo.msid&&e.vMsid||(this.videoSmallInfo.subscribeState=e.video?ve.Subscribed:ve.NotSubscribe),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=e.video?ve.Subscribed:ve.NotSubscribe)),e.screen!==void 0&&(this.screenInfo.subscribeState=e.screen?ve.Subscribed:ve.NotSubscribe),e.audio!==void 0&&(this.audioInfo.subscribeState=e.audio?ve.Subscribed:ve.NotSubscribe),e.data!==void 0&&(this.dataInfo.subscribeState=e.data?ve.Subscribed:ve.NotSubscribe),{audioInfo:this.audioInfo,videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo,screenInfo:this.screenInfo,dataInfo:this.dataInfo}}updateRemoteUserDeviceStatus(e){let t=Il.parseStatus(e);const{audioDisable:i,videoDisable:n,screenDisable:a}=t;return this.userStatus?(this.userStatus.audioDisable!=i&&(this.userStatus.audioDisable=i,this.emit(bt.Remote,i?We.MuteAudio:We.UnmuteAudio)),this.userStatus.videoDisable!=n&&(this.userStatus.videoDisable=n,this.emit(bt.Remote,n?We.MuteVideo:We.UnmuteVideo)),this.userStatus.screenDisable!=a&&(this.userStatus.screenDisable=a,this.emit(bt.Remote,a?We.MuteScreen:We.UnmuteScreen))):(this.userStatus=t,this.emit(bt.Remote,i?We.MuteAudio:We.UnmuteAudio),this.emit(bt.Remote,n?We.MuteVideo:We.UnmuteVideo),this.emit(bt.Remote,a?We.MuteScreen:We.UnmuteScreen)),!1}}b(Hn,"logName","RemoteStreamInfo"),((s,r,e,t)=>{for(var i,n=t>1?void 0:t?cm(r,e):r,a=s.length-1;a>=0;a--)(i=s[a])&&(n=(t?i(r,e,n):i(n))||n);t&&n&&om(r,e,n)})([k()],Hn.prototype,"updateRemoteTrackSubState",1);class Nl{constructor(r){b(this,"remoteUser");this.remoteUser=r}get userId(){return this.remoteUser.userId}get displayName(){return this.remoteUser.displayname}get isMuteAudioPlaying(){return this.remoteUser.getAudioMuted()}get hasAudio(){return this.remoteUser.hasAudioTrack}get hasCamera(){return this.remoteUser.hasVideoTrack}get hasCameraLarge(){return this.remoteUser.hasVideoLargeTrack}get hasCameraSmall(){return this.remoteUser.hasVideoSmallTrack}get hasScreenShare(){return this.remoteUser.hasScreenTrack}get isAudioSubscribing(){return this.remoteUser.isAudioSubscribing}get isVideoSubscribing(){return this.remoteUser.isVideoSubscribing}get isVideoLargeSubscribing(){return this.remoteUser.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.remoteUser.isVideoSmallSubscribing}get isScreenSubscribing(){return this.remoteUser.isScreenSubscribing}get audioElement(){return this.remoteUser.getAudioElement()}}var dm=Object.defineProperty,lm=Object.getOwnPropertyDescriptor,st=(s,r,e,t)=>{for(var i,n=t>1?void 0:t?lm(r,e):r,a=s.length-1;a>=0;a--)(i=s[a])&&(n=(t?i(r,e,n):i(n))||n);return t&&n&&dm(r,e,n),n};class ri extends de{constructor(){super();b(this,"state");b(this,"time");b(this,"_enabled");this.state=ge.AliRtcStateSubscribeIdle,this.time=Date.now(),this._enabled=!0}setState(e){if(this.state===e)return;const t=this.state,i=this.time;this.state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-i)/1e3))}get currentState(){return this.state}getEnabled(){return this._enabled}setEnabled(e){this._enabled=e}}const et=(jr=class extends Al{constructor(e){var p;const{userId:t,displayName:i,rtsManager:n,usersViewMap:a,slsReporter:c,signalingManager:o,localUser:l,audioVolumeIndicationInterval:d,playoutVolume:h,parameter:u}=e;super(t,i,n,d);b(this,"remoteCallId","");b(this,"remoteUserInfo");b(this,"localUser");b(this,"lastPubId","");b(this,"stream");b(this,"screenStream");b(this,"viewMap");b(this,"audioTrack");b(this,"audioElement");b(this,"subscribed",!1);b(this,"mediaStream");b(this,"secondaryMediaStream");b(this,"prevSubConfig");b(this,"signalingManager");b(this,"slsReporter");b(this,"wantSubAudio",!1);b(this,"wantSubVideo",!1);b(this,"wantSubScreen",!1);b(this,"defaultVideoStreamType",it.AliRtcVideoStreamTypeHigh);b(this,"audioMuted",!1);b(this,"playoutVolume",1);b(this,"playoutGainNode");b(this,"audioSubState");b(this,"videoSubState");b(this,"videoLargeSubState",new ri);b(this,"videoSmallSubState",new ri);b(this,"screenSubState");b(this,"dataSubState");b(this,"dc");b(this,"dcMsgWaitingPieces",[]);b(this,"streamInfo");b(this,"_streamUrl","");b(this,"parameter",{});b(this,"monitorTimerId");b(this,"monitorDataCache",{});b(this,"traceId","");b(this,"handleAudioContextSuspended",e=>{e.target.state==="suspended"&&this.emit("remoteAudioPlayError",this.uid,"AudioContext suspended")});b(this,"onDataChannelMessage",e=>{var n;const t=Lr.parse(e.slice(4));let i;if(t.body){if(!t.isFin)return t.header.frameType===1&&(this.dcMsgWaitingPieces=[]),void this.dcMsgWaitingPieces.push(t.body);if(this.dcMsgWaitingPieces.length>0){const a=this.dcMsgWaitingPieces.reduce((c,o)=>c+o.byteLength,t.body.byteLength);try{const c=new ArrayBuffer(a);let o=0;for(let l=0;l<this.dcMsgWaitingPieces.length;l++){const d=this.dcMsgWaitingPieces[l];new Uint8Array(c,o,d.byteLength).set(new Uint8Array(d)),o+=d.byteLength}new Uint8Array(c,o,t.body.byteLength).set(new Uint8Array(t.body)),i=br.parse(c)}catch(c){}this.dcMsgWaitingPieces=[],i||(i=br.parse(t.body))}else i=br.parse(t.body);i||O.event(`[${this.logName}]`,`parse data channel message fail, piece count: ${this.dcMsgWaitingPieces.length+1}`)}i&&(O.event(`[${this.logName}]`,`receive dc message, length(${(n=i.data)==null?void 0:n.byteLength})`),this.emit("remoteDataChannelMessage",this.uid,i))});b(this,"onDataChannelError",e=>{this.emit("occurError",W.fromError(e,z.ERR_SDK_SUBSCRIBE_DATA_ERROR))});b(this,"dataChannelConnected",e=>{e&&(this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"),this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dc.on("message",this.onDataChannelMessage),this.dc.on("error",this.onDataChannelError))});b(this,"handleAudioPaused",()=>{this.emit("remoteAudioPlayError",this.uid,"paused")});this.streamInfo=new Hn,this.remoteUserInfo=new Nl(this),this.parameter=u,this.streamInfo.on(bt.Remote,f=>{this.emit(bt.Remote,f,this.userId)}),this.signalingManager=o,this.viewMap=(p=a[t])!=null?p:{cameraViews:[],screenViews:[]},a[t]=this.viewMap,this.slsReporter=c,this.localUser=l,this.audioSubState=new ri,this.audioSubState.on("change",(f,m,g)=>{this.emit("audioSubscribeStateChanged",this.uid,f,m,g)}),this.videoSubState=new ri,this.videoSubState.on("change",(f,m,g)=>{this.emit("videoSubscribeStateChanged",this.uid,f,m,g)}),this.screenSubState=new ri,this.screenSubState.on("change",(f,m,g)=>{this.emit("screenSubscribeStateChanged",this.uid,f,m,g)}),this.dataSubState=new ri,this.dataSubState.on("change",(f,m,g)=>{this.emit("dataSubscribeStateChanged",this.uid,f,m,g)}),this.playoutVolume=h}get logName(){return`${jr.logName}(${this.userId})`}get streamUrl(){return this._streamUrl}set streamUrl(e){this._streamUrl=e,this.rtsManager.updateAuth(e)}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e}setRemoteDefaultVideoStreamType(e){e!==this.defaultVideoStreamType&&(this.defaultVideoStreamType=e,this.updateSubscribe(De.User))}setAudioMuted(e){this.audioMuted=e,this.toggleAudio(!e)}getAudioElement(){return this.audioElement}setPlayoutVolume(e){if(this.playoutVolume=e,this.audioElement)if(this.parameter.enableAudioContextPlayoutVolume)if(this.playoutGainNode)this.playoutGainNode.gain.value=e;else{const t=this.audioElement.srcObject;if(t){const i=Ur.getInstance();i.addEventListener("statechange",this.handleAudioContextSuspended);const n=i.createMediaStreamSource(t);this.audioElement.muted=!0,this.playoutGainNode=i.createGain(),n.connect(this.playoutGainNode),this.playoutGainNode.gain.value=e,this.playoutGainNode.connect(i.destination)}}else this.audioElement.volume=e}getAudioMuted(){return this.audioMuted}get hasAudioTrack(){return this.streamInfo.hasAudio}get hasVideoTrack(){return this.streamInfo.hasVideo}get hasVideoLargeTrack(){return this.streamInfo.hasVideoLarge}get hasVideoSmallTrack(){return this.streamInfo.hasVideoSmall}get hasScreenTrack(){return this.streamInfo.hasScreen}get isAudioSubscribing(){return this.streamInfo.isAudioSubscribed||this.streamInfo.isAudioSubscribing}get isVideoSubscribing(){return this.streamInfo.isVideoSubscribed||this.streamInfo.isVideoSubscribing}get isVideoLargeSubscribing(){return this.streamInfo.isVideoLargeSubscribed||this.streamInfo.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing}get isScreenSubscribing(){return this.streamInfo.isScreenSubscribed||this.streamInfo.isScreenSubscribing}get isDataSubscribing(){return this.streamInfo.isDataSubscribed||this.streamInfo.isDataSubscribing}get audioEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.audioTrack)!=null&&t.enabled)}get videoEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get screenEnabled(){var e,t;return!!((t=(e=this.screenStream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get getAudioTrack(){return this.audioTrack}get getCameraStream(){return this.stream}get getScreenStream(){return this.screenStream}setViewConfig(e,t){if(t!==be.AliRtcVideoTrackScreen&&t!==be.AliRtcVideoTrackCamera)throw new W(z.ERR_INVALID_ARGUMENTS,"track is not AliRtcVideoTrackScreen or AliRtcVideoTrackCamera");e?bn(e).forEach(i=>{i.setAttribute("playsinline",""),Pe.BrowserUtil.isMicroMessenger&&(i.setAttribute("x5-video-player-type","h5-page"),i.setAttribute("x5-playsinline",""),Pe.SystenUtil.isAndroid||Pe.SystenUtil.isIos&&i.setAttribute("x-webkit-airplay","allow")),t===be.AliRtcVideoTrackScreen?this.viewMap.screenViews.push(i):this.viewMap.cameraViews.push(i),this.play(i,t===be.AliRtcVideoTrackScreen)}):(this.stopPlayAll(t===be.AliRtcVideoTrackScreen),t===be.AliRtcVideoTrackScreen?this.viewMap.screenViews=[]:this.viewMap.cameraViews=[])}clear(e=!0){return _(this,null,function*(){ca(jr.prototype,this,"clear").call(this),this.stopPlayAudio(),this.stopStreamMonitor(),e&&this.subscribeDeleteAllTracks(this.streamUrl).catch(t=>{O.event(`[${this.logName}]`,`stopSubscribeAllTracks error: ${t.message||t}`)}),this.clearStream(),this.clearScreenStream(),this.playoutGainNode&&(this.playoutGainNode.disconnect(),this.playoutGainNode=void 0,Ur.getInstance().removeEventListener("statechange",this.handleAudioContextSuspended)),this.streamInfo.removeAllListeners(bt.Remote)})}updateRemoteUserDeviceStatus(e){this.streamInfo.updateRemoteUserDeviceStatus(e)}updateRemoteTracks(e,t,i,n){return _(this,null,function*(){return this.remoteCallId=e,this.streamUrl&&this.streamInfo.hasTrack||(this.streamUrl=t),this.streamInfo.updateTracks(n)})}subscribe(n,a){return _(this,arguments,function*(e,t,i=Date.now()){var p,f;let c=e;if(!c){const{hasAudio:m,hasVideo:g,hasScreen:S,hasData:v}=(p=this.streamInfo)!=null?p:{};c={audio:this.wantSubAudio&&m,video:this.wantSubVideo&&g,screen:this.wantSubScreen&&S,data:((f=this.parameter.data)==null?void 0:f.enableSubDataChannel)&&v}}this.streamInfo.markRemoteTrackSubscribing(c);const{screen:o,audio:l,video:d,vMsid:h}=c,u=[];(d||l)&&u.push({audio:l,video:d,vMsid:h}),o&&u.push({screen:o}),(u.length!==0||e!=null&&e.data)&&(yield Promise.all(u.map(m=>this.subscribeProxy(m,t||De.User,i))),e!=null&&e.data&&this.subscribeDataChannel())})}subscribeProxy(e,t,i){return _(this,null,function*(){var c,o;let n=new Date().getTime(),a="";try{e.audio&&this.audioSubState.setState(ge.AliRtcStateSubscribing),e.video&&(this.videoSubState.currentState!==ge.AliRtcStateSubscribeIdle&&this.videoSubState.currentState!==ge.AliRtcStateNoSubscribe||this.videoSubState.setState(ge.AliRtcStateSubscribing)),e.screen&&this.screenSubState.setState(ge.AliRtcStateSubscribing);const l=yield this.rtsManager.subscribe({remoteUser:this,options:e},t,((c=this.localUser)==null?void 0:c.callId)||"",this.callId,i);this.streamInfo.updateRemoteTrackSubState(e),a=l.traceId||"";const{stream:d}=l;if(a&&(this.traceId=a),e.audio){const p=d.audioTrack;p&&(this.audioTrack=p,(o=d.mediaStream)==null||o.removeTrack(p),this.playAudio(),this.audioVolumeIndicationInterval&&this.audioLevelMonitor.start(p,this.audioVolumeIndicationInterval)),this.audioSubState.getEnabled()||this.toggleAudio(!1),this.audioSubState.setState(ge.AliRtcStateSubscribed)}e.video&&(this.updateStream(d,this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing),this.videoSubState.getEnabled()||this.toggleVideo(!1),this.videoSubState.setState(ge.AliRtcStateSubscribed),e.vMsid===L.VideoSmall?this.videoSmallSubState.setState(ge.AliRtcStateSubscribed):this.videoLargeSubState.setState(ge.AliRtcStateSubscribed)),e.screen&&(this.updateScreenStream(d),this.videoSubState.getEnabled()||this.toggleScreen(!1),this.screenSubState.setState(ge.AliRtcStateSubscribed));const h=new Date().getTime()-n,u=Date.now();setTimeout(()=>{this.slsReporter.reportSubscribe(this.callId,this.remoteCallId,!!e.video&&e.vMsid===L.VideoLarge,!!e.video&&e.vMsid===L.VideoSmall,!!e.screen,!!e.audio,0,"",h,{pctid:this.rtsManager.pcTraceId,subtid:this.traceId,ajsub:t===De.Join?1:0,url:this.streamUrl,est:n},u)},6e3),this.startStreamMonitor(),l.isHTTP&&l.statsCheckPromise&&(yield Promise.race([l.statsCheckPromise,lr(1500)]))}catch(l){const d=new Date().getTime()-n;e.audio&&this.audioSubState.setState(ge.AliRtcStateNoSubscribe),e.video&&this.videoSubState.setState(ge.AliRtcStateNoSubscribe),e.screen&&this.screenSubState.setState(ge.AliRtcStateNoSubscribe),l&&(l.message=`user(${this.uid}) subscribe error, ${(l==null?void 0:l.message)||""}`);let h=z.ERR_INNER;e.audio&&(h=z.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED),e.video&&(h=e.vMsid===L.VideoSmall?z.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED:z.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED),e.screen&&(h=z.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED),this.slsReporter.reportSubscribe(this.callId,this.remoteCallId,!!e.video&&e.vMsid===L.VideoLarge,!!e.video&&e.vMsid===L.VideoSmall,!!e.screen,!!e.audio,h,"",d,{pctid:this.rtsManager.pcTraceId,subtid:"",ajsub:t===De.Join?1:0,url:this.streamUrl,est:n});const u=W.fromError(l,h);throw this.emit("remoteSubscribeError",u),u}})}subscribeDeleteTracks(e){return _(this,null,function*(){const{audio:t,video:i,screen:n,data:a,vMsid:c}=e,o=[];(t||i||a)&&o.push({audio:t,video:i,vMsid:c}),n&&o.push({screen:n}),o.length!==0&&(yield Promise.all(o.map(l=>this.subscribeDeleteProxy(l))),e.data&&this.subscribeDeleteDataChannel())})}subscribeDeleteProxy(e){return _(this,null,function*(){try{const t=yield this.rtsManager.subscribeDelete({remoteUser:this,options:e}),{stream:i}=t!=null?t:{},n={};e.audio===!0&&(n.audio=!1,this.audioSubState.setState(ge.AliRtcStateNoSubscribe)),e.video===!0&&(n.video=!1,e.vMsid===L.VideoSmall?(this.videoSmallSubState.setState(ge.AliRtcStateNoSubscribe),this.videoLargeSubState.currentState!==ge.AliRtcStateNoSubscribe&&this.videoLargeSubState.currentState!==ge.AliRtcStateSubscribeIdle||this.videoSubState.setState(ge.AliRtcStateNoSubscribe)):(this.videoLargeSubState.setState(ge.AliRtcStateNoSubscribe),this.videoSmallSubState.currentState!==ge.AliRtcStateNoSubscribe&&this.videoSmallSubState.currentState!==ge.AliRtcStateSubscribeIdle||this.videoSubState.setState(ge.AliRtcStateNoSubscribe))),e.screen===!0&&(n.screen=!1,this.screenSubState.setState(ge.AliRtcStateNoSubscribe));const{callId:a,remoteCallId:c}=this,o={callid:a,remoteCallid:c,remoteStream:i};return e.audio&&(this.audioLevelMonitor.stop(),this.stopPlayAudio(),this.audioTrack=void 0),this.streamInfo.updateRemoteTrackSubState({audio:e.audio!==!0&&void 0,video:e.video!==!0&&void 0,screen:e.screen!==!0&&void 0,vMsid:e.vMsid}),o}catch(t){throw W.fromError(t,z.ERR_INNER,"subscribe delete failed")}})}restore(){this.callId="",this.clearStream(),this.clearScreenStream(),this.audioTrack=void 0,this.streamInfo.updateRemoteTrackSubState({audio:!1,video:!1,screen:!1,data:!1}),this.audioElement&&this.audioElement.removeEventListener("pause",this.handleAudioPaused)}resumeAudio(){return _(this,null,function*(){const e=Ur.getInstance();return e.state!=="running"&&e.resume(),this.audioElement?this.audioElement.play():this.playAudio()})}resumeVideo(e){return _(this,null,function*(){return e&&e!==be.AliRtcVideoTrackCamera&&e!==be.AliRtcVideoTrackBoth?e&&e!==be.AliRtcVideoTrackScreen&&e!==be.AliRtcVideoTrackBoth?void 0:this.playAll(!0):this.playAll()})}resumePlay(){this.playAudio(),this.playAll(),this.playAll(!0)}stopSubscribe(e){return _(this,null,function*(){let t=new Date().getTime();try{e?yield this.subscribeDeleteTracks(e):yield this.subscribeDeleteAllTracks(this.streamUrl),this.slsReporter.reportUnsubscribe(this.callId,this.remoteCallId,new Date().getTime()-t,0,"")}catch(i){throw this.slsReporter.reportUnsubscribe(this.callId,this.remoteCallId,new Date().getTime()-t,0,""),i}})}subscribeDeleteAllTracks(e){return _(this,null,function*(){var n,a,c,o;const{callId:t,remoteCallId:i}=this;if((this.isAudioSubscribing||this.isVideoSubscribing||this.isScreenSubscribing||this.dc)&&e)try{yield this.subscribeDeleteTracks({audio:this.isAudioSubscribing,video:this.isVideoSubscribing,screen:this.isScreenSubscribing,data:!!this.dc}),this.restore();const l={callid:t,remoteCallid:i,remoteStream:this.stream};return this.callId="",l}catch(l){if(((o=(c=(a=(n=l==null?void 0:l.extraInfo)==null?void 0:n.parsedData)==null?void 0:a.streams)==null?void 0:c[0])==null?void 0:o.res_code)!==404)throw W.fromError(l,z.ERR_INNER,"subscribe stop failed")}})}updateStream(e,t=!1){return _(this,null,function*(){this.stream&&this.stream.videoTrack&&e.mediaStream&&t&&(yield new Promise(i=>{let n,a;if(e.mediaStream){a=document.createElement("video");const c=()=>{O.event(`[${this.logName}]`,"new mediaStream canplay"),a&&a.removeEventListener("canplaythrough",c,!1),a=void 0,clearTimeout(n),i(!0)};a.addEventListener("canplaythrough",c,!1),(a._playPromise||Promise.resolve()).then(()=>{a&&e.mediaStream&&(a.srcObject=e.mediaStream)})}else i(!0);n=window.setTimeout(()=>{O.event(`[${this.logName}]`,"new mediaStream timeout"),a=void 0,i(!0)},3e3)}),this.updateSubscribe(De.User)),this.stream=e,this.playAll(!1,t),!this.subscribed&&e&&(this.subscribed=!0),e.hasAudio&&this.isAudioSubscribing&&e.enableAudio(),e.hasVideo&&this.isVideoSubscribing&&e.enableVideo()})}updateScreenStream(e){this.screenStream=e,this.playAll(!0),!this.subscribed&&e&&(this.subscribed=!0),e.hasVideo&&this.isScreenSubscribing&&e.enableVideo()}clearStream(){var e;(e=this.stream)==null||e.stop(),this.stream=void 0}clearScreenStream(){var e;(e=this.screenStream)==null||e.stop(),this.screenStream=void 0}subscribeDataChannel(){if(this.dc)try{this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc=void 0}catch(e){}(this.streamInfo.hasAudio||this.streamInfo.hasVideo||this.streamInfo.hasScreen)&&(this.dataSubState.setState(ge.AliRtcStateSubscribing),this.rtsManager.subscribeAddDataChannel(this.streamUrl).then(e=>{if(e)return this.dataChannelConnected(e),this.dataSubState.setState(ge.AliRtcStateSubscribed),void this.streamInfo.updateRemoteTrackSubState({data:!0});throw new Error("no dc founded")}).catch(e=>{const t=W.fromError(e,z.ERR_INNER,"subscribe data failed");this.emit("remoteSubscribeError",t),this.dataSubState.setState(ge.AliRtcStateNoSubscribe)}))}subscribeDeleteDataChannel(){if(this.dc){try{this.rtsManager.subscribeDeleteDatachannel(this.streamUrl,this.dc)}catch(e){}this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dataSubState.setState(ge.AliRtcStateNoSubscribe),this.dc=void 0,this.streamInfo.updateRemoteTrackSubState({data:!1})}}getRetryOptions(){var i,n;const e={};this.wantSubAudio&&this.streamInfo.hasAudio&&(e.audio=!0,e.aMsid=((i=this.streamInfo.getAudioInfo())==null?void 0:i.msid)||L.Audio),this.wantSubVideo&&this.streamInfo.hasVideo&&(this.defaultVideoStreamType===it.AliRtcVideoStreamTypeLow&&this.streamInfo.hasVideoSmall?(e.video=!0,e.vMsid=L.VideoSmall):this.streamInfo.hasVideoLarge&&(e.video=!0,e.vMsid=((n=this.streamInfo.getVideoLargeInfo())==null?void 0:n.msid)||L.VideoLarge)),this.wantSubScreen&&this.streamInfo.hasScreen&&(e.screen=!0);let t={};if(e.audio||e.video)t={audio:e.audio,video:e.video},this.streamInfo.updateRemoteTrackSubState({screen:!1,data:!1});else{if(!e.screen)return;t={screen:e.screen},this.streamInfo.updateRemoteTrackSubState({data:!1})}return{remoteUser:this,options:t}}updateSubscribe(e){var a,c,o,l,d,h;const t=Date.now(),i={},n={};return this.wantSubAudio&&!this.isAudioSubscribing&&this.streamInfo.hasAudio&&this.audioSubState.currentState!==ge.AliRtcStateReconnecting?(i.audio=!0,i.aMsid=((a=this.streamInfo.getAudioInfo())==null?void 0:a.msid)||L.Audio):this.wantSubAudio&&this.streamInfo.hasAudio||!this.isAudioSubscribing||(n.audio=!0,n.aMsid=((c=this.streamInfo.getAudioInfo())==null?void 0:c.msid)||L.Audio),this.wantSubVideo&&this.streamInfo.hasVideo?(this.defaultVideoStreamType===it.AliRtcVideoStreamTypeLow&&!this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall&&this.videoSmallSubState.currentState!==ge.AliRtcStateReconnecting?(i.video=!0,i.vMsid=L.VideoSmall):this.isVideoLargeSubscribing||!this.streamInfo.hasVideoLarge||this.defaultVideoStreamType===it.AliRtcVideoStreamTypeLow&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall||this.videoLargeSubState.currentState===ge.AliRtcStateReconnecting||(i.video=!0,i.vMsid=((o=this.streamInfo.getVideoLargeInfo())==null?void 0:o.msid)||L.VideoLarge),this.defaultVideoStreamType===it.AliRtcVideoStreamTypeLow&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall?(n.video=!0,n.vMsid=L.VideoLarge):this.defaultVideoStreamType!==it.AliRtcVideoStreamTypeHigh&&this.streamInfo.hasVideoSmall||!this.isVideoLargeSubscribing||!this.isVideoSmallSubscribing||(n.video=!0,n.vMsid=L.VideoSmall)):this.wantSubVideo&&this.streamInfo.hasVideo||!this.isVideoSubscribing||(n.video=!0,n.vMsid=this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?L.VideoSmall:((l=this.streamInfo.getVideoLargeInfo())==null?void 0:l.msid)||L.VideoLarge),this.wantSubScreen&&!this.isScreenSubscribing&&this.streamInfo.hasScreen&&this.screenSubState.currentState!==ge.AliRtcStateReconnecting?i.screen=!0:this.wantSubScreen&&this.streamInfo.hasScreen||!this.isScreenSubscribing||(n.screen=!0),(d=this.parameter.data)!=null&&d.enableSubDataChannel&&!this.isDataSubscribing&&this.streamInfo.hasData&&this.dataSubState.currentState!==ge.AliRtcStateReconnecting?i.data=!0:(h=this.parameter.data)!=null&&h.enableSubDataChannel&&this.streamInfo.hasData||!this.isDataSubscribing||(n.data=!0),this.dc&&i.data&&this.subscribeDeleteDataChannel(),(i.audio||i.video||i.screen||i.data)&&(this.createCallId(),this.subscribe(i,e,t)),(n.audio||n.video||n.screen)&&this.subscribeDeleteTracks(n),{addOption:i,deleteOption:n}}handleAutoPlayFailed(){O.event(`[${this.logName}]`,"auto play failed"),this.emit("remoteAudioAutoPlayFail",this.uid);const e=()=>{this.resumeAudio().then(()=>{document.removeEventListener("click",e,!1),document.removeEventListener("touchstart",e,!1)})};document.addEventListener("click",e,!1),document.addEventListener("touchstart",e,!1)}handleVideoPlayFailded(e,t){this.emit("remoteVideoAutoPlayFail",this.uid,t);const i=()=>{var a;const n=(a=t===be.AliRtcVideoTrackScreen?this.screenStream:this.stream)==null?void 0:a.mediaStream;e.srcObject===n&&this.play(e,t===be.AliRtcVideoTrackScreen),document.removeEventListener("click",i,!1),document.removeEventListener("touchstart",i,!1)};document.addEventListener("click",i,!1),document.addEventListener("touchstart",i,!1)}playAudio(){return _(this,null,function*(){var e,t;if(this.audioTrack){if(this.toggleAudio(!this.audioMuted),this.audioElement||(O.event(`[${this.logName}]`,"create audio element"),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("autoplay","autoplay"),this.audioElement.addEventListener("pause",this.handleAudioPaused),this.setPlayoutVolume(this.playoutVolume)),((t=(e=this.audioElement.srcObject)==null?void 0:e.getAudioTracks())==null?void 0:t[0])!==this.audioTrack){let i=this.audioElement.srcObject;i?i.getAudioTracks().forEach(n=>{i.removeTrack(n)}):(i=new MediaStream,this.audioElement.srcObject=i),i.addTrack(this.audioTrack)}if(Pe.SystenUtil.isIos&&parseInt(Pe.SystenUtil.systemVersion)<=13){O.event(`[${this.logName}]`,"play audio for iOS 13-");const i=this.audioElement;i.setAttribute("autoplay","");const n=()=>{i.removeEventListener("playing",n),i.pause(),i.play().catch(()=>{this.handleAutoPlayFailed()})};this.audioElement.addEventListener("playing",n)}else(()=>{var i;O.event(`[${this.logName}]`,"try play audio"),(i=this.audioElement)==null||i.play().then(()=>{O.event(`[${this.logName}]`,"play audio success")}).catch(()=>{this.handleAutoPlayFailed()})})()}else O.event(`[${this.logName}]`,"audio track is null")})}stopPlayAudio(){this.audioElement&&(this.audioElement.pause(),this.audioElement.removeEventListener("pause",this.handleAudioPaused))}playAll(e=!1,t=!1){e?(this.viewMap.screenViews||[]).forEach(i=>{this.play(i,e,t)}):(this.viewMap.cameraViews||[]).forEach(i=>{this.play(i,e,t)})}play(e,t=!1,i=!1){const n=t?this.screenStream:this.stream;e&&n&&n.mediaStream&&Ml(e,n.mediaStream,i).catch(a=>{a.code!==20&&a.name!=="AbortError"&&this.handleVideoPlayFailded(e,t?be.AliRtcVideoTrackScreen:be.AliRtcVideoTrackCamera)})}stopPlayAll(e=!1){e?this.viewMap.screenViews.forEach(t=>{sr(t)}):this.viewMap.cameraViews.forEach(t=>{sr(t)})}toggleAudio(e=!0){this.audioSubState.setEnabled(e),this.audioElement&&(this.audioElement.muted=!e)}toggleVideo(e=!0){this.videoSubState.setEnabled(e),this.stream&&(e?this.stream.enableVideo():this.stream.disableVideo())}toggleScreen(e=!0){this.screenSubState.setEnabled(e),this.screenStream&&(e?this.screenStream.enableVideo():this.screenStream.disableVideo())}getStats(){return _(this,null,function*(){var i,n,a;const e=[];if(this.isAudioSubscribing){const c=yield this.rtsManager.getSubscribeAudioStats(this.streamUrl);c&&e.push({uid:this.uid,track:Or.AliRtcAudioTrackMic,stats:c})}const t=[];if(this.streamInfo.isVideoLargeSubscribed){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((i=this.streamInfo.getVideoLargeInfo())==null?void 0:i.msid)||L.VideoLarge);c&&t.push({uid:this.uid,track:be.AliRtcVideoTrackCamera,streamType:it.AliRtcVideoStreamTypeHigh,stats:c})}if(this.streamInfo.isVideoSmallSubscribed){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((n=this.streamInfo.getVideoSmallInfo())==null?void 0:n.msid)||L.VideoSmall);c&&t.push({uid:this.uid,track:be.AliRtcVideoTrackCamera,streamType:it.AliRtcVideoStreamTypeLow,stats:c})}if(this.isScreenSubscribing){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((a=this.streamInfo.getScreenInfo())==null?void 0:a.msid)||L.Screen);c&&t.push({uid:this.uid,track:be.AliRtcVideoTrackScreen,stats:c})}return{audio:e,video:t}})}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.audioTrack&&this.audioLevelMonitor.start(this.audioTrack,e),this.audioVolumeIndicationInterval=e)}reportSubscribeMonitor(e){e&&(this.slsReporter.reportSubscribeMonitor(this.callId,this.remoteCallId,this.traceId,e,this.monitorDataCache[e]),this.monitorDataCache[e]=[])}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>_(this,null,function*(){try{if(this.streamInfo.subscribingInfos.length===0)return void this.stopStreamMonitor();let e=Object.keys(this.monitorDataCache).filter(t=>{var i;return((i=this.monitorDataCache[t])==null?void 0:i.length)>0});this.streamInfo.subscribingInfos.forEach(t=>{const i=t.msid;if(!i)return;let n;e.includes(i)&&(e=e.filter(c=>c!==i));const a=i===L.Audio;n=a?this.rtsManager.getSubscribeAudioStats(this.streamUrl):this.rtsManager.getSubscribeVideoStats(this.streamUrl,i),n.then(c=>{var h;if(!c.timestamp)return;this.monitorDataCache[i]||(this.monitorDataCache[i]=[]);const o=this.monitorDataCache[i];let l;if((o==null?void 0:o.length)>0){const u=o[o.length-1]||{},d=u,{_last:p}=d;l=jt(d,["_last"])}(o==null?void 0:o.length)>=30&&this.reportSubscribeMonitor(i),c._last=l,c._codec=t.codec,a&&(c._source=(h=this.localUser)==null?void 0:h.getMediaStats(c.playoutId)),this.monitorDataCache[i].push(c)})}),e.forEach(t=>{this.reportSubscribeMonitor(t)})}catch(e){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportSubscribeMonitor(e)})}markReconnect(e){const t=[];!this.isAudioSubscribing||e&&!e.includes(this.streamInfo.getAudioInfo().msid)||t.push(this.audioSubState),this.isVideoSubscribing&&(!e||e.includes(this.streamInfo.getVideoLargeInfo().msid)||e.includes(this.streamInfo.getVideoSmallInfo().msid))&&t.push(this.videoSubState),!this.isScreenSubscribing||e&&!e.includes(this.streamInfo.getScreenInfo().msid)||t.push(this.screenSubState),!this.isDataSubscribing||e&&!e.includes(L.Data)||t.push(this.dataSubState),t.forEach(i=>{i.setState(ge.AliRtcStateReconnecting)})}markReconnected(e){const t=[],i=this.streamInfo.getAudioInfo().msid||L.Audio;if(this.isAudioSubscribing&&(!e||e.includes(i))){t.push(this.audioSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,aMsid:i});o&&o.audioTrack&&(this.audioTrack=o.audioTrack,this.audioVolumeIndicationInterval>0&&(this.audioLevelMonitor.stop(),this.audioLevelMonitor.start(this.audioTrack,this.audioVolumeIndicationInterval)),this.playAudio())}const n=this.streamInfo.getVideoLargeInfo().msid||L.VideoLarge,a=this.streamInfo.getVideoSmallInfo().msid||L.VideoSmall;if(this.isVideoSubscribing&&(!e||e.includes(n)||e.includes(a))){t.push(this.videoSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?a:n});o&&o.mediaStream&&(this.stream=o,this.playAll(!1))}const c=this.streamInfo.getScreenInfo().msid||L.Screen;if(this.isScreenSubscribing&&(!e||e.includes(c))){t.push(this.screenSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:c});o&&o.mediaStream&&(this.screenStream=o,this.playAll(!0))}if(this.isDataSubscribing&&(!e||e.includes(this.streamInfo.getDataInfo().msid))){t.push(this.dataSubState);const o=this.rtsManager.getDatachannelByMsid({url:this.streamUrl,msid:this.streamInfo.getDataInfo().msid||L.Data});this.dataChannelConnected(o)}t.forEach(o=>{o.setState(ge.AliRtcStateSubscribed)}),e||this.updateSubscribe(De.Reconnect)}},b(jr,"logName","RemoteUser"),jr);st([k()],et.prototype,"clear",1),st([k()],et.prototype,"updateRemoteUserDeviceStatus",1),st([k()],et.prototype,"updateRemoteTracks",1),st([k(J)],et.prototype,"subscribe",1),st([k()],et.prototype,"subscribeProxy",1),st([k(J)],et.prototype,"subscribeDeleteProxy",1),st([k()],et.prototype,"restore",1),st([k(J)],et.prototype,"resumeAudio",1),st([k(J)],et.prototype,"stopSubscribe",1),st([k(J)],et.prototype,"subscribeDeleteAllTracks",1),st([k()],et.prototype,"clearStream",1),st([k()],et.prototype,"clearScreenStream",1),st([k()],et.prototype,"updateSubscribe",1),st([k()],et.prototype,"playAudio",1),st([k()],et.prototype,"stopPlayAudio",1),st([k((s,r,e)=>[typeof s=="string"?s:s==null?void 0:s.nodeType,r||"-",e||"-"])],et.prototype,"play",1),st([k()],et.prototype,"stopPlayAll",1),st([k(J)],et.prototype,"markReconnect",1),st([k(J)],et.prototype,"markReconnected",1);let hm=et;var vr=(s=>(s[s.AliRtcPluginErrorCodeSuccess=0]="AliRtcPluginErrorCodeSuccess",s[s.AliRtcPluginErrorCodeFailed=-1]="AliRtcPluginErrorCodeFailed",s[s.AliRtcPluginErrorNoFindPlugin=-2]="AliRtcPluginErrorNoFindPlugin",s[s.AliRtcPluginErrorParameterError=-3]="AliRtcPluginErrorParameterError",s[s.AliRtcPluginErrorLoadError=-4]="AliRtcPluginErrorLoadError",s[s.AliRtcPluginErrorCreateError=-5]="AliRtcPluginErrorCreateError",s[s.AliRtcPluginErrorInitError=-6]="AliRtcPluginErrorInitError",s[s.AliRtcPluginErrorInitTokenError=-7]="AliRtcPluginErrorInitTokenError",s))(vr||{});class um extends de{constructor(){super(...arguments);b(this,"plugins",new Map)}add(e,t){if(this.plugins.has(e.name))throw new W(vr.AliRtcPluginErrorCreateError,`Plugin ${e.name} already exists`);this.plugins.set(e.name,e),t&&e.setOptions(t),this.emit("added",e),e.on("enabled",()=>this.emit("added",e)),e.on("disabled",()=>this.emit("removed",e)),e.on("updated",()=>this.emit("updated",e))}remove(e){const t=this.plugins.get(e);if(!t)throw new W(vr.AliRtcPluginErrorNoFindPlugin,`Plugin ${e} not founded`);this.plugins.delete(e),t.removeAllListeners(),this.emit("removed",t)}removeAll(){this.plugins.forEach(e=>{this.remove(e.name)})}get(e){return this.plugins.get(e)}has(e){return!!this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}}var pm=Object.defineProperty,mm=Object.getOwnPropertyDescriptor,nt=(s,r,e,t)=>{for(var i,n=t>1?void 0:t?mm(r,e):r,a=s.length-1;a>=0;a--)(i=s[a])&&(n=(t?i(r,e,n):i(n))||n);return t&&n&&pm(r,e,n),n};const bs=([s])=>{const{remoteUser:r,options:e}=s;return[`user(${r.userId})`,e]},tt=(Ee=class extends de{constructor(e,t,i){super();b(this,"rts");b(this,"encodedInsertableStreams",!0);b(this,"audioRedEnabled",!1);b(this,"audioCodecPreferences");b(this,"localStreamManager");b(this,"slsReporter");b(this,"_rtsPeerConnectionType","publish");b(this,"connecting",!1);b(this,"connected",!1);b(this,"rtsDisconnected",!1);b(this,"_pcTraceId","");b(this,"_localJoinTime",0);b(this,"connectionResolve");b(this,"connectingPromise");b(this,"dcResolve");b(this,"dcReject");b(this,"dcConnectingPromise");b(this,"_publishingTracks",[]);b(this,"parameter",{});b(this,"preferredPubL1Ip");b(this,"preferredSubL1Ip");b(this,"onePcManager");b(this,"httpPublishUrlMap",{});b(this,"httpSubscribeUrlMap",{});b(this,"traceIdMap",{});this.localStreamManager=e,this.slsReporter=t,this.parameter=i,this.rts=this.createRtsInstance(),this.addRTSListener()}createRtsInstance(){var e,t;return Pe.createClient({singlePcConfig:{usePcReconnect:!0},datachannelDelayOpen:!1,signalDatachannelInitOptions:(t=(e=this.parameter)==null?void 0:e.net)!=null&&t.datachannelInitOptions?this.parameter.net.datachannelInitOptions:void 0})}addRTSListener(){this.rts.on("connectStatusChange",e=>{var t,i,n,a;if(O.event(`[${Ee.logName}]`,"rts connectStatusChange to:",e.status),e.status===ct.CONNECT_STATUS_DISCONNECTED)this.dcReject&&this.dcReject(),this.setConnected(!1),this.rtsDisconnected=!0,this.slsReporter.reportWarning("rts disconnected"),this.emit("disconnected");else if(e.status===ct.CONNECT_STATUS_CONNECTED){if(this.rtsDisconnected){const c=(a=(n=(i=(t=this.rts.commonController)==null?void 0:t.peerCore)==null?void 0:i.getSignal())==null?void 0:n.getDatachannelCore())==null?void 0:a.readyState;O.event(`[${Ee.logName}]`,"dcReadyState:",c),c==="open"&&this.dcResolve&&this.dcResolve(!0)}this.rtsDisconnected=!1,this.setConnected(!0)}}),this.rts.on("reconnect",e=>{var t,i,n;O.debug(`[${Ee.logName}]`,"reconnect",e),this.emit("reconnect",e.type,(t=e.extraInfo)==null?void 0:t.url,(n=(i=e.extraInfo)==null?void 0:i.msids)==null?void 0:n.map(a=>a.name))}),this.rts.on("reconnectFinish",e=>{var t;O.debug(`[${Ee.logName}]`,"reconnectFinish",e),this.emit("reconnectFinish",(e==null?void 0:e.type)||"pc",e==null?void 0:e.latestUrl,(t=e==null?void 0:e.msids)==null?void 0:t.map(i=>i.name));try{this.emit("connected",!0,this._rtsPeerConnectionType)}catch(i){O.error(`[${Ee.logName}]`,"emit connected error:",i)}}),this.rts.on("datachannelStatusChange",e=>{O.event(`[${Ee.logName}]`,"rts datachannelStatusChange to:",e.status),e.status===yt.DATACHANNEL_STATUS_OPEN?this.dcResolve&&this.dcResolve(!0):e.status===yt.DATACHANNEL_STATUS_CLOSE&&(this.dcReject&&this.dcReject(),this.dcConnectingPromise=new Promise((t,i)=>{this.dcResolve=t,this.dcReject=i}))}),this.rts.on("receivedSEI",e=>{var t;if(this.emit("seimessage",e.url,e.sei.payloadType,e.sei.data),e.sei.payloadType===99)try{const i=JSON.parse(new TextDecoder().decode(e.sei.data));this.slsReporter.reportLoopAudioDelay(((t=this.publishingTracks.find(n=>n.type==="audio"))==null?void 0:t.ssrc)||"",i)}catch(i){}}),this.rts.on("onError",e=>{O.event(`[${Ee.logName}]`,"rts onError event:",e)}),this.rts.on("reconnect",e=>{O.event(`[${Ee.logName}]`,"rts reconnect event:",e)}),this.rts.on("traceId",({url:e,traceId:t})=>{e&&t&&this.traceIdMap[e]!==t&&(this.traceIdMap[e]=t,this.emit("traceIdUpdated",e,t))}),this.rts.on("signalSent",e=>{O.event(`[${Ee.logName}]`,"rts signalSent event:",e)}),this.rts.on("signalReceived",e=>{O.event(`[${Ee.logName}]`,"rts signalReceived event:",e)}),this.rts.on("hebtSent",e=>{var t,i,n;(n=(i=(t=this.parameter)==null?void 0:t.net)==null?void 0:i.heartbeat)!=null&&n.enableLog&&O.event(`[${Ee.logName}]`,"rts hebtSent event:",e)}),this.rts.on("hebtReceived",e=>{var t,i,n;(n=(i=(t=this.parameter)==null?void 0:t.net)==null?void 0:i.heartbeat)!=null&&n.enableLog&&O.event(`[${Ee.logName}]`,"rts hebtReceived event:",e)})}updateAuth(e){this.rts.updateAuth(e)}get pcTraceId(){return this._pcTraceId}set localJoinTime(e){this._localJoinTime=e}setEncodedInsertableStreams(e){this.encodedInsertableStreams=e}setReceiverPreferredVideoCodecH265(){var n;let e=(n=RTCRtpReceiver.getCapabilities("video"))==null?void 0:n.codecs;if(!e||e.length===0)return;const t=e.filter(a=>a.mimeType.toLowerCase()!=="video/rtx");let i=t.findIndex(a=>a.mimeType==="video/H265");if(i+1){let a=t[i];t.splice(i,1),t.unshift(a),this.rts.setReceiverCodecPreferences({video:t})}}setSenderPreferredVideoCodecH265(){var n;let e=(n=RTCRtpSender.getCapabilities("video"))==null?void 0:n.codecs;if(!e||e.length===0)return;const t=e.filter(a=>a.mimeType.toLowerCase()!=="video/rtx");let i=t.findIndex(a=>a.mimeType==="video/H265");if(i+1){let a=t[i];t.splice(i,1),t.unshift(a),this.rts.setSenderCodecPreferences({video:t})}}supportVideoCodec(e){var t,i,n;return e===Bt.H265?(t=RTCRtpSender.getCapabilities("video"))==null?void 0:t.codecs.some(a=>a.mimeType==="video/H265"):e===Bt.H264?(i=RTCRtpSender.getCapabilities("video"))==null?void 0:i.codecs.some(a=>a.mimeType==="video/H264"):e===Bt.AV1&&((n=RTCRtpSender.getCapabilities("video"))==null?void 0:n.codecs.some(a=>a.mimeType==="video/AV1"))}changeVideoCodec(e){this.supportVideoCodec(e)?(O.info(`[${Ee.logName}]`,"changeVideoCodec to:",e),Bt.H265===e&&(this.setSenderPreferredVideoCodecH265(),this.setReceiverPreferredVideoCodecH265())):O.warn(`[${Ee.logName}]`,`not support video codec: ${e}`)}setAudioRedEnabled(e){var t;if(e!==this.audioRedEnabled){try{const i=[...((t=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:t.codecs)||[]];if(i.length>0){if(e){const n=i.findIndex(c=>c.mimeType==="audio/red"),a=i.findIndex(c=>c.mimeType==="audio/opus");if(n>-1&&a>-1&&n>a){const c=i[a];i[a]=i[n],i[n]=c}}this.rts.setSenderCodecPreferences({audio:i}),this.rts.setReceiverCodecPreferences({audio:i}),this.audioCodecPreferences=i}}catch(i){}this.audioRedEnabled=e}}clear(){this.setConnected(!1),this.rtsDisconnected=!1,this._publishingTracks=[];try{this.rts.removeAllListeners(),this.rts.unpublish(),this.rts.unsubscribe()}catch(e){}this.rts=this.createRtsInstance(),this.addRTSListener()}startConnect(){this.connecting=!0,this.connectingPromise=new Promise(e=>{this.connectionResolve=e}),this.dcConnectingPromise=new Promise((e,t)=>{this.dcResolve=e,this.dcReject=t})}setConnected(e){var t;this.connected=e,this.connecting=!1,(t=this.connectionResolve)==null||t.call(this,!0)}get isConnecting(){return this.connecting}get isConnected(){return this.connected}get publishingTracks(){return this._publishingTracks}getPubMsid(e,t){const{aMsid:i,vMsid:n}=t!=null?t:{},a={};return e.hasAudio&&(a.aMsid=[i!=null?i:L.Audio]),e.hasScreen&&(a.vMsid=[L.Screen]),e.hasVideo&&(a.vMsid=[n!=null?n:t!=null&&t.isScreen?L.Screen:L.VideoLarge]),a}updatePublishingTracks(e){e&&(this._publishingTracks=e.map(({msid:t,from:i,ssrc:n,codec:a,type:c,trackId:o})=>({msid:t,from:i,type:c,ssrc:`${n}`,codec:a!=null?a:"",trackId:o})))}httpPublish(n){return _(this,arguments,function*(e,t=!1,i=Xt.MANUAL){let a;const c=Date.now(),o=e.url,l=e.callId;this.startConnect();const{publishStream:d,videoSmallStream:h,screenStream:u,vMsid:p}=yield this.localStreamManager.createHTTPPublishStream();if(!d)return O.warn(`[${Ee.logName}]`,"publishStream is null"),{traceId:"",l1ip:a};const f=this.getPubMsid(d,{vMsid:p});f.answerSdpHook=T=>{const R=/\d+\.\d+\.\d+\.\d+(?=\s+1106|\s+8000)/.exec(T);return R!=null&&R[0]&&(a=R[0]),T},this.handleHTTPConfig(f),this._rtsPeerConnectionType="publish";let m=!d.hasVideo,g=p,S="";const v=Date.now();try{const T=zd(o,this.preferredPubL1Ip);this.httpPublishUrlMap[o]=T,S=yield this.rts.publish(T,d,f)}catch(T){this.setConnected(!1);const R=2e3-(Date.now()-v);throw R<=0?this.emit("disconnected"):setTimeout(()=>{this.emit("disconnected")},R),this.slsReporter.reportPublish(t,o,l,d.hasVideo&&(!p||p===L.VideoLarge),d.hasVideo&&p===L.VideoSmall,d.hasVideo&&p===L.Screen,d.hasAudio,(T==null?void 0:T.errorCode)||-1,this.pcTraceId,"",v,v),W.fromRtsError(T)}S&&(this._pcTraceId=S),O.event(`[${Ee.logName}]`,"rts publish success",S);const E=Date.now();setTimeout(()=>{this.slsReporter.reportPublish(t,o,l,d.hasVideo&&(!p||p===L.VideoLarge),d.hasVideo&&p===L.VideoSmall,d.hasVideo&&p===L.Screen,d.hasAudio,0,this.pcTraceId,e.traceId,v,E)},6e3),this.slsReporter.reportConnectionLatencyEvent(Ot.HANDLE_PUB_TASK,Ut.START,l,S,c),this.slsReporter.reportConnectionLatencyEvent(Ot.HANDLE_PUB_TASK,Ut.END,l,S,Date.now());try{const T=Date.now();return this._pcTraceId=S,this.setConnected(!0),this._publishingTracks=this.rts.getPublishTrackInfoList(),h&&(yield this.publishAdd(e,h,{vMsid:L.VideoSmall},t),m=!1,g=L.VideoSmall),u&&(yield this.publishAdd(e,u,{vMsid:L.Screen},t),m=!1,g=L.Screen),yield this.waitPublishSender(o,m,g),this.slsReporter.reportPublishFirstPacket(t,l,v,T,this._localJoinTime,m?L.Audio:f.vMsid,S||"",S||"",i),{traceId:S,l1ip:a}}catch(T){throw this.setConnected(!1),W.fromError(T)}})}waitPublishSender(e,t=!1,i){return _(this,null,function*(){return Promise.race([lr(1e3),((n,a)=>{let c=0;const o=()=>(t?this.rts.getPublishAudioStats(e,i):this.rts.getPublishVideoStats(e,i)).then(l=>!(l.bytesSent>0)&&c<n?(c++,new Promise(d=>setTimeout(()=>d(o()),a))):Promise.resolve());return o()})(5,100)]).catch(()=>{})})}getPublishVideoStats(e,t){return _(this,null,function*(){return yield this.rts.getPublishVideoStats(e,t)})}getPublishAudioStats(e,t){return _(this,null,function*(){return yield this.rts.getPublishAudioStats(e,t)})}publishAdd(o,l,d){return _(this,arguments,function*(e,t,i,n=!1,a=!1,c=Xt.MANUAL){var m,g,S,v;const h=e.url,u=e.callId;yield this.dcConnectingPromise;const p=Date.now(),f=this.getPubMsid(t,i);try{const E=yield Gd(T=>_(this,null,function*(){var R,y,C,w,A,P;if(T>0&&O.event(`[${Ee.logName}]`,`publishAdd retry times: ${T}`),!this.isConnected)return Promise.reject(new W(z.ERR_INNER,"rts not connected"));if(yield this.dcConnectingPromise,this.onePcManager){if(this.onePcManager.willPrePub()&&(O.info(`[${Ee.logName}]`,"pub add waiting for prePub"),yield Promise.race([lr(500),new Promise(M=>{const I=()=>{M(void 0),this.rts.off("prePub",I)};this.rts.on("prePub",I)})])),this.onePcManager.prePubPromise){const{aMsid:M,vMsid:I}=this.onePcManager.prePubSdpInfo;if(M===((R=f.aMsid)==null?void 0:R[0])&&I===((y=f.vMsid)==null?void 0:y[0]))return this.onePcManager.prePubPromise}if(this.onePcManager.prePubSdpInfo&&this.onePcManager.prePubSdpInfo.aMsid===((C=f.aMsid)==null?void 0:C[0])&&this.onePcManager.prePubSdpInfo.vMsid===((w=f.vMsid)==null?void 0:w[0])){const M={video:this.onePcManager.prePubSdpInfo.vSsrcs,audio:this.onePcManager.prePubSdpInfo.aSsrcs};return this.onePcManager.pubAddedMark=`${(A=f.aMsid)==null?void 0:A[0]}-${(P=f.vMsid)==null?void 0:P[0]}`,this.rts.publishAdd([D({url:h,stream:t,updateSourceStream:!1},f)],void 0,M)}}return this.rts.publishAdd([D({url:h,stream:t,updateSourceStream:!1},f)])}),10,100,T=>{var R,y,C,w;return(T==null?void 0:T.errorCode)===15006||((w=(C=(y=(R=T==null?void 0:T.extraInfo)==null?void 0:R.parsedData)==null?void 0:y.streams)==null?void 0:C[0])==null?void 0:w.res_code)===131});if(E){const T=Date.now(),[R]=E,y=Date.now();return setTimeout(()=>{var C,w,A,P;this.slsReporter.reportPublish(!1,h,u,((C=f.vMsid)==null?void 0:C[0])===L.VideoLarge,((w=f.vMsid)==null?void 0:w[0])===L.VideoSmall,((A=f.vMsid)==null?void 0:A[0])===L.Screen,((P=f.aMsid)==null?void 0:P[0])===L.Audio,0,this.pcTraceId,R.traceId||"",p,y)},6e3),R.traceId&&(this._pcTraceId=R.traceId),this.updatePublishingTracks(R.trackInfoList),a&&(yield this.waitPublishSender(h,!t.hasVideo,t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)),this.slsReporter.reportPublishFirstPacket(n,u,p,T,this._localJoinTime,(t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)||"",this.pcTraceId,R.traceId||"",c),R.traceId||""}}catch(E){throw this.slsReporter.reportPublish(!1,h,u,((m=f.vMsid)==null?void 0:m[0])===L.VideoLarge,((g=f.vMsid)==null?void 0:g[0])===L.VideoSmall,((S=f.vMsid)==null?void 0:S[0])===L.Screen,((v=f.aMsid)==null?void 0:v[0])===L.Audio,(E==null?void 0:E.errorCode)||-1,this.pcTraceId,"",p),E!=null&&E.errorCode?W.fromRtsError(E):W.fromError(E)}return""})}publishDelete(e,t){return _(this,null,function*(){var l,d,h,u,p,f,m,g;yield this.dcConnectingPromise;const i=(d=(l=this.publishingTracks)==null?void 0:l.find(({msid:S})=>S===L.Audio))==null?void 0:d.msid,n=(u=(h=this.publishingTracks)==null?void 0:h.find(({msid:S})=>S===L.VideoLarge))==null?void 0:u.msid,a=(f=(p=this.publishingTracks)==null?void 0:p.find(({msid:S})=>S===L.Screen))==null?void 0:f.msid,c=[];t.screen&&a?c.push(a):t.video&&c.push(t.vMsid||n);const o=[];if(t.audio&&i&&o.push(i),this.onePcManager&&this.onePcManager.prePubSdpInfo){const{vMsid:S,aMsid:v}=this.onePcManager.prePubSdpInfo;S&&c.includes(S)&&(this.onePcManager.prePubSdpInfo.vSsrcs=void 0),v&&o.includes(v)&&(this.onePcManager.prePubSdpInfo.aSsrcs=void 0)}O.event(Ee.logName,"publishDelete",{streamUrl:e,aMsid:o,vMsid:c});try{const[S]=(yield this.rts.publishDeleteTracks([{url:e,aMsid:o,vMsid:c}]))||[];return O.event(Ee.logName,"publishDelete",{result:S}),S&&this.updatePublishingTracks(S.trackInfoList),((g=(m=S==null?void 0:S.trackInfoList)==null?void 0:m[0])==null?void 0:g.trackId)||""}catch(S){throw W.fromRtsError(S)}})}publishReplace(e,t,i){return _(this,null,function*(){var c,o;yield this.dcConnectingPromise;const{vMsid:n,aMsid:a}=i!=null?i:{};try{const l=yield this.rts.publishReplaceTracks([{url:e,stream:t,vMsid:n,aMsid:a}]),[d]=l;return this.updatePublishingTracks(d.trackInfoList),((o=(c=d==null?void 0:d.trackInfoList)==null?void 0:c[0])==null?void 0:o.trackId)||""}catch(l){throw W.fromRtsError(l)}})}publishStop(e){return _(this,null,function*(){return yield this.rts.publishStop([{url:e}]),this._publishingTracks=[],""})}publishAddDataChannel(e){return _(this,null,function*(){yield this.dcConnectingPromise;const t=this.httpPublishUrlMap[e]||e,i=yield this.rts.publishAddDatachannel({signalUrl:e,url:t,label:L.Data,msid:L.Data}),n=i==null?void 0:i.datachannel;if(n&&n.send){const a=new ArrayBuffer(4);new DataView(a).setUint8(0,240),n.datachannel.send(a)}return n})}publishStopDataChannel(e,t){return _(this,null,function*(){return yield this.rts.publishStopDatachannel({url:e,datachannel:t})})}unpublish(){return _(this,null,function*(){yield this.rts.unpublish(),this._publishingTracks=[],this.connecting=!1,this.connected=!1})}getSubConfig(e,t){let i=t!=null?t:{};t||(i={audio:!0,video:!0,screen:!0});const n={};return i.audio&&(n.aMsid=[(e==null?void 0:e.getAudioInfo().msid)||L.Audio]),i.video?i.vMsid?n.vMsid=[i.vMsid]:n.vMsid=e!=null&&e.hasVideoLarge?[(e==null?void 0:e.getVideoLargeInfo().msid)||L.VideoLarge]:e!=null&&e.hasVideoSmall?[(e==null?void 0:e.getVideoSmallInfo().msid)||L.VideoSmall]:[L.VideoLarge]:i.screen&&(n.vMsid=[(e==null?void 0:e.getScreenInfo().msid)||L.Screen]),n}handleHTTPConfig(e){var t,i,n,a,c,o,l,d,h,u,p,f;if(this.encodedInsertableStreams&&(e.encodedInsertableStreams=!0),(i=(t=this.parameter)==null?void 0:t.net)!=null&&i.useTCP&&(e.tcpOnly=!0),(a=(n=this.parameter)==null?void 0:n.net)!=null&&a.cumuDelay&&(e.cumuDelay=!0),(o=(c=this.parameter)==null?void 0:c.net)!=null&&o.disableHeartbeat&&(e.disableHeartbeat=!0),(d=(l=this.parameter)==null?void 0:l.net)!=null&&d.heartbeat&&(e.heartbeat=this.parameter.net.heartbeat),(u=(h=this.parameter)==null?void 0:h.net)==null?void 0:u.mediaTimeout){const m=(f=(p=this.parameter)==null?void 0:p.net)==null?void 0:f.mediaTimeout;m>1e3&&m<1e5&&(e.mediaTimeout=m)}e.retryTimes=17,e.retryInterval=5e3,O.info(`[${Ee.logName}]`,"http config",e)}httpSubscribe(e){return _(this,null,function*(){var c,o;const{remoteUser:t,options:i}=e;let n=t.streamUrl;i.video||i.screen?i!=null&&i.audio||(n+="@subaudio=no"):n+="@subvideo=no";const a=this.getSubConfig(t.streamInfo,i);this.handleHTTPConfig(a),this._rtsPeerConnectionType="subscribe",(o=(c=this.parameter)==null?void 0:c.net)!=null&&o.rrtr&&(a.offerSdpHook=En);try{this.startConnect();const l=zd(n,this.preferredSubL1Ip);this.httpSubscribeUrlMap[t.streamUrl]=l;const d=yield this.rts.subscribe(l,a);return this._pcTraceId=d.traceId,this.setConnected(!0),{traceId:d.traceId,stream:d}}catch(l){throw this.setConnected(!1),this.emit("disconnected"),W.fromRtsError(l)}})}subscribeAdd(e){return _(this,null,function*(){var a,c,o,l;const{remoteUser:t,options:i}=e,n=Q(D({url:t.streamUrl,subAudio:!!i.audio,subVideo:!(!i.screen&&!i.video)},this.getSubConfig(t.streamInfo,i)),{targetStream:i.screen?t.getScreenStream:t.getCameraStream});yield this.dcConnectingPromise;try{return(yield Gd(h=>_(this,null,function*(){var m;if(yield this.dcConnectingPromise,h>0&&O.event(`[${Ee.logName}]`,`subscribeAdd retry times: ${h}`),!this.isConnected)return Promise.reject();const u=(m=this.onePcManager)==null?void 0:m.preSubInfoMap[t.streamUrl],p=i.video?L.VideoLarge:void 0,f=i.audio?L.Audio:void 0;if(u&&u.vMsid===p&&u.aMsid===f&&u.subAddPromise)return u.subAddPromise;if(this.onePcManager){if(!t.streamInfo.hasMediaSubscribed&&this.onePcManager.willPreSubMsid(p)&&this.onePcManager.willPreSubMsid(f)){O.info(`[${Ee.logName}]`,`sub add user(${t.userId}) waiting for preSub`),yield Promise.race([lr(500),new Promise(S=>{const v=E=>{E.message.streams[0].method==="add"&&E.message.streams[0].url===t.streamUrl&&S(void 0),this.rts.off("preSub",v)};this.rts.on("preSub",v)})]);const g=this.onePcManager.preSubInfoMap[t.streamUrl];if(g&&g.vMsid===p&&g.aMsid===f&&g.subAddPromise)return O.info(`[${Ee.logName}]`,`sub add user(${t.userId}) waiting success`),g.subAddPromise;O.warn(`[${Ee.logName}]`,`sub add user(${t.userId}) waiting failed`)}this.onePcManager.subAddedMark[t.streamUrl]=`${i.aMsid}-${i.vMsid}`}return this.rts.subscribeAdd([n])}),10,100,h=>{var u,p,f,m,g,S,v,E;return(h==null?void 0:h.errorCode)===15006||((m=(f=(p=(u=h==null?void 0:h.extraInfo)==null?void 0:u.parsedData)==null?void 0:p.streams)==null?void 0:f[0])==null?void 0:m.res_code)===131||(h==null?void 0:h.errorCode)===15004&&((E=(v=(S=(g=h.extraInfo)==null?void 0:g.parsedData)==null?void 0:S.streams)==null?void 0:v[0])==null?void 0:E.res_code)===404}))[0]}catch(d){if(((l=(o=(c=(a=d==null?void 0:d.extraInfo)==null?void 0:a.parsedData)==null?void 0:c.streams)==null?void 0:o[0])==null?void 0:l.res_code)===508)return this.emit("subscribeexceeds"),null;throw W.fromRtsError(d)}})}subscribeDelete(e){return _(this,null,function*(){var c,o,l,d,h,u,p,f;const{remoteUser:t,options:i}=e,n=Q(D({url:t.streamUrl,subAudio:!!i.audio,subVideo:!(!i.screen&&!i.video)},this.getSubConfig(t.streamInfo,i)),{targetStream:i.screen?t.getScreenStream:t.getCameraStream});yield this.dcConnectingPromise;const a=(c=this.onePcManager)==null?void 0:c.preSubInfoMap[t.streamUrl];a&&(a.vMsid===((o=n.vMsid)==null?void 0:o[0])&&(a.vMsid=void 0),a.aMsid===((l=n.aMsid)==null?void 0:l[0])&&(a.aMsid=void 0),a.vMsid||a.aMsid||((d=this.onePcManager)==null||delete d.preSubInfoMap[t.streamUrl]));try{return O.event(`[${Ee.logName}]`,"subscribeDeleteTracks",JSON.stringify({url:n.url,subAudio:n.subAudio,subVideo:n.subVideo,aMsid:n.aMsid,vMsid:n.vMsid})),(yield this.rts.subscribeDeleteTracks([n]))[0]}catch(m){if(((f=(p=(u=(h=m==null?void 0:m.extraInfo)==null?void 0:h.parsedData)==null?void 0:u.streams)==null?void 0:p[0])==null?void 0:f.res_code)===404)return;throw W.fromRtsError(m)}})}subscribeAddDataChannel(e){return _(this,null,function*(){yield this.dcConnectingPromise;const t=this.httpSubscribeUrlMap[e]||e,i=yield this.rts.subscribeAddDatachannel({signalUrl:e,url:t,label:L.Data,msid:L.Data}),n=i==null?void 0:i.datachannel;if(n&&n.send){const a=new ArrayBuffer(4);new DataView(a).setUint8(0,240),n.send(a)}return n})}subscribeDeleteDatachannel(e,t){return _(this,null,function*(){let i;try{i=yield this.rts.subscribeDeleteDatachannel({url:e,msid:L.Data,datachannel:t})}catch(n){}return i})}publish(n){return _(this,arguments,function*(e,t=!1,i=Xt.MANUAL){var l,d;const a=e.url;let c,o="";if(this.connecting&&(yield this.connectingPromise),this.connected){yield this.dcConnectingPromise;const{publishStream:h,videoSmallStream:u,screenStream:p,vMsid:f}=yield this.localStreamManager.createHTTPPublishStream();if(!h)return O.warn(`[${Ee.logName}]`,"publishStream is null"),{traceId:"",l1ip:c};const m=this.getPubMsid(h,{vMsid:f});let g=!h.hasVideo,S=f;h&&(o=yield this.publishAdd(e,h,{vMsid:(l=m.vMsid)==null?void 0:l[0],aMsid:(d=m.aMsid)==null?void 0:d[0]},t),g=!0,S=L.Audio),u&&(yield lr(100),o=yield this.publishAdd(e,u,{vMsid:L.VideoSmall},t),g=!1,S=L.VideoSmall),p&&(yield lr(100),o=yield this.publishAdd(e,p,{isScreen:!0,vMsid:L.Screen},t),g=!1,S=L.Screen),S&&(yield this.waitPublishSender(a,g,S))}else{const h=yield this.httpPublish(e,t,i);o=h.traceId,c=h.l1ip}return{traceId:o,l1ip:c}})}reportSubscribeLatency(e,t,i,n){const a=[];e.audio&&a.push(e.aMsid||L.Audio),e.video?a.push(e.vMsid||L.VideoLarge):e.screen&&a.push(L.Screen),a.forEach(c=>{this.slsReporter.reportConnectionLatencyEvent(Ot.HANDLE_SUB_TASK,Ut.START,t,c,i,0,n),this.slsReporter.reportConnectionLatencyEvent(Ot.HANDLE_SUB_TASK,Ut.END,t,c,Date.now(),0,n)})}subscribe(e,t,i,n,a){return _(this,null,function*(){let c=!1;const{options:o,remoteUser:l}=e;if(o.video&&o.screen)throw new W(z.ERR_INNER,"subscribe error, video and screen cannot be subscribed at the same time");let d;this.connecting&&(yield this.connectingPromise);let h=Date.now();this.connected?d=yield this.subscribeAdd(e):(c=!0,d=yield this.httpSubscribe(e)),this.reportSubscribeLatency(o,i,h,c);const u=Date.now();let p=L.VideoLarge,f=o.video||o.screen,m=o.audio;o.video&&o.vMsid?p=o.vMsid:o.screen&&(p=L.Screen);let g=0,S=0,v=0;const E=((T,R)=>{let y=0;const C=()=>{let w;return m&&!g&&(w=this.rts.getSubscribeAudioStats(l.streamUrl).then(A=>{if(A.packetsReceived>0)g=Date.now(),O.debug(`[${Ee.logName}]`,l.userId,"Stats 音频首包");else if(!f)return y<T&&(y++,new Promise(P=>setTimeout(()=>P(C()),R)));return!0})),f&&!v&&(w=this.rts.getSubscribeVideoStats(l.streamUrl,p).then(A=>(!S&&A.packetsReceived>0&&(S=Date.now(),O.debug(`[${Ee.logName}]`,l.userId,"Stats 视频首包")),A.framesDecoded>0?(v=Date.now(),O.debug(`[${Ee.logName}]`,l.userId,"Stats 视频首帧数据"),!0):y<T?(y++,new Promise(P=>setTimeout(()=>P(C()),R))):(O.event(`[${Ee.logName}]`,l.userId,"尝试获取首帧数据失败"),!1)))),Promise.resolve(w)};return C()})(20,100);return E.then(()=>{S&&this.slsReporter.reportSubscribeFirstPacket(t===De.Resume,i,n,p,{fprt:S-h,ifsprtc:v?v-h:0,ajsub:t===De.Join?1:0,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",sstc:u-h}),v&&this.slsReporter.reportSubscribeFirstFrame(t===De.Resume,i,n,p,{fvfrt:v-h,fp2fftc:v-S,ajsub:t===De.Join?1:0,tffrtc:t===De.Join?v-this.localJoinTime:v-a,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",fvfdtc:v-h}),g&&(this.slsReporter.reportConnectionLatencyEvent(Ot.FIRST_REMOTE,Ut.DECODED,i,L.Audio,g),this.slsReporter.reportSubscribeFirstPacket(t===De.Resume,i,n,L.Audio,{fprt:g-h,ifsprtc:g-h,ajsub:t===De.Join?1:0,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",sstc:u-h}))}),d&&(d.isHTTP=c,d.statsCheckPromise=E),d})}getSubscribeVideoStats(e,t){return _(this,null,function*(){return yield this.rts.getSubscribeVideoStats(e,t)})}getSubscribeAudioStats(e,t){return _(this,null,function*(){return yield this.rts.getSubscribeAudioStats(e,t)})}getStreamByMsid(e){return this.rts.commonController.streamManager.getStreamByMsid(e)}getDatachannelByMsid(e){var t;return(t=this.rts.commonController.datachannelManager)==null?void 0:t.getByMsid(e)}getPCStats(){return _(this,null,function*(){var e,t;return(t=(e=this.rts.commonController.peerCore)==null?void 0:e.pc)==null?void 0:t.getStats()})}sendSEI(e,t,i,n){return _(this,null,function*(){return this.rts.sendSEI({url:e,vMsid:L.VideoLarge,data:t,repeatCount:i,payloadType:n})})}},b(Ee,"logName","RtsManager"),Ee);nt([k(J)],tt.prototype,"startConnect",1),nt([k()],tt.prototype,"updatePublishingTracks",1),nt([k(J,J)],tt.prototype,"httpPublish",1),nt([k(J,J)],tt.prototype,"waitPublishSender",1),nt([k(([s,r,e])=>[s,JSON.stringify(e)],J)],tt.prototype,"publishAdd",1),nt([k(J,J)],tt.prototype,"publishDelete",1),nt([k(([s,r,e])=>[s,JSON.stringify(e)])],tt.prototype,"publishReplace",1),nt([k(J)],tt.prototype,"publishStop",1),nt([k(J)],tt.prototype,"publishAddDataChannel",1),nt([k(J)],tt.prototype,"publishStopDataChannel",1),nt([k()],tt.prototype,"unpublish",1),nt([k(bs,({traceId:s})=>s)],tt.prototype,"httpSubscribe",1),nt([k(bs,({traceId:s})=>s)],tt.prototype,"subscribeAdd",1),nt([k(bs)],tt.prototype,"subscribeDelete",1),nt([k(J)],tt.prototype,"subscribeAddDataChannel",1),nt([k(J)],tt.prototype,"subscribeDeleteDatachannel",1),nt([k(J)],tt.prototype,"publish",1),nt([k(bs)],tt.prototype,"subscribe",1),nt([k()],tt.prototype,"sendSEI",1);let fm=tt;class Wn{constructor(r=Fn){b(this,"defaultProfile");b(this,"profile");b(this,"profileMap",new Map);b(this,"audioProfile");b(this,"contentHint");this.defaultProfile=D({},r)}updateProfile(r,e){this.profileMap.set(r,D(D(D({},this.defaultProfile),this.profileMap.get(r)||{}),e||{})),this.profile=r}get videoProfile(){return this.profile}updateAudioProfile(r){this.audioProfile=r}setContentHint(r,e){e&&(this.contentHint=e),this.contentHint&&r&&(r.contentHint=this.contentHint)}setVideoProfile(r,e,t=!1){return _(this,null,function*(){if(!this.profile)return;const i=this.profileMap.get(this.profile)||(e==null?void 0:e.VideoProfileMap.get(this.profile));if(i){if(!t&&r&&r.readyState==="live"&&r.applyConstraints)try{yield r.applyConstraints(i)}catch(n){}if(e){const n=D({},i);i.maxSendFrameRate&&(n.frameRate=i.maxSendFrameRate),e==null||e.VideoProfileMap.set(this.profile,n),yield e.setVideoProfile(this.profile)}}})}}var Xe=(s=>(s[s.AliRtcSdkStreamTypeCapture=0]="AliRtcSdkStreamTypeCapture",s[s.AliRtcSdkStreamTypeScreen=1]="AliRtcSdkStreamTypeScreen",s))(Xe||{});class jn extends de{constructor(e){super();b(this,"type");b(this,"originVideoTrack");b(this,"videoSource");b(this,"_videoMuted",!1);b(this,"originAudioTrack");b(this,"audioSource");b(this,"_audioMuted",!1);b(this,"_targetVideoTrack");b(this,"_targetDualVideoTrack");b(this,"_targetAudioTrack");b(this,"_publishVideoStream");b(this,"_publishDualVideoStream");b(this,"_publishAudioStream");b(this,"_previewStream");b(this,"plugins",[]);b(this,"_profileManager");b(this,"cameraVideoConstraints");b(this,"micAudioConstraints");b(this,"onVideoTrackEnded",()=>{this.emit("videotrackended")});b(this,"onAudioTrackEnded",()=>{this.emit("audiotrackended")});this.type=e}get profileManager(){return this._profileManager}get audioProfile(){var e;return(e=this.profileManager)==null?void 0:e.audioProfile}updateSource(e,t,i){return _(this,null,function*(){var c,o,l,d,h,u;const{videoTrack:n,audioTrack:a}=e;n&&((c=this.originVideoTrack)==null||c.removeEventListener("ended",this.onVideoTrackEnded)),a&&((o=this.originAudioTrack)==null||o.removeEventListener("ended",this.onAudioTrackEnded)),this.type===Xe.AliRtcSdkStreamTypeScreen?this.stop():(n&&((l=this.originVideoTrack)==null||l.stop()),a&&((d=this.originAudioTrack)==null||d.stop())),n&&(this.originVideoTrack=n,(h=this.originVideoTrack)==null||h.addEventListener("ended",this.onVideoTrackEnded),this.videoSource=t||Ci.Camera,this.updateVideoTrack(n)),a&&(this.originAudioTrack=a,(u=this.originAudioTrack)==null||u.addEventListener("ended",this.onAudioTrackEnded),this.audioSource=i||ms.Microphone,this.updateAudioTrack(a))})}get currentProfile(){var e;return(e=this.profileManager)==null?void 0:e.profile}get currentVideoTrack(){return this._targetVideoTrack}get currentDualVideoTrack(){return this._targetDualVideoTrack}get publishVideoStream(){return this._publishVideoStream}get publishDualVideoStream(){return this._publishDualVideoStream}get currentAudioTrack(){return this._targetAudioTrack}get publishAudioStream(){return this._publishAudioStream}get previewStream(){return this._previewStream}updateVideoTrack(e,t=!1){return _(this,null,function*(){(this._targetVideoTrack!==e||t)&&(this._targetVideoTrack=e)})}updateDualVideoTrack(e,t=!1){return _(this,null,function*(){(this._targetDualVideoTrack!==e||t)&&(this._targetDualVideoTrack=e)})}updateAudioTrack(e,t=!1){return _(this,null,function*(){(this._targetAudioTrack!==e||t)&&(this._targetAudioTrack=e)})}setAudioMuted(e){var t,i;this._audioMuted=e,e?(t=this.publishAudioStream)==null||t.disableAudio():(i=this.publishAudioStream)==null||i.enableAudio()}get isAudioMuted(){return this._audioMuted}setVideoMuted(e){var t,i;this._videoMuted=e,e?(t=this.publishVideoStream)==null||t.disableVideo():(i=this.publishVideoStream)==null||i.enableVideo()}get isVideoMuted(){return this._videoMuted}process(e){return _(this,null,function*(){var t,i,n,a,c,o,l,d,h,u,p,f;this._targetAudioTrack=this.originAudioTrack,this._targetVideoTrack=this.originVideoTrack;for(const m of this.plugins)try{yield m.execute(this,e)}catch(g){console.error(`error in plugin-${m.name}, error: ${g}`)}this._targetVideoTrack?((i=(t=this._publishVideoStream)==null?void 0:t.videoTrack)==null?void 0:i.id)!==this._targetVideoTrack.id&&(this._publishVideoStream=yield Ai(this._targetVideoTrack),this.setVideoMuted(this._videoMuted),(n=this.profileManager)==null||n.setVideoProfile(this.originVideoTrack,this._publishVideoStream,!0),(a=this.profileManager)==null||a.setContentHint(this._targetVideoTrack),this.previewStream?(c=this.previewStream)==null||c.mergeStream(this._publishVideoStream):this._previewStream=yield Ai(this._targetVideoTrack)):(this._publishVideoStream=void 0,(o=this.previewStream)==null||o.deleteTracks({video:!0})),this._targetDualVideoTrack?((d=(l=this._publishDualVideoStream)==null?void 0:l.videoTrack)==null?void 0:d.id)!==this._targetDualVideoTrack.id&&(this._publishDualVideoStream=yield Ai(this._targetDualVideoTrack),this._videoMuted?this._publishDualVideoStream.disableVideo():this._publishDualVideoStream.enableVideo()):this._publishDualVideoStream=void 0,this._targetAudioTrack?((u=(h=this._publishAudioStream)==null?void 0:h.audioTrack)==null?void 0:u.id)!==this._targetAudioTrack.id&&(this._publishAudioStream=yield Ai(this._targetAudioTrack),this.setAudioMuted(this._audioMuted),this.previewStream?(p=this.previewStream)==null||p.mergeStream(this._publishAudioStream):this._previewStream=yield Ai(this._targetAudioTrack)):(this._publishAudioStream=void 0,(f=this.previewStream)==null||f.deleteTracks({audio:!0}))})}stopVideo(){var e,t;this.originVideoTrack&&((e=this.originVideoTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originVideoTrack)==null||t.stop(),this.originVideoTrack=void 0),this.updateVideoTrack(void 0)}stopAudio(){var e,t;this.originAudioTrack&&((e=this.originAudioTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originAudioTrack)==null||t.stop(),this.originAudioTrack=void 0),this.updateAudioTrack(void 0)}stop(){this.stopVideo(),this.stopAudio()}updateVideoProfile(e,t,i=!1){return _(this,null,function*(){this._profileManager||(this._profileManager=new Wn(this.type===Xe.AliRtcSdkStreamTypeScreen?kl:Fn)),e&&this._profileManager.updateProfile(e,t),yield this._profileManager.setVideoProfile(this.originVideoTrack,this._publishVideoStream,i)})}get videoProfile(){var e;return(e=this.profileManager)==null?void 0:e.videoProfile}setVideoContentHint(e){this._profileManager||(this._profileManager=new Wn(this.type===Xe.AliRtcSdkStreamTypeScreen?kl:Fn)),this._profileManager.setContentHint(this.currentVideoTrack,e)}updateAudioProfile(e){return _(this,null,function*(){this._profileManager||(this._profileManager=new Wn),this._profileManager.updateAudioProfile(e)})}cloneVideoProfile(e){return _(this,null,function*(){var t;yield(t=this.profileManager)==null?void 0:t.setVideoProfile(void 0,e)})}addPlugin(e){const t=this.plugins.findIndex(i=>i.zIndex>e.zIndex);t>-1?this.plugins.splice(t,0,e):this.plugins.push(e)}removePlugin(e){const t=this.plugins.indexOf(e);return t>-1&&(e.clear(this),this.plugins.splice(t,1),!0)}}var gm=Object.defineProperty,Sm=Object.getOwnPropertyDescriptor,Zt=(s,r,e,t)=>{for(var i,n=t>1?void 0:t?Sm(r,e):r,a=s.length-1;a>=0;a--)(i=s[a])&&(n=(t?i(r,e,n):i(n))||n);return t&&n&&gm(r,e,n),n};const Ft=(Er=class extends de{constructor(e,t){super();b(this,"pluginManager");b(this,"slsReporter");b(this,"publishingCameraVideoStream");b(this,"publishingScreenVideoStream");b(this,"cameraStreamInfo",new jn(Xe.AliRtcSdkStreamTypeCapture));b(this,"screenStreamInfo",new jn(Xe.AliRtcSdkStreamTypeScreen));b(this,"streamInfos",[this.cameraStreamInfo,this.screenStreamInfo]);b(this,"_audioCaptureDisabled",!1);b(this,"_cameraCaptureDisabled",!1);b(this,"_publishLocalAudioStreamEnabled",!0);b(this,"_publishLocalVideoStreamEnabled",!0);b(this,"_publishLocalScreenStreamEnabled",!0);this.screenStreamInfo.setVideoContentHint("motion"),this.pluginManager=e,this.slsReporter=t,this.cameraStreamInfo.on("videotrackended",()=>_(this,null,function*(){yield this.stopLocalStream({video:!0}),this.emit("trackended",Br.VideoTrackEnded)})),this.cameraStreamInfo.on("audiotrackended",()=>_(this,null,function*(){yield this.stopLocalStream({audio:!0}),this.emit("trackended",Br.AudioTrackEnded)})),this.screenStreamInfo.on("videotrackended",()=>_(this,null,function*(){yield this.stopLocalStream({screen:!0}),this.emit("trackended",Br.ScreenTrackEnded)})),this.pluginManager.on("added",i=>_(this,null,function*(){if(O.info(`[${Er.logName}]`,"plugin added",i.name),!i.isSupported("7.3.0-beta.2"))return console.warn(`${i.name} is not supported!!!`),void i.emit("unsupported");try{yield i.init()}catch(n){i.emit("error",W.fromError(n,vr.AliRtcPluginErrorInitError))}i.streamType===Xe.AliRtcSdkStreamTypeCapture&&(this.cameraStreamInfo.addPlugin(i),yield this.cameraStreamInfo.process(this.streamInfos)),i.streamType===Xe.AliRtcSdkStreamTypeScreen&&(this.screenStreamInfo.addPlugin(i),yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("removed",i=>_(this,null,function*(){this.cameraStreamInfo.removePlugin(i)&&(yield this.cameraStreamInfo.process(this.streamInfos)),this.screenStreamInfo.removePlugin(i)&&(yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("updated",()=>_(this,null,function*(){yield this.updateStreams()}))}get hasCamera(){return!!this.cameraStreamInfo.originVideoTrack}get audioCaptureDisabled(){return this._audioCaptureDisabled}set audioCaptureDisabled(e){this._audioCaptureDisabled=e}get cameraCaptureDisabled(){return this._cameraCaptureDisabled}set cameraCaptureDisabled(e){this._cameraCaptureDisabled=e}setAudioMuted(e){this.cameraStreamInfo.setAudioMuted(e)}get isAudioMuted(){return this.cameraStreamInfo.isAudioMuted}setCameraMuted(e){this.cameraStreamInfo.setVideoMuted(e)}get isCameraMuted(){return this.cameraStreamInfo.isVideoMuted}setScreenMuted(e){this.screenStreamInfo.setVideoMuted(e)}get isScreenMuted(){return this.screenStreamInfo.isVideoMuted}get publishLocalAudioStreamEnabled(){return this._publishLocalAudioStreamEnabled}set publishLocalAudioStreamEnabled(e){this._publishLocalAudioStreamEnabled=e}get publishLocalVideoStreamEnabled(){return this._publishLocalVideoStreamEnabled}set publishLocalVideoStreamEnabled(e){this._publishLocalVideoStreamEnabled=e}get publishLocalScreenStreamEnabled(){return this._publishLocalScreenStreamEnabled}set publishLocalScreenStreamEnabled(e){this._publishLocalScreenStreamEnabled=e}updateStreams(){return _(this,null,function*(){yield this.cameraStreamInfo.process(this.streamInfos),yield this.screenStreamInfo.process(this.streamInfos),this.emit("publishupdate")})}setAvailableCameraDeviceId(){return _(this,null,function*(){var e,t,i,n;if((e=this.cameraStreamInfo.cameraVideoConstraints)!=null&&e.deviceId){let a=(t=this.cameraStreamInfo.cameraVideoConstraints)==null?void 0:t.deviceId;const c=yield Pe.getCameraList();c.find(o=>o.deviceId===a)||(a=(n=(i=c.find(o=>!!o.deviceId))==null?void 0:i.deviceId)!=null?n:""),this.cameraStreamInfo.cameraVideoConstraints.deviceId=a}})}setAvailableMicrophoneDeviceId(){return _(this,null,function*(){var e,t,i,n;if((e=this.cameraStreamInfo.micAudioConstraints)!=null&&e.deviceId){let a=(t=this.cameraStreamInfo.micAudioConstraints)==null?void 0:t.deviceId;const c=yield Pe.getMicList();c.find(o=>o.deviceId===a)||(a=(n=(i=c.find(o=>!!o.deviceId))==null?void 0:i.deviceId)!=null?n:""),this.cameraStreamInfo.micAudioConstraints.deviceId=a}})}createLocalStream(e){return _(this,null,function*(){var h;const{screen:t,mediaStream:i,videoProfile:n,screenProfile:a}=e;let{video:c,audio:o}=e;const l=(u=>{const{audio:p,video:f,screen:m}=u;if(f&&m)throw new W(z.ERR_INNER,"create stream error, cannot create video && screen together");return!!(f||p||m)})(e);let d;if(l){i||(c===!0&&this.cameraStreamInfo.cameraVideoConstraints?(yield this.setAvailableCameraDeviceId(),c=D({},this.cameraStreamInfo.cameraVideoConstraints)):typeof c=="object"&&(yield this.setAvailableCameraDeviceId(),c=D(D({},c),this.cameraStreamInfo.cameraVideoConstraints)),o===void 0&&this.audioCaptureDisabled?o=!1:o&&(o===!0&&this.cameraStreamInfo.micAudioConstraints?(yield this.setAvailableMicrophoneDeviceId(),o=D({},this.cameraStreamInfo.micAudioConstraints)):typeof o=="object"&&(yield this.setAvailableMicrophoneDeviceId(),o=D(D({},o),this.cameraStreamInfo.micAudioConstraints)),this._audioCaptureDisabled=!1));const u=Date.now();try{d=yield Pe.createStream({audio:o,video:c,screen:t,custom:!!i,mediaStream:i,skipProfile:!0}),O.info(`[${Er.logName}]`,"createLocalStream",{audio:o,video:c,screen:t,custom:!!i,time:Date.now()-u}),o&&!i&&this.slsReporter.reportAudio(null,Date.now()-u,((h=d==null?void 0:d.audioTrack)==null?void 0:h.label)||""),t&&!i&&this.slsReporter.reportScreen(null,Date.now()-u)}catch(p){throw o&&!i&&this.slsReporter.reportAudio(p,Date.now()-u,""),t&&!i&&this.slsReporter.reportScreen(null,Date.now()-u),p}if(t)yield this.screenStreamInfo.updateSource(d,Ci.Screen,ms.Screen),yield this.setScreenProfile(a||Dl),this.setScreenContentHint(),this.publishingScreenVideoStream=void 0;else if(yield this.cameraStreamInfo.updateSource(d,Ci.Camera,ms.Microphone),d.hasVideo&&(yield this.setVideoProfile(n||Pl),this.setVideoContentHint(),this.publishingCameraVideoStream=void 0),d.hasAudio&&typeof o=="boolean"){const p=this.cameraStreamInfo.audioProfile;p&&(yield d.setAudioProfile(p))}}return Pe.SystenUtil.isIos&&Pe.SystenUtil.compareVersion("15.1")&&!Pe.SystenUtil.compareVersion("15.2")&&(yield lr(1e3)),yield this.updateStreams(),d})}stopLocalStream(e){return _(this,null,function*(){const{screen:t,video:i,audio:n}=e!=null?e:{};let a=!1;i&&this.cameraStreamInfo.originVideoTrack&&(a=!0,this.cameraStreamInfo.stopVideo(),this.publishingCameraVideoStream=void 0),n&&this.cameraStreamInfo.originAudioTrack&&(a=!0,this.cameraStreamInfo.stopAudio()),t&&this.screenStreamInfo.originVideoTrack&&(a=!0,this.screenStreamInfo.stop(),this.publishingScreenVideoStream=void 0,this.slsReporter.reportScreenStop(null)),a&&(yield this.updateStreams())})}get publishStreams(){const{publishLocalVideoStreamEnabled:e,publishLocalAudioStreamEnabled:t,publishLocalScreenStreamEnabled:i}=this;return{video:e?this.cameraStreamInfo.publishVideoStream:void 0,videoSmall:e?this.cameraStreamInfo.publishDualVideoStream:void 0,audio:t?this.cameraStreamInfo.publishAudioStream:void 0,screen:i?this.screenStreamInfo.publishVideoStream:void 0}}createHTTPPublishStream(){return _(this,null,function*(){var o,l,d,h;let e,t,i,n,a=!1;const c=this.publishStreams;try{if(!(c.audio||c.video||c.videoSmall||c.screen))throw O.error(`[${Er.logName}]`,"no tracks founded"),new W(z.ERR_SDK_PUBLISH_INVAILD,"no tracks founded");const u=new MediaStream;(o=c.audio)!=null&&o.audioTrack&&u.addTrack(c.audio.audioTrack),(l=c.video)!=null&&l.videoTrack?(u.addTrack(c.video.videoTrack),i=c.videoSmall,n=c.screen):(d=c.screen)!=null&&d.videoTrack&&(t=L.Screen,u.addTrack((h=c.screen)==null?void 0:h.videoTrack),a=!0),e=yield Ol(u),a?(this.screenStreamInfo.cloneVideoProfile(e),this.publishingScreenVideoStream=e):(this.cameraStreamInfo.cloneVideoProfile(e),this.publishingCameraVideoStream=e)}catch(u){}return{publishStream:e,videoSmallStream:i,screenStream:n,vMsid:t}})}stop(){this.cameraStreamInfo.stop(),this.screenStreamInfo.stop(),this.updateStreams()}setVideoProfile(e,t,i=!1){return _(this,null,function*(){yield this.cameraStreamInfo.updateVideoProfile(e,t,i),this.publishingCameraVideoStream&&this.cameraStreamInfo.cloneVideoProfile(this.publishingCameraVideoStream)})}setVideoContentHint(e){this.cameraStreamInfo.setVideoContentHint(e)}setAudioProfile(e){return _(this,null,function*(){var t;yield this.cameraStreamInfo.updateAudioProfile(e),yield(t=this.publishingCameraVideoStream)==null?void 0:t.setAudioProfile(e)})}setScreenProfile(e,t){return _(this,null,function*(){yield this.screenStreamInfo.updateVideoProfile(e,t),this.publishingScreenVideoStream&&this.screenStreamInfo.cloneVideoProfile(this.publishingScreenVideoStream)})}setScreenContentHint(e){this.screenStreamInfo.setVideoContentHint(e)}setCameraVideoConstraints(e){var t;this.cameraStreamInfo.cameraVideoConstraints=D(D({},(t=this.cameraStreamInfo.cameraVideoConstraints)!=null?t:{}),e)}setMicAudioConstraints(e){var t;this.cameraStreamInfo.micAudioConstraints=D(D({},(t=this.cameraStreamInfo.micAudioConstraints)!=null?t:{}),e)}},b(Er,"logName","LocalStreamManager"),Er);Zt([k(([s])=>{const{audio:r,video:e,screen:t,custom:i,skipProfile:n,videoProfile:a,screenProfile:c}=s;return[{audio:r,video:e,screen:t,custom:i,skipProfile:n,videoProfile:a,screenProfile:c}]})],Ft.prototype,"createLocalStream",1),Zt([k(J)],Ft.prototype,"stopLocalStream",1),Zt([k()],Ft.prototype,"createHTTPPublishStream",1),Zt([k()],Ft.prototype,"stop",1),Zt([k(J)],Ft.prototype,"setVideoProfile",1),Zt([k(J)],Ft.prototype,"setVideoContentHint",1),Zt([k(J)],Ft.prototype,"setAudioProfile",1),Zt([k(J)],Ft.prototype,"setScreenProfile",1),Zt([k(J)],Ft.prototype,"setScreenContentHint",1),Zt([k(J)],Ft.prototype,"setCameraVideoConstraints",1),Zt([k(J)],Ft.prototype,"setMicAudioConstraints",1);let bm=Ft;const vm=s=>_(this,null,function*(){const r=new Pe.SupportUtil;window.isSecureContext||console.warn("WebRTC 需要 HTTPS 安全上下文,细节可参考:https://developer.mozilla.org/zh-CN/docs/Web/Security/Secure_Contexts");let e={support:!1,detail:{isWebRTCSupported:r.checkMediaDevices()&&r.checkWebRtcSupport(),isH264DecodeSupported:!1,isH264EncodeSupported:!1,isScreenShareSupported:!1,isSendMediaExtensionMsgSupported:!1,isBrowserSupported:!0}},t=!1;try{e.detail.isWebRTCSupported?(yield r.isSupport({isReceiveVideo:!0}),t=!0):console.warn("当前浏览器不支持 WebRTC")}catch(i){t=!1,e.detail.isBrowserSupported=r.checkBrowser({errorCode:0,message:""})}if(e.support=t,r.checkWebRtcSupport()&&s!=="sendonly"){const i=yield r.checkH264Decode();e.detail.isH264DecodeSupported=i,e.support=e.support&&i}if(r.checkWebRtcSupport()&&s!=="recvonly"){const i=yield r.checkH264Encode();e.detail.isH264EncodeSupported=i,e.support=e.support&&i}return e.detail.isScreenShareSupported=r.checkWebRtcSupport()&&r.checkScreenCapture()&&!Pe.SystenUtil.isAndroid&&!Pe.SystenUtil.isIos,e.detail.isSendMediaExtensionMsgSupported=r.checkWebRtcSupport()&&r.checkEncodedTransformSupport(),e});var Ll=(s=>(s[s.PRE_PROCESSOR=0]="PRE_PROCESSOR",s[s.POST_PROCESSOR=1]="POST_PROCESSOR",s))(Ll||{}),ii=(s=>(s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO",s[s.BOTH=2]="BOTH",s))(ii||{});class ur extends de{constructor(e,t=Xe.AliRtcSdkStreamTypeCapture,i=1){super();b(this,"name");b(this,"options");b(this,"type",0);b(this,"streamType");b(this,"trackType");b(this,"zIndex",1);b(this,"_isEnable",!0);b(this,"shouldCache",!0);b(this,"lastInputAudioTrack");b(this,"lastOutputAudioTrack");b(this,"lastInputVideoTrack");b(this,"lastOutputVideoTrack");b(this,"_hasCleared",!0);this.name=e,this.streamType=t,this.trackType=i,this.options=this.initOptions}get initOptions(){return{}}getOptions(){return this.options}init(){return _(this,null,function*(){})}enable(){this._isEnable||(this._isEnable=!0,this.init(),this.emit("enabled"))}disable(){this._isEnable&&(this._isEnable=!1,this.clear(),this.emit("disabled"))}get isEnable(){return this._isEnable}audioUpdated(e){var t,i;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((i=e.currentAudioTrack)==null?void 0:i.id)}videoUpdated(e){var t,i;return((t=this.lastInputVideoTrack)==null?void 0:t.id)!==((i=e.currentVideoTrack)==null?void 0:i.id)}execute(e,t){return _(this,null,function*(){const i=this.shouldUpdate(e,t);this.lastInputAudioTrack=e.currentAudioTrack,this.lastInputVideoTrack=e.currentVideoTrack,this._hasCleared||i?(yield this.process(e,t),this._hasCleared=!1):this.shouldCache&&(!this.lastOutputAudioTrack||this.trackType!==2&&this.trackType!==0||this.lastOutputAudioTrack&&e.updateAudioTrack(this.lastOutputAudioTrack),!this.lastOutputVideoTrack||this.trackType!==2&&this.trackType!==1||this.lastOutputVideoTrack&&e.updateVideoTrack(this.lastOutputVideoTrack)),this.lastOutputAudioTrack=e.currentAudioTrack,this.lastOutputVideoTrack=e.currentVideoTrack})}clear(e){this._hasCleared=!0,this.lastInputAudioTrack=void 0,this.lastInputVideoTrack=void 0,this.lastOutputAudioTrack=void 0,this.lastOutputVideoTrack=void 0}}class Rm extends ur{constructor(){super("AliRtcScreenStandardize",Xe.AliRtcSdkStreamTypeScreen);b(this,"canvas");b(this,"lastWidth");b(this,"lastHeight");b(this,"isProcessingScreenTrack",!1);this.shouldCache=!1}get initOptions(){return{base:4}}setOptions(e){this.options=e}isSupported(){return!(typeof TransformStream=="undefined"||typeof MediaStreamTrackProcessor=="undefined"||typeof MediaStreamTrackGenerator=="undefined")}updateProcessCanvas(e,t){if(this.canvas&&this.lastWidth===e&&this.lastHeight===t)return;const i=Math.ceil(e/this.options.base)*this.options.base,n=Math.ceil(t/this.options.base)*this.options.base;if(this.canvas||(this.canvas=document.createElement("canvas")),this.canvas.width=i,this.canvas.height=n,this.lastWidth&&e>this.lastWidth||this.lastHeight&&t>this.lastHeight){const a=this.canvas.getContext("2d");a&&a.clearRect(0,0,i,n)}this.lastWidth=e,this.lastHeight=t}shouldProcess(e){var i;let t=!1;if(e.originVideoTrack&&e.videoSource===Ci.Screen){const n=(i=e.originVideoTrack)==null?void 0:i.getSettings();if(n){const{width:a,height:c}=n;t=!a||!c||!(a%this.options.base===0&&c%this.options.base===0)}}return t}shouldUpdate(e){return this.shouldProcess(e)!==this.isProcessingScreenTrack}handleFrame(e){return _(this,null,function*(){var a;const{displayWidth:t,displayHeight:i}=e;if(!t||!i||t%this.options.base===0&&i%this.options.base===0)return e;this.updateProcessCanvas(t,i);const n=(a=this.canvas)==null?void 0:a.getContext("2d");if(this.canvas&&n){n.drawImage(e,0,0,t,i);const c=new VideoFrame(this.canvas,{timestamp:e.timestamp});return e.close(),c}return e})}process(e){return _(this,null,function*(){var d;if(!this.shouldProcess(e))return this.clear(e),void(this.isProcessingScreenTrack=!1);if(e.originVideoTrack){const h=e.originVideoTrack.getSettings();if(h){const{width:u,height:p}=h;if(!(!u||!p||!(u%this.options.base===0&&p%this.options.base===0)))return void this.clear(e)}}const t=new MediaStreamTrackProcessor({track:e.originVideoTrack}),i=new MediaStreamTrackGenerator({kind:"video"}),n=new MediaStream([i]),a=this,c=new TransformStream({transform(h,u){return _(this,null,function*(){const p=yield a.handleFrame(h);yield u.enqueue(p),p==null||p.close()})}});t.readable.pipeThrough(c).pipeTo(i.writable);const o=(d=n.getVideoTracks())==null?void 0:d[0];e.updateVideoTrack(o),this.isProcessingScreenTrack=!0})}clear(e){this.canvas=void 0,this.lastWidth=void 0,this.lastHeight=void 0,super.clear(e)}}class Em extends ur{constructor(){super("blankAudio",Xe.AliRtcSdkStreamTypeCapture,ii.BOTH);b(this,"hasTrack",!1);b(this,"oscillator",null);b(this,"audioTrack",null);b(this,"createAudioTrack",()=>{const e=new AudioContext;this.oscillator=e.createOscillator();const t=e.createGain();t.gain.value=0;const i=e.createMediaStreamDestination();this.oscillator.connect(t),t.connect(i),this.oscillator.start();const n=i.stream;return this.audioTrack=n.getAudioTracks()[0],this.audioTrack});this.zIndex=9}isSupported(){return!0}setOptions(){throw new Error("Method not implemented.")}shouldUpdate(e,t){return this.hasTrack!==t.some(i=>i.originVideoTrack||i.originAudioTrack)}process(e,t){return _(this,null,function*(){var n;const i=t.some(a=>a.originVideoTrack||a.originAudioTrack);this.hasTrack=i,i?this.audioTrack&&((n=this.oscillator)==null||n.stop(),this.oscillator=null,this.audioTrack.stop(),this.audioTrack=null):(this.audioTrack||(this.audioTrack=this.createAudioTrack()),e.updateAudioTrack(this.audioTrack))})}}class xl{constructor(r){b(this,"name","COMMON");this.name=r||this.name}info(...r){}warn(...r){}print(r,...e){const t=r.toLowerCase();t&&console[t](`[${r}][${this.name}]`,...e)}}b(xl,"LEVEL",0);class ym{constructor(){b(this,"logger",new xl("AudioMixer"));b(this,"audioContext",new AudioContext);b(this,"audioDestination",this.audioContext.createMediaStreamDestination());b(this,"audioTrack",(r=>r.getAudioTracks()[0])(this.audioDestination.stream));b(this,"sourceNodeMap",{})}get sourceNodeList(){return Object.values(this.sourceNodeMap).map(r=>r.sourceNode).filter(r=>!!r)}get gainNodeList(){return Object.values(this.sourceNodeMap).map(r=>r.gainNode).filter(r=>!!r)}get sourceCount(){return this.sourceNodeList.length}resume(){var r;return(r=this.audioContext)==null?void 0:r.resume()}addTrack(r){this.connectTrack(r)}hasTrack(r){return!!this.sourceNodeMap[r]}removeTrack(r){const{sourceNode:e,gainNode:t}=this.sourceNodeMap[r]||{};t==null||t.disconnect(),e==null||e.disconnect(),delete this.sourceNodeMap[r],e?this.logger.info("SourceNode disconnected. Active source node:",this.sourceNodeList.length):this.logger.warn(`SourceNode ${r} does not exit. Active source node: ${this.sourceNodeList.length}`)}getAudioTrack(){return this.audioTrack}setVolume(r,e){const{gainNode:t}=this.sourceNodeMap[e]||{};t?(this.logger.info(`Setting node(${e}) volume to ${this.scale(r)}`),t.gain.value=this.scale(r)):this.logger.warn(`GainNode ${e} does not exit.`)}reset(){this.disconnectSourceNode(),this.sourceNodeMap={}}dispose(){var r;this.reset(),(r=this.audioTrack)==null||r.stop(),this.audioDestination.disconnect(),this.audioContext.close()}connectTrack(r){if(!this.audioContext)return this.logger.warn("AudioContext not initialized");let e=new MediaStream;e.addTrack(r);const t=this.audioContext.createMediaStreamSource(e),i=this.audioContext.createGain();i.gain.value=1,t.connect(i),i.connect(this.audioDestination),this.sourceNodeMap[r.id]={track:r,sourceNode:t,gainNode:i},this.logger.info("New sourceNode connected. Active source node:",this.sourceNodeList.length)}disconnectSourceNode(){this.sourceNodeList.forEach(r=>r.disconnect()),this.gainNodeList.forEach(r=>r.disconnect())}scale(r){return r/100}}class Tm extends ur{constructor(){super("audioMixer",Xe.AliRtcSdkStreamTypeCapture,ii.AUDIO);b(this,"audioMixer");b(this,"primaryAudioTrackId");b(this,"screenAudioTrackId");b(this,"dirty",!1);this.zIndex=8}get initOptions(){return{audio:1,screen:1}}setOptions(e){Object.entries(e).forEach(([t,i])=>{this.isValidVolume(i)&&(this.options[t]=i)}),this.dirty=!0,this.emit("updated")}isSupported(){return"AudioContext"in window}shouldUpdate(e,t){var a,c;if(e.type!==Xe.AliRtcSdkStreamTypeCapture)return!1;const i=t.find(o=>o.type===Xe.AliRtcSdkStreamTypeCapture),n=t.find(o=>o.type===Xe.AliRtcSdkStreamTypeScreen);return!(this.primaryAudioTrackId===((a=i==null?void 0:i.currentAudioTrack)==null?void 0:a.id)&&this.screenAudioTrackId===((c=n==null?void 0:n.currentAudioTrack)==null?void 0:c.id)&&!this.dirty)}process(e,t){return _(this,null,function*(){var c,o;this.dirty=!1;const i=t.find(l=>l.type===Xe.AliRtcSdkStreamTypeScreen),n=e.currentAudioTrack,a=i==null?void 0:i.currentAudioTrack;if(!a&&this.options.audio===1)return this.audioMixer&&(this.audioMixer.dispose(),this.audioMixer=void 0),this.primaryAudioTrackId=n==null?void 0:n.id,void e.updateAudioTrack(n);this.audioMixer||(this.audioMixer=new ym),yield this.audioMixer.resume(),this.primaryAudioTrackId&&(n==null?void 0:n.id)!==this.primaryAudioTrackId&&((c=this.audioMixer)==null||c.removeTrack(this.primaryAudioTrackId)),n&&!this.audioMixer.hasTrack(n==null?void 0:n.id)&&this.audioMixer.addTrack(n),this.primaryAudioTrackId=n==null?void 0:n.id,this.screenAudioTrackId&&(a==null?void 0:a.id)!==this.screenAudioTrackId&&((o=this.audioMixer)==null||o.removeTrack(this.screenAudioTrackId)),a&&!this.audioMixer.hasTrack(a==null?void 0:a.id)&&this.audioMixer.addTrack(a),this.screenAudioTrackId=a==null?void 0:a.id,this.updateVolume(),e.updateAudioTrack(this.audioMixer.getAudioTrack())})}isValidVolume(e){return e!==void 0&&e>=0&&e<=4}updateVolume(){this.audioMixer&&(this.primaryAudioTrackId&&this.audioMixer.setVolume(100*this.options.audio,this.primaryAudioTrackId),this.screenAudioTrackId&&this.audioMixer.setVolume(100*this.options.screen,this.screenAudioTrackId))}clear(e){var t;(t=this.audioMixer)==null||t.dispose(),super.clear(e)}}class Cm extends ur{constructor(){super(...arguments);b(this,"isProcessing",!1);b(this,"videoScaler")}get initOptions(){return{width:320,height:180,frameRate:15}}setOptions(e){var t;this.options=e,(t=this.videoScaler)==null||t.updateOptions(e)}isSupported(){return Cn.isSupport()}shouldUpdate(e){const t=!!e.currentVideoTrack;return this.isProcessing!==t}process(e){return _(this,null,function*(){if(e.currentVideoTrack){if(this.isProcessing=!0,!this.videoScaler){const i=this.options||this.initOptions;this.videoScaler=Cn.getInstance(e.currentVideoTrack,i)}const t=this.videoScaler.getVideoTrack();t&&e.updateDualVideoTrack(t)}else this.isProcessing&&this.clear()})}clear(e){var t;super.clear(e),this.isProcessing=!1,e==null||e.updateDualVideoTrack(),(t=this.videoScaler)==null||t.dispose()}}function si(s,r,e,t){return new(e||(e=Promise))(function(i,n){function a(l){try{o(t.next(l))}catch(d){n(d)}}function c(l){try{o(t.throw(l))}catch(d){n(d)}}function o(l){var d;l.done?i(l.value):(d=l.value,d instanceof e?d:new e(function(h){h(d)})).then(a,c)}o((t=t.apply(s,r||[])).next())})}var Rr,nr;function Vl(){return si(this,void 0,void 0,function*(){let s=!1;try{s=yield(()=>_(this,null,function*(){return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}))()}catch(r){s=!1}return console.log("isSupportedSIMD",s),s})}typeof SuppressedError=="function"&&SuppressedError,(nr=Rr||(Rr={}))[nr.ERROR=0]="ERROR",nr[nr.WARN=1]="WARN",nr[nr.INFO=2]="INFO",nr[nr.LOG=3]="LOG",nr[nr.DEBUG=4]="DEBUG";class Me{static error(...r){var e;Me.logLevel>=Rr.ERROR&&((e=console.error)===null||e===void 0||e.call(console,`[${Me.logTag}] `,...r))}static warn(...r){var e;Me.logLevel>=Rr.WARN&&((e=console.warn)===null||e===void 0||e.call(console,`[${Me.logTag}] `,...r))}static info(...r){var e;Me.logLevel>=Rr.INFO&&((e=console.info)===null||e===void 0||e.call(console,`[${Me.logTag}] `,...r))}static log(...r){var e;Me.logLevel>=Rr.LOG&&((e=console.log)===null||e===void 0||e.call(console,`[${Me.logTag}] `,...r))}static debug(...r){var e;Me.logLevel>=Rr.DEBUG&&((e=console.debug)===null||e===void 0||e.call(console,`[${Me.logTag}] `,...r))}}Me.logLevel=Rr.WARN,Me.logTag="aliyun-audio-3a";class _m{}class Ul extends _m{static isSupported(){return function(){if(typeof window=="object"&&window!==null){const r="AudioWorklet"in window,e="WebAssembly"in window;return r&&e}return!1}()}static isSupportedSIMD(){return si(this,void 0,void 0,function*(){return yield Vl()})}static setLogger(r){Me.logLevel=r}constructor(r){super(),this.channelCount=1,this.sampleRate=48e3,this.collectDumpOutputData=[],this.collectDumpNearInputData=[],this.collectDumpFarInputData=[],this.collectDumpMetaData=[],this.statUpdateTimer=0,this.statUpdateInterval=5e3,this.options=Object.assign({aecOn:!0,ansOn:!0,agcOn:!0,hdOn:!1,ansMode:1,dumpOn:!1,aiaecOn:!1,wasmCdnPath:"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"},r||{})}initWASM(r,e,t){return si(this,void 0,void 0,function*(){Me.log("initWASM",r,e,t);const i=a=>si(this,void 0,void 0,function*(){try{const c=yield fetch(a,{credentials:"same-origin"});return c.ok||this.onLoadError(new Error(`Failed to fetch WASM: ${c.status}:${c.statusText}, url:${a}`)),c.arrayBuffer()}catch(c){return this.onLoadError(new Error("WASM load error")),Me.error("Error fetching WASM:",c),new Uint8Array(0)}}),n=a=>si(this,void 0,void 0,function*(){return fetch(a).then(c=>c.text())});try{const a=yield Vl(),c=this.options.wasmCdnPath+"audio_module_v2.wasm",o=this.options.wasmCdnPath+"audio_module_v2_simd.wasm",d=yield i(a?o:c),h=this.options.wasmCdnPath+"audio_module_v2.js",u=this.options.wasmCdnPath+"audio_module_v2_simd.js",p=a?u:h,f=yield n(p);r.port.postMessage(Object.assign({type:"init",channelCount:e,sampleRate:t,wasmBuffer:d,isSupportSIMD:a,audioModuleScript:f,logLevel:Me.logLevel},this.options),[d])}catch(a){Me.error("Error initializing WASM:",a),this.onLoadError(new Error("WASM init error"))}r.port.onmessage=a=>{a.data.type==="init_done"&&this.onLoadSuccess(void 0),a.data.type==="dump_output_data"&&this.onDumpOutputData(a.data.data),a.data.type==="dump_near_data"&&this.onDumpNearInputData(a.data.data),a.data.type==="dump_far_data"&&this.onDumpFarInputData(a.data.data),a.data.type==="dump_meta_data"&&this.onDumpMeatData(a.data.data),a.data.type==="output_log"&&this.onOutputLog(a.data.data),a.data.type==="apm_stat_data"&&this.onStatData(a.data.data)}})}createProcessor(r,e,t,i,n){return si(this,void 0,void 0,function*(){this.audioContext=r,this.audioContext.resume(),this.channelCount=t,this.sampleRate=i;try{const o=new Blob(['!function(){"use strict";var tf=Object.defineProperty,rf=Object.defineProperties;var sf=Object.getOwnPropertyDescriptors;var ws=Object.getOwnPropertySymbols,nf=Object.getPrototypeOf,hh=Object.prototype.hasOwnProperty,uh=Object.prototype.propertyIsEnumerable,af=Reflect.get;var oa=(q,de,Ne)=>de in q?tf(q,de,{enumerable:!0,configurable:!0,writable:!0,value:Ne}):q[de]=Ne,D=(q,de)=>{for(var Ne in de||(de={}))hh.call(de,Ne)&&oa(q,Ne,de[Ne]);if(ws)for(var Ne of ws(de))uh.call(de,Ne)&&oa(q,Ne,de[Ne]);return q},Q=(q,de)=>rf(q,sf(de));var jt=(q,de)=>{var Ne={};for(var Et in q)hh.call(q,Et)&&de.indexOf(Et)<0&&(Ne[Et]=q[Et]);if(q!=null&&ws)for(var Et of ws(q))de.indexOf(Et)<0&&uh.call(q,Et)&&(Ne[Et]=q[Et]);return Ne};var b=(q,de,Ne)=>(oa(q,typeof de!="symbol"?de+"":de,Ne),Ne);var ca=(q,de,Ne)=>af(nf(q),Ne,de);var _=(q,de,Ne)=>new Promise((Et,li)=>{var Kr=er=>{try{hi(Ne.next(er))}catch(Jr){li(Jr)}},Cr=er=>{try{hi(Ne.throw(er))}catch(Jr){li(Jr)}},hi=er=>er.done?Et(er.value):Promise.resolve(er.value).then(Kr,Cr);hi((Ne=Ne.apply(q,de)).next())});function t(t,e,a,n){return new(a||(a=Promise))((function(s,i){function o(t){try{h(n.next(t))}catch(t){i(t)}}function r(t){try{h(n.throw(t))}catch(t){i(t)}}function h(t){var e;t.done?s(t.value):(e=t.value,e instanceof a?e:new a((function(t){t(e)}))).then(o,r)}h((n=n.apply(t,e||[])).next())}))}var e;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.ERROR=0]="ERROR",t[t.WARN=1]="WARN",t[t.INFO=2]="INFO",t[t.LOG=3]="LOG",t[t.DEBUG=4]="DEBUG"}(e||(e={}));class a{static error(...t){var n;a.logLevel>=e.ERROR&&(null===(n=console.error)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static warn(...t){var n;a.logLevel>=e.WARN&&(null===(n=console.warn)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static info(...t){var n;a.logLevel>=e.INFO&&(null===(n=console.info)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static log(...t){var n;a.logLevel>=e.LOG&&(null===(n=console.log)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static debug(...t){var n;a.logLevel>=e.DEBUG&&(null===(n=console.debug)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}}a.logLevel=e.WARN,a.logTag="aliyun-audio-3a";const n=Float32Array.BYTES_PER_ELEMENT,s=Uint16Array.BYTES_PER_ELEMENT;class i{constructor(t,e,a,n,s){this._channelData=[],this._name=t,this._isInitialized=!1,this._module=e,this._length=a,this._ringLength=2*a,this._maxChannelCount=s?Math.min(s,32):n,this._channelCount=n,this._allocateHeap(),this._isInitialized=!0,this._readIndex=0,this._writeIndex=0,this._framesAvailable=0,this._channelDataLocal=[];for(let t=0;t<this._channelCount;++t)this._channelDataLocal[t]=new Float32Array(this._ringLength)}_allocateHeap(){const t=this._length*n,e=this._channelCount*t;this._dataPtr=this._module._malloc(e),this._channelData=[];for(let e=0;e<this._channelCount;++e){const a=this._dataPtr+e*t,n=a+t;this._channelData[e]=this._module.HEAPF32.subarray(a>>s,n>>s)}}adaptChannel(t){t<this._maxChannelCount&&(this._channelCount=t)}get length(){return this._isInitialized?this._length:null}get numberOfChannels(){return this._isInitialized?this._channelCount:null}get maxChannelCount(){return this._isInitialized?this._maxChannelCount:null}getChannelData(t){return void 0!==t&&t>=this._channelCount?null:void 0===t?this._channelData:this._channelData[t]}getHeapAddress(){return this._dataPtr}getPointer(){return this._dataPtr}free(){this._isInitialized=!1,null!==this._dataPtr&&this._module._free(this._dataPtr),this._channelData=[]}get framesAvailable(){return this._framesAvailable}push(t){const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)this._channelDataLocal[e][this._writeIndex]=t[e][a];this._writeIndex=(this._writeIndex+1)%this._ringLength}this._framesAvailable+=e,this._framesAvailable>this._ringLength&&(console.warn(this._name,"Too many frames available, overflow"),this._framesAvailable=this._ringLength,this._writeIndex=0)}pull(t){if(0===this._framesAvailable)return void console.warn(this._name,"No frames available");const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)t[e][a]=this._channelDataLocal[e][this._readIndex];this._readIndex=(this._readIndex+1)%this._ringLength}this._framesAvailable-=e,this._framesAvailable<0&&(this._framesAvailable=0,this._readIndex=0)}}class o{constructor(t){this.inited=!1,this.handle=null,this.channelCount=1,this.isEnable=!0,this.dumpAudioData=!1,this.kernelBufferSize=512,this.node=t,this.onDumpOutputDataFunction=null,this.onDumpNearDataFunction=null,this.onDumpFarDataFunction=null,this.onDumpMetaDataFunction=null,this.wasmInvoker=null,this._nearAudioBuffer={},this._outputAudioBuffer={}}destructor(){this.wasmInvoker=null,this.handle=null}init(n){return t(this,void 0,void 0,(function*(){const{wasmBuffer:t,audioModuleScript:s,channelCount:o=1,sampleRate:r=44100,dumpAudioData:h=!1,logLevel:l=e.DEBUG}=n;a.logLevel=l,a.log("AudioAPM init",JSON.stringify(n)),this.channelCount=o,this.dumpAudioData=h;try{const e=new Function(`let module={};let exports={};${s}; return module`)();this.wasmInvoker=yield e.exports({wasmBinary:t})}catch(t){this.node.port.postMessage({type:"error",message:"audioModule init error"}),a.error(t)}this._nearAudioBuffer=new i("inBuffer",this.wasmInvoker,this.kernelBufferSize,2*this.channelCount,32),this._outputAudioBuffer=new i("outBuffer",this.wasmInvoker,this.kernelBufferSize,this.channelCount,32);const u=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=String.fromCharCode.apply(null,a);this.node&&this.node.port&&this.node.port.postMessage({type:"output_log",message:"output_log",data:n})}),"vii");if(this.wasmInvoker.__apm_log_callback(u),this.handle=this.wasmInvoker.__apm_create(n.aecOn?1:0,n.ansOn?1:0,n.agcOn?1:0,n.hdOn?1:0,r,o,n.dumpOn?1:0,this.kernelBufferSize),n.aiaecOn){const t=102;this.wasmInvoker.__apm_set_param(this.handle,t,7)}if(n.useHardOnly){const t=108;this.wasmInvoker.__apm_set_param(this.handle,t,1)}this.node.port.postMessage({type:"init_done",message:"init done"}),this.inited=!0}))}getStatData(){if(this.wasmInvoker&&this.isEnable){let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);this.wasmInvoker._free(t),this.node&&this.node.port&&this.node.port.postMessage({type:"apm_stat_data",message:"apm_stat_data",data:e})}}onOutputLog(t){console.log("[WASM_LOG]",t)}destory(){return t(this,void 0,void 0,(function*(){var t;try{null===(t=this.wasmInvoker)||void 0===t||t.__apm_destory(this.handle),this.inited=!1}catch(t){a.error(t)}finally{this.handle=null}}))}enable(){this.isEnable=!0,a.log("APM enable")}disable(){this.isEnable=!1,a.log("APM disable")}getStat(){if(null==this.wasmInvoker||null==this.handle)return"";let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);return this.wasmInvoker._free(t),e}startDump(){this.onDumpOutputDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_output_data",message:"dump_output_data",data:n})}),"vii"),this.onDumpNearDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_near_data",message:"dump_near_data",data:n})}),"vii"),this.onDumpFarDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_far_data",message:"dump_far_data",data:n})}),"vii"),this.onDumpMetaDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_meta_data",message:"dump_meta_data",data:n})}),"vii"),this.wasmInvoker.__apm_dump_start(this.handle,this.onDumpOutputDataFunction,this.onDumpNearDataFunction,this.onDumpFarDataFunction,this.onDumpMetaDataFunction)}stopDump(){this.wasmInvoker.__apm_dump_stop(this.handle),this.wasmInvoker&&(this.wasmInvoker.removeFunction(this.onDumpOutputDataFunction),this.wasmInvoker.removeFunction(this.onDumpNearDataFunction),this.wasmInvoker.removeFunction(this.onDumpFarDataFunction),this.wasmInvoker.removeFunction(this.onDumpMetaDataFunction))}process(t,e,a){if(!this.inited||!this.isEnable){for(let e=0;e<this.channelCount;e++){a[e].set(t[e])}return}const n=this.channelCount;let s=0;if(this.handle&&this.isEnable){const i=t[0].length,o=[];for(let a=0;a<n;a++)e[a]&&e[a].length>0&&(s=1),o.push(t[a]||new Float32Array(i).fill(0)),o.push(e[a]||new Float32Array(i).fill(0));if(this._nearAudioBuffer.push(o),this._nearAudioBuffer.framesAvailable>=this.kernelBufferSize){this._nearAudioBuffer.pull(this._nearAudioBuffer.getChannelData()),this.wasmInvoker.__apm_process_new(this.handle,this._nearAudioBuffer.getHeapAddress(),this._outputAudioBuffer.getHeapAddress(),n,s);const t=this._outputAudioBuffer.getChannelData();this._outputAudioBuffer.push(t)}this._outputAudioBuffer.pull(a)}}}class r extends AudioWorkletProcessor{constructor(){super(),this.apm=new o(this),this.port.onmessage=t=>{const e=t.data||{};switch(a.log("onmessage data",e),e.type){case"init":this.apm.init(e);break;case"destroy":this.apm.destory();break;case"enable":this.apm.enable();break;case"disable":this.apm.disable();break;case"start_dump":this.apm.startDump();break;case"stop_dump":this.apm.stopDump();break;case"get_stat_data":this.apm.getStatData();break;default:a.warn("Unknown message type:",e.type)}}}process(t,e){const a=t[0],n=t.length>1?t[1]:[],s=e[0];return this.apm.process(a,n,s),!0}}registerProcessor("aliyun-web-3a-processor",r)}();\n'],{type:"application/javascript"}),l=URL.createObjectURL(o);yield this.audioContext.audioWorklet.addModule(l)}catch(o){Me.error("Failed to add module to audio worklet:",o)}let a=new AudioWorkletNode(this.audioContext,"aliyun-web-3a-processor",{numberOfInputs:2,outputChannelCount:[t]});this.workletNode=a,e.connect(a),n&&(this.farNode=n,n.connect(a,0,1));const c=this.audioContext.createMediaStreamDestination();a.connect(c),this.targetMediaTrack=c.stream.getAudioTracks()[0],yield this.initWASM(a,t,i),this.statUpdateTimer=window.setInterval(()=>{this.getStatData()},this.statUpdateInterval)})}addFarNode(r){this.workletNode&&(this.farNode&&this.farNode.disconnect(this.workletNode),r&&(this.farNode=r,r.connect(this.workletNode,0,1)))}getStatData(){var r;try{(r=this.workletNode)===null||r===void 0||r.port.postMessage({type:"get_stat_data"})}catch(e){Me.error("Failed to post message to worklet node:",e)}}destroy(){if(this.statUpdateTimer&&window.clearInterval(this.statUpdateTimer),this.audioContext&&this.workletNode&&this.workletNode.port)try{this.workletNode.port.postMessage({type:"destroy"}),this.workletNode.port.onmessage=null,this.workletNode.disconnect(),Me.log("postMessage destroy")}catch(r){Me.error("Failed to post message to worklet node:",r)}}startDump(){var r;try{(r=this.workletNode)===null||r===void 0||r.port.postMessage({type:"start_dump"})}catch(e){Me.error("Failed to post message to worklet node:",e)}}stopDump(){var r;try{(r=this.workletNode)===null||r===void 0||r.port.postMessage({type:"stop_dump"})}catch(e){Me.error("Failed to post message to worklet node:",e)}setTimeout(()=>{this.onDumpOutputData(null,!0),this.onDumpNearInputData(null,!0),this.onDumpFarInputData(null,!0),this.onDumpMeatData(null,!0)},3e3)}onDumpOutputData(r,e=!1){if(r&&r.length>0&&this.collectDumpOutputData.push(r),e&&this.collectDumpOutputData.length>0||1024*this.collectDumpOutputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpOutputData);this.onDumpData(t,"output_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpOutputData=[]}}onDumpNearInputData(r,e=!1){if(r&&r.length>0&&this.collectDumpNearInputData.push(r),e&&this.collectDumpNearInputData.length>0||1024*this.collectDumpNearInputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpNearInputData);this.onDumpData(t,"near_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpNearInputData=[]}}onDumpFarInputData(r,e=!1){if(r&&r.length>0&&this.collectDumpFarInputData.push(r),e&&this.collectDumpFarInputData.length>0||1024*this.collectDumpFarInputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpFarInputData);this.onDumpData(t,"far_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpFarInputData=[]}}onDumpMeatData(r,e=!1){if(r&&r.length>0&&this.collectDumpMetaData.push(r),e&&this.collectDumpMetaData.length>0||1024*this.collectDumpMetaData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpMetaData);this.onDumpData(t,"meta_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpMetaData=[]}}getMaxDumpBytes(){return 600*Number(this.sampleRate.toFixed(0))*Number(this.channelCount.toFixed(0))*2}enable(){var r;if(!((r=this.workletNode)===null||r===void 0)&&r.port)try{this.workletNode.port.postMessage({type:"enable"}),Me.log("postMessage enable")}catch(e){Me.error("Failed to post message to worklet node:",e)}}disable(){var r;if(!((r=this.workletNode)===null||r===void 0)&&r.port)try{Me.log("postMessage disable"),this.workletNode.port.postMessage({type:"disable"})}catch(e){Me.error("Failed to post message to worklet node:",e)}}on(r,e){r==="loaderror"&&(this.onLoadError=e),r==="loadsuccess"&&(this.onLoadSuccess=e),r==="dumpdata"&&(this.onDumpData=e),r==="outputlog"&&(this.onOutputLog=e),r==="statdata"&&(this.onStatData=e)}onLoadError(r){console.log("onLoadError",r)}onLoadSuccess(r){console.log("onLoadSuccess",r)}onDumpData(r,e){console.log("onDumpData",r,e)}onOutputLog(r){console.log("[WASM]",r)}onStatData(r){console.log("onStatData:",r)}}class wm extends ur{constructor(e){super("AliRtcAudioProcessPlugin",Xe.AliRtcSdkStreamTypeCapture,ii.AUDIO);b(this,"audioProcessor");b(this,"slsReporter");b(this,"enableSoft3ACheck",!1);b(this,"useHardOnly",!1);b(this,"lastDiffOutputLog","");b(this,"audioContext",new AudioContext({sampleRate:48e3}));b(this,"farNode");b(this,"createNode",e=>this.audioContext.createMediaStreamSource(new MediaStream([e])));this.options=e,this.slsReporter=e==null?void 0:e.slsReporter,this.enableSoft3ACheck=(e==null?void 0:e.enableSoft3ACheck)||!1,this.useHardOnly=(e==null?void 0:e.useHardOnly)||!1,this.zIndex=7,document.addEventListener("click",this.activeAudioContext)}activeAudioContext(){var e;(e=this.audioContext)==null||e.resume(),document.removeEventListener("click",this.activeAudioContext)}audioUpdated(e){var t,i;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((i=e.currentAudioTrack)==null?void 0:i.id)}videoUpdated(e){return console.log("videoUpdated",e),!1}setOptions(e){var t;!this.farNode&&e.farMediaStream&&(this.farNode=this.audioContext.createMediaStreamSource(e.farMediaStream),this.audioProcessor&&((t=this.audioProcessor)==null||t.addFarNode(this.farNode)),this.options=D(D({},this.options),e))}isSupported(){return Ul.isSupported()}shouldUpdate(e){return!!(e.originAudioTrack&&!this.audioProcessor||!e.originAudioTrack&&this.audioProcessor)}process(e){return _(this,null,function*(){var t;if(!e.currentAudioTrack)return e.updateAudioTrack(),void this.clear(e);if(!this.audioProcessor){this.audioProcessor=new Ul({aecOn:!0,ansOn:!0,agcOn:!0,dumpOn:((t=this.options)==null?void 0:t.dumpAudioData)||!1,aiaecOn:this.options.aiaecOn||!1,useHardOnly:this.useHardOnly,wasmCdnPath:this.options.wasmCdnPath||"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"}),this.audioProcessor.on("dumpdata",(n,a)=>{let c=3e3;a.includes("far")?c=5e3:a.includes("output")?c=1e4:a.includes("meta")&&(c=8e3),setTimeout(()=>{const o=URL.createObjectURL(n),l=document.createElement("a");l.href=o,l.download=a,document.body.appendChild(l),l.click(),document.body.removeChild(l)},c)}),this.audioProcessor.on("loadsuccess",()=>{var n,a;this.enableSoft3ACheck||e.updateAudioTrack((n=this.audioProcessor)==null?void 0:n.targetMediaTrack),this.options.dumpAudioData&&((a=this.audioProcessor)==null||a.startDump())}),this.audioProcessor.on("loaderror",n=>{this.emit("error",n)}),this.audioProcessor.on("outputlog",n=>{n!=null&&n.includes("diff")&&(this.lastDiffOutputLog=n||"")}),this.audioProcessor.on("statdata",n=>{var a;if(n)try{let c=n;if(this.lastDiffOutputLog){const o=this.extractDiffValue(this.lastDiffOutputLog),l=JSON.parse(n);o!==null&&(l.diff=o);const d=this.extractLeakValue(this.lastDiffOutputLog);d!==null&&(l.leak=d),c=JSON.stringify(l)}(a=this.slsReporter)==null||a.reportPublishAudio3A("","","",c)}catch(c){}});const i=this.createNode(e.currentAudioTrack);yield this.audioProcessor.createProcessor(this.audioContext,i,1,48e3,this.farNode)}})}extractDiffValue(e){if(!e)return null;const t=e.match(/diff\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}extractLeakValue(e){if(!e)return null;const t=e.match(/leak\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}clear(e){var t,i,n;this.options.dumpAudioData&&((t=this.audioProcessor)==null||t.stopDump()),super.clear(e),(i=this.audioProcessor)==null||i.destroy(),this.audioProcessor=void 0,document.removeEventListener("click",this.activeAudioContext),(n=this.farNode)==null||n.disconnect(),this.farNode=void 0}dump(){var e;(e=this.audioProcessor)==null||e.stopDump()}}var ni=(s=>(s[s.Default=0]="Default",s[s.Human=1]="Human",s[s.Robot=2]="Robot",s))(ni||{}),Am=Object.defineProperty,Im=Object.getOwnPropertyDescriptor,Bl=(s,r,e,t)=>{for(var i,n=t>1?void 0:t?Im(r,e):r,a=s.length-1;a>=0;a--)(i=s[a])&&(n=(t?i(r,e,n):i(n))||n);return t&&n&&Am(r,e,n),n};const Gn=(yr=class extends de{constructor(e,t){super();b(this,"self");b(this,"remoteUser");b(this,"sendReadyMsg",!1);b(this,"hasPubDataChannel",!1);b(this,"hasSubDataChannel",!1);b(this,"readyMsgSuccess",!1);b(this,"sendReadyMsgTimer");b(this,"startReadyMsgTime");b(this,"robotUserId");b(this,"onSubscribeDataChannel",e=>{!this.remoteUser&&e&&(this.robotUserId&&this.robotUserId!==e.userId||(this.hasSubDataChannel=!0,this.remoteUser=e,this.remoteUser.on("remoteDataChannelMessage",this.onCheckReadyMsg),this.trySendReadyMsg()))});b(this,"onCheckReadyMsg",(e,t)=>{var i,n;if(this.sendReadyMsg&&!this.readyMsgSuccess)try{const a=new TextDecoder().decode(t.data),c=JSON.parse(a);c.key==="aliyun_aigc"&&c.type==="ready_resp"&&((i=c.data)==null?void 0:i.ready)===!0&&(O.event(`[${yr.logName}]`,"onCheckReadyMsg success"),this.readyMsgSuccess=!0,this.emit("dcready",e),(n=this.remoteUser)==null||n.off("remoteDataChannelMessage",this.onCheckReadyMsg),window.clearTimeout(this.sendReadyMsgTimer))}catch(a){}});b(this,"onDataPublishStateChange",(e,t)=>{t===ne.AliRtcStatePublished&&(this.hasPubDataChannel=!0,this.trySendReadyMsg())});this.self=e,this.self.on("dataPublishStateChanged",this.onDataPublishStateChange),this.robotUserId=t}destroy(){this.self.off("dataPublishStateChanged",this.onDataPublishStateChange),window.clearTimeout(this.sendReadyMsgTimer),this.remoteUser=void 0,this.sendReadyMsg=!1,this.hasPubDataChannel=!1,this.hasSubDataChannel=!1,this.readyMsgSuccess=!1,this.startReadyMsgTime=0}trySendReadyMsg(){O.event(`[${yr.logName}]`,`trySendReadyMsg: pub(${this.hasPubDataChannel}, sub: ${this.hasSubDataChannel})`),this.hasPubDataChannel&&this.hasSubDataChannel&&(this.sendReadyMsg=!0,this.sendReadyMsgLoop())}sendReadyMsgLoop(e=0){return _(this,null,function*(){const t=JSON.stringify({key:"aliyun_aigc",version:"1.0",type:"ready_req",data:{ready:!0}});try{this.self.sendDataChannelMessage(new br(new TextEncoder().encode(t).buffer))}catch(a){}this.startReadyMsgTime||(this.startReadyMsgTime=Date.now());let i=50;const n=Date.now()-this.startReadyMsgTime;i=n<1e3?50:n<2e3?100:n<3e3?500:2e3,e>30?O.event(`[${yr.logName}]`,"sendReadyMsgLoop fail after 30 times"):this.sendReadyMsgTimer=window.setTimeout(()=>{this.sendReadyMsgLoop(e+1)},i)})}},b(yr,"logName","DataChannelReadyHelper"),yr);Bl([k()],Gn.prototype,"destroy",1),Bl([k()],Gn.prototype,"sendReadyMsgLoop",1);let Pm=Gn;class Dm{constructor(r){b(this,"_useSysEchoCancellation",!0);b(this,"_useSysNoiseSuppression",!0);b(this,"_useSysAutoGainControl",!0);b(this,"_useAIAEC",!1);b(this,"_enableSoft3A",!1);b(this,"_enableSoft3ACheck",!1);b(this,"_useHardOnly",!1);b(this,"_dumpAudioData",!1);b(this,"_useAudio3AConfigFromServer",!0);r&&Object.assign(this,r)}get useSysEchoCancellation(){return this._useSysEchoCancellation}set useSysEchoCancellation(r){this._useSysEchoCancellation=r}get useSysNoiseSuppression(){return this._useSysNoiseSuppression}set useSysNoiseSuppression(r){this._useSysNoiseSuppression=r}get useSysAutoGainControl(){return this._useSysAutoGainControl}set useSysAutoGainControl(r){this._useSysAutoGainControl=r}get useAIAEC(){return this._useAIAEC}set useAIAEC(r){this._useAIAEC=r}get enableSoft3A(){return this._enableSoft3A}set enableSoft3A(r){this._enableSoft3A=r}get enableSoft3ACheck(){return this._enableSoft3ACheck}set enableSoft3ACheck(r){this._enableSoft3ACheck=r}get useHardOnly(){return this._useHardOnly}set useHardOnly(r){this._useHardOnly=r}get dumpAudioData(){return this._dumpAudioData}set dumpAudioData(r){this._dumpAudioData=r}get useAudio3AConfigFromServer(){return this._useAudio3AConfigFromServer}set useAudio3AConfigFromServer(r){this._useAudio3AConfigFromServer=r}loadFromLocalConfig(r){var e,t,i,n,a,c,o,l,d;this.useAudio3AConfigFromServer=(e=r.useAudio3AConfigFromServer)!=null?e:this.useAudio3AConfigFromServer,this.useSysEchoCancellation=(t=r.useSysEchoCancellation)!=null?t:this.useSysEchoCancellation,this.useSysNoiseSuppression=(i=r.useSysNoiseSuppression)!=null?i:this.useSysNoiseSuppression,this.useSysAutoGainControl=(n=r.useSysAutoGainControl)!=null?n:this.useSysAutoGainControl,this.useAIAEC=(a=r.useAIAEC)!=null?a:this.useAIAEC,this.enableSoft3A=(c=r.enableSoft3A)!=null?c:this.enableSoft3A,this.dumpAudioData=(o=r.dumpAudioData)!=null?o:this.dumpAudioData,this.enableSoft3ACheck=(l=r.enableSoft3ACheck)!=null?l:this.enableSoft3ACheck,this.useHardOnly=(d=r.useHardOnly)!=null?d:this.useHardOnly}loadFromServerConfig(r){if(r&&typeof r=="object"){const e=xr(r,"enableSoft3A"),t=ei(r,"enableSoft3A");if(e===!0&&t===!0&&(this.enableSoft3A=!0),this.enableSoft3A){if(r.archCfgs){const i=xr(r,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const n=xr(r,"useAIAEC");n!==void 0&&(this.useAIAEC=n);const a=xr(r,"useSysNoiseSuppression");a!==void 0&&(this.useSysNoiseSuppression=a);const c=xr(r,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=xr(r,"useSysAutoGainControl");o!==void 0&&(this.useSysAutoGainControl=o)}if(r.config){const i=ei(r,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const n=ei(r,"useAIAEC");n!==void 0&&(this.useAIAEC=n);const a=ei(r,"useSysNoiseSuppression");a!==void 0&&(this.useSysNoiseSuppression=a);const c=ei(r,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=ei(r,"useSysAutoGainControl");o!==void 0&&(this.useSysAutoGainControl=o)}O.info("setAudio3AConfig:","enableSoft3A",this.enableSoft3A,", enableSoft3ACheck",this.enableSoft3ACheck,", useAIAEC",this.useAIAEC,", useSysNoiseSuppression",this.useSysNoiseSuppression,", useSysEchoCancellation",this.useSysEchoCancellation,", useSysAutoGainControl",this.useSysAutoGainControl)}}}}var km=Object.defineProperty,Mm=Object.getOwnPropertyDescriptor,_t=(s,r,e,t)=>{for(var i,n=t>1?void 0:t?Mm(r,e):r,a=s.length-1;a>=0;a--)(i=s[a])&&(n=(t?i(r,e,n):i(n))||n);return t&&n&&km(r,e,n),n};class St extends de{constructor(e){super();b(this,"self");b(this,"userMap",{});b(this,"usersViewMap",{});b(this,"rtsManager");b(this,"localStreamManager");b(this,"authInfo");b(this,"signalingManager");b(this,"pluginManager");b(this,"audioMixerPlugin");b(this,"dualVideoPlugin");b(this,"blankAudioPlugin");b(this,"audioProcessorPlugin");b(this,"slsReporter");b(this,"statsMonitorId");b(this,"autoSubAudio",!0);b(this,"autoSubVideo",!0);b(this,"autoSubScreen",!0);b(this,"wantSubAudio",!0);b(this,"wantSubVideo",!0);b(this,"wantSubScreen",!0);b(this,"defaultStreamType",it.AliRtcVideoStreamTypeHigh);b(this,"audioMuted",!1);b(this,"playoutVolume",1);b(this,"refreshUrlTimer");b(this,"audioVolumeIndicationInterval",0);b(this,"indicationTimer",0);b(this,"parameter",{});b(this,"audio3AConfig",new Dm);b(this,"dcReadyHelper");b(this,"onePcManager");const{signalingManager:t,slsReporter:i,parameter:n}=e;this.signalingManager=t,this.addSignalingManagerListener(),this.slsReporter=i,n&&(this.parameter=n),this.pluginManager=new um,this.localStreamManager=new bm(this.pluginManager,this.slsReporter),this.rtsManager=new fm(this.localStreamManager,this.slsReporter,this.parameter),this.addRTSListener(),this.self=new am({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,slsReporter:this.slsReporter,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,parameter:this.parameter}),this.audioMixerPlugin=new Tm,this.pluginManager.add(this.audioMixerPlugin),this.dualVideoPlugin=new Cm("dualVideoPlugin"),new Pe.SupportUtil().checkScreenCapture()&&this.pluginManager.add(new Rm)}setOnePcManager(e){this.onePcManager=e,this.rtsManager.onePcManager=e,this.signalingManager.initOnePc(e)}addSignalingManagerListener(){this.signalingManager.on("onNotifyPublish",e=>{e.forEach(t=>{var i;(i=t==null?void 0:t.tracks)==null||i.forEach(n=>{var a;if(n.msid===L.Audio&&n.userdata)try{const c=JSON.parse(n.userdata);c.agent_instance&&((a=this.slsReporter)==null||a.setCustomFields({ageniid:c.agent_instance}))}catch(c){console.error("Failed to parse userdata:",c)}})}),this.slsReporter.reportConnectionLatencyEvent(Ot.RECV_NOTIFY_PUBLISH,"","",""),O.event("[Signaling] Notify Publish ",e),e.forEach(t=>{this.onRemotePublishStateChange(t)})}),this.signalingManager.stsManager.on("onTokenUpdate",(e,t)=>{this.slsReporter.updateToken(t,e)})}addRTSListener(){this.rtsManager.on("traceIdUpdated",(e,t)=>{if(ze.removeQueryString(this.self.url)===ze.removeQueryString(e))return void(this.self.traceId=t);const i=this.remoteUsers.find(n=>ze.removeQueryString(n.streamUrl)===ze.removeQueryString(e));i&&(i.traceId=t)}),this.rtsManager.on("reconnect",(e,t,i)=>{if(!e||e==="pc"||e==="all")return this.self.markReconnect(),void this.remoteUsers.forEach(a=>{a.markReconnect()});if(e==="pub"||e==="pub-data")return void this.self.markReconnect(i);const n=this.remoteUsers.find(a=>ze.removeQueryString(a.streamUrl)===ze.removeQueryString(t||""));n==null||n.markReconnect(i)}),this.rtsManager.on("reconnectFinish",(e,t,i)=>{if(O.event("[RtsManager]","reconnectFinish",e,t,i),!e||e==="pc"||e==="all")return this.self.markReconnected(),void this.remoteUsers.forEach(a=>{a.markReconnected()});if(e==="pub"||e==="pub-data")return void this.self.markReconnected(i);const n=this.remoteUsers.find(a=>ze.removeQueryString(a.streamUrl)===ze.removeQueryString(t||""));n==null||n.markReconnected(i)})}isAutoSubAudio(){return this.autoSubAudio}setAutoSubAudio(e){this.autoSubAudio=e}isAutoSubVideo(){return this.autoSubVideo}setAutoSubVideo(e){this.autoSubVideo=e}isAutoSubScreen(){return this.autoSubScreen}setAutoSubScreen(e){this.autoSubScreen=e}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e,this.remoteUsers.forEach(t=>{t.setWantSubAudio(e),t.updateSubscribe(De.User)})}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e,this.remoteUsers.forEach(t=>{t.setWantSubVideo(e),t.updateSubscribe(De.User)})}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e,this.remoteUsers.forEach(t=>{t.setWantSubScreen(e),t.updateSubscribe(De.User)})}get preferVideoSmall(){return this.defaultStreamType===it.AliRtcVideoStreamTypeLow}setRemoteDefaultVideoStreamType(e){this.defaultStreamType=e,this.remoteUsers.forEach(t=>{t.setRemoteDefaultVideoStreamType(e)})}setRemoteUserVideoStreamType(e,t){var i;(i=this.getRemoteUser(e))==null||i.setRemoteDefaultVideoStreamType(t)}setAudioMuted(e){this.audioMuted=e,this.remoteUsers.forEach(t=>{t.setAudioMuted(e)})}setLocalViewConfig(e,t){if(!e)return this.publisher.setViewConfig(null,t);const i=bn(e);i.length!==0&&i.forEach(n=>{this.publisher.resetElement(n),Object.values(this.usersViewMap).forEach(({cameraViews:a=[],screenViews:c=[]})=>{a.includes(n)&&a.splice(a.indexOf(n),1),c.includes(n)&&c.splice(c.indexOf(n),1)}),this.publisher.setViewConfig(i,t)})}setRemoteViewConfig(e,t,i){var a,c;if(!t)return(a=this.userMap[e])==null?void 0:a.setViewConfig(null,i);const n=bn(t);n.length!==0&&(n.forEach(o=>{this.publisher.resetElement(o),Object.values(this.usersViewMap).forEach(({cameraViews:l=[],screenViews:d=[]})=>{l.includes(o)&&l.splice(l.indexOf(o),1),d.includes(o)&&d.splice(d.indexOf(o),1)})}),(c=this.userMap[e])==null||c.setViewConfig(n,i))}get channel(){var e;return(e=this.authInfo)==null?void 0:e.channelId}get userId(){var e;return(e=this.authInfo)==null?void 0:e.userId}get remoteUsers(){return Object.values(this.userMap)}get publisher(){return this.self}get isSubscribing(){var e;return((e=this.remoteUsers)!=null?e:[]).some(t=>{const{isAudioSubscribing:i,isVideoSubscribing:n,isScreenSubscribing:a}=t;return i||n||a})}onRemotePublishStateChange(e,t=!0){var p;const{userid:i,callid:n,subscribe:a,pubid:c="",tracks:o}=e,l=(p=a==null?void 0:a.pullstreamurl)!=null?p:"";let d=this.getRemoteUser(i);if(!d)return;const h=d.streamInfo.audioTrackInfo,u=d.streamInfo.videoTrackInfo;d.updateRemoteTracks(n,l,c,o),h===d.streamInfo.audioTrackInfo&&u===d.streamInfo.videoTrackInfo||this.emit("remoteTrackAvailableChange",i,d.streamInfo.audioTrackInfo,d.streamInfo.videoTrackInfo),t&&d.updateSubscribe(De.Publish)}setTimeoutToUpdateAllStreamUrls(e){var n;if(!e)return;let t=354e4;const i=(n=function(a){var c,o;try{const l=new URL(a),[d,h]=l.pathname.slice(1).split("/"),u=/(\w+)(web\w{5}-\w{4}-\w{4}-\w{4}-\w{12})/.exec(h),p=u==null?void 0:u[1],f=u==null?void 0:u[2],m=new URLSearchParams(l.search);return{appId:d,channelId:p,sessionId:f,timeoutTs:1e3*parseInt((o=(c=m.get("auth_key"))==null?void 0:c.split("-")[0])!=null?o:"0")}}catch(l){return null}}(e))==null?void 0:n.timeoutTs;i&&(t=i-Date.now()-6e4),this.refreshUrlTimer=window.setTimeout(()=>_(this,null,function*(){var c;const a=yield this.signalingManager.refreshUrl({pushstreamurl:this.self.url,users:this.remoteUsers.map(o=>({userid:o.userId,subscribe:{pullstreamurl:o.streamUrl}}))});a.pushstreamurl&&(this.self.url=a.pushstreamurl),(c=a.users)==null||c.forEach(o=>{var d;const l=this.getRemoteUser(o.userid);l&&((d=o.subscribe)!=null&&d.pullstreamurl)&&(l.streamUrl=o.subscribe.pullstreamurl)}),this.setTimeoutToUpdateAllStreamUrls(a.pushstreamurl)}),t)}init(e,t,i){var n;this.authInfo=e,this.self.enableAudioVolumeIndication(this.audioVolumeIndicationInterval),this.self.initInfo(e,t.pushstreamurl),this.audio3AConfig.useAudio3AConfigFromServer&&this.audio3AConfig.loadFromServerConfig((n=t==null?void 0:t.config)==null?void 0:n.data),this.setupAudioProcessingPluginIfNeeded(),i.capabilityProfile===ni.Human&&(this.dcReadyHelper=new Pm(this.self,i.robotUserId),this.dcReadyHelper.on("dcready",a=>{var c;this.emit("remoteUserSubscribedDataChannel",a),(c=this.dcReadyHelper)==null||c.destroy(),this.dcReadyHelper=void 0})),this.setTimeoutToUpdateAllStreamUrls(t.pushstreamurl),t.users.forEach(a=>{this.addUser(a,De.InRoom)}),this.startStatsMonitor()}leave(){return _(this,null,function*(){var e;this.stopStatsMonitor(),this.refreshUrlTimer!==void 0&&(window.clearTimeout(this.refreshUrlTimer),this.refreshUrlTimer=void 0),Object.values(this.usersViewMap).forEach(({cameraViews:t=[],screenViews:i=[]})=>{t.forEach(n=>{n.srcObject=null,n._playPromise=void 0}),i.forEach(n=>{n.srcObject=null,n._playPromise=void 0})}),this.usersViewMap={};for(let t in this.userMap)this.userMap[t]&&(this.userMap[t].clear(),delete this.userMap[t]);this.self.leave(),(e=this.dcReadyHelper)==null||e.destroy(),this.dcReadyHelper=void 0,this.localStreamManager.stop(),this.rtsManager.clear(),this.authInfo=void 0})}clear(){return _(this,null,function*(){yield this.leave(),this.self.clear(),this.pluginManager.removeAll()})}startStatsMonitor(){this.statsMonitorId=window.setInterval(()=>_(this,null,function*(){if(this.publisher){const{audio:i,video:n,candidate:a}=yield this.publisher.getStats();i&&i.length>0&&this.emit("rtcLocalAudioStats",i),n&&n.length>0&&this.emit("rtcLocalVideoStats",n),a&&this.emit("rtcStats",a)}const e=[],t=[];for(const i of this.remoteUsers){const{audio:n,video:a}=yield i.getStats();n&&n.forEach(c=>{e.push(c)}),a&&a.forEach(c=>{t.push(c)})}e.length>0&&this.emit("rtcRemoteAudioStats",e),t.length>0&&this.emit("rtcRemoteVideoStats",t)}),2e3)}stopStatsMonitor(){this.statsMonitorId&&clearInterval(this.statsMonitorId)}addUser(e,t){const i=e.userid;let n=this.userMap[i];return n||(n=this.executeAddUser(i,e.displayname||"",t),this.userMap[i]=n,this.emit("remoteUserJoin",i,0)),this.onRemotePublishStateChange(e,t!==De.InRoom),n}executeAddUser(e,t,i){const n=new hm({userId:e,displayName:t,onePcManager:this.onePcManager,rtsManager:this.rtsManager,signalingManager:this.signalingManager,usersViewMap:this.usersViewMap,slsReporter:this.slsReporter,localUser:this.self,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,playoutVolume:this.playoutVolume,parameter:this.parameter});return n.on(bt.Remote,this.onRemoteDeviceStatusChange.bind(this)),n.on(We.PullStreamStats,this.onRemoteStatReport.bind(this)),n.on(We.RtsSubscribeExceeds,this.onSubscribeExceeds.bind(this)),n.on("audioSubscribeStateChanged",(a,c,o,l)=>{this.emit("audioSubscribeStateChanged",a,c,o,l,this.channel||"")}),n.on("videoSubscribeStateChanged",(a,c,o,l)=>{this.emit("videoSubscribeStateChanged",a,c,o,l,this.channel||"")}),n.on("screenSubscribeStateChanged",(a,c,o,l)=>{this.emit("screenSubscribeStateChanged",a,c,o,l,this.channel||"")}),n.on("dataSubscribeStateChanged",(a,c,o,l)=>{var d;o===ge.AliRtcStateSubscribed&&((d=this.dcReadyHelper)==null||d.onSubscribeDataChannel(this.userMap[a])),this.emit("dataSubscribeStateChanged",a,c,o,l,this.channel||"")}),n.on("remoteAudioAutoPlayFail",a=>{this.emit("remoteAudioAutoPlayFail",a)}),n.on("remoteVideoAutoPlayFail",(a,c)=>{this.emit("remoteVideoAutoPlayFail",a,c)}),n.on("remoteAudioPlayError",(a,c)=>{this.emit("remoteAudioPlayError",a,c)}),n.on("remoteVideoPlayError",(a,c)=>{this.emit("remoteVideoPlayError",a,c)}),n.on("remoteSubscribeError",a=>{this.emit("remoteSubscribeError",a,n.userId)}),n.on("occurError",a=>{this.emit("occurError",a,n.userId)}),n.on("remoteDataChannelMessage",(a,c)=>{this.emit("remoteDataChannelMessage",a,c)}),n.setWantSubAudio(this.autoSubAudio&&this.wantSubAudio),n.setWantSubVideo(this.autoSubVideo&&this.wantSubVideo),n.setWantSubScreen(this.autoSubScreen&&this.wantSubScreen),n.setRemoteDefaultVideoStreamType(this.defaultStreamType),n.setAudioMuted(this.audioMuted),(this.autoSubAudio||this.autoSubVideo||this.autoSubScreen)&&n.updateSubscribe(i),n}onRemoteDeviceStatusChange(e,t){e===We.MuteAudio?this.emit("userAudioMuted",t,!0):e===We.UnmuteAudio?this.emit("userAudioMuted",t,!1):e===We.MuteVideo?this.emit("userVideoMuted",t,!0):e===We.UnmuteVideo?this.emit("userVideoMuted",t,!1):e===We.MuteScreen?this.emit("userScreenMuted",t,!0):e===We.UnmuteScreen&&this.emit("userScreenMuted",t,!1)}onRemoteStatReport(e,t,i){this.emit(We.PullStreamStats,e,t,i)}onSubscribeExceeds(e,t){this.emit(We.RtsSubscribeExceeds,e,t)}removeLeftUser(e){return _(this,null,function*(){e.userid&&this.userMap[e.userid]&&(yield this.userMap[e.userid].clear(!1),delete this.userMap[e.userid])})}diffUsers(e){const t=[],i=[];e.forEach(a=>{a.userid&&(this.userMap[a.userid]?i.push(a):t.push(a))});const n=Object.keys(this.userMap).filter(a=>!e.find(c=>c.userid===a)).map(a=>({userid:a,reason:"",leavecode:mn.AliRtcUserOfflineQuit}));return{joinList:t,leaveList:n,presentList:i}}getRemoteUser(e){return this.userMap[e]}updateRemoteUserDeviceStatus(e){e&&e.userid&&this.userMap[e.userid]&&this.userMap[e.userid].updateRemoteUserDeviceStatus(e.status)}updateAudioWant(e,t){const i=this.userMap[e];if(!i)throw new W(z.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubAudio(t),t?i.updateSubscribe(De.User):i.stopSubscribe({audio:!0})}updateVideoWant(e,t){const i=this.userMap[e];if(!i)throw new W(z.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubVideo(t),t?i.updateSubscribe(De.User):i.stopSubscribe({video:!0})}updateScreenWant(e,t){const i=this.userMap[e];if(!i)throw new W(z.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubScreen(t),t?i.updateSubscribe(De.User):i.stopSubscribe({screen:!0})}stopIndication(){this.indicationTimer&&window.clearInterval(this.indicationTimer)}startIndication(e){this.stopIndication(),this.indicationTimer=window.setInterval(()=>{const t=this.remoteUsers.map(i=>({userId:i.userId,volume:i.getAudioLevel()||0}));t.unshift({userId:"",volume:this.self.getAudioLevel()||0}),this.emit("audioVolume",t)},e)}setEnableDualVideoStream(e,t){if(!this.dualVideoPlugin)return;t&&this.dualVideoPlugin.setOptions(t);const i=this.pluginManager.has(this.dualVideoPlugin.name);e?!i&&this.pluginManager.add(this.dualVideoPlugin):i&&this.pluginManager.remove(this.dualVideoPlugin.name)}setAudioVolume(e){var t;(t=this.audioMixerPlugin)==null||t.setOptions(e)}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.stopIndication(),e>0&&this.startIndication(e),this.audioVolumeIndicationInterval=e,this.remoteUsers.forEach(t=>{t.enableAudioVolumeIndication(e)}),this.self.enableAudioVolumeIndication(e))}setPlayoutVolume(e){this.playoutVolume=e,this.remoteUsers.forEach(t=>{t.setPlayoutVolume(e)})}refreshAuthInfo(e){this.authInfo&&(this.authInfo=D(D({},this.authInfo),e)),e.userId&&this.self.refreshUserInfo(e.userId)}setEnableMediaExtensionMsg(e){this.rtsManager.setEncodedInsertableStreams(e)}setAudioRedEnabled(e){this.rtsManager.setAudioRedEnabled(e)}setVideoCodec(e){this.rtsManager.changeVideoCodec(e)}setParameter(e){var i,n,a,c;const t=JSON.parse(e);Object.keys(t).forEach(o=>{const l=this.parameter[o],d=t[o];this.parameter[o]=typeof l=="object"&&typeof d=="object"?D(D({},l),d):d}),t.enableBlankAudio===!0?(this.blankAudioPlugin||(this.blankAudioPlugin=new Em),this.pluginManager.has((i=this.blankAudioPlugin)==null?void 0:i.name)||this.pluginManager.add(this.blankAudioPlugin)):t.enableBlankAudio===!1&&(this.blankAudioPlugin&&this.pluginManager.remove((n=this.blankAudioPlugin)==null?void 0:n.name),(a=this.blankAudioPlugin)==null||a.clear(),this.blankAudioPlugin=void 0),t.audio&&((c=this.audio3AConfig)==null||c.loadFromLocalConfig(t.audio))}setupAudioProcessingPluginIfNeeded(){if(this.audio3AConfig.enableSoft3A){let e=0;this.audio3AConfig.enableSoft3ACheck&&(e=1e4),setTimeout(()=>{this.audioProcessorPlugin||(this.audioProcessorPlugin=new wm({dumpAudioData:this.audio3AConfig.dumpAudioData,aiaecOn:this.audio3AConfig.useAIAEC,slsReporter:this.slsReporter,enableSoft3ACheck:this.audio3AConfig.enableSoft3ACheck,useHardOnly:this.audio3AConfig.useHardOnly})),this.audioProcessorPlugin&&!this.pluginManager.has(this.audioProcessorPlugin.name)&&(this.audioProcessorPlugin.on("error",({message:t})=>{var i;O.error("audioProcessorPlugin error:",t),(i=this.self.audioTrack)==null||i.applyConstraints({echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0})}),this.pluginManager.add(this.audioProcessorPlugin))},e)}else this.audioProcessorPlugin&&(this.pluginManager.remove(this.audioProcessorPlugin.name),this.audioProcessorPlugin=void 0);this.self.setMicrophoneConstraints({echoCancellation:this.audio3AConfig.useSysEchoCancellation,noiseSuppression:this.audio3AConfig.useSysNoiseSuppression,autoGainControl:this.audio3AConfig.useSysAutoGainControl})}getParameter(){return JSON.stringify(this.parameter)}sendDataChannelMessage(e){return this.self.sendDataChannelMessage(e)}}b(St,"logName","BizControl"),_t([k()],St.prototype,"init",1),_t([k()],St.prototype,"leave",1),_t([k()],St.prototype,"clear",1),_t([k(J)],St.prototype,"addUser",1),_t([k()],St.prototype,"removeLeftUser",1),_t([k()],St.prototype,"diffUsers",1),_t([k(J)],St.prototype,"updateAudioWant",1),_t([k(J)],St.prototype,"updateVideoWant",1),_t([k(J)],St.prototype,"updateScreenWant",1),_t([k()],St.prototype,"stopIndication",1),_t([k()],St.prototype,"startIndication",1),_t([k(J)],St.prototype,"setEnableDualVideoStream",1),_t([k(J)],St.prototype,"setAudioVolume",1),_t([k()],St.prototype,"enableAudioVolumeIndication",1);var Ii=(s=>(s[s.LiveTranscodingSingle=0]="LiveTranscodingSingle",s[s.LiveTranscodingMix=1]="LiveTranscodingMix",s))(Ii||{}),zn=(s=>(s[s.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",s[s.LiveTranscodingAudio=1]="LiveTranscodingAudio",s[s.LiveTranscodingVideo=2]="LiveTranscodingVideo",s))(zn||{}),ai=(s=>(s[s.LiveTranscodingCamera=0]="LiveTranscodingCamera",s[s.LiveTranscodingShareScreen=1]="LiveTranscodingShareScreen",s))(ai||{});const Pi={0:"camera",1:"shareScreen"};var Kn=(s=>(s[s.LiveTranscoding_Profile_1IN_1080P=0]="LiveTranscoding_Profile_1IN_1080P",s[s.LiveTranscoding_Profile_1IN_720P=1]="LiveTranscoding_Profile_1IN_720P",s[s.LiveTranscoding_Profile_1IN_360P=2]="LiveTranscoding_Profile_1IN_360P",s[s.LiveTranscoding_Profile_2IN_1080P=3]="LiveTranscoding_Profile_2IN_1080P",s[s.LiveTranscoding_Profile_2IN_720P=4]="LiveTranscoding_Profile_2IN_720P",s[s.LiveTranscoding_Profile_2IN_360P=5]="LiveTranscoding_Profile_2IN_360P",s[s.LiveTranscoding_Profile_4IN_1080P=6]="LiveTranscoding_Profile_4IN_1080P",s[s.LiveTranscoding_Profile_4IN_720P=7]="LiveTranscoding_Profile_4IN_720P",s[s.LiveTranscoding_Profile_4IN_360P=8]="LiveTranscoding_Profile_4IN_360P",s[s.LiveTranscoding_Profile_9IN_1080P=9]="LiveTranscoding_Profile_9IN_1080P",s[s.LiveTranscoding_Profile_9IN_720P=10]="LiveTranscoding_Profile_9IN_720P",s[s.LiveTranscoding_Profile_9IN_360P=11]="LiveTranscoding_Profile_9IN_360P",s[s.LiveTranscoding_Profile_12IN_1080P=12]="LiveTranscoding_Profile_12IN_1080P",s[s.LiveTranscoding_Profile_12IN_720P=13]="LiveTranscoding_Profile_12IN_720P",s[s.LiveTranscoding_Profile_12IN_360P=14]="LiveTranscoding_Profile_12IN_360P",s[s.LiveTranscoding_Profile_16IN_1080P=15]="LiveTranscoding_Profile_16IN_1080P",s[s.LiveTranscoding_Profile_16IN_720P=16]="LiveTranscoding_Profile_16IN_720P",s[s.LiveTranscoding_Profile_16IN_360P=17]="LiveTranscoding_Profile_16IN_360P",s[s.LiveTranscoding_Profile_Mixed=9999]="LiveTranscoding_Profile_Mixed",s))(Kn||{});const Om={0:"1IN_1080P",1:"1IN_720P",2:"1IN_360P",3:"2IN_1080P",4:"2IN_720P",5:"2IN_360P",6:"4IN_1080P",7:"4IN_720P",8:"4IN_360P",9:"9IN_1080P",10:"9IN_720P",11:"9IN_360P",12:"12IN_1080P",13:"12IN_720P",14:"12IN_360P",15:"16IN_1080P",16:"16IN_720P",17:"16IN_360P",9999:"Mixed_Audio"};var vs=(s=>(s[s.LiveTranscoding_HZ_48000=48e3]="LiveTranscoding_HZ_48000",s[s.LiveTranscoding_HZ_44100=44100]="LiveTranscoding_HZ_44100",s[s.LiveTranscoding_HZ_32000=32e3]="LiveTranscoding_HZ_32000",s[s.LiveTranscoding_HZ_16000=16e3]="LiveTranscoding_HZ_16000",s[s.LiveTranscoding_HZ_8000=8e3]="LiveTranscoding_HZ_8000",s))(vs||{}),Di=(s=>(s[s.LiveTranscodingNoBody=0]="LiveTranscodingNoBody",s[s.LiveTranscodingBody=1]="LiveTranscodingBody",s))(Di||{}),ki=(s=>(s[s.NOTO_SERIF_CJKSC_REGULAR=0]="NOTO_SERIF_CJKSC_REGULAR",s[s.ALIBABA_PUHUITI_REGULAR=1]="ALIBABA_PUHUITI_REGULAR",s[s.ALIBABA_PUHUITI_BOLD=2]="ALIBABA_PUHUITI_BOLD",s[s.ALIBABA_PUHUITI_Heavy=3]="ALIBABA_PUHUITI_Heavy",s[s.ALIBABA_PUHUITI_LIGHT=4]="ALIBABA_PUHUITI_LIGHT",s[s.ALIBABA_PUHUITI_MEDIUM=5]="ALIBABA_PUHUITI_MEDIUM",s))(ki||{}),Jn=(s=>(s[s.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",s[s.LiveTranscodingCrop=1]="LiveTranscodingCrop",s[s.LiveTranscodingFill=2]="LiveTranscodingFill",s))(Jn||{}),Rs=(s=>(s[s.LiveTranscodingNormal=0]="LiveTranscodingNormal",s[s.LiveTranscodingVirtualBackground=1]="LiveTranscodingVirtualBackground",s))(Rs||{}),$n=(s=>(s[s.LiveTranscodingState_IDLE=0]="LiveTranscodingState_IDLE",s[s.LiveTranscodingState_CONNNECT=1]="LiveTranscodingState_CONNNECT",s[s.LiveTranscodingState_RUNNING=2]="LiveTranscodingState_RUNNING",s[s.LiveTranscodingState_RECOVERING=3]="LiveTranscodingState_RECOVERING",s[s.LiveTranscodingState_FAILURE=4]="LiveTranscodingState_FAILURE",s[s.LiveTranscodingState_END=5]="LiveTranscodingState_END",s))($n||{}),ar=(s=>(s[s.LiveTranscodingErrorPublishOk=0]="LiveTranscodingErrorPublishOk",s[s.LiveTranscodingErrorStreamNotFound=17825793]="LiveTranscodingErrorStreamNotFound",s[s.LiveTranscodingErrorStreamAlreadyExist=17825794]="LiveTranscodingErrorStreamAlreadyExist",s[s.LiveTranscodingErrorInvalidParam=17825795]="LiveTranscodingErrorInvalidParam",s[s.LiveTranscodingErrorInternalError=17825796]="LiveTranscodingErrorInternalError",s[s.LiveTranscodingErrorRtmpServerError=17825797]="LiveTranscodingErrorRtmpServerError",s[s.LiveTranscodingErrorRtmpStreamUrlError=17825798]="LiveTranscodingErrorRtmpStreamUrlError",s[s.LiveTranscodingErrorPublishTimeout=17825799]="LiveTranscodingErrorPublishTimeout",s[s.LiveTranscodingErrorNotAuthorized=17825800]="LiveTranscodingErrorNotAuthorized",s))(ar||{}),Xn=(s=>(s[s.TrascodingPublishTaskStatusStart=0]="TrascodingPublishTaskStatusStart",s[s.TrascodingPublishTaskStatusUpdate=1]="TrascodingPublishTaskStatusUpdate",s[s.TrascodingPublishTaskStatusStop=2]="TrascodingPublishTaskStatusStop",s))(Xn||{}),wt=(s=>(s[s.MPU_TASK_TRANSACTION_START=0]="MPU_TASK_TRANSACTION_START",s[s.MPU_TASK_TRANSACTION_UPDATE=1]="MPU_TASK_TRANSACTION_UPDATE",s[s.MPU_TASK_TRANSACTION_STOP=2]="MPU_TASK_TRANSACTION_STOP",s[s.MPU_TASK_TRANSACTION_LIST=3]="MPU_TASK_TRANSACTION_LIST",s[s.MPU_TASK_TRANSACTION_POLLING=4]="MPU_TASK_TRANSACTION_POLLING",s[s.MPU_TASK_TRANSACTION_ACKNOWLEDGE=5]="MPU_TASK_TRANSACTION_ACKNOWLEDGE",s[s.MPU_TASK_TRANSACTION_END=6]="MPU_TASK_TRANSACTION_END",s))(wt||{});const Nm={0:"/libra/v1/sdk/start-task",1:"/libra/v1/sdk/update-task",2:"/libra/v1/sdk/stop-task",3:"/libra/v1/sdk/list-task",4:"/libra/v1/sdk/polling",5:"/libra/v1/sdk/acknowledge",6:"/"};class Zn{constructor(r,e,t,i,n,a,c,o){b(this,"videoWidth");b(this,"videoHeight");b(this,"videoFramerate",20);b(this,"videoBitrate",2e3);b(this,"videoGop",30);b(this,"audioSamplerate",vs.LiveTranscoding_HZ_44100);b(this,"audioBitrate",500);b(this,"audioChannels",1);this.videoWidth=r,this.videoHeight=e,t&&(this.videoFramerate=t),i&&(this.videoBitrate=i),n&&(this.videoGop=n),a&&(this.audioSamplerate=a),c&&(this.audioBitrate=c),o&&(this.audioChannels=o)}}const Yn=s=>((16711680&s)>>16)+(65280&s)+((255&s)<<16),Ht=(s=0,r)=>{if(r==0)return 0;let e=s/r;return e<0&&(e=0),e>1&&(e=1),e};class Es{constructor(r,e,t){b(this,"mixMode",Ii.LiveTranscodingSingle);b(this,"singleParam");b(this,"mixParam");r&&(this.mixMode=r),e&&(this.singleParam=e),t&&(this.mixParam=t)}toJson(r,e,t,i,n){const a={appid:e.appId,channelid:e.channelId};if(r===wt.MPU_TASK_TRANSACTION_POLLING||r===wt.MPU_TASK_TRANSACTION_LIST||r===wt.MPU_TASK_TRANSACTION_ACKNOWLEDGE)return r===wt.MPU_TASK_TRANSACTION_ACKNOWLEDGE&&(a.messageid=n),a;if(a.taskid=t,r!==wt.MPU_TASK_TRANSACTION_STOP){if(a.mixmode=this.mixMode,i&&(a.streamurl=i),this.mixMode===Ii.LiveTranscodingSingle){const c=this.singleParam;if(c){a.streamtype=c.streamType,c.sourceType===ai.LiveTranscodingShareScreen?a.sourcetype=Pi[c.sourceType]:a.sourcetype=Pi[ai.LiveTranscodingCamera];const o=[];c.userId&&o.push(c.userId),a.subspecusers=o}}else if(r===wt.MPU_TASK_TRANSACTION_START||r===wt.MPU_TASK_TRANSACTION_UPDATE){const c=this.mixParam;if(c){c.taskProfile&&(a.taskprofile=Om[c.taskProfile]);const o=c.encodeParam||new Zn(1280,720);let l=o.videoWidth,d=o.videoHeight;const h={};Object.keys(o).forEach(p=>{const f=o[p];f>0&&(h[p.toLowerCase()]=f)}),h.lowbitratehighquality=0,a.encodeparam=h,a.backgrounds=c.backgrounds.map(p=>p.toJson(l,d)),a.watermarks=c.watermarks.map(p=>p.toJson(l,d)),a.clockwidgets=c.clockWidgets.map(p=>p.toJson(l,d));const u=c.users.map(p=>p.userId);a.subspecusers=[...new Set(u)],a.layouts=[{audiomixcount:c.users.length,panes:c.users.map((p,f)=>p.toJson(f,l,d,c.mediaProcessMode))}],a.layoutids=["0"],a.cropmode=c.cropMode,a.backgroundcolor=Yn(c.backgroundColor),a.taskmode=c.mediaProcessMode}}}return a}}const Qn=s=>_(this,null,function*(){const r=new Uint8Array(160).fill(170),e=new TextEncoder().encode(s),t=yield window.crypto.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-1"}},!1,["sign"]),i=yield window.crypto.subtle.sign("HMAC",t,e);return Array.from(new Uint8Array(i)).map(n=>n.toString(16).padStart(2,"0")).join("")});class Lm{constructor(r){b(this,"authInfo");b(this,"slsReporter");this.slsReporter=r}doRequest(r,e){var c;const t=this.authInfo;if(!t)return Promise.reject(ar.LiveTranscodingErrorInvalidParam);const i=Nm[r],n={appid:t.appId,userid:t.userId,channelid:t.channelId,timestamp:t.timestamp,token:t.token,nonce:t.nonce?t.nonce:"",requestid:ze.createCallid(),tokensid:!1,session:(c=t.sessionId)!=null?c:ze.createCallid()},a=Object.keys(n).map(o=>`${o}=${encodeURIComponent(n[o])}`).join("&");return fetch(`https://gw.rtn.aliyuncs.com${i}?${a}`,{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:JSON.stringify(e)}).then(o=>o.status!==200?(this.slsReporter.reportTranscodingError(o.status,e.taskid||""),Promise.reject(new W(z.ERR_INNER,`transcoding request failed, status: ${o.status}`))):o).catch(o=>Promise.reject(new W(z.ERR_INNER,`transcoding request failed, err: ${o.message}`)))}setAuthInfo(r){this.authInfo=r}clear(){this.authInfo=void 0}startPublishLiveStream(r,e){return _(this,null,function*(){if(!this.authInfo)return Promise.reject(ar.LiveTranscodingErrorInvalidParam);const t=yield Qn(r.split("?")[0]),i=wt.MPU_TASK_TRANSACTION_UPDATE,n=e.toJson(i,this.authInfo,t,r);return this.doRequest(i,n)})}startPublishLiveStreamWithTaskId(r,e){return _(this,null,function*(){if(!this.authInfo)return Promise.reject(ar.LiveTranscodingErrorInvalidParam);const t=wt.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(t,this.authInfo,r);return this.doRequest(t,i)})}updatePublishLiveStream(r,e){return _(this,null,function*(){if(!this.authInfo)return Promise.reject(ar.LiveTranscodingErrorInvalidParam);const t=yield Qn(r.split("?")[0]),i=wt.MPU_TASK_TRANSACTION_UPDATE,n=e.toJson(i,this.authInfo,t,r);return this.doRequest(i,n)})}updatePublishLiveStreamWithTaskId(r,e){return _(this,null,function*(){if(!this.authInfo)return Promise.reject(ar.LiveTranscodingErrorInvalidParam);const t=wt.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(t,this.authInfo,r);return this.doRequest(t,i)})}stopPublishLiveStream(r){return _(this,null,function*(){if(!this.authInfo)return Promise.reject(ar.LiveTranscodingErrorInvalidParam);const e=yield Qn(r.split("?")[0]),t=wt.MPU_TASK_TRANSACTION_STOP,i=new Es().toJson(t,this.authInfo,e,r);return this.doRequest(t,i)})}stopPublishLiveStreamWithTaskId(r){if(!this.authInfo)return Promise.reject(ar.LiveTranscodingErrorInvalidParam);const e=wt.MPU_TASK_TRANSACTION_STOP,t=new Es().toJson(e,this.authInfo,r);return this.doRequest(e,t)}refreshAuthInfo(r){this.authInfo&&this.setAuthInfo(D(D({},this.authInfo),r))}}var ys=(s,r,e)=>new Promise((t,i)=>{var n=o=>{try{c(e.next(o))}catch(l){i(l)}},a=o=>{try{c(e.throw(o))}catch(l){i(l)}},c=o=>o.done?t(o.value):Promise.resolve(o.value).then(n,a);c((e=e.apply(s,r)).next())});function Fl(s,r){const e=new window.XMLHttpRequest;e.open("POST",`${s}?APIVersion=0.6.0`,!0),e.send(r)}function xm(s,r){try{if(r.length>=32768)return void Fl(s,r);(function(e,t){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${e}?APIVersion=0.6.0`,t)})(s,r)||Fl(s,r)}catch(e){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
335
+ `+e),console.error("Failed log data:",s))}}class Hl extends Ld{constructor(r){super(Object.assign({},r,{installUnloadHook:e=>{window.addEventListener("beforeunload",()=>{e()})},sendPayload:(e,t)=>ys(this,null,function*(){xm(e,t)})}))}useStsPlugin(r){this.getOpt().sendPayload=(e,t)=>ys(this,null,function*(){yield function(i,n,a){return ys(this,null,function*(){return new Promise(c=>ys(this,null,function*(){try{i=i.slice(0,-6);const{data:o,header:l}=yield a.process(i,n),d=new window.XMLHttpRequest;d.open("POST",i,!0);for(let h in l)d.setRequestHeader(h,l[h]);d.onreadystatechange=()=>{d.readyState===4&&(d.status===200||window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
336
+ `+d.status),console.error("Failed logdata:",i)),c())},d.send(o)}catch(o){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
337
+ `+o),console.error("Failed log data:",i))}}))})}(e,t,r)}),this.overwriteTransString(r)}}li(window,"SLS_Tracker",Hl);const Gr=class Gr{constructor(){b(this,"ntpClock");this.ntpClock=new Pe.Clock}static getInstance(){return Gr.instance||(Gr.instance=new Gr),Gr.instance}now(){return this.ntpClock.now()}};b(Gr,"instance");let qn=Gr;const Wl=()=>qn.getInstance(),{BrowserUtil:ea,SystenUtil:jl}=Pe;class Gl{constructor(){b(this,"tracker");b(this,"param");b(this,"msgCacheArr",[]);b(this,"index",0);b(this,"stsOpt");b(this,"slsToken");b(this,"ossToken");b(this,"ntpClock");this.ntpClock=Wl()}createTracker(){if(!this.tracker&&this.slsToken&&this.param){const r=this.slsToken;this.ossToken&&(this.param.ossbn=this.ossToken.bucket_name,this.param.ossep=this.ossToken.region_endpoint);const e=new Hl({host:r.region_endpoint,project:r.project,logstore:r.log_store_stats}),t={accessKeyId:r.access_key_id,accessKeySecret:r.access_key_secret,securityToken:r.security_token,refreshSTSToken:()=>{this.slsToken&&(t.accessKeyId=this.slsToken.access_key_id,t.accessKeySecret=this.slsToken.access_key_secret,t.securityToken=this.slsToken.security_token)}};this.stsOpt=t;const i=Ps(t);e.useStsPlugin(i),this.tracker=e,this.msgCacheArr.forEach((n,a)=>{var c,o;(o=this.tracker)==null||o.send(D(Q(D({},this.param),{stat_log_id:`${((c=this.param)==null?void 0:c.sesid)||"nosession"}-${a}`}),n))}),this.index=this.index+this.msgCacheArr.length,this.msgCacheArr=[]}}start(r){this.initParam(r),this.createTracker()}updateToken(r,e){this.slsToken=r,this.ossToken=e,this.createTracker()}stop(){this.tracker=void 0,this.param=void 0,this.msgCacheArr=[],this.index=0,this.stsOpt=void 0,this.slsToken=void 0,this.ossToken=void 0}sendReport(r){var t,i;let e;r.tm=Date.now();try{e=JSON.parse(JSON.stringify(D(Q(D({bt:ea.browserName||"unknown",ntptm:this.ntpClock.now(),ntpofs:this.ntpClock.now()-Date.now()},this.param),{stat_log_id:`${((t=this.param)==null?void 0:t.sesid)||"nosession"}-${this.index}`}),r)))}catch(n){}e&&(this.tracker?((i=this.tracker)==null||i.send(e),this.index++):this.msgCacheArr.push(e))}initParam(r){let e="";try{e=(localStorage==null?void 0:localStorage.getItem("AliRtcUUID"))||"",e||(e=Vt(),localStorage==null||localStorage.setItem("AliRtcUUID",e))}catch(t){}this.param||(this.param={apid:r.appId,usrid:r.userId,statsvrs:"0.6.1",evetid:0,sesid:r.sessionId,sessionId:r.sessionId,channelid:r.channelId,usrn:r.userId,osn:jl.systemName,osv:jl.systemVersion,deb:Up(),den:Lp(),udid:e,sdkvrs:ls,acs:"Unknown",cput:Nd(),dm:`${window.location.protocol}//${window.location.host}`,bt:ea.browserName,bv:ea.browserVersion,envir:"PRODUCT",args:"",instid:Vt()})}}const xe=(s,r=1,e=6e4,t=0)=>{let i=s;return i||(i=0),Math.min(e,Math.max(t,Math.round(i*r)))},Wt=(s,r,e=2e7,t=0)=>{let i=r;(!r||r<0||r>1e4)&&(i=1e3);let n=s;return n||(n=0),Math.min(e,Math.max(t,Math.round(n/(i/1e3))))},Fr=(s,r)=>{if(r===0||!r)return"0.00";let e=s;return(!e||e<0)&&(e=0),(e/r*100).toFixed(2)},zl=s=>s>=0&&s<=1?xe(Math.floor(32767*s),1,32767):0,Fe=(s,r)=>{var t,i,n;let e=((t=s._last)==null?void 0:t[r])||0;return s.ssrc&&((i=s._last)!=null&&i.ssrc)&&s.ssrc!==((n=s._last)==null?void 0:n.ssrc)&&(e=0),((s==null?void 0:s[r])||0)-e},Kl=(s,r)=>xe(Fe(s,r),1e3,1e4),Hr=(s,r=2e7)=>xe(s,1,r),Oi=class Oi{constructor(r){b(this,"engine");b(this,"logClient");b(this,"authInfo");b(this,"ntpClock");b(this,"customFields",{});this.logClient=new Gl,this.engine=r,this.ntpClock=Wl()}static getLogClient(){return this.staticClient||(this.staticClient=new Gl),this.staticClient}static reportOSSUpload(r,e,t=0){Oi.getLogClient().sendReport({errmsg:`${e}/${r}.log`,errtype:t,evetid:70017,sesid:r,sessionId:r,stat_log_id:`${r}-70017`})}setCustomFields(r){this.customFields=D(D({},this.customFields),r)}getCustomField(r){return this.customFields[r]}start(r){this.authInfo=r,this.logClient.start(r)}updateToken(r,e){this.logClient.updateToken(r,e),Oi.getLogClient().updateToken(r,e)}stop(){this.logClient.stop()}reportPublishAudio3A(r,e,t,i){const n={};let a=JSON.parse(i);n.publevel=a.capture_audio_cur_level_db||0,n.eleakrate=a.echo_leak_rate||0,n.playbw=a.render_bandwidth||-1,n.capbw=a.capture_bandwidth||-1,n.diff=a.diff||0,n.leak=a.leak||0,this.log({evetid:10070,traceid:t,calid:r,rmtid:"",args:this.data2String(D({calid:r,tckid:e||"audio3a",rmtid:"",traceid:t},n))})}reportPublishMonitor(r,e,t,i,n){if(!t||n.length<=0)return;const a=t===L.Audio,c={ctm:Math.floor(n[0].timestamp||0),src:n[0].ssrc||"",codec:n[0]._codec||""},o=[],l=[],d=[],h=[],u=[],p=[],f=[],m=[],g=[],S=[],v=[],E=[],T=[],R=[],y=[],C=[],w=[],A=[],P=[];try{if(n.forEach(M=>{var U,ce,ue,te,Re,He;if(!M||!M.timestamp)return;const I=(U=M._last)!=null&&U.timestamp?M.timestamp-M._last.timestamp:1e3,j=Fe(M,"bytesSent"),K=Fe(M,"headerBytesSent"),B=Wt(xe(j+K,8,2e7),I);o.push(B);const F=Wt(xe(j,8,2e7),I);l.push(F);const X=Wt(xe(K,8,2e7),I);d.push(X);const $=Fe(M,"packetsSent"),se=Wt($,I);h.push(se);const N=Fe(M,"packetsLost"),V=Wt(N,I);u.push(V);const x=Fr(N,$);if(p.push(x),a)(ce=M._source)!=null&&ce.audioLevel&&f.push(zl(M._source.audioLevel)),m.push(0);else{g.push(Kl(M,"totalEncodeTime")),S.push(Hr((ue=M._source)==null?void 0:ue.framesPerSecond,100)),v.push(Hr((te=M._source)==null?void 0:te.framesPerSecond,100)),E.push(Hr(M.framesPerSecond,100)),T.push(Hr((Re=M._source)==null?void 0:Re.height,4400)),R.push(Hr((He=M._source)==null?void 0:He.width,7700)),y.push(Hr(M.frameHeight,4400)),C.push(Hr(M.frameWidth,7700));const Ve=Fe(M,"totalPacketSendDelay");w.push(xe(Ve,1/(N||1),2e3));const je=Fe(M,"qpSum");A.push(xe(je,1/(M.framesPerSecond||1),51)),P.push(0)}}),c.sbr=o.join(","),c.mbrs=l.join(","),c.pbrs=d.join(","),c.ps=h.join(","),c.pl=u.join(","),c.plr=p.join(","),a){const M=(i==null?void 0:i.getSettings().sampleRate)||0;c.ailevel=f.join(","),c.arpc=m.join(","),c.arsr=M,c.aesr=M,c.publevel=-90,c.rawlevel=-90}else c.em=g.join(","),c.cfps=S.join(","),c.ifps=v.join(","),c.sfps=E.join(","),c.ih=T.join(","),c.iw=R.join(","),c.sh=y.join(","),c.sw=C.join(","),c.sd=w.join(","),c.aqp=A.join(","),c.caf=P.join(","),c.can=P.join(","),c.cav=l.join(","),c.ifimax=P.join(","),c.ifimin=P.join(","),c.efimax=P.join(","),c.efimin=P.join(","),c.sfimax=P.join(","),c.sfimin=P.join(","),c.apsnr=P.join(",")}catch(M){}this.log({evetid:10070,traceid:e,calid:r,rmtid:"",args:this.data2String(D({calid:r,tckid:t,rmtid:"",traceid:e},c))})}reportSubscribeMonitor(r,e,t,i,n){if(!i||!n||n.length<=0)return;const a=i===L.Audio,c={ctm:Math.floor(n[0].timestamp||0),src:n[0].ssrc||"",codec:n[0]._codec||""},o=[],l=[],d=[],h=[],u=[],p=[],f=[],m=[],g=[],S=[],v=[],E=[],T=[],R=[],y=[],C=[],w=[],A=[],P=[],M=[],I=[],j=[],K=[],B=[],F=[],X=[],$=[],se=[],N=[],V=[],x=[],U=[],ce=[],ue=[];try{n.forEach(te=>{var Te,at;if(!te||!te.timestamp)return;const Re=(Te=te._last)!=null&&Te.timestamp?te.timestamp-te._last.timestamp:1e3,He=Fe(te,"bytesReceived"),Ve=Fe(te,"headerBytesReceived"),je=Wt(xe(He+Ve,8,2e7),Re);o.push(je);const _e=Wt(xe(He,8,2e7),Re);l.push(_e);const Ue=Wt(xe(Ve,8,2e7),Re);d.push(Ue);const ye=Fe(te,"packetsReceived"),Ge=Wt(ye,Re);h.push(Ge);const Oe=Fe(te,"packetsLost"),mt=Wt(Oe,Re);u.push(mt);const At=Fr(Oe,ye);p.push(At);const Se=Fe(te,"jitterBufferDelay"),le=Fe(te,"jitterBufferEmittedCount");if(te.jitterBufferDelay&&te.jitterBufferEmittedCount){const re=xe(Se,1e3/le,1e4);f.push(re)}else f.push(0);const ae=Fe(te,"fecPacketsReceived");E.push(Fr(ae,ye));const Ie=Fe(te,"retransmittedPacketsReceived"),Ze=ye+Oe-Ie;if(g.push(Fr(ye-Ie,Ze)),S.push(Fr(Oe,Ze)),m.push(Fr(Ie,Ze)),v.push(Ze),ce.push(0),ue.push(""),a){R.push(zl(te.audioLevel));const re=((Ke,Qt)=>{var or,qt,Tr;return(((or=Ke==null?void 0:Ke._source)==null?void 0:or[Qt])||0)-(((Tr=(qt=Ke==null?void 0:Ke._last)==null?void 0:qt._source)==null?void 0:Tr[Qt])||0)})(te,"synthesizedSamplesEvents");y.push(re);const dt=Kl(te,"synthesizedSamplesDuration");C.push(dt);const It=Fr(dt,Re);T.push(It),w.push(0)}else{const re=(at=te._last)!=null&&at.totalInterFrameDelay?te.totalInterFrameDelay-te._last.totalInterFrameDelay:0;A.push(xe(re,1e3/(te.framesDecoded||30),500)),P.push(xe(te.framesPerSecond,1,100)),M.push(Fe(te,"framesReceived")),U.push(Fe(te,"framesRendered")),I.push(xe(te.frameHeight,1,4400)),j.push(xe(te.frameWidth,1,7700));const dt=Fe(te,"totalProcessingDelay");K.push(xe(dt,1e3/(te.framesDecoded||30),12e4));const It=Fe(te,"nackCount");F.push(It);const Ke=Fe(te,"pliCount");B.push(Ke);const Qt=Fe(te,"qpSum");X.push(xe(Qt,1/(te.framesPerSecond||1),51)),$.push(xe(te.framesDropped));const or=Fe(te,"totalFreezesDuration");se.push(xe(or,1e3,3e4));const qt=Fe(te,"jitterBufferEmittedCount"),Tr=Fe(te,"jitterBufferDelay");Tr&&qt?N.push(xe(Tr,1e3/qt,3e4)):N.push(0);const Li=Fe(te,"jitterBufferTargetDelay");Li&&qt?V.push(xe(Li,1e3/qt,3e4)):V.push(0);const _s=Fe(te,"jitterBufferMinimumDelay");_s&&qt?x.push(xe(_s,1e3/qt,3e4)):x.push(0)}}),c.rbr=o.join(","),c.mbrs=l.join(","),c.pbrs=d.join(","),c.pr=h.join(","),c.pl=u.join(","),c.plr=p.join(","),c.jd=f.join(","),c.fecr=E.join(","),c.retransr=m.join(","),c.baser=g.join(","),c.basel=S.join(","),c.recoverr=ce.join(","),c.alll=S.join(","),c.totalc=v.join(","),a?(c.er=T.join(","),c.aolevel=R.join(","),c.asrc=w.join(","),c.scnt=y.join(","),c.sdura=C.join(",")):(c.dm=A.join(","),c.dfps=P.join(","),c.rfps=M.join(","),c.rh=I.join(","),c.rw=j.join(","),c.fpt=ue.join(","),c.ns=F.join(","),c.pliss=B.join(","),c.aqp=X.join(","),c.ofimax=ce.join(","),c.ofimin=ce.join(","),c.dfimax=ce.join(","),c.dfimin=ce.join(","),c.rfimax=ce.join(","),c.rfimin=ce.join(","),c.vrstutter=se.join(","),c.cdm=N.join(","),c.tdm=V.join(","),c.pdm=x.join(","),c.ofps=U.join(","),c.dfbd=$.join(","))}catch(te){}this.log({evetid:10080,traceid:t,rmtid:e,calid:r,args:this.data2String(D({calid:r,rmtid:e,tckid:i,traceid:t},c))})}reportNetworkMonitor(r){if(r.length<=0)return;const e=[],t=[],i=[],n=[],a=[],c=[],o=[],l=[],d=[],h=[];r.forEach((p,f)=>{var g;if(!p.timestamp)return;const m=(g=p._last)!=null&&g.timestamp?p.timestamp-p._last.timestamp:1e3;e.push(xe(p.currentRoundTripTime,1e3)),t.push(xe(p.availableOutgoingBitrate,8,2e8)),i.push(Wt(xe(p.bytesSent,8,2e7),m,25e6)),n.push(Wt(xe(p.bytesReceived,8,2e7),m,25e6)),a.push(0),c.push(0),f%5==0&&(o.push(""),l.push(""),d.push(""),h.push(""))});const u={ctm:Math.floor(r[0].timestamp||0),rtt:e.join(","),bsps:i.join(","),brps:n.join(","),cpu:o.join(","),mem:l.join(","),sysmem:d.join(","),systotalmem:h.join(","),audioonly:this.engine.isAudioOnly()?1:0};this.log({evetid:10071,args:this.data2String(D({asb:t.join(","),abms:a.join(","),vbms:c.join(",")},u))}),this.log({evetid:10081,args:this.data2String(D({},u))})}reportLoopAudioDelay(r,e){var f;const{AIAgent:t={},AIGrtn:i={},AIPub:n={},AISub:a={},pub:c={},sub:o={},grtn:l={}}=e||{};if(Object.keys(t).length===0)return;let d=0;d=Object.keys(l).length?(c.vTotalCost||0)+(c.upRTTHalf||0)+(l.totalCost||0)+(o.downRTTHalf||0)+(o.vTotalCost||0):(c.vEncPlugCost||0)+((c.timestampRecv||0)-(c.timestamp||0))+(o.vJitterBufferDelay||0)+(o.vDecPlugCost||0);const h={};let u=0;for(let m=0;m<10;m++){const g=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${m}`,S=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${m}`,v=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${m}`;if(!l.hasOwnProperty(g))break;u+=l[g]||0,u+=l[S]||0,u+=l[v]||0,h[`_gnd${m}`]=`gnd[${m}]: {${this.data2String({gnirh:l[g]||0,gnbp:l[S]||0,gnpc:l[v]||0})}}`}const p={};for(let m=0;m<10;m++){const g=`aigrtninternalrtthalf_${m}`,S=`aigrtnbeforepacer_${m}`,v=`aigrtnpacercost_${m}`;if(!i.hasOwnProperty(g))break;p[`_lgnd${m}`]=`lgnd[${m}]: {${this.data2String({gnirh:i[g]||0,gnbp:i[S]||0,gnpc:i[v]||0})}}`}this.log({evetid:10073,args:this.data2String(Q(D({tdlms:d+(t.aiagenttotalcost||0),_:`aiqud:{${this.data2String(Q(D({uid:((f=this.authInfo)==null?void 0:f.userId)||"",sid:n.aAIClientScentenceId||0,quct:65535*(n.aAIClientQuestionTimestampHEAD||0)+(n.aAIClientQuestionTimestampTAIL||0),anct:65535*(n.aAIClientAnswerTimestampHEAD||0)+(n.aAIClientAnswerTimestampTAIL||0),casc:n.aAIClientSourceCost||0,camc:n.aAIClientMixerCost||0,caec:n.aAIClientEncoderCost||0,cantc:n.aIClientNetsdkThrCost||0,caqtc:n.aIClientQosThrCost||0,capc:n.aIClientPacerCost||0,cuphr:n.aIClientUpRTTHalf||0},p),{qgac:0,ldhr:l.ngxRtcSeiCumulativeDelayKeyDownRttHalf_0||0,larc:a.aAILinuxReceiveCost||0,lanqc:a.aAILinuxNeteqCost||0,larsc:a.aAILinuxRemoteSourceCost||0,lapmc:a.aAILinuxPlayMixerCost||0,lapc:a.aAILinuxPlayCost||0,lsdnc:a.aIClinetSmartDenoise||0,asrc:t.aiasrcost||0,llmc:t.aillmcost||0,ttsc:t.aittscost||0,aamc:t.aimutecost||0,aatc:t.aiagenttotalcost||0}))}};`,ssrc:r,tpd:0,scc:n.aAIClientSourceCost||0,mxc:n.aAIClientMixerCost||0,encc:n.aAIClientEncoderCost||0,netc:n.aIClientNetsdkThrCost||0,qostc:n.aIClientQosThrCost||0,pacerc:n.aIClientPacerCost||0,uphr:n.aIClientUpRTTHalf||0},h),{agac:u,dnhr:o.downRTTHalf||0,tsd:o.vTotalCost||0,rcc:a.aAILinuxReceiveCost||0,nqc:a.aAILinuxNeteqCost||0,rscc:a.aAILinuxRemoteSourceCost||0,plmxc:a.aAILinuxPlayMixerCost||0,plc:a.aAILinuxPlayCost||0,dvd:0}))})}reportJoin(r,e,t=""){var h,u;const{start:i,rs:n=0,re:a=0}=e,c=Date.now()-i,o=a-n;let l=0;n&&(l=n-i);let d=0;a&&(d=a-n),this.log({evetid:10010,args:this.data2String({sesid:((h=this.authInfo)==null?void 0:h.sessionId)||"",joitm:c,rslt:r,gslbtm:0,dnstm:0,avcftm:0,gslbrslt:0,dnsrslt:0,avcfrslt:0,mode:2,jrtc:o,usrn:(u=this.authInfo)==null?void 0:u.userId,mgt:"cdn",cttc:l,iptc:d,ndn:1,gslbloc:1,ccag:0,ucag:0,cpg:0,upg:0,tid:t})})}reportJoinConnection(r){this.log({evetid:20002,args:this.data2String(D({transretrynum:0,ldnstc:0,tcptc:0,ssltc:0,url:""},r))})}reportLeave(r,e,t){this.log({evetid:10020,args:this.data2String({lvetm:r,rslt:e,tid:t})})}reportPublish(r,e,t,i,n,a,c,o,l,d,h,u){this.log({evetid:r?10032:10030,calid:t,tm:u,args:this.data2String({calid:t,url:e,isvl:i?1:0,isvs:n?1:0,isvss:a?1:0,isaudio:c?1:0,rslt:o,tid:"123",pubtm:Date.now()-h,pctid:l,pubtid:d,isvp:0,isarecording:0,isad:0,isdc:0,pubretry:0,pbrttimes:0})})}reportPublishFirstPacket(r,e,t,i,n,a,c,o,l){const d=Date.now();this.log({evetid:r?10033:10031,calid:e,args:this.data2String({calid:e,fpst:d-t,tckid:a,est:t,pctid:c,pubtid:o,totaltm:d-n,jorm:l===Xt.JOIN_CHANNEL?1:0,cptc:0,sptc:i-t,iptc:0,ipc2fptc:0,dctc:0,patc:0})})}reportUnpublish(r,e,t,i){var n;this.log({evetid:10040,args:this.data2String({calid:r,unpubtm:e,rslt:t,tid:i,sesid:((n=this.authInfo)==null?void 0:n.sessionId)||""})})}reportSubscribe(r,e,t,i,n,a,c,o,l,d,h){this.log({evetid:10050,calid:r,rmtid:e,tm:h,args:this.data2String(D({calid:r,rmtid:e,isvl:t?1:0,isvs:i?1:0,isvss:n?1:0,isaudio:a?1:0,rslt:c,tid:o,subtm:l,isvp:0,isaplaying:0,isad:0,isdc:0,subretry:0,sbrttimes:0},d))})}reportSubscribeFirstPacket(r,e,t,i,n){this.log({evetid:r?10054:10051,calid:e,rmtid:t,args:this.data2String(D({calid:e,rmtid:t,tckid:i,cptc:0,iptc:0,ipc2fptc:0,dctc:0,patc:0},n))})}reportSubscribeFirstFrame(r,e,t,i,n){this.log({evetid:r?10055:10052,calid:e,rmtid:t,args:this.data2String(D({calid:e,rmtid:t,tckid:i},n))}),this.log({evetid:r?10058:10057,args:this.data2String(D({calid:e,rmtid:t,tckid:i},n))})}reportUnsubscribe(r,e,t,i,n){this.log({evetid:10060,calid:r,args:this.data2String({calid:r,rmtid:e,unsubtm:t,rslt:i,tid:n})})}reportMute(r,e,t){this.log({evetid:11030,args:this.data2String({calid:r,rmtid:"",enable:e?1:0,mt:t})})}reportRoleUpdate(r,e){this.log({evetid:11040,args:this.data2String({or:r||"",nr:e,ctm:Date.now(),rslt:0})})}reportRoleUpdateResult(r,e,t,i){this.log({evetid:11041,args:this.data2String({or:r||"",nr:e,ctm:t,rslt:i})})}reportVideoProfile(r){this.log({evetid:20074,args:this.data2String({pf:r,tckid:"sophon_camera_large"})})}reportScreenProfile(r){this.log({evetid:20074,args:this.data2String({pf:r,tckid:"sophon_screenshare"})})}reportError(r){this.log({evetid:10091,args:this.data2String({rslt:(r==null?void 0:r.code)||-1})})}reportWarning(r){this.log({evetid:10092,args:this.data2String({rslt:-1,errmsg:r})})}reportRoomServerEvent(r,e,t,i){this.log({evetid:20005,args:this.data2String({calid:"",rmtid:"",rt:r?0:1,dr:r?"s":"r",mt:e,ri:t,cs:1,srt:Date.now(),rspc:(i==null?void 0:i.code)||"",mc:JSON.stringify(i)})})}reportTranscodingError(r,e){this.log({evetid:10101,args:this.data2String({rslt:r,taskid:e})})}reportBye(r){var e;this.log({evetid:10093,args:this.data2String({rslt:r,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportAudio(r,e,t){var i;this.log({evetid:80013,args:this.data2String({rslt:r?-1:0,adm:1,adt:0,adr:r?2:0,acms:e,adrpn:t})}),this.log({evetid:80014,args:this.data2String({sesid:((i=this.authInfo)==null?void 0:i.sessionId)||"",rslt:r?-1:0,adm:1,adt:0,adr:r?2:0,acms:e,adrpn:t})})}reportScreen(r,e){var t,i,n,a;this.log({evetid:90013,args:this.data2String({rslt:r?-1:0,vcms:e,vde:(t=r==null?void 0:r.code)!=null?t:-1,sesid:((i=this.authInfo)==null?void 0:i.sessionId)||""})}),this.log({evetid:90014,args:this.data2String({rslt:r?-1:0,vcms:e,vde:(n=r==null?void 0:r.code)!=null?n:-1,sesid:((a=this.authInfo)==null?void 0:a.sessionId)||""})})}reportScreenStop(r){this.log({evetid:90019,args:this.data2String({rslt:r?r.code||-1:0})}),this.log({evetid:90020,args:this.data2String({rslt:r?r.code||-1:0})})}reportSwitchCamera(r){var e;this.log({evetid:90025,args:this.data2String({rslt:0,td:r,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportPublishProfile(r,e){this.log({evetid:10201,args:this.data2String(D({tckid:r},e))})}reportSDKCreated(r){this.log({evetid:70011,createtm:Date.now()-r,tm:r})}reportJoinInvoked(r){this.log({evetid:70012,jnnonce:r.nonce||"",jntoken:r.token||"",jntm:r.timestamp||""})}reportJoinResult(r){this.log({evetid:70013,rslt:r?r.code||-1:0,dnsrslt:0})}reportSTSResult(r,e){this.log({evetid:70014,rslt:r,asty:1,reqtm:Date.now()-e})}reportLeaveInvoked(){this.log({evetid:70015})}reportSEIMessage(r,e,t,i,n){this.log({evetid:40301,args:this.data2String({tm:Date.now(),sei_pt:r,sei_len:e,sei_rep:t,sei_delay:i,sei_key:n})})}reportConnectionLatencyEvent(r,e,t,i,n,a,c=!1){const o={ageniid:this.getCustomField("ageniid")},l=D({tm:n||Date.now(),ntptm:a||this.ntpClock.now(),stage:r,status:e,calid:t,tckid:i,cltp:1,http:c?1:0},o);this.log({evetid:12001,args:this.data2String(l)})}log(r){r&&(r.tm=r.tm||new Date().getTime(),O.debug("[ConsoleLogger]","log",r),this.logClient.sendReport(r))}data2String(r){let e="";for(let t in r)e.length&&(e+="&"),e+=t.startsWith("_")?r[t]:`${t}=${r[t]}`;return e}};b(Oi,"staticClient");let ta=Oi;const ci=class ci extends de{constructor(e){super();b(this,"ws");b(this,"socketStatus",0);b(this,"wsUrl","");b(this,"lastConnectStartTime",0);b(this,"connectRetryMinTimeGap",5e3);b(this,"shouldReconnect",!0);b(this,"connectRetryCount",0);b(this,"gotErr",!1);b(this,"closedByInvoke",!0);b(this,"isReconnecting",!1);b(this,"networkAvailableChecked",!0);b(this,"reconnectTimeoutId",0);e&&(this.connectRetryMinTimeGap=e),this.onOpen=this.onOpen.bind(this),this.onMessage=this.onMessage.bind(this),this.onError=this.onError.bind(this),this.onClose=this.onClose.bind(this)}get connectUrl(){return this.wsUrl}get connectStatus(){return this.socketStatus}start(e){this.wsUrl=e,this.initWebSocket()}send(e){return!(!this.ws||this.socketStatus!==2)&&(this.ws.send(JSON.stringify(e)),!0)}close(){this.closedByInvoke=!0,this.uninitWebsocket()}markShouldReconnect(e){this.shouldReconnect=e}reconnect(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.emit("onWillReconnect"),this.shouldReconnect?(this.emit("onReconnectStart"),this.isReconnecting=!0,this.initWebSocket()):this.emit("onConnectFail")}onOpen(e){O.info(`[${ci.logName}]`,"onOpen"),this.socketStatus=2,this.connectRetryCount=0,this.shouldReconnect=!0,this.networkAvailableChecked=!1,this.closedByInvoke=!1,this.gotErr=!1,this.isReconnecting=!1,this.emit("onOpen",e)}onMessage(e){this.emit("onMessage",e)}onError(e){this.isReconnecting&&this.emit("onReconnectFail",e),this.emit("onError",e),this.isReconnecting=!1,this.socketStatus!==2&&ze.isNetworkAvailable().then(t=>{t&&console.error(ci.logName,"onError, Network is available, token may be invalid")})}onClose(e){return _(this,null,function*(){if(this.closedByInvoke)this.socketStatus=0;else{if(O.info(`[${ci.logName}]`,`onClose, code: ${e.code}, reason: ${e.reason}, status: ${status}, retryCount: ${this.connectRetryCount}`),(yield ze.isNetworkAvailable())&&!this.networkAvailableChecked)return this.reconnect(),void(this.networkAvailableChecked=!0);if(this.connectRetryCount||this.emit("onNetworkError"),!this.reconnectTimeoutId){this.connectRetryCount+=1;const t=Date.now()-this.lastConnectStartTime;t>=this.connectRetryMinTimeGap?this.reconnect():this.reconnectTimeoutId=window.setTimeout(()=>{this.reconnect()},this.connectRetryMinTimeGap-Math.max(0,t))}this.socketStatus=0,this.emit("onClose",e)}})}initWebSocket(){this.uninitWebsocket(),this.socketStatus=1,this.lastConnectStartTime=Date.now(),this.ws=new WebSocket(this.wsUrl),this.ws.addEventListener("open",this.onOpen),this.ws.addEventListener("message",this.onMessage),this.ws.addEventListener("error",this.onError),this.ws.addEventListener("close",this.onClose)}uninitWebsocket(){this.ws&&(this.ws.removeEventListener("open",this.onOpen),this.ws.removeEventListener("message",this.onMessage),this.ws.removeEventListener("error",this.onError),this.ws.removeEventListener("close",this.onClose),this.ws.readyState!==WebSocket.CLOSED&&this.ws.close(),this.ws=void 0,this.socketStatus=0)}};b(ci,"logName","Socket");let ra=ci;const Nt=class Nt extends de{constructor(e,t,i,n,a,c){super();b(this,"authInfo");b(this,"userName");b(this,"channelProfile");b(this,"clientRole");b(this,"slsReporter");b(this,"wsClient");b(this,"packageCreator");b(this,"keepAliveTimer",0);b(this,"lastKeepAliveResponseTime",0);b(this,"maxConnectRetryDuration",90);b(this,"packageCache",new Map);b(this,"isFirstConnect",!0);b(this,"aliveChecker",0);b(this,"reconnectData");b(this,"joinChannelExtraData");b(this,"onePcManager");this.authInfo=e,this.userName=t,this.packageCreator=new Ei(e,t),this.channelProfile=i,this.clientRole=n,this.slsReporter=a,c&&(this.maxConnectRetryDuration=c),this.wsClient=new ra,this.wsClient.on("onOpen",this.onOpen.bind(this)),this.wsClient.on("onMessage",this.onMessage.bind(this)),this.wsClient.on("onError",this.onError.bind(this)),this.wsClient.on("onClose",this.onClose.bind(this)),this.wsClient.on("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.on("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.on("onNetworkError",this.onNetworkError.bind(this)),this.wsClient.on("onWillReconnect",this.onWillReconnect.bind(this)),this.wsClient.on("onReconnectStart",this.onReconnectStart.bind(this)),this.wsClient.on("onReconnectFail",this.onReconnectFail.bind(this))}initOnePc(e){this.onePcManager=e,this.packageCreator=e.packageCreator,this.onePcManager.on("onMessage",this.onMessage.bind(this))}send(e){this.onePcManager?this.onePcManager.send(e):this.wsClient.send(e)}get retryCount(){return this.wsClient.connectRetryCount}destroy(){this.lastKeepAliveResponseTime=0,this.close()}start(e,t){this.joinChannelExtraData=t,this.wsClient.start(e)}startKeepAlive(){this.keepAliveTimer===0&&(this.keepAliveTimer=window.setInterval(()=>{let e=this.packageCreator.createKeepAlivePackage();this.sendPackage(e)},5e3)),this.checkAlive()}stopKeepAlive(){this.keepAliveTimer!==0&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=0),this.aliveChecker&&(window.clearTimeout(this.aliveChecker),this.aliveChecker=0)}sendPkgCache(){this.packageCache.forEach(e=>{this.send(e)})}leave(){let e=this.packageCreator.createLeavePackage();this.sendPackage(e)}reportStatus(e){let t=this.packageCreator.createStatusPackage(e);this.sendPackage(t)}publish(e){const l=e,{l1ip:t}=l,i=jt(l,["l1ip"]);let n=this.packageCreator.createPublishPackage();n.data.users=[],n.data.l1ip=t,i.subscribe.signal=this.wsClient.connectUrl;const{tracks:a,resume:c}=i;let o="7.3.0-beta.2";o&&(o=o.split("-")[0]),a.forEach(d=>{const{codec:h,ssrc:u}=d;d.userdata=JSON.stringify({sdk_version:o,codec:h}),d.ssrc=`${u}`,c&&(d.attr={reason:"reconnect"})}),n.data.users.push(i),this.sendPackage(n)}roleUpdate(e){let t=this.packageCreator.createRoleUpdatePackage();t.data.clientrole=e,this.sendPackage(t)}refreshUrl(e){const t=this.packageCreator.createRefreshUrlPackage();t.data=D(Q(D({},t.data),{sessionid:t.header.sessionid}),e),this.sendPackage(t)}refreshAuthInfo(e){this.authInfo=e,this.packageCreator.refreshAuthInfo(e)}close(){var e;O.info(`[${Nt.logName}] close`),this.stopKeepAlive(),(e=this.onePcManager)==null||e.off("onMessage"),this.onePcManager=void 0,this.wsClient.off("onOpen",this.onOpen.bind(this)),this.wsClient.off("onMessage",this.onMessage.bind(this)),this.wsClient.off("onError",this.onError.bind(this)),this.wsClient.off("onClose",this.onClose.bind(this)),this.wsClient.off("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.off("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.off("onReconnectStart"),this.wsClient.off("onReconnectFail"),this.wsClient.close()}sendPackage(e){[Qe.KEEPALIVE,Qe.RECONNECT,Qe.JOINCHANNEL].includes(e.msgtype)||this.packageCache.set(e.tid,e),this.send(e),e.msgtype!==Qe.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!0,e.msgtype,e.tid,e)}updateReconnectData(e){this.reconnectData=e}onOpen(){if(O.info(`[${Nt.logName}] onOpen`),this.isFirstConnect){let e=this.packageCreator.createJoinPackage(this.joinChannelExtraData);e.data.configure={channelprofile:this.channelProfile},this.channelProfile!==Jt.AliRtcSdkInteractiveLive&&this.channelProfile!==Jt.AliRtcSdkInteractiveWithLowLatencyLive||(e.data.configure.clientrole=this.clientRole),this.sendPackage(e)}else{this.stopKeepAlive();const e=this.packageCreator.createReconnectPackage(this.reconnectData);this.sendPackage(e)}}onMessage(e){try{let t=JSON.parse(e.data);this.packageCache.delete(t.tid),this.onRecvMessage(t),t!=null&&t.msgtype&&(t==null?void 0:t.msgtype)!==Qe.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!1,t.msgtype,t.tid,t)}catch(t){O.warn(`[${Nt.logName}] onMessage err`,t,e)}}onError(e){O.warn(`[${Nt.logName}] onError`,e),this.isFirstConnect&&this.onConnectFail()}onConnectFail(){O.warn(`[${Nt.logName}] onConnectFail`);const e=new W(z.ERR_INNER,"Signaling connect failed.");this.isFirstConnect?this.emit("onJoinChannelResult",e):this.emit("onConnectFail",e)}onAuthInvalid(){O.warn(`[${Nt.logName}] onAuthInvalid`),this.isFirstConnect&&this.emit("onAuthInvalid")}onNetworkError(){O.warn(`[${Nt.logName}] onNetworkError`);const e=new W(z.ERR_INNER,"Network error, signaling connect failed.");this.emit("onNetworkError",e)}onClose(e){O.info(`[${Nt.logName}] onClose`,e),this.stopKeepAlive()}onKeepAliveRsp(){this.emit("onKeepAliveRsp"),this.lastKeepAliveResponseTime=Date.now(),this.checkAlive()}onWillReconnect(){this.lastKeepAliveResponseTime||(this.lastKeepAliveResponseTime=Date.now()),Date.now()-this.lastKeepAliveResponseTime>1e3*this.maxConnectRetryDuration&&this.wsClient.markShouldReconnect(!1)}onReconnectStart(){this.emit("onReconnectStart")}onReconnectFail(){this.emit("onReconnectFail",new W(z.ERR_INNER,"signaling reconnect failed."))}checkAlive(){window.clearTimeout(this.aliveChecker),this.aliveChecker=window.setTimeout(()=>{O.info(`[${Nt.logName}] not alive, reconnect`),this.stopKeepAlive(),this.emit("onReconnectStart"),this.wsClient.reconnect()},15e3)}onRecvMessage(e){switch(e.msgtype!==Qe.KEEPALIVE&&O.info(`[${Nt.logName}] recv msg: ${e.msgtype}`),e.msgtype){case Qe.JOINCHANNEL:this.onJoinResult(e);break;case Qe.KEEPALIVE:this.onKeepAliveRsp();break;case Qe.PUBLISH:this.onPublishResult(e);break;case Qe.NOTIFYJOIN:this.onNotifyJoin(e);break;case Qe.NOTIFYSTATUS:this.onNotifyStatus(e);break;case Qe.LEAVECHANNEL:this.onLeaveResult(e);break;case Qe.NOTIFYLEAVE:this.onNotifyLeave(e);break;case Qe.NOTIFYPUBLISH:this.onNotifyPublish(e);break;case Qe.STATUSREPORT:this.onStatusReport(e);break;case Qe.BYE:this.onBye(e);break;case Qe.ROLEUPDATE:this.onRoleUpdateResult(e);break;case Qe.REFRESHURL:this.onRefreshUrlResult(e);break;case Qe.RECONNECT:this.onReconnectResult(e);break;default:this.onUnknownMessage(e)}}onJoinResult(e){this.isFirstConnect=!1,this.emit("onJoinChannelResult",e)}onLeaveResult(e){this.emit("onLeaveResult",e.code,e.tid)}onPublishResult(e){this.emit("onPublishResult",e.code,e.tid,e.description)}onRoleUpdateResult(e){this.emit("onRoleUpdateResult",e.code,e.tid,e.description)}onRefreshUrlResult(e){this.emit("onRefreshUrlResult",e)}onReconnectResult(e){if(e.code===200)this.sendPkgCache(),this.startKeepAlive(),this.emit("onReconnectSuccess",e.data.users);else{const t=new W(z.ERR_INNER,`reconnect failed, code: ${e.code};description: ${e.description}`);e.code===403&&(t.code=403),this.emit("onReconnectFail",t),this.close()}}onNotifyJoin(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.send(t),e&&e.data&&e.data.users&&this.emit("onNotifyJoin",e.data.users)}onNotifyStatus(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.send(t),e.data&&e.data.status&&e.data.status.length&&this.emit("onNotifyStatus",e.data.status)}onNotifyLeave(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyLeave",e.data.users)}onNotifyPublish(e){let t=this.packageCreator.createResponsePackage(e.tid,e.msgtype);this.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyPublish",e.data.users)}onStatusReport(e){this.emit("onStatusReport",e.code,e.tid,e.description)}onBye(e){this.stopKeepAlive(),this.emit("onBye",e.reason,e.description)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}};b(Nt,"logName","RSMessageCenter");let Ts=Nt;var Vm=Object.defineProperty,Um=Object.getOwnPropertyDescriptor,ia=(s,r,e,t)=>{for(var i,n=t>1?void 0:t?Um(r,e):r,a=s.length-1;a>=0;a--)(i=s[a])&&(n=(t?i(r,e,n):i(n))||n);return t&&n&&Vm(r,e,n),n};const Cs=(Rt=class extends de{constructor(e,t,i,n=Kt.prod){super();b(this,"messageCenter");b(this,"authInfo");b(this,"userName");b(this,"channelProfile");b(this,"clientRole");b(this,"slsReporter");b(this,"reconnectData");b(this,"roomServerUri","");this.channelProfile=e,this.clientRole=t,this.slsReporter=i,this.reconnectData={role:{channelprofile:e,clientrole:t}};const a=n===Kt.pre?qr.pre:qr.prod;this.roomServerUri=`wss://${a}/roomserver/v1/ws`}updateReconnectData(e){var t;this.reconnectData=e,(t=this.messageCenter)==null||t.updateReconnectData(this.reconnectData)}reset(){O.info("[roomsig] reset"),this.messageCenter&&(this.messageCenter.destroy(),this.messageCenter=void 0),this.authInfo=void 0}initOnePc(e){this.messageCenter=new Ts(e.authInfo,e.userName,this.channelProfile,this.clientRole,this.slsReporter),this.messageCenter.initOnePc(e),this.initMessageCenter()}join(e,t,i,n){return _(this,null,function*(){return new Promise((a,c)=>{const o={};this.authInfo=e,this.userName=t,this.messageCenter=new Ts(e,t,this.channelProfile,this.clientRole,this.slsReporter,i),this.initMessageCenter(),this.messageCenter.once("onJoinChannelResult",d=>{var h,u,p;if(O.info(`[${Rt.logName}]`,"join result: ",d),o.taskretrynum=((h=this.messageCenter)==null?void 0:h.retryCount)||0,d.code==200){(u=this.messageCenter)==null||u.sendPkgCache(),(p=this.messageCenter)==null||p.startKeepAlive();let f=d.data;f.tid=d.tid,f.users=d.data.users,f.timestamp=d.timestamp,o.est&&(o.joinconnecttc=Date.now()-o.est),this.slsReporter.reportJoinConnection(o),a(f)}else this.reset(),c(this.handleSignalError(d.code,d.reason,z.ERR_JOIN_CHANNEL_FAILED))}),this.messageCenter.once("onAuthInvalid",()=>{this.reset(),c(new W(z.ERR_JOIN_BAD_TOKEN,"join failed because authentication failed"))}),O.info(`[${Rt.logName}]`,"start ws connecting roomserver and auto join when connected");const l={appid:this.authInfo.appId,channelid:this.authInfo.channelId,userid:this.authInfo.userId,nonce:this.authInfo.nonce||"",timestamp:this.authInfo.timestamp,token:this.authInfo.token,authtype:"app",tid:Vt()};e.role&&(l.tokenrole=e.role),o.est=Date.now(),this.messageCenter.start(this.roomServerUri+"?"+ze.queryingParam(l),n)})})}leave(){return O.info("[roomsig] leave .."),new Promise((e,t)=>{this.messageCenter?(this.messageCenter.on("onLeaveResult",(i,n)=>{O.info(`[${Rt.logName}]`,"recv leave response "+i),i===200?(this.updateReconnectData(),this.reset(),e({tid:n})):t(this.handleSignalError(i,"leave error"))}),O.info(`[${Rt.logName}]`,"send leave request"),this.messageCenter.leave()):(O.info(`[${Rt.logName}]`,"no message center, ok to leave"),e({tid:""}))})}publish(e){return new Promise((t,i)=>{var n;this.messageCenter?(this.messageCenter.once("onPublishResult",(a,c,o)=>{O.info(`[${Rt.logName}]`,"recv pubish response "+a),a===200?(this.updateReconnectData(Q(D({},this.reconnectData),{publish:{users:[e]}})),t({tid:c})):i(this.handleSignalError(a,`publish error, ${o}`))}),this.authInfo&&(e.sessionid=(n=this.authInfo.sessionId)!=null?n:""),e.callid||(e.callid=Vt()),O.info(`[${Rt.logName}]`,"assign callid "+e.callid+" and send publish request"),this.messageCenter.publish(e)):i(this.handleSignalError(-1,"publish error, no message center"))})}roleUpdate(e){return new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRoleUpdateResult",(n,a,c)=>{var o,l;O.info(`[${Rt.logName}]`,"recv role update response "+n),n===200?((l=(o=this.reconnectData)==null?void 0:o.role)!=null&&l.clientrole&&(this.reconnectData.role.clientrole=e,this.updateReconnectData(this.reconnectData)),t({tid:a})):i(this.handleSignalError(n,`role update error, ${c}`))}),this.messageCenter.roleUpdate(e)):i(this.handleSignalError(-1,"role update error, no message center"))})}setChannelProfile(e){this.channelProfile=e}refreshUrl(e){return O.info(`[${Rt.logName}]`,"refreshUrl .."),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRefreshUrlResult",n=>{const{code:a,description:c,data:o={}}=n||{};O.info("recv refresh url response "+a),a===200?t(o):i(this.handleSignalError(a,`refresh url error, ${c}`))}),O.info("send refresh url request"),this.messageCenter.refreshUrl(e)):i(this.handleSignalError(-1,"refresh url error, no message center"))})}reportStatus(e){return O.info(`[${Rt.logName}]`,"reportStatus "+e),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.once("onStatusReport",(n,a)=>{n===200?t():i(new W(n,a))}),this.messageCenter.reportStatus(e)):i(new W(-1,"No messageCenter"))})}handleSignalError(e,t,i=z.ERR_INNER){return new W(i,`signal error: code - ${e}; description - ${t}`)}refreshAuthInfo(e){return _(this,null,function*(){var t;this.authInfo&&(this.authInfo=e,(t=this.messageCenter)==null||t.refreshAuthInfo(this.authInfo))})}initMessageCenter(){var e,t,i,n,a,c,o,l,d,h,u,p,f;(e=this.messageCenter)==null||e.on("onKeepAliveRsp",()=>{this.emit("onKeepAliveRsp")}),(t=this.messageCenter)==null||t.on("onNotifyJoin",m=>{this.emit("onNotifyJoin",m)}),(i=this.messageCenter)==null||i.on("onNotifyStatus",m=>{this.emit("onNotifyStatus",m)}),(n=this.messageCenter)==null||n.on("onNotifyLeave",m=>{this.emit("onNotifyLeave",m)}),(a=this.messageCenter)==null||a.on("onNotifyPublish",m=>{this.emit("onNotifyPublish",m)}),(c=this.messageCenter)==null||c.on("onBye",(m,g)=>{this.emit("onBye",m,g)}),(o=this.messageCenter)==null||o.on("onReconnectStart",()=>{this.emit("onReconnectStart")}),(l=this.messageCenter)==null||l.on("onReconnectSuccess",m=>{this.emit("onReconnectSuccess",m)}),(d=this.messageCenter)==null||d.on("onReconnectFail",m=>{this.emit("onReconnectFail",m)}),(h=this.messageCenter)==null||h.on("onConnectFail",m=>{this.emit("onConnectFail",m),this.reset()}),(u=this.messageCenter)==null||u.on("onNetworkError",m=>{this.emit("onNetworkError",m)}),(p=this.messageCenter)==null||p.on("onAuthInvalid",()=>{this.emit("onAuthInvalid")}),(f=this.messageCenter)==null||f.on("onUnknownMessage",m=>{this.emit("onUnknownMessage",m)})}},b(Rt,"logName","RoomServerSignaling"),Rt);ia([k()],Cs.prototype,"join",1),ia([k()],Cs.prototype,"publish",1),ia([k()],Cs.prototype,"roleUpdate",1);let Jl=Cs;const Bm=6e5,Ni=class Ni extends de{constructor(e,t){super();b(this,"env");b(this,"authInfo");b(this,"timer");b(this,"slsReporter");b(this,"expiration",0);b(this,"skipTime",0);b(this,"requestToken",()=>_(this,null,function*(){if(this.skipTime=0,!this.authInfo)return;const{appId:e,channelId:t,userId:i,nonce:n="",token:a,timestamp:c,sessionId:o,role:l}=this.authInfo;let d="https://gw.rtn.aliyuncs.com";this.env===Kt.pre&&(d="https://pgw.rtn.aliyuncs.com");const h=`${d}/gslb/v1/stsupdate?appid=${e}&channelid=${t}&userid=${i}&nonce=${n}&token=${a}&timestamp=${c}&session=${o}${l?`&tokenrole=${l}`:""}&slstoken=true&osstoken=true&tokensid=false`,u=Date.now();fetch(h).then(p=>p.json()).then(p=>{var f,m;if(p.code!==0)throw new Error;{const g=(f=p.data)==null?void 0:f.oss,S=(m=p.data)==null?void 0:m.sls;this.expiration=g.expiration||S.expiration,this.emit("onTokenUpdate",g,S),O.event(`[${Ni.logName}]`,"getToken",g,S)}this.slsReporter.reportSTSResult(200,u)}).catch(p=>{this.slsReporter.reportSTSResult(-1,u),O.error(`[${Ni.logName}]`,"getToken",p.message)})}));this.slsReporter=e,this.env=t}refreshAuthInfo(e){this.authInfo=e}startSTSUpdate(e){this.authInfo=e,this.requestToken(),this.timer&&clearInterval(this.timer),this.timer=window.setInterval(()=>{this.expiration&&Math.floor((Date.now()+9e5)/1e3)<this.expiration&&this.skipTime<12?this.skipTime+=1:this.requestToken()},Bm)}clear(){this.timer&&clearInterval(this.timer)}};b(Ni,"logName","StsManager");let sa=Ni;var Fm=Object.defineProperty,Hm=Object.getOwnPropertyDescriptor;class na extends de{constructor(e,t,i,n=Kt.prod){super();b(this,"signaling");b(this,"authInfo");b(this,"userName");b(this,"channelProfile");b(this,"clientRole");b(this,"env",Kt.prod);b(this,"maxSignalingReconnectDuration");b(this,"stsManager");b(this,"slsReporter");this.channelProfile=e,this.clientRole=t,this.env=n,this.slsReporter=i,this.stsManager=new sa(i,n)}reset(){var e;O.info("[signalingmanager] reset"),(e=this.signaling)==null||e.reset(),this.stsManager.clear(),this.signaling=void 0,this.authInfo=void 0}initOnePc(e){e?(this.signaling=new Jl(this.channelProfile,this.clientRole,this.slsReporter,this.env),this.signaling.initOnePc(e),this.authInfo=e.authInfo,this.initSignaling()):(this.signaling=void 0,this.authInfo=void 0)}join(e,t=e.userId,i,n,a){return this.maxSignalingReconnectDuration=i,this.userName=t,new Promise((c,o)=>{this.signaling?o(new W(z.ERR_JOIN_ALREADY_JOINED,"already joined")):(O.info("[signalingmanager] create signaling"),this.signaling=new Jl(this.channelProfile,this.clientRole,this.slsReporter,this.env),this.initSignaling(),n&&(n.rs=Date.now()),this.signaling.join(e,t,i,a).then(l=>{this.authInfo=e,n&&(n.re=Date.now()),c(l)}).catch(l=>{this.reset(),o(l)}),this.stsManager.startSTSUpdate(e))})}retryJoin(){const e=this.authInfo;this.reset(),e&&this.join(e,this.userName,this.maxSignalingReconnectDuration)}leave(){return new Promise((e,t)=>{this.signaling?this.signaling.leave().then(i=>{this.reset(),e(i)}).catch(i=>{t(i)}):e({tid:""})})}publish(e){return new Promise((t,i)=>{var n;this.signaling&&this.authInfo?(e.userid=this.authInfo.userId,e.displayname=(n=this.userName)!=null?n:this.authInfo.userId,this.signaling.publish(e).then(a=>{t(a)}).catch(a=>{i(a)})):i(new W(z.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL,"no signaling"))})}reportStatus(e){return new Promise((t,i)=>{this.signaling?this.signaling.reportStatus(e).then(()=>{t()}).catch(n=>{i(n)}):i(new W(-1,"no signaling"))})}setClientRole(e){return _(this,null,function*(){const t=this.clientRole;if(!this.signaling)return void(this.clientRole=e);const i=Date.now();try{const n=yield this.signaling.roleUpdate(e);return this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-i,0),n}catch(n){this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-i,n.code||-1)}})}setChannelProfile(e){this.signaling?this.signaling.setChannelProfile(e):this.channelProfile=e}refreshUrl(e){return this.signaling?this.signaling.refreshUrl(e):Promise.reject(new W(z.ERR_SDK_INVALID_STATE,"should join first"))}refreshAuthInfo(e){return _(this,null,function*(){var t;try{this.authInfo&&(this.authInfo=D(D({},this.authInfo),e),(t=this.signaling)==null||t.refreshAuthInfo(this.authInfo),this.stsManager.refreshAuthInfo(this.authInfo))}catch(i){throw i}})}initSignaling(){var e,t,i,n,a,c,o,l,d,h,u,p,f,m;(e=this.signaling)==null||e.on("onKeepAliveRsp",this.onKeepAliveRsp.bind(this)),(t=this.signaling)==null||t.on("onNotifyJoin",this.onNotifyJoin.bind(this)),(i=this.signaling)==null||i.on("onNotifyStatus",this.onNotifyStatus.bind(this)),(n=this.signaling)==null||n.on("onNotifyLeave",this.onNotifyLeave.bind(this)),(a=this.signaling)==null||a.on("onNotifyPublish",this.onNotifyPublish.bind(this)),(c=this.signaling)==null||c.on("onBye",this.onBye.bind(this)),(o=this.signaling)==null||o.on("onReconnectStart",this.onReconnectStart.bind(this)),(l=this.signaling)==null||l.on("onReconnectSuccess",this.onReconnectSuccess.bind(this)),(d=this.signaling)==null||d.on("onReconnectFail",this.onReconnectFail.bind(this)),(h=this.signaling)==null||h.on("onConnectFail",this.onConnectFail.bind(this)),(u=this.signaling)==null||u.on("onNetworkError",this.onNetworkError.bind(this)),(p=this.signaling)==null||p.on("onAuthInvalid",this.onAuthInvalid.bind(this)),(f=this.signaling)==null||f.on("onError",this.onError.bind(this)),(m=this.signaling)==null||m.on("onUnknownMessage",this.onUnknownMessage.bind(this))}onKeepAliveRsp(){this.emit("onKeepAliveRsp")}onNotifyJoin(e){this.emit("onNotifyJoin",e)}onNotifyStatus(e){this.emit("onNotifyStatus",e)}onNotifyLeave(e){this.emit("onNotifyLeave",e)}onNotifyPublish(e){this.emit("onNotifyPublish",e)}onBye(e,t){this.emit("onBye",e,t)}onConnectFail(e){this.reset(),this.emit("onConnectFail",e)}onNetworkError(e){this.emit("onNetworkError",e)}onAuthInvalid(){}onReconnectStart(){this.emit("onReconnectStart")}onReconnectSuccess(e){this.emit("onReconnectSuccess",e)}onReconnectFail(e){this.emit("onReconnectFail",e)}onError(e){this.emit("onError",e)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}}b(na,"logName","SignalingManager"),((s,r,e,t)=>{for(var i,n=t>1?void 0:t?Hm(r,e):r,a=s.length-1;a>=0;a--)(i=s[a])&&(n=(t?i(r,e,n):i(n))||n);t&&n&&Fm(r,e,n)})([k(J)],na.prototype,"publish",1);class $l{constructor(r){b(this,"taskProfile");b(this,"encodeParam");b(this,"users",[]);b(this,"backgroundColor",0);b(this,"backgrounds",[]);b(this,"watermarks",[]);b(this,"clockWidgets",[]);b(this,"cropMode");b(this,"mediaProcessMode");this.taskProfile=r}}class Xl{constructor(r,e,t){b(this,"userId");b(this,"streamType");b(this,"sourceType");this.userId=r,this.streamType=e,this.sourceType=t}}class Zl{constructor(r,e,t,i=0,n=16777215,a=ki.NOTO_SERIF_CJKSC_REGULAR){b(this,"x");b(this,"y");b(this,"fontSize");b(this,"zOrder");b(this,"fontColor");b(this,"fontType");this.x=r,this.y=e,this.fontSize=t,this.zOrder=i,this.fontColor=n,this.fontType=a}toJson(r,e){return{x:Ht(this.x,r),y:Ht(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:Yn(this.fontColor),zorder:this.zOrder}}}var Yl=(s=>(s[s.NOT_DISPLAY=0]="NOT_DISPLAY",s[s.ALWAYS=1]="ALWAYS",s[s.WHEN_NO_VIDEO=2]="WHEN_NO_VIDEO",s))(Yl||{});class aa{constructor(r,e,t,i,n,a=0,c=1,o=1){b(this,"url");b(this,"x");b(this,"y");b(this,"width");b(this,"height");b(this,"alpha");b(this,"display",1);b(this,"zOrder");this.url=r,this.x=e,this.y=t,this.width=i,this.height=n,this.zOrder=a,this.alpha=c,this.display=o}toJson(r,e){return{url:this.url,alpha:this.alpha,display:this.display,x:Ht(this.x,r),y:Ht(this.y,e),width:Ht(this.width,r),height:Ht(this.height,e),zorder:this.zOrder}}}b(aa,"DisplayType",Yl);class Ql{constructor(r,e,t,i,n=0,a=16777215,c=ki.NOTO_SERIF_CJKSC_REGULAR){b(this,"text");b(this,"x");b(this,"y");b(this,"fontSize");b(this,"zOrder");b(this,"fontColor");b(this,"fontType");this.text=r,this.x=e,this.y=t,this.fontSize=i,this.zOrder=n,this.fontColor=a,this.fontType=c}toJson(r,e){return{text:this.text,x:Ht(this.x,r),y:Ht(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:Yn(this.fontColor),zorder:this.zOrder}}}class ql{constructor(r,e,t,i,n,a=0,c){b(this,"userId");b(this,"x");b(this,"y");b(this,"width");b(this,"height");b(this,"zOrder");b(this,"sourceType");b(this,"segmentType",Di.LiveTranscodingNoBody);b(this,"images",[]);b(this,"texts",[]);this.userId=typeof r=="number"?r.toString():r,this.x=e,this.y=t,this.width=i,this.height=n,this.zOrder=a,c&&(this.sourceType=c)}toJson(r,e,t,i){const n={paneid:r,majorpane:0,x:Ht(this.x,e),y:Ht(this.y,t),width:Ht(this.width,e),height:Ht(this.height,t),zorder:this.zOrder,userid:this.userId,images:this.images.map(a=>a.toJson(e,t)),texts:this.texts.map(a=>a.toJson(e,t))};return this.sourceType&&Pi[this.sourceType]?n.sourcetype=Pi[this.sourceType]:n.sourcetype=Pi[ai.LiveTranscodingCamera],this.segmentType&&i===Rs.LiveTranscodingVirtualBackground?n.segmenttype=this.segmentType:n.segmenttype=Di.LiveTranscodingNoBody,n}}class Wm{constructor(r){b(this,"_updateables");b(this,"_useWebworker");b(this,"_inited");b(this,"_active");b(this,"_previousRAFTime");b(this,"_previousWorkerTime");b(this,"_webWorkerString");b(this,"_webWorker");b(this,"_intervalThreshold");b(this,"_rafId");this._updateables=[],this._useWebworker=!1,this._inited=!1,this._active=!1,this._previousRAFTime=void 0,this._previousWorkerTime=void 0,this._intervalThreshold=r&&r>0&&r<=60?1/r:.1,this._webWorkerString=`
135
338
  var running = false;
136
339
  function tick(){
137
340
  postMessage(Date.now());
@@ -146,4 +349,4 @@ onmessage = function(evt) {
146
349
  tick();
147
350
  }
148
351
  if (data === 'stop') running = false;
149
- });`,this._webWorker=void 0}_initWebWorker(){window.URL=window.URL||window.webkitURL;let a=new Blob([this._webWorkerString],{type:"application/javascript"});this._webWorker=new Worker(URL.createObjectURL(a)),this._webWorker.onmessage=e=>{let t=e.data;this._updateWorkerTime(t)}}_lostVisibility(){var a;this._previousWorkerTime=Date.now(),this._useWebworker=!0,this._webWorker||this._initWebWorker(),this._active&&((a=this._webWorker)==null||a.postMessage("start"))}_gainedVisibility(){this._useWebworker=!1,this._previousRAFTime=void 0,this._webWorker&&this._webWorker.postMessage("stop"),this._active&&(this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)))}_init(){if(window.Worker){if(document.hidden===void 0)return window.addEventListener("focus",this._gainedVisibility.bind(this)),void window.addEventListener("blur",this._lostVisibility.bind(this));document.addEventListener("visibilitychange",()=>{document.hidden===!0?this._lostVisibility():this._gainedVisibility()},!1)}}_updateWorkerTime(a){let e=(a-(this._previousWorkerTime||0))/1e3;e>this._intervalThreshold&&(this._update(e),this._previousWorkerTime=a)}_updateRAFTime(a){this._previousRAFTime===void 0&&(this._previousRAFTime=a);let e=(a-this._previousRAFTime)/1e3;e>this._intervalThreshold&&(this._update(e),this._previousRAFTime=a),!this._useWebworker&&this._active?this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)):this._rafId=0}_update(a){for(let e=0;e<this._updateables.length;e++)this._updateables[e]._update(typeof a=="number"?a:parseFloat(a))}register(a){this._updateables.push(a),this._inited===!1&&(this._inited=!0,this._init()),this._active===!1&&(this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)),this._active=!0)}unregister(a){const e=this._updateables.indexOf(a);e!==-1&&this._updateables.splice(e,1),this._updateables.length===0&&(this._active=!1,this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=0),this._useWebworker&&this._webWorker&&this._webWorker.postMessage("stop"))}}class wn extends Dt{constructor(e,t=10){super("AliRtcImageHolder");g(this,"url");g(this,"image");g(this,"canvas");g(this,"mediaStream");g(this,"updateableManager");g(this,"updateable");g(this,"hasVideoTrack",!1);this.url=e,this.canvas=document.createElement("canvas"),this.canvas.width=1280,this.canvas.height=720,this.drawImageToCanvas(),this.updateableManager=new Mc(t)}get initOptions(){return{imageUrl:""}}setOptions(e){e.imageUrl&&(this.options=e,e.imageUrl!==this.url&&this.drawImageToCanvas())}drawImageToCanvas(){return I(this,null,function*(){if(!this.url)return;const e=this.canvas.getContext("2d"),t=document.createElement("img");let i;this.image=t,t.crossOrigin="anonymous",t.src=this.url;const{width:r,height:n}=yield new Promise(c=>{t.onload=()=>{i&&clearTimeout(i),c({width:t.width||16,height:t.height||16})},t.onerror=()=>{i&&clearTimeout(i),c({width:16,height:16})},i=setTimeout(()=>{c({width:16,height:16})},5e3)});this.canvas.width=r,this.canvas.height=n,e.drawImage(t,0,0,r,n)})}start(){return I(this,null,function*(){var i;if(!this.url)throw new Error("no image url founded");if(!this.canvas)throw new Error("get canvas error");const e=this.canvas.captureStream(25),t=this.canvas.getContext("2d");return this.image&&this.image.width&&t.drawImage(this.image,0,0,this.image.width,this.image.height),this.mediaStream=e,t.fillStyle="transparent",this.updateable={_update:()=>{t.fillRect(0,0,1,1)}},this.updateableManager.register(this.updateable),(i=e.getVideoTracks())==null?void 0:i[0]})}stop(){var e,t;this.updateable&&(this.updateableManager.unregister(this.updateable),this.updateable=null),(t=(e=this.mediaStream)==null?void 0:e.getVideoTracks()[0])==null||t.stop(),this.mediaStream=void 0}isSupported(){return!0}shouldUpdate(e){return this.hasVideoTrack===!!e.originVideoTrack}process(e){return I(this,null,function*(){if(this.hasVideoTrack=!!e.originVideoTrack,e.originVideoTrack){const i=e.currentVideoTrack;return i&&i.id===e.originVideoTrack.id||e.updateVideoTrack(e.originVideoTrack),void this.stop()}const t=yield this.start();e.updateVideoTrack(t)})}}class Ti{static checkString(a){return typeof a=="string"}static checkNumber(a){return typeof a=="number"}static checkHtmlVideoElement(a){return a&&a.nodeName==="VIDEO"}static checkHtmlAudioElement(a){return a&&a.nodeName==="AUDIO"}static checkAuthInfo(a){return a?a.appId?a.channelId?Ti.checkString(a.channelId)?a.userId?Ti.checkString(a.userId)?a.timestamp?Ti.checkNumber(a.timestamp)?a.token?null:new V(U.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no token founded"):new V(U.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"timestamp is not number"):new V(U.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no timestamp founded"):new V(U.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"userId is not string"):new V(U.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no userId founded"):new V(U.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"channelId is not string"):new V(U.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no channelId founded"):new V(U.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no appId founded"):new V(U.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no authInfo founded")}static checkMediaStreamTrack(a){return a instanceof MediaStreamTrack}static checkVideoEncoderConfiguration(a){return a&&(a.width||a.height||a.frameRate||a.bitrateMax)}}var Lc=Object.defineProperty,Nc=Object.getOwnPropertyDescriptor,j=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Nc(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&Lc(a,e,r),r};const F=($=class extends se{constructor(e){super();g(this,"channelProfile");g(this,"clientRole");g(this,"signalingManager");g(this,"bizControl");g(this,"liveTranscoding");g(this,"maxSignalingReconnectDuration");g(this,"slsReporter");g(this,"connectState",oe.AliRtcConnectionStatusInit);g(this,"networkError",!1);g(this,"_audioOnlyMode",!1);g(this,"_authInfoWillExpireTimer",null);g(this,"_authInfoExpiredTimer",null);g(this,"_serverCheckAuthInfoTimestamp",null);g(this,"_localCheckAuthInfoTimestamp",null);g(this,"_proxyAiTid",null);g(this,"_agentParam",null);this.config=e;const t=Date.now();N.init(),this.slsReporter=new $r(this),this.channelProfile=kt.AliRtcSdkCommunication,this.clientRole=Nt.AliRtcSdkLive,this.liveTranscoding=new _c(this.slsReporter),this.signalingManager=new Xr(this.channelProfile,this.clientRole,this.slsReporter,(e==null?void 0:e.env)===mt.pre?mt.pre:mt.prod),this.addSignalingManagerListeners(),this.maxSignalingReconnectDuration=e==null?void 0:e.maxSignalingReconnectDuration,this.bizControl=new Xe({slsReporter:this.slsReporter,signalingManager:this.signalingManager,parameter:e==null?void 0:e.parameter}),this.addBizControlListeners(),this.addPublisherListeners(),this.slsReporter.reportConnectionLatencyEvent(ot.CREATE_ENGINE,dt.START,"","",t),this.slsReporter.reportConnectionLatencyEvent(ot.CREATE_ENGINE,dt.END,"","",Date.now()),this.slsReporter.reportSDKCreated(t)}static getSdkVersion(){return Ni}static setLogLevel(e){N.setLogLevel(e)}static getInstance(e){return $._instance||($._instance=new $(e)),$._instance}destroy(){return I(this,null,function*(){$._instance=void 0,yield this.leaveChannel(),yield this.bizControl.clear(),N.destroy()})}get channel(){return this.bizControl.channel}get userId(){return this.bizControl.userId}get remoteUsers(){return this.bizControl.remoteUsers}get publisher(){return this.bizControl.publisher}get publishAudioStream(){return this.publisher.publishStreams.audio}get isPublishing(){const{publisher:e}=this.bizControl;return!!e&&e.isPublishing}get currentRoleCanPublish(){return this.channelProfile===kt.AliRtcSdkCommunication||this.clientRole===Nt.AliRtcSdkInteractive}addPublisherListeners(){this.publisher.on(Qe.Local,e=>{N.event("[Publisher] Device Status Change",e),this.onLocalDeviceStatusChange(e)}),this.publisher.on(qt.VideoTrackEnded,()=>{N.event("[Publisher] VideoTrack Ended"),this.emit("localDeviceException",Rt.AliEngineLocalDeviceTypeCamera,Be.AliEngineLocalDeviceExceptionTypeCameraInterrupt,"")}),this.publisher.on(qt.ScreenTrackEnded,()=>{N.event("[Publisher] ScreenTrack Ended"),this.emit("localDeviceException",Rt.AliEngineLocalDeviceTypeDisplay,Be.AliEngineLocalDeviceExceptionTypeDisplayException,"")}),this.publisher.on(qt.AudioTrackEnded,()=>{N.event("[Publisher] AudioTrack Ended"),this.emit("localDeviceException",Rt.AliEngineLocalDeviceTypeMic,Be.AliEngineLocalDeviceExceptionTypeMicInterrupt,"")}),this.publisher.on("localDeviceException",(e,t,i="")=>{this.emit("localDeviceException",e,t,i)}),this.publisher.on("audioPublishStateChanged",(e,t,i)=>{var r;this.emit("audioPublishStateChanged",e,t,i,(r=this.channel)!=null?r:"")}),this.publisher.on("videoPublishStateChanged",(e,t,i)=>{var r;this.emit("videoPublishStateChanged",e,t,i,(r=this.channel)!=null?r:"")}),this.publisher.on("dualStreamPublishStateChanged",(e,t,i)=>{var r;this.emit("dualStreamPublishStateChanged",e,t,i,(r=this.channel)!=null?r:"")}),this.publisher.on("screenPublishStateChanged",(e,t,i)=>{var r;this.emit("screenSharePublishStateChanged",e,t,i,(r=this.channel)!=null?r:"")}),this.publisher.on("dataPublishStateChanged",(e,t,i)=>{var r;this.emit("dataPublishStateChanged",e,t,i,(r=this.channel)!=null?r:"")})}occurError(e,t){N.event(`[${$.logName}]`,"Occur Error",e,t),this.emit("onOccurError",e,t),this.emit("occurError",e,t)}addBizControlListeners(){this.bizControl.rtsManager.on("disconnected",()=>I(this,null,function*(){N.event(`[${$.logName}]`,"RTS Disconnected"),(yield Ne.isNetworkAvailable())?this.onNetworkRecovery():this.onNetworkError()})),this.bizControl.rtsManager.on("subscribeexceeds",()=>I(this,null,function*(){N.event(`[${$.logName}]`,"RTS SubscribeExceeds"),this.bizControl.rtsManager.clear(),yield this.resumePublishForNetworkRecovery(),yield this.resumeSubList()})),this.bizControl.rtsManager.on("seimessage",(e,t,i)=>{const r=this.remoteUsers.find(n=>n.streamUrl===e);r&&this.emit("mediaExtensionMsgReceived",r.userId,i,t)}),this.bizControl.on(Qe.Remote,(e,t)=>{N.event(`[${$.logName}]`,"RemoteUser Device Status Change",e,t)}),this.bizControl.on("remoteUserJoin",(e,t)=>{this.emit("remoteUserOnLineNotify",e,t)}),this.bizControl.on("remoteTrackAvailableChange",(e,t,i)=>{this.emit("remoteTrackAvailableNotify",e,t,i)}),this.bizControl.on("audioSubscribeStateChanged",(e,t,i,r,n)=>{this.emit("audioSubscribeStateChanged",e,t,i,r,n)}),this.bizControl.on("videoSubscribeStateChanged",(e,t,i,r,n)=>{this.emit("videoSubscribeStateChanged",e,t,i,r,n)}),this.bizControl.on("screenSubscribeStateChanged",(e,t,i,r,n)=>{this.emit("screenShareSubscribeStateChanged",e,t,i,r,n)}),this.bizControl.on("dataSubscribeStateChanged",(e,t,i,r,n)=>{this.emit("dataSubscribeStateChanged",e,t,i,r,n)}),this.bizControl.on("userAudioMuted",(e,t)=>{this.emit("userAudioMuted",e,t)}),this.bizControl.on("userVideoMuted",(e,t)=>{this.emit("userVideoMuted",e,t)}),this.bizControl.on("userScreenMuted",(e,t)=>{this.emit("userScreenMuted",e,t)}),this.bizControl.on("audioVolume",e=>{this.emit("audioVolume",e)}),this.bizControl.on("remoteAudioAutoPlayFail",e=>{this.emit("remoteAudioAutoPlayFail",e)}),this.bizControl.on("remoteVideoAutoPlayFail",(e,t)=>{this.emit("remoteVideoAutoPlayFail",e,t)}),this.bizControl.on("remoteAudioPlayError",(e,t)=>{this.emit("remoteAudioPlayError",e,t)}),this.bizControl.on("remoteVideoPlayError",(e,t)=>{this.emit("remoteVideoPlayError",e,t)}),this.bizControl.on("rtcStats",e=>{this.emit("rtcStats",e)}),this.bizControl.on("rtcLocalAudioStats",e=>{this.emit("rtcLocalAudioStats",e)}),this.bizControl.on("rtcLocalVideoStats",e=>{this.emit("rtcLocalVideoStats",e)}),this.bizControl.on("rtcRemoteAudioStats",e=>{this.emit("rtcRemoteAudioStats",e)}),this.bizControl.on("rtcRemoteVideoStats",e=>{this.emit("rtcRemoteVideoStats",e)}),this.bizControl.on("remoteSubscribeError",(e,t)=>{this.occurError(e,t),this.slsReporter.reportError(e)}),this.bizControl.on("occurError",(e,t)=>{this.occurError(e,t),this.slsReporter.reportError(e)}),this.bizControl.on("remoteDataChannelMessage",(e,t)=>{this.emit("dataChannelMsg",e,t)}),this.bizControl.on("remoteUserSubscribedDataChannel",e=>{this.emit("remoteUserSubscribedDataChannel",e)})}addSignalingManagerListeners(){this.signalingManager.on("onKeepAliveRsp",()=>{this.networkError&&(N.event("[Signaling] Receive KeepAlive Response",`networkError: ${this.networkError}`),this.onNetworkRecovery())}),this.signalingManager.on("onNotifyJoin",e=>{N.event("[Signaling] Notify Join ",e),this.handleUsersJoin(e)}),this.signalingManager.on("onNotifyStatus",e=>{N.event("[Signaling] Notify Status ",e),e.forEach(t=>{this.bizControl.updateRemoteUserDeviceStatus(t)})}),this.signalingManager.on("onNotifyLeave",e=>{N.event("[Signaling] Notify Leave ",e),e.forEach(t=>I(this,null,function*(){yield this.bizControl.removeLeftUser(t),this.emit("remoteUserOffLineNotify",t.userid,t.leavecode)}))}),this.signalingManager.on("onBye",(e,t)=>{N.event("[Signaling] Bye ",e,t),this.slsReporter.reportError({message:`reason: ${e}, description: ${t}`}),this.emit("bye",e),this.signalingManager.reset(),this.leaveChannel(),this.slsReporter.reportBye(e)}),this.signalingManager.on("onConnectFail",e=>{N.event("[Signaling] Connect Failed ",e),this.onError(e),this.backToUnpublishStatus(),this.bizControl.leave(),this.signalingManager.reset(),this.connectState=oe.AliRtcConnectionStatusFailed,this.emit("connectionStatusChange",oe.AliRtcConnectionStatusFailed,At.AliRtcConnectionChangedNetworkInterrupted)}),this.signalingManager.on("onNetworkError",e=>{this.slsReporter.reportWarning("signaling network error"),N.event("[Signaling] Network error ",e),this.onNetworkError()}),this.signalingManager.on("onAuthInvalid",()=>{N.event("[Signaling] Auth Invalid")}),this.signalingManager.on("onReconnectStart",()=>{this.onNetworkError(),N.event("[Signaling] Reconnect Start "),this.connectState=oe.AliRtcConnectionStatusReconnecting,this.emit("connectionStatusChange",oe.AliRtcConnectionStatusReconnecting,At.AliRtcConnectionSignalingConnecting)}),this.signalingManager.on("onReconnectSuccess",e=>{N.event("[Signaling] Reconnect Success ",e),this.onNetworkRecovery(e)}),this.signalingManager.on("onReconnectFail",e=>{this.slsReporter.reportWarning("signaling reconnect fail: ${err.code}"),N.event("[Signaling] Reconnect Failed ",e),e.code===403&&this.emit("authInfoExpired")}),this.signalingManager.on("onError",e=>{this.slsReporter.reportWarning("signaling error: ${err.message}"),N.event("[Signaling] Error ",e),this.onError(e)}),this.signalingManager.on("onUnknownMessage",e=>{if(e.msgtype==="proxyai"&&e.tid===this._proxyAiTid){let t=e.data.retcode;t===200&&(t=0),this.emit("AIAgentResult",t,this._agentParam.action,e.data.body)}})}backToUnpublishStatus(){this.connectState=oe.AliRtcConnectionStatusDisconnected,this.publisher.isPublishing&&this.publisher.clearPublishState(),this.networkError=!1}handleUsersJoin(e){e.forEach(t=>{this.bizControl.addUser(t,be.Join)})}onLocalDeviceStatusChange(e){N.event(`[${$.logName}]`,Qe.Local,e),this.signalingManager.reportStatus(e).then(()=>{N.debug("[signaling] reportStatus suc")}).catch(t=>{N.error("[signaling] reportStatus failed",t)})}resumePublishForNetworkRecovery(){return I(this,null,function*(){try{yield this.publisher.resumePublish()}catch(e){const{code:t}=e;if(t===10205){let r=1;try{yield new Promise((n,c)=>{const o=setInterval(()=>I(this,null,function*(){r>1&&(clearInterval(o),c()),r+=1;try{yield this.publisher.resumePublish(),clearInterval(o),n()}catch(l){const{code:d}=l;d!==10205&&(clearInterval(o),c())}}),1e3)})}catch(n){}}throw e}})}onNetworkRecovery(e){return I(this,null,function*(){N.event($.logName,"onNetworkRecovery",`rts isConnected: ${this.bizControl.rtsManager.isConnected}; rts isConnecting: ${this.bizControl.rtsManager.isConnecting}`,{users:e}),yield this.resumeSubList(e),this.networkError&&(this.networkError=!1,this.publisher.reportSelfDeviceStatus(),this.connectState=oe.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",oe.AliRtcConnectionStatusConnected,At.AliRtcConnectionSignalingHeartbeatAlive))})}resumeSubList(e){return I(this,null,function*(){if(e){const{joinList:t,leaveList:i,presentList:r}=this.bizControl.diffUsers(e);N.info(`[${$.logName}]`,"resumeSubList",{joinList:t,leaveList:i,presentList:r}),this.handleUsersJoin(t),i.forEach(n=>{N.event($.logName,Ce.UserLeft,n.userid,n.reason),this.bizControl.onRemotePublishStateChange({userid:n.userid,displayname:"",callid:"",tracks:[]}),this.bizControl.removeLeftUser(n),this.emit("remoteUserOffLineNotify",n.userid,or.AliRtcUserOfflineQuit)}),r.forEach(n=>{this.bizControl.onRemotePublishStateChange(n)})}else for(let t=0;t<this.remoteUsers.length;t++){const i=this.remoteUsers[t];try{i.restore(),i.updateSubscribe(be.Resume)}catch(r){}}})}retrySubscribe(e){return I(this,null,function*(){const t=this.bizControl.getRemoteUser(e);if(!t)throw new V(U.ERR_INNER,`no remote user(${e}) founded`);t.restore(),t.updateSubscribe(be.Retry)})}onNetworkError(){this.connectState===oe.AliRtcConnectionStatusConnected&&(this.networkError||(this.connectState=oe.AliRtcConnectionStatusDisconnected,this.emit("connectionStatusChange",oe.AliRtcConnectionStatusDisconnected,At.AliRtcConnectionChangedNetworkInterrupted)),this.networkError=!0)}onError(e){this.slsReporter.reportError(e),N.event($.logName,Ce.Error,e)}setEnableDualVideoStream(e,t){this.bizControl.setEnableDualVideoStream(e,t)}hadPushStream(e){if(!this.publisher||!e)throw new V(U.ERR_INNER,"stream is not publishing")}getCurrentMicDeviceId(){return this.publisher.getCurrentMicDeviceId()}setChannelProfile(e){if(![oe.AliRtcConnectionStatusInit,oe.AliRtcConnectionStatusDisconnected,oe.AliRtcConnectionStatusFailed].includes(this.connectState))throw new V(U.ERR_INNER,"cannot set channel profile in call");this.channelProfile=e,this.channelProfile===kt.AliRtcSdkCommunication&&(this.clientRole=Nt.AliRtcSdkLive),this.signalingManager.setChannelProfile(e)}startDefaultDevices(){return I(this,null,function*(){if(!this.publisher)return;const{hasCamera:e,hasMicrophone:t,hasScreenShare:i}=this.publisher;if(!e&&!t&&!i){try{yield this.publisher.startDefaultCameraAndMic(this._audioOnlyMode)}catch(r){N.warn(`[${$.logName}]`,"startDefaultDevices failed",r.code,r.message),r instanceof V&&this.occurError(r);const n=r.code;this.occurError(new V(n>=U.ERR_CAMERA_OPEN_FAIL&&n<=U.ERR_CAMERA_NOT_AVAILABLE?U.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED:U.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED,`auto publish device failed, ${r.message||""}`))}yield this.publisher.previewAll()}})}startPublish(e){return I(this,null,function*(){try{yield this.publisher.startPublish(!1,e)}catch(t){const i=this.publisher.publishStreams||{},r=[];i!=null&&i.audio&&r.push(U.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),i!=null&&i.video&&r.push(U.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),r.forEach(n=>{this.occurError(new V(n,`auto publish stream failed, ${t.message||""}`))})}})}setClientRole(e){return I(this,null,function*(){try{if(this.channelProfile===kt.AliRtcSdkCommunication)return;if(!Object.values(Nt).includes(e))throw new V(U.ERR_INVALID_ARGUMENTS,`set client role error, role value(${e}) is invalid`);if(this.clientRole===e)return;this.slsReporter.reportRoleUpdate(this.clientRole,e),this.isInCall()?this.clientRole===Nt.AliRtcSdkInteractive?(this.publisher.isPublishing?yield this.publisher.unPublish():yield this.publisher.clearStream(),yield this.signalingManager.setClientRole(e)):(yield this.signalingManager.setClientRole(e),yield this.startDefaultDevices(),yield this.startPublish(_t.ROLE_CHANGE)):yield this.signalingManager.setClientRole(e),this.clientRole=e}catch(t){throw t.code===403&&this.emit("authInfoExpired"),t}})}getCurrentClientRole(){return this.clientRole}setAudioOnlyMode(e){if(this.isInCall())throw new V(U.ERR_INNER,"can not change audioOnly mode in call");this._audioOnlyMode=e}setAudioRedEnabled(e){if(this.isInCall())throw new V(U.ERR_INNER,"can not change audioRedEnabled in call");this.bizControl.setAudioRedEnabled(e)}setVideoCodec(e){this.bizControl.setVideoCodec(e)}setCheckAuthInfoTimer(e,t){const i=1e3*(e-t);this._authInfoExpiredTimer=window.setTimeout(()=>{this.emit("authInfoExpired")},i),this._authInfoWillExpireTimer=window.setTimeout(()=>{this.emit("authInfoWillExpire")},i-3e4),this._serverCheckAuthInfoTimestamp=t,this._localCheckAuthInfoTimestamp=+Date.now()/1e3}clearCheckAuthInfoTimer(){this._authInfoExpiredTimer&&window.clearTimeout(this._authInfoExpiredTimer),this._authInfoWillExpireTimer&&window.clearTimeout(this._authInfoWillExpireTimer)}joinChannel(r,n){return I(this,arguments,function*(e,t,i={}){const c=Date.now();let o,l=typeof t=="string"?t:t==null?void 0:t.userName;if(typeof e=="string")try{const p=JSON.parse(window.atob(e));o={appId:p.appid,channelId:p.channelid,userId:p.userid,timestamp:p.timestamp,nonce:p.nonce,token:p.token}}catch(p){throw new V(U.ERR_INVALID_ARGUMENTS,`authInfo is invalid: ${p.message||""}`)}else o=e;l||(l=o.userId);const d={start:Date.now()};let h=Ti.checkAuthInfo(o);if(oe.AliRtcConnectionStatusInit!==this.connectState&&oe.AliRtcConnectionStatusDisconnected!==this.connectState&&oe.AliRtcConnectionStatusFailed!==this.connectState){const p=new V(U.ERR_JOIN_ALREADY_JOINED,"already joined");throw this.connectState===oe.AliRtcConnectionStatusConnecting&&(p.message="Repeated operation during login"),this.slsReporter.reportJoin(p.code,d,""),p}{if(h)throw this.connectState=oe.AliRtcConnectionStatusFailed,this.slsReporter.reportJoin(h.code,d,""),this.slsReporter.reportJoinResult(h),h;o.sessionId=Ne.createCallid("web"),this.slsReporter.start(o),this.slsReporter.reportConnectionLatencyEvent(ot.JOIN,dt.START,"","",c),this.connectState=oe.AliRtcConnectionStatusConnecting,this.emit("connectionStatusChange",oe.AliRtcConnectionStatusConnecting,At.AliRtcConnectionSignalingConnecting),N.setSessionID(o.appId,o.sessionId);const p=()=>I(this,null,function*(){var m,b;try{let S="Conference";typeof t=="object"&&t.capabilityProfile===Ai.Human&&(S="AIUser");const v=JSON.parse(this.getParameter());v.joinMode&&(S=v.joinMode);const R=new fi(((m=this.config)==null?void 0:m.env)||mt.prod,o,S);if(R.result){const _=(u=R.result.config,f=et.EnableNonOnePcDefaultJoinMode,Kt(u==null?void 0:u.data,f));R.result.useonepc&&_!==!1||(S=""),N.info(`[${fi.logName}]`,"got allocate result from localStorage",`joinMode: ${S}`,R.result.useonepc,_)}else N.info(`[${fi.logName}]`,"no allocate result in localStorage",`joinMode: ${S}`);S&&(i.joinmode=S);const w=Date.now(),y=yield this.signalingManager.join(o,l,this.maxSignalingReconnectDuration,d,i);y.l1ip?(N.info("allocate l1 pub ip with mode",S,y.l1ip),this.bizControl.rtsManager.preferredPubL1Ip=y.l1ip):this.bizControl.rtsManager.preferredPubL1Ip=void 0,y.l1subip?(N.info("allocate l1 sub ip with mode",S,y.l1subip),this.bizControl.rtsManager.preferredSubL1Ip=y.l1subip):this.bizControl.rtsManager.preferredSubL1Ip=void 0;const A=Date.now();this.connectState=oe.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",oe.AliRtcConnectionStatusConnected,At.AliRtcConnectionSignalingJoinRoomSuccess),this.bizControl.init(o,y,{capabilityProfile:typeof t=="object"?t.capabilityProfile:Ai.Default,robotUserId:typeof t=="object"?t.robotUserId:void 0}),this.setCheckAuthInfoTimer(o.timestamp,y.timestamp),this.liveTranscoding.setAuthInfo(o),this.slsReporter.reportJoin(0,d,y.tid),this.slsReporter.reportJoinResult(null),this.slsReporter.reportConnectionLatencyEvent(ot.JOIN,dt.SEND_SIG,"","",w),this.slsReporter.reportConnectionLatencyEvent(ot.JOIN,dt.RECV_RST,"","",A),this.slsReporter.reportConnectionLatencyEvent(ot.JOIN,dt.END,"","")}catch(S){const v=(b=S.code)!=null?b:-1,R=S.reason||S.message||"";throw this.connectState=oe.AliRtcConnectionStatusDisconnected,this.emit("connectionStatusChange",oe.AliRtcConnectionStatusDisconnected,At.AliRtcConnectionSignalingJoinRoomFailure),this.slsReporter.reportJoin(v,d,""),this.slsReporter.reportJoinResult(S),new V(v,R)}var u,f});this.currentRoleCanPublish?(yield Promise.all([p(),this.startDefaultDevices()]),yield this.startPublish(_t.JOIN_CHANNEL)):yield p(),this.publisher.reportSelfDeviceStatus(),this.remoteUsers.forEach(u=>{u.updateSubscribe(be.Join)})}})}joinAIChannel(e,t,i){return I(this,null,function*(){return this._proxyAiTid=lt(),this._agentParam=i,this.joinChannel(e,t,{proxyai:{tid:this._proxyAiTid,region:i.region,proxydata:JSON.stringify({Region:i.region,Action:i.action,ActionParams:i.params})}})})}leaveChannel(){return I(this,null,function*(){var t;this.slsReporter.reportLeaveInvoked(),yield this.bizControl.leave();let e=new Date().getTime();if(oe.AliRtcConnectionStatusConnected===this.connectState)try{let i;i=yield this.signalingManager.leave(),this.slsReporter.reportLeave(new Date().getTime()-e,0,(t=i==null?void 0:i.tid)!=null?t:"")}catch(i){this.slsReporter.reportLeave(new Date().getTime()-e,i.code,i.reason)}else this.slsReporter.reportLeave(0,0,"");this.networkError=!1,this.connectState=oe.AliRtcConnectionStatusDisconnected,this.clearCheckAuthInfoTimer(),this.liveTranscoding.clear(),this.slsReporter.stop(),this.signalingManager.reset(),N.reportEnd()})}isInCall(){return this.connectState===oe.AliRtcConnectionStatusConnected}refreshAuthInfo(e){return I(this,null,function*(){let t;if(typeof e=="string")try{const d=JSON.parse(window.atob(e));t={userId:d.userid,timestamp:d.timestamp,nonce:d.nonce,token:d.token}}catch(d){throw new V(U.ERR_INVALID_ARGUMENTS,`authInfo is invalid: ${d.message||""}`)}else t=e;const{userId:i,nonce:r,timestamp:n,token:c,role:o}=t,l={userId:i,nonce:r,timestamp:n,token:c,role:o};try{yield this.signalingManager.refreshAuthInfo(l),this.bizControl.refreshAuthInfo(l),this.liveTranscoding.refreshAuthInfo(l),this.clearCheckAuthInfoTimer(),this._serverCheckAuthInfoTimestamp&&this._localCheckAuthInfoTimestamp&&t.timestamp&&this.setCheckAuthInfoTimer(t.timestamp,this._serverCheckAuthInfoTimestamp+(Date.now()-this._localCheckAuthInfoTimestamp))}catch(d){throw d}})}isAudioOnly(){return this._audioOnlyMode}publishLocalAudioStream(e){return I(this,null,function*(){this.publisher.setPublishLocalAudioStreamEnabled(e),this.connectState===oe.AliRtcConnectionStatusConnected&&(e?this.publisher.hasMicrophone?yield this.publisher.updateStreams():yield this.startAudioCapture():yield this.publisher.publishUpdate())})}isLocalAudioStreamPublished(){var e;return(e=this.publisher.publishLocalAudioStreamEnabled)!=null?e:!0}setDefaultSubscribeAllRemoteAudioStreams(e){this.bizControl.setAutoSubAudio(e)}subscribeAllRemoteAudioStreams(e){this.bizControl.setWantSubAudio(e)}subscribeRemoteAudioStream(e,t){if(t&&!this.bizControl.isWantSubAudio)throw new V(U.ERR_INVALID_ARGUMENTS,"subscribeAllRemoteAudioStreams(true) must be called first");this.bizControl.updateAudioWant(e,t)}resumeRemoteAudioStream(e){const t=this.bizControl.getRemoteUser(e);if(!t)throw new V(U.ERR_INNER,`no remote user(${e}) founded`);t.resumeAudio()}stopRemoteAudioPlay(e){const t=this.bizControl.getRemoteUser(e);if(!t)throw new V(U.ERR_INNER,`no remote user(${e}) founded`);t.stopPlayAudio()}publishLocalVideoStream(e){return I(this,null,function*(){this.publisher.setPublishLocalVideoStreamEnabled(e),this.connectState===oe.AliRtcConnectionStatusConnected&&(e?this.publisher.hasCamera?yield this.publisher.updateStreams():yield this.enableLocalVideo():yield this.publisher.publishUpdate())})}isLocalVideoStreamPublished(){var e;return(e=this.publisher.publishLocalVideoStreamEnabled)!=null?e:!0}setRemoteDefaultVideoStreamType(e){[Ke.AliRtcVideoStreamTypeHigh,Ke.AliRtcVideoStreamTypeLow].includes(e)&&this.bizControl.setRemoteDefaultVideoStreamType(e)}setRemoteUserVideoStreamType(e,t){[Ke.AliRtcVideoStreamTypeHigh,Ke.AliRtcVideoStreamTypeLow].includes(t)&&this.bizControl.setRemoteUserVideoStreamType(e,t)}setDefaultSubscribeAllRemoteVideoStreams(e){this.bizControl.setAutoSubVideo(e),this.bizControl.setAutoSubScreen(e)}subscribeAllRemoteVideoStreams(e){this.bizControl.setWantSubVideo(e),this.bizControl.setWantSubScreen(e)}subscribeRemoteMediaStream(e,t,i,r){const n=this.bizControl.getRemoteUser(e);if(!n)throw new V(U.ERR_INNER,`no remote user(${e}) founded`);!i||t!==ce.AliRtcVideoTrackScreen&&t!==ce.AliRtcVideoTrackBoth?n.setWantSubScreen(!1):n.setWantSubScreen(!0),!i||t!==ce.AliRtcVideoTrackCamera&&t!==ce.AliRtcVideoTrackBoth?n.setWantSubVideo(!1):n.setWantSubVideo(!0),n.setWantSubAudio(r),n.updateSubscribe(be.User)}resumeRemoteMediaStream(e,t){const i=this.bizControl.getRemoteUser(e);i&&i.resumeVideo(t)}getOnlineRemoteUsers(){return this.bizControl.remoteUsers.map(e=>e.userId)}getUserInfo(e){var t;return(t=this.bizControl.getRemoteUser(e))==null?void 0:t.remoteUserInfo}isUserOnline(e){return!!this.bizControl.remoteUsers.find(t=>t.userId===e)}startScreenShare(e){return I(this,null,function*(){const t={video:!1,audio:!1},{audio:i=!1,videoTrack:r,audioTrack:n}=e||{};if(r||n){t.screen=!0;const c=new MediaStream;r&&c.addTrack(r),n&&c.addTrack(n),t.mediaStream=c}else t.screen=!i||{audio:!0};yield this.publisher.createLocalStream(t)})}stopScreenShare(){return I(this,null,function*(){this.publisher.stopLocalStream({screen:!0})})}setScreenShareConfiguration(e){return I(this,null,function*(){const{width:t,height:i}=e;if(t&&!isNaN(t)&&i&&!isNaN(i)&&t*i>9437184)throw new V(U.ERR_INVALID_ARGUMENTS,"width * height must be less than 9437184");const o=e,{bitrate:r}=o,n=Mt(o,["bitrate"]),c=G({},n);r&&(c.maxBitrate=e.bitrate),yield this.publisher.setScreenProfile(c)})}setScreenShareContentHint(e){return I(this,null,function*(){e&&this.publisher.setScreenContentHint(e)})}publishLocalScreenShareStream(e,t){return I(this,null,function*(){this.publisher.setPublishLocalScreenStreamEnabled(e),this.connectState===oe.AliRtcConnectionStatusConnected&&(e?this.publisher.hasScreenShare?yield this.publisher.updateStreams():yield this.startScreenShare(t):yield this.publisher.publishUpdate())})}isScreenSharePublished(){var e;return(e=this.publisher.publishLocalScreenStreamEnabled)!=null?e:!0}setAudioShareVolume(e){if(typeof e!="number")throw new V(U.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setAudioVolume({screen:Math.max(0,Math.min(e,400))/100})}enableAudioVolumeIndication(e){this.bizControl.enableAudioVolumeIndication(e)}muteLocalMic(e=!1){this.publisher.muteLocalMic(e),this.connectState===oe.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()}muteRemoteAudioPlaying(e,t=!1){const i=this.bizControl.getRemoteUser(e);if(!i)throw new V(U.ERR_INNER,`no remote user(${e}) founded`);i.setAudioMuted(t)}muteAllRemoteAudioPlaying(e=!1){this.bizControl.setAudioMuted(e)}startAudioCapture(e){return I(this,null,function*(){const t={audio:e||!0};yield this.publisher.createLocalStream(t)})}setAudioConstraints(e){return I(this,null,function*(){yield this.publisher.setMicrophoneConstraints(e)})}stopAudioCapture(){this.publisher.stopAudioCapture()}switchMicrophone(e,t){return I(this,null,function*(){if(yield this.publisher.setMicrophoneDeviceId(e),!this.publisher.audioCaptureDisabled){if(t)return void(yield this.publisher.createLocalStream({audio:!0,mediaStream:new MediaStream([t])}));yield this.publisher.createLocalStream({audio:{deviceId:e}})}})}setRecordingVolume(e){if(typeof e!="number")throw new V(U.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setAudioVolume({audio:Math.max(0,Math.min(e,400))/100})}setPlayoutVolume(e){if(typeof e!="number")throw new V(U.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setPlayoutVolume(Math.max(0,Math.min(e,100))/100)}setRemoteAudioVolume(e,t){const i=this.bizControl.getRemoteUser(e);if(!i)throw new V(U.ERR_INNER,`no remote user(${e}) founded`);if(typeof t!="number")throw new V(U.ERR_INVALID_ARGUMENTS,"volume must be a number");i.setPlayoutVolume(Math.max(0,Math.min(t,100))/100)}setAudioProfile(e){return I(this,null,function*(){yield this.publisher.setAudioProfile(e)})}getAudioTrack(e){return I(this,null,function*(){if(!e)return this.publisher.audioTrack;const t=this.bizControl.getRemoteUser(e);return t==null?void 0:t.getAudioTrack})}setLocalViewConfig(e,t){return I(this,null,function*(){var i;if(this._audioOnlyMode)throw new V(U.ERR_INNER,"Cannot set local view in audio only mode");(i=this.bizControl)==null||i.setLocalViewConfig(e,t),t===ce.AliRtcVideoTrackCamera&&this.publisher.hasCamera?yield this.startPreview():t===ce.AliRtcVideoTrackScreen&&this.publisher.hasScreenShare&&(yield this.startPreviewScreen())})}setCameraCapturerConfiguration(e){return I(this,null,function*(){const l=e,{cameraDirection:t,deviceId:i,bitrate:r,maxSendFrameRate:n}=l,c=Mt(l,["cameraDirection","deviceId","bitrate","maxSendFrameRate"]),o=G({},c);r&&(o.maxBitrate=r),n&&(o.maxSendFrameRate=n),Object.keys(o).length>0&&(yield this.publisher.setVideoProfile(o)),t!==void 0&&this.publisher.setCameraDirection(t),i&&this.publisher.setCameraDeviceId(i)})}setCameraCapturerContentHint(e){return I(this,null,function*(){e&&this.publisher.setVideoContentHint(e)})}enableLocalVideo(e=!0){return I(this,null,function*(){var t,i,r,n,c,o;if(this._audioOnlyMode)throw new V(U.ERR_INNER,"Cannot enable local video in audio only mode");e?((t=this.publisher.publishStreams)!=null&&t.video&&((r=(i=this.publisher.publishStreams)==null?void 0:i.video)==null||r.disableVideo(),(o=(c=(n=this.publisher.publishStreams)==null?void 0:n.video)==null?void 0:c.videoTrack)==null||o.stop()),yield this.publisher.startCameraCapture()):yield this.publisher.stopCameraCapture()})}muteLocalCamera(e){return I(this,null,function*(){this.publisher.muteLocalCamera(e),this.connectState===oe.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()})}muteLocalScreen(e){return I(this,null,function*(){this.publisher.muteLocalScreen(e),this.connectState===oe.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()})}setRemoteViewConfig(e,t,i){this.bizControl.setRemoteViewConfig(t,e,i)}isCameraOn(){var e;return(e=this.publisher.hasCamera)!=null?e:!1}switchCamera(e,t){return I(this,null,function*(){var r;if(this._audioOnlyMode)throw new V(U.ERR_INNER,"Cannot switch camera in audio only mode");const i={};if(e?(i.deviceId=e,this.slsReporter.reportSwitchCamera(e)):t||(i.cameraDirection=this.publisher.cameraDirection==="environment"?mi.CAMERA_FRONT:mi.CAMERA_REAR,this.slsReporter.reportSwitchCamera(this.publisher.cameraDirection||"")),yield this.setCameraCapturerConfiguration(i),!this.publisher.cameraCaptureDisabled){(r=this.publisher.cameraTrack)==null||r.stop();const n={video:!0};t&&(n.mediaStream=new MediaStream([t])),yield this.publisher.createLocalStream(n)}})}getCurrentCameraDeviceId(){return this.publisher.getCurrentCameraDeviceId()}startPreview(){return I(this,null,function*(){if(this._audioOnlyMode)throw new V(U.ERR_INNER,"Cannot start preview camera in audio only mode");this.publisher.hasCamera||(yield this.enableLocalVideo(!0)),yield this.publisher.previewAll({screen:!1})})}startPreviewScreen(e){return I(this,null,function*(){if(this._audioOnlyMode)throw new V(U.ERR_INNER,"Cannot start preview screen share in audio only mode");this.publisher.hasScreenShare||(yield this.startScreenShare(e)),yield this.publisher.previewAll({primary:!1})})}stopPreview(){return I(this,null,function*(){yield this.publisher.stopPreview({primary:!0,screen:!1})})}stopPreviewScreen(){return I(this,null,function*(){yield this.publisher.stopPreview({primary:!1,screen:!0})})}getVideoTrack(e){return I(this,null,function*(){var n,c;const{userId:t,streamType:i}=e;if(!t)return i===Oe.AliRtcSdkStreamTypeCapture?this.publisher.cameraTrack:this.publisher.screenTrack;const r=this.bizControl.getRemoteUser(t);return i===Oe.AliRtcSdkStreamTypeCapture?(n=r==null?void 0:r.getCameraStream)==null?void 0:n.videoTrack:(c=r==null?void 0:r.getScreenStream)==null?void 0:c.videoTrack})}startPublishLiveStream(e,t){return I(this,null,function*(){return this.liveTranscoding.startPublishLiveStream(e,t)})}updatePublishLiveStream(e,t){return I(this,null,function*(){return this.liveTranscoding.updatePublishLiveStream(e,t)})}updatePublishLiveStreamWithTaskId(e,t){return this.liveTranscoding.updatePublishLiveStreamWithTaskId(e,t)}stopPublishLiveStream(e){return I(this,null,function*(){return this.liveTranscoding.stopPublishLiveStream(e)})}stopPublishLiveStreamWithTaskId(e){return this.liveTranscoding.stopPublishLiveStreamWithTaskId(e)}setEnableMediaExtensionMsg(e){var t;(t=this.bizControl)==null||t.setEnableMediaExtensionMsg(!!e)}sendMediaExtensionMsg(e,t){return I(this,null,function*(){return this.sendMediaExtensionMsgEx(e,t,5)})}sendMediaExtensionMsgEx(e,t,i){return I(this,null,function*(){if(!this.publisher||!this.isPublishing)throw new V(U.ERR_INNER,"you should publish first");return this.slsReporter.reportSEIMessage(i,e.byteLength,t,0,!1),this.publisher.sendSEI(e,t,i)})}enablePlugin(e,t){this.bizControl.pluginManager.add(e,t)}removePlugin(e){this.bizControl.pluginManager.remove(e)}setPluginOption(e,t){const i=this.bizControl.pluginManager.get(e);i&&t&&i.setOptions(t)}getPluginByName(e){return this.bizControl.pluginManager.get(e)}getPluginOption(e){const t=this.bizControl.pluginManager.get(e);return t==null?void 0:t.getOptions()}isBeautyAvailable(){return this.bizControl.pluginManager.has("AliRtcBeauty")}isBeautyEnabled(){const e=this.bizControl.pluginManager.get("AliRtcBeauty");if(!e)throw new V(Ut.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");return!!(e!=null&&e.isEnable)}setBeautyEffect(e,t){const i=this.bizControl.pluginManager.get("AliRtcBeauty");if(!i)throw new V(Ut.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");e?i.enable():i.disable(),i.setOptions({basicBeauty:{skinBuffing:Math.max(Math.min(1,+t.smoothnessLevel),0),whitening:Math.max(Math.min(1,+t.whiteningLevel),0)}})}enableBackgroundExchange(e,t){const i=this.bizControl.pluginManager.get("AliRtcBeauty");if(!i||!i.isEnable)throw new V(Ut.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const r={setSegmentBackgroundImage:{backgroundImgUrl:e?t:""}};e&&(r.segmentBackgroundProcess={enable:!1}),i.setOptions(r)}enableBackgroundBlur(e){const t=this.bizControl.pluginManager.get("AliRtcBeauty");if(!t||!t.isEnable)throw new V(Ut.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const i={segmentBackgroundProcess:{type:0,enable:e}};e&&(i.setSegmentBackgroundImage={type:0,backgroundImgUrl:""}),t.setOptions(i)}setParameter(e){this.bizControl.setParameter(e)}getParameter(){return this.bizControl.getParameter()}sendDataChannelMessage(e){this.bizControl.sendDataChannelMessage(e)}},g($,"logName","AliRtcEngine"),g($,"logError",!0),g($,"isSupported",oc),g($,"isDualVideoStreamSupported",hr.isSupport),g($,"getCameraList",()=>I($,null,function*(){return(yield X.AliRTS.getCameraList()).filter(e=>e.deviceId)})),g($,"getMicrophoneList",()=>I($,null,function*(){return(yield X.AliRTS.getMicList()).filter(e=>e.deviceId)})),g($,"getSpeakerList",()=>I($,null,function*(){return(yield X.AliRTS.getSpeakerList()).filter(e=>e.deviceId)})),g($,"_instance"),g($,"AliRtcSdkChannelProfile",kt),g($,"AliRtcSdkClientRole",Nt),g($,"AliRtcVideoStreamType",Ke),g($,"AliRtcVideoTrack",ce),g($,"AliRtcAudioTrack",$t),g($,"AliRtcPublishState",te),g($,"AliRtcSubscribeState",ae),g($,"AliRtcRawDataStreamType",Oe),g($,"AliRtcLogLevel",ar),g($,"AliRtcEngineLocalDeviceType",Rt),g($,"AliRtcEngineLocalDeviceExceptionType",Be),g($,"AliRtcConnectionStatus",oe),g($,"AliRtcConnectionStatusChangeReason",At),g($,"AliRtcPlugin",Dt),g($,"AliRtcPluginTrackType",oi),g($,"AliRtcImageHolderPlugin",wn),g($,"AliRtcLiveTranscodingParam",Ji),g($,"AliRtcLiveTranscodingEncodeParam",Hr),g($,"AliRtcLiveTranscodingMixParam",bn),g($,"AliRtcLiveTranscodingSingleParam",vn),g($,"AliRtcTranscodingClockWidget",yn),g($,"AliRtcTranscodingImage",Yr),g($,"AliRtcTranscodingText",An),g($,"AliRtcTranscodingUser",_n),g($,"AliRtcLiveTranscodingMixMode",_i),g($,"AliRtcLiveTranscodingStreamType",xr),g($,"AliRtcLiveTranscodingSourceType",li),g($,"AliRtcLiveTranscodingTaskProfile",Or),g($,"AliRtcLiveTranscodingAudioSampleRate",$i),g($,"AliRtcLiveTranscodingSegmentType",Ei),g($,"AliRtcLiveTranscodingFontType",Ii),g($,"AliRtcLiveTranscodingCropMode",Vr),g($,"AliRtcLiveTranscodingMediaProcessMode",Ki),g($,"AliRtcLiveTranscodingState",Ur),g($,"AliRtcLiveTranscodingErrorCode",It),g($,"AliRtcTrascodingPublishTaskStatus",Br),g($,"AliRtcDataChannelMsg",Vt),g($,"AliRtcDataMsgType",kr),g($,"Plugin",Dt),$);j([C()],F.prototype,"destroy",1),j([C()],F.prototype,"backToUnpublishStatus",1),j([C()],F.prototype,"resumePublishForNetworkRecovery",1),j([C()],F.prototype,"onNetworkRecovery",1),j([C()],F.prototype,"resumeSubList",1),j([C(B)],F.prototype,"retrySubscribe",1),j([C(B)],F.prototype,"setEnableDualVideoStream",1),j([C(B)],F.prototype,"setChannelProfile",1),j([C(B)],F.prototype,"setClientRole",1),j([C(B)],F.prototype,"setAudioOnlyMode",1),j([C()],F.prototype,"clearCheckAuthInfoTimer",1),j([C(B)],F.prototype,"joinChannel",1),j([C(B)],F.prototype,"joinAIChannel",1),j([C(B)],F.prototype,"leaveChannel",1),j([C(B)],F.prototype,"refreshAuthInfo",1),j([C(B)],F.prototype,"publishLocalAudioStream",1),j([C(B)],F.prototype,"setDefaultSubscribeAllRemoteAudioStreams",1),j([C(B)],F.prototype,"subscribeAllRemoteAudioStreams",1),j([C(B)],F.prototype,"subscribeRemoteAudioStream",1),j([C(B)],F.prototype,"resumeRemoteAudioStream",1),j([C(B)],F.prototype,"stopRemoteAudioPlay",1),j([C(B)],F.prototype,"publishLocalVideoStream",1),j([C(B)],F.prototype,"setRemoteDefaultVideoStreamType",1),j([C(B)],F.prototype,"setRemoteUserVideoStreamType",1),j([C(B)],F.prototype,"setDefaultSubscribeAllRemoteVideoStreams",1),j([C(B)],F.prototype,"subscribeAllRemoteVideoStreams",1),j([C(B)],F.prototype,"subscribeRemoteMediaStream",1),j([C(B)],F.prototype,"resumeRemoteMediaStream",1),j([C(([s])=>[`${s==null?void 0:s.audio}`])],F.prototype,"startScreenShare",1),j([C()],F.prototype,"stopScreenShare",1),j([C(B)],F.prototype,"setScreenShareConfiguration",1),j([C(B)],F.prototype,"setScreenShareContentHint",1),j([C()],F.prototype,"publishLocalScreenShareStream",1),j([C(B)],F.prototype,"setAudioShareVolume",1),j([C(B)],F.prototype,"enableAudioVolumeIndication",1),j([C(B)],F.prototype,"muteLocalMic",1),j([C(B)],F.prototype,"muteRemoteAudioPlaying",1),j([C(B)],F.prototype,"muteAllRemoteAudioPlaying",1),j([C(B)],F.prototype,"startAudioCapture",1),j([C(B)],F.prototype,"setAudioConstraints",1),j([C()],F.prototype,"stopAudioCapture",1),j([C(B)],F.prototype,"switchMicrophone",1),j([C(B)],F.prototype,"setRecordingVolume",1),j([C(B)],F.prototype,"setPlayoutVolume",1),j([C(B)],F.prototype,"setRemoteAudioVolume",1),j([C(B)],F.prototype,"setAudioProfile",1),j([C(B)],F.prototype,"getAudioTrack",1),j([C(B)],F.prototype,"setLocalViewConfig",1),j([C(B)],F.prototype,"setCameraCapturerConfiguration",1),j([C(B)],F.prototype,"setCameraCapturerContentHint",1),j([C(B)],F.prototype,"enableLocalVideo",1),j([C(B)],F.prototype,"muteLocalCamera",1),j([C(B)],F.prototype,"muteLocalScreen",1),j([C(B)],F.prototype,"setRemoteViewConfig",1),j([C(B)],F.prototype,"switchCamera",1),j([C()],F.prototype,"startPreview",1),j([C()],F.prototype,"startPreviewScreen",1),j([C()],F.prototype,"stopPreview",1),j([C()],F.prototype,"stopPreviewScreen",1),j([C()],F.prototype,"startPublishLiveStream",1),j([C()],F.prototype,"updatePublishLiveStream",1),j([C()],F.prototype,"updatePublishLiveStreamWithTaskId",1),j([C()],F.prototype,"stopPublishLiveStream",1),j([C()],F.prototype,"stopPublishLiveStreamWithTaskId",1),j([C(B)],F.prototype,"setEnableMediaExtensionMsg",1),j([C(([s,a,e])=>[s.byteLength,a,e])],F.prototype,"sendMediaExtensionMsgEx",1),j([C(([s,a])=>[s.name||"",a])],F.prototype,"enablePlugin",1),j([C(B)],F.prototype,"removePlugin",1),j([C(B)],F.prototype,"setPluginOption",1),j([C(B)],F.prototype,"getPluginByName",1),j([C(B)],F.prototype,"getPluginOption",1),j([C(B)],F.prototype,"setBeautyEffect",1),j([C(B)],F.prototype,"enableBackgroundExchange",1),j([C(B)],F.prototype,"enableBackgroundBlur",1),j([C(B)],F.prototype,"setParameter",1),j([C(([s])=>{var a;return[(a=s.data)==null?void 0:a.byteLength]})],F.prototype,"sendDataChannelMessage",1),j([C(B)],F,"setLogLevel",1);let En=F;const In=new Ir({businessName:"imp-web-rtc",version:(Tn=En.getSdkVersion())!=null?Tn:"unknown",env:"prod",disabled:window.AliRtcOptionsDisableProxy===!0});In.setReady();const xc=In.wrap(En);W.AliRtcAudioTrack=$t,W.AliRtcCapabilityProfile=Ai,W.AliRtcConnectionStatus=oe,W.AliRtcConnectionStatusChangeReason=At,W.AliRtcDataChannelMsg=Vt,W.AliRtcDataMsgType=kr,W.AliRtcEngineLocalDeviceExceptionType=Be,W.AliRtcEngineLocalDeviceType=Rt,W.AliRtcErrorCode=U,W.AliRtcImageHolderPlugin=wn,W.AliRtcLiveTranscodingAudioSampleRate=$i,W.AliRtcLiveTranscodingCropMode=Vr,W.AliRtcLiveTranscodingEncodeParam=Hr,W.AliRtcLiveTranscodingErrorCode=It,W.AliRtcLiveTranscodingFontType=Ii,W.AliRtcLiveTranscodingMediaProcessMode=Ki,W.AliRtcLiveTranscodingMixMode=_i,W.AliRtcLiveTranscodingMixParam=bn,W.AliRtcLiveTranscodingParam=Ji,W.AliRtcLiveTranscodingSegmentType=Ei,W.AliRtcLiveTranscodingSingleParam=vn,W.AliRtcLiveTranscodingSourceType=li,W.AliRtcLiveTranscodingState=Ur,W.AliRtcLiveTranscodingStreamType=xr,W.AliRtcLiveTranscodingTaskProfile=Or,W.AliRtcLocalStreamInfo=Lr,W.AliRtcLogLevel=ar,W.AliRtcPlugin=Dt,W.AliRtcPluginTrackType=oi,W.AliRtcPluginType=nn,W.AliRtcPublishState=te,W.AliRtcRawDataStreamType=Oe,W.AliRtcRemoteUserInfo=an,W.AliRtcSdkChannelProfile=kt,W.AliRtcSdkClientRole=Nt,W.AliRtcSubscribeState=ae,W.AliRtcTranscodingClockWidget=yn,W.AliRtcTranscodingImage=Yr,W.AliRtcTranscodingText=An,W.AliRtcTranscodingUser=_n,W.AliRtcTrascodingPublishTaskStatus=Br,W.AliRtcVideoStreamType=Ke,W.AliRtcVideoTrack=ce,W.default=xc,Object.defineProperties(W,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
352
+ });`,this._webWorker=void 0}_initWebWorker(){window.URL=window.URL||window.webkitURL;let r=new Blob([this._webWorkerString],{type:"application/javascript"});this._webWorker=new Worker(URL.createObjectURL(r)),this._webWorker.onmessage=e=>{let t=e.data;this._updateWorkerTime(t)}}_lostVisibility(){var r;this._previousWorkerTime=Date.now(),this._useWebworker=!0,this._webWorker||this._initWebWorker(),this._active&&((r=this._webWorker)==null||r.postMessage("start"))}_gainedVisibility(){this._useWebworker=!1,this._previousRAFTime=void 0,this._webWorker&&this._webWorker.postMessage("stop"),this._active&&(this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)))}_init(){if(window.Worker){if(document.hidden===void 0)return window.addEventListener("focus",this._gainedVisibility.bind(this)),void window.addEventListener("blur",this._lostVisibility.bind(this));document.addEventListener("visibilitychange",()=>{document.hidden===!0?this._lostVisibility():this._gainedVisibility()},!1)}}_updateWorkerTime(r){let e=(r-(this._previousWorkerTime||0))/1e3;e>this._intervalThreshold&&(this._update(e),this._previousWorkerTime=r)}_updateRAFTime(r){this._previousRAFTime===void 0&&(this._previousRAFTime=r);let e=(r-this._previousRAFTime)/1e3;e>this._intervalThreshold&&(this._update(e),this._previousRAFTime=r),!this._useWebworker&&this._active?this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)):this._rafId=0}_update(r){for(let e=0;e<this._updateables.length;e++)this._updateables[e]._update(typeof r=="number"?r:parseFloat(r))}register(r){this._updateables.push(r),this._inited===!1&&(this._inited=!0,this._init()),this._active===!1&&(this._rafId=requestAnimationFrame(this._updateRAFTime.bind(this)),this._active=!0)}unregister(r){const e=this._updateables.indexOf(r);e!==-1&&this._updateables.splice(e,1),this._updateables.length===0&&(this._active=!1,this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=0),this._useWebworker&&this._webWorker&&this._webWorker.postMessage("stop"))}}class eh extends ur{constructor(e,t=10){super("AliRtcImageHolder");b(this,"url");b(this,"image");b(this,"canvas");b(this,"mediaStream");b(this,"updateableManager");b(this,"updateable");b(this,"hasVideoTrack",!1);this.url=e,this.canvas=document.createElement("canvas"),this.canvas.width=1280,this.canvas.height=720,this.drawImageToCanvas(),this.updateableManager=new Wm(t)}get initOptions(){return{imageUrl:""}}setOptions(e){e.imageUrl&&(this.options=e,e.imageUrl!==this.url&&this.drawImageToCanvas())}drawImageToCanvas(){return _(this,null,function*(){if(!this.url)return;const e=this.canvas.getContext("2d"),t=document.createElement("img");let i;this.image=t,t.crossOrigin="anonymous",t.src=this.url;const{width:n,height:a}=yield new Promise(c=>{t.onload=()=>{i&&clearTimeout(i),c({width:t.width||16,height:t.height||16})},t.onerror=()=>{i&&clearTimeout(i),c({width:16,height:16})},i=setTimeout(()=>{c({width:16,height:16})},5e3)});this.canvas.width=n,this.canvas.height=a,e.drawImage(t,0,0,n,a)})}start(){return _(this,null,function*(){var i;if(!this.url)throw new Error("no image url founded");if(!this.canvas)throw new Error("get canvas error");const e=this.canvas.captureStream(25),t=this.canvas.getContext("2d");return this.image&&this.image.width&&t.drawImage(this.image,0,0,this.image.width,this.image.height),this.mediaStream=e,t.fillStyle="transparent",this.updateable={_update:()=>{t.fillRect(0,0,1,1)}},this.updateableManager.register(this.updateable),(i=e.getVideoTracks())==null?void 0:i[0]})}stop(){var e,t;this.updateable&&(this.updateableManager.unregister(this.updateable),this.updateable=null),(t=(e=this.mediaStream)==null?void 0:e.getVideoTracks()[0])==null||t.stop(),this.mediaStream=void 0}isSupported(){return!0}shouldUpdate(e){return this.hasVideoTrack===!!e.originVideoTrack}process(e){return _(this,null,function*(){if(this.hasVideoTrack=!!e.originVideoTrack,e.originVideoTrack){const i=e.currentVideoTrack;return i&&i.id===e.originVideoTrack.id||e.updateVideoTrack(e.originVideoTrack),void this.stop()}const t=yield this.start();e.updateVideoTrack(t)})}}class Mi{static checkString(r){return typeof r=="string"}static checkNumber(r){return typeof r=="number"}static checkHtmlVideoElement(r){return r&&r.nodeName==="VIDEO"}static checkHtmlAudioElement(r){return r&&r.nodeName==="AUDIO"}static checkAuthInfo(r){return r?r.appId?r.channelId?Mi.checkString(r.channelId)?r.userId?Mi.checkString(r.userId)?r.timestamp?Mi.checkNumber(r.timestamp)?r.token?null:new W(z.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no token founded"):new W(z.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"timestamp is not number"):new W(z.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no timestamp founded"):new W(z.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"userId is not string"):new W(z.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no userId founded"):new W(z.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"channelId is not string"):new W(z.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no channelId founded"):new W(z.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no appId founded"):new W(z.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no authInfo founded")}static checkMediaStreamTrack(r){return r instanceof MediaStreamTrack}static checkVideoEncoderConfiguration(r){return r&&(r.width||r.height||r.frameRate||r.bitrateMax)}}var jm=Object.defineProperty,Gm=Object.getOwnPropertyDescriptor,Y=(s,r,e,t)=>{for(var i,n=t>1?void 0:t?Gm(r,e):r,a=s.length-1;a>=0;a--)(i=s[a])&&(n=(t?i(r,e,n):i(n))||n);return t&&n&&jm(r,e,n),n};const Z=(ee=class extends de{constructor(e){super();b(this,"channelProfile");b(this,"clientRole");b(this,"signalingManager");b(this,"bizControl");b(this,"liveTranscoding");b(this,"maxSignalingReconnectDuration");b(this,"slsReporter");b(this,"connectState",fe.AliRtcConnectionStatusInit);b(this,"networkError",!1);b(this,"_audioOnlyMode",!1);b(this,"_authInfoWillExpireTimer",null);b(this,"_authInfoExpiredTimer",null);b(this,"_serverCheckAuthInfoTimestamp",null);b(this,"_localCheckAuthInfoTimestamp",null);b(this,"_proxyAiTid",null);b(this,"_agentParam",null);b(this,"onePcManager");b(this,"sessionId");this.config=e;const t=Date.now();O.init(),this.slsReporter=new ta(this),this.channelProfile=Jt.AliRtcSdkCommunication,this.clientRole=gr.AliRtcSdkLive,this.liveTranscoding=new Lm(this.slsReporter),this.signalingManager=new na(this.channelProfile,this.clientRole,this.slsReporter,(e==null?void 0:e.env)===Kt.pre?Kt.pre:Kt.prod),this.addSignalingManagerListeners(),this.maxSignalingReconnectDuration=e==null?void 0:e.maxSignalingReconnectDuration,this.bizControl=new St({slsReporter:this.slsReporter,signalingManager:this.signalingManager,parameter:e==null?void 0:e.parameter}),this.addBizControlListeners(),this.addPublisherListeners(),this.slsReporter.reportConnectionLatencyEvent(Ot.CREATE_ENGINE,Ut.START,"","",t),this.slsReporter.reportConnectionLatencyEvent(Ot.CREATE_ENGINE,Ut.END,"","",Date.now()),this.slsReporter.reportSDKCreated(t)}static getSdkVersion(){return ls}static setLogLevel(e){O.setLogLevel(e)}static getInstance(e){return ee._instance||(ee._instance=new ee(e)),ee._instance}destroy(){return _(this,null,function*(){ee._instance=void 0,yield this.leaveChannel(),yield this.bizControl.clear(),O.destroy()})}get channel(){return this.bizControl.channel}get userId(){return this.bizControl.userId}get remoteUsers(){return this.bizControl.remoteUsers}get publisher(){return this.bizControl.publisher}get publishAudioStream(){return this.publisher.publishStreams.audio}get isPublishing(){const{publisher:e}=this.bizControl;return!!e&&e.isPublishing}get currentRoleCanPublish(){return this.channelProfile===Jt.AliRtcSdkCommunication||this.clientRole===gr.AliRtcSdkInteractive}addPublisherListeners(){this.publisher.on(bt.Local,e=>{O.event("[Publisher] Device Status Change",e),this.onLocalDeviceStatusChange(e)}),this.publisher.on(Br.VideoTrackEnded,()=>{O.event("[Publisher] VideoTrack Ended"),this.emit("localDeviceException",ir.AliEngineLocalDeviceTypeCamera,qe.AliEngineLocalDeviceExceptionTypeCameraInterrupt,"")}),this.publisher.on(Br.ScreenTrackEnded,()=>{O.event("[Publisher] ScreenTrack Ended"),this.emit("localDeviceException",ir.AliEngineLocalDeviceTypeDisplay,qe.AliEngineLocalDeviceExceptionTypeDisplayException,"")}),this.publisher.on(Br.AudioTrackEnded,()=>{O.event("[Publisher] AudioTrack Ended"),this.emit("localDeviceException",ir.AliEngineLocalDeviceTypeMic,qe.AliEngineLocalDeviceExceptionTypeMicInterrupt,"")}),this.publisher.on("localDeviceException",(e,t,i="")=>{this.emit("localDeviceException",e,t,i)}),this.publisher.on("audioPublishStateChanged",(e,t,i)=>{var n;this.emit("audioPublishStateChanged",e,t,i,(n=this.channel)!=null?n:"")}),this.publisher.on("videoPublishStateChanged",(e,t,i)=>{var n;this.emit("videoPublishStateChanged",e,t,i,(n=this.channel)!=null?n:"")}),this.publisher.on("dualStreamPublishStateChanged",(e,t,i)=>{var n;this.emit("dualStreamPublishStateChanged",e,t,i,(n=this.channel)!=null?n:"")}),this.publisher.on("screenPublishStateChanged",(e,t,i)=>{var n;this.emit("screenSharePublishStateChanged",e,t,i,(n=this.channel)!=null?n:"")}),this.publisher.on("dataPublishStateChanged",(e,t,i)=>{var n;this.emit("dataPublishStateChanged",e,t,i,(n=this.channel)!=null?n:"")})}occurError(e,t){O.event(`[${ee.logName}]`,"Occur Error",e,t),this.emit("onOccurError",e,t),this.emit("occurError",e,t)}addBizControlListeners(){this.bizControl.rtsManager.on("disconnected",()=>_(this,null,function*(){O.event(`[${ee.logName}]`,"RTS Disconnected"),(yield ze.isNetworkAvailable())?this.onNetworkRecovery():this.onNetworkError()})),this.bizControl.rtsManager.on("subscribeexceeds",()=>_(this,null,function*(){O.event(`[${ee.logName}]`,"RTS SubscribeExceeds"),this.bizControl.rtsManager.clear(),yield this.resumePublishForNetworkRecovery(),yield this.resumeSubList()})),this.bizControl.rtsManager.on("seimessage",(e,t,i)=>{const n=this.remoteUsers.find(a=>a.streamUrl===e);n&&this.emit("mediaExtensionMsgReceived",n.userId,i,t)}),this.bizControl.on(bt.Remote,(e,t)=>{O.event(`[${ee.logName}]`,"RemoteUser Device Status Change",e,t)}),this.bizControl.on("remoteUserJoin",(e,t)=>{this.emit("remoteUserOnLineNotify",e,t)}),this.bizControl.on("remoteTrackAvailableChange",(e,t,i)=>{this.emit("remoteTrackAvailableNotify",e,t,i)}),this.bizControl.on("audioSubscribeStateChanged",(e,t,i,n,a)=>{this.emit("audioSubscribeStateChanged",e,t,i,n,a)}),this.bizControl.on("videoSubscribeStateChanged",(e,t,i,n,a)=>{this.emit("videoSubscribeStateChanged",e,t,i,n,a)}),this.bizControl.on("screenSubscribeStateChanged",(e,t,i,n,a)=>{this.emit("screenShareSubscribeStateChanged",e,t,i,n,a)}),this.bizControl.on("dataSubscribeStateChanged",(e,t,i,n,a)=>{this.emit("dataSubscribeStateChanged",e,t,i,n,a)}),this.bizControl.on("userAudioMuted",(e,t)=>{this.emit("userAudioMuted",e,t)}),this.bizControl.on("userVideoMuted",(e,t)=>{this.emit("userVideoMuted",e,t)}),this.bizControl.on("userScreenMuted",(e,t)=>{this.emit("userScreenMuted",e,t)}),this.bizControl.on("audioVolume",e=>{this.emit("audioVolume",e)}),this.bizControl.on("remoteAudioAutoPlayFail",e=>{this.emit("remoteAudioAutoPlayFail",e)}),this.bizControl.on("remoteVideoAutoPlayFail",(e,t)=>{this.emit("remoteVideoAutoPlayFail",e,t)}),this.bizControl.on("remoteAudioPlayError",(e,t)=>{this.emit("remoteAudioPlayError",e,t)}),this.bizControl.on("remoteVideoPlayError",(e,t)=>{this.emit("remoteVideoPlayError",e,t)}),this.bizControl.on("rtcStats",e=>{this.emit("rtcStats",e)}),this.bizControl.on("rtcLocalAudioStats",e=>{this.emit("rtcLocalAudioStats",e)}),this.bizControl.on("rtcLocalVideoStats",e=>{this.emit("rtcLocalVideoStats",e)}),this.bizControl.on("rtcRemoteAudioStats",e=>{this.emit("rtcRemoteAudioStats",e)}),this.bizControl.on("rtcRemoteVideoStats",e=>{this.emit("rtcRemoteVideoStats",e)}),this.bizControl.on("remoteSubscribeError",(e,t)=>{this.occurError(e,t),this.slsReporter.reportError(e)}),this.bizControl.on("occurError",(e,t)=>{this.occurError(e,t),this.slsReporter.reportError(e)}),this.bizControl.on("remoteDataChannelMessage",(e,t)=>{this.emit("dataChannelMsg",e,t)}),this.bizControl.on("remoteUserSubscribedDataChannel",e=>{this.emit("remoteUserSubscribedDataChannel",e)})}addSignalingManagerListeners(){this.signalingManager.on("onKeepAliveRsp",()=>{this.networkError&&(O.event("[Signaling] Receive KeepAlive Response",`networkError: ${this.networkError}`),this.onNetworkRecovery())}),this.signalingManager.on("onNotifyJoin",e=>{O.event("[Signaling] Notify Join ",e),this.handleUsersJoin(e)}),this.signalingManager.on("onNotifyStatus",e=>{O.event("[Signaling] Notify Status ",e),e.forEach(t=>{this.bizControl.updateRemoteUserDeviceStatus(t)})}),this.signalingManager.on("onNotifyLeave",e=>{O.event("[Signaling] Notify Leave ",e),e.forEach(t=>_(this,null,function*(){yield this.bizControl.removeLeftUser(t),this.emit("remoteUserOffLineNotify",t.userid,t.leavecode)}))}),this.signalingManager.on("onBye",(e,t)=>{O.event("[Signaling] Bye ",e,t),this.slsReporter.reportError({message:`reason: ${e}, description: ${t}`}),this.emit("bye",e),this.signalingManager.reset(),this.leaveChannel(),this.slsReporter.reportBye(e)}),this.signalingManager.on("onConnectFail",e=>{O.event("[Signaling] Connect Failed ",e),this.onError(e),this.backToUnpublishStatus(),this.bizControl.leave(),this.signalingManager.reset(),this.connectState=fe.AliRtcConnectionStatusFailed,this.emit("connectionStatusChange",fe.AliRtcConnectionStatusFailed,$t.AliRtcConnectionChangedNetworkInterrupted)}),this.signalingManager.on("onNetworkError",e=>{this.slsReporter.reportWarning("signaling network error"),O.event("[Signaling] Network error ",e),this.onNetworkError()}),this.signalingManager.on("onAuthInvalid",()=>{O.event("[Signaling] Auth Invalid")}),this.signalingManager.on("onReconnectStart",()=>{this.onNetworkError(),O.event("[Signaling] Reconnect Start "),this.connectState=fe.AliRtcConnectionStatusReconnecting,this.emit("connectionStatusChange",fe.AliRtcConnectionStatusReconnecting,$t.AliRtcConnectionSignalingConnecting)}),this.signalingManager.on("onReconnectSuccess",e=>{O.event("[Signaling] Reconnect Success ",e),this.onNetworkRecovery(e)}),this.signalingManager.on("onReconnectFail",e=>{this.slsReporter.reportWarning("signaling reconnect fail: ${err.code}"),O.event("[Signaling] Reconnect Failed ",e),e.code===403&&this.emit("authInfoExpired")}),this.signalingManager.on("onError",e=>{this.slsReporter.reportWarning("signaling error: ${err.message}"),O.event("[Signaling] Error ",e),this.onError(e)}),this.signalingManager.on("onUnknownMessage",e=>{if(e.msgtype==="proxyai"&&e.tid===this._proxyAiTid){let t=e.data.retcode;t===200&&(t=0),this.emit("AIAgentResult",t,this._agentParam.action,e.data.body)}})}backToUnpublishStatus(){this.connectState=fe.AliRtcConnectionStatusDisconnected,this.publisher.isPublishing&&this.publisher.clearPublishState(),this.networkError=!1}handleUsersJoin(e){e.forEach(t=>{this.bizControl.addUser(t,De.Join)})}onLocalDeviceStatusChange(e){O.event(`[${ee.logName}]`,bt.Local,e),this.signalingManager.reportStatus(e).then(()=>{O.debug("[signaling] reportStatus suc")}).catch(t=>{O.error("[signaling] reportStatus failed",t)})}resumePublishForNetworkRecovery(){return _(this,null,function*(){try{yield this.publisher.resumePublish()}catch(e){const{code:t}=e;if(t===10205){let n=1;try{yield new Promise((a,c)=>{const o=setInterval(()=>_(this,null,function*(){n>1&&(clearInterval(o),c()),n+=1;try{yield this.publisher.resumePublish(),clearInterval(o),a()}catch(l){const{code:d}=l;d!==10205&&(clearInterval(o),c())}}),1e3)})}catch(a){}}throw e}})}onNetworkRecovery(e){return _(this,null,function*(){O.event(ee.logName,"onNetworkRecovery",`rts isConnected: ${this.bizControl.rtsManager.isConnected}; rts isConnecting: ${this.bizControl.rtsManager.isConnecting}`,{users:e}),yield this.resumeSubList(e),this.networkError&&(this.networkError=!1,this.publisher.reportSelfDeviceStatus(),this.connectState=fe.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",fe.AliRtcConnectionStatusConnected,$t.AliRtcConnectionSignalingHeartbeatAlive))})}resumeSubList(e){return _(this,null,function*(){if(e){const{joinList:t,leaveList:i,presentList:n}=this.bizControl.diffUsers(e);O.info(`[${ee.logName}]`,"resumeSubList",{joinList:t,leaveList:i,presentList:n}),this.handleUsersJoin(t),i.forEach(a=>{O.event(ee.logName,We.UserLeft,a.userid,a.reason),this.bizControl.onRemotePublishStateChange({userid:a.userid,displayname:"",callid:"",tracks:[]}),this.bizControl.removeLeftUser(a),this.emit("remoteUserOffLineNotify",a.userid,mn.AliRtcUserOfflineQuit)}),n.forEach(a=>{this.bizControl.onRemotePublishStateChange(a)})}else for(let t=0;t<this.remoteUsers.length;t++){const i=this.remoteUsers[t];try{i.restore(),i.updateSubscribe(De.Resume)}catch(n){}}})}retrySubscribe(e){return _(this,null,function*(){const t=this.bizControl.getRemoteUser(e);if(!t)throw new W(z.ERR_INNER,`no remote user(${e}) founded`);t.restore(),t.updateSubscribe(De.Retry)})}onNetworkError(){this.connectState===fe.AliRtcConnectionStatusConnected&&(this.networkError||(this.connectState=fe.AliRtcConnectionStatusDisconnected,this.emit("connectionStatusChange",fe.AliRtcConnectionStatusDisconnected,$t.AliRtcConnectionChangedNetworkInterrupted)),this.networkError=!0)}onError(e){this.slsReporter.reportError(e),O.event(ee.logName,We.Error,e)}setEnableDualVideoStream(e,t){this.bizControl.setEnableDualVideoStream(e,t)}hadPushStream(e){if(!this.publisher||!e)throw new W(z.ERR_INNER,"stream is not publishing")}getCurrentMicDeviceId(){return this.publisher.getCurrentMicDeviceId()}setChannelProfile(e){if(![fe.AliRtcConnectionStatusInit,fe.AliRtcConnectionStatusDisconnected,fe.AliRtcConnectionStatusFailed].includes(this.connectState))throw new W(z.ERR_INNER,"cannot set channel profile in call");this.channelProfile=e,this.channelProfile===Jt.AliRtcSdkCommunication&&(this.clientRole=gr.AliRtcSdkLive),this.signalingManager.setChannelProfile(e)}get shouldStartCamera(){const{hasCamera:e,cameraCaptureDisabled:t,publishLocalVideoStreamEnabled:i}=this.publisher,{_audioOnlyMode:n}=this;return!e&&!n&&!t&&i}get shouldStartMic(){const{hasMicrophone:e,audioCaptureDisabled:t,publishLocalAudioStreamEnabled:i}=this.publisher;return!e&&!t&&i}startDefaultDevices(){return _(this,null,function*(){if(this.shouldStartCamera||this.shouldStartMic){try{yield this.publisher.startDefaultCameraAndMic(this._audioOnlyMode)}catch(e){O.warn(`[${ee.logName}]`,"startDefaultDevices failed",e.code,e.message),e instanceof W&&this.occurError(e);const t=e.code;this.occurError(new W(t>=z.ERR_CAMERA_OPEN_FAIL&&t<=z.ERR_CAMERA_NOT_AVAILABLE?z.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED:z.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED,`auto publish device failed, ${e.message||""}`))}yield this.publisher.previewAll()}})}startPublish(e){return _(this,null,function*(){try{yield this.publisher.startPublish(!1,e)}catch(t){const i=this.publisher.publishStreams||{},n=[];i!=null&&i.audio&&n.push(z.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),i!=null&&i.video&&n.push(z.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),n.forEach(a=>{this.occurError(new W(a,`auto publish stream failed, ${t.message||""}`))})}})}setClientRole(e){return _(this,null,function*(){try{if(this.channelProfile===Jt.AliRtcSdkCommunication)return;if(!Object.values(gr).includes(e))throw new W(z.ERR_INVALID_ARGUMENTS,`set client role error, role value(${e}) is invalid`);if(this.clientRole===e)return;this.slsReporter.reportRoleUpdate(this.clientRole,e),this.isInCall()?this.clientRole===gr.AliRtcSdkInteractive?(this.publisher.isPublishing?yield this.publisher.unPublish():yield this.publisher.clearStream(),yield this.signalingManager.setClientRole(e)):(yield this.signalingManager.setClientRole(e),yield this.startDefaultDevices(),yield this.startPublish(Xt.ROLE_CHANGE)):yield this.signalingManager.setClientRole(e),this.clientRole=e}catch(t){throw t.code===403&&this.emit("authInfoExpired"),t}})}getCurrentClientRole(){return this.clientRole}setAudioOnlyMode(e){if(this.isInCall())throw new W(z.ERR_INNER,"can not change audioOnly mode in call");this._audioOnlyMode=e}setAudioRedEnabled(e){if(this.isInCall())throw new W(z.ERR_INNER,"can not change audioRedEnabled in call");this.bizControl.setAudioRedEnabled(e)}setVideoCodec(e){this.bizControl.setVideoCodec(e)}setCheckAuthInfoTimer(e,t){const i=1e3*(e-t);this._authInfoExpiredTimer=window.setTimeout(()=>{this.emit("authInfoExpired")},i),this._authInfoWillExpireTimer=window.setTimeout(()=>{this.emit("authInfoWillExpire")},i-3e4),this._serverCheckAuthInfoTimestamp=t,this._localCheckAuthInfoTimestamp=+Date.now()/1e3}clearCheckAuthInfoTimer(){this._authInfoExpiredTimer&&window.clearTimeout(this._authInfoExpiredTimer),this._authInfoWillExpireTimer&&window.clearTimeout(this._authInfoWillExpireTimer)}joinChannel(n,a){return _(this,arguments,function*(e,t,i={}){var u;const c=Date.now();let o,l=typeof t=="string"?t:t==null?void 0:t.userName;if(typeof e=="string")try{const p=JSON.parse(window.atob(e));o={appId:p.appid,channelId:p.channelid,userId:p.userid,timestamp:p.timestamp,nonce:p.nonce,token:p.token}}catch(p){throw new W(z.ERR_INVALID_ARGUMENTS,`authInfo is invalid: ${p.message||""}`)}else o=e;l||(l=o.userId);const d={start:Date.now()};let h=Mi.checkAuthInfo(o);if(fe.AliRtcConnectionStatusInit!==this.connectState&&fe.AliRtcConnectionStatusDisconnected!==this.connectState&&fe.AliRtcConnectionStatusFailed!==this.connectState){const p=new W(z.ERR_JOIN_ALREADY_JOINED,"already joined");throw this.connectState===fe.AliRtcConnectionStatusConnecting&&(p.message="Repeated operation during login"),this.slsReporter.reportJoin(p.code,d,""),p}{if(h)throw this.connectState=fe.AliRtcConnectionStatusFailed,this.slsReporter.reportJoin(h.code,d,""),this.slsReporter.reportJoinResult(h),h;o.sessionId=ze.createCallid("web"),this.sessionId=o.sessionId,this.slsReporter.start(o),this.slsReporter.reportConnectionLatencyEvent(Ot.JOIN,Ut.START,"","",c),this.connectState=fe.AliRtcConnectionStatusConnecting,this.emit("connectionStatusChange",fe.AliRtcConnectionStatusConnecting,$t.AliRtcConnectionSignalingConnecting),O.setSessionID(o.appId,o.sessionId);let p="Conference";typeof t=="object"&&t.capabilityProfile===ni.Human&&(p="AIUser");const f=JSON.parse(this.getParameter());f.joinMode&&(p=f.joinMode);const m=new Ti(((u=this.config)==null?void 0:u.env)||Kt.prod,o,p);if(m.result){const g=function(S,v){return xr(S==null?void 0:S.data,v)}(m.result.config,Ne.EnableNonOnePcDefaultJoinMode);m.result.useonepc&&g!==!1||(p=""),O.info(`[${Ti.logName}]`,"got allocate result from localStorage",`joinMode: ${p}`,m.result.useonepc,g)}else O.info(`[${Ti.logName}]`,"no allocate result in localStorage",`joinMode: ${p}`);if(window.AliRtcOptionsDisableOnePc!==!0){let g=m.result;g||(O.info(`[${ee.logName}]`,"allocator result is null, read from server"),g=yield m.pms),O.info(`[${ee.logName}]`,"use allocator result",g==null?void 0:g.h5auth.ice_ufrag);const S=!!(g&&g.useonepc&&g.onepc&&g.h5auth&&g.grtnbacksvr&&g.grtnbacksvrport);if(g&&S)try{yield this.innerJoinChannelV2({ar:g,authInfo:o,_userName:l,userNameOrParam:t})}catch(v){O.error("joinRoomV2 error",v),this.onePcManager=void 0,this.bizControl.setOnePcManager(void 0),yield this.innerJoinChannelV1({authInfo:o,_userName:l,userNameOrParam:t,extraData:i,joinMode:p,timeRecorder:d})}else O.info(`[${ee.logName}]`,"use legacy join because",`useonepc: ${g==null?void 0:g.useonepc}, onepc:`,g==null?void 0:g.onepc,"h5auth:",g==null?void 0:g.h5auth,`grtnbacksvr: ${g==null?void 0:g.grtnbacksvr}, grtnbacksvrport: ${g==null?void 0:g.grtnbacksvrport}`),yield this.innerJoinChannelV1({authInfo:o,_userName:l,userNameOrParam:t,extraData:i,joinMode:p,timeRecorder:d})}else yield this.innerJoinChannelV1({authInfo:o,_userName:l,userNameOrParam:t,extraData:i,joinMode:p,timeRecorder:d})}})}innerJoinChannelV1(e){return _(this,null,function*(){const{authInfo:t,_userName:i,userNameOrParam:n,extraData:a,joinMode:c,timeRecorder:o}=e,l=()=>_(this,null,function*(){var d;try{c&&(a.joinmode=c);const h=Date.now(),u=yield this.signalingManager.join(t,i,this.maxSignalingReconnectDuration,o,a);u.l1ip?(O.info("allocate l1 pub ip with mode",c,u.l1ip),this.bizControl.rtsManager.preferredPubL1Ip=u.l1ip):this.bizControl.rtsManager.preferredPubL1Ip=void 0,u.l1subip?(O.info("allocate l1 sub ip with mode",c,u.l1subip),this.bizControl.rtsManager.preferredSubL1Ip=u.l1subip):this.bizControl.rtsManager.preferredSubL1Ip=void 0;const p=Date.now();this.connectState=fe.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",fe.AliRtcConnectionStatusConnected,$t.AliRtcConnectionSignalingJoinRoomSuccess),this.bizControl.init(t,u,{capabilityProfile:typeof n=="object"?n.capabilityProfile:ni.Default,robotUserId:typeof n=="object"?n.robotUserId:void 0}),this.setCheckAuthInfoTimer(t.timestamp,u.timestamp),this.liveTranscoding.setAuthInfo(t),this.slsReporter.reportJoin(0,o,u.tid),this.slsReporter.reportJoinResult(null),this.slsReporter.reportConnectionLatencyEvent(Ot.JOIN,Ut.SEND_SIG,"","",h),this.slsReporter.reportConnectionLatencyEvent(Ot.JOIN,Ut.RECV_RST,"","",p),this.slsReporter.reportConnectionLatencyEvent(Ot.JOIN,Ut.END,"","")}catch(h){const u=(d=h.code)!=null?d:-1,p=h.reason||h.message||"";throw this.connectState=fe.AliRtcConnectionStatusDisconnected,this.emit("connectionStatusChange",fe.AliRtcConnectionStatusDisconnected,$t.AliRtcConnectionSignalingJoinRoomFailure),this.slsReporter.reportJoin(u,o,""),this.slsReporter.reportJoinResult(h),new W(u,p)}});this.currentRoleCanPublish?(yield Promise.all([l(),this.startDefaultDevices()]),yield this.startPublish(Xt.JOIN_CHANNEL)):yield l(),this.publisher.reportSelfDeviceStatus(),this.remoteUsers.forEach(d=>{d.updateSubscribe(De.Join)})})}innerJoinChannelV2(e){return _(this,null,function*(){var v;const{authInfo:t,_userName:i,userNameOrParam:n,ar:a}=e;let c;O.info(`[${ee.logName}]`,"use onepc"),this.currentRoleCanPublish&&(c=this.startDefaultDevices());const o=new yn(t,i,this.channelProfile,this.clientRole,this.bizControl.rtsManager,this.publisher);this.onePcManager=o,this.bizControl.setOnePcManager(o);const l=this.currentRoleCanPublish&&this.shouldStartCamera,d=this.currentRoleCanPublish&&this.shouldStartMic,h=l?L.VideoLarge:void 0,u=d?L.Audio:void 0,p=this.bizControl.isAutoSubVideo()&&this.bizControl.isWantSubVideo(),f=this.bizControl.isAutoSubAudio()&&this.bizControl.isWantSubAudio(),m=p?L.VideoLarge:void 0,g=f?L.Audio:void 0,S=yield o.connect(a,{prePub:{vMsid:h,aMsid:u},preSub:{vMsid:m,aMsid:g,preferVideoSmall:m===L.VideoLarge&&this.bizControl.preferVideoSmall}},c);this.connectState=fe.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",fe.AliRtcConnectionStatusConnected,$t.AliRtcConnectionSignalingJoinRoomSuccess),this.bizControl.init(t,S.data,{capabilityProfile:typeof n=="object"?n.capabilityProfile:ni.Default}),this.remoteUsers.forEach(E=>{E.updateSubscribe(De.Join)}),yield c,yield this.startPublish(Xt.JOIN_CHANNEL),(v=this.publisher)==null||v.reportSelfDeviceStatus()})}joinAIChannel(e,t,i){return _(this,null,function*(){return this._proxyAiTid=Vt(),this._agentParam=i,this.joinChannel(e,t,{proxyai:{tid:this._proxyAiTid,region:i.region,proxydata:JSON.stringify({Region:i.region,Action:i.action,ActionParams:i.params})}})})}leaveChannel(){return _(this,null,function*(){var t;this.slsReporter.reportLeaveInvoked(),yield this.bizControl.leave();let e=new Date().getTime();if(fe.AliRtcConnectionStatusConnected===this.connectState){try{let i;i=yield this.signalingManager.leave(),this.slsReporter.reportLeave(new Date().getTime()-e,0,(t=i==null?void 0:i.tid)!=null?t:"")}catch(i){this.slsReporter.reportLeave(new Date().getTime()-e,i.code,i.reason)}this.onePcManager&&(this.onePcManager.leave(),this.onePcManager=void 0,this.bizControl.setOnePcManager(void 0))}else this.slsReporter.reportLeave(0,0,"");this.sessionId=void 0,this.networkError=!1,this.connectState=fe.AliRtcConnectionStatusDisconnected,this.clearCheckAuthInfoTimer(),this.liveTranscoding.clear(),this.slsReporter.stop(),this.signalingManager.reset(),O.reportEnd()})}isInCall(){return this.connectState===fe.AliRtcConnectionStatusConnected}refreshAuthInfo(e){return _(this,null,function*(){let t;if(typeof e=="string")try{const d=JSON.parse(window.atob(e));t={userId:d.userid,timestamp:d.timestamp,nonce:d.nonce,token:d.token}}catch(d){throw new W(z.ERR_INVALID_ARGUMENTS,`authInfo is invalid: ${d.message||""}`)}else t=e;const{userId:i,nonce:n,timestamp:a,token:c,role:o}=t,l={userId:i,nonce:n,timestamp:a,token:c,role:o};try{yield this.signalingManager.refreshAuthInfo(l),this.bizControl.refreshAuthInfo(l),this.liveTranscoding.refreshAuthInfo(l),this.clearCheckAuthInfoTimer(),this._serverCheckAuthInfoTimestamp&&this._localCheckAuthInfoTimestamp&&t.timestamp&&this.setCheckAuthInfoTimer(t.timestamp,this._serverCheckAuthInfoTimestamp+(Date.now()-this._localCheckAuthInfoTimestamp))}catch(d){throw d}})}isAudioOnly(){return this._audioOnlyMode}publishLocalAudioStream(e){return _(this,null,function*(){this.publisher.setPublishLocalAudioStreamEnabled(e),this.connectState===fe.AliRtcConnectionStatusConnected&&(e?this.publisher.hasMicrophone?yield this.publisher.updateStreams():yield this.startAudioCapture():yield this.publisher.publishUpdate())})}isLocalAudioStreamPublished(){var e;return(e=this.publisher.publishLocalAudioStreamEnabled)!=null?e:!0}setDefaultSubscribeAllRemoteAudioStreams(e){this.bizControl.setAutoSubAudio(e)}subscribeAllRemoteAudioStreams(e){this.bizControl.setWantSubAudio(e)}subscribeRemoteAudioStream(e,t){if(t&&!this.bizControl.isWantSubAudio)throw new W(z.ERR_INVALID_ARGUMENTS,"subscribeAllRemoteAudioStreams(true) must be called first");this.bizControl.updateAudioWant(e,t)}resumeRemoteAudioStream(e){const t=this.bizControl.getRemoteUser(e);if(!t)throw new W(z.ERR_INNER,`no remote user(${e}) founded`);t.resumeAudio()}stopRemoteAudioPlay(e){const t=this.bizControl.getRemoteUser(e);if(!t)throw new W(z.ERR_INNER,`no remote user(${e}) founded`);t.stopPlayAudio()}publishLocalVideoStream(e){return _(this,null,function*(){this.publisher.setPublishLocalVideoStreamEnabled(e),this.connectState===fe.AliRtcConnectionStatusConnected&&(e?this.publisher.hasCamera?yield this.publisher.updateStreams():yield this.enableLocalVideo():yield this.publisher.publishUpdate())})}isLocalVideoStreamPublished(){var e;return(e=this.publisher.publishLocalVideoStreamEnabled)!=null?e:!0}setRemoteDefaultVideoStreamType(e){[it.AliRtcVideoStreamTypeHigh,it.AliRtcVideoStreamTypeLow].includes(e)&&this.bizControl.setRemoteDefaultVideoStreamType(e)}setRemoteUserVideoStreamType(e,t){[it.AliRtcVideoStreamTypeHigh,it.AliRtcVideoStreamTypeLow].includes(t)&&this.bizControl.setRemoteUserVideoStreamType(e,t)}setDefaultSubscribeAllRemoteVideoStreams(e){this.bizControl.setAutoSubVideo(e),this.bizControl.setAutoSubScreen(e)}subscribeAllRemoteVideoStreams(e){this.bizControl.setWantSubVideo(e),this.bizControl.setWantSubScreen(e)}subscribeRemoteMediaStream(e,t,i,n){const a=this.bizControl.getRemoteUser(e);if(!a)throw new W(z.ERR_INNER,`no remote user(${e}) founded`);!i||t!==be.AliRtcVideoTrackScreen&&t!==be.AliRtcVideoTrackBoth?a.setWantSubScreen(!1):a.setWantSubScreen(!0),!i||t!==be.AliRtcVideoTrackCamera&&t!==be.AliRtcVideoTrackBoth?a.setWantSubVideo(!1):a.setWantSubVideo(!0),a.setWantSubAudio(n),a.updateSubscribe(De.User)}resumeRemoteMediaStream(e,t){const i=this.bizControl.getRemoteUser(e);i&&i.resumeVideo(t)}getOnlineRemoteUsers(){return this.bizControl.remoteUsers.map(e=>e.userId)}getUserInfo(e){var t;return(t=this.bizControl.getRemoteUser(e))==null?void 0:t.remoteUserInfo}isUserOnline(e){return!!this.bizControl.remoteUsers.find(t=>t.userId===e)}startScreenShare(e){return _(this,null,function*(){if(this._audioOnlyMode)throw new W(z.ERR_INNER,"Cannot enable screen share in audio only mode");const t={video:!1,audio:!1},{audio:i=!1,videoTrack:n,audioTrack:a}=e||{};if(n||a){t.screen=!0;const c=new MediaStream;n&&c.addTrack(n),a&&c.addTrack(a),t.mediaStream=c}else t.screen=!i||{audio:!0};yield this.publisher.createLocalStream(t)})}stopScreenShare(){return _(this,null,function*(){this.publisher.stopLocalStream({screen:!0})})}setScreenShareConfiguration(e){return _(this,null,function*(){const{width:t,height:i}=e;if(t&&!isNaN(t)&&i&&!isNaN(i)&&t*i>9437184)throw new W(z.ERR_INVALID_ARGUMENTS,"width * height must be less than 9437184");const o=e,{bitrate:n}=o,a=jt(o,["bitrate"]),c=D({},a);n&&(c.maxBitrate=e.bitrate),yield this.publisher.setScreenProfile(c)})}setScreenShareContentHint(e){return _(this,null,function*(){e&&this.publisher.setScreenContentHint(e)})}publishLocalScreenShareStream(e,t){return _(this,null,function*(){this.publisher.setPublishLocalScreenStreamEnabled(e),this.connectState===fe.AliRtcConnectionStatusConnected&&(e?this.publisher.hasScreenShare?yield this.publisher.updateStreams():yield this.startScreenShare(t):yield this.publisher.publishUpdate())})}isScreenSharePublished(){var e;return(e=this.publisher.publishLocalScreenStreamEnabled)!=null?e:!0}setAudioShareVolume(e){if(typeof e!="number")throw new W(z.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setAudioVolume({screen:Math.max(0,Math.min(e,400))/100})}enableAudioVolumeIndication(e){this.bizControl.enableAudioVolumeIndication(e)}muteLocalMic(e=!1){this.publisher.muteLocalMic(e),this.connectState===fe.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()}muteRemoteAudioPlaying(e,t=!1){const i=this.bizControl.getRemoteUser(e);if(!i)throw new W(z.ERR_INNER,`no remote user(${e}) founded`);i.setAudioMuted(t)}muteAllRemoteAudioPlaying(e=!1){this.bizControl.setAudioMuted(e)}startAudioCapture(e){return _(this,null,function*(){const t={audio:e||!0};yield this.publisher.createLocalStream(t)})}setAudioConstraints(e){return _(this,null,function*(){yield this.publisher.setMicrophoneConstraints(e)})}stopAudioCapture(){this.publisher.stopAudioCapture()}switchMicrophone(e,t){return _(this,null,function*(){if(yield this.publisher.setMicrophoneDeviceId(e),!this.publisher.audioCaptureDisabled){if(t)return void(yield this.publisher.createLocalStream({audio:!0,mediaStream:new MediaStream([t])}));yield this.publisher.createLocalStream({audio:{deviceId:e}})}})}setRecordingVolume(e){if(typeof e!="number")throw new W(z.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setAudioVolume({audio:Math.max(0,Math.min(e,400))/100})}setPlayoutVolume(e){if(typeof e!="number")throw new W(z.ERR_INVALID_ARGUMENTS,"volume must be a number");this.bizControl.setPlayoutVolume(Math.max(0,Math.min(e,100))/100)}setRemoteAudioVolume(e,t){const i=this.bizControl.getRemoteUser(e);if(!i)throw new W(z.ERR_INNER,`no remote user(${e}) founded`);if(typeof t!="number")throw new W(z.ERR_INVALID_ARGUMENTS,"volume must be a number");i.setPlayoutVolume(Math.max(0,Math.min(t,100))/100)}setAudioProfile(e){return _(this,null,function*(){yield this.publisher.setAudioProfile(e)})}getAudioTrack(e){return _(this,null,function*(){if(!e)return this.publisher.audioTrack;const t=this.bizControl.getRemoteUser(e);return t==null?void 0:t.getAudioTrack})}setLocalViewConfig(e,t){return _(this,null,function*(){var i;if(this._audioOnlyMode)throw new W(z.ERR_INNER,"Cannot set local view in audio only mode");(i=this.bizControl)==null||i.setLocalViewConfig(e,t),t===be.AliRtcVideoTrackCamera&&this.publisher.hasCamera?yield this.startPreview():t===be.AliRtcVideoTrackScreen&&this.publisher.hasScreenShare&&(yield this.startPreviewScreen())})}setCameraCapturerConfiguration(e){return _(this,null,function*(){const l=e,{cameraDirection:t,deviceId:i,bitrate:n,maxSendFrameRate:a}=l,c=jt(l,["cameraDirection","deviceId","bitrate","maxSendFrameRate"]),o=D({},c);n&&(o.maxBitrate=n),a&&(o.maxSendFrameRate=a),Object.keys(o).length>0&&(yield this.publisher.setVideoProfile(o)),t!==void 0&&this.publisher.setCameraDirection(t),i&&this.publisher.setCameraDeviceId(i)})}setCameraCapturerContentHint(e){return _(this,null,function*(){e&&this.publisher.setVideoContentHint(e)})}enableLocalVideo(e=!0){return _(this,null,function*(){var t,i,n,a,c,o;if(this._audioOnlyMode)throw new W(z.ERR_INNER,"Cannot enable local video in audio only mode");e?((t=this.publisher.publishStreams)!=null&&t.video&&((n=(i=this.publisher.publishStreams)==null?void 0:i.video)==null||n.disableVideo(),(o=(c=(a=this.publisher.publishStreams)==null?void 0:a.video)==null?void 0:c.videoTrack)==null||o.stop()),yield this.publisher.startCameraCapture()):yield this.publisher.stopCameraCapture()})}muteLocalCamera(e){return _(this,null,function*(){this.publisher.muteLocalCamera(e),this.connectState===fe.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()})}muteLocalScreen(e){return _(this,null,function*(){this.publisher.muteLocalScreen(e),this.connectState===fe.AliRtcConnectionStatusConnected&&this.isPublishing&&this.publisher.reportSelfDeviceStatus()})}setRemoteViewConfig(e,t,i){this.bizControl.setRemoteViewConfig(t,e,i)}isCameraOn(){var e;return(e=this.publisher.hasCamera)!=null?e:!1}switchCamera(e,t){return _(this,null,function*(){var n;if(this._audioOnlyMode)throw new W(z.ERR_INNER,"Cannot switch camera in audio only mode");const i={};if(e?(i.deviceId=e,this.slsReporter.reportSwitchCamera(e)):t||(i.cameraDirection=this.publisher.cameraDirection==="environment"?yi.CAMERA_FRONT:yi.CAMERA_REAR,this.slsReporter.reportSwitchCamera(this.publisher.cameraDirection||"")),yield this.setCameraCapturerConfiguration(i),!this.publisher.cameraCaptureDisabled){(n=this.publisher.cameraTrack)==null||n.stop();const a={video:!0};t&&(a.mediaStream=new MediaStream([t])),yield this.publisher.createLocalStream(a)}})}getCurrentCameraDeviceId(){return this.publisher.getCurrentCameraDeviceId()}startPreview(){return _(this,null,function*(){if(this._audioOnlyMode)throw new W(z.ERR_INNER,"Cannot start preview camera in audio only mode");this.publisher.hasCamera||(yield this.enableLocalVideo(!0)),yield this.publisher.previewAll({screen:!1})})}startPreviewScreen(e){return _(this,null,function*(){if(this._audioOnlyMode)throw new W(z.ERR_INNER,"Cannot start preview screen share in audio only mode");this.publisher.hasScreenShare||(yield this.startScreenShare(e)),yield this.publisher.previewAll({primary:!1})})}stopPreview(){return _(this,null,function*(){yield this.publisher.stopPreview({primary:!0,screen:!1})})}stopPreviewScreen(){return _(this,null,function*(){yield this.publisher.stopPreview({primary:!1,screen:!0})})}getVideoTrack(e){return _(this,null,function*(){var a,c;const{userId:t,streamType:i}=e;if(!t)return i===Xe.AliRtcSdkStreamTypeCapture?this.publisher.cameraTrack:this.publisher.screenTrack;const n=this.bizControl.getRemoteUser(t);return i===Xe.AliRtcSdkStreamTypeCapture?(a=n==null?void 0:n.getCameraStream)==null?void 0:a.videoTrack:(c=n==null?void 0:n.getScreenStream)==null?void 0:c.videoTrack})}startPublishLiveStream(e,t){return _(this,null,function*(){return this.liveTranscoding.startPublishLiveStream(e,t)})}updatePublishLiveStream(e,t){return _(this,null,function*(){return this.liveTranscoding.updatePublishLiveStream(e,t)})}updatePublishLiveStreamWithTaskId(e,t){return this.liveTranscoding.updatePublishLiveStreamWithTaskId(e,t)}stopPublishLiveStream(e){return _(this,null,function*(){return this.liveTranscoding.stopPublishLiveStream(e)})}stopPublishLiveStreamWithTaskId(e){return this.liveTranscoding.stopPublishLiveStreamWithTaskId(e)}setEnableMediaExtensionMsg(e){var t;(t=this.bizControl)==null||t.setEnableMediaExtensionMsg(!!e)}sendMediaExtensionMsg(e,t){return _(this,null,function*(){return this.sendMediaExtensionMsgEx(e,t,5)})}sendMediaExtensionMsgEx(e,t,i){return _(this,null,function*(){if(!this.publisher||!this.isPublishing)throw new W(z.ERR_INNER,"you should publish first");return this.slsReporter.reportSEIMessage(i,e.byteLength,t,0,!1),this.publisher.sendSEI(e,t,i)})}enablePlugin(e,t){this.bizControl.pluginManager.add(e,t)}removePlugin(e){this.bizControl.pluginManager.remove(e)}setPluginOption(e,t){const i=this.bizControl.pluginManager.get(e);i&&t&&i.setOptions(t)}getPluginByName(e){return this.bizControl.pluginManager.get(e)}getPluginOption(e){const t=this.bizControl.pluginManager.get(e);return t==null?void 0:t.getOptions()}isBeautyAvailable(){return this.bizControl.pluginManager.has("AliRtcBeauty")}isBeautyEnabled(){const e=this.bizControl.pluginManager.get("AliRtcBeauty");if(!e)throw new W(vr.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");return!!(e!=null&&e.isEnable)}setBeautyEffect(e,t){const i=this.bizControl.pluginManager.get("AliRtcBeauty");if(!i)throw new W(vr.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");e?i.enable():i.disable(),i.setOptions({basicBeauty:{skinBuffing:Math.max(Math.min(1,+t.smoothnessLevel),0),whitening:Math.max(Math.min(1,+t.whiteningLevel),0)}})}enableBackgroundExchange(e,t){const i=this.bizControl.pluginManager.get("AliRtcBeauty");if(!i||!i.isEnable)throw new W(vr.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const n={setSegmentBackgroundImage:{backgroundImgUrl:e?t:""}};e&&(n.segmentBackgroundProcess={enable:!1}),i.setOptions(n)}enableBackgroundBlur(e){const t=this.bizControl.pluginManager.get("AliRtcBeauty");if(!t||!t.isEnable)throw new W(vr.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const i={segmentBackgroundProcess:{type:0,enable:e}};e&&(i.setSegmentBackgroundImage={type:0,backgroundImgUrl:""}),t.setOptions(i)}setParameter(e){this.bizControl.setParameter(e)}getParameter(){return this.bizControl.getParameter()}sendDataChannelMessage(e){this.bizControl.sendDataChannelMessage(e)}},b(ee,"logName","AliRtcEngine"),b(ee,"logError",!0),b(ee,"isSupported",vm),b(ee,"isDualVideoStreamSupported",Cn.isSupport),b(ee,"getCameraList",()=>_(ee,null,function*(){return(yield Pe.getCameraList()).filter(e=>e.deviceId)})),b(ee,"getMicrophoneList",()=>_(ee,null,function*(){return(yield Pe.getMicList()).filter(e=>e.deviceId)})),b(ee,"getSpeakerList",()=>_(ee,null,function*(){return(yield Pe.getSpeakerList()).filter(e=>e.deviceId)})),b(ee,"_instance"),b(ee,"AliRtcSdkChannelProfile",Jt),b(ee,"AliRtcSdkClientRole",gr),b(ee,"AliRtcVideoStreamType",it),b(ee,"AliRtcVideoTrack",be),b(ee,"AliRtcAudioTrack",Or),b(ee,"AliRtcPublishState",ne),b(ee,"AliRtcSubscribeState",ge),b(ee,"AliRtcRawDataStreamType",Xe),b(ee,"AliRtcLogLevel",un),b(ee,"AliRtcEngineLocalDeviceType",ir),b(ee,"AliRtcEngineLocalDeviceExceptionType",qe),b(ee,"AliRtcConnectionStatus",fe),b(ee,"AliRtcConnectionStatusChangeReason",$t),b(ee,"AliRtcPlugin",ur),b(ee,"AliRtcPluginTrackType",ii),b(ee,"AliRtcImageHolderPlugin",eh),b(ee,"AliRtcLiveTranscodingParam",Es),b(ee,"AliRtcLiveTranscodingEncodeParam",Zn),b(ee,"AliRtcLiveTranscodingMixParam",$l),b(ee,"AliRtcLiveTranscodingSingleParam",Xl),b(ee,"AliRtcTranscodingClockWidget",Zl),b(ee,"AliRtcTranscodingImage",aa),b(ee,"AliRtcTranscodingText",Ql),b(ee,"AliRtcTranscodingUser",ql),b(ee,"AliRtcLiveTranscodingMixMode",Ii),b(ee,"AliRtcLiveTranscodingStreamType",zn),b(ee,"AliRtcLiveTranscodingSourceType",ai),b(ee,"AliRtcLiveTranscodingTaskProfile",Kn),b(ee,"AliRtcLiveTranscodingAudioSampleRate",vs),b(ee,"AliRtcLiveTranscodingSegmentType",Di),b(ee,"AliRtcLiveTranscodingFontType",ki),b(ee,"AliRtcLiveTranscodingCropMode",Jn),b(ee,"AliRtcLiveTranscodingMediaProcessMode",Rs),b(ee,"AliRtcLiveTranscodingState",$n),b(ee,"AliRtcLiveTranscodingErrorCode",ar),b(ee,"AliRtcTrascodingPublishTaskStatus",Xn),b(ee,"AliRtcDataChannelMsg",br),b(ee,"AliRtcDataMsgType",gn),b(ee,"Plugin",ur),ee);Y([k()],Z.prototype,"destroy",1),Y([k()],Z.prototype,"backToUnpublishStatus",1),Y([k()],Z.prototype,"resumePublishForNetworkRecovery",1),Y([k()],Z.prototype,"onNetworkRecovery",1),Y([k()],Z.prototype,"resumeSubList",1),Y([k(J)],Z.prototype,"retrySubscribe",1),Y([k(J)],Z.prototype,"setEnableDualVideoStream",1),Y([k(J)],Z.prototype,"setChannelProfile",1),Y([k(J)],Z.prototype,"setClientRole",1),Y([k(J)],Z.prototype,"setAudioOnlyMode",1),Y([k()],Z.prototype,"clearCheckAuthInfoTimer",1),Y([k(J)],Z.prototype,"joinChannel",1),Y([k(J)],Z.prototype,"joinAIChannel",1),Y([k(J)],Z.prototype,"leaveChannel",1),Y([k(J)],Z.prototype,"refreshAuthInfo",1),Y([k(J)],Z.prototype,"publishLocalAudioStream",1),Y([k(J)],Z.prototype,"setDefaultSubscribeAllRemoteAudioStreams",1),Y([k(J)],Z.prototype,"subscribeAllRemoteAudioStreams",1),Y([k(J)],Z.prototype,"subscribeRemoteAudioStream",1),Y([k(J)],Z.prototype,"resumeRemoteAudioStream",1),Y([k(J)],Z.prototype,"stopRemoteAudioPlay",1),Y([k(J)],Z.prototype,"publishLocalVideoStream",1),Y([k(J)],Z.prototype,"setRemoteDefaultVideoStreamType",1),Y([k(J)],Z.prototype,"setRemoteUserVideoStreamType",1),Y([k(J)],Z.prototype,"setDefaultSubscribeAllRemoteVideoStreams",1),Y([k(J)],Z.prototype,"subscribeAllRemoteVideoStreams",1),Y([k(J)],Z.prototype,"subscribeRemoteMediaStream",1),Y([k(J)],Z.prototype,"resumeRemoteMediaStream",1),Y([k(([s])=>[`${s==null?void 0:s.audio}`])],Z.prototype,"startScreenShare",1),Y([k()],Z.prototype,"stopScreenShare",1),Y([k(J)],Z.prototype,"setScreenShareConfiguration",1),Y([k(J)],Z.prototype,"setScreenShareContentHint",1),Y([k()],Z.prototype,"publishLocalScreenShareStream",1),Y([k(J)],Z.prototype,"setAudioShareVolume",1),Y([k(J)],Z.prototype,"enableAudioVolumeIndication",1),Y([k(J)],Z.prototype,"muteLocalMic",1),Y([k(J)],Z.prototype,"muteRemoteAudioPlaying",1),Y([k(J)],Z.prototype,"muteAllRemoteAudioPlaying",1),Y([k(J)],Z.prototype,"startAudioCapture",1),Y([k(J)],Z.prototype,"setAudioConstraints",1),Y([k()],Z.prototype,"stopAudioCapture",1),Y([k(J)],Z.prototype,"switchMicrophone",1),Y([k(J)],Z.prototype,"setRecordingVolume",1),Y([k(J)],Z.prototype,"setPlayoutVolume",1),Y([k(J)],Z.prototype,"setRemoteAudioVolume",1),Y([k(J)],Z.prototype,"setAudioProfile",1),Y([k(J)],Z.prototype,"getAudioTrack",1),Y([k(J)],Z.prototype,"setLocalViewConfig",1),Y([k(J)],Z.prototype,"setCameraCapturerConfiguration",1),Y([k(J)],Z.prototype,"setCameraCapturerContentHint",1),Y([k(J)],Z.prototype,"enableLocalVideo",1),Y([k(J)],Z.prototype,"muteLocalCamera",1),Y([k(J)],Z.prototype,"muteLocalScreen",1),Y([k(J)],Z.prototype,"setRemoteViewConfig",1),Y([k(J)],Z.prototype,"switchCamera",1),Y([k()],Z.prototype,"startPreview",1),Y([k()],Z.prototype,"startPreviewScreen",1),Y([k()],Z.prototype,"stopPreview",1),Y([k()],Z.prototype,"stopPreviewScreen",1),Y([k()],Z.prototype,"startPublishLiveStream",1),Y([k()],Z.prototype,"updatePublishLiveStream",1),Y([k()],Z.prototype,"updatePublishLiveStreamWithTaskId",1),Y([k()],Z.prototype,"stopPublishLiveStream",1),Y([k()],Z.prototype,"stopPublishLiveStreamWithTaskId",1),Y([k(J)],Z.prototype,"setEnableMediaExtensionMsg",1),Y([k(([s,r,e])=>[s.byteLength,r,e])],Z.prototype,"sendMediaExtensionMsgEx",1),Y([k(([s,r])=>[s.name||"",r])],Z.prototype,"enablePlugin",1),Y([k(J)],Z.prototype,"removePlugin",1),Y([k(J)],Z.prototype,"setPluginOption",1),Y([k(J)],Z.prototype,"getPluginByName",1),Y([k(J)],Z.prototype,"getPluginOption",1),Y([k(J)],Z.prototype,"setBeautyEffect",1),Y([k(J)],Z.prototype,"enableBackgroundExchange",1),Y([k(J)],Z.prototype,"enableBackgroundBlur",1),Y([k(J)],Z.prototype,"setParameter",1),Y([k(([s])=>{var r;return[(r=s.data)==null?void 0:r.byteLength]})],Z.prototype,"sendDataChannelMessage",1),Y([k(J)],Z,"setLogLevel",1);let th=Z;const rh=new Bn({businessName:"imp-web-rtc",version:(ih=th.getSdkVersion())!=null?ih:"unknown",env:"prod",disabled:window.AliRtcOptionsDisableProxy===!0});rh.setReady();const zm=rh.wrap(th);q.AliRtcAudioTrack=Or,q.AliRtcCapabilityProfile=ni,q.AliRtcConnectionStatus=fe,q.AliRtcConnectionStatusChangeReason=$t,q.AliRtcDataChannelMsg=br,q.AliRtcDataMsgType=gn,q.AliRtcEngineLocalDeviceExceptionType=qe,q.AliRtcEngineLocalDeviceType=ir,q.AliRtcErrorCode=z,q.AliRtcImageHolderPlugin=eh,q.AliRtcLiveTranscodingAudioSampleRate=vs,q.AliRtcLiveTranscodingCropMode=Jn,q.AliRtcLiveTranscodingEncodeParam=Zn,q.AliRtcLiveTranscodingErrorCode=ar,q.AliRtcLiveTranscodingFontType=ki,q.AliRtcLiveTranscodingMediaProcessMode=Rs,q.AliRtcLiveTranscodingMixMode=Ii,q.AliRtcLiveTranscodingMixParam=$l,q.AliRtcLiveTranscodingParam=Es,q.AliRtcLiveTranscodingSegmentType=Di,q.AliRtcLiveTranscodingSingleParam=Xl,q.AliRtcLiveTranscodingSourceType=ai,q.AliRtcLiveTranscodingState=$n,q.AliRtcLiveTranscodingStreamType=zn,q.AliRtcLiveTranscodingTaskProfile=Kn,q.AliRtcLocalStreamInfo=jn,q.AliRtcLogLevel=un,q.AliRtcPlugin=ur,q.AliRtcPluginTrackType=ii,q.AliRtcPluginType=Ll,q.AliRtcPublishState=ne,q.AliRtcRawDataStreamType=Xe,q.AliRtcRemoteUserInfo=Nl,q.AliRtcSdkChannelProfile=Jt,q.AliRtcSdkClientRole=gr,q.AliRtcSubscribeState=ge,q.AliRtcTranscodingClockWidget=Zl,q.AliRtcTranscodingImage=aa,q.AliRtcTranscodingText=Ql,q.AliRtcTranscodingUser=ql,q.AliRtcTrascodingPublishTaskStatus=Xn,q.AliRtcVideoStreamType=it,q.AliRtcVideoTrack=be,q.default=zm,Object.defineProperties(q,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});