/**
 * AgoraWebSDK_N-v4.24.4-0-gb4d645709-dirty Copyright AgoraInc.
 */

function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var i=function(e){try{return!!e()}catch(e){return!0}},r=!i((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),o=r,s=Function.prototype,a=s.call,c=o&&s.bind.bind(a,a),d=o?c:function(e){return function(){return a.apply(e,arguments)}},l=d({}.isPrototypeOf),u=function(e){return e&&e.Math===Math&&e},h=u("object"==typeof globalThis&&globalThis)||u("object"==typeof window&&window)||u("object"==typeof self&&self)||u("object"==typeof t&&t)||u("object"==typeof t&&t)||function(){return this}()||Function("return this")(),p=r,_=Function.prototype,E=_.apply,m=_.call,f="object"==typeof Reflect&&Reflect.apply||(p?m.bind(E):function(){return m.apply(E,arguments)}),g=d,S=g({}.toString),T=g("".slice),R=function(e){return T(S(e),8,-1)},v=R,y=d,b=function(e){if("Function"===v(e))return y(e)},C="object"==typeof document&&document.all,I=void 0===C&&void 0!==C?function(e){return"function"==typeof e||e===C}:function(e){return"function"==typeof e},A={},w=!i((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]})),O=r,N=Function.prototype.call,D=O?N.bind(N):function(){return N.apply(N,arguments)},P={},L={}.propertyIsEnumerable,k=Object.getOwnPropertyDescriptor,M=k&&!L.call({1:2},1);P.f=M?function(e){var t=k(this,e);return!!t&&t.enumerable}:L;var U,V,x=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},F=i,B=R,j=Object,G=d("".split),W=F((function(){return!j("z").propertyIsEnumerable(0)}))?function(e){return"String"===B(e)?G(e,""):j(e)}:j,K=function(e){return null==e},H=K,Y=TypeError,X=function(e){if(H(e))throw new Y("Can't call method on "+e);return e},J=W,z=X,Z=function(e){return J(z(e))},q=I,Q=function(e){return"object"==typeof e?null!==e:q(e)},$={},ee=$,te=h,ne=I,ie=function(e){return ne(e)?e:void 0},re=function(e,t){return arguments.length<2?ie(ee[e])||ie(te[e]):ee[e]&&ee[e][t]||te[e]&&te[e][t]},oe=h.navigator,se=oe&&oe.userAgent,ae=se?String(se):"",ce=h,de=ae,le=ce.process,ue=ce.Deno,he=le&&le.versions||ue&&ue.version,pe=he&&he.v8;pe&&(V=(U=pe.split("."))[0]>0&&U[0]<4?1:+(U[0]+U[1])),!V&&de&&(!(U=de.match(/Edge\/(\d+)/))||U[1]>=74)&&(U=de.match(/Chrome\/(\d+)/))&&(V=+U[1]);var _e=V,Ee=_e,me=i,fe=h.String,ge=!!Object.getOwnPropertySymbols&&!me((function(){var e=Symbol("symbol detection");return!fe(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&Ee&&Ee<41})),Se=ge&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,Te=re,Re=I,ve=l,ye=Object,be=Se?function(e){return"symbol"==typeof e}:function(e){var t=Te("Symbol");return Re(t)&&ve(t.prototype,ye(e))},Ce=String,Ie=function(e){try{return Ce(e)}catch(e){return"Object"}},Ae=I,we=Ie,Oe=TypeError,Ne=function(e){if(Ae(e))return e;throw new Oe(we(e)+" is not a function")},De=Ne,Pe=K,Le=function(e,t){var n=e[t];return Pe(n)?void 0:De(n)},ke=D,Me=I,Ue=Q,Ve=TypeError,xe={exports:{}},Fe=h,Be=Object.defineProperty,je=h,Ge=function(e,t){try{Be(Fe,e,{value:t,configurable:!0,writable:!0})}catch(n){Fe[e]=t}return t},We="__core-js_shared__",Ke=xe.exports=je[We]||Ge(We,{});(Ke.versions||(Ke.versions=[])).push({version:"3.49.0",mode:"pure",copyright:"© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.",license:"https://github.com/zloirock/core-js/blob/v3.49.0/LICENSE",source:"https://github.com/zloirock/core-js"});var He=xe.exports,Ye=He,Xe=function(e,t){return Ye[e]||(Ye[e]=t||{})},Je=X,ze=Object,Ze=function(e){return ze(Je(e))},qe=Ze,Qe=d({}.hasOwnProperty),$e=Object.hasOwn||function(e,t){return Qe(qe(e),t)},et=d,tt=0,nt=Math.random(),it=et(1.1.toString),rt=function(e){return"Symbol("+(void 0===e?"":e)+")_"+it(++tt+nt,36)},ot=Xe,st=$e,at=rt,ct=ge,dt=Se,lt=h.Symbol,ut=ot("wks"),ht=dt?lt.for||lt:lt&&lt.withoutSetter||at,pt=function(e){return st(ut,e)||(ut[e]=ct&&st(lt,e)?lt[e]:ht("Symbol."+e)),ut[e]},_t=D,Et=Q,mt=be,ft=Le,gt=function(e,t){var n,i;if("string"===t&&Me(n=e.toString)&&!Ue(i=ke(n,e)))return i;if(Me(n=e.valueOf)&&!Ue(i=ke(n,e)))return i;if("string"!==t&&Me(n=e.toString)&&!Ue(i=ke(n,e)))return i;throw new Ve("Can't convert object to primitive value")},St=TypeError,Tt=pt("toPrimitive"),Rt=function(e,t){if(!Et(e)||mt(e))return e;var n,i=ft(e,Tt);if(i){if(void 0===t&&(t="default"),n=_t(i,e,t),!Et(n)||mt(n))return n;throw new St("Can't convert object to primitive value")}return void 0===t&&(t="number"),gt(e,t)},vt=be,yt=function(e){var t=Rt(e,"string");return vt(t)?t:t+""},bt=Q,Ct=h.document,It=bt(Ct)&&bt(Ct.createElement),At=function(e){return It?Ct.createElement(e):{}},wt=At,Ot=!w&&!i((function(){return 7!==Object.defineProperty(wt("div"),"a",{get:function(){return 7}}).a})),Nt=w,Dt=D,Pt=P,Lt=x,kt=Z,Mt=yt,Ut=$e,Vt=Ot,xt=Object.getOwnPropertyDescriptor;A.f=Nt?xt:function(e,t){if(e=kt(e),t=Mt(t),Vt)try{return xt(e,t)}catch(e){}if(Ut(e,t))return Lt(!Dt(Pt.f,e,t),e[t])};var Ft=i,Bt=I,jt=/#|\.prototype\./,Gt=function(e,t){var n=Kt[Wt(e)];return n===Yt||n!==Ht&&(Bt(t)?Ft(t):!!t)},Wt=Gt.normalize=function(e){return String(e).replace(jt,".").toLowerCase()},Kt=Gt.data={},Ht=Gt.NATIVE="N",Yt=Gt.POLYFILL="P",Xt=Gt,Jt=Ne,zt=r,Zt=b(b.bind),qt=function(e,t){return Jt(e),void 0===t?e:zt?Zt(e,t):function(){return e.apply(t,arguments)}},Qt={},$t=w&&i((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),en=Q,tn=String,nn=TypeError,rn=function(e){if(en(e))return e;throw new nn(tn(e)+" is not an object")},on=w,sn=Ot,an=$t,cn=rn,dn=yt,ln=TypeError,un=Object.defineProperty,hn=Object.getOwnPropertyDescriptor,pn="enumerable",_n="configurable",En="writable";Qt.f=on?an?function(e,t,n){if(cn(e),t=dn(t),cn(n),"function"==typeof e&&"prototype"===t&&"value"in n&&En in n&&!n[En]){var i=hn(e,t);i&&i[En]&&(e[t]=n.value,n={configurable:_n in n?n[_n]:i[_n],enumerable:pn in n?n[pn]:i[pn],writable:!1})}return un(e,t,n)}:un:function(e,t,n){if(cn(e),t=dn(t),cn(n),sn)try{return un(e,t,n)}catch(e){}if("get"in n||"set"in n)throw new ln("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var mn=Qt,fn=x,gn=w?function(e,t,n){return mn.f(e,t,fn(1,n))}:function(e,t,n){return e[t]=n,e},Sn=h,Tn=f,Rn=b,vn=I,yn=A.f,bn=Xt,Cn=$,In=qt,An=gn,wn=$e,On=function(e){var t=function(n,i,r){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(n);case 2:return new e(n,i)}return new e(n,i,r)}return Tn(e,this,arguments)};return t.prototype=e.prototype,t},Nn=function(e,t){var n,i,r,o,s,a,c,d,l,u=e.target,h=e.global,p=e.stat,_=e.proto,E=h?Sn:p?Sn[u]:Sn[u]&&Sn[u].prototype,m=h?Cn:Cn[u]||An(Cn,u,{})[u],f=m.prototype;for(o in t)i=!(n=bn(h?o:u+(p?".":"#")+o,e.forced))&&E&&wn(E,o),a=m[o],i&&(c=e.dontCallGetSet?(l=yn(E,o))&&l.value:E[o]),s=i&&c?c:t[o],(n||_||typeof a!=typeof s)&&(d=e.bind&&i?In(s,Sn):e.wrap&&i?On(s):_&&vn(s)?Rn(s):s,(e.sham||s&&s.sham||a&&a.sham)&&An(d,"sham",!0),An(m,o,d),_&&(wn(Cn,r=u+"Prototype")||An(Cn,r,{}),An(Cn[r],o,s),e.real&&f&&(n||!f[o])&&An(f,o,s)))},Dn=Math.ceil,Pn=Math.floor,Ln=Math.trunc||function(e){var t=+e;return(t>0?Pn:Dn)(t)},kn=Ln,Mn=function(e){var t=+e;return t!=t||0===t?0:kn(t)},Un=Mn,Vn=Math.max,xn=Math.min,Fn=function(e,t){var n=Un(e);return n<0?Vn(n+t,0):xn(n,t)},Bn=Mn,jn=Math.min,Gn=function(e){var t=Bn(e);return t>0?jn(t,9007199254740991):0},Wn=Gn,Kn=function(e){return Wn(e.length)},Hn=Z,Yn=Fn,Xn=Kn,Jn=function(e){return function(t,n,i){var r=Hn(t),o=Xn(r);if(0===o)return!e&&-1;var s,a=Yn(i,o);if(e&&n!=n){for(;o>a;)if((s=r[a++])!=s)return!0}else for(;o>a;a++)if((e||a in r)&&r[a]===n)return e||a||0;return!e&&-1}},zn={includes:Jn(!0),indexOf:Jn(!1)},Zn=Nn,qn=zn.includes,Qn=i,$n=Qn((function(){return!Array(1).includes()})),ei=Qn((function(){return[,1].includes(void 0,1)}));Zn({target:"Array",proto:!0,forced:$n||ei},{includes:function(e){return qn(this,e,arguments.length>1?arguments[1]:void 0)}});var ti=h,ni=$,ii=function(e,t){var n=ni[e+"Prototype"],i=n&&n[t];if(i)return i;var r=ti[e],o=r&&r.prototype;return o&&o[t]},ri=ii("Array","includes"),oi=Q,si=R,ai=pt("match"),ci=function(e){var t;return oi(e)&&(void 0!==(t=e[ai])?!!t:"RegExp"===si(e))},di=ci,li=TypeError,ui={};ui[pt("toStringTag")]="z";var hi="[object z]"===String(ui),pi=hi,_i=I,Ei=R,mi=pt("toStringTag"),fi=Object,gi="Arguments"===Ei(function(){return arguments}()),Si=pi?Ei:function(e){var t,n,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=fi(e),mi))?n:gi?Ei(t):"Object"===(i=Ei(t))&&_i(t.callee)?"Arguments":i},Ti=Si,Ri=String,vi=function(e){if("Symbol"===Ti(e))throw new TypeError("Cannot convert a Symbol value to a string");return Ri(e)},yi=pt("match"),bi=Nn,Ci=function(e){if(di(e))throw new li("The method doesn't accept regular expressions");return e},Ii=X,Ai=vi,wi=function(e){var t=/./;try{"/./"[e](t)}catch(n){try{return t[yi]=!1,"/./"[e](t)}catch(e){}}return!1},Oi=d("".indexOf);bi({target:"String",proto:!0,forced:!wi("includes")},{includes:function(e){return!!~Oi(Ai(Ii(this)),Ai(Ci(e)),arguments.length>1?arguments[1]:void 0)}});var Ni=ii("String","includes"),Di=l,Pi=ri,Li=Ni,ki=Array.prototype,Mi=String.prototype,Ui=function(e){var t=e.includes;return e===ki||Di(ki,e)&&t===ki.includes?Pi:"string"==typeof e||e===Mi||Di(Mi,e)&&t===Mi.includes?Li:t},Vi=n(Ui),xi=Ne,Fi=Ze,Bi=W,ji=Kn,Gi=TypeError,Wi="Reduce of empty array with no initial value",Ki=function(e){return function(t,n,i,r){var o=Fi(t),s=Bi(o),a=ji(o);if(xi(n),0===a&&i<2)throw new Gi(Wi);var c=e?a-1:0,d=e?-1:1;if(i<2)for(;;){if(c in s){r=s[c],c+=d;break}if(c+=d,e?c<0:a<=c)throw new Gi(Wi)}for(;e?c>=0:a>c;c+=d)c in s&&(r=n(r,s[c],c,o));return r}},Hi={left:Ki(!1),right:Ki(!0)},Yi=i,Xi=function(e,t){var n=[][e];return!!n&&Yi((function(){n.call(null,t||function(){return 1},1)}))},Ji=h,zi=ae,Zi=R,qi=function(e){return zi.slice(0,e.length)===e},Qi=qi("Bun/")?"BUN":qi("Cloudflare-Workers")?"CLOUDFLARE":qi("Deno/")?"DENO":qi("Node.js/")?"NODE":Ji.Bun&&"string"==typeof Bun.version?"BUN":Ji.Deno&&"object"==typeof Deno.version?"DENO":"process"===Zi(Ji.process)?"NODE":Ji.window&&Ji.document?"BROWSER":"REST",$i="NODE"===Qi,er=Hi.left;Nn({target:"Array",proto:!0,forced:!$i&&_e>79&&_e<83||!Xi("reduce")},{reduce:function(e){var t=arguments.length;return er(this,e,t,t>1?arguments[1]:void 0)}});var tr=ii("Array","reduce"),nr=l,ir=tr,rr=Array.prototype,or=function(e){var t=e.reduce;return e===rr||nr(rr,e)&&t===rr.reduce?ir:t},sr=or,ar=n(sr),cr=R,dr=Array.isArray||function(e){return"Array"===cr(e)},lr=Nn,ur=dr,hr=d([].reverse),pr=[1,2];lr({target:"Array",proto:!0,forced:String(pr)===String(pr.reverse())},{reverse:function(){return ur(this)&&(this.length=this.length),hr(this)}});var _r=ii("Array","reverse"),Er=l,mr=_r,fr=Array.prototype,gr=function(e){var t=e.reverse;return e===fr||Er(fr,e)&&t===fr.reverse?mr:t},Sr=gr,Tr=n(Sr),Rr=rt,vr=Xe("keys"),yr=function(e){return vr[e]||(vr[e]=Rr(e))},br=!i((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Cr=$e,Ir=I,Ar=Ze,wr=br,Or=yr("IE_PROTO"),Nr=Object,Dr=Nr.prototype,Pr=wr?Nr.getPrototypeOf:function(e){var t=Ar(e);if(Cr(t,Or))return t[Or];var n=t.constructor;return Ir(n)&&t instanceof n?n.prototype:t instanceof Nr?Dr:null},Lr=d,kr=Ne,Mr=Q,Ur=function(e){return Mr(e)||null===e},Vr=String,xr=TypeError,Fr=function(e,t,n){try{return Lr(kr(Object.getOwnPropertyDescriptor(e,t)[n]))}catch(e){}},Br=Q,jr=X,Gr=function(e){if(Ur(e))return e;throw new xr("Can't set "+Vr(e)+" as a prototype")},Wr=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,n={};try{(e=Fr(Object.prototype,"__proto__","set"))(n,[]),t=n instanceof Array}catch(e){}return function(n,i){return jr(n),Gr(i),Br(n)?(t?e(n,i):n.__proto__=i,n):n}}():void 0),Kr={},Hr={},Yr=$e,Xr=Z,Jr=zn.indexOf,zr=Hr,Zr=d([].push),qr=function(e,t){var n,i=Xr(e),r=0,o=[];for(n in i)!Yr(zr,n)&&Yr(i,n)&&Zr(o,n);for(;t.length>r;)Yr(i,n=t[r++])&&(~Jr(o,n)||Zr(o,n));return o},Qr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],$r=qr,eo=Qr.concat("length","prototype");Kr.f=Object.getOwnPropertyNames||function(e){return $r(e,eo)};var to={};to.f=Object.getOwnPropertySymbols;var no=re,io=Kr,ro=to,oo=rn,so=d([].concat),ao=no("Reflect","ownKeys")||function(e){var t=io.f(oo(e)),n=ro.f;return n?so(t,n(e)):t},co=$e,lo=ao,uo=A,ho=Qt,po={},_o=qr,Eo=Qr,mo=Object.keys||function(e){return _o(e,Eo)},fo=w,go=$t,So=Qt,To=rn,Ro=Z,vo=mo;po.f=fo&&!go?Object.defineProperties:function(e,t){To(e);for(var n,i=Ro(t),r=vo(t),o=r.length,s=0;o>s;)So.f(e,n=r[s++],i[n]);return e};var yo,bo=re("document","documentElement"),Co=rn,Io=po,Ao=Qr,wo=Hr,Oo=bo,No=At,Do="prototype",Po="script",Lo=yr("IE_PROTO"),ko=function(){},Mo=function(e){return"<"+Po+">"+e+"</"+Po+">"},Uo=function(e){e.write(Mo("")),e.close();var t=e.parentWindow.Object;return e=null,t},Vo=function(){try{yo=new ActiveXObject("htmlfile")}catch(e){}var e,t,n;Vo="undefined"!=typeof document?document.domain&&yo?Uo(yo):(t=No("iframe"),n="java"+Po+":",t.style.display="none",Oo.appendChild(t),t.src=String(n),(e=t.contentWindow.document).open(),e.write(Mo("document.F=Object")),e.close(),e.F):Uo(yo);for(var i=Ao.length;i--;)delete Vo[Do][Ao[i]];return Vo()};wo[Lo]=!0;var xo=Object.create||function(e,t){var n;return null!==e?(ko[Do]=Co(e),n=new ko,ko[Do]=null,n[Lo]=e):n=Vo(),void 0===t?n:Io.f(n,t)},Fo=Q,Bo=gn,jo=Error,Go=d("".replace),Wo=String(new jo("zxcasd").stack),Ko=/\n\s*at [^:]*:[^\n]*/,Ho=Ko.test(Wo),Yo=x,Xo=!i((function(){var e=new Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",Yo(1,7)),7!==e.stack)})),Jo=gn,zo=function(e,t){if(Ho&&"string"==typeof e&&!jo.prepareStackTrace)for(;t--;)e=Go(e,Ko,"");return e},Zo=Xo,qo=Error.captureStackTrace,Qo={},$o=Qo,es=pt("iterator"),ts=Array.prototype,ns=function(e){return void 0!==e&&($o.Array===e||ts[es]===e)},is=Si,rs=Le,os=K,ss=Qo,as=pt("iterator"),cs=function(e){if(!os(e))return rs(e,as)||rs(e,"@@iterator")||ss[is(e)]},ds=D,ls=Ne,us=rn,hs=Ie,ps=cs,_s=TypeError,Es=function(e,t){var n=arguments.length<2?ps(e):t;if(ls(n))return us(ds(n,e));throw new _s(hs(e)+" is not iterable")},ms=D,fs=rn,gs=Le,Ss=function(e,t,n){var i,r;fs(e);try{if(!(i=gs(e,"return"))){if("throw"===t)throw n;return n}i=ms(i,e)}catch(e){r=!0,i=e}if("throw"===t)throw n;if(r)throw i;return fs(i),n},Ts=qt,Rs=D,vs=rn,ys=Ie,bs=ns,Cs=Kn,Is=l,As=Es,ws=cs,Os=Ss,Ns=TypeError,Ds=function(e,t){this.stopped=e,this.result=t},Ps=Ds.prototype,Ls=function(e,t,n){var i,r,o,s,a,c,d,l=n&&n.that,u=!(!n||!n.AS_ENTRIES),h=!(!n||!n.IS_RECORD),p=!(!n||!n.IS_ITERATOR),_=!(!n||!n.INTERRUPTED),E=Ts(t,l),m=function(e){var t=i;return i=void 0,t&&Os(t,"normal"),new Ds(!0,e)},f=function(e){return u?(vs(e),_?E(e[0],e[1],m):E(e[0],e[1])):_?E(e,m):E(e)};if(h)i=e.iterator;else if(p)i=e;else{if(!(r=ws(e)))throw new Ns(ys(e)+" is not iterable");if(bs(r)){for(o=0,s=Cs(e);s>o;o++)if((a=f(e[o]))&&Is(Ps,a))return a;return new Ds(!1)}i=As(e,r)}for(c=h?e.next:i.next;!(d=Rs(c,i)).done;){var g=d.value;try{a=f(g)}catch(e){if(!i)throw e;Os(i,"throw",e)}if("object"==typeof a&&a&&Is(Ps,a))return a}return new Ds(!1)},ks=vi,Ms=Nn,Us=l,Vs=Pr,xs=Wr,Fs=function(e,t,n){for(var i=lo(t),r=ho.f,o=uo.f,s=0;s<i.length;s++){var a=i[s];co(e,a)||n&&co(n,a)||r(e,a,o(t,a))}},Bs=xo,js=gn,Gs=x,Ws=function(e,t){Fo(t)&&"cause"in t&&Bo(e,"cause",t.cause)},Ks=function(e,t,n,i){Zo&&(qo?qo(e,t):Jo(e,"stack",zo(n,i)))},Hs=Ls,Ys=function(e,t){return void 0===e?arguments.length<2?"":t:ks(e)},Xs=pt("toStringTag"),Js=Error,zs=[].push,Zs=function(e,t){var n,i=Us(qs,this);xs?n=xs(new Js,i?Vs(this):qs):(n=i?this:Bs(qs),js(n,Xs,"Error")),void 0!==t&&js(n,"message",Ys(t)),Ks(n,Zs,n.stack,1),arguments.length>2&&Ws(n,arguments[2]);var r=[];return Hs(e,zs,{that:r}),js(n,"errors",r),n};xs?xs(Zs,Js):Fs(Zs,Js,{name:!0});var qs=Zs.prototype=Bs(Js.prototype,{constructor:Gs(1,Zs),message:Gs(1,""),name:Gs(1,"AggregateError")});Ms({global:!0,constructor:!0,arity:2},{AggregateError:Zs});var Qs,$s,ea,ta=I,na=h.WeakMap,ia=ta(na)&&/native code/.test(String(na)),ra=h,oa=Q,sa=gn,aa=$e,ca=He,da=yr,la=Hr,ua="Object already initialized",ha=ra.TypeError,pa=ra.WeakMap;if(ia||ca.state){var _a=ca.state||(ca.state=new pa);_a.get=_a.get,_a.has=_a.has,_a.set=_a.set,Qs=function(e,t){if(_a.has(e))throw new ha(ua);return t.facade=e,_a.set(e,t),t},$s=function(e){return _a.get(e)||{}},ea=function(e){return _a.has(e)}}else{var Ea=da("state");la[Ea]=!0,Qs=function(e,t){if(aa(e,Ea))throw new ha(ua);return t.facade=e,sa(e,Ea,t),t},$s=function(e){return aa(e,Ea)?e[Ea]:{}},ea=function(e){return aa(e,Ea)}}var ma,fa,ga,Sa={set:Qs,get:$s,has:ea,enforce:function(e){return ea(e)?$s(e):Qs(e,{})},getterFor:function(e){return function(t){var n;if(!oa(t)||(n=$s(t)).type!==e)throw new ha("Incompatible receiver, "+e+" required");return n}}},Ta=w,Ra=$e,va=Function.prototype,ya=Ta&&Object.getOwnPropertyDescriptor,ba=Ra(va,"name"),Ca={EXISTS:ba,PROPER:ba&&"something"===function(){}.name,CONFIGURABLE:ba&&(!Ta||Ta&&ya(va,"name").configurable)},Ia=gn,Aa=function(e,t,n,i){return i&&i.enumerable?e[t]=n:Ia(e,t,n),e},wa=i,Oa=I,Na=Q,Da=xo,Pa=Pr,La=Aa,ka=pt("iterator"),Ma=!1;[].keys&&("next"in(ga=[].keys())?(fa=Pa(Pa(ga)))!==Object.prototype&&(ma=fa):Ma=!0);var Ua=!Na(ma)||wa((function(){var e={};return ma[ka].call(e)!==e}));Oa((ma=Ua?{}:Da(ma))[ka])||La(ma,ka,(function(){return this}));var Va={IteratorPrototype:ma,BUGGY_SAFARI_ITERATORS:Ma},xa=Si,Fa=hi?{}.toString:function(){return"[object "+xa(this)+"]"},Ba=hi,ja=Qt.f,Ga=gn,Wa=$e,Ka=Fa,Ha=pt("toStringTag"),Ya=function(e,t,n,i){var r=n?e:e&&e.prototype;r&&(Wa(r,Ha)||ja(r,Ha,{configurable:!0,value:t}),i&&!Ba&&Ga(r,"toString",Ka))},Xa=Va.IteratorPrototype,Ja=xo,za=x,Za=Ya,qa=Qo,Qa=function(){return this},$a=function(e,t,n,i){var r=t+" Iterator";return e.prototype=Ja(Xa,{next:za(+!i,n)}),Za(e,r,!1,!0),qa[r]=Qa,e},ec=Nn,tc=D,nc=Ca,ic=$a,rc=Pr,oc=Ya,sc=Aa,ac=Qo,cc=Va,dc=nc.PROPER,lc=cc.BUGGY_SAFARI_ITERATORS,uc=pt("iterator"),hc="keys",pc="values",_c="entries",Ec=function(){return this},mc=function(e,t,n,i,r,o,s){ic(n,t,i);var a,c,d,l=function(e){if(e===r&&E)return E;if(!lc&&e&&e in p)return p[e];switch(e){case hc:case pc:case _c:return function(){return new n(this,e)}}return function(){return new n(this)}},u=t+" Iterator",h=!1,p=e.prototype,_=p[uc]||p["@@iterator"]||r&&p[r],E=!lc&&_||l(r),m="Array"===t&&p.entries||_;if(m&&(a=rc(m.call(new e)))!==Object.prototype&&a.next&&(oc(a,u,!0,!0),ac[u]=Ec),dc&&r===pc&&_&&_.name!==pc&&(h=!0,E=function(){return tc(_,this)}),r)if(c={values:l(pc),keys:o?E:l(hc),entries:l(_c)},s)for(d in c)(lc||h||!(d in p))&&sc(p,d,c[d]);else ec({target:t,proto:!0,forced:lc||h},c);return s&&p[uc]!==E&&sc(p,uc,E,{name:r}),ac[t]=E,c},fc=function(e,t){return{value:e,done:t}},gc=Z,Sc=Qo,Tc=Sa;Qt.f;var Rc=mc,vc=fc,yc="Array Iterator",bc=Tc.set,Cc=Tc.getterFor(yc);Rc(Array,"Array",(function(e,t){bc(this,{type:yc,target:gc(e),index:0,kind:t})}),(function(){var e=Cc(this),t=e.target,n=e.index++;if(!t||n>=t.length)return e.target=null,vc(void 0,!0);switch(e.kind){case"keys":return vc(n,!1);case"values":return vc(t[n],!1)}return vc([n,t[n]],!1)}),"values"),Sc.Arguments=Sc.Array;var Ic=Qt,Ac=function(e,t,n){return Ic.f(e,t,n)},wc=re,Oc=Ac,Nc=w,Dc=pt("species"),Pc=l,Lc=TypeError,kc=function(e,t){if(Pc(t,e))return e;throw new Lc("Incorrect invocation")},Mc=I,Uc=He,Vc=d(Function.toString);Mc(Uc.inspectSource)||(Uc.inspectSource=function(e){return Vc(e)});var xc=Uc.inspectSource,Fc=d,Bc=i,jc=I,Gc=Si,Wc=xc,Kc=function(){},Hc=re("Reflect","construct"),Yc=/^\s*(?:class|function)\b/,Xc=Fc(Yc.exec),Jc=!Yc.test(Kc),zc=function(e){if(!jc(e))return!1;try{return Hc(Kc,[],e),!0}catch(e){return!1}},Zc=function(e){if(!jc(e))return!1;switch(Gc(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Jc||!!Xc(Yc,Wc(e))}catch(e){return!0}};Zc.sham=!0;var qc,Qc,$c,ed,td=!Hc||Bc((function(){var e;return zc(zc.call)||!zc(Object)||!zc((function(){e=!0}))||e}))?Zc:zc,nd=td,id=Ie,rd=TypeError,od=rn,sd=function(e){if(nd(e))return e;throw new rd(id(e)+" is not a constructor")},ad=K,cd=pt("species"),dd=function(e,t){var n,i=od(e).constructor;return void 0===i||ad(n=od(i)[cd])?t:sd(n)},ld=d([].slice),ud=TypeError,hd=function(e,t){if(e<t)throw new ud("Not enough arguments");return e},pd=ae,_d=/ipad|iphone|ipod/i.test(pd)&&/applewebkit/i.test(pd),Ed=h,md=f,fd=qt,gd=I,Sd=$e,Td=i,Rd=bo,vd=ld,yd=At,bd=hd,Cd=_d,Id=$i,Ad=Ed.setImmediate,wd=Ed.clearImmediate,Od=Ed.process,Nd=Ed.Dispatch,Dd=Ed.Function,Pd=Ed.MessageChannel,Ld=Ed.String,kd=0,Md={},Ud="onreadystatechange";Td((function(){qc=Ed.location}));var Vd=function(e){if(Sd(Md,e)){var t=Md[e];delete Md[e],t()}},xd=function(e){return function(){Vd(e)}},Fd=function(e){Vd(e.data)},Bd=function(e){Ed.postMessage(Ld(e),qc.protocol+"//"+qc.host)};Ad&&wd||(Ad=function(e){bd(arguments.length,1);var t=gd(e)?e:Dd(e),n=vd(arguments,1);return Md[++kd]=function(){md(t,void 0,n)},Qc(kd),kd},wd=function(e){delete Md[e]},Id?Qc=function(e){Od.nextTick(xd(e))}:Nd&&Nd.now?Qc=function(e){Nd.now(xd(e))}:Pd&&!Cd?(ed=($c=new Pd).port2,$c.port1.onmessage=Fd,Qc=fd(ed.postMessage,ed)):Ed.addEventListener&&gd(Ed.postMessage)&&!Ed.importScripts&&qc&&"file:"!==qc.protocol&&!Td(Bd)?(Qc=Bd,Ed.addEventListener("message",Fd,!1)):Qc=Ud in yd("script")?function(e){Rd.appendChild(yd("script"))[Ud]=function(){Rd.removeChild(this),Vd(e)}}:function(e){setTimeout(xd(e),0)});var jd={set:Ad,clear:wd},Gd=h,Wd=w,Kd=Object.getOwnPropertyDescriptor,Hd=function(e){if(!Wd)return Gd[e];var t=Kd(Gd,e);return t&&t.value},Yd=function(){this.head=null,this.tail=null};Yd.prototype={add:function(e){var t={item:e,next:null},n=this.tail;n?n.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var Xd,Jd,zd,Zd,qd,Qd=Yd,$d=/ipad|iphone|ipod/i.test(ae)&&"undefined"!=typeof Pebble,el=/web0s(?!.*chrome)/i.test(ae),tl=h,nl=Hd,il=qt,rl=jd.set,ol=Qd,sl=_d,al=$d,cl=el,dl=$i,ll=tl.MutationObserver||tl.WebKitMutationObserver,ul=tl.document,hl=tl.process,pl=tl.Promise,_l=nl("queueMicrotask");if(!_l){var El=new ol,ml=function(){var e,t;for(dl&&(e=hl.domain)&&e.exit();t=El.get();)try{t()}catch(e){throw El.head&&Xd(),e}e&&e.enter()};sl||dl||cl||!ll||!ul?!al&&pl&&pl.resolve?((Zd=pl.resolve(void 0)).constructor=pl,qd=il(Zd.then,Zd),Xd=function(){qd(ml)}):dl?Xd=function(){hl.nextTick(ml)}:(rl=il(rl,tl),Xd=function(){rl(ml)}):(Jd=!0,zd=ul.createTextNode(""),new ll(ml).observe(zd,{characterData:!0}),Xd=function(){zd.data=Jd=!Jd}),_l=function(e){El.head||Xd(),El.add(e)}}var fl=_l,gl=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},Sl=h.Promise,Tl=h,Rl=Sl,vl=I,yl=Xt,bl=xc,Cl=pt,Il=Qi,Al=_e,wl=Rl&&Rl.prototype,Ol=Cl("species"),Nl=!1,Dl=vl(Tl.PromiseRejectionEvent),Pl=yl("Promise",(function(){var e=bl(Rl),t=e!==String(Rl);if(!t&&66===Al)return!0;if(!wl.catch||!wl.finally)return!0;if(!Al||Al<51||!/native code/.test(e)){var n=new Rl((function(e){e(1)})),i=function(e){e((function(){}),(function(){}))};if((n.constructor={})[Ol]=i,!(Nl=n.then((function(){}))instanceof i))return!0}return!(t||"BROWSER"!==Il&&"DENO"!==Il||Dl)})),Ll={CONSTRUCTOR:Pl,REJECTION_EVENT:Dl,SUBCLASSING:Nl},kl={},Ml=Ne,Ul=TypeError,Vl=function(e){var t,n;this.promise=new e((function(e,i){if(void 0!==t||void 0!==n)throw new Ul("Bad Promise constructor");t=e,n=i})),this.resolve=Ml(t),this.reject=Ml(n)};kl.f=function(e){return new Vl(e)};var xl,Fl,Bl,jl=Nn,Gl=$i,Wl=h,Kl=$,Hl=D,Yl=Aa,Xl=Ya,Jl=function(e){var t=wc(e);Nc&&t&&!t[Dc]&&Oc(t,Dc,{configurable:!0,get:function(){return this}})},zl=Ne,Zl=I,ql=Q,Ql=kc,$l=dd,eu=jd.set,tu=fl,nu=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(e){}},iu=gl,ru=Qd,ou=Sa,su=Sl,au=Ll,cu=kl,du="Promise",lu=au.CONSTRUCTOR,uu=au.REJECTION_EVENT,hu=ou.getterFor(du),pu=ou.set,_u=su&&su.prototype,Eu=su,mu=_u,fu=Wl.TypeError,gu=Wl.document,Su=Wl.process,Tu=cu.f,Ru=Tu,vu=!!(gu&&gu.createEvent&&Wl.dispatchEvent),yu="unhandledrejection",bu=function(e){var t;return!(!ql(e)||!Zl(t=e.then))&&t},Cu=function(e,t){var n,i,r,o=t.value,s=1===t.state,a=s?e.ok:e.fail,c=e.resolve,d=e.reject,l=e.domain;try{a?(s||(2===t.rejection&&Nu(t),t.rejection=1),!0===a?n=o:(l&&l.enter(),n=a(o),l&&(l.exit(),r=!0)),n===e.promise?d(new fu("Promise-chain cycle")):(i=bu(n))?Hl(i,n,c,d):c(n)):d(o)}catch(e){l&&!r&&l.exit(),d(e)}},Iu=function(e,t){e.notified||(e.notified=!0,tu((function(){for(var n,i=e.reactions;n=i.get();)Cu(n,e);e.notified=!1,t&&!e.rejection&&wu(e)})))},Au=function(e,t,n){var i,r;vu?((i=gu.createEvent("Event")).promise=t,i.reason=n,i.initEvent(e,!1,!0),Wl.dispatchEvent(i)):i={promise:t,reason:n},!uu&&(r=Wl["on"+e])?r(i):e===yu&&nu("Unhandled promise rejection",n)},wu=function(e){Hl(eu,Wl,(function(){var t,n=e.facade,i=e.value;if(Ou(e)&&(t=iu((function(){Gl?Su.emit("unhandledRejection",i,n):Au(yu,n,i)})),e.rejection=Gl||Ou(e)?2:1,t.error))throw t.value}))},Ou=function(e){return 1!==e.rejection&&!e.parent},Nu=function(e){Hl(eu,Wl,(function(){var t=e.facade;Gl?Su.emit("rejectionHandled",t):Au("rejectionhandled",t,e.value)}))},Du=function(e,t,n){return function(i){e(t,i,n)}},Pu=function(e,t,n){e.done||(e.done=!0,n&&(e=n),e.value=t,e.state=2,Iu(e,!0))},Lu=function(e,t,n){if(!e.done){e.done=!0,n&&(e=n);try{if(e.facade===t)throw new fu("Promise can't be resolved itself");var i=bu(t);i?tu((function(){var n={done:!1};try{Hl(i,t,Du(Lu,n,e),Du(Pu,n,e))}catch(t){Pu(n,t,e)}})):(e.value=t,e.state=1,Iu(e,!1))}catch(t){Pu({done:!1},t,e)}}};lu&&(mu=(Eu=function(e){Ql(this,mu),zl(e),Hl(xl,this);var t=hu(this);try{e(Du(Lu,t),Du(Pu,t))}catch(e){Pu(t,e)}}).prototype,(xl=function(e){pu(this,{type:du,done:!1,notified:!1,parent:!1,reactions:new ru,rejection:!1,state:0,value:null})}).prototype=Yl(mu,"then",(function(e,t){var n=hu(this),i=Tu($l(this,Eu));return n.parent=!0,i.ok=!Zl(e)||e,i.fail=Zl(t)&&t,i.domain=Gl?Su.domain:void 0,0===n.state?n.reactions.add(i):tu((function(){Cu(i,n)})),i.promise})),Fl=function(){var e=new xl,t=hu(e);this.promise=e,this.resolve=Du(Lu,t),this.reject=Du(Pu,t)},cu.f=Tu=function(e){return e===Eu||e===Bl?new Fl(e):Ru(e)}),jl({global:!0,constructor:!0,wrap:!0,forced:lu},{Promise:Eu}),Bl=Kl.Promise,Xl(Eu,du,!1,!0),Jl(du);var ku=pt("iterator"),Mu=!1;try{var Uu=0,Vu={next:function(){return{done:!!Uu++}},return:function(){Mu=!0}};Vu[ku]=function(){return this},Array.from(Vu,(function(){throw 2}))}catch(e){}var xu=function(e,t){try{if(!t&&!Mu)return!1}catch(e){return!1}var n=!1;try{var i={};i[ku]=function(){return{next:function(){return{done:n=!0}}}},e(i)}catch(e){}return n},Fu=Sl,Bu=Ll.CONSTRUCTOR||!xu((function(e){Fu.all(e).then(void 0,(function(){}))})),ju=D,Gu=Ne,Wu=kl,Ku=gl,Hu=Ls;Nn({target:"Promise",stat:!0,forced:Bu},{all:function(e){var t=this,n=Wu.f(t),i=n.resolve,r=n.reject,o=Ku((function(){var n=Gu(t.resolve),o=[],s=0,a=1;Hu(e,(function(e){var c=s++,d=!1;a++,ju(n,t,e).then((function(e){d||(d=!0,o[c]=e,--a||i(o))}),r)})),--a||i(o)}));return o.error&&r(o.value),n.promise}});var Yu=Nn,Xu=Ll.CONSTRUCTOR;Sl&&Sl.prototype,Yu({target:"Promise",proto:!0,forced:Xu,real:!0},{catch:function(e){return this.then(void 0,e)}});var Ju=D,zu=Ne,Zu=kl,qu=gl,Qu=Ls;Nn({target:"Promise",stat:!0,forced:Bu},{race:function(e){var t=this,n=Zu.f(t),i=n.reject,r=qu((function(){var r=zu(t.resolve);Qu(e,(function(e){Ju(r,t,e).then(n.resolve,i)}))}));return r.error&&i(r.value),n.promise}});var $u=kl;Nn({target:"Promise",stat:!0,forced:Ll.CONSTRUCTOR},{reject:function(e){var t=$u.f(this);return(0,t.reject)(e),t.promise}});var eh=rn,th=Q,nh=kl,ih=function(e,t){if(eh(e),th(t)&&t.constructor===e)return t;var n=nh.f(e);return(0,n.resolve)(t),n.promise},rh=Nn,oh=Sl,sh=Ll.CONSTRUCTOR,ah=ih,ch=re("Promise"),dh=!sh;rh({target:"Promise",stat:!0,forced:true},{resolve:function(e){return ah(dh&&this===ch?oh:this,e)}});var lh=D,uh=Ne,hh=kl,ph=gl,_h=Ls;Nn({target:"Promise",stat:!0,forced:Bu},{allSettled:function(e){var t=this,n=hh.f(t),i=n.resolve,r=n.reject,o=ph((function(){var n=uh(t.resolve),r=[],o=0,s=1;_h(e,(function(e){var a=o++,c=!1;s++,lh(n,t,e).then((function(e){c||(c=!0,r[a]={status:"fulfilled",value:e},--s||i(r))}),(function(e){c||(c=!0,r[a]={status:"rejected",reason:e},--s||i(r))}))})),--s||i(r)}));return o.error&&r(o.value),n.promise}});var Eh=D,mh=Ne,fh=re,gh=kl,Sh=gl,Th=Ls,Rh="No one promise resolved";Nn({target:"Promise",stat:!0,forced:Bu},{any:function(e){var t=this,n=fh("AggregateError"),i=gh.f(t),r=i.resolve,o=i.reject,s=Sh((function(){var i=mh(t.resolve),s=[],a=0,c=1,d=!1;Th(e,(function(e){var l=a++,u=!1;c++,Eh(i,t,e).then((function(e){u||d||(d=!0,r(e))}),(function(e){u||d||(u=!0,s[l]=e,--c||o(new n(s,Rh)))}))})),--c||o(new n(s,Rh))}));return s.error&&o(s.value),i.promise}});var vh=Nn,yh=f,bh=ld,Ch=kl,Ih=Ne,Ah=gl,wh=h.Promise,Oh=!1;vh({target:"Promise",stat:!0,forced:!wh||!wh.try||Ah((function(){wh.try((function(e){Oh=8===e}),8)})).error||!Oh},{try:function(e){var t=arguments.length>1?bh(arguments,1):[],n=Ch.f(this),i=Ah((function(){return yh(Ih(e),void 0,t)}));return(i.error?n.reject:n.resolve)(i.value),n.promise}});var Nh=kl;Nn({target:"Promise",stat:!0},{withResolvers:function(){var e=Nh.f(this);return{promise:e.promise,resolve:e.resolve,reject:e.reject}}});var Dh=Nn,Ph=Sl,Lh=i,kh=re,Mh=I,Uh=dd,Vh=ih,xh=Ph&&Ph.prototype;Dh({target:"Promise",proto:!0,real:!0,forced:!!Ph&&Lh((function(){xh.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=Uh(this,kh("Promise")),n=Mh(e);return this.then(n?function(n){return Vh(t,e()).then((function(){return n}))}:e,n?function(n){return Vh(t,e()).then((function(){throw n}))}:e)}});var Fh=d,Bh=Mn,jh=vi,Gh=X,Wh=Fh("".charAt),Kh=Fh("".charCodeAt),Hh=Fh("".slice),Yh=function(e){return function(t,n){var i,r,o=jh(Gh(t)),s=Bh(n),a=o.length;return s<0||s>=a?e?"":void 0:(i=Kh(o,s))<55296||i>56319||s+1===a||(r=Kh(o,s+1))<56320||r>57343?e?Wh(o,s):i:e?Hh(o,s,s+2):r-56320+(i-55296<<10)+65536}},Xh={codeAt:Yh(!1),charAt:Yh(!0)},Jh=Xh.charAt,zh=vi,Zh=Sa,qh=mc,Qh=fc,$h="String Iterator",ep=Zh.set,tp=Zh.getterFor($h);qh(String,"String",(function(e){ep(this,{type:$h,string:zh(e),index:0})}),(function(){var e,t=tp(this),n=t.string,i=t.index;return i>=n.length?Qh(void 0,!0):(e=Jh(n,i),t.index+=e.length,Qh(e,!1))}));var np=$.Promise,ip={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},rp=h,op=Ya,sp=Qo;for(var ap in ip)op(rp[ap],ap),sp[ap]=sp.Array;var cp=np,dp=n(cp),lp=ii("Array","values"),up=Si,hp=$e,pp=l,_p=lp,Ep=Array.prototype,mp={DOMTokenList:!0,NodeList:!0},fp=function(e){var t=e.values;return e===Ep||pp(Ep,e)&&t===Ep.values||hp(mp,up(e))?_p:t},gp=n(fp),Sp=Ie,Tp=TypeError,Rp=ld,vp=Math.floor,yp=function(e,t){var n=e.length;if(n<8)for(var i,r,o=1;o<n;){for(r=o,i=e[o];r&&t(e[r-1],i)>0;)e[r]=e[--r];r!==o++&&(e[r]=i)}else for(var s=vp(n/2),a=yp(Rp(e,0,s),t),c=yp(Rp(e,s),t),d=a.length,l=c.length,u=0,h=0;u<d||h<l;)e[u+h]=u<d&&h<l?t(a[u],c[h])<=0?a[u++]:c[h++]:u<d?a[u++]:c[h++];return e},bp=yp,Cp=ae.match(/firefox\/(\d+)/i),Ip=!!Cp&&+Cp[1],Ap=/MSIE|Trident/.test(ae),wp=ae.match(/AppleWebKit\/(\d+)\./),Op=!!wp&&+wp[1],Np=Nn,Dp=d,Pp=Ne,Lp=Ze,kp=Kn,Mp=function(e,t){if(!delete e[t])throw new Tp("Cannot delete property "+Sp(t)+" of "+Sp(e))},Up=vi,Vp=i,xp=bp,Fp=Xi,Bp=Ip,jp=Ap,Gp=_e,Wp=Op,Kp=[],Hp=Dp(Kp.sort),Yp=Dp(Kp.push),Xp=Vp((function(){Kp.sort(void 0)})),Jp=Vp((function(){Kp.sort(null)})),zp=Fp("sort"),Zp=!Vp((function(){if(Gp)return Gp<70;if(!(Bp&&Bp>3)){if(jp)return!0;if(Wp)return Wp<603;var e,t,n,i,r="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(i=0;i<47;i++)Kp.push({k:t+i,v:n})}for(Kp.sort((function(e,t){return t.v-e.v})),i=0;i<Kp.length;i++)t=Kp[i].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return"DGBEFHACIJK"!==r}}));Np({target:"Array",proto:!0,forced:Xp||!Jp||!zp||!Zp},{sort:function(e){void 0!==e&&Pp(e);var t=Lp(this);if(Zp)return void 0===e?Hp(t):Hp(t,e);var n,i,r=[],o=kp(t);for(i=0;i<o;i++)i in t&&Yp(r,t[i]);for(xp(r,function(e){return function(t,n){if(void 0===n)return-1;if(void 0===t)return 1;if(void 0!==e)return+e(t,n)||0;var i=Up(t),r=Up(n);return i===r?0:i>r?1:-1}}(e)),n=kp(r),i=0;i<n;)t[i]=r[i++];for(;i<o;)Mp(t,i++);return t}});var qp=ii("Array","sort"),Qp=l,$p=qp,e_=Array.prototype,t_=function(e){var t=e.sort;return e===e_||Qp(e_,e)&&t===e_.sort?$p:t},n_=n(t_),i_=Nn,r_=d,o_=Fn,s_=RangeError,a_=String.fromCharCode,c_=String.fromCodePoint,d_=r_([].join);i_({target:"String",stat:!0,arity:1,forced:!!c_&&1!==c_.length},{fromCodePoint:function(e){for(var t,n=[],i=arguments.length,r=0;i>r;){if(o_(t=+arguments[r],1114111)!==t)throw new s_(t+" is not a valid code point");n[r++]=t<65536?a_(t):a_(55296+((t-=65536)>>10),t%1024+56320)}return d_(n,"")}});var l_=i,u_=pt("iterator"),h_=!l_((function(){var e=new URL("b?a=1&b=2&c=3","https://a"),t=e.searchParams,n=new URLSearchParams("a=1&a=2&b=3"),i="";return e.pathname="c%20d",t.forEach((function(e,n){t.delete("b"),i+=n+e})),n.delete("a",2),n.delete("b",void 0),!e.toJSON||!n.has("a",1)||n.has("a",2)||!n.has("a",void 0)||n.has("b")||!t.size&&true||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[u_]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("https://тест").host||"#%D0%B1"!==new URL("https://a#б").hash||"a1c3"!==i||"x"!==new URL("https://x",void 0).host})),p_=Aa,__=Nn,E_=h,m_=Hd,f_=re,g_=D,S_=d,T_=w,R_=h_,v_=Aa,y_=Ac,b_=function(e,t,n){for(var i in t)n&&n.unsafe&&e[i]?e[i]=t[i]:p_(e,i,t[i],n);return e},C_=Ya,I_=$a,A_=Sa,w_=kc,O_=I,N_=$e,D_=qt,P_=Si,L_=rn,k_=Q,M_=vi,U_=xo,V_=x,x_=Es,F_=cs,B_=fc,j_=hd,G_=bp,W_=pt("iterator"),K_="URLSearchParams",H_=K_+"Iterator",Y_=A_.set,X_=A_.getterFor(K_),J_=A_.getterFor(H_),z_=m_("fetch"),Z_=m_("Request"),q_=m_("Headers"),Q_=Z_&&Z_.prototype,$_=q_&&q_.prototype,eE=E_.TypeError,tE=E_.encodeURIComponent,nE=String.fromCharCode,iE=f_("String","fromCodePoint"),rE=parseInt,oE=S_("".charAt),sE=S_([].join),aE=S_([].push),cE=S_("".replace),dE=S_([].shift),lE=S_([].splice),uE=S_("".split),hE=S_("".slice),pE=S_(/./.exec),_E=/\+/g,EE=/^[0-9a-f]+$/i,mE=function(e,t){var n=hE(e,t,t+2);return pE(EE,n)?rE(n,16):NaN},fE=function(e){for(var t=0,n=128;n>0&&0!=(e&n);n>>=1)t++;return t},gE=function(e){var t=null,n=e.length;switch(n){case 1:t=e[0];break;case 2:t=(31&e[0])<<6|63&e[1];break;case 3:t=(15&e[0])<<12|(63&e[1])<<6|63&e[2];break;case 4:t=(7&e[0])<<18|(63&e[1])<<12|(63&e[2])<<6|63&e[3]}return null===t||t>1114111||t>=55296&&t<=57343||t<(n>3?65536:n>2?2048:n>1?128:0)?null:t},SE=function(e){for(var t=(e=cE(e,_E," ")).length,n="",i=0;i<t;){var r=oE(e,i);if("%"===r){if("%"===oE(e,i+1)||i+3>t){n+="%",i++;continue}var o=mE(e,i+1);if(o!=o){n+=r,i++;continue}i+=2;var s=fE(o);if(0===s)r=nE(o);else{if(1===s||s>4){n+="�",i++;continue}for(var a=[o],c=1;c<s&&!(++i+3>t||"%"!==oE(e,i));){var d=mE(e,i+1);if(d!=d||d>191||d<128)break;if(1===c){if(224===o&&d<160)break;if(237===o&&d>159)break;if(240===o&&d<144)break;if(244===o&&d>143)break}aE(a,d),i+=2,c++}if(a.length!==s){n+="�";continue}var l=gE(a);if(null===l){for(var u=0;u<s;u++)n+="�";i++;continue}r=iE(l)}}n+=r,i++}return n},TE=/[!'()~]|%20/g,RE={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},vE=function(e){return RE[e]},yE=function(e){return cE(tE(e),TE,vE)},bE=I_((function(e,t){Y_(this,{type:H_,target:X_(e).entries,index:0,kind:t})}),K_,(function(){var e=J_(this),t=e.target,n=e.index++;if(!t||n>=t.length)return e.target=null,B_(void 0,!0);var i=t[n];switch(e.kind){case"keys":return B_(i.key,!1);case"values":return B_(i.value,!1)}return B_([i.key,i.value],!1)}),!0),CE=function(e){this.entries=[],this.url=null,void 0!==e&&(k_(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===oE(e,0)?hE(e,1):e:M_(e)))};CE.prototype={type:K_,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,n,i,r,o,s,a,c=this.entries,d=F_(e);if(d)for(n=(t=x_(e,d)).next;!(i=g_(n,t)).done;){if(o=(r=x_(L_(i.value))).next,(s=g_(o,r)).done||(a=g_(o,r)).done||!g_(o,r).done)throw new eE("Expected sequence with length 2");aE(c,{key:M_(s.value),value:M_(a.value)})}else for(var l in e)N_(e,l)&&aE(c,{key:l,value:M_(e[l])})},parseQuery:function(e){if(e)for(var t,n,i=this.entries,r=uE(e,"&"),o=0;o<r.length;)(t=r[o++]).length&&(n=uE(t,"="),aE(i,{key:SE(dE(n)),value:SE(sE(n,"="))}))},serialize:function(){for(var e,t=this.entries,n=[],i=0;i<t.length;)e=t[i++],aE(n,yE(e.key)+"="+yE(e.value));return sE(n,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var IE=function(){w_(this,AE);var e=Y_(this,new CE(arguments.length>0?arguments[0]:void 0));T_||(this.size=e.entries.length)},AE=IE.prototype;if(b_(AE,{append:function(e,t){var n=X_(this);j_(arguments.length,2),aE(n.entries,{key:M_(e),value:M_(t)}),T_||this.size++,n.updateURL()},delete:function(e){for(var t=X_(this),n=j_(arguments.length,1),i=t.entries,r=M_(e),o=n<2?void 0:arguments[1],s=void 0===o?o:M_(o),a=0;a<i.length;){var c=i[a];c.key!==r||void 0!==s&&c.value!==s?a++:lE(i,a,1)}T_||(this.size=i.length),t.updateURL()},get:function(e){var t=X_(this).entries;j_(arguments.length,1);for(var n=M_(e),i=0;i<t.length;i++)if(t[i].key===n)return t[i].value;return null},getAll:function(e){var t=X_(this).entries;j_(arguments.length,1);for(var n=M_(e),i=[],r=0;r<t.length;r++)t[r].key===n&&aE(i,t[r].value);return i},has:function(e){for(var t=X_(this).entries,n=j_(arguments.length,1),i=M_(e),r=n<2?void 0:arguments[1],o=void 0===r?r:M_(r),s=0;s<t.length;){var a=t[s++];if(a.key===i&&(void 0===o||a.value===o))return!0}return!1},set:function(e,t){var n=X_(this);j_(arguments.length,2);for(var i,r=n.entries,o=!1,s=M_(e),a=M_(t),c=0;c<r.length;c++)(i=r[c]).key===s&&(o?lE(r,c--,1):(o=!0,i.value=a));o||aE(r,{key:s,value:a}),T_||(this.size=r.length),n.updateURL()},sort:function(){var e=X_(this);G_(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,n=X_(this).entries,i=D_(e,arguments.length>1?arguments[1]:void 0),r=0;r<n.length;)i((t=n[r++]).value,t.key,this)},keys:function(){return new bE(this,"keys")},values:function(){return new bE(this,"values")},entries:function(){return new bE(this,"entries")}},{enumerable:!0}),v_(AE,W_,AE.entries,{name:"entries"}),v_(AE,"toString",(function(){return X_(this).serialize()}),{enumerable:!0}),T_&&y_(AE,"size",{get:function(){return X_(this).entries.length},configurable:!0,enumerable:!0}),C_(IE,K_),__({global:!0,constructor:!0,forced:!R_},{URLSearchParams:IE}),!R_&&O_(q_)){var wE=S_($_.has),OE=S_($_.set),NE=function(e){if(k_(e)){var t,n=e.body;if(P_(n)===K_)return t=e.headers?new q_(e.headers):new q_,wE(t,"content-type")||OE(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),U_(e,{body:V_(0,M_(n)),headers:V_(0,t)})}return e};if(O_(z_)&&__({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return z_(e,arguments.length>1?NE(arguments[1]):{})}}),O_(Z_)){var DE=function(e){return w_(this,Q_),new Z_(e,arguments.length>1?NE(arguments[1]):{})};Q_.constructor=DE,DE.prototype=Q_,__({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:DE})}}var PE,LE={URLSearchParams:IE,getState:X_},kE=$.URLSearchParams,ME=w,UE=d,VE=D,xE=i,FE=mo,BE=to,jE=P,GE=Ze,WE=W,KE=Object.assign,HE=Object.defineProperty,YE=UE([].concat),XE=!KE||xE((function(){if(ME&&1!==KE({b:1},KE(HE({},"a",{enumerable:!0,get:function(){HE(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},n=Symbol("assign detection"),i="abcdefghijklmnopqrst";return e[n]=7,i.split("").forEach((function(e){t[e]=e})),7!==KE({},e)[n]||FE(KE({},t)).join("")!==i}))?function(e,t){for(var n=GE(e),i=arguments.length,r=1,o=BE.f,s=jE.f;i>r;)for(var a,c=WE(arguments[r++]),d=o?YE(FE(c),o(c)):FE(c),l=d.length,u=0;l>u;)a=d[u++],ME&&!VE(s,c,a)||(n[a]=c[a]);return n}:KE,JE=rn,zE=Ss,ZE=w,qE=Qt,QE=x,$E=function(e,t,n){ZE?qE.f(e,t,QE(0,n)):e[t]=n},em=w,tm=dr,nm=TypeError,im=Object.getOwnPropertyDescriptor,rm=em&&!function(){if(void 0!==this)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(e){return e instanceof TypeError}}()?function(e,t){if(tm(e)&&!im(e,"length").writable)throw new nm("Cannot set read only .length");return e.length=t}:function(e,t){return e.length=t},om=qt,sm=D,am=Ze,cm=function(e,t,n,i){try{return i?t(JE(n)[0],n[1]):t(n)}catch(t){zE(e,"throw",t)}},dm=ns,lm=td,um=Kn,hm=$E,pm=rm,_m=Es,Em=cs,mm=Ss,fm=Array,gm=function(e){var t=lm(this),n=arguments.length,i=n>1?arguments[1]:void 0,r=void 0!==i;r&&(i=om(i,n>2?arguments[2]:void 0));var o,s,a,c,d,l,u=am(e),h=Em(u),p=0;if(!h||this===fm&&dm(h))for(o=um(u),s=t?new this(o):fm(o);o>p;p++)l=r?i(u[p],p):u[p],hm(s,p,l);else for(s=t?new this:[],d=(c=_m(u,h)).next;!(a=sm(d,c)).done;p++){l=r?cm(c,i,[a.value,p],!0):a.value;try{hm(s,p,l)}catch(e){mm(c,"throw",e)}}return pm(s,p),s},Sm=d,Tm=2147483647,Rm=/[^\0-\u007E]/,vm=/[.\u3002\uFF0E\uFF61]/g,ym="Overflow: input needs wider integers to process",bm=RangeError,Cm=Sm(vm.exec),Im=Math.floor,Am=String.fromCharCode,wm=Sm("".charCodeAt),Om=Sm([].join),Nm=Sm([].push),Dm=Sm("".replace),Pm=Sm("".split),Lm=Sm("".toLowerCase),km=function(e){return e+22+75*(e<26)},Mm=function(e,t,n){var i=0;for(e=n?Im(e/700):e>>1,e+=Im(e/t);e>455;)e=Im(e/35),i+=36;return Im(i+36*e/(e+38))},Um=function(e){var t=[];e=function(e){for(var t=[],n=0,i=e.length;n<i;){var r=wm(e,n++);if(r>=55296&&r<=56319&&n<i){var o=wm(e,n++);56320==(64512&o)?Nm(t,((1023&r)<<10)+(1023&o)+65536):(Nm(t,r),n--)}else Nm(t,r)}return t}(e);var n,i,r=e.length,o=128,s=0,a=72;for(n=0;n<e.length;n++)(i=e[n])<128&&Nm(t,Am(i));var c=t.length,d=c;for(c&&Nm(t,"-");d<r;){var l=Tm;for(n=0;n<e.length;n++)(i=e[n])>=o&&i<l&&(l=i);var u=d+1;if(l-o>Im((Tm-s)/u))throw new bm(ym);for(s+=(l-o)*u,o=l,n=0;n<e.length;n++){if((i=e[n])<o&&++s>Tm)throw new bm(ym);if(i===o){for(var h=s,p=36;;){var _=p<=a?1:p>=a+26?26:p-a;if(h<_)break;var E=h-_,m=36-_;Nm(t,Am(km(_+E%m))),h=Im(E/m),p+=36}Nm(t,Am(km(h))),a=Mm(s,u,d===c),s=0,d++}}s++,o++}return Om(t,"")},Vm=Nn,xm=w,Fm=h_,Bm=h,jm=qt,Gm=d,Wm=Aa,Km=Ac,Hm=kc,Ym=$e,Xm=XE,Jm=gm,zm=ld,Zm=Xh.codeAt,qm=function(e){var t,n,i=[],r=Pm(Dm(Lm(e),vm,"."),".");for(t=0;t<r.length;t++)n=r[t],Nm(i,Cm(Rm,n)?"xn--"+Um(n):n);return Om(i,".")},Qm=vi,$m=Ya,ef=hd,tf=LE,nf=Sa,rf=nf.set,of=nf.getterFor("URL"),sf=tf.URLSearchParams,af=tf.getState,cf=Bm.URL,df=Bm.TypeError,lf=Bm.encodeURIComponent,uf=Bm.parseInt,hf=Math.floor,pf=Math.pow,_f=Gm("".charAt),Ef=Gm(/./.exec),mf=Gm([].join),ff=Gm(1.1.toString),gf=Gm([].pop),Sf=Gm([].push),Tf=Gm("".replace),Rf=Gm([].shift),vf=Gm("".split),yf=Gm("".slice),bf=Gm("".toLowerCase),Cf=Gm([].unshift),If="Invalid scheme",Af="Invalid host",wf="Invalid port",Of=/[a-z]/i,Nf=/[\d+\-.a-z]/i,Df=/\d/,Pf=/^0x/i,Lf=/^[0-7]+$/,kf=/^\d+$/,Mf=/^[\da-f]+$/i,Uf=/[\0\t\n\r #%/:<>?@[\\\]^|]/,Vf=/[\0\t\n\r #/:<>?@[\\\]^|]/,xf=/^[\u0000-\u0020]+/,Ff=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,Bf=/[\t\n\r]/g,jf=function(e){var t,n,i,r;if("number"==typeof e){for(t=[],n=0;n<4;n++)Cf(t,e%256),e=hf(e/256);return mf(t,".")}if("object"==typeof e){for(t="",i=function(e){for(var t=null,n=1,i=null,r=0,o=0;o<8;o++)0!==e[o]?(r>n&&(t=i,n=r),i=null,r=0):(null===i&&(i=o),++r);return r>n?i:t}(e),n=0;n<8;n++)r&&0===e[n]||(r&&(r=!1),i===n?(t+=n?":":"::",r=!0):(t+=ff(e[n],16),n<7&&(t+=":")));return"["+t+"]"}return e},Gf={},Wf=Xm({},Gf,{" ":1,'"':1,"#":1,"<":1,">":1}),Kf=Xm({},Wf,{"'":1}),Hf=Xm({},Gf,{" ":1,'"':1,"<":1,">":1,"`":1}),Yf=Xm({},Hf,{"#":1,"?":1,"{":1,"}":1,"^":1}),Xf=Xm({},Yf,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),Jf=function(e,t){var n=Zm(e,0);return n>=32&&n<127&&!Ym(t,e)?e:"'"===e&&Ym(t,e)?"%27":lf(e)},zf={ftp:21,file:null,http:80,https:443,ws:80,wss:443},Zf=function(e,t){var n;return 2===e.length&&Ef(Of,_f(e,0))&&(":"===(n=_f(e,1))||!t&&"|"===n)},qf=function(e){var t;return e.length>1&&Zf(yf(e,0,2))&&(2===e.length||"/"===(t=_f(e,2))||"\\"===t||"?"===t||"#"===t)},Qf=function(e){return"."===e||"%2e"===bf(e)},$f={},eg={},tg={},ng={},ig={},rg={},og={},sg={},ag={},cg={},dg={},lg={},ug={},hg={},pg={},_g={},Eg={},mg={},fg={},gg={},Sg={},Tg=function(e,t,n){var i,r,o,s=Qm(e);if(t){if(r=this.parse(s))throw new df(r);this.searchParams=null}else{if(void 0!==n&&(i=new Tg(n,!0)),r=this.parse(s,null,i))throw new df(r);(o=af(new sf)).bindURL(this),this.searchParams=o}};Tg.prototype={type:"URL",parse:function(e,t,n){var i,r,o,s,a,c=this,d=t||$f,l=0,u="",h=!1,p=!1,_=!1;for(e=Qm(e),t||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=Tf(e,xf,""),e=Tf(e,Ff,"$1")),e=Tf(e,Bf,""),i=Jm(e);l<=i.length;){switch(r=i[l],d){case $f:if(!r||!Ef(Of,r)){if(t)return If;d=tg;continue}u+=bf(r),d=eg;break;case eg:if(r&&Ef(Nf,r))u+=bf(r);else{if(":"!==r){if(t)return If;u="",d=tg,l=0;continue}if(t&&(c.isSpecial()!==Ym(zf,u)||"file"===u&&(c.includesCredentials()||null!==c.port)||"file"===c.scheme&&""===c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&zf[c.scheme]===c.port&&(c.port=null));u="","file"===c.scheme?d=hg:c.isSpecial()&&n&&n.scheme===c.scheme?d=ng:c.isSpecial()?d=sg:"/"===i[l+1]?(d=ig,l++):(c.cannotBeABaseURL=!0,Sf(c.path,""),d=fg)}break;case tg:if(!n||n.cannotBeABaseURL&&"#"!==r)return If;if(n.cannotBeABaseURL&&"#"===r){c.scheme=n.scheme,c.path=zm(n.path),c.query=n.query,c.fragment="",c.cannotBeABaseURL=!0,d=Sg;break}d="file"===n.scheme?hg:rg;continue;case ng:if("/"!==r||"/"!==i[l+1]){d=rg;continue}d=ag,l++;break;case ig:if("/"===r){d=cg;break}d=mg;continue;case rg:if(c.scheme=n.scheme,r===PE)c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=zm(n.path),c.query=n.query;else if("/"===r||"\\"===r&&c.isSpecial())d=og;else if("?"===r)c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=zm(n.path),c.query="",d=gg;else{if("#"!==r){c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=zm(n.path),c.path.length&&c.path.length--,d=mg;continue}c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=zm(n.path),c.query=n.query,c.fragment="",d=Sg}break;case og:if(!c.isSpecial()||"/"!==r&&"\\"!==r){if("/"!==r){c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,d=mg;continue}d=cg}else d=ag;break;case sg:if(d=ag,"/"!==r||"/"!==i[l+1])continue;l++;break;case ag:if("/"!==r&&"\\"!==r){d=cg;continue}break;case cg:if("@"===r){h&&(u="%40"+u),h=!0,o=Jm(u);for(var E=0;E<o.length;E++){var m=o[E];if(":"!==m||_){var f=Jf(m,Xf);_?c.password+=f:c.username+=f}else _=!0}u=""}else if(r===PE||"/"===r||"?"===r||"#"===r||"\\"===r&&c.isSpecial()){if(h&&""===u)return"Invalid authority";l-=Jm(u).length+1,u="",d=dg}else u+=r;break;case dg:case lg:if(t&&"file"===c.scheme){d=_g;continue}if(":"!==r||p){if(r===PE||"/"===r||"?"===r||"#"===r||"\\"===r&&c.isSpecial()){if(c.isSpecial()&&""===u)return Af;if(t&&""===u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",d=Eg,t)return;continue}"["===r?p=!0:"]"===r&&(p=!1),u+=r}else{if(""===u)return Af;if(t===lg)return;if(s=c.parseHost(u))return s;u="",d=ug}break;case ug:if(!Ef(Df,r)){if(r===PE||"/"===r||"?"===r||"#"===r||"\\"===r&&c.isSpecial()||t){if(""!==u){var g=uf(u,10);if(g>65535)return wf;c.port=c.isSpecial()&&g===zf[c.scheme]?null:g,u=""}if(t)return;d=Eg;continue}return wf}u+=r;break;case hg:if(c.scheme="file",c.host="","/"===r||"\\"===r)d=pg;else{if(!n||"file"!==n.scheme){d=mg;continue}switch(r){case PE:c.host=n.host,c.path=zm(n.path),c.query=n.query;break;case"?":c.host=n.host,c.path=zm(n.path),c.query="",d=gg;break;case"#":c.host=n.host,c.path=zm(n.path),c.query=n.query,c.fragment="",d=Sg;break;default:c.host=n.host,qf(mf(zm(i,l),""))||(c.path=zm(n.path),c.shortenPath()),d=mg;continue}}break;case pg:if("/"===r||"\\"===r){d=_g;break}n&&"file"===n.scheme&&(c.host=n.host,!qf(mf(zm(i,l),""))&&Zf(n.path[0],!0)&&Sf(c.path,n.path[0])),d=mg;continue;case _g:if(r===PE||"/"===r||"\\"===r||"?"===r||"#"===r){if(!t&&Zf(u))d=mg;else if(""===u){if(c.host="",t)return;d=Eg}else{if(s=c.parseHost(u))return s;if("localhost"===c.host&&(c.host=""),t)return;u="",d=Eg}continue}u+=r;break;case Eg:if(c.isSpecial()){if(d=mg,"/"!==r&&"\\"!==r)continue}else if(t||"?"!==r)if(t||"#"!==r){if(r!==PE&&(d=mg,"/"!==r))continue}else c.fragment="",d=Sg;else c.query="",d=gg;break;case mg:if(r===PE||"/"===r||"\\"===r&&c.isSpecial()||!t&&("?"===r||"#"===r)){if(".."===(a=bf(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"===r||"\\"===r&&c.isSpecial()||Sf(c.path,"")):Qf(u)?"/"===r||"\\"===r&&c.isSpecial()||Sf(c.path,""):("file"===c.scheme&&!c.path.length&&Zf(u)&&(null!==c.host&&""!==c.host&&(c.host=""),u=_f(u,0)+":"),Sf(c.path,u)),u="","file"===c.scheme&&(r===PE||"?"===r||"#"===r))for(;c.path.length>1&&""===c.path[0];)Rf(c.path);"?"===r?(c.query="",d=gg):"#"===r&&(c.fragment="",d=Sg)}else u+=Jf(r,Yf);break;case fg:"?"===r?(c.query="",d=gg):"#"===r?(c.fragment="",d=Sg):r!==PE&&(c.path[0]+=Jf(r,Gf));break;case gg:t||"#"!==r?r!==PE&&(c.query+=Jf(r,c.isSpecial()?Kf:Wf)):(c.fragment="",d=Sg);break;case Sg:r!==PE&&(c.fragment+=Jf(r,Hf))}l++}},parseHost:function(e){var t,n,i;if("["===_f(e,0)){if("]"!==_f(e,e.length-1))return Af;if(t=function(e){var t,n,i,r,o,s,a,c=[0,0,0,0,0,0,0,0],d=0,l=null,u=0,h=function(){return _f(e,u)};if(":"===h()){if(":"!==_f(e,1))return;u+=2,l=++d}for(;h();){if(8===d)return;if(":"!==h()){for(t=n=0;n<4&&Ef(Mf,h());)t=16*t+uf(h(),16),u++,n++;if("."===h()){if(0===n)return;if(u-=n,d>6)return;for(i=0;h();){if(r=null,i>0){if(!("."===h()&&i<4))return;u++}if(!Ef(Df,h()))return;for(;Ef(Df,h());){if(o=uf(h(),10),null===r)r=o;else{if(0===r)return;r=10*r+o}if(r>255)return;u++}c[d]=256*c[d]+r,2!=++i&&4!==i||d++}if(4!==i)return;break}if(":"===h()){if(u++,!h())return}else if(h())return;c[d++]=t}else{if(null!==l)return;u++,l=++d}}if(null!==l)for(s=d-l,d=7;0!==d&&s>0;)a=c[d],c[d--]=c[l+s-1],c[l+--s]=a;else if(8!==d)return;return c}(yf(e,1,-1)),!t)return Af;this.host=t}else if(this.isSpecial()){if(e=qm(e),Ef(Uf,e))return Af;if(function(e){var t,n,i=vf(e,".");if(""===i[i.length-1]){if(1===i.length)return!1;i.length--}return t=i[i.length-1],!!Ef(kf,t)||!!Ef(Pf,t)&&(""===(n=yf(t,2))||!!Ef(Mf,n))}(e)){if(t=function(e){var t,n,i,r,o,s,a,c=vf(e,".");if(c.length&&""===c[c.length-1]&&c.length--,(t=c.length)>4)return null;for(n=[],i=0;i<t;i++){if(""===(r=c[i]))return null;if(o=10,r.length>1&&"0"===_f(r,0)&&(o=Ef(Pf,r)?16:8,r=yf(r,8===o?1:2)),""===r)s=0;else{if(!Ef(10===o?kf:8===o?Lf:Mf,r))return null;s=uf(r,o)}Sf(n,s)}for(i=0;i<t;i++)if(s=n[i],i===t-1){if(s>=pf(256,5-t))return null}else if(s>255)return null;for(a=gf(n),i=0;i<n.length;i++)a+=n[i]*pf(256,3-i);return a}(e),null===t)return Af;this.host=t}else this.host=e}else{if(Ef(Vf,e))return Af;for(t="",n=Jm(e),i=0;i<n.length;i++)t+=Jf(n[i],Gf);this.host=t}},cannotHaveUsernamePasswordPort:function(){return null===this.host||""===this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return Ym(zf,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&Zf(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,n=e.username,i=e.password,r=e.host,o=e.port,s=e.path,a=e.query,c=e.fragment,d=t+":";return null!==r?(d+="//",e.includesCredentials()&&(d+=n+(i?":"+i:"")+"@"),d+=jf(r),null!==o&&(d+=":"+o)):"file"===t&&(d+="//"),null===r&&!e.cannotBeABaseURL&&s.length>1&&""===s[0]&&(d+="/."),d+=e.cannotBeABaseURL?s[0]:s.length?"/"+mf(s,"/"):"",null!==a&&(d+="?"+a),null!==c&&(d+="#"+c),d},setHref:function(e){var t=this.parse(e);if(t)throw new df(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new Rg(this.path[0]).origin}catch(e){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+jf(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(Qm(e)+":",$f)},getUsername:function(){return this.username},setUsername:function(e){var t=Jm(Qm(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var n=0;n<t.length;n++)this.username+=Jf(t[n],Xf)}},getPassword:function(){return this.password},setPassword:function(e){var t=Jm(Qm(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var n=0;n<t.length;n++)this.password+=Jf(t[n],Xf)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?jf(e):jf(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,dg)},getHostname:function(){var e=this.host;return null===e?"":jf(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,lg)},getPort:function(){var e=this.port;return null===e?"":Qm(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=Qm(e))?this.port=null:this.parse(e,ug))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+mf(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,Eg))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=Qm(e))?this.query=null:("?"===_f(e,0)&&(e=yf(e,1)),this.query="",this.parse(e,gg)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=Qm(e))?("#"===_f(e,0)&&(e=yf(e,1)),this.fragment="",this.parse(e,Sg)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var Rg=function(e){var t=Hm(this,vg),n=ef(arguments.length,1)>1?arguments[1]:void 0,i=rf(t,new Tg(e,!1,n));xm||(t.href=i.serialize(),t.origin=i.getOrigin(),t.protocol=i.getProtocol(),t.username=i.getUsername(),t.password=i.getPassword(),t.host=i.getHost(),t.hostname=i.getHostname(),t.port=i.getPort(),t.pathname=i.getPathname(),t.search=i.getSearch(),t.searchParams=i.getSearchParams(),t.hash=i.getHash())},vg=Rg.prototype,yg=function(e,t){return{get:function(){return of(this)[e]()},set:t&&function(e){return of(this)[t](e)},configurable:!0,enumerable:!0}};if(xm&&(Km(vg,"href",yg("serialize","setHref")),Km(vg,"origin",yg("getOrigin")),Km(vg,"protocol",yg("getProtocol","setProtocol")),Km(vg,"username",yg("getUsername","setUsername")),Km(vg,"password",yg("getPassword","setPassword")),Km(vg,"host",yg("getHost","setHost")),Km(vg,"hostname",yg("getHostname","setHostname")),Km(vg,"port",yg("getPort","setPort")),Km(vg,"pathname",yg("getPathname","setPathname")),Km(vg,"search",yg("getSearch","setSearch")),Km(vg,"searchParams",yg("getSearchParams")),Km(vg,"hash",yg("getHash","setHash"))),Wm(vg,"toJSON",(function(){return of(this).serialize()}),{enumerable:!0}),Wm(vg,"toString",(function(){return of(this).serialize()}),{enumerable:!0}),cf){var bg=cf.createObjectURL,Cg=cf.revokeObjectURL;bg&&Wm(Rg,"createObjectURL",jm(bg,cf)),Cg&&Wm(Rg,"revokeObjectURL",jm(Cg,cf))}$m(Rg,"URL"),Vm({global:!0,constructor:!0,forced:!Fm,sham:!xm},{URL:Rg});var Ig=Nn,Ag=i,wg=hd,Og=vi,Ng=h_,Dg=re("URL"),Pg=Ng&&Ag((function(){Dg.canParse()})),Lg=Ag((function(){return 1!==Dg.canParse.length}));Ig({target:"URL",stat:!0,forced:!Pg||Lg},{canParse:function(e){var t=wg(arguments.length,1),n=Og(e),i=t<2||void 0===arguments[1]?void 0:Og(arguments[1]);try{return!!new Dg(n,i)}catch(e){return!1}}});var kg=Nn,Mg=hd,Ug=vi,Vg=h_,xg=re("URL");kg({target:"URL",stat:!0,forced:!Vg},{parse:function(e){var t=Mg(arguments.length,1),n=Ug(e),i=t<2||void 0===arguments[1]?void 0:Ug(arguments[1]);try{return new xg(n,i)}catch(e){return null}}});var Fg=n($.URL);let Bg=!0,jg=!0;function Gg(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseInt(i[n],10)}function Wg(e,t,n){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return r.apply(this,arguments);const o=e=>{const t=n(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,o),r.apply(this,[e,o])};const o=i.removeEventListener;i.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(n))return o.apply(this,arguments);const i=this._eventMap[t].get(n);return this._eventMap[t].delete(n),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function Kg(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Bg=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Hg(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(jg=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Yg(){if("object"==typeof window){if(Bg)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Xg(e,t){jg&&console.warn(e+" is deprecated, please use "+t+" instead.")}function Jg(e){return"[object Object]"===Object.prototype.toString.call(e)}function zg(e){var t;return Jg(e)?ar(t=Object.keys(e)).call(t,(function(t,n){const i=Jg(e[n]),r=i?zg(e[n]):e[n],o=i&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[n]:r})}),{}):e}function Zg(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?Zg(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach((t=>{Zg(e,e.get(t),n)}))})))}function qg(e,t,n){const i=n?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((n=>{n.type===i&&n.trackId===t.id&&Zg(e,n,r)}))})),r}const Qg=Yg;function $g(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((n=>{if("require"===n||"advanced"===n||"mediaSource"===n)return;const i="object"==typeof e[n]?e[n]:{ideal:e[n]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[r("min",n)]=i.ideal,t.optional.push(e),e={},e[r("max",n)]=i.ideal,t.optional.push(e)):(e[r("",n)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",n)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,n)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return n.mediaDevices.enumerateDevices().then((n=>{n=n.filter((e=>"videoinput"===e.kind));let s=n.find((e=>t.some((t=>{var n;return Vi(n=e.label.toLowerCase()).call(n,t)}))));return!s&&n.length&&Vi(t).call(t,"back")&&(s=n[n.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=i(e.video),Qg("chrome: "+JSON.stringify(e)),r(e)}))}e.video=i(e.video)}return Qg("chrome: "+JSON.stringify(e)),r(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(n.getUserMedia=function(e,t,i){r(e,(e=>{n.webkitGetUserMedia(e,t,(e=>{i&&i(o(e))}))}))}.bind(n),n.mediaDevices.getUserMedia){const e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>dp.reject(o(e))))))}}}function eS(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function tS(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.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 t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.track.id)):{track:n.track};const r=new Event("track");r.track=n.track,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.id)):{track:n};const r=new Event("track");r.track=n,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Wg(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function nS(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let r=n.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function iS(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const e=Array.prototype.slice.call(arguments),n=e[0],i=e[1],r=e[2];if(arguments.length>0&&"function"==typeof n)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof n))return t.apply(this,[]);const o=function(e){const t={};return e.result().forEach((e=>{const n={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{n[t]=e.stat(t)})),t[n.id]=n})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const e=function(e){i(s(o(e)))};return t.apply(this,[e,n])}return new dp(((e,n)=>{t.apply(this,[function(t){e(s(o(t)))},n])})).then(i,r)}}function rS(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>qg(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),Wg(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>qg(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,n,i;return this.getSenders().forEach((n=>{n.track===e&&(t?i=!0:t=n)})),this.getReceivers().forEach((t=>(t.track===e&&(n?i=!0:n=t),t.track===e))),i||t&&n?dp.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():n?n.getStats():dp.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function oS(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?-1===this._shimmedLocalStreams[n.id].indexOf(i)&&this._shimmedLocalStreams[n.id].push(i):this._shimmedLocalStreams[n.id]=[n,i],i};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();n.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const n=this._shimmedLocalStreams[t].indexOf(e);-1!==n&&this._shimmedLocalStreams[t].splice(n,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function sS(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return oS(e);const n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}i.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],r=e._streams[i.id];n=n.replace(new RegExp(r.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:n})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single  stream which is associated with the specified track.","NotSupportedError");const r=this.getSenders().find((e=>e.track===t));if(r)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[n.id];if(o)o.addTrack(t),dp.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[n.id]=i,this._reverseStreams[i.id]=n,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?n.apply(this,[t=>{const n=o(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],r=e._streams[i.id];n=n.replace(new RegExp(i.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:n})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((n=>{this._streams[n].getTracks().find((t=>e.track===t))&&(t=this._streams[n])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function aS(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function cS(e,t){Wg(e,"negotiationneeded",(e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e}))}var dS=Object.freeze({__proto__:null,fixNegotiationNeeded:cS,shimAddTrackRemoveTrack:sS,shimAddTrackRemoveTrackWithNative:oS,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(n){return t(n).then((t=>{const i=n.video&&n.video.width,r=n.video&&n.video.height,o=n.video&&n.video.frameRate;return n.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},i&&(n.video.mandatory.maxWidth=i),r&&(n.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(n)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:nS,shimGetStats:iS,shimGetUserMedia:$g,shimMediaStream:eS,shimOnTrack:tS,shimPeerConnection:aS,shimSenderReceiverGetStats:rS});function lS(e,t){const n=e&&e.navigator,i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){Xg("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return"object"==typeof n&&"object"==typeof n.audio&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,"autoGainControl","mozAutoGainControl"),e(n.audio,"noiseSuppression","mozNoiseSuppression")),t(n)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const n=t.apply(this,arguments);return e(n,"mozAutoGainControl","autoGainControl"),e(n,"mozNoiseSuppression","noiseSuppression"),n}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(n){return"audio"===this.kind&&"object"==typeof n&&(n=JSON.parse(JSON.stringify(n)),e(n,"autoGainControl","mozAutoGainControl"),e(n,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[n])}}}}function uS(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function hS(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const e=Array.prototype.slice.call(arguments),r=e[0],o=e[1],s=e[2];return i.apply(this,[r||null]).then((e=>{if(t.version<53&&!o)try{e.forEach((e=>{e.type=n[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:n[t.type]||t.type}))}))}return e})).then(o,s)}}function pS(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):dp.resolve(new Map)}}function _S(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),Wg(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ES(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Xg("removeStream","removeTrack"),this.getSenders().forEach((t=>{var n;t.track&&Vi(n=e.getTracks()).call(n,t.track)&&this.removeTrack(t)}))})}function mS(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function fS(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const n=e.length>0;n&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(n){const t=i.sender,n=t.getParameters();(!("encodings"in n)||1===n.encodings.length&&0===Object.keys(n.encodings[0]).length)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function gS(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function SS(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?dp.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function TS(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?dp.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var RS=Object.freeze({__proto__:null,shimAddTransceiver:fS,shimCreateAnswer:TS,shimCreateOffer:SS,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!n||!n.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,dp.reject(e)}return!0===n.video?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})},shimGetParameters:gS,shimGetUserMedia:lS,shimOnTrack:uS,shimPeerConnection:hS,shimRTCDataChannel:mS,shimReceiverGetStats:_S,shimRemoveStream:ES,shimSenderGetStats:pS});function vS(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){var n;this._localStreams||(this._localStreams=[]),Vi(n=this._localStreams).call(n,e)||this._localStreams.push(e),e.getAudioTracks().forEach((n=>t.call(this,n,e))),e.getVideoTracks().forEach((n=>t.call(this,n,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return i&&i.forEach((e=>{var t;this._localStreams?Vi(t=this._localStreams).call(t,e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const n=e.getTracks();this.getSenders().forEach((e=>{Vi(n).call(n,e.track)&&this.removeTrack(e)}))})}}function yS(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.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=e=>{e.streams.forEach((e=>{var t;if(this._remoteStreams||(this._remoteStreams=[]),Vi(t=this._remoteStreams).call(t,e))return;this._remoteStreams.push(e);const n=new Event("addstream");n.stream=e,this.dispatchEvent(n)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const n=new Event("addstream");n.stream=t,e.dispatchEvent(n)}))}),t.apply(e,arguments)}}}function bS(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,r=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),dp.resolve()):r},t.createAnswer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),dp.resolve()):r};let a=function(e,t,n){const i=r.apply(this,[e]);return n?(i.then(t,n),dp.resolve()):i};t.setLocalDescription=a,a=function(e,t,n){const i=o.apply(this,[e]);return n?(i.then(t,n),dp.resolve()):i},t.setRemoteDescription=a,a=function(e,t,n){const i=s.apply(this,[e]);return n?(i.then(t,n),dp.resolve()):i},t.addIceCandidate=a}function CS(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(IS(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,i){t.mediaDevices.getUserMedia(e).then(n,i)}.bind(t))}function IS(e){return e&&void 0!==e.video?Object.assign({},e,{video:zg(e.video)}):e}function AS(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){const t=[];for(let n=0;n<e.iceServers.length;n++){let i=e.iceServers[n];!i.hasOwnProperty("urls")&&i.hasOwnProperty("url")?(Xg("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function wS(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function OS(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const n=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveVideo||n||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function NS(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var DS=Object.freeze({__proto__:null,shimAudioContext:NS,shimCallbacksAPI:bS,shimConstraints:IS,shimCreateOfferLegacy:OS,shimGetUserMedia:CS,shimLocalStreamsAPI:vS,shimRTCIceServerUrls:AS,shimRemoteStreamsAPI:yS,shimTrackEventTransceiver:wS}),PS="\t\n\v\f\r                　\u2028\u2029\ufeff",LS=X,kS=vi,MS=PS,US=d("".replace),VS=RegExp("^["+MS+"]+"),xS=RegExp("(^|[^"+MS+"])["+MS+"]+$"),FS=function(e){return function(t){var n=kS(LS(t));return 1&e&&(n=US(n,VS,"")),2&e&&(n=US(n,xS,"$1")),n}},BS={start:FS(1),end:FS(2),trim:FS(3)},jS=Ca.PROPER,GS=i,WS=PS,KS=BS.trim;Nn({target:"String",proto:!0,forced:function(e){return GS((function(){return!!WS[e]()||"​᠎"!=="​᠎"[e]()||jS&&WS[e].name!==e}))}("trim")},{trim:function(){return KS(this)}});var HS=ii("String","trim"),YS=l,XS=HS,JS=String.prototype,zS=function(e){var t=e.trim;return"string"==typeof e||e===JS||YS(JS,e)&&t===JS.trim?XS:t},ZS=n(zS),qS={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){const n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter((e=>0===e.indexOf(n)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const n={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":n.relatedAddress=t[e+1];break;case"rport":n.relatedPort=parseInt(t[e+1],10);break;case"tcptype":n.tcpType=t[e+1];break;case"ufrag":n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:void 0===n[t[e]]&&(n[t[e]]=t[e+1])}return n},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const n=e.component;"rtp"===n?t.push(1):"rtcp"===n?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&void 0!==e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const n={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=3===t.length?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let n;const i=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<i.length;e++)n=i[e].trim().split("="),t[n[0].trim()]=n[1];return t},t.writeFmtp=function(e){let t="",n=e.payloadType;if(void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+n+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),n={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(n.attribute=e.substring(t+1,i),n.value=e.substring(i+1)):n.attribute=e.substring(t+1),n},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const n=t.matchPrefix(e,"a=mid:")[0];if(n)return n.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,n){return{role:"auto",fingerprints:t.matchPrefix(e+n,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let n="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),n},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(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}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,n){return t.matchPrefix(e+n,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,n){const i=t.matchPrefix(e+n,"a=ice-ufrag:")[0],r=t.matchPrefix(e+n,"a=ice-pwd:")[0];return i&&r?{usernameFragment:i.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");n.profile=i[2];for(let r=3;r<i.length;r++){const o=i[r],s=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(s){const i=t.parseRtpMap(s),r=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(i.parameters=r.length?t.parseFmtp(r[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),n.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(i.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{n.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),n},t.writeRtpDescription=function(e,n){let i="";i+="m="+e+" ",i+=n.codecs.length>0?"9":"0",i+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=n.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",n.codecs.forEach((e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));let r=0;return n.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(i+="a=maxptime:"+r+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const n=[],i=t.parseRtpParameters(e),r=-1!==i.fecMechanisms.indexOf("RED"),o=-1!==i.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),i.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),n.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},n.push(t))}})),0===n.length&&a&&n.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,n.forEach((e=>{e.maxBitrate=l}))),n},t.parseRtcpParameters=function(e){const n={},i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];i&&(n.cname=i.value,n.ssrc=i.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=r.length>0,n.compound=0===r.length;const o=t.matchPrefix(e,"a=rtcp-mux");return n.mux=o.length>0,n},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let n;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return n=i[0].substring(7).split(" "),{stream:n[0],track:n[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(n=r[0].value.split(" "),{stream:n[0],track:n[1]}):void 0},t.parseSctpDescription=function(e){const n=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let r;i.length>0&&(r=parseInt(i[0].substring(19),10)),isNaN(r)&&(r=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:n.fmt,maxMessageSize:r};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let n=[];return n="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,n,i){let r;const o=void 0!==n?n:2;r=e||t.generateSessionId();return"v=0\r\no="+(i||"thisisadapterortc")+" "+r+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){const i=t.splitLines(e);for(let e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const n=t.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},t.parseOLine=function(e){const n=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||"="!==n[e].charAt(1))return!1;return!0},e.exports=t}(qS);var QS=qS.exports,$S=n(QS),eT=e({__proto__:null,default:$S},[QS]);function tT(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const n=new t(e),i=$S.parseCandidate(e.candidate),r=Object.assign(n,i);return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,Wg(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function nT(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||Wg(e,"icecandidate",(e=>{if(e.candidate){const t=$S.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function iT(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const n=function(e){if(!e||!e.sdp)return!1;const t=$S.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=$S.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},i=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const n=parseInt(t[1],10);return n!=n?-1:n},r=function(e){let n=65536;return"firefox"===t.browser&&(n=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),n},o=function(e,n){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const r=$S.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?i=parseInt(r[0].substr(19),10):"firefox"===t.browser&&-1!==n&&(i=2147483637),i},s=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){"plan-b"===this.getConfiguration().sdpSemantics&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(n(arguments[0])){const e=i(arguments[0]),t=r(e),n=o(arguments[0],e);let s;s=0===t&&0===n?Number.POSITIVE_INFINITY:0===t||0===n?Math.max(t,n):Math.min(t,n);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>s}),this._sctp=a}return s.apply(this,arguments)}}function rT(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const n=e.send;e.send=function(){const i=arguments[0],r=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return n.apply(e,arguments)}}const n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=n.apply(this,arguments);return t(e,this),e},Wg(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function oT(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"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 n=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const n=new Event("connectionstatechange",e);t.dispatchEvent(n)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}}))}function sT(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const n=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==ZS(e).call(e))).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:n}):t.sdp=n}return n.apply(this,arguments)}}function aT(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.addIceCandidate;n&&0!==n.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?dp.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),dp.resolve())})}function cT(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.setLocalDescription;n&&0!==n.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return n.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return n.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>n.apply(this,[e])))})}var dT=Object.freeze({__proto__:null,removeExtmapAllowMixed:sT,shimAddIceCandidateNullOrEmpty:aT,shimConnectionState:oT,shimMaxMessageSize:iT,shimParameterlessSetLocalDescription:cT,shimRTCIceCandidate:tT,shimRTCIceCandidateRelayProtocol:nT,shimSendThrowTypeError:rT});!function(){let e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).window,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=Yg,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const n=e.navigator;if(n.mozGetUserMedia)t.browser="firefox",t.version=Gg(n.userAgent,/Firefox\/(\d+)\./,1);else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=Gg(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=Gg(n.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:i,commonShim:dT,extractVersion:Gg,disableLog:Kg,disableWarnings:Hg,sdp:eT};switch(i.browser){case"chrome":if(!dS||!aS||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(null===i.version)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=dS,aT(e,i),cT(e),$g(e,i),eS(e),aS(e,i),tS(e),sS(e,i),nS(e),iS(e),rS(e),cS(e,i),tT(e),nT(e),oT(e),iT(e,i),rT(e),sT(e,i);break;case"firefox":if(!RS||!hS||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=RS,aT(e,i),cT(e),lS(e,i),hS(e,i),uS(e),ES(e),pS(e),_S(e),mS(e),fS(e),gS(e),SS(e),TS(e),tT(e),oT(e),iT(e,i),rT(e);break;case"safari":if(!DS||!t.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=DS,aT(e,i),cT(e),AS(e),OS(e),bS(e),vS(e),yS(e),wS(e),CS(e),NS(e),tT(e),nT(e),iT(e,i),rT(e),sT(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window}),Nn({target:"Array",stat:!0},{isArray:dr});var lT=n($.Array.isArray);var uT=TypeError,hT=function(e){if(e>9007199254740991)throw new uT("Maximum allowed index exceeded");return e},pT=dr,_T=td,ET=Q,mT=pt("species"),fT=Array,gT=function(e){var t;return pT(e)&&(t=e.constructor,(_T(t)&&(t===fT||pT(t.prototype))||ET(t)&&null===(t=t[mT]))&&(t=void 0)),void 0===t?fT:t},ST=function(e,t){return new(gT(e))(0===t?0:t)},TT=i,RT=_e,vT=pt("species"),yT=function(e){return RT>=51||!TT((function(){var t=[];return(t.constructor={})[vT]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},bT=Nn,CT=i,IT=dr,AT=Q,wT=Ze,OT=Kn,NT=hT,DT=$E,PT=rm,LT=ST,kT=yT,MT=_e,UT=pt("isConcatSpreadable"),VT=MT>=51||!CT((function(){var e=[];return e[UT]=!1,e.concat()[0]!==e})),xT=function(e){if(!AT(e))return!1;var t=e[UT];return void 0!==t?!!t:IT(e)};bT({target:"Array",proto:!0,arity:1,forced:!VT||!kT("concat")},{concat:function(e){var t,n,i,r,o,s=wT(this),a=LT(s,0),c=0;for(t=-1,i=arguments.length;t<i;t++)if(xT(o=-1===t?s:arguments[t]))for(r=OT(o),NT(c+r),n=0;n<r;n++,c++)n in o&&DT(a,c,o[n]);else NT(c+1),DT(a,c++,o);return PT(a,c),a}});var FT={},BT=R,jT=Z,GT=Kr.f,WT=ld,KT="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];FT.f=function(e){return KT&&"Window"===BT(e)?function(e){try{return GT(e)}catch(e){return WT(KT)}}(e):GT(jT(e))};var HT={},YT=pt;HT.f=YT;var XT=$,JT=$e,zT=HT,ZT=Qt.f,qT=function(e){var t=XT.Symbol||(XT.Symbol={});JT(t,e)||ZT(t,e,{value:zT.f(e)})},QT=D,$T=re,eR=pt,tR=Aa,nR=function(){var e=$T("Symbol"),t=e&&e.prototype,n=t&&t.valueOf,i=eR("toPrimitive");t&&!t[i]&&tR(t,i,(function(e){return QT(n,this)}),{arity:1})},iR=qt,rR=W,oR=Ze,sR=Kn,aR=ST,cR=$E,dR=function(e){var t=1===e,n=2===e,i=3===e,r=4===e,o=6===e,s=7===e,a=5===e||o;return function(c,d,l){for(var u,h,p=oR(c),_=rR(p),E=sR(_),m=iR(d,l),f=0,g=0,S=t?aR(c,E):n||s?aR(c,0):void 0;E>f;f++)if((a||f in _)&&(h=m(u=_[f],f,p),e))if(t)cR(S,f,h);else if(h)switch(e){case 3:return!0;case 5:return u;case 6:return f;case 2:cR(S,g++,u)}else switch(e){case 4:return!1;case 7:cR(S,g++,u)}return o?-1:i||r?r:S}},lR={forEach:dR(0),map:dR(1),filter:dR(2),some:dR(3),every:dR(4),find:dR(5),findIndex:dR(6),filterReject:dR(7)},uR=Nn,hR=h,pR=D,_R=d,ER=w,mR=ge,fR=i,gR=$e,SR=l,TR=rn,RR=Z,vR=yt,yR=vi,bR=x,CR=xo,IR=mo,AR=Kr,wR=FT,OR=to,NR=A,DR=Qt,PR=po,LR=P,kR=Aa,MR=Ac,UR=Xe,VR=Hr,xR=rt,FR=pt,BR=HT,jR=qT,GR=nR,WR=Ya,KR=Sa,HR=lR.forEach,YR=yr("hidden"),XR="Symbol",JR="prototype",zR=KR.set,ZR=KR.getterFor(XR),qR=Object[JR],QR=hR.Symbol,$R=QR&&QR[JR],ev=hR.RangeError,tv=hR.TypeError,nv=hR.QObject,iv=NR.f,rv=DR.f,ov=wR.f,sv=LR.f,av=_R([].push),cv=UR("symbols"),dv=UR("op-symbols"),lv=UR("wks"),uv=!nv||!nv[JR]||!nv[JR].findChild,hv=function(e,t,n){var i=iv(qR,t);return i&&delete qR[t],rv(e,t,n),i&&e!==qR&&rv(qR,t,i),e},pv=ER&&fR((function(){return 7!==CR(rv({},"a",{get:function(){return rv(this,"a",{value:7}).a}})).a}))?hv:rv,_v=function(e,t){var n=cv[e]=CR($R);return zR(n,{type:XR,tag:e,description:t}),ER||(n.description=t),n},Ev=function(e,t,n){e===qR&&Ev(dv,t,n),TR(e);var i=vR(t);return TR(n),gR(cv,i)?(("enumerable"in n?!n.enumerable:!gR(e,i)||gR(e,YR)&&e[YR][i])?(gR(e,YR)||rv(e,YR,bR(1,CR(null))),e[YR][i]=!0):(gR(e,YR)&&e[YR][i]&&(e[YR][i]=!1),n=CR(n,{enumerable:bR(0,!1)})),pv(e,i,n)):rv(e,i,n)},mv=function(e,t){TR(e);var n=RR(t),i=IR(n).concat(Tv(n));return HR(i,(function(t){ER&&!pR(fv,n,t)||Ev(e,t,n[t])})),e},fv=function(e){var t=vR(e),n=pR(sv,this,t);return!(this===qR&&gR(cv,t)&&!gR(dv,t))&&(!(n||!gR(this,t)||!gR(cv,t)||gR(this,YR)&&this[YR][t])||n)},gv=function(e,t){var n=RR(e),i=vR(t);if(n!==qR||!gR(cv,i)||gR(dv,i)){var r=iv(n,i);return!r||!gR(cv,i)||gR(n,YR)&&n[YR][i]||(r.enumerable=!0),r}},Sv=function(e){var t=ov(RR(e)),n=[];return HR(t,(function(e){gR(cv,e)||gR(VR,e)||av(n,e)})),n},Tv=function(e){var t=e===qR,n=ov(t?dv:RR(e)),i=[];return HR(n,(function(e){!gR(cv,e)||t&&!gR(qR,e)||av(i,cv[e])})),i};mR||(kR($R=(QR=function(){if(SR($R,this))throw new tv("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?yR(arguments[0]):void 0,t=xR(e),n=function(e){var i=void 0===this?hR:this;i===qR&&pR(n,dv,e),gR(i,YR)&&gR(i[YR],t)&&(i[YR][t]=!1);var r=bR(1,e);try{pv(i,t,r)}catch(e){if(!(e instanceof ev))throw e;hv(i,t,r)}};return ER&&uv&&pv(qR,t,{configurable:!0,set:n}),_v(t,e)})[JR],"toString",(function(){return ZR(this).tag})),kR(QR,"withoutSetter",(function(e){return _v(xR(e),e)})),LR.f=fv,DR.f=Ev,PR.f=mv,NR.f=gv,AR.f=wR.f=Sv,OR.f=Tv,BR.f=function(e){return _v(FR(e),e)},ER&&MR($R,"description",{configurable:!0,get:function(){return ZR(this).description}})),uR({global:!0,constructor:!0,wrap:!0,forced:!mR,sham:!mR},{Symbol:QR}),HR(IR(lv),(function(e){jR(e)})),uR({target:XR,stat:!0,forced:!mR},{useSetter:function(){uv=!0},useSimple:function(){uv=!1}}),uR({target:"Object",stat:!0,forced:!mR,sham:!ER},{create:function(e,t){return void 0===t?CR(e):mv(CR(e),t)},defineProperty:Ev,defineProperties:mv,getOwnPropertyDescriptor:gv}),uR({target:"Object",stat:!0,forced:!mR},{getOwnPropertyNames:Sv}),GR(),WR(QR,XR),VR[YR]=!0;var Rv=ge&&!!Symbol.for&&!!Symbol.keyFor,vv=Nn,yv=re,bv=$e,Cv=vi,Iv=Xe,Av=Rv,wv=Iv("string-to-symbol-registry"),Ov=Iv("symbol-to-string-registry");vv({target:"Symbol",stat:!0,forced:!Av},{for:function(e){var t=Cv(e);if(bv(wv,t))return wv[t];var n=yv("Symbol")(t);return wv[t]=n,Ov[n]=t,n}});var Nv=Nn,Dv=$e,Pv=be,Lv=Ie,kv=Rv,Mv=Xe("symbol-to-string-registry");Nv({target:"Symbol",stat:!0,forced:!kv},{keyFor:function(e){if(!Pv(e))throw new TypeError(Lv(e)+" is not a symbol");if(Dv(Mv,e))return Mv[e]}});var Uv=Q,Vv=Sa.get,xv=d,Fv=$e,Bv=SyntaxError,jv=parseInt,Gv=String.fromCharCode,Wv=xv("".charAt),Kv=xv("".slice),Hv=xv(/./.exec),Yv={'\\"':'"',"\\\\":"\\","\\/":"/","\\b":"\b","\\f":"\f","\\n":"\n","\\r":"\r","\\t":"\t"},Xv=/^[\da-f]{4}$/i,Jv=/^[\u0000-\u001F]$/,zv=!i((function(){var e="9007199254740993",t=JSON.rawJSON(e);return!JSON.isRawJSON(t)||JSON.stringify(t)!==e})),Zv=Nn,qv=re,Qv=f,$v=D,ey=d,ty=i,ny=dr,iy=I,ry=function(e){if(!Uv(e))return!1;var t=Vv(e);return!!t&&"RawJSON"===t.type},oy=be,sy=R,ay=vi,cy=ld,dy=function(e,t){for(var n=!0,i="";t<e.length;){var r=Wv(e,t);if("\\"===r){var o=Kv(e,t,t+2);if(Fv(Yv,o))i+=Yv[o],t+=2;else{if("\\u"!==o)throw new Bv('Unknown escape sequence: "'+o+'"');var s=Kv(e,t+=2,t+4);if(!Hv(Xv,s))throw new Bv("Bad Unicode escape at: "+t);i+=Gv(jv(s,16)),t+=4}}else{if('"'===r){n=!1,t++;break}if(Hv(Jv,r))throw new Bv("Bad control character in string literal at: "+t);i+=r,t++}}if(n)throw new Bv("Unterminated string at: "+t);return{value:i,end:t}},ly=rt,uy=ge,hy=zv,py=String,_y=qv("JSON","stringify"),Ey=ey(/./.exec),my=ey("".charAt),fy=ey("".charCodeAt),gy=ey("".replace),Sy=ey("".slice),Ty=ey([].push),Ry=ey(1.1.toString),vy=/[\uD800-\uDFFF]/g,yy=/^[\uD800-\uDBFF]$/,by=/^[\uDC00-\uDFFF]$/,Cy=ly(),Iy=Cy.length,Ay=!uy||ty((function(){var e=qv("Symbol")("stringify detection");return"[null]"!==_y([e])||"{}"!==_y({a:e})||"{}"!==_y(Object(e))})),wy=ty((function(){return'"\\udf06\\ud834"'!==_y("\udf06\ud834")||'"\\udead"'!==_y("\udead")})),Oy=Ay?function(e,t){var n=cy(arguments),i=Dy(t);if(iy(i)||void 0!==e&&!oy(e))return n[1]=function(e,t){if(iy(i)&&(t=$v(i,this,py(e),t)),!oy(t))return t},Qv(_y,null,n)}:_y,Ny=function(e,t,n){var i=my(n,t-1),r=my(n,t+1);return Ey(yy,e)&&!Ey(by,r)||Ey(by,e)&&!Ey(yy,i)?"\\u"+Ry(fy(e,0),16):e},Dy=function(e){if(iy(e))return e;if(ny(e)){for(var t=e.length,n=[],i=0;i<t;i++){var r=e[i];"string"==typeof r?Ty(n,r):"number"!=typeof r&&"Number"!==sy(r)&&"String"!==sy(r)||Ty(n,ay(r))}var o=n.length,s=!0;return function(e,t){if(s)return s=!1,t;if(ny(this))return t;for(var i=0;i<o;i++)if(n[i]===e)return t}}};_y&&Zv({target:"JSON",stat:!0,arity:3,forced:Ay||wy||!hy},{stringify:function(e,t,n){var i=Dy(t),r=[],o=Oy(e,(function(e,t){var n=iy(i)?$v(i,this,py(e),t):t;return!hy&&ry(n)?Cy+(Ty(r,n.rawJSON)-1):n}),n);if("string"!=typeof o)return o;if(wy&&(o=gy(o,vy,Ny)),hy)return o;for(var s="",a=o.length,c=0;c<a;c++){var d=my(o,c);if('"'===d){var l=dy(o,++c).end-1,u=Sy(o,c,l);s+=Sy(u,0,Iy)===Cy?r[Sy(u,Iy)]:'"'+u+'"',c=l}else s+=d}return s}});var Py=to,Ly=Ze;Nn({target:"Object",stat:!0,forced:!ge||i((function(){Py.f(1)}))},{getOwnPropertySymbols:function(e){var t=Py.f;return t?t(Ly(e)):[]}}),qT("asyncDispose"),qT("asyncIterator"),qT("dispose"),qT("hasInstance"),qT("isConcatSpreadable"),qT("iterator"),qT("match"),qT("matchAll"),qT("replace"),qT("search"),qT("species"),qT("split");var ky=nR;qT("toPrimitive"),ky();var My=re,Uy=Ya;qT("toStringTag"),Uy(My("Symbol"),"Symbol"),qT("unscopables"),Ya(h.JSON,"JSON",!0);var Vy=$.Symbol,xy=pt,Fy=Qt.f,By=xy("metadata"),jy=Function.prototype;void 0===jy[By]&&Fy(jy,By,{value:null}),qT("metadata");var Gy=Vy,Wy=d,Ky=re("Symbol"),Hy=Ky.keyFor,Yy=Wy(Ky.prototype.valueOf),Xy=Ky.isRegisteredSymbol||function(e){try{return void 0!==Hy(Yy(e))}catch(e){return!1}};Nn({target:"Symbol",stat:!0},{isRegisteredSymbol:Xy});for(var Jy=Xe,zy=re,Zy=d,qy=be,Qy=pt,$y=zy("Symbol"),eb=$y.isWellKnownSymbol,tb=zy("Object","getOwnPropertyNames"),nb=Zy($y.prototype.valueOf),ib=Jy("wks"),rb=0,ob=tb($y),sb=ob.length;rb<sb;rb++)try{var ab=ob[rb];qy($y[ab])&&Qy(ab)}catch(e){}var cb=function(e){if(eb&&eb(e))return!0;try{for(var t=nb(e),n=0,i=tb(ib),r=i.length;n<r;n++)if(ib[i[n]]==t)return!0}catch(e){}return!1};Nn({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:cb}),qT("customMatcher"),qT("observable"),Nn({target:"Symbol",stat:!0,name:"isRegisteredSymbol"},{isRegistered:Xy}),Nn({target:"Symbol",stat:!0,name:"isWellKnownSymbol",forced:!0},{isWellKnown:cb}),qT("matcher"),qT("metadataKey"),qT("patternMatch"),qT("replaceAll");var db=n(Gy),lb=n(cs),ub=Ze,hb=Kn,pb=rm,_b=hT;Nn({target:"Array",proto:!0,arity:1,forced:i((function(){return 4294967297!==[].push.call({length:4294967296},1)}))||!function(){try{Object.defineProperty([],"length",{writable:!1}).push()}catch(e){return e instanceof TypeError}}()},{push:function(e){var t=ub(this),n=hb(t),i=arguments.length;_b(n+i);for(var r=0;r<i;r++)t[n]=arguments[r],n++;return pb(t,n),n}});var Eb=ii("Array","push"),mb=l,fb=Eb,gb=Array.prototype,Sb=function(e){var t=e.push;return e===gb||mb(gb,e)&&t===gb.push?fb:t},Tb=n(Sb);var Rb=Nn,vb=dr,yb=td,bb=Q,Cb=Fn,Ib=Kn,Ab=Z,wb=$E,Ob=rm,Nb=pt,Db=ld,Pb=yT("slice"),Lb=Nb("species"),kb=Array,Mb=Math.max;Rb({target:"Array",proto:!0,forced:!Pb},{slice:function(e,t){var n,i,r,o=Ab(this),s=Ib(o),a=Cb(e,s),c=Cb(void 0===t?s:t,s);if(vb(o)&&(n=o.constructor,(yb(n)&&(n===kb||vb(n.prototype))||bb(n)&&null===(n=n[Lb]))&&(n=void 0),n===kb||void 0===n))return Db(o,a,c);for(i=new(void 0===n?kb:n)(Mb(c-a,0)),r=0;a<c;a++,r++)a in o&&wb(i,r,o[a]);return Ob(i,r),i}});var Ub=ii("Array","slice"),Vb=l,xb=Ub,Fb=Array.prototype,Bb=function(e){var t=e.slice;return e===Fb||Vb(Fb,e)&&t===Fb.slice?xb:t},jb=n(Bb),Gb=gm;Nn({target:"Array",stat:!0,forced:!xu((function(e){Array.from(e)}))},{from:Gb});var Wb=n($.Array.from);function Kb(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function Hb(e,t){return function(e){if(lT(e))return e}(e)||function(e,t){var n=null==e?null:void 0!==db&&lb(e)||e["@@iterator"];if(null!=n){var i,r,o,s,a=[],c=!0,d=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=o.call(n)).done)&&(Tb(a).call(a,i.value),a.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw r}}return a}}(e,t)||function(e,t){if(e){var n;if("string"==typeof e)return Kb(e,t);var i=jb(n={}.toString.call(e)).call(n,8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Wb(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?Kb(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var Yb=i,Xb=h.RegExp,Jb=!Yb((function(){var e=!0;try{Xb(".","d")}catch(t){e=!1}var t={},n="",i=e?"dgimsy":"gimsy",r=function(e,i){Object.defineProperty(t,e,{get:function(){return n+=i,!0}})},o={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var s in e&&(o.hasIndices="d"),o)r(s,o[s]);return Object.getOwnPropertyDescriptor(Xb.prototype,"flags").get.call(t)!==i||n!==i})),zb=rn,Zb=D,qb=$e,Qb=l,$b={correct:Jb},eC=function(){var e=zb(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},tC=RegExp.prototype,nC=$b.correct?function(e){return e.flags}:function(e){return $b.correct||!Qb(tC,e)||qb(e,"flags")?e.flags:Zb(eC,e)},iC=d,rC=Ze,oC=Math.floor,sC=iC("".charAt),aC=iC("".replace),cC=iC("".slice),dC=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,lC=/\$([$&'`]|\d{1,2})/g,uC=Nn,hC=D,pC=d,_C=X,EC=I,mC=Q,fC=ci,gC=vi,SC=Le,TC=nC,RC=function(e,t,n,i,r,o){var s=n+e.length,a=i.length,c=lC;return void 0!==r&&(r=rC(r),c=dC),aC(o,c,(function(o,c){var d;switch(sC(c,0)){case"$":return"$";case"&":return e;case"`":return cC(t,0,n);case"'":return cC(t,s);case"<":d=r[cC(c,1,-1)];break;default:var l=+c;if(0===l)return o;if(l>a){var u=oC(l/10);return 0===u?o:u<=a?void 0===i[u-1]?sC(c,1):i[u-1]+sC(c,1):o}d=i[l-1]}return void 0===d?"":d}))},vC=pt("replace"),yC=TypeError,bC=pC("".indexOf),CC=pC("".replace),IC=pC("".slice),AC=Math.max;uC({target:"String",proto:!0},{replaceAll:function(e,t){var n,i,r,o,s,a,c,d,l,u,h=_C(this),p=0,_="";if(mC(e)){if((n=fC(e))&&(i=gC(_C(TC(e))),!~bC(i,"g")))throw new yC("`.replaceAll` does not allow non-global regexes");if(r=SC(e,vC))return hC(r,e,h,t);if(n)return CC(gC(h),e,t)}for(o=gC(h),s=gC(e),(a=EC(t))||(t=gC(t)),c=s.length,d=AC(1,c),l=bC(o,s);-1!==l;)u=a?gC(t(s,l,o)):RC(s,o,l,[],void 0,t),_+=IC(o,p,l)+u,p=l+c,l=l+d>o.length?-1:bC(o,s,l+d);return p<o.length&&(_+=IC(o,p)),_}});var wC=ii("String","replaceAll"),OC=l,NC=wC,DC=String.prototype,PC=function(e){var t=e.replaceAll;return"string"==typeof e||e===DC||OC(DC,e)&&t===DC.replaceAll?NC:t},LC=n(PC),kC=h;Nn({global:!0,forced:kC.globalThis!==kC},{globalThis:kC});var MC,UC,VC=n(h),xC={exports:{}};MC=xC,UC=xC.exports,function(e,t){var n="function",i="undefined",r="object",o="string",s="major",a="model",c="name",d="type",l="vendor",u="version",h="architecture",p="console",_="mobile",E="tablet",m="smarttv",f="wearable",g="embedded",S="Amazon",T="Apple",R="ASUS",v="BlackBerry",y="Browser",b="Chrome",C="Firefox",I="Google",A="Honor",w="Huawei",O="LG",N="Microsoft",D="Motorola",P="Nvidia",L="OnePlus",k="Opera",M="OPPO",U="Samsung",V="Sharp",x="Sony",F="Xiaomi",B="Zebra",j="Facebook",G="Chromium OS",W="Mac OS",K=" Browser",H=function(e){for(var t={},n=0;n<e.length;n++)t[e[n].toUpperCase()]=e[n];return t},Y=function(e,t){return typeof e===o&&-1!==X(t).indexOf(X(e))},X=function(e){return e.toLowerCase()},J=function(e,t){if(typeof e===o)return e=e.replace(/^\s\s*/,""),typeof t===i?e:e.substring(0,500)},z=function(e,i){for(var o,s,a,c,d,l,u=0;u<i.length&&!d;){var h=i[u],p=i[u+1];for(o=s=0;o<h.length&&!d&&h[o];)if(d=h[o++].exec(e))for(a=0;a<p.length;a++)l=d[++s],typeof(c=p[a])===r&&c.length>0?2===c.length?typeof c[1]==n?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==n||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):t:this[c[0]]=l?c[1].call(this,l,c[2]):t:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):t):this[c]=l||t;u+=2}},Z=function(e,n){for(var i in n)if(typeof n[i]===r&&n[i].length>0){for(var o=0;o<n[i].length;o++)if(Y(n[i][o],e))return"?"===i?t:i}else if(Y(n[i],e))return"?"===i?t:i;return n.hasOwnProperty("*")?n["*"]:e},q={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"},Q={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[u,[c,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[u,[c,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[c,u],[/opios[\/ ]+([\w\.]+)/i],[u,[c,k+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[u,[c,k+" GX"]],[/\bopr\/([\w\.]+)/i],[u,[c,k]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[u,[c,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[u,[c,"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],[c,u],[/quark(?:pc)?\/([-\w\.]+)/i],[u,[c,"Quark"]],[/\bddg\/([\w\.]+)/i],[u,[c,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[u,[c,"UC"+y]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[u,[c,"WeChat"]],[/konqueror\/([\w\.]+)/i],[u,[c,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[u,[c,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[u,[c,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[u,[c,"Smart Lenovo "+y]],[/(avast|avg)\/([\w\.]+)/i],[[c,/(.+)/,"$1 Secure "+y],u],[/\bfocus\/([\w\.]+)/i],[u,[c,C+" Focus"]],[/\bopt\/([\w\.]+)/i],[u,[c,k+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[u,[c,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[u,[c,"Dolphin"]],[/coast\/([\w\.]+)/i],[u,[c,k+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[u,[c,"MIUI"+K]],[/fxios\/([\w\.-]+)/i],[u,[c,C]],[/\bqihoobrowser\/?([\w\.]*)/i],[u,[c,"360"]],[/\b(qq)\/([\w\.]+)/i],[[c,/(.+)/,"$1Browser"],u],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[c,/(.+)/,"$1"+K],u],[/samsungbrowser\/([\w\.]+)/i],[u,[c,U+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[u,[c,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[c,"Sogou Mobile"],u],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[c,u],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[c],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[u,c],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[c,j],u],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/(daum)apps[\/ ]([\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],[c,u],[/\bgsa\/([\w\.]+) .*safari\//i],[u,[c,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[u,[c,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[u,[c,b+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[c,b+" WebView"],u],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[u,[c,"Android "+y]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[c,u],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[u,[c,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[u,c],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[c,[u,Z,{"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],[c,u],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[c,"Netscape"],u],[/(wolvic|librewolf)\/([\w\.]+)/i],[c,u],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[u,[c,C+" 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,/(amaya|dillo|doris|icab|ladybird|lynx|mosaic|netsurf|obigo|polaris|w3m|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/\b(links) \(([\w\.]+)/i],[c,[u,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[c,[u,/master.|lts./,""]]],cpu:[[/\b((amd|x|x86[-_]?|wow|win)64)\b/i],[[h,"amd64"]],[/(ia32(?=;))/i,/\b((i[346]|x)86)(pc)?\b/i],[[h,"ia32"]],[/\b(aarch64|arm(v?[89]e?l?|_?64))\b/i],[[h,"arm64"]],[/\b(arm(v[67])?ht?n?[fl]p?)\b/i],[[h,"armhf"]],[/( (ce|mobile); ppc;|\/[\w\.]+arm\b)/i],[[h,"arm"]],[/((ppc|powerpc)(64)?)( mac|;|\))/i],[[h,/ower/,"",X]],[/ sun4\w[;\)]/i],[[h,"sparc"]],[/\b(avr32|ia64(?=;)|68k(?=\))|\barm(?=v([1-7]|[5-7]1)l?|;|eabi)|(irix|mips|sparc)(64)?\b|pa-risc)/i],[[h,X]]],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],[a,[l,U],[d,E]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[a,[l,U],[d,_]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[a,[l,T],[d,_]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[a,[l,T],[d,E]],[/(macintosh);/i],[a,[l,T]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[a,[l,V],[d,_]],[/\b((?:brt|eln|hey2?|gdi|jdn)-a?[lnw]09|(?:ag[rm]3?|jdn2|kob2)-a?[lw]0[09]hn)(?: bui|\)|;)/i],[a,[l,A],[d,E]],[/honor([-\w ]+)[;\)]/i],[a,[l,A],[d,_]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?|605hw|bg2-u03|(?:gem|fdr|m2|ple|t1)-[7a]0[1-4][lu]|t1-a2[13][lw]|mediapad[\w\. ]*(?= bui|\)))\b(?!.+d\/s)/i],[a,[l,w],[d,E]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[a,[l,w],[d,_]],[/oid[^\)]+; (2[\dbc]{4}(182|283|rp\w{2})[cgl]|m2105k81a?c)(?: bui|\))/i,/\b((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i],[[a,/_/g," "],[l,F],[d,E]],[/\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,/ ([\w ]+) miui\/v?\d/i],[[a,/_/g," "],[l,F],[d,_]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[a,[l,M],[d,_]],[/\b(opd2(\d{3}a?))(?: bui|\))/i],[a,[l,Z,{OnePlus:["304","403","203"],"*":M}],[d,E]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[a,[l,"Vivo"],[d,_]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[a,[l,"Realme"],[d,_]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto(?! 360)[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[a,[l,D],[d,_]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[a,[l,D],[d,E]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[a,[l,O],[d,E]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv|watch)\w+)/i,/\blg-?([\d\w]+) bui/i],[a,[l,O],[d,_]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])( bui|;|\)|\/)/i,/lenovo ?(b[68]0[08]0-?[hf]?|tab(?:[\w- ]+?)|tb[\w-]{6,7})( bui|;|\)|\/)/i],[a,[l,"Lenovo"],[d,E]],[/(nokia) (t[12][01])/i],[l,a,[d,E]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,/nokia[-_ ]?(([-\w\. ]*))/i],[[a,/_/g," "],[d,_],[l,"Nokia"]],[/(pixel (c|tablet))\b/i],[a,[l,I],[d,E]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[a,[l,I],[d,_]],[/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],[a,[l,x],[d,_]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[a,"Xperia Tablet"],[l,x],[d,E]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[a,[l,L],[d,_]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[a,[l,S],[d,E]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[a,/(.+)/g,"Fire Phone $1"],[l,S],[d,_]],[/(playbook);[-\w\),; ]+(rim)/i],[a,l,[d,E]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[a,[l,v],[d,_]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[a,[l,R],[d,E]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[a,[l,R],[d,_]],[/(nexus 9)/i],[a,[l,"HTC"],[d,E]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[l,[a,/_/g," "],[d,_]],[/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],[a,[l,"TCL"],[d,E]],[/(itel) ((\w+))/i],[[l,X],a,[d,Z,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[a,[l,"Acer"],[d,E]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[a,[l,"Meizu"],[d,_]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[a,[l,"Ulefone"],[d,_]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[a,[l,"Energizer"],[d,_]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[a,[l,"Cat"],[d,_]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[a,[l,"Smartfren"],[d,_]],[/droid.+; (a(?:015|06[35]|142p?))/i],[a,[l,"Nothing"],[d,_]],[/; (x67 5g|tikeasy \w+|ac[1789]\d\w+)( b|\))/i,/archos ?(5|gamepad2?|([\w ]*[t1789]|hello) ?\d+[\w ]*)( b|\))/i],[a,[l,"Archos"],[d,E]],[/archos ([\w ]+)( b|\))/i,/; (ac[3-6]\d\w{2,8})( b|\))/i],[a,[l,"Archos"],[d,_]],[/(imo) (tab \w+)/i,/(infinix) (x1101b?)/i],[l,a,[d,E]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus(?! zenw)|dell|jolla|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (hmd|imo) ([\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,/(oppo) ?([\w ]+) bui/i],[l,a,[d,_]],[/(kobo)\s(ereader|touch)/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],[l,a,[d,E]],[/(surface duo)/i],[a,[l,N],[d,E]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[a,[l,"Fairphone"],[d,_]],[/(u304aa)/i],[a,[l,"AT&T"],[d,_]],[/\bsie-(\w*)/i],[a,[l,"Siemens"],[d,_]],[/\b(rct\w+) b/i],[a,[l,"RCA"],[d,E]],[/\b(venue[\d ]{2,7}) b/i],[a,[l,"Dell"],[d,E]],[/\b(q(?:mv|ta)\w+) b/i],[a,[l,"Verizon"],[d,E]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[a,[l,"Barnes & Noble"],[d,E]],[/\b(tm\d{3}\w+) b/i],[a,[l,"NuVision"],[d,E]],[/\b(k88) b/i],[a,[l,"ZTE"],[d,E]],[/\b(nx\d{3}j) b/i],[a,[l,"ZTE"],[d,_]],[/\b(gen\d{3}) b.+49h/i],[a,[l,"Swiss"],[d,_]],[/\b(zur\d{3}) b/i],[a,[l,"Swiss"],[d,E]],[/\b((zeki)?tb.*\b) b/i],[a,[l,"Zeki"],[d,E]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[l,"Dragon Touch"],a,[d,E]],[/\b(ns-?\w{0,9}) b/i],[a,[l,"Insignia"],[d,E]],[/\b((nxa|next)-?\w{0,9}) b/i],[a,[l,"NextBook"],[d,E]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[l,"Voice"],a,[d,_]],[/\b(lvtel\-)?(v1[12]) b/i],[[l,"LvTel"],a,[d,_]],[/\b(ph-1) /i],[a,[l,"Essential"],[d,_]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[a,[l,"Envizen"],[d,E]],[/\b(trio[-\w\. ]+) b/i],[a,[l,"MachSpeed"],[d,E]],[/\btu_(1491) b/i],[a,[l,"Rotor"],[d,E]],[/((?:tegranote|shield t(?!.+d tv))[\w- ]*?)(?: b|\))/i],[a,[l,P],[d,E]],[/(sprint) (\w+)/i],[l,a,[d,_]],[/(kin\.[onetw]{3})/i],[[a,/\./g," "],[l,N],[d,_]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[a,[l,B],[d,E]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[a,[l,B],[d,_]],[/smart-tv.+(samsung)/i],[l,[d,m]],[/hbbtv.+maple;(\d+)/i],[[a,/^/,"SmartTV"],[l,U],[d,m]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[l,O],[d,m]],[/(apple) ?tv/i],[l,[a,T+" TV"],[d,m]],[/crkey/i],[[a,b+"cast"],[l,I],[d,m]],[/droid.+aft(\w+)( bui|\))/i],[a,[l,S],[d,m]],[/(shield \w+ tv)/i],[a,[l,P],[d,m]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[a,[l,V],[d,m]],[/(bravia[\w ]+)( bui|\))/i],[a,[l,x],[d,m]],[/(mi(tv|box)-?\w+) bui/i],[a,[l,F],[d,m]],[/Hbbtv.*(technisat) (.*);/i],[l,a,[d,m]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[l,J],[a,J],[d,m]],[/droid.+; ([\w- ]+) (?:android tv|smart[- ]?tv)/i],[a,[d,m]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[d,m]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[l,a,[d,p]],[/droid.+; (shield)( bui|\))/i],[a,[l,P],[d,p]],[/(playstation \w+)/i],[a,[l,x],[d,p]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[a,[l,N],[d,p]],[/\b(sm-[lr]\d\d[0156][fnuw]?s?|gear live)\b/i],[a,[l,U],[d,f]],[/((pebble))app/i,/(asus|google|lg|oppo) ((pixel |zen)?watch[\w ]*)( bui|\))/i],[l,a,[d,f]],[/(ow(?:19|20)?we?[1-3]{1,3})/i],[a,[l,M],[d,f]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[a,[l,T],[d,f]],[/(opwwe\d{3})/i],[a,[l,L],[d,f]],[/(moto 360)/i],[a,[l,D],[d,f]],[/(smartwatch 3)/i],[a,[l,x],[d,f]],[/(g watch r)/i],[a,[l,O],[d,f]],[/droid.+; (wt63?0{2,3})\)/i],[a,[l,B],[d,f]],[/droid.+; (glass) \d/i],[a,[l,I],[d,f]],[/(pico) (4|neo3(?: link|pro)?)/i],[l,a,[d,f]],[/; (quest( \d| pro)?)/i],[a,[l,j],[d,f]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[l,[d,g]],[/(aeobc)\b/i],[a,[l,S],[d,g]],[/(homepod).+mac os/i],[a,[l,T],[d,g]],[/windows iot/i],[[d,g]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[a,[d,_]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[a,[d,E]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[d,E]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[d,_]],[/droid .+?; ([\w\. -]+)( bui|\))/i],[a,[l,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[u,[c,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[c,u],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[u,[c,"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],[c,u],[/ladybird\//i],[[c,"LibWeb"]],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[u,c]],os:[[/microsoft (windows) (vista|xp)/i],[c,u],[/(windows (?:phone(?: os)?|mobile|iot))[\/ ]?([\d\.\w ]*)/i],[c,[u,Z,q]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[u,Z,q],[c,"Windows"]],[/[adehimnop]{4,7}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[u,/_/g,"."],[c,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[c,W],[u,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[u,c],[/(ubuntu) ([\w\.]+) like android/i],[[c,/(.+)/,"$1 Touch"],u],[/(android|bada|blackberry|kaios|maemo|meego|openharmony|qnx|rim tablet os|sailfish|series40|symbian|tizen|webos)\w*[-\/; ]?([\d\.]*)/i],[c,u],[/\(bb(10);/i],[u,[c,v]],[/(?:symbian ?os|symbos|s60(?=;)|series ?60)[-\/ ]?([\w\.]*)/i],[u,[c,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[u,[c,C+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[u,[c,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[u,[c,"watchOS"]],[/crkey\/([\d\.]+)/i],[u,[c,b+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[c,G],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)(?: arm\w*| x86\w*| ?)([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[c,u],[/(sunos) ?([\w\.\d]*)/i],[[c,"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],[c,u]]},$=function(p,m){if(typeof p===r&&(m=p,p=t),!(this instanceof $))return new $(p,m).getResult();var f=typeof e!==i&&e.navigator?e.navigator:t,g=p||(f&&f.userAgent?f.userAgent:""),S=f&&f.userAgentData?f.userAgentData:t,T=m?function(e,t){var n={};for(var i in e)t[i]&&t[i].length%2==0?n[i]=t[i].concat(e[i]):n[i]=e[i];return n}(Q,m):Q,R=f&&f.userAgent==g;return this.getBrowser=function(){var e={};return e[c]=t,e[u]=t,z.call(e,g,T.browser),e[s]=function(e){return typeof e===o?e.replace(/[^\d\.]/g,"").split(".")[0]:t}(e[u]),R&&f&&f.brave&&typeof f.brave.isBrave==n&&(e[c]="Brave"),e},this.getCPU=function(){var e={};return e[h]=t,z.call(e,g,T.cpu),e},this.getDevice=function(){var e={};return e[l]=t,e[a]=t,e[d]=t,z.call(e,g,T.device),R&&!e[d]&&S&&S.mobile&&(e[d]=_),R&&"Macintosh"==e[a]&&f&&typeof f.standalone!==i&&f.maxTouchPoints&&f.maxTouchPoints>2&&(e[a]="iPad",e[d]=E),e},this.getEngine=function(){var e={};return e[c]=t,e[u]=t,z.call(e,g,T.engine),e},this.getOS=function(){var e={};return e[c]=t,e[u]=t,z.call(e,g,T.os),R&&!e[c]&&S&&S.platform&&"Unknown"!=S.platform&&(e[c]=S.platform.replace(/chrome os/i,G).replace(/macos/i,W)),e},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 g},this.setUA=function(e){return g=typeof e===o&&e.length>500?J(e,500):e,this},this.setUA(g),this};$.VERSION="0.7.41",$.BROWSER=H([c,u,s]),$.CPU=H([h]),$.DEVICE=H([a,l,d,p,_,m,E,f,g]),$.ENGINE=$.OS=H([c,u]),MC.exports&&(UC=MC.exports=$),UC.UAParser=$;var ee=typeof e!==i&&(e.jQuery||e.Zepto);if(ee&&!ee.ua){var te=new $;ee.ua=te.getResult(),ee.ua.get=function(){return te.getUA()},ee.ua.set=function(e){te.setUA(e);var t=te.getResult();for(var n in t)ee.ua[n]=t[n]}}}("object"==typeof window?window:t);var FC=n(xC.exports),BC=jd.clear;Nn({global:!0,bind:!0,enumerable:!0,forced:h.clearImmediate!==BC},{clearImmediate:BC});var jC=h,GC=f,WC=I,KC=Qi,HC=ae,YC=ld,XC=hd,JC=jC.Function,zC=/MSIE .\./.test(HC)||"BUN"===KC&&function(){var e=jC.Bun.version.split(".");return e.length<3||"0"===e[0]&&(e[1]<3||"3"===e[1]&&"0"===e[2])}(),ZC=Nn,qC=h,QC=jd.set,$C=function(e,t){var n=t?2:1;return zC?function(i,r){var o=XC(arguments.length,1)>n,s=WC(i)?i:JC(i),a=o?YC(arguments,n):[],c=o?function(){GC(s,this,a)}:s;return t?e(c,r):e(c)}:e},eI=qC.setImmediate?$C(QC,!1):QC;ZC({global:!0,bind:!0,enumerable:!0,forced:qC.setImmediate!==eI},{setImmediate:eI});var tI=n($.setImmediate),nI=h,iI=fl,rI=Ne,oI=hd,sI=w;Nn({global:!0,enumerable:!0,dontCallGetSet:!0,forced:i((function(){return sI&&1!==Object.getOwnPropertyDescriptor(nI,"queueMicrotask").value.length}))},{queueMicrotask:function(e){oI(arguments.length,1),iI(rI(e))}});var aI=n($.queueMicrotask);function cI(e,t){return function(){return e.apply(t,arguments)}}const dI=Object.prototype.toString,lI=Object.getPrototypeOf,uI=Symbol.iterator,hI=Symbol.toStringTag,pI=(_I=Object.create(null),e=>{const t=dI.call(e);return _I[t]||(_I[t]=t.slice(8,-1).toLowerCase())});var _I;const EI=e=>(e=e.toLowerCase(),t=>pI(t)===e),mI=e=>t=>typeof t===e,fI=Array.isArray,gI=mI("undefined");function SI(e){return null!==e&&!gI(e)&&null!==e.constructor&&!gI(e.constructor)&&vI(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const TI=EI("ArrayBuffer");const RI=mI("string"),vI=mI("function"),yI=mI("number"),bI=e=>null!==e&&"object"==typeof e,CI=e=>{if("object"!==pI(e))return!1;const t=lI(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||hI in e||uI in e)},II=EI("Date"),AI=EI("File"),wI=EI("Blob"),OI=EI("FileList");const NI=void 0!==VC?VC:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},DI=void 0!==NI.FormData?NI.FormData:void 0,PI=EI("URLSearchParams"),LI=Hb(["ReadableStream","Request","Response","Headers"].map(EI),4),kI=LI[0],MI=LI[1],UI=LI[2],VI=LI[3];function xI(e,t){let n,i,r=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).allOwnKeys,o=void 0!==r&&r;if(null!=e)if("object"!=typeof e&&(e=[e]),fI(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(SI(e))return;const i=o?Object.getOwnPropertyNames(e):Object.keys(e),r=i.length;let s;for(n=0;n<r;n++)s=i[n],t.call(null,e[s],s,e)}}function FI(e,t){if(SI(e))return null;t=t.toLowerCase();const n=Object.keys(e);let i,r=n.length;for(;r-- >0;)if(i=n[r],t===i.toLowerCase())return i;return null}const BI=void 0!==VC?VC:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,jI=e=>!gI(e)&&e!==BI;const GI=(WI="undefined"!=typeof Uint8Array&&lI(Uint8Array),e=>WI&&e instanceof WI);var WI;const KI=EI("HTMLFormElement"),HI=(e=>{let t=Object.prototype.hasOwnProperty;return(e,n)=>t.call(e,n)})(),YI=EI("RegExp"),XI=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),i={};xI(n,((n,r)=>{let o;!1!==(o=t(n,r,e))&&(i[r]=o||n)})),Object.defineProperties(e,i)};const JI=EI("AsyncFunction"),zI=(ZI="function"==typeof tI,qI=vI(BI.postMessage),ZI?tI:qI?(QI="axios@".concat(Math.random()),$I=[],BI.addEventListener("message",(e=>{let t=e.source,n=e.data;t===BI&&n===QI&&$I.length&&$I.shift()()}),!1),e=>{$I.push(e),BI.postMessage(QI,"*")}):e=>setTimeout(e));var ZI,qI,QI,$I;const eA=void 0!==aI?aI.bind(BI):"undefined"!=typeof process&&process.nextTick||zI;var tA={isArray:fI,isArrayBuffer:TI,isBuffer:SI,isFormData:e=>{if(!e)return!1;if(DI&&e instanceof DI)return!0;const t=lI(e);if(!t||t===Object.prototype)return!1;if(!vI(e.append))return!1;const n=pI(e);return"formdata"===n||"object"===n&&vI(e.toString)&&"[object FormData]"===e.toString()},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&TI(e.buffer),t},isString:RI,isNumber:yI,isBoolean:e=>!0===e||!1===e,isObject:bI,isPlainObject:CI,isEmptyObject:e=>{if(!bI(e)||SI(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isReadableStream:kI,isRequest:MI,isResponse:UI,isHeaders:VI,isUndefined:gI,isDate:II,isFile:AI,isReactNativeBlob:e=>!(!e||void 0===e.uri),isReactNative:e=>e&&void 0!==e.getParts,isBlob:wI,isRegExp:YI,isFunction:vI,isStream:e=>bI(e)&&vI(e.pipe),isURLSearchParams:PI,isTypedArray:GI,isFileList:OI,forEach:xI,merge:function e(){const t=jI(this)&&this||{},n=t.caseless,i=t.skipUndefined,r={},o=(t,o)=>{if("__proto__"===o||"constructor"===o||"prototype"===o)return;const s=n&&FI(r,o)||o,a=HI(r,s)?r[s]:void 0;CI(a)&&CI(t)?r[s]=e(a,t):CI(t)?r[s]=e({},t):fI(t)?r[s]=t.slice():i&&gI(t)||(r[s]=t)};for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];for(let e=0,t=a.length;e<t;e++)a[e]&&xI(a[e],o);return r},extend:function(e,t,n){return xI(t,((t,i)=>{n&&vI(t)?Object.defineProperty(e,i,{__proto__:null,value:cI(t,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,i,{__proto__:null,value:t,writable:!0,enumerable:!0,configurable:!0})}),{allOwnKeys:(arguments.length>3&&void 0!==arguments[3]?arguments[3]:{}).allOwnKeys}),e},trim:e=>ZS(e)?ZS(e).call(e):e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,n,i)=>{e.prototype=Object.create(t.prototype,i),Object.defineProperty(e.prototype,"constructor",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{__proto__:null,value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,i)=>{let r,o,s;const a={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),o=r.length;o-- >0;)s=r[o],i&&!i(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==n&&lI(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:pI,kindOfTest:EI,endsWith:(e,t,n)=>{e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;const i=e.indexOf(t,n);return-1!==i&&i===n},toArray:e=>{if(!e)return null;if(fI(e))return e;let t=e.length;if(!yI(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[uI]).call(e);let i;for(;(i=n.next())&&!i.done;){const n=i.value;t.call(e,n[0],n[1])}},matchAll:(e,t)=>{let n;const i=[];for(;null!==(n=e.exec(t));)i.push(n);return i},isHTMLForm:KI,hasOwnProperty:HI,hasOwnProp:HI,reduceDescriptors:XI,freezeMethods:e=>{XI(e,((t,n)=>{var i;if(vI(e)&&Vi(i=["arguments","caller","callee"]).call(i,n))return!1;const r=e[n];vI(r)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))}))},toObjectSet:(e,t)=>{const n={},i=e=>{e.forEach((e=>{n[e]=!0}))};return fI(e)?i(e):i(String(e).split(t)),n},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,n){return t.toUpperCase()+n})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:FI,global:BI,isContextDefined:jI,isSpecCompliantForm:function(e){return!!(e&&vI(e.append)&&"FormData"===e[hI]&&e[uI])},toJSONObject:e=>{const t=new WeakSet,n=e=>{if(bI(e)){if(t.has(e))return;if(SI(e))return e;if(!("toJSON"in e)){t.add(e);const i=fI(e)?[]:{};return xI(e,((e,t)=>{const r=n(e);!gI(r)&&(i[t]=r)})),t.delete(e),i}}return e};return n(e)},isAsyncFn:JI,isThenable:e=>e&&(bI(e)||vI(e))&&vI(e.then)&&vI(e.catch),setImmediate:zI,asap:eA,isIterable:e=>null!=e&&vI(e[uI])};const nA=tA.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const iA=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),rA=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function oA(e,t){return tA.isArray(e)?e.map((e=>oA(e,t))):function(e){let t=0,n=e.length;for(;t<n;){const n=e.charCodeAt(t);if(9!==n&&32!==n)break;t+=1}for(;n>t;){const t=e.charCodeAt(n-1);if(9!==t&&32!==t)break;n-=1}return 0===t&&n===e.length?e:e.slice(t,n)}(String(e).replace(t,""))}const sA=e=>oA(e,iA),aA=e=>oA(e,rA);function cA(e){const t=Object.create(null);return tA.forEach(e.toJSON(),((e,n)=>{t[n]=aA(e)})),t}const dA=Symbol("internals");function lA(e){var t;return e&&ZS(t=String(e)).call(t).toLowerCase()}function uA(e){return!1===e||null==e?e:tA.isArray(e)?e.map(uA):sA(String(e))}function hA(e,t,n,i,r){return tA.isFunction(i)?i.call(this,t,n):(r&&(t=n),tA.isString(t)?tA.isString(i)?-1!==t.indexOf(i):tA.isRegExp(i)?i.test(t):void 0:void 0)}class pA{constructor(e){e&&this.set(e)}set(e,t,n){const i=this;function r(e,t,n){const r=lA(t);if(!r)throw new Error("header name must be a non-empty string");const o=tA.findKey(i,r);(!o||void 0===i[o]||!0===n||void 0===n&&!1!==i[o])&&(i[o||t]=uA(e))}const o=(e,t)=>tA.forEach(e,((e,n)=>r(e,n,t)));if(tA.isPlainObject(e)||e instanceof this.constructor)o(e,t);else if(tA.isString(e)&&(e=ZS(e).call(e))&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(ZS(s=e).call(s)))o((e=>{const t={};let n,i,r;return e&&e.split("\n").forEach((function(e){var o,s;r=e.indexOf(":"),n=ZS(o=e.substring(0,r)).call(o).toLowerCase(),i=ZS(s=e.substring(r+1)).call(s),!n||t[n]&&nA[n]||("set-cookie"===n?t[n]?t[n].push(i):t[n]=[i]:t[n]=t[n]?t[n]+", "+i:i)})),t})(e),t);else if(tA.isObject(e)&&tA.isIterable(e)){let n,i,r={};for(const t of e){if(!tA.isArray(t))throw TypeError("Object iterator must return a key-value pair");r[i=t[0]]=(n=r[i])?tA.isArray(n)?[...n,t[1]]:[n,t[1]]:t[1]}o(r,t)}else null!=e&&r(t,e,n);var s;return this}get(e,t){if(e=lA(e)){const n=tA.findKey(this,e);if(n){const e=this[n];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=n.exec(e);)t[i[1]]=i[2];return t}(e);if(tA.isFunction(t))return t.call(this,e,n);if(tA.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=lA(e)){const n=tA.findKey(this,e);return!(!n||void 0===this[n]||t&&!hA(0,this[n],n,t))}return!1}delete(e,t){const n=this;let i=!1;function r(e){if(e=lA(e)){const r=tA.findKey(n,e);!r||t&&!hA(0,n[r],r,t)||(delete n[r],i=!0)}}return tA.isArray(e)?e.forEach(r):r(e),i}clear(e){const t=Object.keys(this);let n=t.length,i=!1;for(;n--;){const r=t[n];e&&!hA(0,this[r],r,e,!0)||(delete this[r],i=!0)}return i}normalize(e){const t=this,n={};return tA.forEach(this,((i,r)=>{var o;const s=tA.findKey(n,r);if(s)return t[s]=uA(i),void delete t[r];const a=e?function(e){return ZS(e).call(e).toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,n)=>t.toUpperCase()+n))}(r):ZS(o=String(r)).call(o);a!==r&&delete t[r],t[a]=uA(i),n[a]=!0})),this}concat(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.constructor.concat(this,...t)}toJSON(e){const t=Object.create(null);return tA.forEach(this,((n,i)=>{null!=n&&!1!==n&&(t[i]=e&&tA.isArray(n)?n.join(", "):n)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((e=>{let t=Hb(e,2);return t[0]+": "+t[1]})).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e){const t=new this(e);for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return i.forEach((e=>t.set(e))),t}static accessor(e){const t=(this[dA]=this[dA]={accessors:{}}).accessors,n=this.prototype;function i(e){const i=lA(e);t[i]||(!function(e,t){const n=tA.toCamelCase(" "+t);["get","set","has"].forEach((i=>{Object.defineProperty(e,i+n,{__proto__:null,value:function(e,n,r){return this[i].call(this,t,e,n,r)},configurable:!0})}))}(n,e),t[i]=!0)}return tA.isArray(e)?e.forEach(i):i(e),this}}pA.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),tA.reduceDescriptors(pA.prototype,((e,t)=>{let n=e.value,i=t[0].toUpperCase()+t.slice(1);return{get:()=>n,set(e){this[i]=e}}})),tA.freezeMethods(pA);var _A=pA;const EA="[REDACTED ****]";function mA(e,t){const n=new Set(t.map((e=>String(e).toLowerCase()))),i=[],r=e=>{if(null===e||"object"!=typeof e)return e;if(tA.isBuffer(e))return e;if(-1!==i.indexOf(e))return;let t;if(e instanceof _A&&(e=e.toJSON()),i.push(e),tA.isArray(e))t=[],e.forEach(((e,n)=>{const i=r(e);tA.isUndefined(i)||(t[n]=i)}));else{if(!tA.isPlainObject(e)&&function(e){if(tA.hasOwnProp(e,"toJSON"))return!0;let t=Object.getPrototypeOf(e);for(;t&&t!==Object.prototype;){if(tA.hasOwnProp(t,"toJSON"))return!0;t=Object.getPrototypeOf(t)}return!1}(e))return i.pop(),e;t=Object.create(null);for(const i of Object.entries(e)){var o=Hb(i,2);const e=o[0],s=o[1],a=n.has(e.toLowerCase())?EA:r(s);tA.isUndefined(a)||(t[e]=a)}}return i.pop(),t};return r(e)}class fA extends Error{static from(e,t,n,i,r,o){const s=new fA(e.message,t||e.code,n,i,r);return s.cause=e,s.name=e.name,null!=e.status&&null==s.status&&(s.status=e.status),o&&Object.assign(s,o),s}constructor(e,t,n,i,r){super(e),Object.defineProperty(this,"message",{__proto__:null,value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),n&&(this.config=n),i&&(this.request=i),r&&(this.response=r,this.status=r.status)}toJSON(){const e=this.config,t=e&&tA.hasOwnProp(e,"redact")?e.redact:void 0,n=tA.isArray(t)&&t.length>0?mA(e,t):tA.toJSONObject(e);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:n,code:this.code,status:this.status}}}fA.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",fA.ERR_BAD_OPTION="ERR_BAD_OPTION",fA.ECONNABORTED="ECONNABORTED",fA.ETIMEDOUT="ETIMEDOUT",fA.ECONNREFUSED="ECONNREFUSED",fA.ERR_NETWORK="ERR_NETWORK",fA.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",fA.ERR_DEPRECATED="ERR_DEPRECATED",fA.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",fA.ERR_BAD_REQUEST="ERR_BAD_REQUEST",fA.ERR_CANCELED="ERR_CANCELED",fA.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",fA.ERR_INVALID_URL="ERR_INVALID_URL",fA.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";var gA=fA;function SA(e){return tA.isPlainObject(e)||tA.isArray(e)}function TA(e){return tA.endsWith(e,"[]")?e.slice(0,-2):e}function RA(e,t,n){return e?e.concat(t).map((function(e,t){return e=TA(e),!n&&t?"["+e+"]":e})).join(n?".":""):t}const vA=tA.toFlatObject(tA,{},null,(function(e){return/^is[A-Z]/.test(e)}));function yA(e,t,n){if(!tA.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(n=tA.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!tA.isUndefined(t[e])}))).metaTokens,r=n.visitor||u,o=n.dots,s=n.indexes,a=n.Blob||"undefined"!=typeof Blob&&Blob,c=void 0===n.maxDepth?100:n.maxDepth,d=a&&tA.isSpecCompliantForm(t);if(!tA.isFunction(r))throw new TypeError("visitor must be a function");function l(e){if(null===e)return"";if(tA.isDate(e))return e.toISOString();if(tA.isBoolean(e))return e.toString();if(!d&&tA.isBlob(e))throw new gA("Blob is not supported. Use a Buffer instead.");return tA.isArrayBuffer(e)||tA.isTypedArray(e)?d&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function u(e,n,r){let a=e;if(tA.isReactNative(t)&&tA.isReactNativeBlob(e))return t.append(RA(r,n,o),l(e)),!1;if(e&&!r&&"object"==typeof e)if(tA.endsWith(n,"{}"))n=i?n:n.slice(0,-2),e=JSON.stringify(e);else if(tA.isArray(e)&&function(e){return tA.isArray(e)&&!e.some(SA)}(e)||(tA.isFileList(e)||tA.endsWith(n,"[]"))&&(a=tA.toArray(e)))return n=TA(n),a.forEach((function(e,i){!tA.isUndefined(e)&&null!==e&&t.append(!0===s?RA([n],i,o):null===s?n:n+"[]",l(e))})),!1;return!!SA(e)||(t.append(RA(r,n,o),l(e)),!1)}const h=[],p=Object.assign(vA,{defaultVisitor:u,convertValue:l,isVisitable:SA});if(!tA.isObject(e))throw new TypeError("data must be an object");return function e(n,i){let o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(!tA.isUndefined(n)){if(o>c)throw new gA("Object is too deeply nested ("+o+" levels). Max depth: "+c,gA.ERR_FORM_DATA_DEPTH_EXCEEDED);if(-1!==h.indexOf(n))throw Error("Circular reference detected in "+i.join("."));h.push(n),tA.forEach(n,(function(n,s){!0===(!(tA.isUndefined(n)||null===n)&&r.call(t,n,tA.isString(s)?ZS(s).call(s):s,i,p))&&e(n,i?i.concat(s):[s],o+1)})),h.pop()}}(e),t}function bA(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(e).replace(/[!'()~]|%20/g,(function(e){return t[e]}))}function CA(e,t){this._pairs=[],e&&yA(e,this,t)}const IA=CA.prototype;function AA(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function wA(e,t,n){if(!t)return e;const i=n&&n.encode||AA,r=tA.isFunction(n)?{serialize:n}:n,o=r&&r.serialize;let s;if(s=o?o(t,r):tA.isURLSearchParams(t)?t.toString():new CA(t,r).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}IA.append=function(e,t){this._pairs.push([e,t])},IA.toString=function(e){const t=e?function(t){return e.call(this,t,bA)}:bA;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var OA=class{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){tA.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},NA={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},DA={exports:{}},PA=Nn,LA=w,kA=Qt.f;PA({target:"Object",stat:!0,forced:Object.defineProperty!==kA,sham:!LA},{defineProperty:kA});var MA=$.Object,UA=DA.exports=function(e,t,n){return MA.defineProperty(e,t,n)};MA.defineProperty.sham&&(UA.sham=!0);var VA=n(DA.exports),xA=n(HT.f("iterator"));function FA(e){return FA="function"==typeof db&&"symbol"==typeof xA?function(e){return typeof e}:function(e){return e&&"function"==typeof db&&e.constructor===db&&e!==db.prototype?"symbol":typeof e},FA(e)}var BA=n(HT.f("toPrimitive"));function jA(e){var t=function(e,t){if("object"!=FA(e)||!e)return e;var n=e[BA];if(void 0!==n){var i=n.call(e,t||"default");if("object"!=FA(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==FA(t)?t:t+""}function GA(e,t,n){return(t=jA(t))in e?VA(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var WA=n(kE),KA={isBrowser:!0,classes:{URLSearchParams:void 0!==WA?WA:CA,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const HA="undefined"!=typeof window&&"undefined"!=typeof document,YA="object"==typeof navigator&&navigator||void 0,XA=HA&&(!YA||["ReactNative","NativeScript","NS"].indexOf(YA.product)<0),JA="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,zA=HA&&window.location.href||"http://localhost";function ZA(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function qA(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ZA(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ZA(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var QA=qA(qA({},Object.freeze({__proto__:null,hasBrowserEnv:HA,hasStandardBrowserEnv:XA,hasStandardBrowserWebWorkerEnv:JA,navigator:YA,origin:zA})),KA);function $A(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function ew(e,t){return yA(e,new QA.classes.URLSearchParams,function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?$A(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$A(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({visitor:function(e,t,n,i){return QA.isNode&&tA.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}var tw=Xh.charAt,nw=D,iw=rn,rw=I,ow=R,sw=/./.exec,aw=TypeError,cw=Nn,dw=D,lw=b,uw=$a,hw=fc,pw=X,_w=Gn,Ew=vi,mw=rn,fw=Q,gw=R,Sw=ci,Tw=nC,Rw=Le,vw=i,yw=dd,bw=function(e,t,n){return t+(n&&tw(e,t).length||1)},Cw=function(e,t){var n=e.exec;if(rw(n)){var i=nw(n,e,t);return null!==i&&iw(i),i}if("RegExp"===ow(e))return nw(sw,e,t);throw new aw("RegExp#exec called on incompatible receiver")},Iw=Sa,Aw=pt("matchAll"),ww="RegExp String",Ow=ww+" Iterator",Nw=Iw.set,Dw=Iw.getterFor(Ow),Pw=TypeError,Lw=lw("".indexOf),kw=lw("".matchAll),Mw=!!kw&&!vw((function(){kw("a",/./)})),Uw=uw((function(e,t,n,i){Nw(this,{type:Ow,regexp:e,string:t,global:n,unicode:i,done:!1})}),ww,(function(){var e=Dw(this);if(e.done)return hw(void 0,!0);var t=e.regexp,n=e.string,i=Cw(t,n);return null===i?(e.done=!0,hw(void 0,!0)):e.global?(""===Ew(i[0])&&(t.lastIndex=bw(n,_w(t.lastIndex),e.unicode)),hw(i,!1)):(e.done=!0,hw(i,!1))})),Vw=function(e){var t,n,i,r=mw(this),o=Ew(e),s=yw(r,RegExp),a=Ew(Tw(r));return t=new s(s===RegExp?r.source:r,a),n=!!~Lw(a,"g"),i=!!~Lw(a,"u")||!!~Lw(a,"v"),t.lastIndex=_w(r.lastIndex),new Uw(t,o,n,i)};cw({target:"String",proto:!0,forced:Mw},{matchAll:function(e){var t,n,i,r,o=pw(this);if(fw(e)){if(Sw(e)&&(t=Ew(pw(Tw(e))),!~Lw(t,"g")))throw new Pw("`.matchAll` does not allow non-global regexes");if(Mw)return kw(o,e);if(void 0===(i=Rw(e,Aw))&&"RegExp"===gw(e)&&(i=Vw),i)return dw(i,e,o)}else if(Mw)return kw(o,e);return n=Ew(o),r=new RegExp(e,"g"),dw(Vw,r,n)}});var xw=ii("String","matchAll"),Fw=l,Bw=xw,jw=String.prototype,Gw=function(e){var t=e.matchAll;return"string"==typeof e||e===jw||Fw(jw,e)&&t===jw.matchAll?Bw:t},Ww=n(Gw);function Kw(e){function t(e,n,i,r){let o=e[r++];if("__proto__"===o)return!0;const s=Number.isFinite(+o),a=r>=e.length;if(o=!o&&tA.isArray(i)?i.length:o,a)return tA.hasOwnProp(i,o)?i[o]=tA.isArray(i[o])?i[o].concat(n):[i[o],n]:i[o]=n,!s;tA.hasOwnProp(i,o)&&tA.isObject(i[o])||(i[o]=[]);return t(e,n,i[o],r)&&tA.isArray(i[o])&&(i[o]=function(e){const t={},n=Object.keys(e);let i;const r=n.length;let o;for(i=0;i<r;i++)o=n[i],t[o]=e[o];return t}(i[o])),!s}if(tA.isFormData(e)&&tA.isFunction(e.entries)){const n={};return tA.forEachEntry(e,((e,i)=>{t(function(e){return Ww(tA).call(tA,/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),i,n,0)})),n}return null}const Hw=(e,t)=>null!=e&&tA.hasOwnProp(e,t)?e[t]:void 0;const Yw={transitional:NA,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=tA.isObject(e);r&&tA.isHTMLForm(e)&&(e=new FormData(e));if(tA.isFormData(e))return i?JSON.stringify(Kw(e)):e;if(tA.isArrayBuffer(e)||tA.isBuffer(e)||tA.isStream(e)||tA.isFile(e)||tA.isBlob(e)||tA.isReadableStream(e))return e;if(tA.isArrayBufferView(e))return e.buffer;if(tA.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let o;if(r){const t=Hw(this,"formSerializer");if(n.indexOf("application/x-www-form-urlencoded")>-1)return ew(e,t).toString();if((o=tA.isFileList(e))||n.indexOf("multipart/form-data")>-1){const n=Hw(this,"env"),i=n&&n.FormData;return yA(o?{"files[]":e}:e,i&&new i,t)}}return r||i?(t.setContentType("application/json",!1),function(e,t,n){if(tA.isString(e))try{return(t||JSON.parse)(e),ZS(tA).call(tA,e)}catch(e){if("SyntaxError"!==e.name)throw e}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=Hw(this,"transitional")||Yw.transitional,n=t&&t.forcedJSONParsing,i=Hw(this,"responseType"),r="json"===i;if(tA.isResponse(e)||tA.isReadableStream(e))return e;if(e&&tA.isString(e)&&(n&&!i||r)){const n=!(t&&t.silentJSONParsing)&&r;try{return JSON.parse(e,Hw(this,"parseReviver"))}catch(e){if(n){if("SyntaxError"===e.name)throw gA.from(e,gA.ERR_BAD_RESPONSE,this,null,Hw(this,"response"));throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:QA.classes.FormData,Blob:QA.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};tA.forEach(["delete","get","head","post","put","patch","query"],(e=>{Yw.headers[e]={}}));var Xw=Yw;function Jw(e,t){const n=this||Xw,i=t||n,r=_A.from(i.headers);let o=i.data;return tA.forEach(e,(function(e){o=e.call(n,o,r.normalize(),t?t.status:void 0)})),r.normalize(),o}function zw(e){return!(!e||!e.__CANCEL__)}var Zw=class extends gA{constructor(e,t,n){super(null==e?"canceled":e,gA.ERR_CANCELED,t,n),this.name="CanceledError",this.__CANCEL__=!0}};function qw(e,t,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(new gA("Request failed with status code "+n.status,n.status>=400&&n.status<500?gA.ERR_BAD_REQUEST:gA.ERR_BAD_RESPONSE,n.config,n.request,n)):e(n)}const Qw=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3,i=0;const r=function(e,t){e=e||10;const n=new Array(e),i=new Array(e);let r,o=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=i[s];r||(r=c),n[o]=a,i[o]=c;let l=s,u=0;for(;l!==o;)u+=n[l++],l%=e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-r<t)return;const h=d&&c-d;return h?Math.round(1e3*u/h):void 0}}(50,250);return function(e,t){let n,i,r=0,o=1e3/t;const s=function(t){let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();r=o,n=null,i&&(clearTimeout(i),i=null),e(...t)};return[function(){const e=Date.now(),t=e-r;for(var a=arguments.length,c=new Array(a),d=0;d<a;d++)c[d]=arguments[d];t>=o?s(c,e):(n=c,i||(i=setTimeout((()=>{i=null,s(n)}),o-t)))},()=>n&&s(n)]}((n=>{if(!n||"number"!=typeof n.loaded)return;const o=n.loaded,s=n.lengthComputable?n.total:void 0,a=null!=s?Math.min(o,s):o,c=Math.max(0,a-i),d=r(c);i=Math.max(i,a);e({loaded:a,total:s,progress:s?a/s:void 0,bytes:c,rate:d||void 0,estimated:d&&s?(s-a)/d:void 0,event:n,lengthComputable:null!=s,[t?"download":"upload"]:!0})}),n)},$w=(e,t)=>{const n=null!=e;return[i=>t[0]({lengthComputable:n,total:e,loaded:i}),t[1]]},eO=e=>function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return tA.asap((()=>e(...n)))};var tO=QA.hasStandardBrowserEnv?((e,t)=>n=>(n=new Fg(n,QA.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new Fg(QA.origin),QA.navigator&&/(msie|trident)/i.test(QA.navigator.userAgent)):()=>!0,nO=QA.hasStandardBrowserEnv?{write(e,t,n,i,r,o,s){if("undefined"==typeof document)return;const a=["".concat(e,"=").concat(encodeURIComponent(t))];tA.isNumber(n)&&a.push("expires=".concat(new Date(n).toUTCString())),tA.isString(i)&&a.push("path=".concat(i)),tA.isString(r)&&a.push("domain=".concat(r)),!0===o&&a.push("secure"),tA.isString(s)&&a.push("SameSite=".concat(s)),document.cookie=a.join("; ")},read(e){if("undefined"==typeof document)return null;const t=document.cookie.split(";");for(let n=0;n<t.length;n++){const i=t[n].replace(/^\s+/,""),r=i.indexOf("=");if(-1!==r&&i.slice(0,r)===e)return decodeURIComponent(i.slice(r+1))}return null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};function iO(e,t,n){let i=!function(e){return"string"==typeof e&&/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t);return e&&(i||!1===n)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}function rO(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function oO(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?rO(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):rO(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const sO=e=>e instanceof _A?oO({},e):e;function aO(e,t){t=t||{};const n=Object.create(null);function i(e,t,n,i){return tA.isPlainObject(e)&&tA.isPlainObject(t)?tA.merge.call({caseless:i},e,t):tA.isPlainObject(t)?tA.merge({},t):tA.isArray(t)?t.slice():t}function r(e,t,n,r){return tA.isUndefined(t)?tA.isUndefined(e)?void 0:i(void 0,e,0,r):i(e,t,0,r)}function o(e,t){if(!tA.isUndefined(t))return i(void 0,t)}function s(e,t){return tA.isUndefined(t)?tA.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function a(n,r,o){return tA.hasOwnProp(t,o)?i(n,r):tA.hasOwnProp(e,o)?i(void 0,n):void 0}Object.defineProperty(n,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});const c={url:o,method:o,data:o,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,allowedSocketPaths:s,responseEncoding:s,validateStatus:a,headers:(e,t,n)=>r(sO(e),sO(t),0,!0)};return tA.forEach(Object.keys(oO(oO({},e),t)),(function(i){if("__proto__"===i||"constructor"===i||"prototype"===i)return;const o=tA.hasOwnProp(c,i)?c[i]:r,s=o(tA.hasOwnProp(e,i)?e[i]:void 0,tA.hasOwnProp(t,i)?t[i]:void 0,i);tA.isUndefined(s)&&o!==a||(n[i]=s)})),n}const cO=["content-type","content-length"];var dO=e=>{const t=aO({},e),n=e=>tA.hasOwnProp(t,e)?t[e]:void 0,i=n("data");let r=n("withXSRFToken");const o=n("xsrfHeaderName"),s=n("xsrfCookieName");let a=n("headers");const c=n("auth"),d=n("baseURL"),l=n("allowAbsoluteUrls"),u=n("url");var h;if(t.headers=a=_A.from(a),t.url=wA(iO(d,u,l),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?(h=c.password,encodeURIComponent(h).replace(/%([0-9A-F]{2})/gi,((e,t)=>String.fromCharCode(parseInt(t,16))))):""))),tA.isFormData(i)&&(QA.hasStandardBrowserEnv||QA.hasStandardBrowserWebWorkerEnv?a.setContentType(void 0):tA.isFunction(i.getHeaders)&&function(e,t,n){"content-only"===n?Object.entries(t).forEach((t=>{let n=Hb(t,2),i=n[0],r=n[1];Vi(cO).call(cO,i.toLowerCase())&&e.set(i,r)})):e.set(t)}(a,i.getHeaders(),n("formDataHeaderPolicy"))),QA.hasStandardBrowserEnv){tA.isFunction(r)&&(r=r(t));if(!0===r||null==r&&tO(t.url)){const e=o&&s&&nO.read(s);e&&a.set(o,e)}}return t};var lO="undefined"!=typeof XMLHttpRequest&&function(e){return new dp((function(t,n){var i;const r=dO(e);let o=r.data;const s=_A.from(r.headers).normalize();let a,c,d,l,u,h=r.responseType,p=r.onUploadProgress,_=r.onDownloadProgress;function E(){l&&l(),u&&u(),r.cancelToken&&r.cancelToken.unsubscribe(a),r.signal&&r.signal.removeEventListener("abort",a)}let m=new XMLHttpRequest;function f(){if(!m)return;const i=_A.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());qw((function(e){t(e),E()}),(function(e){n(e),E()}),{data:h&&"text"!==h&&"json"!==h?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:i,config:e,request:m}),m=null}if(m.open(r.method.toUpperCase(),r.url,!0),m.timeout=r.timeout,"onloadend"in m?m.onloadend=f:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&m.responseURL.startsWith("file:"))&&setTimeout(f)},m.onabort=function(){m&&(n(new gA("Request aborted",gA.ECONNABORTED,e,m)),E(),m=null)},m.onerror=function(t){const i=t&&t.message?t.message:"Network Error",r=new gA(i,gA.ERR_NETWORK,e,m);r.event=t||null,n(r),E(),m=null},m.ontimeout=function(){let t=r.timeout?"timeout of "+r.timeout+"ms exceeded":"timeout exceeded";const i=r.transitional||NA;r.timeoutErrorMessage&&(t=r.timeoutErrorMessage),n(new gA(t,i.clarifyTimeoutError?gA.ETIMEDOUT:gA.ECONNABORTED,e,m)),E(),m=null},void 0===o&&s.setContentType(null),"setRequestHeader"in m&&tA.forEach(cA(s),(function(e,t){m.setRequestHeader(t,e)})),tA.isUndefined(r.withCredentials)||(m.withCredentials=!!r.withCredentials),h&&"json"!==h&&(m.responseType=r.responseType),_){var g=Hb(Qw(_,!0),2);d=g[0],u=g[1],m.addEventListener("progress",d)}if(p&&m.upload){var S=Hb(Qw(p),2);c=S[0],l=S[1],m.upload.addEventListener("progress",c),m.upload.addEventListener("loadend",l)}(r.cancelToken||r.signal)&&(a=t=>{m&&(n(!t||t.type?new Zw(null,e,m):t),m.abort(),E(),m=null)},r.cancelToken&&r.cancelToken.subscribe(a),r.signal&&(r.signal.aborted?a():r.signal.addEventListener("abort",a)));const T=function(e){const t=/^([-+\w]{1,25}):(?:\/\/)?/.exec(e);return t&&t[1]||""}(r.url);!T||Vi(i=QA.protocols).call(i,T)?m.send(o||null):n(new gA("Unsupported protocol "+T+":",gA.ERR_BAD_REQUEST,e))}))};var uO=(e,t)=>{if(e=e?e.filter(Boolean):[],!t&&!e.length)return;const n=new AbortController;let i=!1;const r=function(e){if(!i){i=!0,s();const t=e instanceof Error?e:this.reason;n.abort(t instanceof gA?t:new Zw(t instanceof Error?t.message:t))}};let o=t&&setTimeout((()=>{o=null,r(new gA("timeout of ".concat(t,"ms exceeded"),gA.ETIMEDOUT))}),t);const s=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(r):e.removeEventListener("abort",r)})),e=null)};e.forEach((e=>e.addEventListener("abort",r)));const a=n.signal;return a.unsubscribe=()=>tA.asap(s),a},hO=n(cp),pO=HT.f("asyncIterator"),_O=n(pO);function EO(e,t){this.v=e,this.k=t}function mO(e){return function(){return new fO(e.apply(this,arguments))}}function fO(e){var t,n;function i(t,n){try{var o=e[t](n),s=o.value,a=s instanceof EO;hO.resolve(a?s.v:s).then((function(n){if(a){var c="return"===t&&s.k?t:"next";if(!s.k||n.done)return i(c,n);n=e[c](n).value}r(!!o.done,n)}),(function(e){i("throw",e)}))}catch(e){r(2,e)}}function r(e,r){2===e?t.reject(r):t.resolve({value:r,done:e}),(t=t.next)?i(t.key,t.arg):n=null}this._invoke=function(e,r){return new hO((function(o,s){var a={key:e,arg:r,resolve:o,reject:s,next:null};n?n=n.next=a:(t=n=a,i(e,r))}))},"function"!=typeof e.return&&(this.return=void 0)}function gO(e){return new EO(e,0)}function SO(e){var t={},n=!1;function i(t,i){return n=!0,i=new hO((function(n){n(e[t](i))})),{done:!1,value:new EO(i,1)}}return t[void 0!==db&&xA||"@@iterator"]=function(){return this},t.next=function(e){return n?(n=!1,e):i("next",e)},"function"==typeof e.throw&&(t.throw=function(e){if(n)throw n=!1,e;return i("throw",e)}),"function"==typeof e.return&&(t.return=function(e){return n?(n=!1,e):i("return",e)}),t}fO.prototype["function"==typeof db&&_O||"@@asyncIterator"]=function(){return this},fO.prototype.next=function(e){return this._invoke("next",e)},fO.prototype.throw=function(e){return this._invoke("throw",e)},fO.prototype.return=function(e){return this._invoke("return",e)};var TO=n(pO);function RO(e){var t,n,i,r=2;for("undefined"!=typeof Symbol&&(n=TO,i=Symbol.iterator);r--;){if(n&&null!=(t=e[n]))return t.call(e);if(i&&null!=(t=e[i]))return new vO(t.call(e));n="@@asyncIterator",i="@@iterator"}throw new TypeError("Object is not async iterable")}function vO(e){function t(e){if(Object(e)!==e)return dp.reject(new TypeError(e+" is not an object."));var t=e.done;return dp.resolve(e.value).then((function(e){return{value:e,done:t}}))}return vO=function(e){this.s=e,this.n=e.next},vO.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return void 0===n?dp.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return void 0===n?dp.reject(e):t(n.apply(this.s,arguments))}},new vO(e)}const yO=function*(e,t){let n=e.byteLength;if(!t||n<t)return void(yield e);let i,r=0;for(;r<n;)i=r+t,yield e.slice(r,i),r=i},bO=function(){var e=mO((function*(e,t){var n,i=!1,r=!1;try{for(var o,s=RO(CO(e));i=!(o=yield gO(s.next())).done;i=!1){const e=o.value;yield*SO(RO(yO(e,t)))}}catch(e){r=!0,n=e}finally{try{i&&null!=s.return&&(yield gO(s.return()))}finally{if(r)throw n}}}));return function(t,n){return e.apply(this,arguments)}}(),CO=function(){var e=mO((function*(e){if(e[TO])return void(yield*SO(RO(e)));const t=e.getReader();try{for(;;){const e=yield gO(t.read()),n=e.done,i=e.value;if(n)break;yield i}}finally{yield gO(t.cancel())}}));return function(t){return e.apply(this,arguments)}}(),IO=(e,t,n,i)=>{const r=bO(e,t);let o,s=0,a=e=>{o||(o=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const t=await r.next(),i=t.done,o=t.value;if(i)return a(),void e.close();let c=o.byteLength;if(n){let e=s+=c;n(e)}e.enqueue(new Uint8Array(o))}catch(e){throw a(e),e}},cancel:e=>(a(e),r.return())},{highWaterMark:2})};const AO="1.16.1";function wO(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function OO(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?wO(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):wO(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const NO=tA.isFunction,DO=function(e){try{for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return!!e(...n)}catch(e){return!1}},PO=e=>{const t=void 0!==tA.global&&null!==tA.global?tA.global:VC,n=t.ReadableStream,i=t.TextEncoder,r=e=tA.merge.call({skipUndefined:!0},{Request:t.Request,Response:t.Response},e),o=r.fetch,s=r.Request,a=r.Response,c=o?NO(o):"function"==typeof fetch,d=NO(s),l=NO(a);if(!c)return!1;const u=c&&NO(n),h=c&&("function"==typeof i?(p=new i,e=>p.encode(e)):async e=>new Uint8Array(await new s(e).arrayBuffer()));var p;const _=d&&u&&DO((()=>{let e=!1;const t=new s(QA.origin,{body:new n,method:"POST",get duplex(){return e=!0,"half"}}),i=t.headers.has("Content-Type");return null!=t.body&&t.body.cancel(),e&&!i})),E=l&&u&&DO((()=>tA.isReadableStream(new a("").body))),m={stream:E&&(e=>e.body)};c&&["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!m[e]&&(m[e]=(t,n)=>{let i=t&&t[e];if(i)return i.call(t);throw new gA("Response type '".concat(e,"' is not supported"),gA.ERR_NOT_SUPPORT,n)})}));const f=async(e,t)=>{const n=tA.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(tA.isBlob(e))return e.size;if(tA.isSpecCompliantForm(e)){const t=new s(QA.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return tA.isArrayBufferView(e)||tA.isArrayBuffer(e)?e.byteLength:(tA.isURLSearchParams(e)&&(e+=""),tA.isString(e)?(await h(e)).byteLength:void 0)})(t):n};return async e=>{let t=dO(e),n=t.url,r=t.method,c=t.data,l=t.signal,u=t.cancelToken,h=t.timeout,p=t.onDownloadProgress,g=t.onUploadProgress,S=t.responseType,T=t.headers,R=t.withCredentials,v=void 0===R?"same-origin":R,y=t.fetchOptions,b=t.maxContentLength,C=t.maxBodyLength;const I=tA.isNumber(b)&&b>-1,A=tA.isNumber(C)&&C>-1;let w=o||fetch;S=S?(S+"").toLowerCase():"text";let O=uO([l,u&&u.toAbortSignal()],h),N=null;const D=O&&O.unsubscribe&&(()=>{O.unsubscribe()});let P;try{if(I&&"string"==typeof n&&n.startsWith("data:")){const t=function(e){if(!e||"string"!=typeof e)return 0;if(!e.startsWith("data:"))return 0;const t=e.indexOf(",");if(t<0)return 0;const n=e.slice(5,t),i=e.slice(t+1);if(/;base64/i.test(n)){let e=i.length;const t=i.length;for(let n=0;n<t;n++)if(37===i.charCodeAt(n)&&n+2<t){const t=i.charCodeAt(n+1),r=i.charCodeAt(n+2);(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102)&&(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102)&&(e-=2,n+=2)}let n=0,r=t-1;const o=e=>e>=2&&37===i.charCodeAt(e-2)&&51===i.charCodeAt(e-1)&&(68===i.charCodeAt(e)||100===i.charCodeAt(e));r>=0&&(61===i.charCodeAt(r)?(n++,r--):o(r)&&(n++,r-=3)),1===n&&r>=0&&(61===i.charCodeAt(r)||o(r))&&n++;const s=3*Math.floor(e/4)-(n||0);return s>0?s:0}if("undefined"!=typeof Buffer&&"function"==typeof Buffer.byteLength)return Buffer.byteLength(i,"utf8");let r=0;for(let e=0,t=i.length;e<t;e++){const n=i.charCodeAt(e);if(n<128)r+=1;else if(n<2048)r+=2;else if(n>=55296&&n<=56319&&e+1<t){const t=i.charCodeAt(e+1);t>=56320&&t<=57343?(r+=4,e++):r+=3}else r+=3}return r}(n);if(t>b)throw new gA("maxContentLength size of "+b+" exceeded",gA.ERR_BAD_RESPONSE,e,N)}if(A&&"get"!==r&&"head"!==r){const t=await f(T,c);if("number"==typeof t&&isFinite(t)&&t>C)throw new gA("Request body larger than maxBodyLength limit",gA.ERR_BAD_REQUEST,e,N)}if(g&&_&&"get"!==r&&"head"!==r&&0!==(P=await f(T,c))){let e,t=new s(n,{method:"POST",body:c,duplex:"half"});if(tA.isFormData(c)&&(e=t.headers.get("content-type"))&&T.setContentType(e),t.body){const e=Hb($w(P,Qw(eO(g))),2),n=e[0],i=e[1];c=IO(t.body,65536,n,i)}}tA.isString(v)||(v=v?"include":"omit");const t=d&&"credentials"in s.prototype;if(tA.isFormData(c)){const e=T.getContentType();e&&/^multipart\/form-data/i.test(e)&&!/boundary=/i.test(e)&&T.delete("content-type")}T.set("User-Agent","axios/"+AO,!1);const o=OO(OO({},y),{},{signal:O,method:r.toUpperCase(),headers:cA(T.normalize()),body:c,duplex:"half",credentials:t?v:void 0});N=d&&new s(n,o);let l=await(d?w(N,y):w(n,o));if(I){const t=tA.toFiniteNumber(l.headers.get("content-length"));if(null!=t&&t>b)throw new gA("maxContentLength size of "+b+" exceeded",gA.ERR_BAD_RESPONSE,e,N)}const u=E&&("stream"===S||"response"===S);if(E&&l.body&&(p||I||u&&D)){const t={};["status","statusText","headers"].forEach((e=>{t[e]=l[e]}));const n=tA.toFiniteNumber(l.headers.get("content-length")),i=Hb(p&&$w(n,Qw(eO(p),!0))||[],2),r=i[0],o=i[1];let s=0;const c=t=>{if(I&&(s=t,s>b))throw new gA("maxContentLength size of "+b+" exceeded",gA.ERR_BAD_RESPONSE,e,N);r&&r(t)};l=new a(IO(l.body,65536,c,(()=>{o&&o(),D&&D()})),t)}S=S||"text";let h=await m[tA.findKey(m,S)||"text"](l,e);if(I&&!E&&!u){let t;if(null!=h&&("number"==typeof h.byteLength?t=h.byteLength:"number"==typeof h.size?t=h.size:"string"==typeof h&&(t="function"==typeof i?(new i).encode(h).byteLength:h.length)),"number"==typeof t&&t>b)throw new gA("maxContentLength size of "+b+" exceeded",gA.ERR_BAD_RESPONSE,e,N)}return!u&&D&&D(),await new dp(((t,n)=>{qw(t,n,{data:h,headers:_A.from(l.headers),status:l.status,statusText:l.statusText,config:e,request:N})}))}catch(t){if(D&&D(),O&&O.aborted&&O.reason instanceof gA){const n=O.reason;throw n.config=e,N&&(n.request=N),t!==n&&(n.cause=t),n}if(t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new gA("Network Error",gA.ERR_NETWORK,e,N,t&&t.response),{cause:t.cause||t});throw gA.from(t,t&&t.code,e,N,t&&t.response)}}},LO=new Map,kO=e=>{let t=e&&e.env||{};const n=t.fetch,i=[t.Request,t.Response,n];let r,o,s=i.length,a=LO;for(;s--;)r=i[s],o=a.get(r),void 0===o&&a.set(r,o=s?new Map:PO(t)),a=o;return o};kO();const MO={http:null,xhr:lO,fetch:{get:kO}};tA.forEach(MO,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{__proto__:null,value:t})}catch(e){}Object.defineProperty(e,"adapterName",{__proto__:null,value:t})}}));const UO=e=>"- ".concat(e),VO=e=>tA.isFunction(e)||null===e||!1===e;var xO={getAdapter:function(e,t){const n=(e=tA.isArray(e)?e:[e]).length;let i,r;const o={};for(let s=0;s<n;s++){let n;if(i=e[s],r=i,!VO(i)&&(r=MO[(n=String(i)).toLowerCase()],void 0===r))throw new gA("Unknown adapter '".concat(n,"'"));if(r&&(tA.isFunction(r)||(r=r.get(t))))break;o[n||"#"+s]=r}if(!r){const e=Object.entries(o).map((e=>{let t=Hb(e,2),n=t[0],i=t[1];return"adapter ".concat(n," ")+(!1===i?"is not supported by the environment":"is not available in the build")}));let t=n?e.length>1?"since :\n"+e.map(UO).join("\n"):" "+UO(e[0]):"as no adapter specified";throw new gA("There is no suitable adapter to dispatch the request "+t,"ERR_NOT_SUPPORT")}return r},adapters:MO};function FO(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Zw(null,e)}function BO(e){FO(e),e.headers=_A.from(e.headers),e.data=Jw.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return xO.getAdapter(e.adapter||Xw.adapter,e)(e).then((function(t){FO(e),e.response=t;try{t.data=Jw.call(e,e.transformResponse,t)}finally{delete e.response}return t.headers=_A.from(t.headers),t}),(function(t){if(!zw(t)&&(FO(e),t&&t.response)){e.response=t.response;try{t.response.data=Jw.call(e,e.transformResponse,t.response)}finally{delete e.response}t.response.headers=_A.from(t.response.headers)}return dp.reject(t)}))}const jO={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{jO[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}}));const GO={};jO.transitional=function(e,t,n){function i(e,t){return"[Axios v"+AO+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,r,o)=>{if(!1===e)throw new gA(i(r," has been removed"+(t?" in "+t:"")),gA.ERR_DEPRECATED);return t&&!GO[r]&&(GO[r]=!0,console.warn(i(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,r,o)}},jO.spelling=function(e){return(t,n)=>(console.warn("".concat(n," is likely a misspelling of ").concat(e)),!0)};var WO={assertOptions:function(e,t,n){if("object"!=typeof e)throw new gA("options must be an object",gA.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let r=i.length;for(;r-- >0;){const o=i[r],s=Object.prototype.hasOwnProperty.call(t,o)?t[o]:void 0;if(s){const t=e[o],n=void 0===t||s(t,o,e);if(!0!==n)throw new gA("option "+o+" must be "+n,gA.ERR_BAD_OPTION_VALUE)}else if(!0!==n)throw new gA("Unknown option "+o,gA.ERR_BAD_OPTION)}},validators:jO};const KO=WO.validators;let HO=class{constructor(e){this.defaults=e||{},this.interceptors={request:new OA,response:new OA}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const n=(()=>{if(!t.stack)return"";const e=t.stack.indexOf("\n");return-1===e?"":t.stack.slice(e+1)})();try{if(e.stack){if(n){const t=n.indexOf("\n"),i=-1===t?-1:n.indexOf("\n",t+1),r=-1===i?"":n.slice(i+1);String(e.stack).endsWith(r)||(e.stack+="\n"+n)}}else e.stack=n}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{};const n=t=aO(this.defaults,t),i=n.transitional,r=n.paramsSerializer,o=n.headers;void 0!==i&&WO.assertOptions(i,{silentJSONParsing:KO.transitional(KO.boolean),forcedJSONParsing:KO.transitional(KO.boolean),clarifyTimeoutError:KO.transitional(KO.boolean),legacyInterceptorReqResOrdering:KO.transitional(KO.boolean)},!1),null!=r&&(tA.isFunction(r)?t.paramsSerializer={serialize:r}:WO.assertOptions(r,{encode:KO.function,serialize:KO.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),WO.assertOptions(t,{baseUrl:KO.spelling("baseURL"),withXsrfToken:KO.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=o&&tA.merge(o.common,o[t.method]);o&&tA.forEach(["delete","get","head","post","put","patch","query","common"],(e=>{delete o[e]})),t.headers=_A.concat(s,o);const a=[];let c=!0;this.interceptors.request.forEach((function(e){if("function"==typeof e.runWhen&&!1===e.runWhen(t))return;c=c&&e.synchronous;const n=t.transitional||NA;n&&n.legacyInterceptorReqResOrdering?a.unshift(e.fulfilled,e.rejected):a.push(e.fulfilled,e.rejected)}));const d=[];let l;this.interceptors.response.forEach((function(e){d.push(e.fulfilled,e.rejected)}));let u,h=0;if(!c){const e=[BO.bind(this),void 0];for(e.unshift(...a),e.push(...d),u=e.length,l=dp.resolve(t);h<u;)l=l.then(e[h++],e[h++]);return l}u=a.length;let p=t;for(;h<u;){const e=a[h++],t=a[h++];try{p=e(p)}catch(e){t.call(this,e);break}}try{l=BO.call(this,p)}catch(e){return dp.reject(e)}for(h=0,u=d.length;h<u;)l=l.then(d[h++],d[h++]);return l}getUri(e){return wA(iO((e=aO(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};tA.forEach(["delete","get","head","options"],(function(e){HO.prototype[e]=function(t,n){return this.request(aO(n||{},{method:e,url:t,data:(n||{}).data}))}})),tA.forEach(["post","put","patch","query"],(function(e){function t(t){return function(n,i,r){return this.request(aO(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:i}))}}HO.prototype[e]=t(),"query"!==e&&(HO.prototype[e+"Form"]=t(!0))}));var YO=HO;class XO{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new dp((function(e){t=e}));const n=this;this.promise.then((e=>{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null})),this.promise.then=e=>{let t;const i=new dp((e=>{n.subscribe(e),t=e})).then(e);return i.cancel=function(){n.unsubscribe(t)},i},e((function(e,i,r){n.reason||(n.reason=new Zw(e,i,r),t(n.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;const t=new XO((function(t){e=t}));return{token:t,cancel:e}}}var JO=XO;const zO={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(zO).forEach((e=>{let t=Hb(e,2),n=t[0],i=t[1];zO[i]=n}));var ZO=zO;const qO=function e(t){const n=new YO(t),i=cI(YO.prototype.request,n);return tA.extend(i,YO.prototype,n,{allOwnKeys:!0}),tA.extend(i,n,null,{allOwnKeys:!0}),i.create=function(n){return e(aO(t,n))},i}(Xw);qO.Axios=YO,qO.CanceledError=Zw,qO.CancelToken=JO,qO.isCancel=zw,qO.VERSION=AO,qO.toFormData=yA,qO.AxiosError=gA,qO.Cancel=qO.CanceledError,qO.all=function(e){return dp.all(e)},qO.spread=function(e){return function(t){return e.apply(null,t)}},qO.isAxiosError=function(e){return tA.isObject(e)&&!0===e.isAxiosError},qO.mergeConfig=aO,qO.AxiosHeaders=_A,qO.formToJSON=e=>Kw(tA.isHTMLForm(e)?new FormData(e):e),qO.getAdapter=xO.getAdapter,qO.HttpStatusCode=ZO,qO.default=qO;var QO=qO;QO.Axios,QO.AxiosError,QO.CanceledError,QO.isCancel,QO.CancelToken,QO.VERSION,QO.all,QO.Cancel,QO.isAxiosError,QO.spread,QO.toFormData,QO.AxiosHeaders,QO.HttpStatusCode,QO.formToJSON,QO.getAdapter,QO.mergeConfig,QO.create;const $O=()=>{};function eN(){const e={promise:void 0,isResolved:!1,isRejected:!1,isFinished:!1,resolve:void 0,reject:void 0,cancel:$O};return e.promise=new dp(((t,n)=>{e.resolve=n=>{e.isFinished||(e.isResolved=!0,e.isFinished=!0,t(n),e.value=n)},e.reject=t=>{e.isFinished||(e.isRejected=!0,e.isFinished=!0,n(t))}})),e}const tN=new Map,nN=new Map,iN=new Map;let rN=function(e){return e.WIN_10="Windows 10",e.WIN_81="Windows 8.1",e.WIN_8="Windows 8",e.WIN_7="Windows 7",e.WIN_VISTA="Windows Vista",e.WIN_SERVER_2003="Windows Server 2003",e.WIN_XP="Windows XP",e.WIN_2000="Windows 2000",e.ANDROID="Android",e.HARMONY_OS="HarmonyOS",e.OPEN_BSD="Open BSD",e.SUN_OS="Sun OS",e.LINUX="Linux",e.IOS="iOS",e.MAC_OS="Mac OS",e.CHROMIUM_OS="Chromium OS",e.QNX="QNX",e.UNIX="UNIX",e.BEOS="BeOS",e.OS_2="OS/2",e.SEARCH_BOT="Search Bot",e}({}),oN=function(e){return e.CHROME="Chrome",e.SAFARI="Safari",e.EDGE="Edge",e.FIREFOX="Firefox",e.OPERA="OPR",e.QQ="QQBrowser",e.WECHAT="MicroMessenger",e}({});const sN=new FC;let aN=sN.getResult(),cN=null;function dN(e){if(!cN){e&&sN.setUA(e),aN=sN.getResult();const t=function(e){if("Blink"===e.engine.name&&"WeChat"!==e.browser.name)return oN.CHROME;switch(e.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return oN.CHROME;case"Safari":case"Mobile Safari":return oN.SAFARI;case"Edge":return oN.EDGE;case"Firefox":return oN.FIREFOX;case"QQ":case"QQBrowser":return oN.QQ;case"Opera":return oN.OPERA;case"WeChat":return oN.WECHAT;default:return e.browser.name||""}}(aN),n=lN(aN),i=function(e){return"Windows"===e.os.name?e.os.version?e.os.name+" "+e.os.version:e.os.name:e.os.name||""}(aN),r=aN.os.version,o=lN(aN,!1),s=aN.device.type;if(!(t&&n&&i&&r))return{name:t,version:n,os:i,osVersion:r,browserVersion:o,deviceType:s};cN={name:t,version:n,os:i,osVersion:r,browserVersion:o,deviceType:s}}return cN}function lN(e){let t,n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return t="Blink"===e.engine.name?e.engine.version||"":e.browser.version||"",n?t.split(".")[0]:t}function uN(){return dN().os}function hN(){const e=dN();return"".concat(e.os," ").concat(e.osVersion)}function pN(){const e=dN();return!!("WebKit"===aN.engine.name&&e.os===rN.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&e.name!==oN.SAFARI||TN()&&e.name!==oN.SAFARI)}function _N(){return dN().name===oN.CHROME}function EN(){return dN().name===oN.SAFARI}function mN(){const e=dN();if(e.name!==oN.SAFARI||!e.browserVersion)return!1;const t=e.browserVersion.split(".");return Number(t[0])>15||15===Number(t[0])&&Number(t[1])>=4}function fN(){const e=dN();if(e.name!==oN.SAFARI||!e.browserVersion)return!1;const t=e.browserVersion.split(".");return Number(t[0])>18||18===Number(t[0])&&Number(t[1])>=4}function gN(){return dN().name===oN.EDGE}function SN(){return dN().name===oN.FIREFOX}function TN(){return dN().os===rN.IOS}function RN(e){const t=dN();return!(t.name!==oN.CHROME||!t.osVersion)&&Number(t.version)>=e}function vN(e){const t=dN();return!(t.name!==oN.CHROME||!t.osVersion)&&Number(t.version)<e}function yN(e,t,n){const i=dN();return!(i.name!==e||!i.osVersion)&&(n?Number(i.version)>=t&&Number(i.version)<=n:Number(i.version)===t)}function bN(e){const t=dN();return!(t.name!==oN.EDGE||!t.osVersion)&&Number(t.version)>=e}function CN(e){const t=dN();return!(t.name!==oN.FIREFOX||!t.osVersion)&&Number(t.version)>=e}function IN(e){const t=dN();return!(t.name!==oN.SAFARI||!t.osVersion)&&Number(t.version)>=e}function AN(e,t,n){const i=dN();if(i.os!==rN.IOS||!i.osVersion)return!1;const r=i.osVersion.split(".");return n?t&&Number(r[0])===e&&Number(r[1])>t||Number(r[0])>e:t?Number(r[0])===e&&Number(r[1])>=t||Number(r[0])>e:Number(r[0])>=e}function wN(e,t,n){const i=dN();if(i.os!==rN.IOS||!i.osVersion)return!1;const r=i.osVersion.split(".");return n?t&&Number(r[0])===e&&Number(r[1])<t||Number(r[0])<e:t?Number(r[0])===e&&Number(r[1])<=t||Number(r[0])<e:Number(r[0])<=e}function ON(e,t,n){const i=dN();if(i.name!==oN.SAFARI||!i.osVersion||!i.browserVersion)return!1;const r=i.browserVersion.split(".");return n?t&&Number(r[0])===e&&Number(r[1])<t||Number(r[0])<e:t?Number(r[0])===e&&Number(r[1])<=t||Number(r[0])<e:Number(r[0])<=e}function NN(e){const t=dN();return!(t.name!==oN.OPERA||!t.osVersion)&&Number(t.version)>=e}function DN(){const e=dN();if(e.os!==rN.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return Number(t[0])<14||14===Number(t[0])&&Number(t[1])<=6}function PN(){const e=dN();if(e.os!==rN.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])}function LN(){const e=dN();if(e.os!==rN.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 16===Number(t[0])}function kN(){const e=dN();if(e.os!==rN.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=1}function MN(){return EN()&&navigator.maxTouchPoints>0}function UN(){return dN().name===oN.WECHAT}function VN(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}function xN(){const e=uN();return function(){const e=dN().deviceType;return"mobile"===e||"tablet"===e}()||e===rN.ANDROID||e===rN.IOS||e===rN.HARMONY_OS}function FN(){const e=dN();return e.name!==oN.EDGE&&e.name!==oN.SAFARI&&!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function BN(){return uN()===rN.ANDROID}function jN(){const e=dN();return BN()&&(e.name===oN.CHROME||e.name===oN.WECHAT||/chrome|chromium/i.test(navigator.userAgent))}function GN(){var e;return!!Vi(e=window.navigator.userAgent).call(e,"AgoraWebView")}function WN(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function KN(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function HN(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function YN(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?HN(Object(n),!0).forEach((function(t){KN(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):HN(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function XN(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,o,s,a=[],c=!0,d=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=o.call(n)).done)&&(a.push(i.value),a.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return WN(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?WN(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}let JN=function(e){return e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.UNEXPECTED_RESPONSE="UNEXPECTED_RESPONSE",e.PB_ERROR="PB_ERROR",e.TIMEOUT="TIMEOUT",e.INVALID_PARAMS="INVALID_PARAMS",e.NOT_READABLE="NOT_READABLE",e.NOT_SUPPORTED="NOT_SUPPORTED",e.INVALID_OPERATION="INVALID_OPERATION",e.OPERATION_ABORTED="OPERATION_ABORTED",e.WEB_SECURITY_RESTRICT="WEB_SECURITY_RESTRICT",e.EXCHANGE_SDP_FAILED="EXCHANGE_SDP_FAILED",e.ADD_CANDIDATE_FAILED="ADD_CANDIDATE_FAILED",e.DATACHANNEL_FAILED="DATACHANNEL_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.NETWORK_TIMEOUT="NETWORK_TIMEOUT",e.NETWORK_RESPONSE_ERROR="NETWORK_RESPONSE_ERROR",e.API_INVOKE_TIMEOUT="API_INVOKE_TIMEOUT",e.ENUMERATE_DEVICES_FAILED="ENUMERATE_DEVICES_FAILED",e.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",e.ELECTRON_IS_NULL="ELECTRON_IS_NULL",e.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR="ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR",e.CHROME_PLUGIN_NO_RESPONSE="CHROME_PLUGIN_NO_RESPONSE",e.CHROME_PLUGIN_NOT_INSTALL="CHROME_PLUGIN_NOT_INSTALL",e.MEDIA_OPTION_INVALID="MEDIA_OPTION_INVALID",e.PERMISSION_DENIED="PERMISSION_DENIED",e.CONSTRAINT_NOT_SATISFIED="CONSTRAINT_NOT_SATISFIED",e.TRACK_IS_DISABLED="TRACK_IS_DISABLED",e.GET_VIDEO_ELEMENT_VISIBLE_ERROR="GET_VIDEO_ELEMENT_VISIBLE_ERROR",e.SHARE_AUDIO_NOT_ALLOWED="SHARE_AUDIO_NOT_ALLOWED",e.LOW_STREAM_ENCODING_ERROR="LOW_STREAM_ENCODING_ERROR",e.SET_ENCODING_PARAMETER_ERROR="SET_ENCODING_PARAMETER_ERROR",e.TRACK_STATE_UNREACHABLE="TRACK_STATE_UNREACHABLE",e.INVALID_UINT_UID_FROM_STRING_UID="INVALID_UINT_UID_FROM_STRING_UID",e.CAN_NOT_GET_PROXY_SERVER="CAN_NOT_GET_PROXY_SERVER",e.CAN_NOT_GET_GATEWAY_SERVER="CAN_NOT_GET_GATEWAY_SERVER",e.VOID_GATEWAY_ADDRESS="VOID_GATEWAY_ADDRESS",e.UID_CONFLICT="UID_CONFLICT",e.MULTI_UNILBS_RESPONSE_ERROR="MULTI_UNILBS_RESPONSE_ERROR",e.UPDATE_TICKET_FAILED="UPDATE_TICKET_FAILED",e.TOKEN_EXPIRE="TOKEN_EXPIRE",e.INVALID_LOCAL_TRACK="INVALID_LOCAL_TRACK",e.INVALID_TRACK="INVALID_TRACK",e.SENDER_NOT_FOUND="SENDER_NOT_FOUND",e.CREATE_OFFER_FAILED="CREATE_OFFER_FAILED",e.SET_ANSWER_FAILED="SET_ANSWER_FAILED",e.ICE_FAILED="ICE_FAILED",e.PC_CLOSED="PC_CLOSED",e.SENDER_REPLACE_FAILED="SENDER_REPLACE_FAILED",e.GET_LOCAL_CAPABILITIES_FAILED="GET_LOCAL_CAPABILITIES_FAILED",e.GET_LOCAL_CONNECTION_PARAMS_FAILED="GET_LOCAL_CONNECTION_PARAMS_FAILED",e.SUBSCRIBE_FAILED="SUBSCRIBE_FAILED",e.UNSUBSCRIBE_FAILED="UNSUBSCRIBE_FAILED",e.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",e.NO_ICE_CANDIDATE="NO_ICE_CANDIDATE",e.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS="CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS",e.EXIST_DISABLED_VIDEO_TRACK="EXIST_DISABLED_VIDEO_TRACK",e.INVALID_REMOTE_USER="INVALID_REMOTE_USER",e.REMOTE_USER_IS_NOT_PUBLISHED="REMOTE_USER_IS_NOT_PUBLISHED",e.CUSTOM_REPORT_SEND_FAILED="CUSTOM_REPORT_SEND_FAILED",e.CUSTOM_REPORT_FREQUENCY_TOO_HIGH="CUSTOM_REPORT_FREQUENCY_TOO_HIGH",e.FETCH_AUDIO_FILE_FAILED="FETCH_AUDIO_FILE_FAILED",e.READ_LOCAL_AUDIO_FILE_ERROR="READ_LOCAL_AUDIO_FILE_ERROR",e.DECODE_AUDIO_FILE_FAILED="DECODE_AUDIO_FILE_FAILED",e.WS_ABORT="WS_ABORT",e.WS_DISCONNECT="WS_DISCONNECT",e.WS_ERR="WS_ERR",e.EXTERNAL_SIGNAL_ABORT="EXTERNAL_SIGNAL_ABORT",e.LIVE_STREAMING_TASK_CONFLICT="LIVE_STREAMING_TASK_CONFLICT",e.LIVE_STREAMING_INVALID_ARGUMENT="LIVE_STREAMING_INVALID_ARGUMENT",e.LIVE_STREAMING_INTERNAL_SERVER_ERROR="LIVE_STREAMING_INTERNAL_SERVER_ERROR",e.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED="LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED",e.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED="LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED",e.LIVE_STREAMING_CDN_ERROR="LIVE_STREAMING_CDN_ERROR",e.LIVE_STREAMING_INVALID_RAW_STREAM="LIVE_STREAMING_INVALID_RAW_STREAM",e.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT="LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT",e.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE="LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE",e.LIVE_STREAMING_WARN_FREQUENT_REQUEST="LIVE_STREAMING_WARN_FREQUENT_REQUEST",e.WEBGL_INTERNAL_ERROR="WEBGL_INTERNAL_ERROR",e.BEAUTY_PROCESSOR_INTERNAL_ERROR="BEAUTY_PROCESSOR_INTERNAL_ERROR",e.CROSS_CHANNEL_WAIT_STATUS_ERROR="CROSS_CHANNEL_WAIT_STATUS_ERROR",e.CROSS_CHANNEL_FAILED_JOIN_SRC="CROSS_CHANNEL_FAILED_JOIN_SEC",e.CROSS_CHANNEL_FAILED_JOIN_DEST="CROSS_CHANNEL_FAILED_JOIN_DEST",e.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST="CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST",e.CROSS_CHANNEL_SERVER_ERROR_RESPONSE="CROSS_CHANNEL_SERVER_ERROR_RESPONSE",e.METADATA_OUT_OF_RANGE="METADATA_OUT_OF_RANGE",e.LOCAL_AEC_ERROR="LOCAL_AEC_ERROR",e.INVALID_PLUGIN="INVALID_PLUGIN",e.DISCONNECT_P2P="DISCONNECT_P2P",e.CONVERTING_IMAGEDATA_TO_BLOB_FAILED="CONVERTING_IMAGEDATA_TO_BLOB_FAILED",e.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED="CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED",e.INIT_DATACHANNEL_TIMEOUT="INIT_DATACHANNEL_TIMEOUT",e.CREATE_DATACHANNEL_ERROR="CREATE_DATACHANNEL_ERROR",e.DATACHANNEL_CONNECTION_TIMEOUT="DATACHANNEL_CONNECTION_TIMEOUT",e.PROHIBITED_OPERATION="PROHIBITED_OPERATION",e.IMAGE_MODERATION_UPLOAD_FAILED="IMAGE_MODERATION_UPLOAD_FAILED",e.P2P_MESSAGE_FAILED="P2P_MESSAGE_FAILED",e}({}),zN=class extends Error{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2?arguments[2]:void 0;super(t),KN(this,"code",void 0),KN(this,"message",void 0),KN(this,"data",void 0),KN(this,"name","AgoraRTCException"),this.code=e,this.message="AgoraRTCError ".concat(this.code,": ").concat(t),this.data=n}toString(){return this.data?"".concat(this.message,"\ndata: ").concat(JSON.stringify(this.data)):this.message}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error",t=arguments.length>1?arguments[1]:void 0;return"error"===e&&(t||console).error(this.toString()),"warning"===e&&(t||console).warn(this.toString()),this}throw(e){throw this.print("error",e),this}};function ZN(e,t){if("boolean"!=typeof e)throw new zN(JN.INVALID_PARAMS,"Invalid ".concat(t,": The value is of the boolean type."))}function qN(e,t,n){if(!Vi(n).call(n,e))throw new zN(JN.INVALID_PARAMS,"".concat(t," can only be set as ").concat(JSON.stringify(n)))}function QN(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e4;if(e<n||e>i||(!(arguments.length>4&&void 0!==arguments[4])||arguments[4])&&!function(e){return"number"==typeof e&&e%1==0}(e))throw new zN(JN.INVALID_PARAMS,"invalid ".concat(t,": the value range is [").concat(n,", ").concat(i,"]. integer only"))}function $N(e,t){if("number"!=typeof e){if(!(e.min||e.max||e.ideal||e.exact))throw new zN(JN.INVALID_PARAMS,"".concat(t," is not a valid ConstrainLong"));void 0!==e.min&&QN(e.min,"".concat(t,".min"),0,1/0),void 0!==e.max&&QN(e.max,"".concat(t,".max"),1,1/0),void 0!==e.exact&&QN(e.exact,"".concat(t,".exact"),1,1/0),void 0!==e.ideal&&QN(e.ideal,"".concat(t,".ideal"),1,1/0)}else QN(e,t,1,1/0)}function eD(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:255,r=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];if(null==e)throw new zN(JN.INVALID_PARAMS,"".concat(t||"param"," cannot be empty"));if(!iD(e,n,i,r))throw new zN(JN.INVALID_PARAMS,"Invalid ".concat(t||"string param",": Length of the string: [").concat(n,",").concat(i,"].").concat(r?" ASCII characters only.":""))}function tD(e,t){if(!Array.isArray(e))throw new zN(JN.INVALID_PARAMS,"".concat(t," should be an array"))}function nD(e){return null==e}function iD(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:255,i=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return"string"==typeof e&&e.length<=n&&e.length>=t&&(!i||function(e){if("string"!=typeof e)return!1;for(let t=0;t<e.length;t+=1){const n=e.charCodeAt(t);if(n<0||n>255)return!1}return!0}(e))}function rD(e,t,n){if("getBigUint64"in DataView.prototype)return e.getBigUint64(t,n);const i=e.getUint32(t,n),r=e.getUint32(t+4,n),o=Number(!!n),s=Number(!n);return BigInt(i*s+r*o)<<BigInt(32)|BigInt(i*o+r*s)}function oD(e,t,n,i){if("setBigUint64"in DataView.prototype)return e.setBigUint64(t,n,i);const r=Number(n>>BigInt(32)),o=Number(n&BigInt(4294967295));i?(e.setUint32(t+4,r,i),e.setUint32(t,o,i)):(e.setUint32(t,r,i),e.setUint32(t+4,o,i))}var sD=function(e){return e.COVERED="COVERED",e.POSITION="POSITION",e.SIZE="SIZE",e.STYLE="STYLE",e}(sD||{}),aD=function(e){return e.UNMOUNTED="UNMOUNTED",e.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT",e}(aD||{});const cD=new class{constructor(){KN(this,"_clientSize",null),KN(this,"getClientWidth",(()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth)),KN(this,"getClientHeight",(()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight)),KN(this,"getStyle",(e=>window.getComputedStyle(e,null))),KN(this,"checkCssVisibleProperty",(e=>{var t;let n=!0;const i=this.getStyle(e),r=i.display,o=i.visibility,s=i.opacity,a=i.filter;return("none"===r||Vi(t=["hidden","collapse"]).call(t,o)||Number(s)<.1)&&(n=!1),!!n&&(a&&a.split(" ").filter((e=>{var t;const n=e.split("(")[0];return Vi(t=["brightness","blur","opacity"]).call(t,n)})).map((e=>{const t=XN(e.split(/\(|\)/),2),n=t[0],i=t[1];return[n,Number(i.match(/^[0-9\.]+/))]})).forEach((e=>{const t=XN(e,2),i=t[0],r=t[1];switch(i){case"brightness":(r<.1||r>3)&&(n=!1);break;case"blur":r>3&&(n=!1);break;case"opacity":r<.1&&(n=!1)}})),n)})),KN(this,"checkPropertyUpToAllParentNodes",((e,t)=>{let n=!0,i=!0;const r=e=>t(e);let o=e;for(;o&&i;)r(o)||(n=!1,i=!1),o=o.parentElement,o||(i=!1);return n})),KN(this,"checkActualCssVisibleIncludeInherit",(e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty))),KN(this,"getSizeAboutClient",(e=>{const t=e.getBoundingClientRect(),n=t.width,i=t.height,r=t.left,o=t.right,s=t.top,a=t.bottom,c=this.getClientWidth(),d=this.getClientHeight();return{width:n,height:i,left:r,right:o,top:s,bottom:a,clientWidth:c,clientHeight:d,clientMin:Math.min(c,d)}})),KN(this,"checkActualSize",(()=>{const e=this._clientSize,t=e.width,n=e.height,i=e.clientMin;return this.checkSizeIsVisible(t,n,i)})),KN(this,"elementFromPoint",((e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null)),KN(this,"checkCoverForAPoint",((e,t,n)=>{const i=this.elementFromPoint(e,t);return null!==i&&i!==n})),KN(this,"getPointPositionList",(()=>{const e=this._clientSize,t=e.width,n=e.height,i=e.left,r=e.top,o=t/6,s=n/6,a=[],c=10**6;for(let e=0;e<5;e++)for(let t=0;t<5;t++){const n=(i*c+(0===e?.1:4===e?(o*e*c-1e5)/c:o*e)*c)/c,d=(r*c+(0===t?.1:4===t?(s*t*c-1e5)/c:s*t)*c)/c;a.push({x:n,y:d})}return[...a]})),KN(this,"checkElementCover",(e=>this.getPointPositionList().map((t=>this.checkCoverForAPoint(t.x,t.y,e))).filter((e=>!!e)).length>6)),KN(this,"checkSizeIsVisible",((e,t,n)=>(e>50||n/e<=10)&&(t>50||n/t<=10))),KN(this,"checkSizeOfPartInClient",(()=>{const e=this._clientSize,t=e.left,n=e.right,i=e.top,r=e.bottom,o=e.clientHeight,s=e.clientWidth,a=e.clientMin;let c,d,l,u;if(t<0)c=0;else{if(!(t<s))return!1;c=t}if(n<0)return!1;if(d=n<s?n:s,i<0)l=0;else{if(!(i<o))return!1;l=i}if(r<0)return!1;u=r<o?r:o;const h=d-c,p=u-l;return this.checkSizeIsVisible(h,p,a)})),KN(this,"returnHiddenResult",(e=>(this._clientSize=null,{visible:!1,reason:e}))),KN(this,"checkOneElementVisible",(e=>{if(e instanceof HTMLElement){if(this.checkElementIsMountedOnDom(e)){if(this.checkActualCssVisibleIncludeInherit(e)){if(this._clientSize=this.getSizeAboutClient(e),this.checkElementCover(e))return this.returnHiddenResult(sD.COVERED);{const e=this.checkActualSize(),t=this.checkSizeOfPartInClient();return e&&!t?this.returnHiddenResult(sD.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(sD.SIZE)}}return this.returnHiddenResult(sD.STYLE)}return this.returnHiddenResult(aD.UNMOUNTED)}return this.returnHiddenResult(aD.INVALID_HTML_ELEMENT)})),KN(this,"checkElementIsMountedOnDom",(e=>this.checkPropertyUpToAllParentNodes(e,(e=>"HTML"!==e.nodeName.toUpperCase()?null!==e.parentElement:!!document.documentElement))))}};function dD(e){return(new TextEncoder).encode(e)}const lD=function(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n};const uD=async e=>function(e,t){let n="";return new Uint8Array(e).forEach((e=>{n+=e.toString(t).padStart(2,"0")})),n}(await crypto.subtle.digest("SHA-256",dD(e)),16);let hD=class{constructor(){KN(this,"_events",{}),KN(this,"addListener",this.on)}getListeners(e){return this._events[e]?this._events[e].map((e=>e.listener)):[]}on(e,t){this._events[e]||(this._events[e]=[]);const n=this._events[e];-1===this._indexOfListener(n,t)&&n.push({listener:t,once:!1})}once(e,t){this._events[e]||(this._events[e]=[]);const n=this._events[e];-1===this._indexOfListener(n,t)&&n.push({listener:t,once:!0})}off(e,t){if(!this._events[e])return;const n=this._events[e],i=this._indexOfListener(n,t);-1!==i&&n.splice(i,1),0===this._events[e].length&&delete this._events[e]}removeAllListeners(e){e?delete this._events[e]:this._events={}}emit(e){this._events[e]||(this._events[e]=[]);const t=this._events[e].map((e=>e));for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];for(let n=0;n<t.length;n+=1){const r=t[n];r.once&&this.off(e,r.listener),r.listener.apply(this,i||[])}}safeEmit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];[...this._events[e]||[]].forEach((t=>{t.once&&this.off(e,t.listener);try{t.listener.apply(this,n)}catch(t){console.error("safeEmit event:".concat(e," error ").concat(null==t?void 0:t.toString()))}}))}_indexOfListener(e,t){let n=e.length;for(;n--;)if(e[n].listener===t)return n;return-1}};let pD=null;function _D(){if(pD)return pD;if(window.electron)return pD=window.electron;if(!window.require)return null;try{return pD=window.require("electron"),pD}catch(e){return null}}let ED=function(e){return e.CREATE_CLIENT="createClient",e.CHECK_SYSTEM_REQUIREMENTS="checkSystemRequirements",e.SET_AREA="setArea",e.PRELOAD="PRELOAD",e.CHECK_VIDEO_TRACK_IS_ACTIVE="checkVideoTrackIsActive",e.CHECK_AUDIO_TRACK_IS_ACTIVE="checkAudioTrackIsActive",e.CREATE_MIC_AUDIO_TRACK="createMicrophoneAudioTrack",e.CREATE_CUSTOM_AUDIO_TRACK="createCustomAudioTrack",e.CREATE_BUFFER_AUDIO_TRACK="createBufferSourceAudioTrack",e.CREATE_CAM_VIDEO_TRACK="createCameraVideoTrack",e.CREATE_CUSTOM_VIDEO_TRACK="createCustomVideoTrack",e.CREATE_MIC_AND_CAM_TRACKS="createMicrophoneAndCameraTracks",e.CREATE_SCREEN_VIDEO_TRACK="createScreenVideoTrack",e.SET_ENCRYPTION_CONFIG="Client.setEncryptionConfig",e.START_PROXY_SERVER="Client.startProxyServer",e.STOP_PROXY_SERVER="Client.stopProxyServer",e.SET_PROXY_SERVER="Client.setProxyServer",e.SET_TURN_SERVER="Client.setTurnServer",e.SET_CLIENT_ROLE="Client.setClientRole",e.SET_LOW_STREAM_PARAMETER="Client.setLowStreamParameter",e.ENABLE_DUAL_STREAM="Client.enableDualStream",e.DISABLE_DUAL_STREAM="Client.disableDualStream",e.JOIN="Client.join",e.LEAVE="Client.leave",e.PUBLISH="Client.publish",e.UNPUBLISH="Client.unpublish",e.SUBSCRIBE="Client.subscribe",e.MASS_SUBSCRIBE="Client.massSubscribe",e.MASS_UNSUBSCRIBE="Client.massUnsubscribe",e.UNSUBSCRIBE="Client.unsubscribe",e.RENEW_TOKEN="Client.renewToken",e.SET_REMOTE_VIDEO_STREAM_TYPE="Client.setRemoteVideoStreamType",e.SET_STREAM_FALLBACK_OPTION="Client.setStreamFallbackOption",e.ENABLE_AUDIO_VOLUME_INDICATOR="Client.enableAudioVolumeIndicator",e.SEND_CUSTOM_REPORT_MESSAGE="Client.sendCustomReportMessage",e.INSPECT_VIDEO_CONTENT="Client.inspectVideoContent",e.STOP_INSPECT_VIDEO_CONTENT="Client.stopInspectVideoContent",e.JOIN_FALLBACK_TO_PROXY="Client._joinFallbackToProxy",e.ON_LIVE_STREAM_WARNING="Client.onLiveStreamWarning",e.ON_LIVE_STREAM_ERROR="Client.onLiveStreamingError",e.START_LIVE_STREAMING="Client.startLiveStreaming",e.SET_LIVE_TRANSCODING="Client.setLiveTranscoding",e.STOP_LIVE_STREAMING="Client.stopLiveStreaming",e.START_CHANNEL_MEDIA_RELAY="Client.startChannelMediaRelay",e.UPDATE_CHANNEL_MEDIA_RELAY="Client.updateChannelMediaRelay",e.STOP_CHANNEL_MEDIA_RELAY="Client.stopChannelMediaRelay",e.REQUEST_CONFIG_DISTRIBUTE="_config-distribute-request",e.SET_CONFIG_DISTRIBUTE="_configDistribute",e.LOCAL_TRACK_SET_MUTED="LocalTrack.setMute",e.LOCAL_AUDIO_TRACK_PLAY="LocalAudioTrack.play",e.LOCAL_AUDIO_TRACK_PLAY_IN_ELEMENT="LocalAudioTrack.playInElement",e.LOCAL_AUDIO_TRACK_STOP="LocalAudioTrack.stop",e.LOCAL_AUDIO_TRACK_SET_VOLUME="LocalAudioTrack.setVolume",e.MIC_AUDIO_TRACK_SET_DEVICE="MicrophoneAudioTrack.setDevice",e.BUFFER_AUDIO_TRACK_START="BufferSourceAudioTrack.startProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_STOP="BufferSourceAudioTrack.stopProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_PAUSE="BufferSourceAudioTrack.pauseProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_RESUME="BufferSourceAudioTrack.resumeProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_SEEK="BufferSourceAudioTrack.seekAudioBuffer",e.LOCAL_VIDEO_TRACK_PLAY="LocalVideoTrack.play",e.LOCAL_VIDEO_TRACK_STOP="LocalVideoTrack.stop",e.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE="LocalVideoTrack.getVideoElementVisibleStatus",e.LOCAL_VIDEO_TRACK_BEAUTY="LocalVideoTrack.setBeautyEffect",e.LOCAL_VIDEO_SEND_SEI_DATA="LocalVideoTrack.sendSeiData",e.CAM_VIDEO_TRACK_SET_DEVICE="CameraVideoTrack.setDevice",e.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG="CameraVideoTrack.setEncoderConfiguration",e.REMOTE_VIDEO_TRACK_PLAY="RemoteVideoTrack.play",e.REMOTE_VIDEO_TRACK_STOP="RemoteVideoTrack.stop",e.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE="RemoteVideoTrack.getVideoElementVisibleStatus",e.REMOTE_AUDIO_TRACK_PLAY="RemoteAudioTrack.play",e.REMOTE_AUDIO_TRACK_STOP="RemoteAudioTrack.stop",e.REMOTE_AUDIO_SET_VOLUME="RemoteAudioTrack.setVolume",e.REMOTE_AUDIO_SET_OUTPUT_DEVICE="RemoteAudioTrack.setOutputDevice",e.GET_MEDIA_STREAM_TRACK="Track.getMediaStreamTrack",e.STREAM_TYPE_CHANGE="streamTypeChange",e.CONNECTION_STATE_CHANGE="connectionStateChange",e.LOAD_CONFIG_FROM_LOCALSTORAGE="loadConfigFromLocalStorage",e.IMAGE_MODERATION_UPLOAD="imageModerationUpload",e.REPUB_AFTER_PC_CONNECTED="repubAfterPCConnected",e.PRELOAD_MEDIA_FAILED="preloadMediaFailed",e.MISMATCH_DTLS_PARAMETERS="mismatchDtlsParameters",e.MISMATCH_ICE_PARAMETERS="mismatchIceParameters",e.VOS_FALLBACK_CN="vosFallbackCN",e.DATACHANNEL_FAILBACK="datachannelFailback",e}({}),mD=function(e){return e.TRACER="tracer",e}({});function fD(e){return QN(e.timeout,"config.timeout",0,1e5),QN(e.timeoutFactor,"config.timeoutFactor",0,100,!1),QN(e.maxRetryCount,"config.maxRetryConfig",0,1/0),QN(e.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}let gD=function(e){return e[e.AUDIENCE_LEVEL_LOW_LATENCY=1]="AUDIENCE_LEVEL_LOW_LATENCY",e[e.AUDIENCE_LEVEL_ULTRA_LOW_LATENCY=2]="AUDIENCE_LEVEL_ULTRA_LOW_LATENCY",e[e.AUDIENCE_LEVEL_SYNC_LATENCY=3]="AUDIENCE_LEVEL_SYNC_LATENCY",e}({}),SD=function(e){return e.LEAVE="LEAVE",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.UID_BANNED="UID_BANNED",e.FALLBACK="FALLBACK",e.IP_BANNED="IP_BANNED",e.CHANNEL_BANNED="CHANNEL_BANNED",e.LICENSE_MISSING="LICENSE_MISSING",e.LICENSE_EXPIRED="LICENSE_EXPIRED",e.LICENSE_MINUTES_EXCEEDED="LICENSE_MINUTES_EXCEEDED",e.LICENSE_PERIOD_INVALID="LICENSE_PERIOD_INVALID",e.LICENSE_MULTIPLE_SDK_SERVICE="LICENSE_MULTIPLE_SDK_SERVICE",e.LICENSE_ILLEGAL="LICENSE_ILLEGAL",e.TOKEN_EXPIRE="TOKEN_EXPIRE",e.FALLBACK_TO_HLS="FALLBACK_TO_HLS",e.UID_CONFLICT="UID_CONFLICT",e}({});function TD(e){if(!Array.isArray(e)||e.length<1)return!1;try{e.forEach((e=>{if(!e.urls)throw Error()}))}catch(e){return!1}return!0}function RD(e){return eD(e.turnServerURL,"turnServerURL"),eD(e.username,"username"),eD(e.password,"password"),e.udpport&&QN(e.udpport,"udpport",1,99999,!0),e.forceturn&&ZN(e.forceturn,"forceturn"),e.security&&ZN(e.security,"security"),e.tcpport&&QN(e.tcpport,"tcpport",1,99999,!0),!0}let vD=function(e){return e[e.AUTO_SIMULCAST_STREAM=-1]="AUTO_SIMULCAST_STREAM",e[e.DISABLE_SIMULCAST_STREM=0]="DISABLE_SIMULCAST_STREM",e[e.ENABLE_SIMULCAST_STREAM=1]="ENABLE_SIMULCAST_STREAM",e}({});function yD(e){return void 0!==e.level&&qN(e.level,"level",[1,2,3]),void 0!==e.delay&&QN(e.delay,"delay",0,3e3,!0),!0}let bD=function(e){return e.PEERCONNECTION_STATE_CHANGE="peerconnection-state-change",e.AUDIO_METADATA="audio-metadata",e.AUDIO_PTS="audio-pts",e.CONNECTION_STATE_CHANGE="connection-state-change",e.MEDIA_RECONNECT_START="media-reconnect-start",e.MEDIA_RECONNECT_END="media-reconnect-end",e.IS_USING_CLOUD_PROXY="is-using-cloud-proxy",e.USER_JOINED="user-joined",e.USER_LEAVED="user-left",e.USER_PUBLISHED="user-published",e.USER_UNPUBLISHED="user-unpublished",e.USER_INFO_UPDATED="user-info-updated",e.CLIENT_BANNED="client-banned",e.CHANNEL_MEDIA_RELAY_STATE="channel-media-relay-state",e.CHANNEL_MEDIA_RELAY_EVENT="channel-media-relay-event",e.VOLUME_INDICATOR="volume-indicator",e.CRYPT_ERROR="crypt-error",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="token-privilege-will-expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="token-privilege-did-expire",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGED="stream-type-changed",e.STREAM_FALLBACK="stream-fallback",e.RECEIVE_METADATA="receive-metadata",e.STREAM_MESSAGE="stream-message",e.LIVE_STREAMING_ERROR="live-streaming-error",e.LIVE_STREAMING_WARNING="live-streaming-warning",e.EXCEPTION="exception",e.ERROR="error",e.P2P_LOST="p2p_lost",e.JOIN_FALLBACK_TO_PROXY="join-fallback-to-proxy",e.CHANNEL_FALLBACK_TO_WEBSOCKET="channel-fallback-to-websocket",e.MEDIA_CONNECTION_TYPE_CHANGE="media-connection-type-change",e.PUBLISHED_USER_LIST="published-user-list",e.USER_LIST="user-list",e.CONTENT_INSPECT_CONNECTION_STATE_CHANGE="content-inspect-connection-state-change",e.CONTENT_INSPECT_ERROR="content-inspect-error",e.CONTENT_INSPECT_RESULT="content-inspect-result",e.IMAGE_MODERATION_CONNECTION_STATE_CHANGE="image-moderation-connection-state-change",e.FALLBACK_TO_HLS="fallback-to-hls",e.FIRST_VIDEO_BUFFER_READY="first-video-buffer-ready",e.FIRST_VIDEO_PRE_RENDER="first-video-pre-render",e.AV1_DECODABLE_RESULT="av1-decodable-result",e}({}),CD=function(e){return e.CONFIG="config",e.VOSERROR="vos_error",e.AP_ERROR="ap_error",e}({}),ID=function(e){return e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK",e.REGIONAL_DISTRIBUTION="REGIONAL_DISTRIBUTION",e}({}),AD=function(e){return e.ONLINE="ONLINE",e.OFFLINE="OFFLINE",e}({}),wD=function(e){return e.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",e.ONLINE="ONLINE",e.OFFLINE="OFFLINE",e}({});function OD(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return 0===e.getListeners(t).length?dp.reject(new zN(JN.UNEXPECTED_ERROR,"can not emit promise")):new dp(((n,r)=>{e.emit(t,...i,n,r)}))}function ND(e,t){if(0===e.getListeners(t).length)return dp.resolve();for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return OD(e,t,...i)}function DD(e,t){if(0===e.getListeners(t).length)return null;for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return PD(e,t,...i)}function PD(e,t){let n=null,i=null;for(var r=arguments.length,o=new Array(r>2?r-2:0),s=2;s<r;s++)o[s-2]=arguments[s];if(e.emit(t,...o,(e=>{n=e}),(e=>{i=e})),null!==i)throw i;if(null===n)throw new zN(JN.UNEXPECTED_ERROR,"handler is not sync");return n}const LD=new class extends hD{set networkState(e){this.emit(wD.NETWORK_STATE_CHANGE,e,this._networkState),e===AD.ONLINE?this.emit(wD.ONLINE):e===AD.OFFLINE&&(this.onlineWaiter=new dp((e=>{this.once(wD.ONLINE,(()=>{this.onlineWaiter=void 0,e(AD.ONLINE)}))})),this.emit(wD.OFFLINE)),this._networkState=e}get networkState(){return this._networkState}get isOnline(){return this._networkState===AD.ONLINE}constructor(){super(),KN(this,"_moduleName","network-indicator"),KN(this,"_networkState",AD.ONLINE),KN(this,"onlineWaiter",void 0),window.addEventListener("online",(()=>{this.networkState=AD.ONLINE})),window.addEventListener("offline",(()=>{this.networkState=AD.OFFLINE}))}},kD=[];for(let e=0;e<256;++e)kD.push((e+256).toString(16).slice(1));const MD="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);let UD;const VD=new Uint8Array(16);function xD(){return MD?MD():function(e,t,n){var i,r,o,s;const a=null!==(i=null!==(r=(e=e||{}).random)&&void 0!==r?r:null===(o=(s=e).rng)||void 0===o?void 0:o.call(s))&&void 0!==i?i:function(){if(!UD){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");UD=crypto.getRandomValues.bind(crypto)}return UD(VD)}();if(a.length<16)throw new Error("Random bytes length must be >= 16");if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t){if((n=n||0)<0||n+16>t.length)throw new RangeError("UUID byte range ".concat(n,":").concat(n+15," is out of buffer bounds"));for(let e=0;e<16;++e)t[n+e]=a[e];return t}return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return(kD[e[t+0]]+kD[e[t+1]]+kD[e[t+2]]+kD[e[t+3]]+"-"+kD[e[t+4]]+kD[e[t+5]]+"-"+kD[e[t+6]]+kD[e[t+7]]+"-"+kD[e[t+8]]+kD[e[t+9]]+"-"+kD[e[t+10]]+kD[e[t+11]]+kD[e[t+12]]+kD[e[t+13]]+kD[e[t+14]]+kD[e[t+15]]).toLowerCase()}(a)}(e,t,undefined);var e,t}function FD(e,t){const n=e.indexOf(t);-1!==n&&e.splice(n,1)}function BD(e){const t=[];return e.forEach((e=>{-1===t.indexOf(e)&&t.push(e)})),t}function jD(e){void 0!==dp?dp.resolve().then(e):setTimeout(e,0)}function GD(e){return JSON.parse(JSON.stringify(e))}function WD(e){try{return GD(e)}catch(t){return e}}const KD={};function HD(e,t){KD[t]||(KD[t]=!0,e())}function YD(e){const t=window.atob(e),n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function XD(e){let t="";for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return window.btoa(t)}function JD(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=(new TextEncoder).encode(e);if(n.length>t)n=n.slice(0,t);else if(n.length<t){const e=new Uint8Array(t);e.set(n),n=e}return n}function zD(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=ar(t).call(t,((e,t)=>e+t.length),0),r=new Uint8Array(new ArrayBuffer(i));let o=0;return t.forEach((e=>{r.set(e,o),o+=e.length})),r}function ZD(e){return window.TextEncoder?(new TextEncoder).encode(e).length:e.length}function qD(e){let t=0;return(/DingTalk/i.test(navigator.userAgent)||/AliApp/i.test(navigator.userAgent))&&e.realFormData&&(e=e.realFormData),e.forEach((e=>{t+="string"==typeof e?ZD(e):e.size})),t+138}function QD(e){const t=new zN(JN.TIMEOUT,"timeout");return new dp(((n,i)=>{window.setTimeout((()=>i(t)),e)}))}function $D(e){return new dp((t=>{window.setTimeout(t,e)}))}function eP(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:7,t=arguments.length>1?arguments[1]:void 0;const n=Math.random().toString(16).substr(2,e).toLowerCase();return n.length===e?"".concat(t).concat(n):"".concat(t).concat(n)+eP(e-n.length,"")}function tP(){let e,t=!1;try{var n;e=LC(n=xD()).call(n,"-","")}catch(e){t=!0}return!t&&e&&32===e.length||(e=eP(32,"")),e.toUpperCase()}const nP=()=>{},iP=new class{constructor(){KN(this,"fnMap",new Map)}throttleByKey(e,t,n,i){for(var r=arguments.length,o=new Array(r>4?r-4:0),s=4;s<r;s++)o[s-4]=arguments[s];if(this.fnMap.has(t)){const r=this.fnMap.get(t);if(r.threshold!==n){r.fn(...r.args),clearTimeout(r.timer);const s=window.setTimeout((()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)}),n);this.fnMap.set(t,{fn:e,threshold:n,timer:s,args:o,skipFn:i})}else r.skipFn&&r.skipFn(...r.args),this.fnMap.set(t,YN(YN({},r),{},{fn:e,args:o,skipFn:i}))}else{const r=window.setTimeout((()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)}),n);this.fnMap.set(t,{fn:e,threshold:n,timer:r,args:o,skipFn:i})}}},rP=iP.throttleByKey.bind(iP);function oP(e){return"object"==typeof e&&null!==e&&!(e instanceof RegExp)}function sP(e,t){if(!oP(e)||!oP(t))return t;if(Array.isArray(e)&&!Array.isArray(t)||!Array.isArray(e)&&Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e)){const n=[...e];for(let i=0;i<t.length;i++)n[i]=sP(e[i],t[i]);return n}{const n=YN({},e);for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(Object.prototype.hasOwnProperty.call(e,i)?n[i]=sP(e[i],t[i]):n[i]=t[i]);return n}}function aP(e,t){let n=[0];if(t&&(n=new Array(t).fill(0)),0===e)return n;let i=0;for(;e>0&&(n[i]=255&e,e>>=8,i++,!t||i!==t););return n}function cP(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function dP(e,t){try{return"object"==typeof e&&"object"==typeof t&&JSON.stringify(e)===JSON.stringify(t)}catch(e){return!1}}function lP(e){return ar(e).call(e,((e,t)=>e+t),0)}function uP(e){const t="0123456789abcdef";function n(e){let n,i="";for(n=0;n<=3;n++)i+=t.charAt(e>>8*n+4&15)+t.charAt(e>>8*n&15);return i}function i(e,t){const n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function r(e,t,n,r,o,s){return i(function(e,t){return e<<t|e>>>32-t}(i(i(t,e),i(r,s)),o),n)}function o(e,t,n,i,o,s,a){return r(t&n|~t&i,e,t,o,s,a)}function s(e,t,n,i,o,s,a){return r(t&i|n&~i,e,t,o,s,a)}function a(e,t,n,i,o,s,a){return r(t^n^i,e,t,o,s,a)}function c(e,t,n,i,o,s,a){return r(n^(t|~i),e,t,o,s,a)}const d=function(e){let t;const n=1+(e.length+8>>6),i=new Array(16*n);for(t=0;t<16*n;t++)i[t]=0;for(t=0;t<e.length;t++)i[t>>2]|=e.charCodeAt(t)<<t%4*8;return i[t>>2]|=128<<t%4*8,i[16*n-2]=8*e.length,i}(e);let l,u,h,p,_,E=1732584193,m=-271733879,f=-1732584194,g=271733878;for(l=0;l<d.length;l+=16)u=E,h=m,p=f,_=g,E=o(E,m,f,g,d[l+0],7,-680876936),g=o(g,E,m,f,d[l+1],12,-389564586),f=o(f,g,E,m,d[l+2],17,606105819),m=o(m,f,g,E,d[l+3],22,-1044525330),E=o(E,m,f,g,d[l+4],7,-176418897),g=o(g,E,m,f,d[l+5],12,1200080426),f=o(f,g,E,m,d[l+6],17,-1473231341),m=o(m,f,g,E,d[l+7],22,-45705983),E=o(E,m,f,g,d[l+8],7,1770035416),g=o(g,E,m,f,d[l+9],12,-1958414417),f=o(f,g,E,m,d[l+10],17,-42063),m=o(m,f,g,E,d[l+11],22,-1990404162),E=o(E,m,f,g,d[l+12],7,1804603682),g=o(g,E,m,f,d[l+13],12,-40341101),f=o(f,g,E,m,d[l+14],17,-1502002290),m=o(m,f,g,E,d[l+15],22,1236535329),E=s(E,m,f,g,d[l+1],5,-165796510),g=s(g,E,m,f,d[l+6],9,-1069501632),f=s(f,g,E,m,d[l+11],14,643717713),m=s(m,f,g,E,d[l+0],20,-373897302),E=s(E,m,f,g,d[l+5],5,-701558691),g=s(g,E,m,f,d[l+10],9,38016083),f=s(f,g,E,m,d[l+15],14,-660478335),m=s(m,f,g,E,d[l+4],20,-405537848),E=s(E,m,f,g,d[l+9],5,568446438),g=s(g,E,m,f,d[l+14],9,-1019803690),f=s(f,g,E,m,d[l+3],14,-187363961),m=s(m,f,g,E,d[l+8],20,1163531501),E=s(E,m,f,g,d[l+13],5,-1444681467),g=s(g,E,m,f,d[l+2],9,-51403784),f=s(f,g,E,m,d[l+7],14,1735328473),m=s(m,f,g,E,d[l+12],20,-1926607734),E=a(E,m,f,g,d[l+5],4,-378558),g=a(g,E,m,f,d[l+8],11,-2022574463),f=a(f,g,E,m,d[l+11],16,1839030562),m=a(m,f,g,E,d[l+14],23,-35309556),E=a(E,m,f,g,d[l+1],4,-1530992060),g=a(g,E,m,f,d[l+4],11,1272893353),f=a(f,g,E,m,d[l+7],16,-155497632),m=a(m,f,g,E,d[l+10],23,-1094730640),E=a(E,m,f,g,d[l+13],4,681279174),g=a(g,E,m,f,d[l+0],11,-358537222),f=a(f,g,E,m,d[l+3],16,-722521979),m=a(m,f,g,E,d[l+6],23,76029189),E=a(E,m,f,g,d[l+9],4,-640364487),g=a(g,E,m,f,d[l+12],11,-421815835),f=a(f,g,E,m,d[l+15],16,530742520),m=a(m,f,g,E,d[l+2],23,-995338651),E=c(E,m,f,g,d[l+0],6,-198630844),g=c(g,E,m,f,d[l+7],10,1126891415),f=c(f,g,E,m,d[l+14],15,-1416354905),m=c(m,f,g,E,d[l+5],21,-57434055),E=c(E,m,f,g,d[l+12],6,1700485571),g=c(g,E,m,f,d[l+3],10,-1894986606),f=c(f,g,E,m,d[l+10],15,-1051523),m=c(m,f,g,E,d[l+1],21,-2054922799),E=c(E,m,f,g,d[l+8],6,1873313359),g=c(g,E,m,f,d[l+15],10,-30611744),f=c(f,g,E,m,d[l+6],15,-1560198380),m=c(m,f,g,E,d[l+13],21,1309151649),E=c(E,m,f,g,d[l+4],6,-145523070),g=c(g,E,m,f,d[l+11],10,-1120210379),f=c(f,g,E,m,d[l+2],15,718787259),m=c(m,f,g,E,d[l+9],21,-343485551),E=i(E,u),m=i(m,h),f=i(f,p),g=i(g,_);return n(E)+n(m)+n(f)+n(g)}let hP=1,pP=console,_P=class{static setLogger(e){pP=e}constructor(e,t){KN(this,"id",void 0),KN(this,"lockingPromise",dp.resolve()),KN(this,"locks",0),KN(this,"name",""),KN(this,"lockId",void 0),this.lockId=hP++,e&&(this.name=e),t&&(this.id=t),this.logger("created")}logger(e,t){const n=(this.id?"[".concat(this.id,"]"):"")+"[lock-".concat(this.name,"-").concat(this.lockId,"]"),i="created"===e?"is ".concat(e,"."):"is ".concat(e,", current queue ").concat(this.locks,". ").concat(null!=t?t:"");pP.debug("".concat(n," ").concat(i))}setId(e){this.id=e}get isLocked(){return this.locks>0}lock(e){let t;this.locks+=1,this.logger("locked",e);const n=new dp((n=>{t=()=>{this.locks-=1,this.logger("unlocked",e),n()}})),i=this.lockingPromise.then((()=>t));return this.lockingPromise=this.lockingPromise.then((()=>n)),i}};function EP(e,t){return function(n,i,r){const o=r.value;if("function"!=typeof o)throw new Error("Cannot use mutex on object property.");return r.value=async function(){const n=this[t];if(!n)throw new Error("mutex property key ".concat(t," doesn't exist on ").concat(e));const r=await n.lock("From ".concat(e,".").concat(i));try{for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return await o.apply(this,a)}finally{r()}},r}}const mP={timeout:500,timeoutFactor:1.5,maxRetryCount:1/0,maxRetryTimeout:1e4};function fP(e,t){const n=Math.floor(t.timeout*Math.pow(t.timeoutFactor,e));return Math.min(t.maxRetryTimeout,n)}function gP(e,t,n,i){const r=Object.assign({},mP,i);let o=r.timeout;const s=async()=>{await function(e){return new dp((t=>{window.setTimeout(t,e)}))}(o),o*=r.timeoutFactor,o=Math.min(r.maxRetryTimeout,o)};let a=!1;const c=new dp((async(i,o)=>{t=t||(()=>!1),n=n||(()=>!0);for(let c=0;c<r.maxRetryCount;c+=1){if(a)return o(new zN(JN.OPERATION_ABORTED));try{const n=await e();if(!t(n,c))return i(n);if(c+1===r.maxRetryCount)return i(n);await s()}catch(e){if(!n(e,c))return o(e);if(c+1===r.maxRetryCount)return o(e);await s()}}}));return c.cancel=()=>a=!0,c}let SP,TP=class{constructor(e){KN(this,"input",[]),KN(this,"size",void 0),this.size=e}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}mean(){var e;return 0===this.input.length?0:ar(e=this.input).call(e,((e,t)=>e+t))/this.input.length}},RP=0,vP=0;function yP(e,t,n,i){return new dp(((r,o)=>{t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),RP+=ZD(t.data)):n&&(t.data.size?RP+=t.data.size:t.data instanceof FormData?RP+=qD(t.data):RP+=ZD(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,QO.request(t).then((e=>{"string"==typeof e.data?vP+=ZD(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?vP+=e.data.byteLength:vP+=ZD(JSON.stringify(e.data)),i&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{QO.isCancel(e)?o(new zN(JN.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new zN(JN.NETWORK_TIMEOUT,e.message)):e.response?o(new zN(JN.NETWORK_RESPONSE_ERROR,e.response.status)):o(new zN(JN.NETWORK_ERROR,e.message))}))}))}async function bP(e,t){const n=new Blob([t.data],{type:"buffer"});return await yP(e,YN(YN({},t),{},{data:n,headers:{"Content-Type":"application/octet-stream"}}),!0)}const CP=()=>void 0!==window.isSecureContext;function IP(e){if(Array.isArray(e))return e.map((e=>e));if(!AP(e))return e;const t={};for(const n in e){const i=e[n];AP(i)||Array.isArray(i)?t[n]=IP(i):t[n]=i}return t}function AP(e){return!("object"!=typeof e||Array.isArray(e)||!e)}let wP=class{constructor(e){KN(this,"input",[]),KN(this,"size",void 0),this.size=e}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}diffMean(){return 0===this.input.length?0:(this.input[this.input.length-1]-this.input[0])/this.input.length}};const OP={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},NP={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],transport:{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0},selectedCandidatePair:{id:"unknown",localCandidate:OP,remoteCandidate:OP},updateInterval:0},DP={firsCount:0,nacksCount:0,plisCount:0,framesDecodeCount:0,framesDecodeInterval:0,framesDecodeFreezeTime:0,decodeFrameRate:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,qpSumPerFrame:0,framesDroppedCount:0,outputFrameRate:0,packetsDiscarded:0,framesAssembledFromMultiplePackets:0,totalProcessingDelay:0,avgDecodeMs:0,avgFramesAssembledFromMultiplePacketsMs:0,avgProcessingDelayMs:0,avgInterFrameDelayMs:0,totalAssemblyTime:0},PP={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},LP={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},kP={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packetsDiscarded:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0,totalSamplesReceived:0,silentConcealedSamples:0,concealmentEvents:0,freezeMs80:0,freezeMs200:0,freezeSamples80:0,freezeSamples200:0};let MP=class{constructor(e,t){KN(this,"onFirstVideoReceived",void 0),KN(this,"onFirstVideoDecoded",void 0),KN(this,"onFirstAudioReceived",void 0),KN(this,"onFirstVideoDecodedTimeout",void 0),KN(this,"onFirstAudioDecoded",void 0),KN(this,"onSelectedLocalCandidateChanged",void 0),KN(this,"onSelectedRemoteCandidateChanged",void 0),KN(this,"videoIsReady",!1),KN(this,"videoIsReady2",{}),KN(this,"pc",void 0),KN(this,"options",void 0),KN(this,"intervalTimer",void 0),KN(this,"stats",IP(NP)),KN(this,"isFirstVideoReceived",{}),KN(this,"isFirstVideoDecoded",{}),KN(this,"isFirstAudioReceived",{}),KN(this,"isFirstAudioDecoded",{}),KN(this,"isFirstVideoDecodedTimeout",{}),KN(this,"lossRateWindowStats",[]),this.pc=e,this.options=t,this.intervalTimer=window.setInterval((async()=>{this.updateStats()}),this.options.updateInterval)}getStats(){return this.stats}getSelectedCandidatePair(){return new dp((e=>{e({local:YN({},OP),remote:YN({},OP)})}))}setVideoIsReady(e){this.videoIsReady=e}setVideoIsReady2(e,t){this.videoIsReady2[e]=t}getVideoIsReady(e){return this.videoIsReady2[e]||!1}setIsFirstAudioDecoded(e){}destroy(){window.clearInterval(this.intervalTimer),this.pc=void 0}calcLossRate(e){this.lossRateWindowStats.push(e),this.lossRateWindowStats.length>this.options.lossRateInterval&&this.lossRateWindowStats.splice(0,1);const t=this.lossRateWindowStats.length,n=["videoSend","audioSend","videoRecv","audioRecv"];let i=0,r=0,o=0,s=0;for(const a of n)e[a].forEach(((e,n)=>{if(!this.lossRateWindowStats[t-1][a][n]||!this.lossRateWindowStats[0][a][n])return;const c=this.lossRateWindowStats[t-1][a][n].packets-this.lossRateWindowStats[0][a][n].packets,d=this.lossRateWindowStats[t-1][a][n].packetsLost-this.lossRateWindowStats[0][a][n].packetsLost;"videoSend"===a||"audioSend"===a?(i+=c,o+=d):(r+=c,s+=d),Number.isNaN(c)||Number.isNaN(c)?e.packetLostRate=0:e.packetLostRate=c<=0||d<=0?0:d/(c+d)}));e.sendPacketLossRate=i<=0||o<=0?0:o/(i+o),e.recvPacketLossRate=r<=0||s<=0?0:s/(r+s)}},UP=class extends MP{constructor(){super(...arguments),KN(this,"_stats",NP),KN(this,"lastDecodeVideoReceiverStats",new Map)}async updateStats(){const e=await this._getStats(),t=this.statsResponsesToObjects(e);this._stats=IP(NP);const n=t.filter((e=>"ssrc"===e.type));this.processSSRCStats(n);const i=t.find((e=>"VideoBwe"===e.type));i&&this.processBandwidthStats(i),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}processBandwidthStats(e){this._stats.bitrate={actualEncoded:Number(e.googActualEncBitrate),targetEncoded:Number(e.googTargetEncBitrate),retransmit:Number(e.googRetransmitBitrate),transmit:Number(e.googTransmitBitrate)},this._stats.sendBandwidth=Number(e.googAvailableSendBandwidth)}processSSRCStats(e){e.forEach((e=>{var t;const n=Vi(t=e.id).call(t,"send");switch("".concat(e.mediaType,"_").concat(n?"send":"recv")){case"video_send":{const t=IP(PP);t.codec=e.googCodecName,t.adaptionChangeReason="none",e.googCpuLimitedResolution&&(t.adaptionChangeReason="cpu"),e.googBandwidthLimitedResolution&&(t.adaptionChangeReason="bandwidth"),t.avgEncodeMs=Number(e.googAvgEncodeMs),t.inputFrame={width:Number(e.googFrameWidthInput)||Number(e.googFrameWidthSent),height:Number(e.googFrameHeightInput)||Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.sentFrame={width:Number(e.googFrameWidthSent),height:Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.firsCount=Number(e.googFirReceived),t.nacksCount=Number(e.googNacksReceived),t.plisCount=Number(e.googPlisReceived),t.frameCount=Number(e.framesEncoded),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.videoSend.push(t),this._stats.rtt=t.rttMs;break}case"video_recv":{const t=IP(DP),n=this.lastDecodeVideoReceiverStats.get(Number(e.ssrc));if(t.codec=e.googCodecName,t.targetDelayMs=Number(e.googTargetDelayMs),t.renderDelayMs=Number(e.googRenderDelayMs),t.currentDelayMs=Number(e.googCurrentDelayMs),t.minPlayoutDelayMs=Number(e.googMinPlayoutDelayMs),t.decodeMs=Number(e.googDecodeMs),t.maxDecodeMs=Number(e.googMaxDecodeMs),t.receivedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateReceived)},t.decodedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateDecoded)},t.decodeFrameRate=Number(e.googFrameRateDecoded),t.outputFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateOutput)},t.jitterBufferMs=Number(e.googJitterBufferMs),t.firsCount=Number(e.googFirsSent),t.nacksCount=Number(e.googNacksSent),t.plisCount=Number(e.googPlisSent),t.framesDecodeCount=Number(e.framesDecoded),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]&&(this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,t.decodedFrame.width,t.decodedFrame.height),this.isFirstVideoDecoded[t.ssrc]=!0),n){const i=n.stats,r=Date.now()-n.lts;t.framesDecodeFreezeTime=i.framesDecodeFreezeTime,t.framesDecodeInterval=i.framesDecodeInterval,t.framesDecodeCount>i.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(n.lts=Date.now(),t.framesDecodeInterval=r,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc,10))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount<n.stats.framesDecodeCount&&(t.framesDecodeInterval=0)}this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:YN({},t),lts:Date.now()}),this._stats.videoRecv.push(t);break}case"audio_recv":{const t=IP(kP);t.codec=e.googCodecName,t.outputLevel=Math.abs(Number(e.audioOutputLevel))/32767,t.decodingCNG=Number(e.googDecodingCNG),t.decodingCTN=Number(e.googDecodingCTN),t.decodingCTSG=Number(e.googDecodingCTSG),t.decodingNormal=Number(e.googDecodingNormal),t.decodingPLC=Number(e.googDecodingPLC),t.decodingPLCCNG=Number(e.googDecodingPLCCNG),t.expandRate=Number(e.googExpandRate),t.accelerateRate=Number(e.googAccelerateRate),t.preemptiveExpandRate=Number(e.googPreemptiveExpandRate),t.secondaryDecodedRate=Number(e.googSecondaryDecodedRate),t.speechExpandRate=Number(e.googSpeechExpandRate),t.preferredJitterBufferMs=Number(e.googPreferredJitterBufferMs),t.jitterBufferMs=Number(e.googJitterBufferMs),t.jitterMs=Number(e.googJitterReceived),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.receivedFrames=Number(e.googDecodingCTN)||Number(e.packetsReceived),t.droppedFrames=Number(e.googDecodingPLC)+Number(e.googDecodingPLCCNG)||Number(e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.decodingNormal>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),this._stats.audioRecv.push(t);break}case"audio_send":{const t=IP(LP);t.codec=e.googCodecName,t.inputLevel=Math.abs(Number(e.audioInputLevel))/32767,t.aecReturnLoss=Number(e.googEchoCancellationReturnLoss||0),t.aecReturnLossEnhancement=Number(e.googEchoCancellationReturnLossEnhancement||0),t.residualEchoLikelihood=Number(e.googResidualEchoLikelihood||0),t.residualEchoLikelihoodRecentMax=Number(e.googResidualEchoLikelihoodRecentMax||0),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.rtt=t.rttMs,this._stats.audioSend.push(t);break}}}))}_getStats(){return new dp(((e,t)=>{this.pc.getStats(e,t)}))}statsResponsesToObjects(e){const t=[];return e.result().forEach((e=>{const n={id:e.id,timestamp:e.timestamp.valueOf().toString(),type:e.type};e.names().forEach((t=>{n[t]=e.stat(t)})),t.push(n)})),t}},VP=function(e){return e.BANDWIDTH="bandwidth",e.CPU="cpu",e.NONE="none",e.OTHER="other",e}({}),xP=function(e){return e.L1T1="L1T1",e.L1T2="L1T2",e.L1T3="L1T3",e.L1T3_KEY="L1T3_KEY",e.L2T1_KEY="L2T1_KEY",e.L2T2_KEY="L2T2_KEY",e.L2T3_KEY="L2T3_KEY",e.L3T1_KEY="L3T1_KEY",e.L3T2_KEY="L3T2_KEY",e.L3T3_KEY="L3T3_KEY",e}({}),FP=function(e){return e[e.new=0]="new",e[e.connecting=1]="connecting",e[e.connected=2]="connected",e[e.disconnected=3]="disconnected",e[e.failed=4]="failed",e[e.closed=5]="closed",e}({}),BP=function(e){return e.CERTIFICATE="certificate",e.CODEC="codec",e.CANDIDATE_PAIR="candidate-pair",e.LOCAL_CANDIDATE="local-candidate",e.REMOTE_CANDIDATE="remote-candidate",e.INBOUND="inbound-rtp",e.TRACK="track",e.OUTBOUND="outbound-rtp",e.PC="peer-connection",e.REMOTE_INBOUND="remote-inbound-rtp",e.REMOTE_OUTBOUND="remote-outbound-rtp",e.TRANSPORT="transport",e.CSRC="csrc",e.DATA_CHANNEL="data-channel",e.STREAM="stream",e.SENDER="sender",e.RECEIVER="receiver",e}({});var jP=function(e){return e[e.kNone=1]="kNone",e[e.kMillisecondsFromSeconds=1e3]="kMillisecondsFromSeconds",e[e.kBytesToBits=8]="kBytesToBits",e}(jP||{});function GP(e,t,n,i){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:jP.kNone;if(!t)return;const o=Number(t[n]);if("number"!=typeof o)return;const s=Number(t[i]);if("number"!=typeof s)return;if(!e)return s?o/s*r:void 0;const a=Number(e[n]);if("number"!=typeof a)return;const c=Number(e[i]);if("number"!=typeof c)return;const d=s-c;return d?(o-a)/d*r:void 0}let WP=class extends MP{constructor(){super(...arguments),KN(this,"_stats",NP),KN(this,"report",void 0),KN(this,"lastDecodeVideoReceiverStats",new Map),KN(this,"lastVideoFramesRecv",new Map),KN(this,"lastVideoFramesSent",new Map),KN(this,"lastVideoFramesDecode",new Map),KN(this,"lastVideoFramesOutput",new Map),KN(this,"lastVideoJBDelay",new Map),KN(this,"lastAudioJBDelay",new Map),KN(this,"mediaBytesSent",new Map),KN(this,"mediaBytesRetransmit",new Map),KN(this,"mediaBytesTargetEncode",new Map),KN(this,"lastDecodeAudioReceiverStats",new Map),KN(this,"lastAudioConcealment",new Map),KN(this,"lastEncoderMs",new Map)}async updateStats(){this.report=await this.pc.getStats(),this._stats=IP(NP),this.report.forEach((e=>{switch(e.type){case BP.OUTBOUND:case BP.INBOUND:{const t=e.mediaType||e.kind,n=!t&&"frameWidth"in e,i=!t&&!("frameWidth"in e);e.type===BP.OUTBOUND?"audio"===t||i?this.processAudioOutboundStats(e):("video"===t||n)&&this.processVideoOutboundStats(e):e.type===BP.INBOUND&&("audio"===t||i?this.processAudioInboundStats(e):("video"===t||n)&&this.processVideoInboundStats(e));break}case BP.TRANSPORT:{this.processTransportStats(e);const t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break}case BP.CANDIDATE_PAIR:e.selected&&this.processCandidatePairStats(e)}})),this.updateSendBitrate(),this._stats.updateInterval=Date.now()-this.stats.timestamp,this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}async getSelectedCandidatePair(){const e=await this.pc.getStats(),t={local:YN({},OP),remote:YN({},OP)};return e.forEach((n=>{let i;if(n.type===BP.TRANSPORT&&(i=e.get(n.selectedCandidatePairId)),n.type===BP.CANDIDATE_PAIR&&n.selected&&(i=n),i){const n=(e,t)=>{e.type=t.type,e.id=t.id,t.address&&(e.address=t.address),t.candidateType&&(e.candidateType=t.candidateType),t.port&&(e.port=t.port),t.priority&&(e.priority=t.priority),t.protocol&&(e.protocol=t.protocol),t.relayProtocol&&(e.relayProtocol=t.relayProtocol)};if(i.localCandidateId){const r=e.get(i.localCandidateId);r&&n(t.local,r)}if(i.remoteCandidateId){const r=e.get(i.remoteCandidateId);r&&n(t.remote,r)}}})),t}processCandidatePairStats(e){if(this._stats.sendBandwidth=e.availableOutgoingBitrate||0,e.currentRoundTripTime&&(this._stats.rtt=1e3*e.currentRoundTripTime),this._stats.videoSend.forEach((t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)})),this._stats.audioSend.forEach((t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)})),this._stats.selectedCandidatePair.id=e.id,e.localCandidateId){const t=this.report.get(e.localCandidateId);t&&this.processCandidateStats(t)}if(e.remoteCandidateId){const t=this.report.get(e.remoteCandidateId);t&&this.processCandidateStats(t)}}processCandidateStats(e){let t;e.type===BP.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===BP.REMOTE_CANDIDATE&&(t=this._stats.selectedCandidatePair.remoteCandidate),t&&(t.type=e.type,t.id=e.id,e.address&&(t.address=e.address),e.candidateType&&(t.candidateType=e.candidateType),e.port&&(t.port=e.port),e.priority&&(t.priority=e.priority),e.protocol&&(t.protocol=e.protocol),e.relayProtocol&&(t.relayProtocol=e.relayProtocol),e.type===BP.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(YN({},t),YN({},this.stats.selectedCandidatePair.localCandidate)),e.type===BP.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(YN({},t),YN({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(e){let t=this._stats.audioRecv.find((t=>t.ssrc===e.ssrc));t||(t=IP(kP),this._stats.audioRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.packetsDiscarded=e.packetsDiscarded,t.bytes=e.bytesReceived,t.jitterMs=1e3*e.jitter,t.retransmittedBytesReceived=e.retransmittedBytesReceived,t.retransmittedPacketsReceived=e.retransmittedPacketsReceived,t.totalProcessingDelay=e.totalProcessingDelay,t.jitterBufferEmittedCount=e.jitterBufferEmittedCount,t.estimatedPlayoutTimestamp=e.estimatedPlayoutTimestamp;const n=this.lastDecodeAudioReceiverStats.get(t.ssrc);t.avgProcessingDelayMs=GP(n,t,"totalProcessingDelay","jitterBufferEmittedCount",jP.kMillisecondsFromSeconds),this.processAudioTrackReceiverStats(e,e.trackId,t),this.calculateAudioFreeze(t,n,e),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),t.receivedFrames||(t.receivedFrames=e.packetsReceived),t.droppedFrames||(t.droppedFrames=e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.outputLevel&&t.outputLevel>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),"number"==typeof e.concealedSamples&&(t.concealedSamples=e.concealedSamples),this.lastDecodeAudioReceiverStats.set(t.ssrc,YN({},t))}calculateAudioFreeze(e,t,n){const i=this.lastAudioConcealment.get(e.ssrc);if(null!=t&&null!=i){const r=i.lts,o=n.timestamp,s=o-r;if(s<=0)return;const a=e.concealedSamples-t.concealedSamples-0,c=i.nonSilent+a,d=e.totalSamplesReceived-t.totalSamplesReceived;if(d<=0)return;const l=80*d/s,u=200*d/s,h=s/d;let p=0;e.freezeSamples80=t.freezeSamples80,e.freezeMs80=t.freezeMs80,c>l&&(i.plc80>0?(e.freezeSamples80+=a,e.freezeMs80+=Math.round(a*h)):(e.freezeSamples80+=c,e.freezeMs80+=Math.round(c*h)),p=i.plc80+1);let _=0;e.freezeSamples200=t.freezeSamples200,e.freezeMs200=t.freezeMs200,c>u&&(i.plc200>0?(e.freezeSamples200+=a,e.freezeMs200+=Math.round(a*h)):(e.freezeSamples200+=c,e.freezeMs200+=Math.round(c*h)),_=i.plc200+1),this.lastAudioConcealment.set(e.ssrc,{nonSilent:a,lts:o,plc80:p,plc200:_})}else e.freezeSamples80=0,e.freezeSamples200=0,e.freezeMs80=0,e.freezeMs200=0,this.lastAudioConcealment.set(e.ssrc,{nonSilent:0,lts:n.timestamp,plc80:0,plc200:0})}processVideoInboundStats(e){let t=this._stats.videoRecv.find((t=>t.ssrc===e.ssrc));t||(t=IP(DP),this._stats.videoRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.framesDecodeCount=e.framesDecoded,t.framesDroppedCount=e.framesDropped,t.totalInterFrameDelay=e.totalInterFrameDelay,t.totalSquaredInterFrameDelay=e.totalSquaredInterFrameDelay,t.totalFreezesDuration=e.totalFreezesDuration,t.totalProcessingDelay=e.totalProcessingDelay,t.packetsDiscarded=e.packetsDiscarded,t.framesAssembledFromMultiplePackets=e.framesAssembledFromMultiplePackets,t.totalAssemblyTime=e.totalAssemblyTime,t.keyFramesDecoded=e.keyFramesDecoded,t.retransmittedBytesReceived=e.retransmittedBytesReceived,t.retransmittedPacketsReceived=e.retransmittedPacketsReceived,t.estimatedPlayoutTimestamp=e.estimatedPlayoutTimestamp;const n=this.lastDecodeVideoReceiverStats.get(t.ssrc),i=this.lastVideoFramesDecode.get(t.ssrc),r=this.lastVideoFramesOutput.get(t.ssrc),o=Date.now();if(t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]){const e=t.decodedFrame?t.decodedFrame.width:0,n=t.decodedFrame?t.decodedFrame.height:0;this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,e,n),this.isFirstVideoDecoded[t.ssrc]=!0}if(n){const i=n.stats,r=o-n.lts;t.framesDecodeFreezeTime=i.framesDecodeFreezeTime,t.framesDecodeInterval=i.framesDecodeInterval,!this.isFirstVideoDecoded[t.ssrc]&&r>this.options.firstVideoDecodedTimeout&&!this.isFirstVideoDecodedTimeout[t.ssrc]&&(this.onFirstVideoDecodedTimeout&&this.onFirstVideoDecodedTimeout(t.ssrc),this.isFirstVideoDecodedTimeout[t.ssrc]=!0),t.framesDecodeCount>i.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(n.lts=Date.now(),t.framesDecodeInterval=r,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount<i.framesDecodeCount&&(t.framesDecodeInterval=0),e.framesDecoded&&e.qpSum&&(n.stats.framesDecodeCount>e.framesDecoded?t.qpSumPerFrame=e.qpSum/e.framesDecoded:t.qpSumPerFrame=(e.qpSum-n.qpSum)/(e.framesDecoded-n.stats.framesDecodeCount))}e.totalDecodeTime&&(t.decodeMs=1e3*e.totalDecodeTime,t.avgDecodeMs=GP(null==n?void 0:n.stats,t,"decodeMs","framesDecodeCount")),t.avgProcessingDelayMs=GP(null==n?void 0:n.stats,t,"totalProcessingDelay","framesDecodeCount",jP.kMillisecondsFromSeconds),t.avgFramesAssembledFromMultiplePacketsMs=GP(null==n?void 0:n.stats,t,"totalAssemblyTime","framesAssembledFromMultiplePackets",jP.kMillisecondsFromSeconds),t.avgInterFrameDelayMs=GP(null==n?void 0:n.stats,t,"totalInterFrameDelay","framesDecodeCount",jP.kMillisecondsFromSeconds),i&&o-i.lts>=800?(t.decodeFrameRate=Math.round((t.framesDecodeCount-i.count)/((o-i.lts)/1e3)),this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:t.decodeFrameRate})):i?t.decodeFrameRate=i.rate:this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:0}),t.framesDroppedCount&&e.framesReceived&&(r&&o-r.lts>=800?(t.outputFrameRate=Math.round((e.framesReceived-t.framesDroppedCount-r.count)/((o-r.lts)/1e3)),this.lastVideoFramesOutput.set(t.ssrc,{count:e.framesReceived-t.framesDroppedCount,lts:o,rate:Math.max(t.outputFrameRate,0)})):r?t.outputFrameRate=r.rate:this.lastVideoFramesOutput.set(t.ssrc,{count:e.framesReceived-t.framesDroppedCount,lts:o,rate:0})),this.processVideoTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),"boolean"==typeof e.powerEfficientDecoder&&(t.powerEfficientDecoder=e.powerEfficientDecoder?1:0),e.framerateMean&&(t.framesRateFirefox=e.framerateMean),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:YN({},t),lts:n?n.lts:Date.now(),qpSum:e.qpSum})}processVideoOutboundStats(e){let t=this._stats.videoSend.find((t=>t.ssrc===e.ssrc));t||(t=IP(PP),this._stats.videoSend.push(t));const n=this.mediaBytesSent.get(e.ssrc);if(n)n.add(e.bytesSent);else{const t=new wP(10);t.add(e.bytesSent),this.mediaBytesSent.set(e.ssrc,t)}if(void 0!==e.retransmittedBytesSent){const t=this.mediaBytesRetransmit.get(e.ssrc);if(t)t.add(e.retransmittedBytesSent);else{const t=new wP(10);t.add(e.retransmittedBytesSent),this.mediaBytesRetransmit.set(e.ssrc,t)}}if(e.totalEncodedBytesTarget){const t=this.mediaBytesTargetEncode.get(e.ssrc);if(t)t.add(e.totalEncodedBytesTarget);else{const t=new wP(10);t.add(e.totalEncodedBytesTarget),this.mediaBytesTargetEncode.set(e.ssrc,t)}}if(t.ssrc=e.ssrc,t.bytes=e.bytesSent,t.packets=e.packetsSent,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.frameCount=e.framesEncoded,t.adaptionChangeReason=e.qualityLimitationReason,t.scalabilityMode=e.scalabilityMode,t.retransmittedBytesSent=e.retransmittedBytesSent,t.retransmittedPacketsSent=e.retransmittedPacketsSent,t.hugeFramesSent=e.hugeFramesSent,t.keyFramesEncoded=e.keyFramesEncoded,t.targetBitrate=e.targetBitrate,e.totalEncodeTime&&e.framesEncoded){const n=this.lastEncoderMs.get(e.ssrc);if(!n||n.lastFrameCount>e.framesEncoded)t.avgEncodeMs=1e3*e.totalEncodeTime/e.framesEncoded;else{const i=e.framesEncoded-n.lastFrameCount,r=e.totalEncodeTime-n.lastEncoderTime;t.avgEncodeMs=1e3*r/i}}if(e.framesEncoded&&e.qpSum){const n=this.lastEncoderMs.get(e.ssrc);!n||n.lastFrameCount>e.framesEncoded?t.qpSumPerFrame=e.qpSum/e.framesEncoded:t.qpSumPerFrame=(e.qpSum-n.lastQpSum)/(e.framesEncoded-n.lastFrameCount)}if(this.lastEncoderMs.set(e.ssrc,{lastFrameCount:e.framesEncoded,lastEncoderTime:e.totalEncodeTime,lastQpSum:e.qpSum,lts:Date.now()}),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),"boolean"==typeof e.powerEfficientEncoder&&(t.powerEfficientEncoder=e.powerEfficientEncoder?1:0),e.mediaSourceId&&this.processVideoMediaSource(e.mediaSourceId,t),this.processVideoTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const n=this.findRemoteStatsId(e.ssrc,BP.REMOTE_INBOUND);n&&this.processRemoteInboundStats(n,t)}}processAudioOutboundStats(e){let t=this._stats.audioSend.find((t=>t.ssrc===e.ssrc));if(t||(t=IP(LP),this._stats.audioSend.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsSent,t.bytes=e.bytesSent,t.retransmittedBytesSent=e.retransmittedBytesSent,t.retransmittedPacketsSent=e.retransmittedPacketsSent,e.mediaSourceId&&this.processAudioMediaSource(e.mediaSourceId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),this.processAudioTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const n=this.findRemoteStatsId(e.ssrc,BP.REMOTE_INBOUND);n&&this.processRemoteInboundStats(n,t)}}processTransportStats(e){this._stats.transport.bytesReceived=e.bytesReceived||this._stats.transport.bytesReceived,this._stats.transport.bytesSent=e.bytesSent||this._stats.transport.bytesSent,this._stats.transport.packetsReceived=e.packetsReceived||this._stats.transport.packetsReceived,this._stats.transport.packetsSent=e.packetsSent||this._stats.transport.packetsSent}findRemoteStatsId(e,t){var n;const i=Array.from(gp(n=this.report).call(n)).find((n=>n.type===t&&n.ssrc===e));return i?i.id:null}processVideoMediaSource(e,t){const n=this.report.get(e);n&&n.width&&n.height&&n.framesPerSecond&&(t.inputFrame={width:n.width,height:n.height,frameRate:n.framesPerSecond})}processAudioMediaSource(e,t){const n=this.report.get(e);n&&(t.inputLevel=n.audioLevel)}processVideoTrackSenderStats(e,t,n){var i,r,o,s;const a=t?this.report.get(t):void 0,c=null!==(i=null==a?void 0:a.framesSent)&&void 0!==i?i:e.framesSent;if("number"!=typeof c)return;let d=null!==(r=null==a?void 0:a.frameWidth)&&void 0!==r?r:e.frameWidth,l=null!==(o=null==a?void 0:a.frameHeight)&&void 0!==o?o:e.frameHeight,u=null!==(s=null==a?void 0:a.framesPerSecond)&&void 0!==s?s:e.framesPerSecond;if("number"==typeof d&&"number"==typeof l||(d=0,l=0),null==u){const e=Date.now(),t=this.lastVideoFramesSent.get(n.ssrc);t&&e-t.lts>=800?(u=Math.round((c-t.count)/((e-t.lts)/1e3)),this.lastVideoFramesSent.set(n.ssrc,{count:c,lts:e,rate:u})):t?u=t.rate:this.lastVideoFramesSent.set(n.ssrc,{count:c,lts:e,rate:0})}n.sentFrame={width:d,height:l,frameRate:Math.max(0,u)}}processVideoTrackReceiverStats(e,t,n){var i,r,o,s,a;const c=t?this.report.get(t):void 0,d=null!==(i=null==c?void 0:c.framesReceived)&&void 0!==i?i:e.framesReceived,l=null!==(r=null==c?void 0:c.frameWidth)&&void 0!==r?r:e.frameWidth,u=null!==(o=null==c?void 0:c.frameHeight)&&void 0!==o?o:e.frameHeight,h=null!==(s=null==c?void 0:c.jitterBufferDelay)&&void 0!==s?s:e.jitterBufferDelay,p=null!==(a=null==c?void 0:c.jitterBufferEmittedCount)&&void 0!==a?a:e.jitterBufferEmittedCount;if("number"==typeof d){const e=this.lastVideoFramesRecv.get(n.ssrc),t=Date.now();n.framesReceivedCount=d;let i=0;e&&t-e.lts>=800?(i=Math.round((d-e.count)/((t-e.lts)/1e3)),this.lastVideoFramesRecv.set(n.ssrc,{count:d,lts:t,rate:i})):e?i=e.rate:this.lastVideoFramesRecv.set(n.ssrc,{count:d,lts:t,rate:0}),n.receivedFrame={width:l||0,height:u||0,frameRate:i||0},n.decodedFrame={width:l||0,height:u||0,frameRate:n.decodeFrameRate||0},n.outputFrame={width:l||0,height:u||0,frameRate:n.outputFrameRate||n.decodeFrameRate||0}}if(h&&p){const e=this.lastVideoJBDelay.get(n.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const i=p-e.jitterBufferEmittedCount;i>0&&(t=1e3*(h-e.jitterBufferDelay)/i),n.jitterBufferMs=t,n.currentDelayMs=Math.round(t),this.lastVideoJBDelay.set(n.ssrc,{jitterBufferDelay:h,jitterBufferEmittedCount:p,jitterBufferMs:n.currentDelayMs})}}processAudioTrackSenderStats(e,t,n){var i,r,o,s;const a=t?this.report.get(t):void 0,c=null!==(i=null!==(r=null==a?void 0:a.echoReturnLoss)&&void 0!==r?r:e.echoReturnLoss)&&void 0!==i?i:0,d=null!==(o=null!==(s=null==a?void 0:a.echoReturnLossEnhancement)&&void 0!==s?s:e.echoReturnLossEnhancement)&&void 0!==o?o:0;n.aecReturnLoss=c,n.aecReturnLossEnhancement=d}processAudioTrackReceiverStats(e,t,n){var i,r,o,s,a,c,d,l,u;const h=t?this.report.get(t):void 0,p=null!==(i=null==h?void 0:h.removedSamplesForAcceleration)&&void 0!==i?i:e.removedSamplesForAcceleration,_=null!==(r=null==h?void 0:h.totalSamplesReceived)&&void 0!==r?r:e.totalSamplesReceived,E=null!==(o=null==h?void 0:h.jitterBufferDelay)&&void 0!==o?o:e.jitterBufferDelay,m=null!==(s=null==h?void 0:h.jitterBufferEmittedCount)&&void 0!==s?s:e.jitterBufferEmittedCount,f=null!==(a=null==h?void 0:h.audioLevel)&&void 0!==a?a:null==e?void 0:e.audioLevel,g=null!==(c=null==h?void 0:h.totalSamplesDuration)&&void 0!==c?c:null==e?void 0:e.totalSamplesDuration,S=null!==(d=null==h?void 0:h.concealedSamples)&&void 0!==d?d:e.concealedSamples,T=null!==(l=null==h?void 0:h.silentConcealedSamples)&&void 0!==l?l:e.silentConcealedSamples,R=null!==(u=null==h?void 0:h.concealmentEvents)&&void 0!==u?u:e.concealmentEvents;if("number"==typeof _&&(n.totalSamplesReceived=_),"number"==typeof T&&(n.silentConcealedSamples=T),"number"==typeof R&&(n.concealmentEvents=R),"number"==typeof S&&(n.concealedSamples=S),p&&_&&(n.accelerateRate=p/_),E&&m){const e=this.lastAudioJBDelay.get(n.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const i=m-e.jitterBufferEmittedCount;i>0&&(t=1e3*(E-e.jitterBufferDelay)/i),n.jitterBufferMs=Math.round(t),this.lastAudioJBDelay.set(n.ssrc,{jitterBufferDelay:E,jitterBufferEmittedCount:m,jitterBufferMs:n.jitterBufferMs})}n.outputLevel=f;let v=1920;g&&_&&(v=_/g/50,n.receivedFrames=Math.round(_/v)),S&&(n.droppedFrames=Math.round(S/v))}processRemoteInboundStats(e,t){const n=this.report.get(e);n&&(t.packetsLost=n.packetsLost,n.roundTripTime&&(t.rttMs=1e3*n.roundTripTime),n.jitter&&(t.jitterMs=1e3*n.jitter),n.timestamp&&(t.timestamp=n.timestamp))}getCodecFromCodecStats(e){const t=this.report.get(e);if(!t)return"";const n=t.mimeType.match(/\/(.*)$/);return n&&n[1]?n[1]:""}updateSendBitrate(){let e=0,t=null,n=null;this.mediaBytesSent.forEach((t=>{e+=t.diffMean()})),this.mediaBytesRetransmit.forEach((e=>{t=null===t?e.diffMean():t+e.diffMean()})),this.mediaBytesTargetEncode.forEach((e=>{n=null===n?e.diffMean():n+e.diffMean()}));const i=null!==t?e-t:e;this._stats.bitrate={actualEncoded:8*i/(this.options.updateInterval/1e3),transmit:8*e/(this.options.updateInterval/1e3)},null!==t&&(this._stats.bitrate.retransmit=8*t/(this.options.updateInterval/1e3)),null!==n&&(this._stats.bitrate.targetEncoded=8*n/(this.options.updateInterval/1e3))}},KP=class extends MP{updateStats(){return dp.resolve()}};function HP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:250,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:500,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1e4;const o=function(){const e=navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]*/i);return e&&e[0]?Number(e[0].split("/")[1]):null}();return o?o<76?new UP(e,{updateInterval:t,lossRateInterval:n,freezeRateLimit:i,firstVideoDecodedTimeout:r}):new WP(e,{updateInterval:t,lossRateInterval:n,freezeRateLimit:i,firstVideoDecodedTimeout:r}):function(e){if(!window.RTCStatsReport)return!1;const t=e.getStats();return!!(t instanceof dp||function(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}(t))}(e)?new WP(e,{updateInterval:t,lossRateInterval:n,freezeRateLimit:i,firstVideoDecodedTimeout:r}):new KP(e,{updateInterval:t,lossRateInterval:n,freezeRateLimit:i,firstVideoDecodedTimeout:r})}const YP="websdk_ng_install_id";function XP(){try{if(rL("INSTALL_ID"))return rL("INSTALL_ID");let e=window.localStorage.getItem(YP);return e||(e=tP(),window.localStorage.setItem(YP,e)),iL("INSTALL_ID",e),e}catch(e){return}}const JP=function(e){if(e.match(/[0-9]+\.[0-9]+\.[0-9]+$/))return e;const t=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-([0-9]+)/);if(t&&t[1]&&t[2]){const e=t[1],n=t[2];return"".concat(e,".").concat(n)}return"4.0.0.999"}("4.24.4"),zP=function(){try{return!0===JSON.parse("true")}catch(e){return!0}}();let ZP=function(e){return e.Default="default",e.Auto="auto",e.Relay="relay",e.SdRtn="sd-rtn",e}({});const qP=function(){const e="us".concat("erna","me"),t="pa".concat("sswo","rd"),n=["t","s","t"];n.splice(1,0,"e");const i=n.join(""),r=[];for(let e=0;e<6;e++)r.push("1");const o=r.join(""),s={};return s[e]=i,s[t]=o,Object.assign(s,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=qP;const QP={ENABLE_PUBLISHED_USER_LIST:!0,ENABLE_USER_LIST:!1,MAX_SUBSCRIPTION:50,SUBSCRIBE_AUDIO_FILTER_TOPN:void 0,ENABLE_PUBLISH_AUDIO_FILTER:void 0,ENABLE_USER_LICENSE_CHECK:!0,DISABLE_FEC:void 0,ENABLE_NTP_REPORT:!1,ENABLE_INSTANT_VIDEO:!1,ENABLE_USER_AUTO_REBALANCE_CHECK:!0,ENABLE_LOSSBASED_BWE:!0,ENABLE_AUT_CC:!0,FORCE_ENABLE_AUT_CC:!1,ENABLE_CC_FALLBACK:void 0,SUBSCRIBE_TWCC:!0,PUBLISH_TWCC:!1,ENABLE_SVC_DEFAULT_CODECS:["H264","VP8","VP9","AV1"],SVC:[],ENABLE_FULL_LINK_AV_SYNC:!1,SVC_MODE:null,ENABLE_AUT_FEEDBACK:!0,SVC_EXTENDED:["VP9"],ENABLE_JOIN_V4:!1,ENABLE_AP_COMPRESS:!0},$P={MIN_FRAME_RATE:1,MAX_FRAME_RATE:30,MAX_THRESHOLD_FRAMERATE:30,BITRATE_MIN_THRESHOLD:100,BITRATE_MAX_THRESHOLD:100,MAX_SCALE:5,BWE_SCALE_UP_THRESHOLD:.6,BWE_SCALE_DOWN_THRESHOLD:.6,PERF_SCALE_UP_THRESHOLD:.7,PERF_SCALE_DOWN_THRESHOLD:.6,MOTION_RESOLUTION_FACTOR:.8,MOTION_BITRATE_FACTOR:.6,DETAIL_FRAMERATE_FACTOR:.8,DETAIL_BITRATE_FACTOR:.6,BALANCE_RESOLUTION_FACTOR:.9,BALANCE_FRAMERATE_FACTOR:.9,BALANCE_BITRATE_FACTOR:.6,OVERUSE_TIMES_THRESHOLD:10,UNDERUSE_TIMES_THRESHOLD:40},eL="v4.24.4-0-gb4d645709-dirty(5/26/2026, 6:19:32 PM)",tL={ENABLE_EVENT_REPORT:!0,UPLOAD_LOG:!1,ENABLE_AG_ADAPTATION:!0,FORCE_AG_HIGH_FRAMERATE:!1,FORCE_SUPPORT_AG_ADAPTATION:!1,ENCODER_CONFIG_LIMIT:{},CAMERA_CAPTURE_CONFIG:void 0,ENABLE_PRELOAD:!0,NEW_ICE_RESTART:!0,ICE_RESTART_INTERVAL:1e4,RESTART_SEQUENCE:["udp_tcp_relay","relay"],FIRST_TCP_CANDIDATE:!1,MAX_CONFIG_RETRY:10,ENABLE_CONFIG_RESTORE:!1,CONFIG_RESTORE_ERROR_API:["createClient","Client.join"],CONFIG_ERROR_MONITOR:["INVALID_OPERATION","UNEXPECTED_ERROR"],BLOCKED_CONFIG_MAX_TIME:864e5,FIRST_TCP_CANDIDATE_INTERVAL:1e3,TURN_DOMAIN:"edge.agora.io",TURN_DOMAINS:["edge.agora.io"],USE_TURN_IP:!0,NEW_TURN_MODE:4,NEW_FORCE_TURN:!1,USE_NEW_RENDER_FREEZE_TIME:!0,FLS_FALLBACK_TIMEOUT:3e4,RTE_DETAIL_REPORT_INTERVAL:6e4,ENCODE_EXCEPTION_TIMES:5,ENABLE_ENCODE_EXCEPTION:!0,ENCODE_EXCEPTION_VALIDATE_CODEC:["h264"],VIDEO_ENCODER_CONFIG_LIST:[{width:240,height:180},{width:320,height:240},{width:400,height:300},{width:480,height:360},{width:560,height:420},{width:640,height:480}],DELETE_NEQ_AFTER_USER_LEAVE:!0,UPDATE_RTP_CAP_IN_HOST:!1,IOS_BG_TAG:!0,IOS_AUTO_RESTART_BG_TAG:!0,IGNORE_UID_CHECK:!1,ENABLE_UP_SPS_PPS:!1,ENABLE_DOWN_SPS_PPS:!0,NO_EDGES_RETRY:!0,BUFFER_READY_FRAMES:3,FLS_SYNC_AV_PLAY_LIMIT:0,FLS_BUFFER_WAIT_TIME:1500,VOS_CONFIGURE:void 0,ENABLE_QUALITY_FALLBACK:!1,QUALITY_FALLBACK_REHEARSAL:!0,ENABLE_FLS_AV1_FIRST:!1,ENABLE_AP_MULTI_IP:!0,FLS_ENABLE_AV1_DETECT:!0,FLS_ENABLE_AV1_DECODE_DETECT:!0,ENABLE_SDP_ENDPOINT_LOG:!1,REMOTE_VIDEO_FREEZE_TIME_VERSION:2},nL=YN(YN(YN(YN({},tL),{},{PROCESS_ID:"",ENCRYPT_AES:!0,AREAS:["CHINA","GLOBAL"],WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io","webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io","webrtc2-4.ap.sd-rtn.com"],SDP_ENDPOINT_DOMAIN:["webrtc2-ap-web-1.agora.io","webrtc2-2.ap.sd-rtn.com"],SDP_ENDPOINT_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io","webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-web-2.ap.sd-rtn.com","cds-ap-web-3.agora.io","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-web-2.ap.sd-rtn.com","sua-ap-web-3.agora.io","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-ap-web-1.agora.io","uap-web-2.ap.sd-rtn.com","uap-ap-web-3.agora.io","uap-web-4.ap.sd-rtn.com"],LOG_UPLOAD_SERVER:"logservice.agora.io",EVENT_REPORT_DOMAIN:"statscollector-1.agora.io",EVENT_REPORT_BACKUP_DOMAIN:"web-2.statscollector.sd-rtn.com",GATEWAY_ADDRESS:[],GATEWAY_WSS_ADDRESS:"",LIVE_STREAMING_ADDRESS:"",HTTP_CONNECT_TIMEOUT:5e3,SIGNAL_REQUEST_TIMEOUT:1e4,REPORT_STATS:!0,NOT_REPORT_EVENT:[],PING_PONG_TIME_OUT:10,WEBSOCKET_TIMEOUT_MIN:1e4,EVENT_REPORT_SEND_INTERVAL:3e3,CONFIG_DISTRIBUTE_INTERVAL:3e5,ENABLE_CONFIG_DISTRIBUTE:!0,CANDIDATE_TIMEOUT:5e3,SHOW_REPORT_INVOKER_LOG:!1,SHOW_REPORT_USER_INVOKER_LOG:!0,JOIN_EXTEND:"",PUB_EXTEND:"",SUB_EXTEND:"",FORCE_TURN:!1,TURN_ENABLE_TCP:!0,TURN_ENABLE_UDP:!0,MAX_UPLOAD_CACHE:50,UPLOAD_CACHE_INTERVAL:2e3,AJAX_REQUEST_CONCURRENT:3,REPORT_APP_SCENARIO:void 0,GATEWAY_DOMAINS:["edge.agora.io","edge.sd-rtn.com"],CONNECT_GATEWAY_WITHOUT_DOMAIN:!1,WORKER_DOMAIN:"edge.agora.io",EVENT_REPORT_RETRY:!0,CHROME_FORCE_PLAN_B:!1,AUDIO_SOURCE_VOLUME_UPDATE_INTERVAL:400,AUDIO_SOURCE_AVG_VOLUME_DURATION:3e3,AUDIO_VOLUME_INDICATION_INTERVAL:2e3,VOLUME_VOICE_WEIGHT:10,GET_VOLUME_OF_MUTED_AUDIO_TRACK:!1,STATS_UPDATE_INTERVAL:250,NORMAL_EVENT_QUEUE_CAPACITY:100,CUSTOM_REPORT:!0,CUSTOM_REPORT_LIMIT:20,PROXY_SERVER_TYPE2:"webnginx-proxy.agora.io",PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com","webrtc-cloud-proxy.agora.io"],CUSTOM_PUB_ANSWER_MODIFIER:null,CUSTOM_SUB_ANSWER_MODIFIER:null,CUSTOM_PUB_OFFER_MODIFIER:null,CUSTOM_SUB_OFFER_MODIFIER:null,DSCP_TYPE:"high",REMOVE_NEW_CODECS:!0,FRAGEMENT_LENGTH:3,WEBSOCKET_COMPRESS:!1,SIMULCAST:!1,CHECK_VIDEO_VISIBLE_INTERVAL:3e4,CHECK_LOCAL_STATS_INTERVAL:250,PROFILE_SWITCH_INTERVAL:2e3,UNSUPPORTED_VIDEO_CODEC:[],ENUMERATE_DEVICES_INTERVAL:!1,ENUMERATE_DEVICES_INTERVAL_TIME:1e4,USE_NEW_TOKEN:!1,CLOSE_AFB_FOR_LOCAL_AP:!0,JOIN_MAX_CONCURRENCY:6,JOIN_WITH_FALLBACK_SIGNAL_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE:!1,JOIN_GATEWAY_TRY_443PORT_DURATION:2e3,JOIN_GATEWAY_USE_443PORT_ONLY:!1,JOIN_GATEWAY_USE_DUAL_DOMAIN:!0,JOIN_GATEWAY_FALLBACK_PORT:443,USE_TURN_SERVER_OF_GATEWAY:!1,H264_PROFILE_LEVEL_ID:"",USE_NEW_LOG:!1,LOG_VERSION:3,MEDIA_DEVICE_CONSTRAINTS:null,ENCRYPT_PROXY_USERNAME_AND_PSW:!0,SDP_LOGGING:!1,CSP_DETECTED_HOSTNAME_LIST:["agora.io","sd-rtn.com"],REMOTE_AUDIO_TRACK_USES_WEB_AUDIO:!1,LOCAL_AUDIO_TRACK_USES_WEB_AUDIO:!1,BITRATE_ADAPTER_TYPE:"STANDARD_BITRATE",AI_DENOISER_PARAMETERS:{excludedLinks:[]},ADJUST_3A_FROM_PLUGINS:!0,RAISE_H264_BASELINE_PRIORITY:!0,FILTER_SEND_H264_BASELINE:!1,FIRST_H264_PROFILE_LEVEL_ID:"42001f",FIRST_PACKETIZATION_MODE:"",X_GOOGLE_START_BITRATE:void 0,NEW_REPORT_SERVER:!1,NEW_REPORT_SERVER_DOMAINS:["data-reporting.agora.io","data-reporting.agora.io"],VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT:3e5,VIDEO_INSPECT_INTERVAL_MINIMUM:1e3,VIDEO_INSPECT_QUALITY_RATIO:.9,VIDEO_INSPECT_WORKER_MANAGER_HOST:"edge.agora.io",VIDEO_INSPECT_WORKER_MANAGER_PORT:"",VIDEO_INSPECT_WORKER_MANAGER_WSS:"",VIDEO_INSPECT_WORKER_PORT:"",SHOW_VIDEO_INSPECT_WORKER_MESSAGE:!1,STATS_COLLECTOR_PORT:443,FORCE_TURN_TCP:!1,WEBAUDIO_INIT_OPTIONS:void 0,FILTER_VIDEO_FEC:!0,FILTER_AUDIO_FEC:!1,CHROME_DUAL_STREAM_USE_ENCODING:!0,DISABLE_DUAL_STREAM_USE_ENCODING:!1,EXTENSION_USAGE_UPLOAD_INTERVAL:1e4,ICE_RESTART:!0,FINGERPRINT:null,ENABLE_VIDEO_FRAME_CALLBACK:!0,VIDEO_FREEZE_DURATION:500,SPATIALIZER_PARAMETERS:{},UPLOAD_LOG_INTERVAL:3e3,UPLOAD_LOG_REQUEST_RETRY_INTERVAL:2e3,UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL:2e4,UPLOAD_LOG_TRY_INTERVAL_WHILE_OFF:5e3,UPLOAD_LOG_RETRY_INTERVAL_V1:1e4,UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1:200,UPLOAD_LOG_LENGTH_EACH_TIME:10,APP_TYPE:0,DISABLE_WEBAUDIO:!1,CHANNEL_MEDIA_RELAY_SERVERS:void 0,KEEP_LAST_FRAME:!0,FORWARD_P2P_CREATION:!0,SYNC_GROUP:!0,BLOCK_LOCAL_CLIENT:!1,ENABLE_AUDIO_TOPN:!1,ENABLE_AUDIO_METADATA:!1,ENABLE_AUDIO_PTS:!1,TOPN_SMOOTH_LEVEL:void 0,TOPN_NEW_SPEAKER_DELAY:void 0,TOPN_SWITCH_HOLD_MS:void 0,TOPN_AUDIO_GAIN:void 0,TOPN_SILENCE_THRESHOLD:250,AP_AREA:!0,ENABLE_ENCODED_TRANSFORM:!1,ENABLE_VIDEO_SEI:!1,IMAGE_MODERATION_WORKER_HOST:"edge.agora.io",IMAGE_MODERATION_WORKER_WSS:"",IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT:3e5,IMAGE_MODERATION_INTERVAL_MINIMUM:1e3,SHOW_IMAGE_MODERATION_WORKER_MESSAGE:!1,IMAGE_MODERATION_QUALITY_RATIO:.9,IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL:5e3,SHOW_GLOBAL_CLIENT_LIST:!1,DATASTREAM_MAX_RETRANSMITS:10,TCP_CANDIDATE_ONLY:!1,EXTERNAL_SIGNAL_REQUEST_TIMEOUT:3e3,SHOW_P2P_LOG:!1,MAX_P2P_TIMEOUT:3e4,P2P_TOKEN_INTERVAL:1e3,SHOW_DATASTREAM2_LOG:!1,RESTRICTION_SET_PLAYBACK_DEVICE:!0,USE_PURE_ENCRYPTION_MASTER_KEY:!1,ENABLE_AUDIO_RED:!1,OPUS_PTIME:void 0,AUDIO_DUPLICATE_NUM:void 0,ENABLE_ABSSENDTIME_AS_SENTTS:!0,ACCOUNT_REGISTER_RETRY_TIMEOUT:1,ACCOUNT_REGISTER_RETRY_RATIO:2,ACCOUNT_REGISTER_RETRY_TIMEOUT_MAX:6e4,ACCOUNT_REGISTER_RETRY_COUNT_MAX:1e5,AUDIO_CONTEXT:null,WEBCS_BACKUP_CONNECT_TIMEOUT:6e3,PLAYER_STATE_DEFER:2e3,SIGNAL_REQUEST_WATCH_INTERVAL:1e3,FILEPATH_LENMAX:255,DUALSTREAM_OPERATION_CHECK:!0,MEDIA_ELEMENT_EXISTS_DEPTH:3,SHIM_CANDIDATE:!1,LEAVE_MSG_TIMEOUT:2e3,STATS_FILTER:{transportId:!0,googTrackId:!0},FILTER_VIDEO_CODEC:[],SIGNAL_CHANNEL:0,TRANSMITTER_INITIAL_RTT:30,TRANSMITTER_INITIAL_RTO:30,TRANSMITTER_MAX_BATCH_ACK_COUNT:2,TRANSMITTER_MAX_RTO:500,DATACHANNEL_COMPRESS:!1,DC_JOIN_WITH_FAILBACK:4e3,DC_CONNECTION_TIMEOUT:2e3,DC_PINGPONG_INTERVAL:2e3,DC_DEBUG_LOG:!1,UNSUPPORTED_VIDEO_UPLINK_CODEC:[],UNSUPPORTED_VIDEO_DOWNLINK_CODEC:[],USE_NEW_NETWORK_CONFIG:!1,AUTO_RESET_AUDIO_ROUTE:!1,PLUGIN_INFO:[],OVERUSE_DETECTOR_PARAMS:$P,CUSTOM_ADAPTATION_DEFAULT_MODE:"",HIDE_NO_POSTER:!1,AP_CACHE_NUM:10,AP_UPDATE_INTERVAL:12e4,AP_CACHE_LIFETIME:12e4,MAX_PRELOAD_ASYNC_LENGTH:3,DISABLE_SCREEN_SHARE_REMB:!1},QP),{},{USE_CANDIDATE_FROM_AP_DETAIL:!1,AP_REQUEST_DETAIL:void 0,ENABLE_ROLE_SELECT_EDGE:!1,CLIENT_ROLE_OPTIONS:void 0,REMOTE_VIDEO_STREAM_TYPE:void 0,COMPATIBLE_SDP_EXTENSION:["gdpr_forbidden"],LIMIT_BITRATE:void 0,EXPERIMENTS:{},USE_PUB_RTX:!0,USE_SUB_RTX:!0,ENABLE_DATASTREAM_2:!1,USE_XR:!0,ENABLE_PREALLOC_PC:!1,ENABLE_PRE_SUB:!1,ENABLE_SVC:!1,ENABLE_FORCE_HLS:!1,MAX_WEBAUDIO_VOLUME:300,ENABLE_VOS_FALLBACK:!1,ENABLE_FALLBACK_TO_HLS:!1,ENABLE_PRE_RENDER:!1,FORCE_DISABLE_AUTO_SUB:!1,ENABLE_PRE_SUB_WITH_PRE_PC:!0,PRE_USE_LOCAL_CODECS:!0},{INSTALL_ID:""}),{},{K_MIN_RENDER_DELAY:66,USE_STANDARD_BITRATE_DEFAULT:!1,VIDEO_NEW_BITRATE_RATIO:void 0,VIDEO_STANDARD_BITRATE_VERSION:2,BASELINE_MORE_H264_BITRATE_RATIO:1.1,IGNORE_RTC_DEVICE_CHECK:!1,FLS_AUTOPLAY_EMITS:!1,ENABLE_DUAL_STREAM_FLAG:!1,FORBID_MODIFY_LOCAL_OFFER_SDP:!1,RESERVE_MID_1_MLINE:!1,PRE_SUB_NUM:1,DC_IN_ESM:!0,PRE_PLAYOUT_DELAY_HINT:void 0});function iL(e,t,n){var i,r,o;Vi(i=Object.keys(nL)).call(i,e)&&(!n&&Vi(r=Object.keys(sL)).call(r,e)||(nL[e]=t,"ENABLE_VIDEO_SEI"!==e&&"ENABLE_AUDIO_TOPN"!==e&&"ENABLE_AUDIO_METADATA"!==e&&"ENABLE_AUDIO_PTS"!==e||!0!==t||(nL.ENABLE_ENCODED_TRANSFORM=!0),"USE_NEW_NETWORK_CONFIG"===e&&t&&(o=!!t,nL.USE_NEW_NETWORK_CONFIG=o,o&&(nL.WEBCS_DOMAIN=["webrtc2-2.ap.sd-rtn.com"],nL.WEBCS_DOMAIN_BACKUP_LIST=["webrtc2-4.ap.sd-rtn.com"],nL.CDS_AP=["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],nL.ACCOUNT_REGISTER=["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],nL.EVENT_REPORT_DOMAIN="web-2.statscollector.sd-rtn.com",nL.EVENT_REPORT_BACKUP_DOMAIN="statscollector-1.agora.io",nL.GATEWAY_DOMAINS=["edge.sd-rtn.com"])),"ENABLE_PRE_SUB"===e&&t&&(nL.ENABLE_INSTANT_VIDEO=!0,nL.ENABLE_PREALLOC_PC=!0),"ENABLE_SVC"===e&&t&&(nL.ENABLE_AUT_CC=!0),"NEW_FORCE_TURN"===e&&t&&(nL.NEW_TURN_MODE||(nL.NEW_TURN_MODE=4))))}function rL(e){if("TURN_DOMAINS"===e){const e=nL.TURN_DOMAINS;return Vi(e).call(e,rL("TURN_DOMAIN"))?e:[rL("TURN_DOMAIN")].concat(e)}return nL[e]}zP||(nL.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],nL.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],nL.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],nL.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],nL.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],nL.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],nL.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",nL.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",nL.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",nL.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",nL.AREAS=["NORTH_AMERICA","OVERSEA"]);let oL=function(e){return e[e.REALTIME=1]="REALTIME",e}({});const sL={};var aL=function(e){return e.SET_SESSION_ID="SET_SESSION_ID",e.SET_RTE_URL="SET_RTE_URL",e.SET_RTE_SID="SET_RTE_SID",e.SET_P2P_ID="SET_P2P_id",e.SET_DC_ID="SET_DC_id",e.SET_UID="SET_UID",e.SET_INT_UID="SET_INT_UID",e.SET_PUB_ID="SET_PUB_ID",e.SET_CLOUD_PROXY_SERVER_MODE="SET_CLOUD_PROXY_SERVER_MODE",e.KEY_METRIC_CLIENT_CREATED="KEY_METRIC_CLIENT_CREATED",e.KEY_METRIC_JOIN_START="KEY_METRIC_JOIN_START",e.KEY_METRIC_PRELOAD_START="KEY_METRIC_PRELOAD_START",e.KEY_METRIC_PRELOAD_END="KEY_METRIC_PRELOAD_END",e.KEY_METRIC_JOIN_END="KEY_METRIC_JOIN_END",e.KEY_METRIC_REQUEST_AP_START="KEY_METRIC_REQUEST_AP_START",e.KEY_METRIC_REQUEST_AP_END="KEY_METRIC_REQUEST_AP_END",e.KEY_METRIC_REQUEST_SUA_END="KEY_METRIC_REQUEST_SUA_END",e.KEY_METRIC_BEFORE_CONNECT="KEY_METRIC_BEFORE_CONNECT",e.KEY_METRIC_PEER_RECEIVER="KEY_METRIC_PEER_RECEIVER",e.KEY_METRIC_SIGNAL_CONNECTED="KEY_METRIC_SIGNAL_CONNECTED",e.KEY_METRIC_JOIN_REQ="KEY_METRIC_JOIN_REQ",e.KEY_METRIC_JOIN_REP="KEY_METRIC_JOIN_REP",e.KEY_METRIC_JOIN_GATEWAY_START="KEY_METRIC_JOIN_GATEWAY_START",e.KEY_METRIC_JOIN_GATEWAY_END="KEY_METRIC_JOIN_GATEWAY_END",e.KEY_METRIC_PEER_CONNECTION_START="KEY_METRIC_PEER_CONNECTION_START",e.KEY_METRIC_PEER_CONNECTION_END="KEY_METRIC_PEER_CONNECTION_END",e.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED="KEY_METRIC_FIRST_VIDEO_FRAME_DECODED",e.KEY_METRIC_DESCRIPTION_START="KEY_METRIC_DESCRIPTION_START",e.KEY_METRIC_ICE_CONNECTION_END="KEY_METRIC_ICE_CONNECTION_END",e.KEY_METRIC_SIGNAL_CHANNEL_OPEN="KEY_METRIC_SIGNAL_CHANNEL_OPEN",e.KEY_METRIC_PUBLISH="KEY_METRIC_PUBLISH",e.KEY_METRIC_SUBSCRIBE="KEY_METRIC_SUBSCRIBE",e.RECORD_JOIN_CHANNEL_SERVICE="RECORD_JOIN_CHANNEL_SERVICE",e.RESET_JOIN_CHANNEL_SERVICE_RECORDS="RESET_JOIN_CHANNEL_SERVICE_RECORDS",e.RESET_KEY_METRICS="RESET_KEY_METRICS",e.RESET_FIRST_VIDEO_FRAME_DECODED="RESET_FIRST_VIDEO_FRAME_DECODED",e.SET_USE_P2P="SET_USE_P2P",e.SET_TRANSPORT_TYPE="SET_TRANSPORT_TYPE",e}(aL||{});let cL=function(e){return e.h264="h264",e.h265="h265",e.vp8="vp8",e.vp9="vp9",e.av1="av1",e}({});!function(e){e.opus="opus",e.pcma="pcma",e.pcmu="pcmu",e.g722="g722"}({});const dL=128,lL=96,uL=1e3,hL=10;let pL=0;var _L=(()=>{var e={8:(e,t,n)=>{n.r(t),n.d(t,{Parser:()=>v,Printer:()=>A,parse:()=>D,print:()=>P});const i="\n",r="".concat("\r").concat(i),o=" ";let s;function a(e){return e>="0"&&e<="9"}function c(e){return e>="!"&&e<="~"}function d(e){return c(e)||e>=""&&e<="ÿ"}function l(e){return"!"===e||e>="#"&&e<="'"||e>="*"&&e<="+"||e>="-"&&e<="."||e>="0"&&e<="9"||e>="A"&&e<="Z"||e>="^"&&e<="~"}function u(e){return e>="1"&&e<="9"}function h(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function p(e){return"d"===e||"h"===e||"m"===e||"s"===e}function _(e){return e>""&&e<"\t"||e>"\v"&&e<"\f"||e>""&&e<"ÿ"}function E(e){return h(e)||a(e)||"+"===e||"/"===e}function m(e){return a(e)||h(e)||"+"===e||"/"===e||"-"===e||"_"===e}function f(e){return h(e)||a(e)||"+"===e||"/"===e}function g(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function S(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?g(Object(n),!0).forEach((function(t){T(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):g(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function T(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}!function(e){e.VERSION="v",e.ORIGIN="o",e.SESSION_NAME="s",e.INFORMATION="i",e.URI="u",e.EMAIL="e",e.PHONE="p",e.CONNECTION="c",e.BANDWIDTH="b",e.TIME="t",e.REPEAT="r",e.ZONE_ADJUSTMENTS="z",e.KEY="k",e.ATTRIBUTE="a",e.MEDIA="m"}(s||(s={}));class R{consumeText(e,t){let n=t;for(;n<e.length;){const t=e[n];if("\0"===t||"\r"===t||t===i)break;n+=1}if(n-t==0)throw new Error("Invalid text, at ".concat(e));return n}consumeUnicastAddress(e,t,n){return this.consumeTill(e,t,o)}consumeOneOrMore(e,t,n){let i=t;for(;n(e[i]);)i++;if(i-t==0)throw new Error("Invalid rule at ".concat(t,"."));return i}consumeSpace(e,t){if(e[t]===o)return t+1;throw new Error("Invalid space at ".concat(t,"."))}consumeIP4Address(e,t){let n=t;for(let t=0;t<4;t++)if(n=this.consumeDecimalUChar(e,n),3!==t){if("."!==e[n])throw new Error("Invalid IP4 address.");n++}return n}consumeDecimalUChar(e,t){let n=t;for(let t=0;t<3&&a(e[n]);t++,n++);if(n-t==0)throw new Error("Invalid decimal uchar.");const i=parseInt(e.slice(t,n));if(i>=0&&i<=255)return n;throw new Error("Invalid decimal uchar")}consumeIP6Address(e,t){let n=this.consumeHexpart(e,t);return":"===e[n]?(n+=1,n=this.consumeIP4Address(e,n),n):n}consumeHexpart(e,t){let n=t;if(":"===e[n]&&":"===e[n+1]){n+=2;try{n=this.consumeHexseq(e,n)}catch(e){}return n}if(n=this.consumeHexseq(e,n),":"===e[n]&&":"===e[n+1]){n+=2;try{n=this.consumeHexseq(e,n)}catch(e){}return n}return n}consumeHexseq(e,t){let n=t;for(;n=this.consumeHex4(e,n),":"===e[n]&&":"!==e[n+1];)n+=1;return n}consumeHex4(e,t){let n=0;for(;n<4;n++)if(!((i=e[t+n])>="0"&&i<="9"||i>="a"&&i<="f"||i>="A"&&i<="F")){if(0===n)throw new Error("Invalid hex 4");break}var i;return t+n}consumeFQDN(e,t){let n=t;for(;a(e[n])||h(e[n])||"-"===e[n]||"."===e[n];)n+=1;if(n-t<4)throw new Error("Invalid FQDN");return n}consumeExtnAddr(e,t){return this.consumeOneOrMore(e,t,d)}consumeMulticastAddress(e,t,n){switch(n){case"IP4":case"ip4":return this.consumeIP4MulticastAddress(e,t);case"IP6":case"ip6":return this.consumeIP6MulticastAddress(e,t);default:try{return this.consumeFQDN(e,t)}catch(n){return this.consumeExtnAddr(e,t)}}}consumeIP6MulticastAddress(e,t){const n=this.consumeHexpart(e,t);return"/"===e[n]?this.consumeInteger(e,n+1):n}consumeIP4MulticastAddress(e,t){let n=t+3;const i=e.slice(t,n),r=parseInt(i);if(r<224||r>239)throw new Error("Invalid IP4 multicast address, IPv4 multicast addresses may be in the range 224.0.0.0 to 239.255.255.255.");for(let t=0;t<3;t++){if("."!==e[n])throw new Error("Invalid IP4 multicast address.");n+=1,n=this.consumeDecimalUChar(e,n)}return"/"===e[n]&&(n+=1),n=this.consumeTTL(e,n),"/"===e[n]&&(n=this.consumeInteger(e,n)),n}consumeInteger(e,t){if(!u(e[t]))throw new Error("Invalid integer.");for(t+=1;a(e[t]);)t+=1;return t}consumeTTL(e,t){if("0"===e[t])return t+1;if(!u(e[t]))throw new Error("Invalid TTL.");t+=1;for(let n=0;n<2&&a(e[t]);n++)t+=1;return t}consumeToken(e,t){return this.consumeOneOrMore(e,t,l)}consumeTime(e,t){let n=t;if("0"===e[n])return n+1;for(u(e[n])&&(n+=1);a(e[n]);)n++;if(n-t<10)throw new Error("Invalid time");return n}consumeAddress(e,t){return this.consumeTill(e,t,o)}consumeTypedTime(e,t){let n=t;return n=this.consumeOneOrMore(e,n,a),p(e[n])?n+1:n}consumeRepeatInterval(e,t){if(!u(e[t]))throw new Error("Invalid repeat interval");for(t+=1;a(e[t]);)t+=1;return p(e[t])&&(t+=1),t}consumePort(e,t){return this.consumeOneOrMore(e,t,a)}consume(e,t,n){for(let i=0;i<n.length;i++){if(t+i>=e.length)throw new Error("consume exceeding value length");if(e[t+i]!==n[i])throw new Error("consume ".concat(n," failed at ").concat(i))}return t+n.length}consumeTill(e,t,n){let i=t;for(;i<e.length&&("string"!=typeof n||e[i]!==n)&&("function"!=typeof n||!n(e[i]));)i++;return i}}class v extends R{constructor(){super(),T(this,"records",[]),T(this,"currentLine",0)}parse(e){const t=this.probeEOL(e);this.records=e.split(t).filter((e=>!!ZS(e).call(e))).map(this.parseLine),this.currentLine=0;const n=this.parseVersion(),i=this.parseOrigin(),r=this.parseSessionName(),o=this.parseInformation(),s=this.parseUri(),a=this.parseEmail(),c=this.parsePhone(),d=this.parseConnection(),l=this.parseBandWidth(),u=this.parseTimeFields(),h=this.parseKey(),p=this.parseSessionAttribute(),_=this.parseMediaDescription();if(this.currentLine!==this.records.length)throw new Error("parsing failed, non exhaustive sdp lines.");return{version:n,origin:i,sessionName:r,information:o,uri:s,emails:a,phones:c,connection:d,bandwidths:l,timeFields:u,key:h,attributes:p,mediaDescriptions:_}}getCurrentRecord(){const e=this.records[this.currentLine];if(!e)throw new Error("Record doesn't exit.");return e}probeEOL(e){for(let t=0;t<e.length;t++)if(e[t]===i)return"\r"===e[t-1]?r:i;throw new Error("Invalid newline character.")}parseLine(e,t){if(e.length<2)throw new Error("Invalid sdp line, sdp line should be of form <type>=<value>.");const n=e[0];if("="!==e[1])throw new Error('Invalid sdp line, <type> should be a single character followed by an "=" sign.');return{type:n,value:e.slice(2),line:t,cur:0}}parseSessionAttribute(){const e=new b;for(;this.currentLine<this.records.length;){const t=this.getCurrentRecord();if(t.type!==s.ATTRIBUTE)break;const n={attField:this.extractOneOrMore(t,(e=>l(e)&&":"!==e)),_cur:0};":"===t.value[t.cur]&&(t.cur+=1,n.attValue=this.extractOneOrMore(t,_)),e.parse(n),this.currentLine++}return e.digest()}parseMediaAttributes(e){const t=new C(e);for(;this.currentLine<this.records.length;){const e=this.getCurrentRecord();if(e.type!==s.ATTRIBUTE)break;const n={attField:this.extractOneOrMore(e,(e=>l(e)&&":"!==e)),_cur:0};":"===e.value[e.cur]&&(e.cur+=1,n.attValue=this.extractOneOrMore(e,_)),t.parse(n),this.currentLine++}return t.digest()}parseKey(){const e=this.getCurrentRecord();if(e.type===s.KEY){if("prompt"===e.value||"clear:"===e.value||"base64:"===e.value||"uri:"===e.value)return e.value;throw this.currentLine++,new Error("Invalid key.")}}parseZone(){const e=this.getCurrentRecord();if(e.type===s.ZONE_ADJUSTMENTS){const t=[];for(;;)try{const n=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);let i=!1;"-"===e.value[e.cur]&&(i=!0,e.cur+=1);const r=this.extract(e,this.consumeTypedTime);t.push({time:n,typedTime:r,back:i})}catch(e){break}if(0===t.length)throw new Error("Invalid zone adjustments");return this.currentLine++,t}return[]}parseRepeat(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.REPEAT)break;{const n=this.extract(t,this.consumeRepeatInterval),i=this.parseTypedTime(t);e.push({repeatInterval:n,typedTimes:i}),this.currentLine++}}return e}parseTypedTime(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeTypedTime))}catch(e){break}if(0===t.length)throw new Error("Invalid typed time.");return t}parseTime(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);const n=this.extract(e,this.consumeTime);return this.currentLine++,{startTime:t,stopTime:n}}parseBandWidth(){const e=[];for(;this.currentLine<this.records.length;){const t=this.getCurrentRecord();if(t.type!==s.BANDWIDTH)break;{const n=this.extractOneOrMore(t,l);if(":"!==t.value[t.cur])throw new Error("Invalid bandwidth field.");t.cur++;const i=this.extractOneOrMore(t,a);e.push({bwtype:n,bandwidth:i}),this.currentLine++}}return e}parseVersion(){const e=this.getCurrentRecord();if(e.type!==s.VERSION)throw new Error("first sdp record must be version");const t=e.value.slice(0,this.consumeOneOrMore(e.value,0,a));if(t.length!==e.value.length)throw new Error('invalid proto version, "v='.concat(e.value,'"'));return this.currentLine++,t}parseOrigin(){const e=this.getCurrentRecord();if(e.type!==s.ORIGIN)throw new Error("second line of sdp must be origin");const t=this.extractOneOrMore(e,d);this.consumeSpaceForRecord(e);const n=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);const i=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);const r=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const o=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const c=this.extract(e,this.consumeUnicastAddress);return this.currentLine++,{username:t,sessId:n,sessVersion:i,nettype:r,addrtype:o,unicastAddress:c}}parseSessionName(){const e=this.getCurrentRecord();if(e.type===s.SESSION_NAME){const t=this.extract(e,this.consumeText);return this.currentLine++,t}}parseInformation(){const e=this.getCurrentRecord();if(e.type!==s.INFORMATION)return;const t=this.extract(e,this.consumeText);return this.currentLine++,t}parseUri(){const e=this.getCurrentRecord();if(e.type===s.URI)return this.currentLine++,e.value}parseEmail(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.EMAIL)break;e.push(t.value),this.currentLine++}return e}parsePhone(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.PHONE)break;e.push(t.value),this.currentLine++}return e}parseConnection(){const e=this.getCurrentRecord();if(e.type===s.CONNECTION){const t=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const n=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const i=this.extract(e,this.consumeAddress);return this.currentLine++,{nettype:t,addrtype:n,address:i}}}parseMedia(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeToken);this.consumeSpaceForRecord(e);let n=this.extract(e,this.consumePort);"/"===e.value[e.cur]&&(e.cur+=1,n+=this.extract(e,this.consumeInteger)),this.consumeSpaceForRecord(e);const i=[];for(i.push(this.extract(e,this.consumeToken));"/"===e.value[e.cur];)e.cur+=1,i.push(this.extract(e,this.consumeToken));if(0===i.length)throw new Error("Invalid proto");const r=this.parseFmt(e);return this.currentLine++,{mediaType:t,port:n,protos:i,fmts:r}}parseTimeFields(){const e=[];for(;this.getCurrentRecord().type===s.TIME;){const t=this.parseTime(),n=this.parseRepeat(),i=this.parseZone();e.push({time:t,repeats:n,zones:i})}return e}parseMediaDescription(){const e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===s.MEDIA;){const t=this.parseMedia(),n=this.parseInformation(),i=this.parseConnections(),r=this.parseBandWidth(),o=this.parseKey(),s=this.parseMediaAttributes(t);e.push({media:t,information:n,connections:i,bandwidths:r,key:o,attributes:s})}return e}parseConnections(){const e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===s.CONNECTION;)e.push(this.parseConnection());return e}parseFmt(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeToken))}catch(e){break}if(0===t.length)throw new Error("Invalid fmts");return t}extract(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];const o=t.call(this,e.value,e.cur,...i),s=e.value.slice(e.cur,o);return e.cur=o,s}extractOneOrMore(e,t){const n=this.consumeOneOrMore(e.value,e.cur,t),i=e.value.slice(e.cur,n);return e.cur=n,i}consumeSpaceForRecord(e){if(e.value[e.cur]!==o)throw new Error("Invalid space at ".concat(e.cur,"."));e.cur+=1}}class y extends R{constructor(){super(...arguments),T(this,"attributes",void 0),T(this,"digested",!1)}extractOneOrMore(e,t,n){const i=this.consumeOneOrMore(e.attValue,e._cur,t),r=e.attValue.slice(e._cur,i),o=Hb(n||[],2),s=o[0],a=o[1];if("number"==typeof s&&r.length<s)throw new Error("error in length, should be more or equal than ".concat(s," characters."));if("number"==typeof a&&r.length>a)throw new Error("error in length, should be less or equal than ".concat(a," characters."));return e._cur=i,r}consumeAttributeSpace(e){if(e.attValue[e._cur]!==o)throw new Error("Invalid space at ".concat(e._cur,"."));e._cur+=1}extract(e,t){if(!e.attValue)throw new Error("Nothing to extract from attValue.");for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];const o=t.call(this,e.attValue,e._cur,...i),s=e.attValue.slice(e._cur,o);return e._cur=o,s}atEnd(e){if(!e.attValue)throw new Error;return e._cur>=e.attValue.length}peekChar(e){if(!e.attValue)throw new Error;return e.attValue[e._cur]}peek(e,t){if(!e.attValue)throw new Error;for(let n=0;n<t.length;n++)if(t[n]!==e.attValue[e._cur+n])return!1;return!0}parseIceUfrag(e){if(this.attributes.iceUfrag)throw new Error("Invalid ice-ufrag, should be only a single line if 'a=ice-ufrag'");this.attributes.iceUfrag=this.extractOneOrMore(e,E,[4,256])}parseIcePwd(e){if(this.attributes.icePwd)throw new Error("Invalid ice-pwd, should be only a single line if 'a=ice-pwd'");this.attributes.icePwd=this.extractOneOrMore(e,E,[22,256])}parseIceOptions(e){if(this.attributes.iceOptions)throw new Error("Invalid ice-options, should be only one 'ice-options' line");const t=[];for(;!this.atEnd(e);){t.push(this.extractOneOrMore(e,E));try{this.consumeAttributeSpace(e)}catch(t){if(this.atEnd(e))break;throw t}}this.attributes.iceOptions=t}parseFingerprint(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeTill);this.attributes.fingerprints.push({hashFunction:t,fingerprint:n})}parseExtmap(e){const t=this.extractOneOrMore(e,a);let n;"/"===this.peekChar(e)&&(this.extract(e,this.consume,"/"),n=this.extract(e,this.consumeToken)),this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,o),r=S(S({entry:parseInt(t,10)},n&&{direction:n}),{},{extensionName:i});this.peekChar(e)===o&&(this.consumeAttributeSpace(e),r.extensionAttributes=this.extract(e,this.consumeTill)),this.attributes.extmaps.push(r)}parseSetup(e){if(this.attributes.setup)throw new Error("must only be one single 'a=setup' line.");const t=this.extract(e,this.consumeTill);if("active"!==t&&"passive"!==t&&"actpass"!==t&&"holdconn"!==t)throw new Error("role must be one of 'active', 'passive', 'actpass', 'holdconn'.");this.attributes.setup=t}}class b extends y{constructor(){super(...arguments),T(this,"attributes",{unrecognized:[],groups:[],extmaps:[],fingerprints:[],identities:[]})}parse(e){if(this.digested)throw new Error("already digested");try{switch(e.attField){case"group":this.parseGroup(e);break;case"ice-lite":this.parseIceLite();break;case"ice-ufrag":this.parseIceUfrag(e);break;case"ice-pwd":this.parseIcePwd(e);break;case"ice-options":this.parseIceOptions(e);break;case"fingerprint":this.parseFingerprint(e);break;case"setup":this.parseSetup(e);break;case"tls-id":this.parseTlsId(e);break;case"identity":this.parseIdentity(e);break;case"extmap":this.parseExtmap(e);break;case"msid-semantic":this.parseMsidSemantic(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e)}}catch(t){throw console.error("parsing session attribute ".concat(e.attField,' error, "a=').concat(e.attField,":").concat(e.attValue,'"')),t}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw new Error("attribute parsing error")}digest(){return this.digested=!0,this.attributes}parseGroup(e){const t=this.extract(e,this.consumeToken),n=[];for(;!this.atEnd(e)&&this.peekChar(e)===o;)this.consumeAttributeSpace(e),n.push(this.extract(e,this.consumeToken));this.attributes.groups.push({semantic:t,identificationTag:n})}parseIceLite(){if(this.attributes.iceLite)throw new Error("Invalid ice-lite, should be only a single line of 'a=ice-lite'");this.attributes.iceLite=!0}parseTlsId(e){if(this.attributes.tlsId)throw new Error("must be only one tld-id line");this.attributes.tlsId=this.extractOneOrMore(e,m)}parseIdentity(e){const t=this.extractOneOrMore(e,f),n=[];for(;!this.atEnd(e)&&this.peekChar(e)===o;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.extract(e,this.consume,"=");const i=this.extractOneOrMore(e,(e=>e!==o&&_(e)));n.push({name:t,value:i})}this.attributes.identities.push({assertionValue:t,extensions:n})}parseMsidSemantic(e){this.peekChar(e)===o&&this.consumeAttributeSpace(e);const t={semantic:this.extract(e,this.consumeToken),identifierList:[]};for(;;){try{this.consumeAttributeSpace(e)}catch(e){break}if("*"===this.peekChar(e)){this.extract(e,this.consume,"*"),t.applyForAll=!0;break}{const n=this.extract(e,this.consumeTill,o);t.identifierList.push(n)}}this.attributes.msidSemantic=t}}class C extends y{constructor(e){super(),T(this,"attributes",void 0),-1!==e.protos.indexOf("RTP")||e.protos.indexOf("rtp"),this.attributes={unrecognized:[],candidates:[],extmaps:[],fingerprints:[],imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[]}}parse(e){if(this.digested)throw new Error("already digested");try{switch(e.attField){case"extmap":this.parseExtmap(e);break;case"setup":this.parseSetup(e);break;case"ice-ufrag":this.parseIceUfrag(e);break;case"ice-pwd":this.parseIcePwd(e);break;case"ice-options":this.parseIceOptions(e);break;case"candidate":this.parseCandidate(e);break;case"remote-candidate":this.parseRemoteCandidate(e);break;case"end-of-candidates":this.parseEndOfCandidates();break;case"fingerprint":this.parseFingerprint(e);break;case"rtpmap":this.parseRtpmap(e);break;case"ptime":this.parsePtime(e);break;case"maxptime":this.parseMaxPtime(e);break;case"sendrecv":case"recvonly":case"sendonly":case"inactive":this.parseDirection(e);break;case"ssrc":this.parseSSRC(e);break;case"fmtp":this.parseFmtp(e);break;case"rtcp-fb":this.parseRtcpFb(e);break;case"rtcp-mux":this.parseRTCPMux();break;case"rtcp-mux-only":this.parseRTCPMuxOnly();break;case"rtcp-rsize":this.parseRTCPRsize();break;case"rtcp":this.parseRTCP(e);break;case"mid":this.parseMid(e);break;case"msid":this.parseMsid(e);break;case"imageattr":this.parseImageAttr(e);break;case"rid":this.parseRid(e);break;case"simulcast":this.parseSimulcast(e);break;case"sctp-port":this.parseSctpPort(e);break;case"max-message-size":this.parseMaxMessageSize(e);break;case"ssrc-group":this.parseSSRCGroup(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e)}}catch(t){throw console.error("parsing media attribute ".concat(e.attField,' error, "a=').concat(e.attField,":").concat(e.attValue,'"')),t}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw new Error("attribute parsing error")}parseCandidate(e){const t=this.extractOneOrMore(e,E,[1,32]);this.consumeAttributeSpace(e);const n=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const r=this.extractOneOrMore(e,a,[1,10]);this.consumeAttributeSpace(e);const s=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const d=this.extract(e,this.consumePort);this.consumeAttributeSpace(e),this.extract(e,this.consume,"typ"),this.consumeAttributeSpace(e);const l={foundation:t,componentId:n,transport:i,priority:r,connectionAddress:s,port:d,type:this.extract(e,this.consumeToken),extension:{}};for(this.peek(e," raddr")&&(this.extract(e,this.consume," raddr"),this.consumeAttributeSpace(e),l.relAddr=this.extract(e,this.consumeAddress)),this.peek(e," rport")&&(this.extract(e,this.consume," rport"),this.consumeAttributeSpace(e),l.relPort=this.extract(e,this.consumePort));this.peekChar(e)===o;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e),l.extension[t]=this.extractOneOrMore(e,c)}this.attributes.candidates.push(l)}parseRemoteCandidate(e){const t=[];for(;;){const n=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const r=this.extract(e,this.consumePort);t.push({componentId:n,connectionAddress:i,port:r});try{this.consumeAttributeSpace(e)}catch(e){break}}this.attributes.remoteCandidatesList.push(t)}parseEndOfCandidates(){if(this.attributes.endOfCandidates)throw new Error("must be only one line of end-of-candidates");this.attributes.endOfCandidates=!0}parseRtpmap(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeTill,"/");this.extract(e,this.consume,"/");const i={encodingName:n,clockRate:this.extractOneOrMore(e,a)};this.atEnd(e)||"/"!==this.peekChar(e)||(this.extract(e,this.consume,"/"),i.encodingParameters=parseInt(this.extract(e,this.consumeTill),10));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.rtpMap=i:this.attributes.payloads.push({payloadType:parseInt(t,10),rtpMap:i,rtcpFeedbacks:[]})}parsePtime(e){if(this.attributes.ptime)throw new Error("must be only one line of ptime");this.attributes.ptime=this.extract(e,this.consumeTill)}parseMaxPtime(e){if(this.attributes.maxPtime)throw new Error("must be only one line of ptime");this.attributes.maxPtime=this.extract(e,this.consumeTill)}parseDirection(e){if(this.attributes.direction)throw new Error("must be only one line of direction info");this.attributes.direction=e.attField}parseSSRC(e){const t=this.extractOneOrMore(e,a);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeTill,":");let i;":"===this.peekChar(e)&&(this.extract(e,this.consume,":"),i=this.extract(e,this.consumeTill));const r=this.attributes.ssrcs.find((e=>e.ssrcId===parseInt(t,10)));r?r.attributes[n]=i:this.attributes.ssrcs.push({ssrcId:parseInt(t,10),attributes:{[n]:i}})}parseFmtp(e){const t=this.extract(e,this.consumeTill,o);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeTill),i={};n.split(";").forEach((e=>{let t=Hb(e.split("="),2),n=t[0],r=t[1];n=ZS(n).call(n);const o="string"==typeof r?ZS(r).call(r):null;"string"==typeof n&&n.length>0&&(i[n]=o)}));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.fmtp={parameters:i}:this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[],fmtp:{parameters:i}})}parseFmtParameters(e){const t={},n=this.extract(e,this.consumeTill,"=");e._cur++;const i=this.extract(e,this.consumeTill,";");for(t[n]=i;";"===e.attValue[e._cur];){const n=this.extract(e,this.consumeTill,"=");e._cur++;const i=this.extract(e,this.consumeTill,";");t[n]=i}return t}parseRtcpFb(e){let t="";t="*"===this.peekChar(e)?this.extract(e,this.consume,"*"):this.extract(e,this.consumeTill,o),this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeTill,o);let i;if("trr-int"===n)i={type:n,interval:this.extract(e,this.consumeTill)};else{const t={type:n};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.parameter=this.extract(e,this.consumeToken),this.peekChar(e)===o&&(t.additional=this.extract(e,this.consumeTill))),i=t}if("*"===t)this.attributes.rtcpFeedbackWildcards.push(i);else{const e=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));e?e.rtcpFeedbacks.push(i):this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[i]})}}parseRTCPMux(){if(this.attributes.rtcpMux)throw new Error("must be single line of rtcp-mux");this.attributes.rtcpMux=!0}parseRTCPMuxOnly(){if(this.attributes.rtcpMuxOnly)throw new Error("must be single line of rtcp-only");this.attributes.rtcpMuxOnly=!0}parseRTCPRsize(){if(this.attributes.rtcpRsize)throw new Error("must be single line of rtcp-rsize");this.attributes.rtcpRsize=!0}parseRTCP(e){if(this.attributes.rtcp)throw new Error("must be single line of rtcp");const t={port:this.extract(e,this.consumePort)};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.netType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.addressType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.address=this.extract(e,this.consumeAddress)),this.attributes.rtcp=t}parseMsid(e){const t={id:this.extractOneOrMore(e,l,[1,64])};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.appdata=this.extractOneOrMore(e,l,[1,64])),this.attributes.msids.push(t)}parseImageAttr(e){this.attributes.imageattr.push(e.attValue)}parseRid(e){const t=this.extractOneOrMore(e,(e=>h(e)||a(e)||"_"===e||"-"===e));this.consumeAttributeSpace(e);const n={id:t,direction:this.extract(e,this.consumeToken),params:[]};if(this.peekChar(e)===o){if(this.consumeAttributeSpace(e),this.peek(e,"pt=")){this.extract(e,this.consume,"pt=");const t=[];for(;;){const n=this.extract(e,this.consumeToken);t.push(n);try{this.extract(e,this.consume,",")}catch(e){break}}n.payloads=t,this.peekChar(e)===o&&this.extract(e,this.consume,o)}for(;;){const t=this.extract(e,this.consumeToken);switch(t){case"depend":{const i={type:t,rids:this.extract(e,this.consume,"=").split(",")};n.params.push(i);break}default:{const i={type:t};"="===this.peekChar(e)&&(this.extract(e,this.consume,"="),i.val=this.extract(e,this.consumeTill,";")),n.params.push(i)}}try{this.extract(e,this.consume,";")}catch(e){break}}}this.attributes.rids.push(n)}parseSimulcast(e){if(this.attributes.simulcast)throw new Error("must be single line of simulcast");this.attributes.simulcast=e.attValue,this.extract(e,this.consumeTill)}parseSctpPort(e){this.attributes.sctpPort=this.extractOneOrMore(e,a,[1,5])}parseMaxMessageSize(e){this.attributes.maxMessageSize=this.extractOneOrMore(e,a,[1,void 0])}digest(){return this.digested=!0,this.attributes}parseMid(e){this.attributes.mid=this.extract(e,this.consumeToken)}parseSSRCGroup(e){const t=this.extract(e,this.consumeToken),n=[];for(;;)try{this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeInteger);n.push(parseInt(t,10))}catch(e){break}this.attributes.ssrcGroups.push({semantic:t,ssrcIds:n})}}function I(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class A{constructor(){I(this,"eol",r)}print(e,t){let n="";return t&&(this.eol=t),n+=this.printVersion(e.version),n+=this.printOrigin(e.origin),n+=this.printSessionName(e.sessionName),n+=this.printInformation(e.information),n+=this.printUri(e.uri),n+=this.printEmail(e.emails),n+=this.printPhone(e.phones),n+=this.printConnection(e.connection),n+=this.printBandwidth(e.bandwidths),n+=this.printTimeFields(e.timeFields),n+=this.printKey(e.key),n+=this.printSessionAttributes(e.attributes),n+=this.printMediaDescription(e.mediaDescriptions),n}printVersion(e){return"v=".concat(e).concat(this.eol)}printOrigin(e){return"o=".concat(e.username," ").concat(e.sessId," ").concat(e.sessVersion," ").concat(e.nettype," ").concat(e.addrtype," ").concat(e.unicastAddress).concat(this.eol)}printSessionName(e){return e?"s=".concat(e).concat(this.eol):""}printInformation(e){return e?"i=".concat(e).concat(this.eol):""}printUri(e){return e?"u=".concat(e).concat(this.eol):""}printEmail(e){let t="";for(const n of e)t+="e=".concat(n).concat(this.eol);return t}printPhone(e){let t="";for(const n of e)t+="e=".concat(n).concat(this.eol);return t}printConnection(e){return e?"c=".concat(e.nettype," ").concat(e.addrtype," ").concat(e.address).concat(this.eol):""}printBandwidth(e){let t="";for(const n of e)t+="b=".concat(n.bwtype,":").concat(n.bandwidth).concat(this.eol);return t}printTimeFields(e){let t="";for(const n of e){t+="t=".concat(n.time.startTime," ").concat(n.time.startTime).concat(this.eol);for(const e of n.repeats)t+="r=".concat(e.repeatInterval," ").concat(e.typedTimes.join(" ")).concat(this.eol);n.zoneAdjustments&&(t+="z=",t+="z=".concat(n.zoneAdjustments.map((e=>"".concat(e.time," ").concat(e.back?"-":""," ").concat(e.typedTime))).join(" ")).concat(this.eol),t+=this.eol)}return t}printKey(e){return e?"k=".concat(e).concat(this.eol):""}printAttributes(e){let t="";for(const n of e)t+="a=".concat(n.attField).concat(n.attValue?":".concat(n.attValue):"").concat(this.eol);return t}printMediaDescription(e){let t="";for(const n of e)t+=this.printMedia(n.media),t+=this.printInformation(n.information),t+=this.printConnections(n.connections),t+=this.printBandwidth(n.bandwidths),t+=this.printKey(n.key),t+=this.printMediaAttributes(n);return t}printConnections(e){let t="";for(const n of e)t+=this.printConnection(n);return t}printMedia(e){return"m=".concat(e.mediaType," ").concat(e.port," ").concat(e.protos.join("/")," ").concat(e.fmts.join(" ")).concat(this.eol)}printSessionAttributes(e){return new O(this.eol).print(e)}printMediaAttributes(e){return new N(this.eol).print(e)}}class w{constructor(e){I(this,"eol",void 0),this.eol=e}printIceUfrag(e){return void 0===e?"":"a=ice-ufrag:".concat(e).concat(this.eol)}printIcePwd(e){return void 0===e?"":"a=ice-pwd:".concat(e).concat(this.eol)}printIceOptions(e){return void 0===e?"":"a=ice-options:".concat(e.join(o)).concat(this.eol)}printFingerprints(e){return e.length>0?e.map((e=>"a=fingerprint:".concat(e.hashFunction).concat(o).concat(e.fingerprint))).join(this.eol)+this.eol:""}printExtmap(e){return e.map((e=>"a=extmap:".concat(e.entry).concat(e.direction?"/".concat(e.direction):"").concat(o).concat(e.extensionName).concat(e.extensionAttributes?"".concat(o).concat(e.extensionAttributes):"").concat(this.eol))).join("")}printSetup(e){return void 0===e?"":"a=setup:".concat(e).concat(this.eol)}printUnrecognized(e){return e.map((e=>"a=".concat(e.attField).concat(e.attValue?":".concat(e.attValue):"").concat(this.eol))).join("")}}class O extends w{print(e){let t="";return t+=this.printGroups(e.groups),t+=this.printMsidSemantic(e.msidSemantic),t+=this.printIceLite(e.iceLite),t+=this.printIceUfrag(e.iceUfrag),t+=this.printIcePwd(e.icePwd),t+=this.printIceOptions(e.iceOptions),t+=this.printFingerprints(e.fingerprints),t+=this.printSetup(e.setup),t+=this.printTlsId(e.tlsId),t+=this.printIdentity(e.identities),t+=this.printExtmap(e.extmaps),t+=this.printUnrecognized(e.unrecognized),t}printGroups(e){let t="";return e.length>0&&(t+=e.map((e=>"a=group:".concat(e.semantic).concat(e.identificationTag.map((e=>"".concat(o).concat(e))).join("")).concat(this.eol))).join("")),t}printIceLite(e){return void 0===e?"":"a=ice-lite"+this.eol}printTlsId(e){return e?"a=tls-id:".concat(e).concat(this.eol):""}printIdentity(e){return 0===e.length?"":e.map((e=>"a=identity:".concat(e.assertionValue).concat(e.extensions.map((e=>"".concat(o).concat(e.name).concat(e.value?"=".concat(e.value):"")))))).join(this.eol)+this.eol}printMsidSemantic(e){if(!e)return"";let t="a=msid-semantic:".concat(e.semantic);return e.applyForAll?t+="".concat(o,"*"):e.identifierList.length>0&&(t+=e.identifierList.map((e=>"".concat(o).concat(e)))),t+this.eol}}class N extends w{print(e){const t=e.attributes;let n="";return n+=this.printRTCP(t.rtcp),n+=this.printIceUfrag(t.iceUfrag),n+=this.printIcePwd(t.icePwd),n+=this.printIceOptions(t.iceOptions),n+=this.printCandidates(t.candidates),n+=this.printRemoteCandidatesList(t.remoteCandidatesList),n+=this.printEndOfCandidates(t.endOfCandidates),n+=this.printFingerprints(t.fingerprints),n+=this.printSetup(t.setup),n+=this.printMid(t.mid),n+=this.printExtmap(t.extmaps),n+=this.printRTPRelated(t),n+=this.printPtime(t.ptime),n+=this.printMaxPtime(t.maxPtime),n+=this.printDirection(t.direction),n+=this.printSSRCGroups(t.ssrcGroups),n+=this.printSSRC(t.ssrcs),n+=this.printRTCPMux(t.rtcpMux),n+=this.printRTCPMuxOnly(t.rtcpMuxOnly),n+=this.printRTCPRsize(t.rtcpRsize),n+=this.printMSId(t.msids),n+=this.printImageattr(t.imageattr),n+=this.printRid(t.rids),n+=this.printSimulcast(t.simulcast),n+=this.printSCTPPort(t.sctpPort),n+=this.printMaxMessageSize(t.maxMessageSize),n+=this.printUnrecognized(t.unrecognized),n}printCandidates(e){return e.map((e=>"a=candidate:".concat(e.foundation).concat(o).concat(e.componentId).concat(o).concat(e.transport).concat(o).concat(e.priority).concat(o).concat(e.connectionAddress).concat(o).concat(e.port).concat(o,"typ").concat(o).concat(e.type).concat(e.relAddr?"".concat(o,"raddr").concat(o).concat(e.relAddr):"").concat(e.relPort?"".concat(o,"rport").concat(o).concat(e.relPort):"").concat(Object.keys(e.extension).map((t=>"".concat(o).concat(t).concat(o).concat(e.extension[t]))).join("")).concat(this.eol))).join("")}printRemoteCandidatesList(e){return e.map((e=>"a=remote-candidates:".concat(e.join(o)).concat(this.eol))).join("")}printEndOfCandidates(e){return void 0===e?"":"a=end-of-candidates"+this.eol}printRTPRelated(e){if(!e.payloads)return"";const t=e.payloads;let n="";n+=e.rtcpFeedbackWildcards.map((e=>this.printRTCPFeedback("*",e))).join("");for(const e of t)n+=this.printRtpMap(e.payloadType,e.rtpMap),n+=this.printFmtp(e.payloadType,e.fmtp),n+=e.rtcpFeedbacks.map((t=>this.printRTCPFeedback(e.payloadType,t))).join("");return n}printFmtp(e,t){if(!t)return"";const n=Object.keys(t.parameters);return 1===n.length&&null===t.parameters[n[0]]?"a=fmtp:".concat(e).concat(o).concat(n[0]).concat(this.eol):"a=fmtp:".concat(e).concat(o).concat(Object.keys(t.parameters).map((e=>"".concat(e,"=").concat(t.parameters[e]))).join(";")).concat(this.eol)}printRtpMap(e,t){return t?"a=rtpmap:".concat(e).concat(o).concat(t.encodingName,"/").concat(t.clockRate).concat(t.encodingParameters?"/".concat(t.encodingParameters):"").concat(this.eol):""}printRTCPFeedback(e,t){let n="a=rtcp-fb:".concat(e).concat(o),i=t;return"trr-int"===i.type?n+="ttr-int".concat(o).concat(i.interval):(n+="".concat(i.type),i.parameter&&(n+="".concat(o).concat(i.parameter),i.additional&&(n+="".concat(o).concat(i.additional)))),n+this.eol}printPtime(e){return void 0===e?"":"a=ptime:".concat(e).concat(this.eol)}printMaxPtime(e){return void 0===e?"":"a=maxptime:".concat(e).concat(this.eol)}printDirection(e){return void 0===e?"":"a=".concat(e).concat(this.eol)}printSSRC(e){return e.map((e=>Object.keys(e.attributes).map((t=>"a=ssrc:".concat(e.ssrcId.toString(10)).concat(o).concat(t).concat(e.attributes[t]?":".concat(e.attributes[t]):"").concat(this.eol))).join(""))).join("")}printRTCPMux(e){return void 0===e?"":"a=rtcp-mux".concat(this.eol)}printRTCPMuxOnly(e){return void 0===e?"":"a=rtcp-mux-only".concat(this.eol)}printRTCPRsize(e){return void 0===e?"":"a=rtcp-rsize".concat(this.eol)}printRTCP(e){if(void 0===e)return"";let t="a=rtcp:".concat(e.port);return e.netType&&(t+="".concat(o).concat(e.netType)),e.addressType&&(t+="".concat(o).concat(e.addressType)),e.address&&(t+="".concat(o).concat(e.address)),t+this.eol}printMSId(e){return e.map((e=>"a=msid:".concat(e.id).concat(e.appdata?"".concat(o).concat(e.appdata):"").concat(this.eol))).join("")}printImageattr(e){return e.map((e=>"a=imageattr:".concat(e).concat(this.eol))).join("")}printRid(e){return e.map((e=>{let t="a=rid:".concat(e.id).concat(o).concat(e.direction);return e.payloads&&(t+="".concat(o,"pt=").concat(e.payloads.join(","))),e.params.length>0&&(t+="".concat(o).concat(e.params.map((e=>"depend"===e.type?"depend=".concat(e.rids.join(",")):"".concat(e.type,"=").concat(e.val))).join(";"))),t+this.eol})).join("")}printSimulcast(e){return void 0===e?"":"a=simulcast:".concat(e).concat(this.eol)}printSCTPPort(e){return void 0===e?"":"a=sctp-port:".concat(e).concat(this.eol)}printMaxMessageSize(e){return void 0===e?"":"a=max-message-size:".concat(e).concat(this.eol)}printMid(e){return void 0===e?"":"a=mid:".concat(e).concat(this.eol)}printSSRCGroups(e){return e.map((e=>"a=ssrc-group:".concat(e.semantic).concat(e.ssrcIds.map((e=>"".concat(o).concat(e.toString(10)))).join("")).concat(this.eol))).join("")}}function D(e){return(new v).parse(e)}function P(e,t){return(new A).print(e,t)}}},t={};function n(i){if(t[i])return t[i].exports;var r=t[i]={exports:{}};return e[i](r,r.exports,n),r.exports}return n.d=(e,t)=>{for(var i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n(8)})();function EL(e){return _L.parse(e)}function mL(e,t){return _L.print(e,t)}var fL=ii("Array","keys"),gL=Si,SL=$e,TL=l,RL=fL,vL=Array.prototype,yL={DOMTokenList:!0,NodeList:!0},bL=function(e){var t=e.keys;return e===vL||TL(vL,e)&&t===vL.keys||SL(yL,gL(e))?RL:t},CL=n(bL);function IL(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function AL(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function wL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function OL(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?wL(Object(n),!0).forEach((function(t){AL(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):wL(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function NL(e,t){return NL=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},NL(e,t)}function DL(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,o,s,a=[],c=!0,d=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=o.call(n)).done)&&(a.push(i.value),a.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return IL(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?IL(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function PL(){PL=function(e,t){return new n(e,void 0,t)};var e=RegExp.prototype,t=new WeakMap;function n(e,i,r){var o=RegExp(e,i);return t.set(o,r||t.get(e)),NL(o,n.prototype)}function i(e,n){var i,r=t.get(n);return ar(i=Object.keys(r)).call(i,(function(t,n){var i=r[n];if("number"==typeof i)t[n]=e[i];else{for(var o=0;void 0===e[i[o]]&&o+1<i.length;)o++;t[n]=e[i[o]]}return t}),Object.create(null))}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&NL(e,t)}(n,RegExp),n.prototype.exec=function(t){var n=e.exec.call(this,t);if(n){n.groups=i(n,this);var r=n.indices;r&&(r.groups=i(r,this))}return n},n.prototype[Symbol.replace]=function(n,r){if("string"==typeof r){var o=t.get(this);return e[Symbol.replace].call(this,n,r.replace(/\$<([^>]+)(>|$)/g,(function(e,t,n){if(""===n)return e;var i=o[t];return Array.isArray(i)?"$"+i.join("$"):"number"==typeof i?"$"+i:""})))}if("function"==typeof r){var s=this;return e[Symbol.replace].call(this,n,(function(){var e=arguments;return"object"!=typeof e[e.length-1]&&(e=[].slice.call(e)).push(i(e,s)),r.apply(this,e)}))}return e[Symbol.replace].call(this,n,r)},PL.apply(this,arguments)}const LL=new class extends hD{constructor(){super(...arguments),AL(this,"currentUploadLogID",0)}reportLogUploadError(e){const t=e.errorRange;t[t.length-1]&&t[t.length-1]>this.currentUploadLogID&&(this.currentUploadLogID=t[t.length-1],this.emit("REPORT_LOG_UPLOAD",e))}};function kL(){const e=new Date;return e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}function ML(){const e=new Date,t=/((\d+:){2}\d+)/.exec((new Date).toUTCString());return t?(null==t?void 0:t[0])+":"+e.getUTCMilliseconds():e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}const UL={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},VL=Date.now(),xL=e=>{for(const t in UL)if(Object.prototype.hasOwnProperty.call(UL,t)&&UL[t]===e)return t;return"DEFAULT"};const FL=new class{constructor(){AL(this,"proxyServerURL",void 0),AL(this,"logLevel",UL.DEBUG),AL(this,"uploadState","collecting"),AL(this,"uploadLogWaitingList",[]),AL(this,"uploadLogUploadingList",[]),AL(this,"uploadErrorCount",0),AL(this,"currentLogID",0),AL(this,"url",void 0),AL(this,"extLog",((e,t)=>{this.appendLogToWaitingList(e,...t)}))}debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[UL.DEBUG].concat(t);this.log.apply(this,i)}info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[UL.INFO].concat(t);this.log.apply(this,i)}warning(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[UL.WARNING].concat(t);this.log.apply(this,i)}warn(){this.warning(...arguments)}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[UL.ERROR].concat(t);this.log.apply(this,i)}upload(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[UL.DEBUG].concat(t);this.uploadLog.apply(this,i)}setLogLevel(e){e=Math.min(Math.max(0,e),4),this.logLevel=e}enableLogUpload(){iL("UPLOAD_LOG",!0)}disableLogUpload(){iL("UPLOAD_LOG",!1),this.uploadLogUploadingList=[],this.uploadLogWaitingList=[]}setProxyServer(e){this.proxyServerURL=e}prefix(e){return new class{constructor(e){AL(this,"logger",void 0),AL(this,"prefixLists",[]),this.logger=e}debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.logger.debug(...this.prefixLists,...t)}info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.logger.info(...this.prefixLists,...t)}warning(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.logger.warning(...this.prefixLists,...t)}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.logger.error(...this.prefixLists,...t)}prefix(e){return this.prefixLists.push(e),this}popPrefix(){return this.prefixLists.pop(),this}}(this).prefix(e)}log(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];if(Date.now()-VL<100)return void setTimeout((()=>{this.log(...t)}),Date.now()-VL);const i=Math.max(0,Math.min(4,t[0]));if(t[0]=kL()+" Agora-SDK [".concat(xL(i),"]:"),this.appendLogToWaitingList(i,...t),i<this.logLevel)return;const r=kL()+" %cAgora-SDK [".concat(xL(i),"]:");let o=[];if(!rL("USE_NEW_LOG"))switch(i){case UL.DEBUG:o=[r,"color: #64B5F6;"].concat(t.slice(1)),console.log.apply(console,o);break;case UL.INFO:o=[r,"color: #1E88E5; font-weight: bold;"].concat(t.slice(1)),console.log.apply(console,o);break;case UL.WARNING:o=[r,"color: #FB8C00; font-weight: bold;"].concat(t.slice(1)),console.warn.apply(console,o);break;case UL.ERROR:o=[r,"color: #B00020; font-weight: bold;"].concat(t.slice(1)),console.error.apply(console,o)}}uploadLog(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];if(Date.now()-VL<100)return void setTimeout((()=>{this.uploadLog(...t)}),Date.now()-VL);const i=Math.max(0,Math.min(4,t[0]));t[0]=kL()+" Agora-SDK [".concat(xL(i),"]:"),this.appendLogToWaitingList(i,...t)}appendLogToWaitingList(e){if(!rL("UPLOAD_LOG"))return;for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];Array.isArray(n[0])?n[0][0]=ML()+" Agora-SDK [".concat(xL(e),"]:"):n[0]=ML()+" Agora-SDK [".concat(xL(e),"]:");let r="";n.forEach((e=>{"object"==typeof e&&(e=JSON.stringify(e)),r+="".concat(e," ")})),this.uploadLogWaitingList.push({payload_str:r,log_level:e,log_item_id:this.currentLogID++}),"uploading"===this.uploadState&&0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}startUpload(){this.uploadState="uploading",0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}async uploadLogs(){const e=this.uploadLogUploadingList,t={sdk_version:JP,process_id:rL("PROCESS_ID"),payload:JSON.stringify(e)};return gP((async()=>{const e=await QO.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(rL("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(rL("LOG_UPLOAD_SERVER"),"/upload/v1")),t,{responseType:"text"});if("OK"!==e.data){const t=new Error("unexpected upload log response");throw t.response=e,t}}),(()=>(this.uploadLogUploadingList=[],!1)),(t=>{const n={status:-1,message:t.message,errorRange:e.map((e=>e.log_item_id))};return t.response?(n.status=t.response.status,n.data=t.response.data,n.headers=t.response.headers):t.request&&(n.status=t.request.status),LL.reportLogUploadError(n),!0}),{timeout:rL("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:rL("UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL")})}uploadLogInterval(){0===this.uploadLogUploadingList.length&&0===this.uploadLogWaitingList.length||(0===this.uploadLogUploadingList.length&&(this.uploadLogUploadingList=this.uploadLogWaitingList.splice(0,rL("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then((()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout((()=>this.uploadLogInterval()),rL("UPLOAD_LOG_INTERVAL"))})).catch((e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout((()=>this.uploadLogInterval()),rL("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout((()=>this.uploadLogInterval()),rL("UPLOAD_LOG_RETRY_INTERVAL_V1"))})))}};var BL;function jL(e){return eD(e.reportId,"params.reportId",0,100,!1),eD(e.category,"params.category",0,100,!1),eD(e.event,"params.event",0,100,!1),eD(e.label,"params.label",0,100,!1),QN(e.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}(BL={}).FREE="free",BL.UPLOADING="uploading",function(e){e[e.MISC=0]="MISC",e[e.INTERNAL_EVENT=1]="INTERNAL_EVENT",e[e.PUBLIC_EVENT=2]="PUBLIC_EVENT",e[e.WEB_EVENT=3]="WEB_EVENT",e[e.INTERNAL_API=4]="INTERNAL_API",e[e.WEB_API=5]="WEB_API",e[e.PUBLIC_API=6]="PUBLIC_API"}({});let GL=function(e){return e[e.RECOVER=0]="RECOVER",e[e.WARNING=1]="WARNING",e[e.ERROR=2]="ERROR",e}({}),WL=function(e){return e.CONFIG_DISTRIBUTE="config-distribute-error",e}({});const KL={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};let HL=function(e){return e.PUBLISH="publish",e.SUBSCRIBE="subscribe",e.WS_COMPRESSOR_INIT="ws_compressor_init",e.SESSION_INIT="session_init",e.JOIN_CHOOSE_SERVER="join_choose_server",e.RTE_DETAIL="rte_detail_stats",e.REQ_USER_ACCOUNT="req_user_account",e.JOIN_GATEWAY="join_gateway",e.REJOIN_GATEWAY="rejoin_gateway",e.STREAM_SWITCH="stream_switch",e.REQUEST_PROXY_WORKER_MANAGER="request_proxy_worker_manager",e.REQUEST_PROXY_APPCENTER="request_proxy_appcenter",e.FIRST_VIDEO_RECEIVED="first_video_received",e.FIRST_AUDIO_RECEIVED="first_audio_received",e.FIRST_VIDEO_DECODE="first_video_decode",e.FIRST_AUDIO_DECODE="first_audio_decode",e.XLA_PEER_FIRST_VIDEO_FRAME="xla_peer_first_video_frame",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_UPDATE_STREAM="on_update_stream",e.ON_REMOVE_STREAM="on_remove_stream",e.USER_ANALYTICS="req_user_analytics",e.PC_STATS="pc_stats",e.UPDATE_REMOTE_RTPCAPABILITIES="update_remote_rtpCapabilities",e.AB_TEST="ab_test",e.ALARM_STATUS_NOTIFY="alarm_status_notify",e}({}),YL=function(e){return e.SESSION="io.agora.pb.Wrtc.Session",e.JOIN_CHOOSE_SERVER="io.agora.pb.Wrtc.JoinChooseServer",e.RTE_DETAIL="io.agora.pb.Wrtc.RteDetailStats",e.REQ_USER_ACCOUNT="io.agora.pb.Wrtc.ReqUserAccount",e.JOIN_GATEWAY="io.agora.pb.Wrtc.JoinGateway",e.RE_JOIN_GATEWAY="io.agora.pb.Wrtc.ReJoinGateway",e.PUBLISH="io.agora.pb.Wrtc.Publish",e.SUBSCRIBE="io.agora.pb.Wrtc.Subscribe",e.WS_COMPRESSOR_INIT="io.agora.pb.Wrtc.WsCompressorInit",e.STREAM_SWITCH="io.agora.pb.Wrtc.StreamSwitch",e.AUDIO_SENDING_STOPPED="io.agora.pb.Wrtc.AudioSendingStopped",e.VIDEO_SENDING_STOPPED="io.agora.pb.Wrtc.VideoSendingStopped",e.REQUEST_PROXY_APPCENTER="io.agora.pb.Wrtc.RequestProxyAppCenter",e.REQUEST_PROXY_WORKER_MANAGER="io.agora.pb.Wrtc.RequestProxyWorkerManager",e.API_INVOKE="io.agora.pb.Wrtc.ApiInvoke",e.FIRST_VIDEO_RECEIVED="io.agora.pb.Wrtc.FirstVideoReceived",e.FIRST_AUDIO_RECEIVED="io.agora.pb.Wrtc.FirstAudioReceived",e.FIRST_VIDEO_DECODE="io.agora.pb.Wrtc.FirstVideoDecode",e.FIRST_AUDIO_DECODE="io.agora.pb.Wrtc.FirstAudioDecode",e.XLA_PEER_FIRST_VIDEO_FRAME="io.agora.pb.Wrtc.XLAPeerFirstVideoFrame",e.ON_ADD_AUDIO_STREAM="io.agora.pb.Wrtc.OnAddAudioStream",e.ON_ADD_VIDEO_STREAM="io.agora.pb.Wrtc.OnAddVideoStream",e.ON_UPDATE_STREAM="io.agora.pb.Wrtc.OnUpdateStream",e.ON_REMOVE_STREAM="io.agora.pb.Wrtc.OnRemoveStream",e.JOIN_CHANNEL_TIMEOUT="io.agora.pb.Wrtc.JoinChannelTimeout",e.PEER_PUBLISH_STATUS="io.agora.pb.Wrtc.PeerPublishStatus",e.WORKER_EVENT="io.agora.pb.Wrtc.WorkerEvent",e.AP_WORKER_EVENT="io.agora.pb.Wrtc.APWorkerEvent",e.JOIN_WEB_PROXY_AP="io.agora.pb.Wrtc.JoinWebProxyAP",e.WEBSOCKET_QUIT="io.agora.pb.Wrtc.WebSocketQuit",e.USER_ANALYTICS="io.agora.pb.Wrtc.UserAnalytics",e.AUTOPLAY_FAILED="io.agora.pb.Wrtc.AutoplayFailed",e.PC_STATS="io.agora.pb.Wrtc.PCStats",e.UPDATE_REMOTE_RTPCAPABILITIES="io.agora.pb.Wrtc.UpdateRemoteRTPCapabilities",e.AB_TEST="io.agora.pb.Wrtc.ABTest",e.ALARM_STATUS_NOTIFY="io.agora.pb.Wrtc.AlarmStatusNotify",e}({});!function(e){e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT"}({});let XL=function(e){return e[e.SESSION=26]="SESSION",e[e.JOIN_CHOOSE_SERVER=27]="JOIN_CHOOSE_SERVER",e[e.REQ_USER_ACCOUNT=196]="REQ_USER_ACCOUNT",e[e.JOIN_GATEWAY=28]="JOIN_GATEWAY",e[e.PUBLISH=30]="PUBLISH",e[e.SUBSCRIBE=29]="SUBSCRIBE",e[e.WS_COMPRESSOR_INIT=9430]="WS_COMPRESSOR_INIT",e[e.STREAM_SWITCH=32]="STREAM_SWITCH",e[e.AUDIO_SENDING_STOPPED=33]="AUDIO_SENDING_STOPPED",e[e.VIDEO_SENDING_STOPPED=34]="VIDEO_SENDING_STOPPED",e[e.REQUEST_PROXY_APPCENTER=35]="REQUEST_PROXY_APPCENTER",e[e.REQUEST_PROXY_WORKER_MANAGER=36]="REQUEST_PROXY_WORKER_MANAGER",e[e.API_INVOKE=41]="API_INVOKE",e[e.FIRST_VIDEO_RECEIVED=348]="FIRST_VIDEO_RECEIVED",e[e.FIRST_AUDIO_RECEIVED=349]="FIRST_AUDIO_RECEIVED",e[e.FIRST_VIDEO_DECODE=350]="FIRST_VIDEO_DECODE",e[e.FIRST_AUDIO_DECODE=351]="FIRST_AUDIO_DECODE",e[e.ON_ADD_AUDIO_STREAM=352]="ON_ADD_AUDIO_STREAM",e[e.ON_ADD_VIDEO_STREAM=353]="ON_ADD_VIDEO_STREAM",e[e.ON_UPDATE_STREAM=356]="ON_UPDATE_STREAM",e[e.ON_REMOVE_STREAM=355]="ON_REMOVE_STREAM",e[e.JOIN_CHANNEL_TIMEOUT=407]="JOIN_CHANNEL_TIMEOUT",e[e.PEER_PUBLISH_STATUS=408]="PEER_PUBLISH_STATUS",e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT",e[e.JOIN_WEB_PROXY_AP=700]="JOIN_WEB_PROXY_AP",e[e.WEBSOCKET_QUIT=671]="WEBSOCKET_QUIT",e[e.USER_ANALYTICS=1e4]="USER_ANALYTICS",e[e.AUTOPLAY_FAILED=9178]="AUTOPLAY_FAILED",e}({});const JL="[config-restore]",zL="websdk_ng_",ZL=zL+"blocked_config_hashes",qL=zL+"api_failure_records",QL=zL+"global_parameter",$L=zL+"config_restore_state";function ek(e){var t;return null==e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?"["+e.map((e=>ek(e))).join(",")+"]":"{"+n_(t=Object.keys(e)).call(t).map((t=>JSON.stringify(t)+":"+ek(e[t]))).join(",")+"}"}function tk(e){return function(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}(ek(e))}function nk(){try{const e=window.localStorage.getItem($L);if(e)return JSON.parse(e)}catch(e){}return{currentConfigHash:"",configVerified:!1}}function ik(e){try{window.localStorage.setItem($L,JSON.stringify(e))}catch(e){}}function rk(){try{const e=window.localStorage.getItem(qL);return e?JSON.parse(e):[]}catch(e){return FL.debug("[error] ".concat(JL," error getting API failure records:"),e),[]}}function ok(){var e;return ar(e=rk()).call(e,((e,t)=>e+t.count),0)}function sk(){try{window.localStorage.removeItem(qL)}catch(e){FL.debug("[error] ".concat(JL," error clearing API failure records:"),e)}}function ak(){try{const e=ok(),t=rL("MAX_CONFIG_RETRY");if(e<t)return;const n=nk().currentConfigHash;FL.debug("[warning] ".concat(JL," restoring config due to ").concat(e," API failures")),n&&function(e){try{const t=window.localStorage.getItem(ZL);let n=[];t&&(n=JSON.parse(t).configHashes);const i=[...new Set([...n,e])];window.localStorage.setItem(ZL,JSON.stringify({configHashes:i,timestamp:Date.now()})),FL.debug("[warning] ".concat(JL," blocked config hash: ").concat(e))}catch(e){FL.debug("[error] ".concat(JL," error blocking config hash:"),e)}}(n),window.localStorage.removeItem(QL);const i=rk().slice(-5);(function(e,t){uk.reportAlarm(e,t)})(null,{status:GL.ERROR,type:WL.CONFIG_DISTRIBUTE,message:"Config cache cleared due to API failures",extend:{failureCount:e,maxRetry:t,blockedConfigHash:n,recentFailures:i.map((e=>({api:e.apiName,error:e.errorCode||e.errorMessage,count:e.count,lastTime:e.lastTimestamp})))}}),sk()}catch(e){FL.debug("[error] ".concat(JL," error restoring config:"),e)}}function ck(e,t){try{if(!rL("ENABLE_CONFIG_RESTORE"))return;if(t&&"AgoraRTCException"===t.name){const e=rL("CONFIG_ERROR_MONITOR");if(!Array.isArray(e)||!Vi(e).call(e,t.code))return}const n=window.localStorage.getItem(QL);if(!n||n.length<20)return;if(nk().configVerified)return;const i=rL("CONFIG_RESTORE_ERROR_API");if(!Array.isArray(i)||!Vi(i).call(i,e))return;let r,o;t&&(t.code&&(r=t.code),o=t.message?t.message:"string"==typeof t?t:t.toString()),function(e,t,n){try{const i=rk(),r="".concat(e,":").concat(t||""),o=i.find((e=>"".concat(e.apiName,":").concat(e.errorCode||"")===r)),s=nk().currentConfigHash;if(o)o.count++,o.lastTimestamp=Date.now(),n&&(o.errorMessage=n),s&&(o.configHash=s);else{const r=Date.now();i.push({apiName:e,errorCode:t,errorMessage:n,count:1,firstTimestamp:r,lastTimestamp:r,configHash:s||void 0})}const a=i.length>20?i.slice(-20):i;window.localStorage.setItem(qL,JSON.stringify(a))}catch(e){FL.debug("[error] ".concat(JL," error saving API failure record:"),e)}}(e,r,o);const s=ok(),a=rL("MAX_CONFIG_RETRY");FL.debug("".concat(JL," API failure count: ").concat(s,"/").concat(a,", API: ").concat(e,", Error: ").concat(r||o)),s>=a&&ak()}catch(e){}}function dk(){try{window.localStorage.removeItem(ZL)}catch(e){FL.debug("[error] ".concat(JL," error resetting blocked config:"),e)}}function lk(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,n,i){const r=i.value;if("function"==typeof r){const o=e.className||t.__className__||("AgoraRTCClient"===t.constructor.name?"Client":t.constructor.name);i.value=function(){for(var t,i=arguments.length,s=new Array(i),a=0;a<i;a++)s[a]=arguments[a];let c=s;if(e.argsMap)try{c=e.argsMap(this,...s)}catch(e){FL.warning(e),c=[]}try{JSON.stringify(c)}catch(e){FL.warning("arguments for method ".concat(o,".").concat(String(n)," not serializable for apiInvoke.")),c=[]}const d=(e.report||uk).reportApiInvoke(this._sessionId||null,{id:this._clientId||(null===(t=this.store)||void 0===t?void 0:t.clientId)||this._ID,name:"".concat(o,".").concat(String(n)),options:c,tag:mD.TRACER,reportResult:e.reportResult},e.throttleTime);try{const t=r.apply(this,s);return t instanceof dp?t.then((t=>(d.onSuccess(e.reportResult&&t),t))).catch((e=>{throw d.onError(e),e})):(d.onSuccess(e.reportResult&&t),t)}catch(e){throw d.onError(e),e}}}return i}}const uk=new class{constructor(){AL(this,"baseInfoMap",new Map),AL(this,"proxyServer",void 0),AL(this,"eventUploadTimer",void 0),AL(this,"setSessionIdTimer",void 0),AL(this,"url",void 0),AL(this,"sids",new Set),AL(this,"backupUrl",void 0),AL(this,"_appId",void 0),AL(this,"_aid",0),AL(this,"keyEventUploadPendingItems",[]),AL(this,"normalEventUploadPendingItems",[]),AL(this,"apiInvokeUploadPendingItems",[]),AL(this,"apiInvokeCount",0),AL(this,"apiInvokeLoggedCount",0),AL(this,"ltsList",[]),AL(this,"lastSendNormalEventTime",Date.now()),AL(this,"customReportCounterTimer",void 0),AL(this,"customReportCount",0),AL(this,"extApiInvoke",(async e=>{for(const t of e){const e=OL(OL({},t),{},{sid:null,invokeId:++this.apiInvokeCount,tag:mD.TRACER});this.sendApiInvoke(e)}})),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),rL("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),rL("EVENT_REPORT_SEND_INTERVAL"))}getBaseInfoBySessionId(e){return this.baseInfoMap.get(e)}setAppId(e){this._appId=e,this._aid=parseInt(e.replace(/[a-fA-F0-9]{8}/g,(e=>{let t=DL(e,2);return t[0]+t[1]})),16)||0}reportApiInvoke(e,t,n){t.timeout=t.timeout||6e4,t.reportResult=void 0===t.reportResult||t.reportResult;const i=Date.now();this.apiInvokeCount+=1;const r=this.apiInvokeCount,o=!!rL("SHOW_REPORT_INVOKER_LOG"),s=!!rL("SHOW_REPORT_USER_INVOKER_LOG"),a=o||s&&t.id;a&&(this.apiInvokeLoggedCount+=1);const c=this.apiInvokeLoggedCount;function d(e,n){if(a){let i="[apiInvoke-".concat(c,"]");if(t.id&&(i+="[".concat(t.id,"]")),t.name&&(i+="[".concat(t.name,"]"),t.name===ED.JOIN))return FL.info("".concat(i," ").concat(e));FL.info("".concat(i," ").concat(e),"start"===e?t.options:n||"")}}const l=()=>({tag:t.tag,invokeId:r,sid:e,name:t.name,apiInvokeTime:i,options:t.options,states:t.states||null});d("start");let u=!1;$D(t.timeout).then((()=>{u||(this.sendApiInvoke(OL(OL({},l()),{},{error:JN.API_INVOKE_TIMEOUT,success:!1})),d("timeout"),ck(t.name,new zN(JN.API_INVOKE_TIMEOUT)))}));const h=new zN(JN.UNEXPECTED_ERROR,"".concat(t.name,": this api invoke is end"));return{onSuccess:e=>{const i=()=>{if(u)throw h;return u=!0,this.sendApiInvoke(OL(OL({},l()),{},{success:!0},t.reportResult&&{result:e})),d("onSuccess"),e};return n?rP(i,t.name+"Success",n,(()=>u=!0)):i()},onError:e=>{const i=()=>{if(u)throw e;u=!0,this.sendApiInvoke(OL(OL({},l()),{},{success:!1,error:e})),ck(t.name,e),d("onFailure",e.toString())};return n?rP(i,t.name+"Error",n,(()=>u=!0)):i()}}}_send(e,t,n){this.send({type:e,data:t},n)}_sendApiInvoke(e){return this.sendApiInvoke(e)}sessionInit(e,t){if(this.baseInfoMap.has(e))return;const n=Date.now(),i=this.createBaseInfo(e,n);i.cname=t.cname,i.rteUrl=t.rteUrl;const r=Object.assign({},{willUploadConsoleLog:rL("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:zP?"global":"oversea",areas:rL("AREAS")&&rL("AREAS").join(",")},t.extend),o=t.stringUid,s=t.channelProfile,a=t.channelMode,c=t.isABTestSuccess,d=t.lsid,l=t.clientRole,u=Date.now(),h=OL(OL({},i),{},{eventType:HL.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,buildFormat:t.buildFormat,build:eL,lts:u,elapse:u-n,extend:JSON.stringify(r),mode:t.mode,process:rL("PROCESS_ID"),appType:rL("APP_TYPE"),success:!0,version:JP,stringUid:o,channelProfile:s,channelMode:a,isABTestSuccess:c,lsid:d,clientType:GN()?42:20,clientRole:l,serviceId:rL("PROCESS_ID"),extensionID:rL("PLUGIN_INFO").join(",")||"",rteUrl:t.rteUrl,rteSid:t.rteSid,installId:XP()});this.send({type:YL.SESSION,data:h},!0)}reportRteDetail(e){const t=this.baseInfoMap.get(e);if(!t)return;const n=t.info,i=Date.now(),r=OL(OL({},n),{},{eventType:HL.RTE_DETAIL,lts:i,success:!0,elapse:i-t.startTime,vid:void 0===n.vid?0:Number(n.vid),ua:navigator.userAgent});this.send({type:YL.RTE_DETAIL,data:r},!0)}joinChooseServer(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info;t.vid&&(i.vid=t.vid);const r=Date.now(),o=OL(OL({},i),{},{role:t.role,eventType:HL.JOIN_CHOOSE_SERVER,lts:r,eventElapse:t.elapse||r-t.lts,chooseServerAddr:t.csAddr,errorCode:t.ec,elapse:r-n.startTime,success:t.succ,chooseServerAddrList:JSON.stringify(t.serverList),uid:t.uid?parseInt(t.uid):null,cid:t.cid?parseInt(t.cid):null,chooseServerIp:t.csIp||"",opid:t.opid,unilbsServerIds:t.unilbsServerIds,extend:t.extend||void 0,isHttp3:t.isHttp3,corssRegionTagReq:t.corssRegionTagReq||void 0,corssRegionTagRes:t.corssRegionTagRes||void 0,ua:navigator.userAgent,resourceTimingInfo:t.resourceTimingInfo||void 0});this.send({type:YL.JOIN_CHOOSE_SERVER,data:o},!0)}reqUserAccount(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=OL(OL({},i),{},{eventType:HL.REQ_USER_ACCOUNT,lts:r,success:t.success,serverAddress:t.serverAddr,stringUid:t.stringUid,uid:t.uid,errorCode:t.errorCode,elapse:t.elapse||r-n.startTime,eventElapse:r-t.lts,extend:JSON.stringify(t.extend)});this.send({type:YL.REQ_USER_ACCOUNT,data:o},!0)}joinGateway(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info;t.vid&&(i.vid=t.vid),i.uid=t.uid,i.cid=t.cid;const r=Date.now(),o=t.firstSuccess,s=t.addr,a=t.isProxy,c=r-n.startTime,d=OL(OL({},i),{},{eventType:HL.JOIN_GATEWAY,lts:r,gatewayAddr:t.addr,success:t.succ,errorCode:t.ec,errorMsg:t.errorMsg||"",elapse:c,eventElapse:r-t.lts,firstSuccess:o,signalChannel:t.signalChannel,preload:t.preload?1:0,installId:XP(),isABTestSuccess:t.isABTestSuccess?1:0,gatewayIp:null,gatewayPort:null,isProxy:a?1:0}),l=d.success?1:0;if(t.succ&&(n.lastJoinSuccessTime=r),s)if("1"===d.signalChannel){const e=PL(/(\d+\.\d+\.\d+\.\d+):(\d+)/,{ip:1,port:2}),t=s.match(e);d.gatewayIp=t&&t.groups?t.groups.ip:"",d.gatewayPort=t&&t.groups?t.groups.port:""}else if(a){const e=s.match(/h=(\d{1,3}-){3}\d{1,3}/g),t=s.match(/p=[0-9]{1,6}/g);d.gatewayIp=e&&e.length?e[0].split("=")[1].replace(/-/g,"."):"",d.gatewayPort=t&&t.length?t[0].split("=")[1]:""}else{const e=s.match(/wss:\/\/(\d{1,3}-){3}\d{1,3}/g),t=s.match(/(:|p=)[0-9]{1,6}/g);d.gatewayIp=e&&e.length?e[0].split("//")[1].replace(/-/g,"."):"",d.gatewayPort=t&&t.length?t[0].split(/:|p=/g)[1]:""}if(o)this.send({type:YL.JOIN_GATEWAY,data:d},!0);else{const e={isSuccess:l,port:d.gatewayPort};delete d.success,delete d.eventType,delete d.firstSuccess,delete d.gatewayPort,d.vid=Number(d.vid);const t=Object.assign({},d,e,{eventType:HL.REJOIN_GATEWAY});this.send({type:YL.RE_JOIN_GATEWAY,data:t},!0)}}joinChannelTimeout(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=Date.now(),r=OL(OL({},n.info),{},{lts:i,timeout:t,elapse:i-n.startTime});this.send({type:YL.JOIN_CHANNEL_TIMEOUT,data:r},!0)}publish(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=OL(OL({},i),{},{eventType:HL.PUBLISH,lts:r,eventElapse:t.eventElapse,elapse:r-n.startTime,success:t.succ,errorCode:t.ec,videoName:t.videoName,audioName:t.audioName,screenName:t.screenName,screenshare:t.screenshare,audio:t.audio,video:t.video,p2pid:t.p2pid,publishRequestid:t.publishRequestid});this.send({type:YL.PUBLISH,data:o},!0)}subscribe(e,t,n){const i=this.baseInfoMap.get(e);if(!i)return;const r=i.info,o=Date.now(),s=OL(OL({},r),{},{eventType:HL.SUBSCRIBE,lts:o,eventElapse:t.eventElapse,elapse:o-i.startTime,success:t.succ,errorCode:t.ec,video:t.video,audio:t.audio,subscribeRequestid:t.subscribeRequestid,p2pid:t.p2pid,preSsrc:t.preSsrc?1:0},n&&{extend:JSON.stringify({isMassSubscribe:!0})});"string"==typeof t.peerid?s.peerSuid=t.peerid:s.peer=t.peerid,this.send({type:YL.SUBSCRIBE,data:s},!0)}wsCompressorInit(e){var t;const n=[...CL(t=this.baseInfoMap).call(t)],i=n.length?n[0]:"UnableToGetSid",r=this.baseInfoMap.get(i);if(!r)return;const o=r.info,s=Date.now(),a=OL(OL({},o),{},{eventType:HL.WS_COMPRESSOR_INIT,lts:s,eventElapse:e.eventElapse,elapse:s-r.startTime,status:e.status?1:2});this.send({type:YL.WS_COMPRESSOR_INIT,data:a},!0)}firstXLAPeerFirstVideoFrame(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=t.peerPubStatusMs-(n.lastJoinSuccessTime||r),s=OL(OL({},i),{},{elapse:r-n.startTime,eventType:HL.XLA_PEER_FIRST_VIDEO_FRAME,lts:r,peer:t.peer,width:t.width,height:t.height,ssrc:t.ssrc,p2pid:t.p2pid,peerPublishDuration:t.peerPublishDuration,joinChannelSuccessElapse:o,peerPubStatusMs:t.peerPubStatusMs-t.joinChannelStart,availablePublish:t.peerPublishDuration>o?1:0,preloadStart:Math.max(t.preloadStart-t.joinChannelStart,0),preloadEnd:Math.max(t.preloadEnd-t.joinChannelStart,0),encrypt:Math.max(t.apStart-t.joinChannelStart,0),ap:Math.max(t.apEnd-t.joinChannelStart,0),sua:Math.max(t.suaEnd-t.joinChannelStart,0),beforeConnect:Math.max(t.beforeConnect-t.joinChannelStart,0),peerRecevier:Math.max(t.peerReceiver-t.joinChannelStart,0),ice:Math.max(t.ice-t.joinChannelStart,0),pc:Math.max(t.pc-t.joinChannelStart,0),signalConnected:Math.max(t.signalConnected-t.joinChannelStart,0),joinReq:Math.max(t.joinReq-t.joinChannelStart,0),joinRes:Math.max(t.joinRes-t.joinChannelStart,0),userJoinNotify:Math.max(t.userJoinNotify-t.joinChannelStart,0),videoSsrcNotify:Math.max(t.videoAddNotify-t.joinChannelStart,0),subscribeDelayMs:Math.max(t.subscribeStart-t.videoAddNotify,0),subscribeStart:Math.max(t.subscribeStart-t.joinChannelStart,0),subscribeEnd:Math.max(t.subscribeEnd-t.joinChannelStart,0),firstReceived:Math.max(t.firstReceived-t.joinChannelStart,0),firstDecoded:Math.max(t.firstDecoded-t.joinChannelStart,0),firstPreRender:Math.max(t.firstPreRender-t.joinChannelStart,0),firstRender:Math.max(t.firstRender-t.joinChannelStart,0),playDelayMs:Math.max(t.playStart-t.subscribeEnd,0),playStart:Math.max(t.playStart-t.joinChannelStart,0),playEnd:Math.max(t.playEnd-t.joinChannelStart,0),isPreSub:t.isPreSub?1:0,isPrePc:t.isPrePc?1:0,isPreInstantVideo:t.isPreInstantVideo?1:0,firstReceivedEncodedFrame:t.firstReceivedEncodedFrame?Math.max(t.firstReceivedEncodedFrame-t.joinChannelStart,0):void 0,frameType:t.frameType||"",rtpTimestamp:t.rtpTimestamp||0,framePayloadType:t.framePayloadType||0,frameDataLength:t.frameDataLength||0,mimeType:t.mimeType||"",sdpEndPoint:t.sdpEndPoint?1:0});this.send({type:YL.XLA_PEER_FIRST_VIDEO_FRAME,data:s},!0)}firstRemoteVideoDecode(e,t,n,i){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=OL(OL(OL({},o),i),{},{elapse:s-r.startTime,eventType:t,lts:s,firstDecodeFrame:Math.max((i.firstFrame||s)-r.startTime,0),apEnd:Math.max(i.apEnd-r.startTime,0),apStart:Math.max(i.apStart-r.startTime,0),joinGwEnd:Math.max(i.joinGwEnd-r.startTime,0),joinGwStart:Math.max(i.joinGwStart-r.startTime,0),pcEnd:Math.max(i.pcEnd-r.startTime,0),pcStart:Math.max(i.pcStart-r.startTime,0),subscriberEnd:Math.max(i.subscriberEnd-r.startTime,0),subscriberStart:Math.max(i.subscriberStart-r.startTime,0),videoAddNotify:Math.max(i.videoAddNotify-r.startTime,0)});this.send({type:n,data:a},!0)}firstRemoteFrame(e,t,n,i){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=OL(OL(OL({},o),i),{},{elapse:s-r.startTime,eventType:t,lts:s});this.send({type:n,data:a},!0)}abTest(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=OL(OL(OL({},i),t),{},{vid:void 0===i.vid?0:Number(i.vid),elapse:r-n.startTime,eventType:HL.AB_TEST,lts:r});this.send({type:YL.AB_TEST,data:o},!0)}pcStats(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=OL(OL(OL({},i),t),{},{vid:void 0===i.vid?0:Number(i.vid),elapse:r-n.startTime,eventType:HL.PC_STATS,lts:r,preallocation:t.preallocation?1:0});this.send({type:YL.PC_STATS,data:o},!0)}updateRemoteRTPCapabilities(e,t){if(e){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=OL(OL(OL({},i),t),{},{vid:void 0===i.vid?0:Number(i.vid),eventType:HL.UPDATE_REMOTE_RTPCAPABILITIES,lts:r});this.send({type:YL.UPDATE_REMOTE_RTPCAPABILITIES,data:o},!0)}}onGatewayStream(e,t,n,i){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=OL(OL(OL({},o),i),{},{eventType:t,lts:s});this.send({type:n,data:a},!0)}streamSwitch(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=OL(OL({},i),{},{eventType:HL.STREAM_SWITCH,lts:r,isDual:t.isdual,elapse:r-n.startTime,success:t.succ});this.send({type:YL.STREAM_SWITCH,data:o},!0)}requestProxyAppCenter(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=OL(OL({},i),{},{eventType:HL.REQUEST_PROXY_APPCENTER,lts:r,eventElapse:r-t.lts,elapse:r-n.startTime,APAddr:t.APAddr,workerManagerList:t.workerManagerList,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:YL.REQUEST_PROXY_APPCENTER,data:o},!0)}requestProxyWorkerManager(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=OL(OL({},i),{},{eventType:HL.REQUEST_PROXY_WORKER_MANAGER,lts:r,eventElapse:r-t.lts,elapse:r-n.startTime,workerManagerAddr:t.workerManagerAddr,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:YL.REQUEST_PROXY_WORKER_MANAGER,data:o},!0)}setProxyServer(e){this.proxyServer=e,e?FL.debug("reportProxyServerurl: ".concat(e)):FL.debug("disable reportProxyServerurl: ".concat(e))}peerPublishStatus(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=OL(OL({},i),{},{subscribeElapse:t.subscribeElapse,peer:t.peer,peerPublishDuration:Math.max(t.audioPublishDuration,t.videoPublishDuration),audiotag:t.audioPublishDuration>0?1:-1,videotag:t.videoPublishDuration>0?1:-1,lts:r,elapse:r-n.startTime,joinChannelSuccessElapse:r-(n.lastJoinSuccessTime||r),peerPublishDurationVideo:t.videoPublishDuration,peerPublishDurationAudio:t.audioPublishDuration});this.send({type:YL.PEER_PUBLISH_STATUS,data:o},!0)}workerEvent(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now();(function(e,t,n){const i=e[t];if(!i||"string"!=typeof i)return[e];e[t]="";const r=ZD(JSON.stringify(e));let o=0;const s=[];let a=0;for(let c=0;c<i.length;c++)a+=i.charCodeAt(c)<=127?1:3,a<=n-r||(s[s.length]=YN(YN({},e),{},{[t]:i.substring(o,c)}),o=c,a=i.charCodeAt(c)<=127?1:3);return o!==i.length-1&&(s[s.length]=YN(YN({},e),{},{[t]:i.substring(o)})),s})(OL(OL(OL({},i),t),{},{elapse:r-n.startTime,lts:r,productType:"WebRTC"}),"payload",1300).forEach((e=>this.send({type:YL.WORKER_EVENT,data:e},!0)))}apworkerEvent(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=OL(OL(OL({},i),t),{},{elapse:r-n.startTime,lts:r});this.send({type:YL.AP_WORKER_EVENT,data:o},!0)}joinWebProxyAP(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=OL(OL(OL({},i),t),{},{elapse:r-n.startTime,lts:r,extend:t.extend||void 0});this.send({type:YL.JOIN_WEB_PROXY_AP,data:o},!0)}WebSocketQuit(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=OL(OL(OL({},i),t),{},{elapse:r-n.startTime,lts:r});this.send({type:YL.WEBSOCKET_QUIT,data:o},!0)}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>rL("CUSTOM_REPORT_LIMIT"))throw new zN(JN.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval((()=>{this.customReportCount=0}),5e3));const n=Date.now(),i=t.map((t=>({type:YL.USER_ANALYTICS,data:OL(OL({sid:e},t),{},{lts:n})})));try{rL("NEW_REPORT_SERVER")?await this.postDataToStatsCollector2(i):await this.postDataToStatsCollector(i)}catch(e){throw FL.error("send custom report message failed",e.toString()),new zN(JN.CUSTOM_REPORT_SEND_FAILED,e.message)}}reportAlarm(e,t){const n=e?this.baseInfoMap.get(e):void 0,i=null==n?void 0:n.info,r=Date.now(),o=OL(OL(OL({},i),t),{},{vid:void 0===(null==i?void 0:i.vid)?0:Number(i.vid),elapse:n?r-n.startTime:0,eventType:HL.ALARM_STATUS_NOTIFY,lts:r,installId:XP(),processId:rL("PROCESS_ID")});this.send({type:YL.ALARM_STATUS_NOTIFY,data:o},!0)}sendApiInvoke(e){const t=rL("NOT_REPORT_EVENT");if(e.tag&&Vi(t)&&Vi(t).call(t,e.tag))return!1;if(null===e.sid)return this.apiInvokeUploadPendingItems.push(e),!1;const n=this.baseInfoMap.get(e.sid);if(!n)return this.apiInvokeUploadPendingItems.push(e),!1;const i=n.info,r=i.cname,o=i.uid,s=i.cid;let a;if(e.lts=e.lts||Date.now(),e.error)if(e.error instanceof zN){const t=e.error,n=t.code,i=t.message;a=n||i||e.error.toString()}else a=e.error.toString();const c={invokeId:e.invokeId,sid:e.sid,cname:r,cid:s,uid:o,lts:e.lts,success:e.success,elapse:e.lts-n.startTime,execElapse:e.lts-e.apiInvokeTime,apiName:e.name,options:e.options?JSON.stringify(e.options):void 0,execStates:e.states?JSON.stringify(e.states):void 0,execResult:e.result?JSON.stringify(e.result):void 0,errorCode:e.error?a:void 0,errorMsg:e.error?JSON.stringify(e.error):void 0};return this.send({type:YL.API_INVOKE,data:c},!1),!0}addSid(e){this.sids.add(e)}removeSid(e){this.sids.delete(e)}appendSessionId(){const e=this.apiInvokeUploadPendingItems;if(0===e.length)return;const t=Array.from(this.sids).find((e=>null!==e));t&&e.forEach((e=>{e&&(e.sid=t,this.sendApiInvoke(Object.assign({},e)))})),e.length=0}send(e,t){if(t)return this.keyEventUploadPendingItems.push(e),void this.sendItems(this.keyEventUploadPendingItems,!0);this.normalEventUploadPendingItems.push(e),this.normalEventUploadPendingItems.length>rL("NORMAL_EVENT_QUEUE_CAPACITY")&&this.normalEventUploadPendingItems.splice(0,1),this.normalEventUploadPendingItems.length>=10&&this.sendItems(this.normalEventUploadPendingItems,!1)}doSend(){this.keyEventUploadPendingItems.length>0&&this.sendItems(this.keyEventUploadPendingItems,!0),this.normalEventUploadPendingItems.length>0&&Date.now()-this.lastSendNormalEventTime>=5e3&&this.sendItems(this.normalEventUploadPendingItems,!1)}sendItems(e,t){const n=[],i=[];for(;e.length;){const t=e.shift();n.length<20?n.push(t):i.push(t)}e.push(...i);for(const e of[...n]){var r;-1!==this.ltsList.indexOf(e.data.lts)?(e.data.lts=this.ltsList[this.ltsList.length-1]+1,this.ltsList.push(e.data.lts)):(this.ltsList.push(e.data.lts),n_(r=this.ltsList).call(r,((e,t)=>e-t)))}return t||(this.lastSendNormalEventTime=Date.now()),rL("ENABLE_EVENT_REPORT")?(n.length&&(rL("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(n):this.postDataToStatsCollector(n)).catch((e=>n=>{rL("EVENT_REPORT_RETRY")&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(e):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(e),this.normalEventUploadPendingItems.length>rL("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-rL("NORMAL_EVENT_QUEUE_CAPACITY")),FL.warning("report: drop normal events"))))})(n)),e):e}async postDataToStatsCollector2(e){LD.networkState===AD.OFFLINE&&await dp.race([LD.onlineWaiter,$D(2*mP.maxRetryTimeout)]);const t=e=>{let t=new Uint8Array;return e.forEach((e=>{const n=dD(JSON.stringify(e.data)),i=new ArrayBuffer(5),r=(e=>{let t=0;return Object.entries(YL).forEach((n=>{let i=DL(n,2),r=i[0];i[1]===e.type&&(t=XL[r])})),t})(e),o=new DataView(i);o.setUint16(0,n.byteLength,!0),o.setUint8(2,255&r),o.setUint8(3,r>>>8&255),o.setUint8(4,r>>>16&255),t=lD(t,new Uint8Array(i)),t=lD(t,n)})),t},n="event";let i=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(rL("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(n):"https://".concat(rL("NEW_REPORT_SERVER_DOMAINS")[0],"/").concat(n);for(let r=0;r<2;r+=1){1===r&&(i=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(rL("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(n):"https://".concat(rL("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(n));try{await yP(i,{timeout:1e4,data:t(e),headers:OL(OL({biz:"webrtc",sendts:Math.round(Date.now()/1e3),debug:"false"},this._appId&&{appid:this._appId}),{},{"Content-Type":"application/octet-stream"})},!0)}catch(e){if(1===r)throw e;continue}return}}async postDataToStatsCollector(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=(e=>{const t=e&&e.data.sid&&this.baseInfoMap.get(e.data.sid);return t&&t.info.vid&&+t.info.vid||0})(e[0]),i=n?void 0:this._aid,r={msgType:"EventMessages",sentTs:Math.round(Date.now()/1e3),payloads:e.map((e=>JSON.stringify(e))),vid:n,aid:i};LD.networkState===AD.OFFLINE&&await dp.race([LD.onlineWaiter,$D(2*mP.maxRetryTimeout)]);const o=t?"/events/proto-raws":"/events/messages";let s=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(rL("EVENT_REPORT_DOMAIN"),"&p=").concat(rL("STATS_COLLECTOR_PORT"),"&d=").concat(o):"https://".concat(rL("EVENT_REPORT_DOMAIN"),":").concat(rL("STATS_COLLECTOR_PORT")).concat(o));for(let e=0;e<2;e+=1){1===e&&(s=this.backupUrl||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(rL("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(rL("STATS_COLLECTOR_PORT"),"&d=").concat(o):"https://".concat(rL("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(rL("STATS_COLLECTOR_PORT")).concat(o)));try{t?await bP(s,{timeout:1e4,data:r}):await yP(s,{timeout:1e4,data:r})}catch(t){if(1===e)throw t;continue}return}}createBaseInfo(e,t){const n=Object.assign({},KL);return n.sid=e,this.baseInfoMap.set(e,{info:n,startTime:t}),n}reportResourceTiming(e,t){const n=performance.getEntriesByName(e),i=n[n.length-1];i&&this.reportApiInvoke(t,{name:"Client.resourceTiming",options:i,tag:mD.TRACER}).onSuccess()}};LL.on("REPORT_LOG_UPLOAD",(e=>{e.networkState=LD.networkState,uk.reportApiInvoke(null,{name:"logUploadError",options:e,tag:mD.TRACER}).onSuccess("logUploadError")}));let hk=class extends zN{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",arguments.length>2?arguments[2]:void 0),AL(this,"name","AgoraRTCException")}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return super.print(e,FL)}throw(){super.throw(FL)}};const pk={getDisplayMedia:!1,getStreamFromExtension:!1,supportUnifiedPlan:!1,supportMinBitrate:!1,supportSetRtpSenderParameters:!1,supportDualStream:!0,webAudioMediaStreamDest:!1,supportReplaceTrack:!1,supportWebGL:!1,webAudioWithAEC:!1,supportRequestFrame:!1,supportShareAudio:!1,supportDualStreamEncoding:!1,supportDataChannel:!1,supportPCSetConfiguration:!1,supportWebRTCEncodedTransform:!1,supportWebRTCInsertableStream:!1,supportRequestVideoFrameCallback:!1,supportWebCrypto:!1,supportSuppressLocalAudioPlayback:!1,supportRestrictOwnAudio:!1};function _k(){return pk}function Ek(){return"setSinkId"in HTMLAudioElement.prototype&&(!rL("RESTRICTION_SET_PLAYBACK_DEVICE")||(_N()||gN())&&!xN())}function mk(){return!pk.supportUnifiedPlan||rL("CHROME_FORCE_PLAN_B")&&FN()}function fk(){return rL("ENABLE_JOIN_V4")}function gk(e){return!(SN()||vN(87)||mk()||!rL("ENABLE_PRE_SUB")&&(null==e||!e.autoSubscribe||rL("FORCE_DISABLE_AUTO_SUB")))}function Sk(e){return rL("ENABLE_INSTANT_VIDEO")?rL("ENABLE_INSTANT_VIDEO"):!(null==e||!e.autoSubscribe||rL("FORCE_DISABLE_AUTO_SUB"))}function Tk(){return!!rL("FORCE_ENABLE_AUT_CC")||!mk()&&(!!rL("ENABLE_AUT_CC")||void 0)}function Rk(){return!!rL("FORCE_ENABLE_AUT_CC")||!mk()&&(!!rL("ENABLE_AUT_FEEDBACK")||void 0)}function vk(){return navigator.mediaDevices&&"getSupportedConstraints"in navigator.mediaDevices}function yk(){if(vk()){const e=navigator.mediaDevices.getSupportedConstraints();return!(!("suppressLocalAudioPlayback"in e)||!e.suppressLocalAudioPlayback)}return RN(141)||bN(141)||NN(141)}function bk(){if(vk()){const e=navigator.mediaDevices.getSupportedConstraints();return!(!("restrictOwnAudio"in e)||!e.restrictOwnAudio)}return RN(141)||bN(141)||NN(125)}let Ck=function(e){return e.IOS_15_16_INTERRUPTION_START="ios15_16-interruption-start",e.IOS_15_16_INTERRUPTION_END="ios15_16-interruption-end",e.IOS_INTERRUPTION_START="ios-interruption-start",e.IOS_INTERRUPTION_END="ios-interruption-end",e.STATE_CHANGE="state-change",e}({});function Ik(e,t,n){return{sampleRate:e,stereo:t,bitrate:n}}function Ak(e,t,n,i,r){return{width:e,height:t,frameRate:n,bitrateMin:i,bitrateMax:r}}function wk(e,t,n,i,r){return{width:{max:e},height:{max:t},frameRate:n,bitrateMin:i,bitrateMax:r}}function Ok(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const Nk={"90p":Ak(160,90),"90p_1":Ak(160,90),"120p":Ak(160,120,15,30,65),"120p_1":Ak(160,120,15,30,65),"120p_3":Ak(120,120,15,30,50),"120p_4":Ak(212,120),"180p":Ak(320,180,15,30,140),"180p_1":Ak(320,180,15,30,140),"180p_3":Ak(180,180,15,30,100),"180p_4":Ak(240,180,15,30,120),"240p":Ak(320,240,15,40,200),"240p_1":Ak(320,240,15,40,200),"240p_3":Ak(240,240,15,40,140),"240p_4":Ak(424,240,15,40,220),"360p":Ak(640,360,15,80,400),"360p_1":Ak(640,360,15,80,400),"360p_3":Ak(360,360,15,80,260),"360p_4":Ak(640,360,30,80,600),"360p_6":Ak(360,360,30,80,400),"360p_7":Ak(480,360,15,80,320),"360p_8":Ak(480,360,30,80,490),"360p_9":Ak(640,360,15,80,800),"360p_10":Ak(640,360,24,80,800),"360p_11":Ak(640,360,24,80,1e3),"480p":Ak(640,480,15,100,500),"480p_1":Ak(640,480,15,100,500),"480p_2":Ak(640,480,30,100,1e3),"480p_3":Ak(480,480,15,100,400),"480p_4":Ak(640,480,30,100,750),"480p_6":Ak(480,480,30,100,600),"480p_8":Ak(848,480,15,100,610),"480p_9":Ak(848,480,30,100,930),"480p_10":Ak(640,480,10,100,400),"720p":Ak(1280,720,15,120,1130),"720p_auto":Ak(1280,720,30,900,3e3),"720p_1":Ak(1280,720,15,120,1130),"720p_2":Ak(1280,720,30,120,2e3),"720p_3":Ak(1280,720,30,120,1710),"720p_5":Ak(960,720,15,120,910),"720p_6":Ak(960,720,30,120,1380),"1080p":Ak(1920,1080,15,120,2080),"1080p_1":Ak(1920,1080,15,120,2080),"1080p_2":Ak(1920,1080,30,120,3e3),"1080p_3":Ak(1920,1080,30,120,3150),"1080p_5":Ak(1920,1080,60,120,4780),"1440p":Ak(2560,1440,30,120,4850),"1440p_1":Ak(2560,1440,30,120,4850),"1440p_2":Ak(2560,1440,60,120,7350),"4k":Ak(3840,2160,30,120,8910),"4k_1":Ak(3840,2160,30,120,8910),"4k_3":Ak(3840,2160,60,120,13500)},Dk={"480p":wk(640,480,5),"480p_1":wk(640,480,5),"480p_2":wk(640,480,30),"480p_3":wk(640,480,15),"720p":wk(1280,720,5),"720p_auto":Ak(1280,720,30,900,3e3),"720p_1":wk(1280,720,5),"720p_2":wk(1280,720,30),"720p_3":wk(1280,720,15),"1080p":wk(1920,1080,5),"1080p_1":wk(1920,1080,5),"1080p_2":wk(1920,1080,30),"1080p_3":wk(1920,1080,15)},Pk={"1SL1TL":Ok(1,1),"3SL3TL":Ok(3,3),"2SL3TL":Ok(2,3)};function Lk(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},Nk[e]):e}function kk(e){return"string"==typeof e?Object.assign({},Dk[e]):e}function Mk(e){return"string"==typeof e?Object.assign({},Pk[e]):e}const Uk={speech_low_quality:Ik(16e3,!1),speech_standard:Ik(32e3,!1,18),music_standard:Ik(48e3,!1),standard_stereo:Ik(48e3,!0,56),high_quality:Ik(48e3,!1,128),high_quality_stereo:Ik(48e3,!0,192)};function Vk(e){return"string"==typeof e?Object.assign({},Uk[e]):e}const xk=[];function Fk(e){return qN(e,"mediaSource",["screen","window","application"]),!0}let Bk=function(e){return e.NEED_RENEGOTIATE="@need_renegotiate",e.NEED_REPLACE_TRACK="@need_replace_track",e.NEED_REPLACE_MIXING_TRACK="@need_replace_mixing_track",e.NEED_CLOSE="@need_close",e.NEED_ENABLE_TRACK="@need_enable_track",e.NEED_DISABLE_TRACK="@need_disable_track",e.NEED_SESSION_ID="@need_sid",e.SET_OPTIMIZATION_MODE="@set_optimization_mode",e.GET_STATS="@get_stats",e.GET_RTC_STATS="@get_rtc_stats",e.GET_LOW_VIDEO_TRACK="@get_low_video_track",e.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",e.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",e.NEED_UPDATE_VIDEO_SEND_PARAMETERS="@need_update_video_send_parameters",e.NEED_MUTE_TRACK="@need_mute_track",e.NEED_UNMUTE_TRACK="@need_unmute_track",e}({}),jk=function(e){return e.SCREEN_TRACK="screen_track",e.CUSTOM_TRACK="custome_track",e.LOW_STREAM="low_stream",e.SCREEN_LOW_TRACK="screen_low_track",e}({});let Gk=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e}({}),Wk=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.HIGH_STREAM_LAYER1=4]="HIGH_STREAM_LAYER1",e[e.HIGH_STREAM_LAYER2=5]="HIGH_STREAM_LAYER2",e[e.HIGH_STREAM_LAYER3=6]="HIGH_STREAM_LAYER3",e[e.HIGH_STREAM_LAYER4=7]="HIGH_STREAM_LAYER4",e[e.HIGH_STREAM_LAYER5=8]="HIGH_STREAM_LAYER5",e[e.HIGH_STREAM_LAYER6=9]="HIGH_STREAM_LAYER6",e}({}),Kk=function(e){return e[e.DISABLE=0]="DISABLE",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.AUDIO_ONLY=2]="AUDIO_ONLY",e[e.HIGH_STREAM_LAYER1=3]="HIGH_STREAM_LAYER1",e[e.HIGH_STREAM_LAYER2=4]="HIGH_STREAM_LAYER2",e[e.HIGH_STREAM_LAYER3=5]="HIGH_STREAM_LAYER3",e[e.HIGH_STREAM_LAYER4=6]="HIGH_STREAM_LAYER4",e[e.HIGH_STREAM_LAYER5=7]="HIGH_STREAM_LAYER5",e[e.HIGH_STREAM_LAYER6=8]="HIGH_STREAM_LAYER6",e}({}),Hk=function(e){return e.TRANSCEIVER_UPDATED="transceiver-updated",e.SEI_TO_SEND="sei-to-send",e.SEI_RECEIVED="sei-received",e.TRACK_UPDATED="track-updated",e}({}),Yk=function(e){return e.SOURCE_STATE_CHANGE="source-state-change",e.TRACK_ENDED="track-ended",e.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.CLOSED="closed",e}({}),Xk=function(e){return e.FIRST_FRAME_DECODED="first-frame-decoded",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.VIDEO_STATE_CHANGED="video-state-changed",e.PLAY_START="play-start",e.PLAY_END="play-end",e.FIRST_FRAME_RENDER="first-frame-render",e}({}),Jk=function(e){return e.AUDIO="audio",e.VIDEO="video",e.DATA="data",e}({}),zk=function(e){return e.AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",e.RECEIVE_TRACK_BUFFER="receive_track_buffer",e.ON_AUDIO_BUFFER="on_audio_buffer",e.UPDATE_SOURCE="update_source",e}({});!function(e){e.UPDATE_TRACK_SOURCE="update-track-source"}({});const Zk={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},qk={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,sendResolutionHeight:0,sendResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},Qk={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receivePacketsDiscarded:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},$k={uplinkNetworkQuality:0,downlinkNetworkQuality:0},eM={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receiveResolutionHeight:0,receiveResolutionWidth:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1};let tM=function(e){return e.ON_TRACK="on_track",e.ON_NODE="on_node",e}({}),nM=function(e){return e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints",e}({}),iM=function(e){return e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND",e}({}),rM=function(e){return e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged",e}({}),oM=function(e){return e.NONE="none",e.INIT="init",e.CANPLAY="canplay",e.PLAYING="playing",e.PAUSED="paused",e.SUSPEND="suspend",e.STALLED="stalled",e.WAITING="waiting",e.ERROR="error",e.DESTROYED="destroyed",e.ABORT="abort",e.ENDED="ended",e.EMPTIED="emptied",e.LOADEDDATA="loadeddata",e}({}),sM=function(e){return e[e.VideoStateStopped=0]="VideoStateStopped",e[e.VideoStateStarting=1]="VideoStateStarting",e[e.VideoStateDecoding=2]="VideoStateDecoding",e[e.VideoStateFrozen=3]="VideoStateFrozen",e}({});const aM={uninit:100,none:110,init:120,loadeddata:130,canplay:200,playing:210,paused:220,suspend:300,stalled:310,waiting:320,error:330,destroyed:340,abort:350,ended:360,emptied:370};let cM=function(e){return e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error",e}({});function dM(e,t,n,i,r){var o,s,a={};return Object.keys(i).forEach((function(e){a[e]=i[e]})),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=ar(o=Tr(s=n.slice()).call(s)).call(o,(function(n,i){return i(e,t,n)||n}),a),r&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(r):void 0,a.initializer=void 0),void 0===a.initializer?(Object.defineProperty(e,t,a),null):a}function lM(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function uM(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function hM(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function pM(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?hM(Object(n),!0).forEach((function(t){uM(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):hM(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function _M(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,o,s,a=[],c=!0,d=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=o.call(n)).done)&&(a.push(i.value),a.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return lM(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?lM(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}let EM=class extends hD{set _mediaStreamTrack(e){e!==this.mediaStreamTrack&&(this.safeEmit(Hk.TRACK_UPDATED,e),this.mediaStreamTrack=e)}get _mediaStreamTrack(){return this.mediaStreamTrack}constructor(e,t){super(),uM(this,"trackMediaType",void 0),uM(this,"_ID",void 0),uM(this,"_rtpTransceiver",void 0),uM(this,"_lowRtpTransceiver",void 0),uM(this,"_hints",[]),uM(this,"_isClosed",!1),uM(this,"_originMediaStreamTrack",void 0),uM(this,"mediaStreamTrack",void 0),uM(this,"_external",{}),this._ID=t||eP(8,"track-"),this._originMediaStreamTrack=e,this.mediaStreamTrack=e,function(e){Vi(xk).call(xk,e)||xk.push(e)}(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){return e||HD((()=>{var e;uk.reportApiInvoke(null,{name:ED.GET_MEDIA_STREAM_TRACK,options:[],tag:mD.TRACER}).onSuccess((null===(e=this._mediaStreamTrack)||void 0===e?void 0:e.label)||"")}),this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===Gk.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,function(e){const t=xk.indexOf(e);-1!==t&&xk.splice(t,1)}(this),this.emit(Yk.CLOSED),this.removeAllListeners(Hk.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===Gk.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(Hk.TRANSCEIVER_UPDATED,e,t)}},mM=class extends EM{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}constructor(e,t){super(e,t),uM(this,"_enabled",!0),uM(this,"_muted",!1),uM(this,"_isExternalTrack",!1),uM(this,"_isClosed",!1),uM(this,"_enabledMutex",void 0),uM(this,"processor",void 0),uM(this,"_processorContext",void 0),uM(this,"_handleTrackEnded",(()=>{this.onTrackEnded()})),this._enabledMutex=new _P("".concat(this.getTrackId())),e.addEventListener("ended",this._handleTrackEnded)}getTrackLabel(){var e,t;return null!==(e=null===(t=this._originMediaStreamTrack)||void 0===t?void 0:t.label)&&void 0!==e?e:""}close(){this._isClosed||(this.stop(),this._originMediaStreamTrack.stop(),this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack.stop(),this._mediaStreamTrack=null),this._originMediaStreamTrack=null,this._enabledMutex=null,FL.debug("[".concat(this.getTrackId(),"] close")),this.emit(Bk.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=n,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await ND(this,Bk.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){FL.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Yk.TRACK_ENDED)}stateCheck(e,t){if(FL.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),ZN(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new zN(JN.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",FL);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new zN(JN.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",FL)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():dp.resolve([])}};const fM=window.AudioContext||window.webkitAudioContext;let gM,SM=null;const TM=new class extends hD{constructor(){super(...arguments),uM(this,"prevState",void 0),uM(this,"curState",void 0),uM(this,"currentTime",void 0),uM(this,"currentTimeStuckAt",void 0),uM(this,"interruptDetectorTrack",void 0),uM(this,"onLocalAudioTrackMute",(()=>{FL.info("ios15-interruption-start"),this.emit(Ck.IOS_15_16_INTERRUPTION_START)})),uM(this,"onLocalAudioTrackUnmute",(async()=>{FL.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?FL.info("ios15-interruption-end-canceled"):(SM&&await SM.suspend(),this.emit(Ck.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){FL.debug("webaudio bindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack||(this.interruptDetectorTrack=e,this.interruptDetectorTrack._mediaStreamTrack.onmute=this.onLocalAudioTrackMute,this.interruptDetectorTrack._mediaStreamTrack.onunmute=this.onLocalAudioTrackUnmute)}unbindInterruptDetectorTrack(e){FL.debug("webaudio unbindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack&&this.interruptDetectorTrack===e&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=null),this.interruptDetectorTrack=void 0)}};function RM(){if(!SM){if(function(){if(!fM)return void FL.error("your browser is not support web audio");FL.info("create audio context");const e=pM({},rL("WEBAUDIO_INIT_OPTIONS"));FL.debug("audio context init option:",JSON.stringify(e)),SM=new fM(e),TM.curState=SM.state,SM.onstatechange=()=>{TM.prevState=TM.curState,TM.curState=SM?SM.state:void 0;const e=TM.prevState,t=TM.curState,n="running"===t,i="interrupted"===t,r="running"===e,o="suspended"===e,s="interrupted"===e,a=dN().osVersion;(TN()||MN())&&r&&i&&(FL.info("ios".concat(a,"-interruption-start")),TM.emit(Ck.IOS_INTERRUPTION_START)),(TN()||MN())&&(o||s)&&n&&(FL.info("ios".concat(a,"-interruption-end")),TM.emit(Ck.IOS_INTERRUPTION_END)),e!==t&&TM.emit(Ck.STATE_CHANGE,t,e)},setInterval((()=>{var e;const t=null===(e=SM)||void 0===e?void 0:e.currentTime;TM.currentTime!==t?(TM.currentTimeStuckAt&&(FL.debug("AudioContext current time resume at ".concat(t)),TM.currentTimeStuckAt=void 0),TM.currentTime=t):(t!==TM.currentTimeStuckAt&&(uk.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:mD.TRACER}).onSuccess(),FL.warning("AudioContext current time stuck at ".concat(t))),TM.currentTimeStuckAt=t)}),5e3),async function(e){const t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let n,i,r=!1,o=!1,s=!1;function a(t){"running"===e.state?c(!1):TN()||MN()?"suspended"===e.state&&(c(!0),t&&e.resume().then(d,d)):"closed"!==e.state&&(c(!0),t&&e.resume().then(d,d))}function c(e){if(r!==e){r=e;for(let n=0,i=t;n<i.length;n+=1){const t=i[n];e?window.addEventListener(t,l,{capture:!0,passive:!0}):window.removeEventListener(t,l,{capture:!0,passive:!0})}}}function d(){a(!1)}function l(){a(!0)}function u(){let e;try{e=n.play(),e?e.then(_,_):(n.addEventListener("playing",_),n.addEventListener("abort",_),n.addEventListener("error",_))}catch(e){_()}}function h(e){s||(n.paused?e?(p(!1),s=!0,u()):p(!0):p(!1))}function p(e){if(o!==e){o=e;for(let n=0,i=t;n<i.length;n++){const t=i[n];e?window.addEventListener(t,E,{capture:!0,passive:!0}):window.removeEventListener(t,E,{capture:!0,passive:!0})}}}function _(){n.removeEventListener("playing",_),n.removeEventListener("abort",_),n.removeEventListener("error",_),s=!1,h(!1)}function E(){h(!0)}if(TN()&&rL("IOS_BG_TAG")){const t=e.createMediaStreamDestination(),r=document.createElement("div");r.innerHTML="<audio x-webkit-airplay='deny'></audio>",n=r.children.item(0),n.controls=!1,n.disableRemotePlayback=!0,n.preload="auto",n.srcObject=t.stream,i=()=>{if(rL("IOS_AUTO_RESTART_BG_TAG")&&n&&n.srcObject&&!s&&(!n.paused||!0!==o)){n.paused||n.pause();try{s=!0,u()}catch(e){s=!1}return!0}},h(!0)}return TM.on(Ck.STATE_CHANGE,(function(){a(!0)})),a(!1),i}(SM).then((e=>{gM=e}))}(),!SM)throw new zN(JN.NOT_SUPPORTED,"can not create audio context");return SM}return SM}function vM(e){if(function(){if(null!==yM)return yM;const e=RM(),t=e.createBufferSource(),n=e.createGain(),i=e.createGain();t.connect(n),t.connect(i),t.disconnect(n);let r=!1;try{t.disconnect(n)}catch(e){r=!0}return t.disconnect(),yM=r,r}())return;const t=e.connect,n=e.disconnect;e.connect=(n,i,r)=>{var o;return e._inputNodes||(e._inputNodes=[]),Vi(o=e._inputNodes).call(o,n)||(n instanceof AudioNode?(e._inputNodes.push(n),t.call(e,n,i,r)):t.call(e,n,i)),e},e.disconnect=(i,r,o)=>{n.call(e),i?FD(e._inputNodes,i):e._inputNodes=[];for(const n of e._inputNodes)t.call(e,n)}}let yM=null;function bM(e,t){let n=!1;const i=1/t;if(rL("DISABLE_WEBAUDIO")){const t=window.setInterval((()=>{n?window.clearInterval(t):e(performance.now()/1e3)}),1e3*i)}else{const t=RM();let r=t.createGain();r.gain.value=0,r.connect(t.destination);const o=()=>{if(n)return void(r=null);const s=t.createOscillator();s.onended=o,s.connect(r),s.start(0),s.stop(t.currentTime+i),e(t.currentTime)};o()}return()=>{n=!0}}let CM=class{constructor(){uM(this,"context",void 0),uM(this,"analyserNode",void 0),uM(this,"sourceNode",void 0),this.context=RM(),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4}updateSource(e){if(e!==this.sourceNode){if(this.sourceNode)try{this.sourceNode.disconnect(this.analyserNode)}catch(e){}this.sourceNode=e,null==e||e.connect(this.analyserNode)}}getVolumeLevel(){if(!this.sourceNode)return 0;if(!this.context||TN()||MN()||"running"!==this.context.state&&this.context.resume(),!this.analyserNode)return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else{const t=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(t);for(let n=0;n<e.length;++n)e[n]=t[n]/128-1}const t=ar(e).call(e,((e,t)=>e+t*t),0)/e.length;return Math.max(10*Math.log10(t)+100,0)/100}getAnalyserNode(){return this.analyserNode}rebuildAnalyser(){try{var e,t;null===(e=this.sourceNode)||void 0===e||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,null===(t=this.sourceNode)||void 0===t||t.connect(this.analyserNode)}catch(e){FL.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}},IM=class extends hD{get processSourceNode(){return this.sourceNode}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var n;null===(n=this.sourceNode)||void 0===n||n.disconnect(this.outputNode)}catch(e){}null===(t=this._processedNode)||void 0===t||t.disconnect(),this._processedNode=e,this.connect()}}get processedNode(){return this._processedNode}constructor(){super(),uM(this,"outputNode",void 0),uM(this,"outputTrack",void 0),uM(this,"isPlayed",!1),uM(this,"sourceNode",void 0),uM(this,"context",void 0),uM(this,"audioBufferNode",void 0),uM(this,"destNode",void 0),uM(this,"audioOutputLevel",0),uM(this,"volumeLevelAnalyser",void 0),uM(this,"_processedNode",void 0),uM(this,"playNode",void 0),uM(this,"isDestroyed",!1),uM(this,"onNoAudioInput",void 0),uM(this,"isNoAudioInput",!1),uM(this,"_noAudioInputCount",0),this.context=RM(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),vM(this.outputNode),this.volumeLevelAnalyser=new CM}startGetAudioBuffer(e){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(e),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=e=>{this.emit(zk.ON_AUDIO_BUFFER,function(e){for(let t=0;t<e.outputBuffer.numberOfChannels;t+=1){const n=e.outputBuffer.getChannelData(t);for(let e=0;e<n.length;e+=1)n[e]=0}return e.inputBuffer}(e))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!_k().webAudioMediaStreamDest)throw new zN(JN.NOT_SUPPORTED,"your browser is not support audio processor");return this.destNode&&this.outputTrack||(this.destNode=this.context.createMediaStreamDestination(),this.outputNode.connect(this.destNode),this.outputTrack=this.destNode.stream.getAudioTracks()[0]),this.outputTrack}play(e){"running"!==this.context.state&&jD((()=>{TM.emit("autoplay-failed")})),this.isPlayed=!0,this.playNode=e||this.context.destination,this.outputNode.connect(this.playNode)}stop(){if(this.isPlayed)try{this.outputNode.disconnect(this.playNode)}catch(e){}this.isPlayed=!1}getAccurateVolumeLevel(){return this.volumeLevelAnalyser.getVolumeLevel()}async checkHasAudioInput(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(e>5)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;TN()||MN()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let n;t.getFloatTimeDomainData?(n=new Float32Array(t.fftSize),t.getFloatTimeDomainData(n)):(n=new Uint8Array(t.fftSize),t.getByteTimeDomainData(n));let i=!1;for(let e=0;e<n.length;e++)0!==n[e]&&(i=!0);return i?(this.isNoAudioInput=!1,!0):(await $D(200),await this.checkHasAudioInput(e?e+1:1)&&i)}getAudioVolume(){return this.outputNode.gain.value}setVolume(e){this.outputNode.gain.setValueAtTime(e,this.context.currentTime)}destroy(){this.disconnect(),this.stop(),this.isDestroyed=!0,this.onNoAudioInput=void 0}disconnect(){var e,t;null===(e=this.processedNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.outputNode&&this.outputNode.disconnect()}connect(){var e;this.processedNode?null===(e=this.processedNode)||void 0===e||e.connect(this.outputNode):this.sourceNode&&this.sourceNode.connect(this.outputNode),this.volumeLevelAnalyser.updateSource(this.outputNode)}},AM=class extends IM{get isFreeze(){return!1}constructor(e,t,n){var i;if(super(),uM(this,"sourceNode",void 0),uM(this,"track",void 0),uM(this,"clonedTrack",void 0),uM(this,"audioElement",void 0),uM(this,"isCurrentTrackCloned",!1),uM(this,"isRemoteTrack",!1),uM(this,"originVolumeLevelAnalyser",void 0),uM(this,"rebuildWebAudio",(async()=>{if(FL.debug("ready to rebuild web audio, state:",this.context.state),this.isNoAudioInput&&await this.checkHasAudioInput(),!this.isNoAudioInput||this.isDestroyed)return document.body.removeEventListener("click",this.rebuildWebAudio,!0),void FL.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>FL.info("resume success"))),FL.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();const e=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?e.stop():this.isCurrentTrackCloned=!0;const t=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(t),vM(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const n=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(n,this.context.currentTime),vM(this.outputNode),this.emit(zk.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),"audio"!==e.kind)throw new zN(JN.UNEXPECTED_ERROR);this.track=e;const r=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(r),vM(this.sourceNode),n){const e=n.clone();e.enabled=!0,this.clonedTrack=e,FL.debug("create an unmuted track ".concat(e.id," from the original track ").concat(n.id," to get the volume"));const t=this.context.createMediaStreamSource(new MediaStream([e]));vM(t),this.originVolumeLevelAnalyser=new CM,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=r;const o=dN();t&&o.os===rN.IOS&&Number(null===(i=o.osVersion)||void 0===i?void 0:i.split(".")[0])<15&&(TM.on(Ck.STATE_CHANGE,(()=>{"suspended"===this.context.state?document.body.addEventListener("click",this.rebuildWebAudio,!0):"running"===this.context.state&&this.rebuildWebAudio()})),this.checkHasAudioInput().then((e=>{e||document.body.addEventListener("click",this.rebuildWebAudio,!0)})))}updateTrack(e){this.sourceNode.disconnect(),this.track=e,this.isCurrentTrackCloned=!1;const t=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(t),vM(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(zk.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),TM.off("state-change",this.rebuildWebAudio),null===(e=this.originVolumeLevelAnalyser)||void 0===e||e.destroy(),this.clonedTrack=void 0,super.destroy()}createMediaStreamSourceNode(e){return this.context.createMediaStreamSource(new MediaStream([e]))}updateOriginTrack(e){const t=e.clone();t.enabled=!0,this.clonedTrack&&(this.clonedTrack.stop(),this.clonedTrack=t),FL.debug("create an unmuted track ".concat(t.id," from the original track ").concat(e.id," to get the volume"));const n=this.context.createMediaStreamSource(new MediaStream([t]));vM(n),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(n)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}};async function wM(e,t,n){const i=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,r={audio:!!n&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:i(t.height,1080),maxWidth:i(t.width,1920)}}};return t.frameRate&&"number"!=typeof t.frameRate?(r.video.mandatory.maxFrameRate=t.frameRate.max,r.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(r.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(r)}async function OM(e,t){const n=await NM(e.mediaSource),i=await function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new dp(((n,i)=>{const r=document.createElement("div");r.innerText="share screen",r.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom:  solid 1px #B9B8B9;");const o=document.createElement("div");o.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");const s=document.createElement("div");s.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.",s.setAttribute("style","height: 12%;");const a=document.createElement("div");a.setAttribute("style","width: 100%; height: 80%; background: #FFF; border:  solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");const c=document.createElement("div");c.setAttribute("style","display: flex; justify-content: space-between; padding: 16px 0;");const d=document.createElement("button");d.innerHTML="cancel",d.setAttribute("style","width: 85px;"),d.onclick=()=>{document.body.removeChild(h);const e=new Error("NotAllowedError");e.name="NotAllowedError",i(e)};let l=t;const u=document.createElement("div");if(t){const e=document.createElement("input");e.setAttribute("type","checkbox");const t=document.createElement("span");e.setAttribute("style","margin-right: 6px;"),t.innerText="Share audio",e.checked=l,e.onchange=()=>{l=e.checked},u.appendChild(e),u.appendChild(t)}c.appendChild(u),c.appendChild(d),o.appendChild(s),o.appendChild(a),o.appendChild(c);const h=document.createElement("div");h.setAttribute("style","position: fixed; z-index: 99999999; top: 50%; left: 50%; width: 620px; height: 525px; background: #ECECEC; border-radius: 4px; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"),h.appendChild(r),h.appendChild(o),document.body.appendChild(h),e.map((e=>{if(e.id){const t=document.createElement("div");t.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;");let i=e.thumbnail;try{i.getSize().width>1920&&(i=i.resize({width:1920}))}catch(e){throw e&&e.message.startsWith("Illegal invocation")&&console.error("Operate thumbnail error, please try to set contextIsolation: false. (https://github.com/electron/electron/issues/34953)"),e}t.innerHTML='<div style="height: 120px; display: table-cell; vertical-align: middle;"><img style="width: 100%; background: #333333; box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);" src='+i.toDataURL()+' /></div><span style="\theight: 40px; line-height: 40px; display: inline-block; width: 70%; word-break: keep-all; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">'+e.name.replace(/[\u00A0-\u9999<>\&]/g,(function(e){return"&#"+e.charCodeAt(0)+";"}))+"</span>",t.onclick=()=>{document.body.removeChild(h),n({sourceId:e.id,audio:l})},a.appendChild(t)}}))}))}(n,t),r=i.sourceId,o=i.audio;return await wM(r,e,o)}async function NM(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const n=_D();if(!n)throw console.error("failed to fetch electron, please mount it to window"),new zN(JN.ELECTRON_IS_NULL);let i=null;try{var r;i=(null===(r=n.desktopCapturer)||void 0===r?void 0:r.getSources({types:t}))||n.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:t})}catch(e){i=null}i&&i.then||(i=new dp(((e,i)=>{n.desktopCapturer.getSources({types:t},((t,n)=>{t?i(t):e(n)}))})));try{return await i}catch(e){throw new zN(JN.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}const DM=new _P("safari");let PM=!1,LM=!1;async function kM(e,t){let n=0,i=null;for(;n<2;)try{i=await MM(e,t,n>0);break}catch(e){if(e instanceof zN)throw FL.error("[".concat(t,"] ").concat(e.toString())),e;const i=UM(e.name||e.code||e,e.message);if(i.code===JN.MEDIA_OPTION_INVALID){FL.debug("[".concat(t,"] detect media option invalid, retry")),n+=1,await $D(500);continue}throw FL.error("[".concat(t,"] ").concat(i.toString())),i}if(!i)throw new zN(JN.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return i}async function MM(e,t,n){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new zN(JN.NOT_SUPPORTED,"can not find getUserMedia");n&&(e.video&&(delete e.video.width,delete e.video.height),e.screen&&(delete e.screen.width,delete e.screen.height));const i=_k(),r=new MediaStream;if(e.audioSource&&r.addTrack(e.audioSource),e.videoSource&&r.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return FL.debug("Using Video Source/ Audio Source"),r;if(e.screen)if(_D())e.screen.sourceId?VM(r,await wM(e.screen.sourceId,e.screen,!!e.screenAudio)):VM(r,await OM(e.screen,!!e.screenAudio));else if(_N()&&e.screen.extensionId&&e.screen.mandatory){if(!i.getStreamFromExtension)throw new zN(JN.NOT_SUPPORTED,"This browser does not support screen sharing");FL.debug("[".concat(t,'] Screen access on chrome stable, looking for extension"'));const n=await(s=e.screen.extensionId,a=t,new dp(((e,t)=>{try{chrome.runtime.sendMessage(s,{getStream:!0},(n=>{if(!n||!n.streamId)return FL.error("[".concat(a,"] No response from Chrome Plugin. Plugin not installed properly"),n),void t(new zN(JN.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(n.streamId)}))}catch(e){FL.error("[".concat(a,"] AgoraRTC screensharing plugin is not accessible(").concat(s,")"),e.toString()),t(new zN(JN.CHROME_PLUGIN_NOT_INSTALL))}})));e.screen.mandatory.chromeMediaSourceId=n,VM(r,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}))}else if(i.getDisplayMedia){var o;e.screen.mediaSource&&Fk(e.screen.mediaSource);const n={width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate,displaySurface:null!==(o=e.screen.displaySurface)&&void 0!==o?o:"screen"===e.screen.mediaSource?"monitor":e.screen.mediaSource},i=e.screen,s=i.selfBrowserSurface,a=i.surfaceSwitching,c=i.systemAudio,d=i.preferCurrentTab,l=i.windowAudio,u=i.monitorTypeSurfaces,h={selfBrowserSurface:s,surfaceSwitching:a,systemAudio:c,preferCurrentTab:d,windowAudio:l,monitorTypeSurfaces:u};!s&&delete h.selfBrowserSurface,!a&&delete h.surfaceSwitching,!c&&delete h.systemAudio,!d&&delete h.preferCurrentTab,!l&&delete h.windowAudio,!u&&delete h.monitorTypeSurfaces,FL.debug("[".concat(t,"] getDisplayMedia:"),JSON.stringify({video:n,audio:e.screenAudio,controls:h})),VM(r,await navigator.mediaDevices.getDisplayMedia(pM({video:n,audio:e.screenAudio},h)))}else{if(!SN())throw FL.error("[".concat(t,"] This browser does not support screenSharing")),new zN(JN.NOT_SUPPORTED,"This browser does not support screen sharing");{e.screen.mediaSource&&Fk(e.screen.mediaSource);const n={video:{mediaSource:e.screen.mediaSource,width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate}};FL.debug("[".concat(t,"] getUserMedia: ").concat(JSON.stringify(n))),VM(r,await navigator.mediaDevices.getUserMedia(n))}}var s,a;if(!e.video&&!e.audio)return r;let c={video:e.video,audio:e.audio},d=rL("MEDIA_DEVICE_CONSTRAINTS");if(d)try{"string"==typeof d&&(d=JSON.parse(d)),c=sP(c,d)}catch(e){}FL.debug("[".concat(t,"] GetUserMedia"),JSON.stringify(c)),dN();let l,u=null;(EN()||TN()||pN())&&(u=await DM.lock());try{l=await navigator.mediaDevices.getUserMedia(c)}catch(e){throw u&&u(),e}return c.audio&&(PM=!0),c.video&&(LM=!0),VM(r,l),u&&u(),r}function UM(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new zN(JN.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new zN(JN.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new zN(JN.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new zN(JN.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new zN(JN.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new zN(JN.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return FL.error("getUserMedia unexpected error",e),new zN(JN.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function VM(e,t){const n=e.getVideoTracks()[0],i=e.getAudioTracks()[0],r=t.getVideoTracks()[0],o=t.getAudioTracks()[0];o&&(i&&e.removeTrack(i),e.addTrack(o)),r&&(n&&e.removeTrack(n),e.addTrack(r))}const xM=new class extends hD{get state(){return this._state}set state(e){e!==this._state&&(this.emit(rM.STATE_CHANGE,e),this._state=e)}constructor(){super(),uM(this,"_state",iM.IDLE),uM(this,"isAccessMicrophonePermission",!1),uM(this,"isAccessCameraPermission",!1),uM(this,"lastAccessMicrophonePermission",!1),uM(this,"lastAccessCameraPermission",!1),uM(this,"checkdeviceMatched",!1),uM(this,"deviceInfoMap",new Map),this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(rL("ENUMERATE_DEVICES_INTERVAL")||(BN()||uN()===rN.HARMONY_OS)&&FN())&&this.updateDevicesInfo()}),rL("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>FL.error(e.toString())))}async enumerateDevices(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)throw new zN(JN.NOT_SUPPORTED,"enumerateDevices() not supported.");const i=await navigator.mediaDevices.enumerateDevices(),r=this.checkMediaDeviceInfoIsOk(i);let o=!this.isAccessMicrophonePermission&&e,s=!this.isAccessCameraPermission&&t;r.audio&&(o=!1),r.video&&(s=!1);let a=null,c=null,d=null;if(!n&&(o||s)){if(DM.isLocked&&(FL.debug("[device manager] wait GUM lock"),(await DM.lock())(),FL.debug("[device manager] GUM unlock")),PM&&(o=!1,this.isAccessMicrophonePermission=!0),LM&&(s=!1,this.isAccessCameraPermission=!0),FL.debug("[device manager] check media device permissions",e,t,o,s),o&&s){try{d=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(e){const t=UM(e.name||e.code||e,e.message);if(t.code===JN.PERMISSION_DENIED)throw t;FL.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(o){try{a=await navigator.mediaDevices.getUserMedia({audio:e})}catch(e){const t=UM(e.name||e.code||e,e.message);if(t.code===JN.PERMISSION_DENIED)throw t;FL.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(s){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=UM(e.name||e.code||e,e.message);if(t.code===JN.PERMISSION_DENIED)throw t;FL.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}FL.debug("[device manager] mic permission",e,"cam permission",t)}try{const e=await navigator.mediaDevices.enumerateDevices();return a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null,e}catch(e){return a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null,new zN(JN.ENUMERATE_DEVICES_FAILED,e.toString()).throw()}}async getRecordingDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audioinput"===e.kind))}async getCamerasDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!1,!0,e)).filter((e=>"videoinput"===e.kind))}async getSpeakers(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audiooutput"===e.kind))}searchDeviceIdByName(e){let t=null;return this.deviceInfoMap.forEach((n=>{n.device.label===e&&(t=n.device.deviceId)})),t}async getDeviceById(e){const t=(await this.enumerateDevices(!0,!0,!0)).find((t=>t.deviceId===e));if(!t)throw new zN(JN.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=iM.INITING;try{await this.updateDevicesInfo(),this.state=iM.INITEND}catch(e){if(this.state=iM.IDLE,!("boolean"==typeof isSecureContext?isSecureContext:"https:"===location.protocol||"file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname||"::1"===location.hostname))throw new zN(JN.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.");throw FL.warning("Device Detection functionality cannot start properly.",e.toString()),e}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),n=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const t=e.find((e=>"audioinput"===e.kind&&"default"===e.deviceId)),n=e.find((e=>"audiooutput"===e.kind&&"default"===e.deviceId));t&&n?n.groupId===t.groupId?FL.debug("[device-check] default input ".concat(t.label," and output ").concat(n.label," is the same group")):FL.debug("[device-check] default input ".concat(t.label," and output ").concat(n.label," is not the same group")):FL.debug("[device-check] default input or output not found")}const i=this.checkMediaDeviceInfoIsOk(e);if(e.forEach((e=>{if(!e.deviceId)return;const i=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(i?i.state:"INACTIVE")){const i={initAt:t,updateAt:t,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),i),n.push(i)}i&&(i.updateAt=t)})),this.deviceInfoMap.forEach(((e,i)=>{"ACTIVE"===e.state&&e.updateAt!==t&&(e.state="INACTIVE",n.push(e))})),this.state!==iM.INITEND)return i.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(i.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));n.forEach((e=>{switch(e.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(rM.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(rM.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(rM.PLAYOUT_DEVICE_CHANGED,e)}})),i.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),i.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){const t=e.filter((e=>"audioinput"===e.kind)),n=e.filter((e=>"videoinput"===e.kind)),i={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){i.audio=!0;break}for(const e of n)if(e.label&&e.deviceId){i.video=!0;break}return i}};let FM=!1;const BM=new class extends hD{constructor(){super(...arguments),uM(this,"onAutoplayFailed",void 0),uM(this,"onAudioAutoplayFailed",void 0)}};function jM(){if(FM)return rL("FLS_AUTOPLAY_EMITS")?(BM.onAutoplayFailed&&BM.onAutoplayFailed(),BM.emit("autoplay-failed")):void 0;{const e=t=>{t.preventDefault(),FM=!1,jN()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};FM=!0,jN()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),FL.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),BM.onAutoplayFailed?BM.onAutoplayFailed():BM.onAudioAutoplayFailed?FL.warning("AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed.\n\n  Please refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."):FL.warning("We have detected a media autoplay failed event, and found out that you haven't implemented AgoraRTC.onAutoplayFailed callback yet.\n\n  It will cause audio/video element not playing automatically on some browsers without user interaction, possibly hurting user experiences.\n\n  Please refer to the Agora document to properly handle autoplay failed event, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."),BM.emit("autoplay-failed")}}function GM(e,t,n,i){if(!e)return;const r=uk.getBaseInfoBySessionId(e);if(!r)return;const o=r.info,s=Date.now(),a=pM(pM({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:s,elapse:s-r.startTime,cbRegistered:BM.onAutoplayFailed||BM.onAudioAutoplayFailed?1:-1,errorMsg:n,mediaType:t,trackId:i,extend:void 0});uk.send({type:YL.AUTOPLAY_FAILED,data:a},!0)}const WM=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],KM=new class{constructor(){uM(this,"onAutoplayFailed",void 0),uM(this,"elementMap",new Map),uM(this,"elementStateMap",new Map),uM(this,"elementsNeedToResume",[]),uM(this,"sinkIdMap",new Map),uM(this,"autoResumeAfterInterruption",(e=>dp.all(Array.from(this.elementMap.entries()).map((async t=>{let n=_M(t,2),i=n[0],r=n[1];const o=this.elementStateMap.get(i),s=r.srcObject.getAudioTracks()[0],a=s&&s.readyState;if(FL.debug("resume after interrupted, ele: ".concat(o," audio: ").concat(a," ").concat(e)),"live"===a){if(e)return r.pause(),r.play();if("running"===TM.curState)return PN()?(r.pause(),r.play()):o&&"paused"===o?r.play():void 0}}))))),uM(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let t=_M(e,2);t[0];let n=t[1];const i=n.srcObject.getAudioTracks()[0];i&&"live"===i.readyState&&(FL.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),n.pause(),n.play())}))})),this.autoResumeAudioElement(),TM.on(Ck.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),TM.on(Ck.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),TM.on(Ck.STATE_CHANGE,(()=>{TN()&&"suspended"===TM.prevState&&"running"===TM.curState&&this.autoResumeAfterInterruption()}))}async setSinkID(e,t){const n=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),n)try{await n.setSinkId(t)}catch(e){throw new zN(JN.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(e,t,n,i){if(this.elementMap.has(t))return;const r=document.createElement("audio");r.autoplay=!0,r.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,r),this.elementMap.set(t,r),this.elementStateMap.set(t,oM.INIT),this.setVolume(t,n);const o=this.sinkIdMap.get(t);if(o)try{r.setSinkId(o).catch((e=>{FL.warning("[".concat(t,"] set sink id failed"),e.toString())}))}catch(e){FL.warning("[".concat(t,"] set sink id failed"),e.toString())}const s=r.play();s&&s.then&&s.catch((e=>{i&&GM(i,"audio",e.message,t),FL.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(FL.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(r),jD((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),jM()})))}))}updateTrack(e,t){const n=this.elementMap.get(e);n&&(n.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e)}setVolume(e,t){const n=this.elementMap.get(e);n&&(t=Math.max(0,Math.min(100,t)),n.volume=t/100)}getVolume(e){const t=this.elementMap.get(e);return t?t.volume:0}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const n=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(n,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}bindAudioElementEvents(e,t){WM.forEach((n=>{t.addEventListener(n,(n=>{const i=this.elementStateMap.get(e),r="pause"===n.type?"paused":n.type;if(FL.debug("[".concat(e,"] audio-element-status change ").concat(i," => ").concat(r)),"error"===n.type){const n=null==t?void 0:t.error;n&&FL.error("[".concat(e,"] media error, code: ").concat(n.code,", message: ").concat(n.message))}this.elementStateMap.set(e,r)}))}))}getPlayerState(e){return this.elementStateMap.get(e)||"uninit"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach((e=>{e.play().then((e=>{FL.debug("Auto resume audio element success")})).catch((e=>{FL.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};new dp((e=>{document.body?e():window.addEventListener("load",(()=>e()))})).then((()=>{jN()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};function HM(){return function(e,t,n){const i=n.value;return"function"==typeof i&&(n.value=function(){this._isClosed&&new zN(JN.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",FL);for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const r=i.apply(this,t);return r instanceof dp?new dp(((e,t)=>{r.then(e).catch(t)})):r}),n}}let YM=class extends hD{constructor(e){super(),uM(this,"name","VideoProcessorDestination"),uM(this,"ID","0"),uM(this,"_source",void 0),uM(this,"videoContext",void 0),uM(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new zN(JN.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new zN(JN.NOT_SUPPORTED,"VideoProcessor cannot unpipe to any other Processor")}enable(){}disable(){}updateInput(e){if(e.context!==this.videoContext)throw new Error("ProcessorContext passed to VideoTrack.processorDestination doesn't match it's belonging VideoTrack's context.\nProbably you are making pipeline like this:\nvideoTrack1.pipe(processor).pipe(videoTrack2.processorDestination).");e.track&&e.track!==this.inputTrack&&(this.videoContext.chained=!0,this.inputTrack=e.track,this.emit(tM.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(tM.ON_TRACK,void 0)}},XM=class extends hD{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),uM(this,"constraintsMap",new Map),uM(this,"statsRegistry",[]),uM(this,"usageRegistry",[]),uM(this,"trackId",void 0),uM(this,"direction",void 0),uM(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await OD(this,nM.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){var n;return FL.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),ND(this,nM.REQUEST_UPDATE_CONSTRAINTS,Array.from(gp(n=this.constraintsMap).call(n)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return FL.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),ND(this,nM.REQUEST_UPDATE_CONSTRAINTS,Array.from(gp(t=this.constraintsMap).call(t)))}registerStats(e,t,n){this.statsRegistry.find((n=>n.processorID===e.ID&&n.processorName===e.name&&n.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:n})}unregisterStats(e,t){const n=this.statsRegistry.findIndex((n=>n.processorID===e.ID&&n.processorName===e.name&&n.type===t));-1!==n&&this.statsRegistry.splice(n,1)}gatherStats(){const e=[];for(const t of this.statsRegistry){const n=t.processorID,i=t.processorName,r=t.type,o=t.cb;try{const t=o();e.push({processorID:n,processorName:i,type:r,stats:t})}catch(e){FL.error(new zN(JN.UNEXPECTED_ERROR,e.message))}}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const t of this.usageRegistry){const n=t.cb;try{let t=n();t instanceof dp&&(t=await t),e.push(pM(pM({},t),{},{direction:this.direction}))}catch(e){FL.error("gather extension usage error",e)}}return e}getDirection(){return this.direction}},JM=class extends hD{constructor(e){super(),uM(this,"name","AudioProcessorDestination"),uM(this,"ID","0"),uM(this,"inputTrack",void 0),uM(this,"inputNode",void 0),uM(this,"audioProcessorContext",void 0),uM(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new zN(JN.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new zN(JN.NOT_SUPPORTED,"AudioProcessor cannot unpipe to any other Processor")}enable(){}disable(){}reset(){this.inputTrack=void 0,this.inputNode=void 0,this.audioProcessorContext.chained=!1,this.emit(tM.ON_TRACK,void 0),this.emit(tM.ON_NODE,void 0)}updateInput(e){if(e.context!==this.audioProcessorContext)throw new Error("ProcessorContext passed to AudioTrack.processorDestination doesn't match it's belonging AudioTrack's context.\n        Probably you are making pipeline like this: audioTrack1.pipe(processor).pipe(audioTrack2.processorDestination).");e.track&&this.inputTrack!==e.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=e.track,this.emit(tM.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(tM.ON_NODE,this.inputNode))}},zM=class extends hD{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,n){super(),uM(this,"constraintsMap",new Map),uM(this,"statsRegistry",[]),uM(this,"audioContext",void 0),uM(this,"trackId",void 0),uM(this,"direction",void 0),uM(this,"usageRegistry",[]),uM(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=n}async getConstraints(){return OD(this,nM.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){var n;return FL.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),ND(this,nM.REQUEST_UPDATE_CONSTRAINTS,Array.from(gp(n=this.constraintsMap).call(n)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),ND(this,nM.REQUEST_UPDATE_CONSTRAINTS,Array.from(gp(t=this.constraintsMap).call(t)))}registerStats(e,t,n){this.statsRegistry.find((n=>n.processorID===e.ID&&n.processorName===e.name&&n.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:n})}unregisterStats(e,t){const n=this.statsRegistry.findIndex((n=>n.processorID===e.ID&&n.processorName===e.name&&n.type===t));-1!==n&&this.statsRegistry.splice(n,1)}gatherStats(){const e=[];for(const t of this.statsRegistry){const n=t.processorID,i=t.processorName,r=t.type,o=t.cb;try{const t=o();e.push({processorID:n,processorName:i,type:r,stats:t})}catch(e){FL.error(new zN(JN.UNEXPECTED_ERROR,e.message))}}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const t of this.usageRegistry){const n=t.cb;try{let t=n();t instanceof dp&&(t=await t),e.push(pM(pM({},t),{},{direction:this.direction}))}catch(e){FL.error("gather extension usage error",e)}}return e}getDirection(){return this.direction}},ZM=class extends hD{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),uM(this,"context",void 0),uM(this,"processSourceNode",void 0),uM(this,"outputTrack",void 0),uM(this,"processedNode",void 0),uM(this,"clonedTrack",void 0),uM(this,"outputNode",void 0),this.outputNode=new qM}setVolume(){}createOutputTrack(){throw new zN(JN.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}},qM=class{disconnect(){}connect(){}};function QM(e){return new dp(((t,n)=>{let i=!1;const r=document.createElement("video");r.setAttribute("autoplay",""),r.setAttribute("muted",""),r.muted=!0,r.autoplay=!0,r.setAttribute("playsinline",""),r.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(r);const o=TN()?"canplay":"playing";r.addEventListener(o,(()=>{const e=r.videoWidth,n=r.videoHeight;!e&&SN()||(i=!0,r.srcObject=null,r.remove(),t([e,n]))})),r.srcObject=new MediaStream([e]),r.play().catch(nP),setTimeout((()=>{i||(r.srcObject=null,r.remove(),t([r.videoWidth,r.videoHeight]))}),4e3)}))}function $M(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const n=Lk(e.encoderConfig);return null!=n.width&&(t.width=n.width),null!=n.height&&(t.height=n.height),!VN()&&n.frameRate&&(t.frameRate=n.frameRate),gN()&&"object"==typeof t.frameRate&&(t.frameRate.max=60),SN()&&(t.frameRate={ideal:30,max:30}),t}function eU(e){const t={};return VN()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,_N()&&e.ANS&&(t.googHighpassFilter=e.ANS))),t}function tU(e){const t=eU(e);if(e.encoderConfig){const n=Vk(e.encoderConfig);t.channelCount=n.stereo?2:1,t.sampleRate=n.sampleRate,t.sampleSize=n.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),BN()&&(t.sampleRate=void 0),t}const nU=e=>{const t=e._encoderConfig;if(!t)return;const n=e.getMediaStreamTrackSettings(),i=n.frameRate,r=n.width,o=n.height;let s=t.frameRate,a=void 0===s?i:s,c=t.width,d=void 0===c?r:c,l=t.height,u=void 0===l?o:l;if(!a||!d||!u)return;d=cP(d),u=cP(u),a=cP(a);const h=function(e,t,n){const i=200*Math.pow(n/15,.6)*Math.pow(e*t/640/360,.75);return{min:Math.floor(i),max:Math.floor(4*i)}}(d,u,a),p=h.max,_=h.min,E=t||{},m=E.bitrateMax,f=E.bitrateMin;m||FL.debug("calculate bitrate: [w: ".concat(d,", h: ").concat(u,", fps: ").concat(a,"] => [brMax: ").concat(m,", brMin: ").concat(f,"]"));const g=rL("ENCODER_CONFIG_LIMIT").maxFramerate;return g&&"number"==typeof g&&(a=Math.min(a,g)),{frameRate:a,bitrateMax:m||p,bitrateMin:f||_,scaleResolutionDownBy:1,scale:0}},iU=async(e,t,n)=>await(async(e,t,n)=>{const i=function(e){const t=[];for(let n=0;n<e.length;n+=2)t.push(parseInt(e.slice(n,n+2),16));return Uint8Array.from(t)}(uP(""+t+n)).slice(0,16),r=i.slice(0,12),o=await window.crypto.subtle.importKey("raw",i,"AES-GCM",!0,["encrypt"]);return new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-GCM",iv:r},o,e))})(e.buffer,t,n),rU=e=>{const t=document.createElement("canvas");return t.width=2,t.height=2,new dp(((n,i)=>{t.toBlob((async e=>{if(t.remove(),e){const i=await oU(e);n({buffer:i,width:t.width,height:t.height})}else i(new zN(JN.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},oU=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};var sU,aU,cU,dU,lU,uU,hU,pU,_U,EU,mU,fU,gU,SU,TU,RU,vU,yU,bU,CU,IU,AU,wU,OU,NU,DU,PU,LU,kU,MU,UU,VU,xU,FU,BU,jU,GU,WU,KU,HU;let YU=(sU=lk({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),aU=lk({argsMap:(e,t)=>[e.getTrackId(),t]}),cU=HM(),dU=EP("LocalAudioTrack","_enabledMutex"),lU=lk({argsMap:(e,t)=>[e.getTrackId(),t]}),uU=HM(),hU=EP("LocalAudioTrack","_enabledMutex"),pU=lk({argsMap:(e,t)=>[e.getTrackId(),t]}),_U=HM(),EU=HM(),mU=HM(),fU=lk({argsMap:e=>[e.getTrackId()]}),gU=HM(),SU=lk({argsMap:e=>[e.getTrackId()]}),TU=HM(),RU=lk({argsMap:e=>[e.getTrackId()]}),vU=lk({argsMap:(e,t)=>[e.getTrackId(),t.name]}),yU=lk({argsMap:e=>[e.getTrackId()]}),dM((bU=class extends mM{get _source(){return this.initWebAudio()}set _source(e){this._trackSource=e}get processorContext(){return this._processorContext||(this._processorContext=this.initProcessor().processorContext),this._processorContext}get processorDestination(){return this._processorDestination||(this._processorDestination=this.initProcessor().processorDestination),this._processorDestination}get isPlaying(){return this._useAudioElement?KM.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,n,i){super(e,n),uM(this,"trackMediaType",Jk.AUDIO),uM(this,"_encoderConfig",void 0),uM(this,"_trackSource",void 0),uM(this,"metadata",[]),uM(this,"_enabled",!0),uM(this,"_volume",100),uM(this,"_useAudioElement",!0),uM(this,"_bypassWebAudio",!1),uM(this,"processor",void 0),uM(this,"_processorContext",void 0),uM(this,"_processorDestination",void 0),uM(this,"_getOriginVolumeLevel",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!i,this._trackSource=new ZM,rL("DISABLE_WEBAUDIO")&&(this._bypassWebAudio=!0),rL("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1),EN()&&!SM?setTimeout((()=>this.initWebAudio())):this.initWebAudio()}setVolume(e){QN(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&KM.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void FL.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,ND(this,Bk.NEED_REPLACE_TRACK,this).then((()=>{FL.debug("[".concat(this.getTrackId(),"] replace web audio track success"))})).catch((e=>{FL.warning("[".concat(this.getTrackId(),"] replace web audio track failed"),e)})))}catch(e){}}getVolumeLevel(){return this._muted&&this.enabled&&this._getOriginVolumeLevel?this._source.getOriginVolumeLevel():this._source.getAccurateVolumeLevel()}async setPlaybackDevice(e){if(!this._useAudioElement||!Ek())throw new zN(JN.NOT_SUPPORTED,"your browser does not support setting the audio output device");await KM.setSinkID(this.getTrackId(),e)}async setEnabled(e,t,n){return this._setEnabled(e,t,n)}async _setEnabled(e,t,n){if(!n){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(FL.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{n||(this._enabled=!0),await ND(this,Bk.NEED_ENABLE_TRACK,this),FL.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw n||(this._enabled=!1),FL.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,n||(this._enabled=!1);try{await ND(this,Bk.NEED_DISABLE_TRACK,this)}catch(e){throw n||(this._enabled=!0),FL.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}}}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,FL.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await ND(this,Bk.NEED_MUTE_TRACK,this):await ND(this,Bk.NEED_UNMUTE_TRACK,this))}getStats(){HD((()=>{FL.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")}),"localAudioTrackGetStatsWarning");return DD(this,Bk.GET_STATS)||pM({},Zk)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(zk.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(zk.ON_AUDIO_BUFFER),this._source.on(zk.ON_AUDIO_BUFFER,(t=>e(t)))}play(){FL.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(FL.debug("[".concat(this.getTrackId(),"] start audio playback in element")),KM.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){FL.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?KM.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this._processorDestination&&this.unbindProcessorDestinationEvents(this._processorDestination),this._processorContext&&this.unbindProcessorContextEvents(this._processorContext),this.unpipe(),this._processorDestination&&this._processorDestination._source&&this._processorDestination._source.unpipe(),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];FL.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&KM.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(e,t){this._originMediaStreamTrack!==e&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this._processorContext&&this.processor.updateInput({track:e,context:this._processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await ND(this,Bk.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return dp.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new zN(JN.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new zN(JN.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(e){e.on(tM.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await ND(this,Bk.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await ND(this,Bk.NEED_REPLACE_TRACK,this))})),e.on(tM.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(e){e.removeAllListeners(tM.ON_TRACK),e.removeAllListeners(tM.ON_NODE)}bindProcessorContextEvents(e){e.on(nM.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}unbindProcessorContextEvents(e){e.removeAllListeners(nM.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof ZM&&(this._trackSource=new AM(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){const e=new zM(this._source.context,this.getTrackId(),"local"),t=new JM(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on(zk.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e})})),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(KM.stop(this.getTrackId()),this._source.play()),ND(this,Bk.NEED_REPLACE_MIXING_TRACK,this).then((()=>{FL.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"))})).catch((e=>{FL.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),e)}))),{processorContext:e,processorDestination:t}}}).prototype,"setVolume",[sU],Object.getOwnPropertyDescriptor(bU.prototype,"setVolume"),bU.prototype),dM(bU.prototype,"setPlaybackDevice",[aU,cU],Object.getOwnPropertyDescriptor(bU.prototype,"setPlaybackDevice"),bU.prototype),dM(bU.prototype,"setEnabled",[dU,lU,uU],Object.getOwnPropertyDescriptor(bU.prototype,"setEnabled"),bU.prototype),dM(bU.prototype,"setMuted",[hU,pU,_U],Object.getOwnPropertyDescriptor(bU.prototype,"setMuted"),bU.prototype),dM(bU.prototype,"getStats",[EU],Object.getOwnPropertyDescriptor(bU.prototype,"getStats"),bU.prototype),dM(bU.prototype,"setAudioFrameCallback",[mU],Object.getOwnPropertyDescriptor(bU.prototype,"setAudioFrameCallback"),bU.prototype),dM(bU.prototype,"play",[fU,gU],Object.getOwnPropertyDescriptor(bU.prototype,"play"),bU.prototype),dM(bU.prototype,"stop",[SU,TU],Object.getOwnPropertyDescriptor(bU.prototype,"stop"),bU.prototype),dM(bU.prototype,"close",[RU],Object.getOwnPropertyDescriptor(bU.prototype,"close"),bU.prototype),dM(bU.prototype,"pipe",[vU],Object.getOwnPropertyDescriptor(bU.prototype,"pipe"),bU.prototype),dM(bU.prototype,"unpipe",[yU],Object.getOwnPropertyDescriptor(bU.prototype,"unpipe"),bU.prototype),bU),XU=(CU=lk({argsMap:(e,t)=>[e.getTrackId(),t]}),IU=HM(),AU=EP("MicrophoneAudioTrack","_enabledMutex"),wU=lk({argsMap:(e,t,n)=>[e.getTrackId(),t,n]}),OU=HM(),NU=lk({argsMap:e=>[e.getTrackId()]}),dM((DU=class extends YU{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,n,i){super(e,t.encoderConfig?Vk(t.encoderConfig):{},i,rL("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),uM(this,"_config",void 0),uM(this,"_deviceName","default"),uM(this,"_constraints",void 0),uM(this,"_originalConstraints",void 0),uM(this,"_enabled",!0),this._config=t,this._constraints=n,this._originalConstraints=n,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(PN()||LN())&&TM.bindInterruptDetectorTrack(this)}async setDevice(e){if(FL.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await xM.getDeviceById(e),n={};n.audio=pM({},this._constraints),n.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let i=null;try{i=await kM(n,this.getTrackId())}catch(e){throw FL.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),i=await kM({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(i.getAudioTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(i.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw FL.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await xM.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw FL.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}FL.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,n){if(t)return FL.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(e);if(!n){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(FL.info("[".concat(this.getTrackId(),"] start setEnabled"),e),rL("AUTO_RESET_AUDIO_ROUTE")&&(TN()||MN())){const t=navigator.audioSession;t&&(e||(t.type="playback"),t.type="auto")}if(!e){var i;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(i=this._source.clonedTrack)||void 0===i||i.stop(),n||(this._enabled=!1);try{await ND(this,Bk.NEED_DISABLE_TRACK,this)}catch(e){throw FL.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const r=pM({},this._constraints),o=xM.searchDeviceIdByName(this._deviceName);o&&!r.deviceId&&(r.deviceId=o);try{n||(this._enabled=!0);const e=await kM({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await ND(this,Bk.NEED_ENABLE_TRACK,this)}catch(e){throw n||(this._enabled=!1),FL.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}FL.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(PN()||LN())&&TM.unbindInterruptDetectorTrack(this),xk.some((e=>function(e){return"__className__"in e&&"MicrophoneAudioTrack"===e.__className__}(e)))||gM&&gM()&&(uk.reportApiInvoke(null,{name:"BG_AUDIO_TAG_RESTART",options:{},tag:mD.TRACER}).onSuccess(),FL.debug("restart background audio tag success"))}onTrackEnded(){if((TN()||MN())&&this._enabled&&!this._isClosed&&TM.duringInterruption){const e=async()=>{TM.off(Ck.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(FL.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};TM.on(Ck.IOS_INTERRUPTION_END,e)}else FL.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Yk.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,n=xM.searchDeviceIdByName(this._deviceName);if(n&&!t.deviceId&&(t.deviceId=n),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await kM({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(nM.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,n)=>{try{const n=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(n),t()}catch(e){n(e)}}))}unbindProcessorContextEvents(e){super.unbindProcessorContextEvents(e),e.removeAllListeners(nM.REQUEST_UPDATE_CONSTRAINTS)}}).prototype,"setDevice",[CU,IU],Object.getOwnPropertyDescriptor(DU.prototype,"setDevice"),DU.prototype),dM(DU.prototype,"setEnabled",[AU,wU,OU],Object.getOwnPropertyDescriptor(DU.prototype,"setEnabled"),DU.prototype),dM(DU.prototype,"close",[NU],Object.getOwnPropertyDescriptor(DU.prototype,"close"),DU.prototype),DU),JU=(PU=lk({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),LU=HM(),kU=lk({argsMap:e=>[e.getTrackId()]}),MU=HM(),UU=lk({argsMap:e=>[e.getTrackId()]}),VU=HM(),xU=lk({argsMap:e=>[e.getTrackId()]}),FU=HM(),BU=lk({argsMap:e=>[e.getTrackId()]}),jU=HM(),GU=lk({argsMap:e=>[e.getTrackId()]}),WU=lk({argsMap:e=>[e.getTrackId()]}),KU=HM(),dM((HU=class extends YU{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,n,i){super(t.createOutputTrack(),n,i),uM(this,"source",void 0),uM(this,"_bufferSource",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on(zk.AUDIO_SOURCE_STATE_CHANGE,(e=>{this.safeEmit(Yk.SOURCE_STATE_CHANGE,e)}));try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}}get currentState(){return this._bufferSource.currentState}get duration(){return this._bufferSource.duration}get playbackSpeed(){return this._bufferSource.playbackSpeed}getCurrentTime(){return this._bufferSource.currentTime}startProcessAudioBuffer(e){e&&this._bufferSource.updateOptions(e),this._bufferSource.startProcessAudioBuffer()}pauseProcessAudioBuffer(){this._bufferSource.pauseProcessAudioBuffer()}seekAudioBuffer(e){this._bufferSource.seekAudioBuffer(e)}resumeProcessAudioBuffer(){this._bufferSource.resumeProcessAudioBuffer()}stopProcessAudioBuffer(){this._bufferSource.stopProcessAudioBuffer()}close(){this.source=null,this._bufferSource.destroy(),super.close()}setAudioBufferPlaybackSpeed(e){QN(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}).prototype,"startProcessAudioBuffer",[PU,LU],Object.getOwnPropertyDescriptor(HU.prototype,"startProcessAudioBuffer"),HU.prototype),dM(HU.prototype,"pauseProcessAudioBuffer",[kU,MU],Object.getOwnPropertyDescriptor(HU.prototype,"pauseProcessAudioBuffer"),HU.prototype),dM(HU.prototype,"seekAudioBuffer",[UU,VU],Object.getOwnPropertyDescriptor(HU.prototype,"seekAudioBuffer"),HU.prototype),dM(HU.prototype,"resumeProcessAudioBuffer",[xU,FU],Object.getOwnPropertyDescriptor(HU.prototype,"resumeProcessAudioBuffer"),HU.prototype),dM(HU.prototype,"stopProcessAudioBuffer",[BU,jU],Object.getOwnPropertyDescriptor(HU.prototype,"stopProcessAudioBuffer"),HU.prototype),dM(HU.prototype,"close",[GU],Object.getOwnPropertyDescriptor(HU.prototype,"close"),HU.prototype),dM(HU.prototype,"setAudioBufferPlaybackSpeed",[WU,KU],Object.getOwnPropertyDescriptor(HU.prototype,"setAudioBufferPlaybackSpeed"),HU.prototype),HU),zU=class e extends YU{get __className__(){return"MixingAudioTrack"}get isActive(){for(const e of this.trackList)if(e._enabled&&!e._isClosed&&!e.muted)return!0;return!1}constructor(){const e=RM().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,eP(8,"track-mix-")),uM(this,"trackList",void 0),uM(this,"destNode",void 0),this._useAudioElement=!1;try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}this.destNode=e,this.trackList=[]}hasAudioTrack(e){return-1!==this.trackList.indexOf(e)}addAudioTrack(e){-1===this.trackList.indexOf(e)?(FL.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):FL.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){FL.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}FD(this.trackList,e),this.updateEncoderConfig()}}updateEncoderConfig(){const e={};this.trackList.forEach((t=>{t._encoderConfig&&((t._encoderConfig.bitrate||0)>(e.bitrate||0)&&(e.bitrate=t._encoderConfig.bitrate),(t._encoderConfig.sampleRate||0)>(e.sampleRate||0)&&(e.sampleRate=t._encoderConfig.sampleRate),(t._encoderConfig.sampleSize||0)>(e.sampleSize||0)&&(e.sampleSize=t._encoderConfig.sampleSize),t._encoderConfig.stereo&&(e.stereo=!0))})),this._encoderConfig=e}_updateRtpTransceiver(t){this._rtpTransceiver!==t&&(this._rtpTransceiver=t,this.trackList.forEach((n=>{n instanceof e?n.emit(Hk.TRANSCEIVER_UPDATED,t):n._updateRtpTransceiver(t)})))}},ZU=class extends IM{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(zk.AUDIO_SOURCE_STATE_CHANGE,this._currentState))}get currentState(){return this._currentState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),uM(this,"audioBuffer",void 0),uM(this,"sourceNode",void 0),uM(this,"startPlayTime",0),uM(this,"startPlayOffset",0),uM(this,"pausePlayTime",0),uM(this,"options",void 0),uM(this,"currentLoopCount",0),uM(this,"currentPlaybackSpeed",100),uM(this,"_currentState","stopped"),this.audioBuffer=e,this.options=t,this.startPlayOffset=this.options.startPlayTime||0}createWebAudioDiagram(){return this.context.createGain()}get duration(){return this.audioBuffer?this.audioBuffer.duration:0}get playbackSpeed(){return this.currentPlaybackSpeed}get currentTime(){return this.audioBuffer?"stopped"===this.currentState?0:"paused"===this.currentState?this.pausePlayTime:((this.context.currentTime-this.startPlayTime)*(this.playbackSpeed/100)+this.startPlayOffset)%this.audioBuffer.duration:0}updateOptions(e){"stopped"===this.currentState?(this.options=e,this.startPlayOffset=this.options.startPlayTime||0):FL.warning("can not set audio source options")}startProcessAudioBuffer(){this.sourceNode&&this.stopProcessAudioBuffer(),this.sourceNode=this.createSourceNode(),this.startSourceNode(),this.currentState="playing"}pauseProcessAudioBuffer(){this.sourceNode&&"playing"===this.currentState&&(this.pausePlayTime=this.currentTime,this.sourceNode.onended=null,this.sourceNode.stop(),this.sourceNode.buffer=null,this.sourceNode=this.createSourceNode(),this.currentState="paused")}seekAudioBuffer(e){this.sourceNode&&(this.sourceNode.onended=null,"playing"===this.currentState&&this.sourceNode.stop(),this.sourceNode=this.createSourceNode(),"playing"===this.currentState?(this.startPlayOffset=e,this.startSourceNode()):"paused"===this.currentState&&(this.pausePlayTime=e))}resumeProcessAudioBuffer(){"paused"===this.currentState&&this.sourceNode&&(this.startPlayOffset=this.pausePlayTime,this.pausePlayTime=0,this.startSourceNode(),this.currentState="playing")}stopProcessAudioBuffer(){if(this.sourceNode){this.sourceNode.onended=null;try{this.sourceNode.stop()}catch(e){}this.reset()}}destroy(){this.audioBuffer=null,super.destroy()}setAudioBufferPlaybackSpeed(e){this.sourceNode&&("playing"===this.currentState&&(this.startPlayOffset=this.currentTime,this.startPlayTime=this.context.currentTime),this.sourceNode.playbackRate.value=e/100),this.currentPlaybackSpeed=e}startSourceNode(){this.sourceNode&&this.sourceNode.buffer&&(this.sourceNode.start(0,this.startPlayOffset),this.startPlayTime=this.context.currentTime,this.sourceNode.onended=this.handleSourceNodeEnded.bind(this))}createSourceNode(){const e=this.context.createBufferSource();return e.buffer=this.audioBuffer,e.loop=!!this.options.loop,e.connect(this.outputNode),e.playbackRate.value=this.currentPlaybackSpeed/100,e}handleSourceNodeEnded(){if(this.currentLoopCount+=1,this.options.cycle&&this.options.cycle>this.currentLoopCount)return this.startPlayOffset=0,this.sourceNode=void 0,void this.startProcessAudioBuffer();this.reset()}reset(){this.startPlayOffset=this.options.startPlayTime||0,this.currentState="stopped",this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=void 0),this.currentLoopCount=0}};const qU=new Map;function QU(e,t){if(0===e.length||0===t.length)return 1/0;const n=lP(e),i=lP(t);return Math.floor(i/n)}let $U=class{get rendFrameRate(){const e=Math.max(1,QU(this._render_interframe_delays_sizes,this._render_interframe_delays));return Math.floor(1e3/e)}get videoElementStatus(){return this._isInPage?this._videoElementStatus:oM.DESTROYED}set videoElementStatus(e){e!==this._videoElementStatus&&(FL.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e)}get videoState(){return this._videoState}set videoState(e){var t;e!==this._videoState&&(this._videoState=e,null===(t=this.onVideoStateChanged)||void 0===t||t.call(this,this.videoState))}constructor(e){uM(this,"trackId",void 0),uM(this,"config",void 0),uM(this,"onFirstVideoFrameDecoded",void 0),uM(this,"onFirstVideoFrameRender",void 0),uM(this,"onVideoBufferReady",void 0),uM(this,"onVideoStateChanged",void 0),uM(this,"freezeTimeCounterList",[]),uM(this,"renderFreezeAccTime",0),uM(this,"renderFreezeAccTime2",0),uM(this,"totalFreezeTime",0),uM(this,"isKeepLastFrame",!1),uM(this,"isDestroyed",!1),uM(this,"timeUpdatedCount",0),uM(this,"freezeTime",0),uM(this,"playbackTime",0),uM(this,"lastTimeUpdatedTime",0),uM(this,"autoplayFailed",!1),uM(this,"videoTrack",void 0),uM(this,"videoElement",void 0),uM(this,"cacheVideoElement",void 0),uM(this,"cancelRVFId",void 0),uM(this,"internal",!1),uM(this,"_render_interframe_delays",[]),uM(this,"_render_interframe_delays_sizes",[]),uM(this,"_videoState",sM.VideoStateStopped),uM(this,"videoElementCheckInterval",void 0),uM(this,"videoElementFreezeTimeout",void 0),uM(this,"_videoElementStatus",oM.NONE),uM(this,"_isInPage",!0),uM(this,"isGettingVideoDimensions",!1),uM(this,"startGetVideoDimensions",(()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return FL.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()})),uM(this,"autoResumeAfterInterruption",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===TM.curState&&(FL.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(hN())),kN()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),uM(this,"handleVideoEvents",(e=>{switch(e.type){case"play":case"playing":"play"===e.type&&FL.debug("[".concat(this.trackId,"] video element status: play")),this.startGetVideoDimensions(),this.videoElementStatus=oM.PLAYING;break;case"loadeddata":if(this.videoState=sM.VideoStateStarting,this.onFirstVideoFrameRender&&this.onFirstVideoFrameRender(),this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove()}catch(e){}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=oM.CANPLAY;break;case"stalled":this.videoElementStatus=oM.STALLED;break;case"suspend":this.videoElementStatus=oM.SUSPEND;break;case"pause":this.videoElementStatus=oM.PAUSED,TN()||MN()||EN()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(FL.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=oM.WAITING;break;case"abort":this.videoElementStatus=oM.ABORT;break;case"ended":this.videoElementStatus=oM.ENDED;break;case"emptied":this.videoElementStatus=oM.EMPTIED;break;case"error":{const e=this.videoElement.error;e&&(this.videoElementStatus=oM.ERROR,FL.error("[".concat(this.trackId,"] media error: ").concat(e.message," (").concat(e.code,")")));break}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.onVideoBufferReady&&this.timeUpdatedCount>rL("BUFFER_READY_FRAMES")&&this.onVideoBufferReady(),this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,n=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,sx.lastVisibleTime<sx.lastHiddenTime||n<sx.lastHiddenTime||n<sx.lastVisibleTime)return;if(this.isSkipCalcRenderFreezeTime())return;for(t>rL("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=t),this.playbackTime+=t;this.playbackTime>=6e3;){this.playbackTime-=6e3;const e=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(e),this.freezeTime=Math.max(0,this.freezeTime-6e3)}break}}})),uM(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(FL.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(hN())),kN()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),this.trackId=e.trackId,this.config=e,e.element instanceof HTMLVideoElement?this.videoElement=e.element:this.videoElement=document.createElement("video"),TM.on(Ck.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),TM.on(Ck.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16)}getVideoElement(){return this.videoElement}getContainerElement(){var e;return null!==(e=this.videoElement.parentElement)&&void 0!==e?e:void 0}updateConfig(e){this.config=e,this.trackId=e.trackId,e.element!==this.videoElement&&(this.destroy(),this.videoElement=e.element),this.videoTrack&&this.initVideoElement()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.initVideoElement())}play(e){const t=this.videoElement.play();t&&t.catch&&t.catch((t=>{e&&GM(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(FL.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):FL.warning("[".concat(this.trackId,"] play warning: "),t)}));const n=dN();if(("Safari"===n.name&&15===Number(n.version)||PN())&&t&&t.then){const e=()=>{this.config.mirror&&!this.config.noStyle&&(this.videoElement.style.transform="rotateY(180deg)")};t.then(e).catch(e)}}getCurrentFrame(){const e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const t=e.getContext("2d");if(!t)return FL.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const n=t.getImageData(0,0,e.width,e.height);return e.remove(),n}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const n=document.createElement("canvas");n.width=this.videoElement.videoWidth,n.height=this.videoElement.videoHeight;const i=n.getContext("2d");return i?(i.drawImage(this.videoElement,0,0,n.width,n.height),new dp(((i,r)=>{n.toBlob((async e=>{if(n.remove(),e){const t=await oU(e);i({buffer:t,width:n.width,height:n.height})}else r(new zN(JN.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await rU(e)}destroy(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.isDestroyed=!0,TM.off(Ck.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),TM.off(Ck.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),e?this.videoElement.pause():this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=sM.VideoStateStopped}initVideoElement(){if(this._videoElementStatus!==oM.NONE&&this._videoElementStatus!==oM.DESTROYED||(this.videoElementStatus=oM.INIT),!this.videoElementCheckInterval&&(eV.forEach((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{this._isInPage=function(e){return e!==document.body&&document.body.contains(e)}(this.videoElement)}),1e3),rL("ENABLE_VIDEO_FRAME_CALLBACK"))){var e,t;let n;const i=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",i),this.videoElementFreezeTimeout=window.setTimeout(r,rL("VIDEO_FREEZE_DURATION")))},r=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===sM.VideoStateDecoding&&("visible"===document.visibilityState?this.videoState=sM.VideoStateFrozen:document.addEventListener("visibilitychange",i))},o=(e,t)=>{if(this.videoElementStatus===oM.PLAYING){if(n){const e=t.presentationTime-n.presentationTime,i=t.presentedFrames-n.presentedFrames;this._render_interframe_delays_sizes.push(i),this._render_interframe_delays.push(e);const o=lP(this._render_interframe_delays_sizes),s=o-this._render_interframe_delays_sizes[0];if(o>30&&s>5&&(this._render_interframe_delays_sizes.shift(),this._render_interframe_delays.shift()),this.videoState===sM.VideoStateStarting&&(this.videoState=sM.VideoStateDecoding),this.videoState===sM.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(r,rL("VIDEO_FREEZE_DURATION"))),e<rL("VIDEO_FREEZE_DURATION")&&this.videoState===sM.VideoStateFrozen&&(this.videoState=sM.VideoStateDecoding),e>rL("VIDEO_FREEZE_DURATION")&&sx.lastVisibleTime>=sx.lastHiddenTime&&n.timestamp>sx.lastVisibleTime&&n.timestamp>sx.lastHiddenTime){const t=Math.min(66,QU(this._render_interframe_delays_sizes,this._render_interframe_delays)),n=Math.max(0,e-(i-1)*t),r=n>t?n:0;this.renderFreezeAccTime2+=r,this.totalFreezeTime+=r,this.renderFreezeAccTime+=e}}n=pM(pM({},t),{},{timestamp:e})}else this.isSkipCalcRenderFreezeTime()&&(n=pM(pM({},t),{},{timestamp:e}));var i,s;rL("ENABLE_VIDEO_FRAME_CALLBACK")&&(this.cancelRVFId=null===(i=(s=this.videoElement).requestVideoFrameCallback)||void 0===i?void 0:i.call(s,o))};this.cancelRVFId=null===(e=(t=this.videoElement).requestVideoFrameCallback)||void 0===e?void 0:e.call(t,o)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),BN()&&!rL("HIDE_NO_POSTER")&&(this.videoElement.poster="noposter");const n=dN();this.config.noStyle||("Safari"===n.name&&15===Number(n.version)||PN()||!this.config.mirror||(this.videoElement.style.transform="rotateY(180deg)"),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover"),this.videoElement.setAttribute("muted",""),this.videoElement.muted=!0,this.videoElement.srcObject&&this.videoElement.srcObject instanceof MediaStream?this.videoElement.srcObject.getVideoTracks()[0]!==this.videoTrack&&(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,SN()&&this.videoElement.load()):(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,SN()&&this.videoElement.load());const i=this.videoElement.play();void 0!==i&&i.catch((e=>{FL.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){var e,t;eV.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.cancelRVFId&&this.videoElement&&(null===(e=(t=this.videoElement).cancelVideoFrameCallback)||void 0===e||e.call(t,this.cancelRVFId),this.cancelRVFId=void 0),this.videoElementStatus=oM.NONE}isSkipCalcRenderFreezeTime(){return this.videoElementStatus===oM.DESTROYED||this.internal}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{FL.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{FL.error(e)})),this.autoplayFailed=!1,jN()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};jN()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),jM()}};const eV=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];let tV=class extends $U{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];super(e),uM(this,"container",void 0),uM(this,"slot",void 0),this.slot=e.element,this.internal=t,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;var n;!this.internal||this.slot?(t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()):(this.slot=t,t&&this.container?(this.internal=!1,this.container.id="agora-video-player-".concat(this.trackId),this.videoElement.id="video_".concat(this.trackId),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",null===(n=this.slot)||void 0===n||n.appendChild(this.container)):this.createElements())}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements())}play(e){var t;null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(e){var t;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,n):await rU(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{var e;this.container.remove(),null===(e=this.slot)||void 0===e||e.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){var e;this.container||(this.container=document.createElement("div")),this.container.id="agora-video-player-".concat(this.trackId),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.overflow="hidden",this.videoTrack?(this.container.style.backgroundColor="black",rL("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),null===(e=this.slot)||void 0===e||e.appendChild(this.container)}mountedVideoElement(){var e;!this.container||null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)||this.container.appendChild(this.videoElement),super.initVideoElement(),this.videoElement.id="video_".concat(this.trackId),this.videoElement.className="agora_video_player",this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.left="0",this.videoElement.style.top="0"}unmountedVideoElement(){var e;if(null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement)}catch(e){}this.videoElement=document.createElement("video")}}resetVideoElement(){var e;null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"))}getContainerElement(){return this.container}};var nV,iV,rV,oV,sV,aV,cV,dV,lV,uV,hV,pV,_V,EV,mV,fV,gV,SV,TV,RV,vV,yV,bV,CV,IV,AV,wV,OV,NV,DV,PV,LV,kV,MV,UV,VV,xV,FV;let BV=(nV=lk({argsMap:(e,t,n)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",n]}),iV=HM(),rV=lk({argsMap:e=>[e.getTrackId()]}),oV=EP("LocalVideoTrack","_enabledMutex"),sV=lk({argsMap:(e,t)=>[e.getTrackId(),t]}),aV=HM(),cV=EP("LocalVideoTrack","_enabledMutex"),dV=lk({argsMap:(e,t)=>[e.getTrackId(),t]}),lV=HM(),uV=lk({argsMap:(e,t)=>[e.getTrackId(),t,e._saveEncodeBitrateRatio]}),hV=HM(),pV=lk({argsMap:(e,t)=>[e.getTrackId(),t]}),_V=HM(),EV=HM(),mV=lk({argsMap:(e,t,n)=>[e.getTrackId(),t,n]}),fV=HM(),gV=HM(),SV=HM(),TV=lk({argsMap:e=>[e.getTrackId()]}),RV=HM(),vV=HM(),yV=HM(),bV=HM(),CV=HM(),IV=lk({argsMap:(e,t)=>[e.getTrackId(),t.name]}),AV=lk({argsMap:e=>[e.getTrackId()]}),wV=lk({argsMap:e=>[e.getTrackId()]}),OV=lk({argsMap:(e,t,n)=>[e.getTrackId(),t.label,n]}),NV=class e extends mM{get videoHeight(){if(EN()){const e=this._mediaStreamTrack.getSettings().height;return this._videoHeight=e,this._videoHeight}return this._videoHeight}get videoWidth(){if(EN()){const e=this._mediaStreamTrack.getSettings().width;return this._videoWidth=e,this._videoWidth}return this._videoWidth}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==oM.PLAYING)}get processorDestination(){return this._processorDestination}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return"LocalVideoTrack"}constructor(e,t,n,i,r,o){if(super(e,r),uM(this,"trackMediaType",Jk.VIDEO),uM(this,"_player",void 0),uM(this,"isUseScaleResolutionDownBy",!1),uM(this,"_videoVisibleTimer",null),uM(this,"_previousVideoVisibleStatus",void 0),uM(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),uM(this,"_encoderConfig",void 0),uM(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),uM(this,"_optimizationMode",void 0),uM(this,"_saveEncodeBitrateRatio",1),uM(this,"_videoHeight",void 0),uM(this,"_videoWidth",void 0),uM(this,"_forceBitrateLimit",void 0),uM(this,"_enabled",!0),uM(this,"_processorDestination",void 0),uM(this,"_processorContext",void 0),EN()){const t=e.getSettings(),n=t.width,i=t.height;this._videoWidth=n,this._videoHeight=i}else this.updateMediaStreamTrackResolution();if(this._scalabilityMode=n,this._optimizationMode=i,this._hints=o||[],t&&-1!==this._hints.indexOf(jk.CUSTOM_TRACK)?this._encoderConfig=GD(t):this._encoderConfig=t,-1===this._hints.indexOf(jk.SCREEN_TRACK))this.updateBitrateFromProfile();else if(yN(oN.CHROME,115)&&-1!==uN().indexOf("Windows")){const t=function(e,t){if("VideoFrame"in window&&"TransformStream"in window&&_k().supportWebRTCInsertableStream){const n=new MediaStreamTrackProcessor(e),i=new MediaStreamTrackGenerator({kind:"video"});let r,o,s=Date.now();const a=()=>{c&&(clearInterval(c),c=void 0),r&&(r.close(),r=void 0),e.stop(),o=void 0,i.removeEventListener("ended",a)};let c=window.setInterval((()=>{if(o&&r&&Date.now()-s>(null!=t?t:1e3))try{"live"===i.readyState?o.enqueue(r.clone()):a()}catch(e){a()}}),null!=t?t:1e3);const d=new TransformStream({transform:(e,t)=>{"live"===i.readyState?(o=t,s=Date.now(),void 0===r?(r=e,t.enqueue(e.clone())):(t.enqueue(r),r=e)):e.close()}});return i.addEventListener("ended",a),n.readable.pipeThrough(d).pipeTo(i.writable),i}}(e);t&&(FL.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t)}t&&-1!==this._hints.indexOf(jk.CUSTOM_TRACK)&&this.setEncoderConfiguration(t),this._processorContext=new XM(this.getTrackId(),"local"),this._processorDestination=new YM(this.processorContext),this.bindProcessorDestinationEvents()}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(FL.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}FL.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const n=pM(pM(pM({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(n):(e instanceof HTMLVideoElement?this._player=new $U(n):this._player=new tV(n),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(Yk.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),rL("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,FL.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(FL.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await ND(this,Bk.NEED_DISABLE_TRACK,this)}catch(e){throw FL.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return t||(this._enabled=!1),void FL.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await ND(this,Bk.NEED_ENABLE_TRACK,this)}catch(e){throw FL.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}FL.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,FL.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await ND(this,Bk.NEED_MUTE_TRACK,this):await ND(this,Bk.NEED_UNMUTE_TRACK,this))}async setSaveEncodeBitrateRatio(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this._saveEncodeBitrateRatio;if(1!==this._saveEncodeBitrateRatio&&this._encoderConfig&&this._encoderConfig.bitrateMax&&this._encoderConfig.bitrateMin){this._encoderConfig.bitrateMin=Math.floor(this._encoderConfig.bitrateMin*e),this._encoderConfig.bitrateMax=Math.floor(this._encoderConfig.bitrateMax*e),FL.debug("[".concat(this.getTrackId(),"] set save encode bitrate ratio, ").concat(e)),this._saveEncodeBitrateRatio=1;try{await ND(this,Bk.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(FL)}}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new zN(JN.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=Lk(e),rL("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),e.width||e.height||e.frameRate){const t=$M({encoderConfig:e});(EN()||TN()||MN())&&(t.deviceId=void 0),FL.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(t));try{await this._originMediaStreamTrack.applyConstraints(t),this.updateMediaStreamTrackResolution()}catch(e){const t=new zN(JN.UNEXPECTED_ERROR,e.toString());throw FL.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(jk.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await ND(this,Bk.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(FL)}}getStats(){HD((()=>{FL.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")}),"localVideoTrackGetStatsWarning");return DD(this,Bk.GET_STATS)||pM({},qk)}async setBeautyEffect(e){FL.error("LocalVideoTrack.setBeautyEffect was deprecated, please migrate to agora-extension-beauty-effect")}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameImage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this._player?this._player.getCurrentFrameToUint8Array(e,t):await rU(e)}async findClosestProfile(){const e=this.getMediaStreamTrackSettings(),t=e.width,n=e.height,i=e.frameRate,r=this._encoderConfig||{},o=r.width,s=r.height,a=r.frameRate,c=cP(this._videoWidth||t||o||0),d=cP(this._videoHeight||n||s||0),l=function(e,t,n){if(!Array.isArray(rL("VIDEO_ENCODER_CONFIG_LIST")))return!1;if(0===rL("VIDEO_ENCODER_CONFIG_LIST").length)return!1;const i=Math.min(e,t);return!(i>=480)&&pM(pM({},rL("VIDEO_ENCODER_CONFIG_LIST").find((e=>e.height>i))),{},{frameRate:n})}(c,d,cP(i||a||15));if(l)return FL.debug("[".concat(this.getTrackId(),"] find closest profile, ").concat(c,"x").concat(d," => ").concat(JSON.stringify(l))),this.setEncoderConfiguration(l)}async setBitrateLimit(e){FL.debug("[".concat(this.getTrackId(),"] set bitrate limit, ").concat(JSON.stringify(e))),e&&(this._forceBitrateLimit=e,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax<e.max_bitrate?this._encoderConfig.bitrateMax:e.max_bitrate:this._encoderConfig.bitrateMax=e.max_bitrate,this._encoderConfig.bitrateMin,this._encoderConfig.bitrateMin=e.min_bitrate))}async setOptimizationMode(e){if("motion"!==e&&"detail"!==e&&"balanced"!==e)return void FL.error(JN.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const t=this._optimizationMode;try{this._optimizationMode=e,await ND(this,Bk.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this)}catch(e){throw this._optimizationMode=t,FL.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}FL.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))}setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return FL.error(JN.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,FL.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){QM(this._originMediaStreamTrack).then((e=>{let t=_M(e,2),n=t[0],i=t[1];this._videoHeight=i,this._videoWidth=n})).catch(nP)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async setSenderConfiguration(e){if(!this._enabled)throw new zN(JN.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");FL.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(e)),e=Lk(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),this._encoderConfig=e,-1===this._hints.indexOf(jk.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await ND(this,Bk.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(FL)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const e=this.getMediaStreamTrackSettings(),t=e.width,n=e.height,i=e.frameRate;if(!t||!n||!i)return;const r=this._encoderConfig,o=r.bitrateMax,s=r.bitrateMin;if(null==s||null==o){const e=function(e,t,n,i,r){const o=rL("BITRATE_ADAPTER_TYPE");if("DEFAULT_BITRATE"===o)return{min:i,max:r};if(void 0===r){const s=Math.floor(200*Math.pow(n/15,.6)*Math.pow(e*t/640/360,.75));r="STANDARD_BITRATE"===o?4*s:2*s,i=null!=i?i:s}else i=null!=i?i:Math.floor(r/10);return{min:i,max:r}}(t,n,i,s,o),r=e.max,a=e.min;if(this._encoderConfig.bitrateMin=a,this._encoderConfig.bitrateMax=r,rL("VIDEO_STANDARD_BITRATE_VERSION")&&null==s&&null==o){const e=_M(function(e,t,n){const i=4*Math.floor(2e5*Math.pow(n/15,.6)*Math.pow(e*t/230400,.75)),r=e*t,o=new Map([[19200,.9],[230400,.85],[518400,.75],[921600,.7],[2073600,.6],[3686400,.5]]),s=new Map([[230400,.95],[518400,.9],[921600,.85],[2073600,.8]]);let a=gp(o).call(o).next().value,c=1;if(o.has(r))a=o.get(r);else{var d;const e=n_(d=Array.from(o.entries())).call(d,((e,t)=>_M(e,1)[0]-_M(t,1)[0])),t=e.find((e=>_M(e,1)[0]>r));if(t){const n=e.indexOf(t);if(n>0){const i=e[n-1],o=(r-i[0])/(t[0]-i[0]);a=i[1]+o*(t[1]-i[1])}else a=t[1]}else a=e[e.length-1][1]}if(s.has(r))c=s.get(r);else{var l;const e=n_(l=Array.from(s.entries())).call(l,((e,t)=>_M(e,1)[0]-_M(t,1)[0])),t=e.find((e=>_M(e,1)[0]>r));if(t){const n=e.indexOf(t);if(n>0){const i=e[n-1],o=(r-i[0])/(t[0]-i[0]);c=i[1]+o*(t[1]-i[1])}else c=t[1]}else c=e[e.length-1][1]}const u=rL("VIDEO_NEW_BITRATE_RATIO");u&&u>0&&(a=u/100);const h=Math.floor(i*a),p=Math.floor(65e4*Math.pow(e*t/230400,.5)*Math.pow(n/15,.69));let _=h;const E=rL("VIDEO_STANDARD_BITRATE_VERSION");return E&&E>0&&(1===E?_=i:2===E?_=h:3===E&&(_=p)),[Math.floor(_/1e3),c]}(t,n,i),2),r=e[0],o=e[1];this._encoderConfig.bitrateMax=r,this._encoderConfig.bitrateMin=a?Math.min(a,r):r,this._saveEncodeBitrateRatio=o,FL.debug("[".concat(this.getTrackId(),"] update new bitrate from profile, [w: ").concat(t,", h: ").concat(n,", fps: ").concat(i,"] => [brMax: ").concat(this._encoderConfig.bitrateMax,", brMin: ").concat(this._encoderConfig.bitrateMin,", save_bitrate_ratio: ").concat(this._saveEncodeBitrateRatio,"]"))}else FL.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(t,", h: ").concat(n,", fps: ").concat(i,"] => [brMax: ").concat(r,", brMin: ").concat(a,"]")),this._saveEncodeBitrateRatio=1}}getVideoElementVisibleStatus(){try{var e,t;const n=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),i={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==n?void 0:n.parentElement},r=i.element,o=i.slot;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=cD.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=uk.reportApiInvoke(null,{tag:mD.TRACER,name:ED.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new zN(JN.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new zN(JN.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe()}clone(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;t&&(i=pM(pM({},i),Lk(t))),i=WD(i);const r=eP(8,"track-video-cloned-"),o=new e(n?this._mediaStreamTrack.clone():this._mediaStreamTrack,i,WD(this._scalabilityMode),this._optimizationMode,r,WD(this._hints));return t&&i&&o.setEncoderConfiguration(i),FL.debug("clone video track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(n)),o}async replaceTrack(e,t){if(!(e instanceof MediaStreamTrack))throw new zN(JN.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new zN(JN.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}sendSeiData(e){if(HD((()=>{uk.reportApiInvoke(null,{name:ED.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:mD.TRACER}).onSuccess("")}),this._mediaStreamTrack.id||this.getTrackId()),!rL("ENABLE_VIDEO_SEI")||!rL("ENABLE_ENCODED_TRANSFORM"))return void FL.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==0)return new zN(JN.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();const t=this.getRTCRtpTransceiver();if(!t)return void FL.warning("Video track is not published, SEI can not be send");const n=t.sender.getParameters();if(0===n.codecs.length)return;const i=n.codecs[0].mimeType.toLocaleLowerCase();"video/h264"===i||"video/h265"===i?this.safeEmit("sei-to-send",e):FL.warning("SEI is not supported by ".concat(i))}bindProcessorDestinationEvents(){this.processorDestination.on(tM.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await ND(this,Bk.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await ND(this,Bk.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(tM.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(nM.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(nM.REQUEST_CONSTRAINTS)}},dM(NV.prototype,"play",[nV,iV],Object.getOwnPropertyDescriptor(NV.prototype,"play"),NV.prototype),dM(NV.prototype,"stop",[rV],Object.getOwnPropertyDescriptor(NV.prototype,"stop"),NV.prototype),dM(NV.prototype,"setEnabled",[oV,sV,aV],Object.getOwnPropertyDescriptor(NV.prototype,"setEnabled"),NV.prototype),dM(NV.prototype,"setMuted",[cV,dV,lV],Object.getOwnPropertyDescriptor(NV.prototype,"setMuted"),NV.prototype),dM(NV.prototype,"setSaveEncodeBitrateRatio",[uV,hV],Object.getOwnPropertyDescriptor(NV.prototype,"setSaveEncodeBitrateRatio"),NV.prototype),dM(NV.prototype,"setEncoderConfiguration",[pV,_V],Object.getOwnPropertyDescriptor(NV.prototype,"setEncoderConfiguration"),NV.prototype),dM(NV.prototype,"getStats",[EV],Object.getOwnPropertyDescriptor(NV.prototype,"getStats"),NV.prototype),dM(NV.prototype,"setBeautyEffect",[mV,fV],Object.getOwnPropertyDescriptor(NV.prototype,"setBeautyEffect"),NV.prototype),dM(NV.prototype,"getCurrentFrameData",[gV],Object.getOwnPropertyDescriptor(NV.prototype,"getCurrentFrameData"),NV.prototype),dM(NV.prototype,"getCurrentFrameImage",[SV],Object.getOwnPropertyDescriptor(NV.prototype,"getCurrentFrameImage"),NV.prototype),dM(NV.prototype,"findClosestProfile",[TV,RV],Object.getOwnPropertyDescriptor(NV.prototype,"findClosestProfile"),NV.prototype),dM(NV.prototype,"setBitrateLimit",[vV],Object.getOwnPropertyDescriptor(NV.prototype,"setBitrateLimit"),NV.prototype),dM(NV.prototype,"setOptimizationMode",[yV],Object.getOwnPropertyDescriptor(NV.prototype,"setOptimizationMode"),NV.prototype),dM(NV.prototype,"setScalabiltyMode",[bV],Object.getOwnPropertyDescriptor(NV.prototype,"setScalabiltyMode"),NV.prototype),dM(NV.prototype,"updateMediaStreamTrackResolution",[CV],Object.getOwnPropertyDescriptor(NV.prototype,"updateMediaStreamTrackResolution"),NV.prototype),dM(NV.prototype,"pipe",[IV],Object.getOwnPropertyDescriptor(NV.prototype,"pipe"),NV.prototype),dM(NV.prototype,"unpipe",[AV],Object.getOwnPropertyDescriptor(NV.prototype,"unpipe"),NV.prototype),dM(NV.prototype,"close",[wV],Object.getOwnPropertyDescriptor(NV.prototype,"close"),NV.prototype),dM(NV.prototype,"replaceTrack",[OV],Object.getOwnPropertyDescriptor(NV.prototype,"replaceTrack"),NV.prototype),NV),jV=(DV=lk({argsMap:(e,t)=>[e.getTrackId(),t]}),PV=HM(),LV=EP("CameraVideoTrack","_enabledMutex"),kV=lk({argsMap:(e,t)=>[e.getTrackId(),t]}),MV=HM(),UV=lk({argsMap:(e,t)=>[e.getTrackId(),t]}),VV=HM(),xV=lk({argsMap:e=>[e.getTrackId()]}),FV=class e extends BV{get __className__(){return"CameraVideoTrack"}constructor(e,t,n,i,r,o){super(e,Lk(t.encoderConfig),i,r,o),uM(this,"_config",void 0),uM(this,"_originalConstraints",void 0),uM(this,"_constraints",void 0),uM(this,"_enabled",!0),uM(this,"_deviceName","default"),uM(this,"tryResumeVideoForIOS15_16WeChat",(async()=>{(PN()||LN())&&!function(){const e=dN();if(e.os!==rN.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=2}()&&UN()&&this._enabled&&!this._isClosed&&(FL.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack())})),this._config=t,this._originalConstraints=n,this._constraints=n,this._deviceName=e.label,this._encoderConfig=Lk(this._config.encoderConfig),TM.on(Ck.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),TM.on(Ck.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),this.bindProcessorContextEvents()}async setDevice(e){return"string"==typeof e?this._setDeviceById(e):e.deviceId?this._setDeviceById(e.deviceId):e.facingMode?this._setDeviceByFacingModel(e.facingMode):void 0}async _setDeviceById(e){if(FL.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await xM.getDeviceById(e),n={};n.video=pM({},this._constraints),n.video.deviceId={exact:e},n.video.facingMode=void 0,this._originMediaStreamTrack.stop();let i=null;try{i=await kM(n,this.getTrackId())}catch(e){throw FL.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),i=await kM({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(i.getVideoTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(i.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw FL.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await xM.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw FL.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}FL.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){FL.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:pM(pM({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await kM(t,this.getTrackId())}catch(t){throw FL.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await kM({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),t}await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution()}this._deviceName="",this._config.facingMode=e,this._config.cameraId=void 0,this._constraints=pM({},t.video),FL.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(FL.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await kM({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await ND(this,Bk.NEED_ENABLE_TRACK,this)}catch(e){throw FL.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),FL.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}else{this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),t||(this._enabled=!1);try{await ND(this,Bk.NEED_DISABLE_TRACK,this)}catch(e){throw FL.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}FL.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new zN(JN.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=Lk(e),rL("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate||e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate||e.bitrateMin);const n=GD(this._config);n.encoderConfig=e;const i=$M(n);(EN()||TN()||MN())&&(i.deviceId=void 0),FL.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(i));try{await this._originMediaStreamTrack.applyConstraints(i),this.updateMediaStreamTrackResolution()}catch(e){const t=new zN(JN.UNEXPECTED_ERROR,e.toString());throw FL.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}this._config=n,this._constraints=i,this._originalConstraints=i,this._encoderConfig=e,-1===this._hints.indexOf(jk.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await ND(this,Bk.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(FL)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((TN()||MN())&&this._enabled&&!this._isClosed&&TM.duringInterruption){const e=async()=>{TM.off(Ck.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(FL.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};TM.on(Ck.IOS_INTERRUPTION_END,e)}else FL.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Yk.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,n=xM.searchDeviceIdByName(this._deviceName);if(n&&!t.deviceId&&(t.deviceId={exact:n}),this._enabled){const e=await kM({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),TM.off(Ck.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),TM.off(Ck.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;t&&(i=pM(pM({},i),Lk(t))),i=WD(i);const r=eP(8,"track-cam-cloned-"),o=new e(n?this._mediaStreamTrack.clone():this._mediaStreamTrack,WD(pM(pM({},this._config),{},{encoderConfig:i})),WD(this._constraints),WD(this._scalabilityMode),this._optimizationMode,r);return t&&i&&o.setEncoderConfiguration(i),FL.debug("clone track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(n)),o}bindProcessorContextEvents(){this.processorContext.on(nM.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,n)=>{try{const n=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(n),t()}catch(e){n(e)}})),this.processorContext.on(nM.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}},dM(FV.prototype,"setDevice",[DV,PV],Object.getOwnPropertyDescriptor(FV.prototype,"setDevice"),FV.prototype),dM(FV.prototype,"setEnabled",[LV,kV,MV],Object.getOwnPropertyDescriptor(FV.prototype,"setEnabled"),FV.prototype),dM(FV.prototype,"setEncoderConfiguration",[UV,VV],Object.getOwnPropertyDescriptor(FV.prototype,"setEncoderConfiguration"),FV.prototype),dM(FV.prototype,"close",[xV],Object.getOwnPropertyDescriptor(FV.prototype,"close"),FV.prototype),FV);function GV(e){const t=eP(8,"track-cus-"),n=uk.reportApiInvoke(null,{id:t,tag:mD.TRACER,name:ED.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),i=new YU(e.mediaStreamTrack,e.encoderConfig?Vk(e.encoderConfig):{},t,!1);return FL.info("create custom audio track success with config",e,"trackId",i.getTrackId()),n.onSuccess(i.getTrackId()),i}function WV(e,t,n,i){n.optimizationMode&&(i&&i.width&&i.height?(n.encoderConfig=pM(pM({},i),{},{bitrateMin:i.bitrateMin,bitrateMax:i.bitrateMax}),"motion"!==n.optimizationMode&&"detail"!==n.optimizationMode||(t.contentHint=n.optimizationMode,t.contentHint===n.optimizationMode?FL.debug("[".concat(e,"] set content hint to"),n.optimizationMode):FL.debug("[".concat(e,"] set content hint failed")))):FL.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}var KV,HV,YV,XV,JV,zV,ZV,qV,QV,$V,ex,tx,nx;let ix=class extends EM{getUserId(){return this._userId}constructor(e,t,n,i){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(i.clientId,"_").concat(eP(5,""))),uM(this,"_userId",void 0),uM(this,"_uintId",void 0),uM(this,"_isDestroyed",!1),uM(this,"store",void 0),uM(this,"processor",void 0),uM(this,"processorContext",void 0),this._userId=t,this._uintId=n,this.store=i}_updateOriginMediaStreamTrack(e){this._originMediaStreamTrack=e,this._mediaStreamTrack=e,this._updatePlayerSource(),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext})}_destroy(){this._isDestroyed=!0,FL.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}},rx=(KV=lk({argsMap:(e,t,n)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",n]}),HV=lk({argsMap:e=>[e.getTrackId()]}),YV=lk({argsMap:(e,t)=>[e.getTrackId(),t.name]}),XV=lk({argsMap:e=>[e.getTrackId()]}),dM((JV=class extends ix{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==oM.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,n,i,r){super(e,t,n,i),uM(this,"_videoVisibleTimer",null),uM(this,"_previousVideoVisibleStatus",void 0),uM(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),uM(this,"trackMediaType",Jk.VIDEO),uM(this,"_videoWidth",void 0),uM(this,"_videoHeight",void 0),uM(this,"_player",void 0),uM(this,"_prePlayer",void 0),uM(this,"processorDestination",void 0),uM(this,"processorContext",void 0),this._prePlayer=r,this.updateMediaStreamTrackResolution(),this.processorContext=new XM(this.getTrackId(),"remote"),this.processorDestination=new YM(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){return HD((()=>{FL.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning"),DD(this,Bk.GET_STATS)||pM({},eM)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.safeEmit(Xk.PLAY_START),"string"==typeof e){const t=document.getElementById(e);t?e=t:(FL.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}FL.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const n=pM(pM({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});if(this._player)this._player.updateConfig(n);else{let t=!1,i=!1;const r=this._prePlayer&&!this._prePlayer.isDestroyed&&e===this._prePlayer.config.element;this._prePlayer&&!r&&(this._prePlayer.destroy(),i=!0),r?(this._player=this._prePlayer,t=this._player.videoState>0,this._player.updateConfig(n)):this._player=e instanceof HTMLVideoElement?new $U(n):new tV(n),this._prePlayer=void 0,this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(Xk.FIRST_FRAME_DECODED),i&&this.safeEmit(Xk.FIRST_FRAME_RENDER)},this._player.onVideoStateChanged=e=>{this.safeEmit(Xk.VIDEO_STATE_CHANGED,e)},t&&(this._player.onFirstVideoFrameDecoded(),this._player.onVideoStateChanged(this._player.videoState))}this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(Xk.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),rL("CHECK_VIDEO_VISIBLE_INTERVAL")),this.safeEmit(Xk.PLAY_END)}stop(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(e),this._player=void 0,FL.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){QM(this._originMediaStreamTrack).then((e=>{let t=_M(e,2),n=t[0],i=t[1];this._videoHeight=i,this._videoWidth=n})).catch(nP)}_updatePlayerSource(){FL.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;const n=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),i={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==n?void 0:n.parentElement},r=i.element,o=i.slot;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=cD.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=uk.reportApiInvoke(null,{tag:mD.TRACER,name:ED.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new zN(JN.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new zN(JN.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(tM.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(tM.ON_TRACK)}_destroy(){this._prePlayer&&(this._prePlayer.destroy(),this._prePlayer=void 0),super._destroy(),this.unbindProcessorDestinationEvents()}_onSei(e){this.emit(Hk.SEI_RECEIVED,e)}}).prototype,"play",[KV],Object.getOwnPropertyDescriptor(JV.prototype,"play"),JV.prototype),dM(JV.prototype,"stop",[HV],Object.getOwnPropertyDescriptor(JV.prototype,"stop"),JV.prototype),dM(JV.prototype,"pipe",[YV],Object.getOwnPropertyDescriptor(JV.prototype,"pipe"),JV.prototype),dM(JV.prototype,"unpipe",[XV],Object.getOwnPropertyDescriptor(JV.prototype,"unpipe"),JV.prototype),JV),ox=(zV=lk({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),ZV=lk({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),qV=lk({argsMap:(e,t)=>[e.getTrackId(),t]}),QV=lk({argsMap:e=>[e.getTrackId()]}),$V=lk({argsMap:e=>[e.getTrackId()]}),ex=lk({argsMap:(e,t)=>[e.getTrackId(),t.name]}),tx=lk({argsMap:e=>[e.getTrackId()]}),dM((nx=class extends ix{get isPlaying(){return this._useAudioElement?KM.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,n,i){super(e,t,n,i),uM(this,"trackMediaType",Jk.AUDIO),uM(this,"_source",void 0),uM(this,"_useAudioElement",!0),uM(this,"_volume",100),uM(this,"processorContext",void 0),uM(this,"processorDestination",void 0),uM(this,"_played",!1),uM(this,"_bypassWebAudio",!1),rL("DISABLE_WEBAUDIO")?(this._source=new ZM,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new AM(e,!0),rL("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(zk.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(Xk.FIRST_FRAME_DECODED)})),this.processorContext=new zM(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new JM(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(zk.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(zk.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(zk.ON_AUDIO_BUFFER),this._source.on(zk.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?KM.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}setAmplifiedVolume(e){this._useAudioElement&&this._played&&(KM.stop(this.getTrackId()),this._source.play()),this._useAudioElement=!1,e=Math.min(e,rL("MAX_WEBAUDIO_VOLUME")),this._volume=e,this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!Ek())throw new zN(JN.NOT_SUPPORTED,"your browser does not support setting the audio output device");await KM.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getVolume(){return this._useAudioElement?KM.getVolume(this.getTrackId()):this._source instanceof AM?this._source.getAudioVolume():0}getStats(){return HD((()=>{FL.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning"),DD(this,Bk.GET_STATS)||pM({},Qk)}play(){FL.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(FL.debug("[".concat(this.getTrackId(),"] use audio element to play")),KM.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):(FL.debug("[".concat(this.getTrackId(),"] use audio context to play")),this._source.play())}stop(){FL.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?KM.stop(this.getTrackId()):this._source.stop()}_destroy(){super._destroy(),this._played=!1,this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];FL.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&KM.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new zN(JN.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new zN(JN.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(this._bypassWebAudio)throw new zN(JN.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(tM.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())})),this.processorDestination.on(tM.ON_NODE,(e=>{this._source.processedNode=e;const t=!e;this._useAudioElement!==t&&(this._played?(this.stop(),this._useAudioElement=t,this.play()):this._useAudioElement=t)}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(tM.ON_TRACK),this.processorDestination.removeAllListeners(tM.ON_NODE)}}).prototype,"setVolume",[zV],Object.getOwnPropertyDescriptor(nx.prototype,"setVolume"),nx.prototype),dM(nx.prototype,"setAmplifiedVolume",[ZV],Object.getOwnPropertyDescriptor(nx.prototype,"setAmplifiedVolume"),nx.prototype),dM(nx.prototype,"setPlaybackDevice",[qV],Object.getOwnPropertyDescriptor(nx.prototype,"setPlaybackDevice"),nx.prototype),dM(nx.prototype,"play",[QV],Object.getOwnPropertyDescriptor(nx.prototype,"play"),nx.prototype),dM(nx.prototype,"stop",[$V],Object.getOwnPropertyDescriptor(nx.prototype,"stop"),nx.prototype),dM(nx.prototype,"pipe",[ex],Object.getOwnPropertyDescriptor(nx.prototype,"pipe"),nx.prototype),dM(nx.prototype,"unpipe",[tx],Object.getOwnPropertyDescriptor(nx.prototype,"unpipe"),nx.prototype),nx);const sx=new class extends hD{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),uM(this,"_lastHiddenTime",0),uM(this,"_lastVisibleTime",0),uM(this,"needUploadStats",[]),uM(this,"isCollectingStats",!1),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),this.isCollectingStats&&this.needUploadStats.push("visible"===document.visibilityState?1:0),FL.debug("current web page is ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)}))}startCollectStats(){this.isCollectingStats=!0,this.needUploadStats.push("visible"===this.visibility?1:0)}stopCollectStats(){this.isCollectingStats=!1,this.needUploadStats.length=0}};let ax=class extends hD{constructor(e,t){super(),uM(this,"trackMediaType",Jk.DATA),uM(this,"_version",1),uM(this,"_type",3),uM(this,"_config",void 0),uM(this,"_originDataChannel",void 0),uM(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),uM(this,"_dataStreamPacketHandler",{serialize:e=>e,deserialize:e=>e}),uM(this,"_datachannelEventMap",new Map),this._config=e,t&&(this._originDataChannel=t,this._bandDataChannelEvents(t)),this._initPacketHeader()}useDataStream(e){this._dataStreamPacketHandler=e}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return rL("DATASTREAM_MAX_RETRANSMITS")}get metadata(){return this._config.metadata}get readyState(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.readyState)&&void 0!==e?e:"connecting"}get _originDataChannelId(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.id)&&void 0!==e?e:null}getChannelId(){return this.id}getConfig(){return this._config}_close(){this._originDataChannel&&(this._unbindDataChannelEvents(this._originDataChannel),this._originDataChannel=void 0)}async _waitTillOpen(){return new dp(((e,t)=>{if(this._originDataChannel){"open"===this._originDataChannel.readyState&&e();const n=setTimeout((()=>{var e;t(new zN(JN.DATACHANNEL_CONNECTION_TIMEOUT,"Cannot create datachannel, id: ".concat(null===(e=this._originDataChannel)||void 0===e?void 0:e.id)))}),1e4);this._originDataChannel.onopen=()=>{clearTimeout(n),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),e()},this._originDataChannel.onerror=()=>{throw clearTimeout(n),new zN(JN.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new zN(JN.DATACHANNEL_CONNECTION_TIMEOUT,"cannot find dataChannel"))}))}_updateOriginDataChannel(e){this._originDataChannel=e,this._bandDataChannelEvents(e)}_initPacketHeader(){const e=new DataView(this._dataStreamPacketHeader);e.setUint16(0,this._version),e.setUint8(2,this._type),e.setUint8(3,this._config.id)}_bandDataChannelEvents(e){this._unbindDataChannelEvents(e),[cM.OPEN,cM.CLOSE,cM.ERROR].forEach((t=>{const n=()=>{this.emit(t)};this._datachannelEventMap.set(t,n),e.addEventListener(t,n)}))}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach((t=>{let n=_M(t,2),i=n[0],r=n[1];e.removeEventListener(i,r)})),this._datachannelEventMap.clear()}},cx=class extends ax{constructor(e){super(e),uM(this,"_messageListener",void 0),this._messageListener=e=>{if(e.data.byteLength<this._dataStreamPacketHeader.byteLength)throw Error("invalid byteLength: the byte length must exceed "+this._dataStreamPacketHeader.byteLength);const t=e.data.slice(0,this._dataStreamPacketHeader.byteLength),n=new DataView(t).getUint8(3);if(n!==this.id)return void(rL("SHOW_DATASTREAM2_LOG")&&FL.debug("invalid datachannel id: ".concat(n," !== ").concat(this.id)));let i=e.data.slice(this._dataStreamPacketHeader.byteLength);i=this._dataStreamPacketHandler.deserialize(i),this.emit(cM.MESSAGE,i)}}_updateDataChannelConfig(e){this._config=e}_updateOriginDataChannel(e){super._updateOriginDataChannel(e),this._bandRemoteDataChannelEvents()}_close(){this._originDataChannel&&(this._originDataChannel.removeEventListener("message",this._messageListener),super._close())}_bandRemoteDataChannelEvents(){this._originDataChannel&&this._originDataChannel.addEventListener("message",this._messageListener)}},dx=class extends ax{send(e){if(this._originDataChannel){let t=e;t=this._dataStreamPacketHandler.serialize(e);const n=new Uint8Array(this._dataStreamPacketHeader.byteLength+t.byteLength);n.set(new Uint8Array(this._dataStreamPacketHeader),0),n.set(new Uint8Array(t),this._dataStreamPacketHeader.byteLength),this._originDataChannel.send(n.buffer)}}};function lx(){const e=new Blob([atob("ZnVuY3Rpb24gdCh0LGUsbil7cmV0dXJuKGU9ZnVuY3Rpb24odCl7dmFyIGU9ZnVuY3Rpb24odCxlKXtpZigib2JqZWN0IiE9dHlwZW9mIHR8fCF0KXJldHVybiB0O3ZhciBuPXRbU3ltYm9sLnRvUHJpbWl0aXZlXTtpZih2b2lkIDAhPT1uKXt2YXIgcj1uLmNhbGwodCxlfHwiZGVmYXVsdCIpO2lmKCJvYmplY3QiIT10eXBlb2YgcilyZXR1cm4gcjt0aHJvdyBuZXcgVHlwZUVycm9yKCJAQHRvUHJpbWl0aXZlIG11c3QgcmV0dXJuIGEgcHJpbWl0aXZlIHZhbHVlLiIpfXJldHVybigic3RyaW5nIj09PWU/U3RyaW5nOk51bWJlcikodCl9KHQsInN0cmluZyIpO3JldHVybiJzeW1ib2wiPT10eXBlb2YgZT9lOmUrIiJ9KGUpKWluIHQ/T2JqZWN0LmRlZmluZVByb3BlcnR5KHQsZSx7dmFsdWU6bixlbnVtZXJhYmxlOiEwLGNvbmZpZ3VyYWJsZTohMCx3cml0YWJsZTohMH0pOnRbZV09bix0fWZ1bmN0aW9uIGUodCxlKXt2YXIgbj1PYmplY3Qua2V5cyh0KTtpZihPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgcj1PYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKHQpO2UmJihyPXIuZmlsdGVyKChmdW5jdGlvbihlKXtyZXR1cm4gT2JqZWN0LmdldE93blByb3BlcnR5RGVzY3JpcHRvcih0LGUpLmVudW1lcmFibGV9KSkpLG4ucHVzaC5hcHBseShuLHIpfXJldHVybiBufWNvbnN0IG49InZpZGVvL2gyNjQiLHI9InZpZGVvL2gyNjUiO2Z1bmN0aW9uIGEodCxlLG4pe2xldCByPW5ldyBVaW50OEFycmF5KHQsZSxuKSxhPVtdLG89MDtmb3IoO2EubGVuZ3RoPG47KW8rMzxuJiYwPT09cltvXSYmMD09PXJbbysxXSYmMz09PXJbbysyXSYmKDA9PT1yW28rM118fDE9PT1yW28rM118fDI9PT1yW28rM118fDM9PT1yW28rM10pPyhhLnB1c2gocltvXSxyW28rMV0scltvKzNdKSxvKz00KTooYS5wdXNoKHJbb10pLG8rKyk7cmV0dXJuIG5ldyBVaW50OEFycmF5KGEpfWZ1bmN0aW9uIG8odCxlKXtzd2l0Y2goZSl7Y2FzZSBuOnJldHVybiBmdW5jdGlvbih0KXtjb25zdCBlPW5ldyBEYXRhVmlldyh0LmRhdGEpO2xldCBuPTA7Zm9yKDtuKzQ8dC5kYXRhLmJ5dGVMZW5ndGg7KXtpZigwPT09ZS5nZXRVaW50OChuKzApJiYwPT09ZS5nZXRVaW50OChuKzEpJiYwPT09ZS5nZXRVaW50OChuKzIpJiYxPT09ZS5nZXRVaW50OChuKzMpJiY2PT09ZS5nZXRVaW50OChuKzQpKXtsZXQgcj1uKzYsbz0wLGk9MDtmb3IoOzI1NT09PShpPWUuZ2V0VWludDgocisrKSk7KW8rPTI1NTtvKz1pO2NvbnN0IHM9YSh0LmRhdGEscixvKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkocyl9bisrfXJldHVybiBudWxsfSh0KTtjYXNlIHI6cmV0dXJuIGZ1bmN0aW9uKHQpe2NvbnN0IGU9bmV3IERhdGFWaWV3KHQuZGF0YSk7bGV0IG49MDtmb3IoO24rNTx0LmRhdGEuYnl0ZUxlbmd0aDspe2lmKDA9PT1lLmdldFVpbnQ4KG4rMCkmJjA9PT1lLmdldFVpbnQ4KG4rMSkmJjA9PT1lLmdldFVpbnQ4KG4rMikmJjE9PT1lLmdldFVpbnQ4KG4rMykmJjc4PT09ZS5nZXRVaW50OChuKzQpJiYxPT09ZS5nZXRVaW50OChuKzUpJiYxMDE9PT1lLmdldFVpbnQ4KG4rNikpe2xldCByPW4rNyxvPTAsaT0wO2Zvcig7MjU1PT09KGk9ZS5nZXRVaW50OChyKyspKTspbys9MjU1O28rPWk7Y29uc3Qgcz1hKHQuZGF0YSxyLG8pO3JldHVybiBuZXcgVWludDhBcnJheShzKX1uKyt9cmV0dXJuIG51bGx9KHQpO2RlZmF1bHQ6cmV0dXJuIG51bGx9fWZ1bmN0aW9uIGkodCl7Y29uc3QgZT10Lmxlbmd0aDtsZXQgbj1bXSxyPTA7Zm9yKDtyPGU7KXIrMjxlJiYwPT09dFtyXSYmMD09PXRbcisxXSYmKDA9PT10W3IrMl18fDE9PT10W3IrMl18fDI9PT10W3IrMl18fDM9PT10W3IrMl0pPyhuLnB1c2godFtyXSx0W3IrMV0sMyx0W3IrMl0pLHIrPTMpOihuLnB1c2godFtyXSkscisrKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkobil9ZnVuY3Rpb24gcyh0LGUsYSl7c3dpdGNoKGEpe2Nhc2UgbjpyZXR1cm4gZnVuY3Rpb24odCxlKXtjb25zdCBuPWkoZSkscj1uLmxlbmd0aCxhPU1hdGguZmxvb3Ioci8yNTUpLG89ciUyNTUscz1uZXcgVWludDhBcnJheSg2K2ErMStyK3QuYnl0ZUxlbmd0aCk7c1swXT0wLHNbMV09MCxzWzJdPTAsc1szXT0xLHNbNF09NixzWzVdPTEwMTtsZXQgZj0wO2Zvcig7ZjxhOylzWzYrZl09MjU1LGYrKztyZXR1cm4gc1s2K2ZdPW8sZisrLHMuc2V0KG4sNitmKSxzLnNldChuZXcgVWludDhBcnJheSh0KSw2K2Yrcikscy5idWZmZXJ9KHQsZSk7Y2FzZSByOnJldHVybiBmdW5jdGlvbih0LGUpe2NvbnN0IG49aShlKSxyPW4ubGVuZ3RoLGE9TWF0aC5mbG9vcihyLzI1NSksbz1yJTI1NSxzPW5ldyBVaW50OEFycmF5KDcrYSsxK3IrMSt0LmJ5dGVMZW5ndGgpO3NbMF09MCxzWzFdPTAsc1syXT0wLHNbM109MSxzWzRdPTc4LHNbNV09MSxzWzZdPTEwMTtsZXQgZj0wO2Zvcig7ZjxhOylzWzcrZl09MjU1LGYrKztyZXR1cm4gc1s3K2ZdPW8sZisrLHMuc2V0KG4sNytmKSxmKz1yLHNbNytmXT0xMjgsZisrLHMuc2V0KG5ldyBVaW50OEFycmF5KHQpLDcrZikscy5idWZmZXJ9KHQsZSk7ZGVmYXVsdDpyZXR1cm4gbnVsbH19ZnVuY3Rpb24gZih0KXtpZih0Lmxlbmd0aDw1KXJldHVybiIiO2xldCBlPS0xO2ZvcihsZXQgbj0wO248dC5sZW5ndGgtMztuKyspe2lmKDA9PT10W25dJiYwPT09dFtuKzFdJiYxPT09dFtuKzJdKXtlPW47YnJlYWt9aWYobjx0Lmxlbmd0aC00JiYwPT09dFtuXSYmMD09PXRbbisxXSYmMD09PXRbbisyXSYmMT09PXRbbiszXSl7ZT1uO2JyZWFrfX1pZigtMT09PWUpcmV0dXJuIiI7Y29uc3QgYT1lKygwPT09dFtlKzJdPzQ6Myk7aWYoYT49dC5sZW5ndGgpcmV0dXJuIiI7Y29uc3Qgbz10W2FdO2lmKDEyOCZvKXJldHVybiIiO2lmKChvPj4xJjYzKT49MzIpcmV0dXJuIHI7aWYoYSsxPHQubGVuZ3RoKXtpZigwPT0oMjQ4JnRbYSsxXSkpcmV0dXJuIHJ9cmV0dXJuKDMxJm8pPD0zMT9uOiIifWNvbnN0IGw9NzEsdT0xLGM9MixnPTEscD0yO3ZhciBkPWZ1bmN0aW9uKHQpe3JldHVybiB0W3QuQVVESU9fTEVWRUw9MV09IkFVRElPX0xFVkVMIix0W3QuTUVUQURBVEE9Ml09Ik1FVEFEQVRBIix0W3QuQVVESU9fNjRfQklUX1BUUz0zXT0iQVVESU9fNjRfQklUX1BUUyIsdH0oZHx8e30pO2Z1bmN0aW9uIGgodCl7bGV0IGU9YXJndW1lbnRzLmxlbmd0aD4xJiZ2b2lkIDAhPT1hcmd1bWVudHNbMV0mJmFyZ3VtZW50c1sxXTtjb25zdCBuPXQuZ2V0VWludDgoMCk7aWYobiE9PWwpcmV0dXJuO2NvbnN0IHI9dC5nZXRVaW50MTYoMSksYT11K2MrcixvPW5ldyBVaW50OEFycmF5KHQuYnl0ZUxlbmd0aC1hKTtvLnNldChuZXcgVWludDhBcnJheSh0LmJ1ZmZlcixhLHQuYnl0ZUxlbmd0aC1hKSk7Y29uc3QgaT17bTpuLHRsdkxlbjpyLHRsdjpbXSxmcmFtZTpvfTtsZXQgcz11K2M7Zm9yKDtzPGE7KXtjb25zdCBuPXQuZ2V0VWludDgocykscj10LmdldFVpbnQxNihzK2cpLGE9ZytwO2lmKG49PT1kLkFVRElPX0xFVkVMKXtsZXQgbz10LmdldFVpbnQ4KHMrYSk7Zm9yKGxldCBlPTE7ZTxyO2UrKylvPW88PDh8dC5nZXRVaW50OChzK2ErZSk7aS50bHYucHVzaCh7dGFnOm4sbGVuZ3RoOnIsdmFsdWU6ZT8xMjdebz4+MToxMjcmb30pfWVsc2UgaWYobj09PWQuTUVUQURBVEF8fG49PT1kLkFVRElPXzY0X0JJVF9QVFMpe2NvbnN0IGU9bmV3IFVpbnQ4QXJyYXkocik7Zm9yKGxldCBuPTA7bjxyO24rKyllW25dPXQuZ2V0VWludDgocythK24pO2kudGx2LnB1c2goe3RhZzpuLGxlbmd0aDpyLHZhbHVlOmV9KX1zKz1hK3J9cmV0dXJuIGl9c2VsZi5vbnJ0Y3RyYW5zZm9ybT1uPT57Y29uc3Qgcj1uLnRyYW5zZm9ybWVyLGE9W10saT1bXTtsZXQgeT1udWxsO3Iub3B0aW9ucy5wb3J0Lm9ubWVzc2FnZT10PT57dC5kYXRhLnNlaSYmYS5wdXNoKHQuZGF0YS5zZWkpLHQuZGF0YS5tZXRhZGF0YSYmaS5wdXNoKHQuZGF0YS5tZXRhZGF0YSl9LHNlbGYucG9zdE1lc3NhZ2UoInN0YXJ0ZWQiKTtjb25zdCBVPXIucmVhZGFibGUuZ2V0UmVhZGVyKCksYj1yLndyaXRhYmxlLmdldFdyaXRlcigpOyJzZWktcngiPT09ci5vcHRpb25zLm5hbWU/ZnVuY3Rpb24gbihyKXtVLnJlYWQoKS50aGVuKChhPT57aWYoIWEuZG9uZSl7aWYoYS52YWx1ZSBpbnN0YW5jZW9mIFJUQ0VuY29kZWRWaWRlb0ZyYW1lKXtjb25zdCBuPWYobmV3IFVpbnQ4QXJyYXkoYS52YWx1ZS5kYXRhKSksaT1vKGEudmFsdWUsbik7aWYoaSYmci5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3NlaTppfSksIXkpe2NvbnN0IG49YS52YWx1ZS5nZXRNZXRhZGF0YSgpfHx7fTt5PWZ1bmN0aW9uKG4pe2Zvcih2YXIgcj0xO3I8YXJndW1lbnRzLmxlbmd0aDtyKyspe3ZhciBhPW51bGwhPWFyZ3VtZW50c1tyXT9hcmd1bWVudHNbcl06e307ciUyP2UoT2JqZWN0KGEpLCEwKS5mb3JFYWNoKChmdW5jdGlvbihlKXt0KG4sZSxhW2VdKX0pKTpPYmplY3QuZ2V0T3duUHJvcGVydHlEZXNjcmlwdG9ycz9PYmplY3QuZGVmaW5lUHJvcGVydGllcyhuLE9iamVjdC5nZXRPd25Qcm9wZXJ0eURlc2NyaXB0b3JzKGEpKTplKE9iamVjdChhKSkuZm9yRWFjaCgoZnVuY3Rpb24odCl7T2JqZWN0LmRlZmluZVByb3BlcnR5KG4sdCxPYmplY3QuZ2V0T3duUHJvcGVydHlEZXNjcmlwdG9yKGEsdCkpfSkpfXJldHVybiBufSh7dHlwZTphLnZhbHVlLnR5cGUscnRwVGltZXN0YW1wOmEudmFsdWUudGltZXN0YW1wLHBheWxvYWRUeXBlOm4ucGF5bG9hZFR5cGV8fDAsc3NyYzpuLnN5bmNocm9uaXphdGlvblNvdXJjZXx8MCxsZW5ndGg6YS52YWx1ZS5kYXRhLmJ5dGVMZW5ndGh9LCJtaW1lVHlwZSJpbiBuP3ttaW1lVHlwZTpuLm1pbWVUeXBlfTp7fSksci5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe2ZpcnN0RnJhbWVJbmZvOnl9KX19Yi53cml0ZShhLnZhbHVlKSxyLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSxuKHIpfX0pKX0ocik6InNlaS10eCI9PT1yLm9wdGlvbnMubmFtZT9mdW5jdGlvbiB0KGUpe1UucmVhZCgpLnRoZW4oKG49PntpZighbi5kb25lKXtpZihuLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZFZpZGVvRnJhbWUpe2NvbnN0IHQ9ZihuZXcgVWludDhBcnJheShuLnZhbHVlLmRhdGEpKSxlPWEuc2hpZnQoKTtpZihlKXtjb25zdCByPXMobi52YWx1ZS5kYXRhLGUsdCk7ciYmKG4udmFsdWUuZGF0YT1yKX19Yi53cml0ZShuLnZhbHVlKSxlLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSx0KGUpfX0pKX0ocik6ImF1ZGlvLW1ldGFkYXRhLXJ4Ij09PXIub3B0aW9ucy5uYW1lP2Z1bmN0aW9uIHQoZSl7VS5yZWFkKCkudGhlbigobj0+e2lmKCFuLmRvbmUpe2lmKG4udmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkQXVkaW9GcmFtZSl7Y29uc3QgdD1uZXcgRGF0YVZpZXcobi52YWx1ZS5kYXRhKSxyPXQuZ2V0VWludDgoMCk7bGV0IGE7aWYoMCE9KDEyOCZyKSYmNzEhPT1yKXtjb25zdCBlPWZ1bmN0aW9uKHQpe2lmKHQuYnl0ZUxlbmd0aDw9MClyZXR1cm5bXTtjb25zdCBlPVtdO2xldCBuPTA7Zm9yKDtuPHQuYnl0ZUxlbmd0aDspe2NvbnN0IHI9KDEyOCZ0LmdldFVpbnQ4KG4pKT4+NyxhPTEyNyZ0LmdldFVpbnQ4KG4pO2lmKCEociYmbis0PD10LmJ5dGVMZW5ndGgpKXtuKys7YnJlYWt9e2NvbnN0IHI9dC5nZXRVaW50MzIobiwhMSksbz0oMTY3NzYxOTImcik+PjEwLGk9MTAyMyZyO2UucHVzaCh7cHQ6YSx0c19vZmZzZXQ6byxsZW5ndGg6aSxkYXRhOm5ldyBVaW50OEFycmF5fSksbis9NH19bGV0IHI9dC5ieXRlTGVuZ3RoLW47Zm9yKGNvbnN0IGEgb2YgZSl7aWYoYS5sZW5ndGg+cilyZXR1cm4gY29uc29sZS53YXJuKCJCcm9rZW4gcmVkIHBheWxvYWQiKSxbXTthLmxlbmd0aD4wJiYoYS5kYXRhPW5ldyBVaW50OEFycmF5KHQuYnVmZmVyLHQuYnl0ZU9mZnNldCtuLGEubGVuZ3RoKSxuKz1hLmxlbmd0aCxyLT1hLmxlbmd0aCl9aWYocj4wKXtjb25zdCBhPXtwdDplLmxlbmd0aD4wP2VbZS5sZW5ndGgtMV0ucHQ6MCx0c19vZmZzZXQ6MCxsZW5ndGg6cixkYXRhOm5ldyBVaW50OEFycmF5KHQuYnVmZmVyLHQuYnl0ZU9mZnNldCtuLHIpfTtlLnB1c2goYSl9cmV0dXJuIGV9KHQpO2lmKGUubGVuZ3RoPjApe2NvbnN0IHQ9ZnVuY3Rpb24odCl7bGV0IGU9MDtmb3IobGV0IG49MDtuPHQubGVuZ3RoO24rKyllKz1uPHQubGVuZ3RoLTE/NDoxLGUrPXRbbl0ubGVuZ3RoO2NvbnN0IG49bmV3IFVpbnQ4QXJyYXkoZSk7bGV0IHI9MDtmb3IobGV0IGU9MDtlPHQubGVuZ3RoO2UrKylpZihlPHQubGVuZ3RoLTEpe2NvbnN0IGE9KDIxNDc0ODM2NDh8KDEyNyZ0W2VdLnB0KTw8MjR8KDI2MjE0MyZ0W2VdLnRzX29mZnNldCk8PDEwfDEwMjMmdFtlXS5sZW5ndGgpPj4+MDtuW3IrK109YT4+MjQmMjU1LG5bcisrXT1hPj4xNiYyNTUsbltyKytdPWE+PjgmMjU1LG5bcisrXT0yNTUmYX1lbHNlIG5bcisrXT0xMjcmdFtlXS5wdDtmb3IoY29uc3QgZSBvZiB0KW4uc2V0KGUuZGF0YSxyKSxyKz1lLmxlbmd0aDtyZXR1cm4gbn0oZS5tYXAoKHQ9Pntjb25zdCBlPW5ldyBVaW50OEFycmF5KHQubGVuZ3RoKTtlLnNldCh0LmRhdGEpO2NvbnN0IG49aChuZXcgRGF0YVZpZXcoZS5idWZmZXIpKTtyZXR1cm4gbnVsbCE9biYmbi5mcmFtZSYmKHQuZGF0YT1udWxsPT1uP3ZvaWQgMDpuLmZyYW1lKSxhPW4sdH0pKSk7bi52YWx1ZS5kYXRhPXQuYnVmZmVyfX1lbHNlIGE9aCh0KSxhJiYobi52YWx1ZS5kYXRhPWEuZnJhbWUuYnVmZmVyKTtpZihhKXtsZXQgdD1hLnRsdi5maW5kKCh0PT50LnRhZz09PWQuTUVUQURBVEEpKTtpZih0JiZ0LnZhbHVlIGluc3RhbmNlb2YgVWludDhBcnJheSYmZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe21ldGFkYXRhOnQudmFsdWV9KSx0PWEudGx2LmZpbmQoKHQ9PnQudGFnPT09ZC5BVURJT182NF9CSVRfUFRTKSksdCYmdC52YWx1ZSBpbnN0YW5jZW9mIFVpbnQ4QXJyYXkmJjg9PXQudmFsdWUubGVuZ3RoKXtjb25zdCBuPW5ldyBEYXRhVmlldyh0LnZhbHVlLmJ1ZmZlcikuZ2V0QmlnVWludDY0KDAsITApO3QmJnQudmFsdWUgaW5zdGFuY2VvZiBVaW50OEFycmF5JiZlLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7cHRzOm59KX19fWIud3JpdGUobi52YWx1ZSksZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3RyYW5zZm9ybWVkOiEwfSksdChlKX19KSl9KHIpOiJhdWRpby1tZXRhZGF0YS10eCI9PT1yLm9wdGlvbnMubmFtZSYmZnVuY3Rpb24gdChlKXtVLnJlYWQoKS50aGVuKChuPT57aWYoIW4uZG9uZSl7aWYoZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe2dldE1ldGFkYXRhOiEwfSksbi52YWx1ZSBpbnN0YW5jZW9mIFJUQ0VuY29kZWRBdWRpb0ZyYW1lKXtjb25zdCB0PWkuc2hpZnQoKTt0JiYobi52YWx1ZS5kYXRhPWZ1bmN0aW9uKHQsZSxuKXtjb25zdCByPW4uYnl0ZUxlbmd0aCxhPXIrZytwLG89dStjK2EsaT1uZXcgQXJyYXlCdWZmZXIodC5ieXRlTGVuZ3RoK28pLHM9bmV3IERhdGFWaWV3KGkpO3Muc2V0VWludDgoMCxsKSxzLnNldFVpbnQxNigxLGEpLHMuc2V0VWludDgoMyxlKSxzLnNldFVpbnQxNig0LHIpO2ZvcihsZXQgdD0wO3Q8cjt0Kyspcy5zZXRVaW50OCg2K3Qsblt0XSk7Y29uc3QgZj1uZXcgVWludDhBcnJheShzLmJ1ZmZlcik7cmV0dXJuIGYuc2V0KG5ldyBVaW50OEFycmF5KHQpLG8pLGYuYnVmZmVyfShuLnZhbHVlLmRhdGEsZC5BVURJT182NF9CSVRfUFRTLHQpKX1iLndyaXRlKG4udmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfShyKX0sc2VsZi5wb3N0TWVzc2FnZSgicmVnaXN0ZXJlZCIpOwo=")],{type:"text/javascript"});return setTimeout((()=>Fg.revokeObjectURL(e)),0),new Worker(Fg.createObjectURL(e))}const ux=71,hx=1,px=2,_x=1,Ex=2;var mx=function(e){return e[e.AUDIO_LEVEL=1]="AUDIO_LEVEL",e[e.METADATA=2]="METADATA",e[e.AUDIO_64_BIT_PTS=3]="AUDIO_64_BIT_PTS",e}(mx||{});function fx(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=e.getUint8(0);if(n!==ux)return;const i=e.getUint16(1),r=hx+px+i,o=new Uint8Array(e.byteLength-r);o.set(new Uint8Array(e.buffer,r,e.byteLength-r));const s={m:n,tlvLen:i,tlv:[],frame:o};let a=hx+px;for(;a<r;){const n=e.getUint8(a),i=e.getUint16(a+_x),r=_x+Ex;if(n===mx.AUDIO_LEVEL){let o=e.getUint8(a+r);for(let t=1;t<i;t++)o=o<<8|e.getUint8(a+r+t);s.tlv.push({tag:n,length:i,value:t?127^o>>1:127&o})}else if(n===mx.METADATA||n===mx.AUDIO_64_BIT_PTS){const t=new Uint8Array(i);for(let n=0;n<i;n++)t[n]=e.getUint8(a+r+n);s.tlv.push({tag:n,length:i,value:t})}a+=r+i}return s}const gx=new Map;const Sx=127,Tx=1e-10,Rx=139/13,vx=new Map;function yx(e,t,n){const i="".concat(e,"-").concat(t,"-").concat(n);let r=0;if(vx.has(i))r=vx.get(i);else{const o=.5;r=Math.log(function(e,t){const n=e-t;t<n&&(t=n);let i=1;for(let n=e,r=1;n>t;n--,r++)i=i*n/r;return i}(t,e))+e*Math.log(o)+(t-e)*Math.log(1-o)-Math.log(n)+n*e,vx.set(i,r)}return r<Tx&&(r=Tx),r}function bx(e,t,n){const i=t.length,r=e.length/i;let o=!1;for(let s=0,a=0;s<i;s++){let i=0;for(let t=a+r;a<t;a++)e[a]>n&&i++;t[s]!==i&&(t[s]=i,o=!0)}return o}window.cache=vx;let Cx=0,Ix=class{constructor(e){uM(this,"id",void 0),uM(this,"immediates",[]),uM(this,"lastNonSilence",-1),uM(this,"immediateSpeechActivityScore",Tx),uM(this,"lastLevelChangedTime",Date.now()),uM(this,"levels",[]),uM(this,"longs",[]),uM(this,"longSpeechActivityScore",Tx),uM(this,"mediums",[]),uM(this,"mediumSpeechActivityScore",Tx),uM(this,"minLevel",0),uM(this,"nextMinLevel",0),uM(this,"nextMinLevelWindowLength",0),uM(this,"energyScore",0),this.id=e||"".concat(Cx++),this.immediates.length=50,this.mediums.length=10,this.longs.length=1,this.levels.length=this.immediates.length}computeImmediates(){const e=this.immediates,t=this.levels,n=this.minLevel+Rx;let i=!1;for(let r=0;r<e.length;++r){let o=t[r];o<n&&(o=0);const s=Math.floor(o/Rx);e[r]!==s&&(e[r]=s,i=!0)}return i}computeLongs(){return bx(this.mediums,this.longs,4)}computeMediums(){return bx(this.immediates,this.mediums,7)}evaluateImmediateSpeechActivityScore(){this.immediateSpeechActivityScore=yx(this.immediates[0],13,.78)}evaluateLongSpeechActivityScore(e){this.longSpeechActivityScore=yx(this.longs[0],10,47),this.longSpeechActivityScore>Tx&&(this.lastNonSilence=e)}evaluateMediumSpeechActivityScore(){this.mediumSpeechActivityScore=yx(this.mediums[0],5,24)}evaluateSpeechActivityScores(e){this.computeImmediates()&&(this.evaluateImmediateSpeechActivityScore(),this.computeMediums()&&(this.evaluateMediumSpeechActivityScore(),this.computeLongs()&&this.evaluateLongSpeechActivityScore(e)))}getLastLevelChangedTime(){return this.lastLevelChangedTime}getLevels(){var e;return"[".concat(Tr(e=[...this.levels]).call(e).join(),"]")}getSpeechActivityScore(e){switch(e){case 0:return this.immediateSpeechActivityScore;case 1:return this.mediumSpeechActivityScore;case 2:return this.longSpeechActivityScore;default:throw new Error("interval "+e)}}levelChanged(e,t){if(this.lastLevelChangedTime<=t){this.lastLevelChangedTime=t;let n=e;return e<0&&(n=0),e>Sx&&(n=Sx),this.levels.unshift(n),this.levels.length>this.immediates.length&&this.levels.pop(),this.updateMinLevel(n),n>=this.minLevel+Rx?n:n/2}return-1}levelTimedOut(){this.levelChanged(0,this.lastLevelChangedTime)}updateMinLevel(e){if(0!==e){if(0===this.minLevel||this.minLevel>e)return this.minLevel=e,this.nextMinLevel=0,void(this.nextMinLevelWindowLength=0);if(0===this.nextMinLevel)return this.nextMinLevel=e,void(this.nextMinLevelWindowLength=1);if(this.nextMinLevel>e&&(this.nextMinLevel=e),this.nextMinLevelWindowLength++,this.nextMinLevelWindowLength>=750){let e=Math.sqrt(this.minLevel*this.nextMinLevel);e<0?e=0:e>Sx&&(e=Sx),this.minLevel=e,this.nextMinLevel=0,this.nextMinLevelWindowLength=0}}}},Ax=class{constructor(e,t,n){uM(this,"isDominant",void 0),uM(this,"energyRanking",void 0),uM(this,"energyScore",void 0),this.isDominant=e,this.energyRanking=t,this.energyScore=n}},wx=class extends hD{constructor(e){super(),uM(this,"dominantId",null),uM(this,"lastDecisionTime",0),uM(this,"lastLevelChangedTime",0),uM(this,"lastLevelIdleTime",0),uM(this,"relativeSpeechActivities",[]),uM(this,"speakers",new Map),uM(this,"enableSilence",!1),uM(this,"timeoutToSilenceInterval",0),uM(this,"decisionMaker",null),uM(this,"loudest",[]),uM(this,"numLoudestToTrack",3),uM(this,"energyExpireTimeMs",250),uM(this,"energyAlphaPct",50),this.timeoutToSilenceInterval=e,this.enableSilence=e>0,this.relativeSpeechActivities.length=3}setLoudestConfig(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3,t=arguments.length>1?arguments[1]:void 0,n=arguments.length>2?arguments[2]:void 0;this.numLoudestToTrack=e,null!=t&&(this.energyExpireTimeMs=t),null!=n&&(this.energyAlphaPct=n),this.loudest.length>e&&this.loudest.splice(e)}getDominantSpeaker(){return this.dominantId}isAmongLoudest(e){return this.loudest.some((t=>t.id===e))}levelChanged(e,t){const n=Date.now(),i=this.getOrCreateSpeaker(e);this.lastLevelChangedTime<n&&(this.lastLevelChangedTime=n,this.maybeStartDecisionMaker());const r=i.levelChanged(t,n);return this.updateLoudestList(i,r,n)}runInDecisionMaker(e){return this.decisionMaker!==e||this.lastDecisionTime>0&&this.lastDecisionTime-this.lastLevelChangedTime>=15e3?-1:this._runInDecisionMaker()}decisionMakerExited(e){this.decisionMaker===e&&(this.decisionMaker=null)}destroy(){this.decisionMaker=null,this.loudest.length=0,this.speakers.clear(),this.removeAllListeners()}addSpeakers(e){e.forEach((e=>{this.speakers.has(e.id)||this.speakers.set(e.id,e)}))}removeSpeakers(e){e.forEach((e=>{this.speakers.delete(e.id)}))}getOrCreateSpeaker(e){let t=this.speakers.get(e);return t||(t=new Ix(e),this.speakers.set(e,t),this.maybeStartDecisionMaker()),t}updateLoudestList(e,t,n){const i=e.id===this.dominantId;if(t<0){let t=0;for(;t<this.loudest.length&&this.loudest[t]!==e;)++t;return new Ax(i,t,e.energyScore)}if(e.energyScore=Math.floor((this.energyAlphaPct*t+(100-this.energyAlphaPct)*e.energyScore+50)/100),0===this.numLoudestToTrack)return new Ax(i,0,e.energyScore);const r=n-this.energyExpireTimeMs;let o=0;for(;o<this.loudest.length;){const t=this.loudest[o];if(t.getLastLevelChangedTime()<r&&this.loudest.length>=this.numLoudestToTrack)this.loudest.splice(o,1);else if(t.id!==e.id)++o;else if(this.loudest.splice(o,1),this.loudest.length<this.numLoudestToTrack)break}let s=0;for(;s<this.loudest.length&&!(this.loudest[s].energyScore<e.energyScore);)++s;return s<this.numLoudestToTrack&&(this.loudest.splice(s,0,e),this.loudest.length>this.numLoudestToTrack&&this.loudest.splice(this.numLoudestToTrack,1)),new Ax(i,s,e.energyScore)}maybeStartDecisionMaker(){!this.decisionMaker&&this.speakers.size>0&&(this.decisionMaker=new class{constructor(e){uM(this,"algorithm",void 0),this.algorithm=e}execute(){let e=!this.algorithm;if(!e)try{const t=this.algorithm.runInDecisionMaker(this);t<=0?e=!0:setTimeout(this.execute.bind(this),t)}catch(t){e=!0}e&&this.algorithm&&this.algorithm.decisionMakerExited(this)}}(this),this.decisionMaker.execute())}makeDecision(e){let t=null,n=null;const i=this.speakers.size;let r=null;if(0===i)r=null;else if(1===i){var o;const t=gp(o=this.speakers).call(o).next().value;this.enableSilence&&t&&(r=t.id,t.evaluateSpeechActivityScores(e),e-t.lastNonSilence>this.timeoutToSilenceInterval&&(r=null))}else{let t=null==this.dominantId?null:this.speakers.get(this.dominantId);if(null==t){const e=this.speakers.entries().next();e.value&&(r=e.value[0],t=e.value[1])}else r=t.id;null!=t&&t.evaluateSpeechActivityScores(e);const n=this.relativeSpeechActivities;let i=2;for(const o of this.speakers.entries()){const s=_M(o,2),a=s[0],c=s[1];if(c===t)continue;c.evaluateSpeechActivityScores(e);for(let e=0;e<n.length;++e){const i=null==t?Tx:t.getSpeechActivityScore(e);n[e]=Math.log(c.getSpeechActivityScore(e)/i)}const d=n[0],l=n[1],u=n[2];d>3&&l>2&&u>0&&l>i&&(i=l,r=a)}this.enableSilence&&null!=t&&r===t.id&&e-t.lastNonSilence>this.timeoutToSilenceInterval&&(r=null)}null==r&&!this.enableSilence||r===this.dominantId||(t=this.dominantId,this.dominantId=r,n=this.dominantId),null==n&&!this.enableSilence||n===t||this.emit("ActiveSpeakerChanged",n)}_runInDecisionMaker(){const e=Date.now(),t=300-(e-this.lastLevelIdleTime);let n=0;t<=0?(0!==this.lastLevelIdleTime&&this.timeoutIdleLevels(e),this.lastLevelIdleTime=e):n=t;let i=300-(e-this.lastDecisionTime);return i<=0&&(this.lastDecisionTime=e,this.makeDecision(e),i=300-(Date.now()-e)),i>0&&n>i&&(n=i),n}timeoutIdleLevels(e){const t=[];for(const i of gp(n=this.speakers).call(n)){var n;const r=e-i.getLastLevelChangedTime();36e5<r&&(null==this.dominantId||i.id!==this.dominantId)?t.push(i.id):300<r&&i.levelTimedOut()}t.forEach((e=>this.speakers.delete(e)))}};const Ox=new Map;let Nx=null,Dx=null;const Px=3;let Lx=[];const kx=new Map,Mx=new Map;let Ux,Vx=class{get samples(){return this.actives+this.inactives}get activeRate(){return this.actives/this.samples}constructor(e,t){uM(this,"id",void 0),uM(this,"track",void 0),uM(this,"score",0),uM(this,"active",!0),uM(this,"muted",!1),uM(this,"timer",0),uM(this,"actives",0),uM(this,"inactives",0),this.id=e,this.track=t,this.setActive(kx.size<3)}autoCheckActive(){this.autoSetActive(),this.autoAdjustActive(),this.resetTimer(),this.actives=0,this.inactives=0}autoSetActive(){const e=this.active;this.active=this.activeRate>=.8;const t=function(){const e=[],t=[];return Array.from(gp(kx).call(kx)).forEach((n=>{n.active?e.push(n):t.push(n)})),{actives:e,inactives:t}}(),n=t.actives,i=t.inactives;if(n.length>3){let e;n.forEach((t=>{(!e||e.score>t.score)&&(e=t)})),e&&e.setActive(!1)}if(n.length<3&&i.length>0){let t;i.forEach((e=>{(!t||t.score<e.score)&&e.id!==this.id&&(t=e)})),t&&e&&!this.active&&(t.samples>40&&t.activeRate-this.activeRate>.4?t.setActive(!0):this.active=!0)}this.setMuted(!this.active)}setActive(e){this.active=e,this.resetTimer(),this.setMuted(!e)}autoAdjustActive(){this.active?this.autoSwitchToInactive():this.autoSwitchToActive()}autoSwitchToActive(){const e=function(e){let t;return Array.from(gp(kx).call(kx)).forEach((n=>{!n.active||n.id===e||n.samples<40||(!t||n.score<t.score)&&(t=n)})),t}(this.id);e&&this.activeRate-e.activeRate>.4&&(e.setActive(!1),this.setActive(!0))}autoSwitchToInactive(){const e=function(e){let t;return Array.from(gp(kx).call(kx)).forEach((n=>{n.active||n.id===e||n.samples<40||(!t||n.score>t.score)&&(t=n)})),t}(this.id);e&&e.activeRate-this.activeRate>.4&&(e.setActive(!0),this.setActive(!1))}addSample(e){e?this.actives+=1:this.inactives+=1,this.samples>66.66666666666667&&this.autoCheckActive()}setMuted(e){this.track&&(this.track.enabled=!e,this.muted=e)}resetTimer(){this.clearTimer(),this.timer=window.setTimeout((()=>{if(0!==this.samples)return this.samples<50?this.resetTimer():void this.autoCheckActive()}),1e3)}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=0)}};function xx(e){const t=kx.get(e);t&&(kx.delete(e),t.clearTimer())}const Fx=new Map,Bx=new Map;const jx="video/h264",Gx="video/h265";function Wx(e,t,n){let i=new Uint8Array(e,t,n),r=[],o=0;for(;r.length<n;)o+3<n&&0===i[o]&&0===i[o+1]&&3===i[o+2]&&(0===i[o+3]||1===i[o+3]||2===i[o+3]||3===i[o+3])?(r.push(i[o],i[o+1],i[o+3]),o+=4):(r.push(i[o]),o++);return new Uint8Array(r)}function Kx(e){const t=e.length;let n=[],i=0;for(;i<t;)i+2<t&&0===e[i]&&0===e[i+1]&&(0===e[i+2]||1===e[i+2]||2===e[i+2]||3===e[i+2])?(n.push(e[i],e[i+1],3,e[i+2]),i+=3):(n.push(e[i]),i++);return new Uint8Array(n)}function Hx(e){if(e.length<5)return"";let t=-1;for(let n=0;n<e.length-3;n++){if(0===e[n]&&0===e[n+1]&&1===e[n+2]){t=n;break}if(n<e.length-4&&0===e[n]&&0===e[n+1]&&0===e[n+2]&&1===e[n+3]){t=n;break}}if(-1===t)return"";const n=t+(0===e[t+2]?4:3);if(n>=e.length)return"";const i=e[n];return 128&i?"":(i>>1&63)>=32||n+1<e.length&&0==(248&e[n+1])?Gx:(31&i)<=31?jx:""}const Yx=new Map;const Xx=new Map;!function(){const e=dN();pk.getDisplayMedia=!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia),pk.getStreamFromExtension=e.name===oN.CHROME&&Number(e.version)>34,pk.supportUnifiedPlan=function(){if(!window.RTCRtpTransceiver)return!1;if(!("currentDirection"in RTCRtpTransceiver.prototype))return!1;const e=new RTCPeerConnection;let t=!1;try{e.addTransceiver("audio"),t=!0}catch(e){}return e.close(),t}(),pk.supportMinBitrate=e.name===oN.CHROME||e.name===oN.EDGE,pk.supportSetRtpSenderParameters=function(){const e=dN();return!!(window.RTCRtpSender&&window.RTCRtpSender.prototype.setParameters&&window.RTCRtpSender.prototype.getParameters)&&(!!FN()||!(!EN()&&!pN())||e.name===oN.FIREFOX&&Number(e.version)>=64)}(),e.name===oN.SAFARI&&(Number(e.version)>=14?pk.supportDualStream=!0:pk.supportDualStream=!1),pk.webAudioMediaStreamDest=function(){const e=dN();return!(e.name===oN.SAFARI&&Number(e.version)<12)}(),pk.supportReplaceTrack=!!window.RTCRtpSender&&"function"==typeof RTCRtpSender.prototype.replaceTrack,pk.supportWebGL="undefined"!=typeof WebGLRenderingContext,pk.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,FN()||(pk.webAudioWithAEC=!0),pk.supportShareAudio=function(){const e=dN();return(e.os===rN.WIN_10||e.os===rN.WIN_81||e.os===rN.WIN_7||e.os===rN.LINUX||e.os===rN.MAC_OS||e.os===rN.CHROMIUM_OS)&&e.name===oN.CHROME&&Number(e.version)>=74}(),pk.supportDataChannel=!!(RN(76)||CN(68)||IN(14)),pk.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!SN()&&!!e&&e.prototype.setConfiguration instanceof Function}(),pk.supportWebRTCEncodedTransform=RN(87)||mN()||CN(117),pk.supportWebRTCInsertableStream=function(){const e=dN();return(e.name===oN.CHROME||e.name===oN.EDGE)&&Number(e.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),pk.supportRequestVideoFrameCallback="requestVideoFrameCallback"in HTMLVideoElement.prototype,pk.supportWebCrypto="undefined"!=typeof window&&void 0!==window.crypto&&void 0!==window.crypto.subtle,pk.supportSuppressLocalAudioPlayback=yk(),pk.supportRestrictOwnAudio=bk(),jD((()=>{pk.supportDualStreamEncoding=function(){const e=dN();return!!rL("DISABLE_WEBAUDIO")||("Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&rL("CHROME_DUAL_STREAM_USE_ENCODING")))}(),FL.debug("browser ua: ",navigator.userAgent),FL.info("browser info: ",e),FL.info("browser compatibility: ",pk)}))}();const Jx=["CHINA","GLOBAL"];const zx=[[0,1,2,3,4,5,5],[0,2,2,3,4,5,5],[0,3,3,3,4,5,5],[0,4,4,4,4,5,5],[0,5,5,5,5,5,5]],Zx=[],qx=[];function Qx(e,t){return!!t&&Zx.some((n=>n.uid===e&&n.channelName===t))}function $x(){return qx.length>0}var eF=lR.forEach,tF=Xi("forEach")?[].forEach:function(e){return eF(this,e,arguments.length>1?arguments[1]:void 0)};Nn({target:"Array",proto:!0,forced:[].forEach!==tF},{forEach:tF});var nF=ii("Array","forEach"),iF=Si,rF=$e,oF=l,sF=nF,aF=Array.prototype,cF={DOMTokenList:!0,NodeList:!0},dF=function(e){var t=e.forEach;return e===aF||oF(aF,e)&&t===aF.forEach||rF(cF,iF(e))?sF:t},lF=n(dF),uF=Ze,hF=mo;Nn({target:"Object",stat:!0,forced:i((function(){hF(1)}))},{keys:function(e){return hF(uF(e))}});var pF=n($.Object.keys),_F=n(sr),EF=n(Sr);function mF(e,t,n,i,r){var o,s,a,c={};return lF(o=pF(i)).call(o,(function(e){c[e]=i[e]})),c.enumerable=!!c.enumerable,c.configurable=!!c.configurable,("value"in c||c.initializer)&&(c.writable=!0),c=_F(s=EF(a=jb(n).call(n)).call(a)).call(s,(function(n,i){return i(e,t,n)||n}),c),r&&void 0!==c.initializer&&(c.value=c.initializer?c.initializer.call(r):void 0,c.initializer=void 0),void 0===c.initializer?(VA(e,t,c),null):c}let fF=function(e){return e[e.ACCESS_POINT=101]="ACCESS_POINT",e[e.UNILBS=201]="UNILBS",e[e.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR",e}({}),gF=function(e){return e[e.IIIEGAL_APPID=1]="IIIEGAL_APPID",e[e.IIIEGAL_UID=2]="IIIEGAL_UID",e[e.INTERNAL_ERROR=3]="INTERNAL_ERROR",e}({}),SF=function(e){return e[e.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",e[e.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",e[e.INTERNAL_ERROR=8]="INTERNAL_ERROR",e[e.NO_AUTHORIZED=9]="NO_AUTHORIZED",e[e.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",e[e.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",e[e.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",e[e.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",e[e.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",e[e.USER_OVERLOAD=16]="USER_OVERLOAD",e[e.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",e[e.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND",e[e.REQ_DOWNGRADE_FALLBACK=27]="REQ_DOWNGRADE_FALLBACK",e}({}),TF=function(e){return e[e.NO_FLAG_SET=100]="NO_FLAG_SET",e[e.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",e[e.INVALID_FALG_SET=102]="INVALID_FALG_SET",e[e.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",e[e.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",e[e.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",e[e.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",e[e.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",e[e.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",e[e.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",e[e.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",e[e.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",e[e.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",e[e.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",e[e.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",e[e.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",e[e.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",e[e.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",e[e.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV",e}({}),RF=function(e){return e[e.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",e[e.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",e[e.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",e[e.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",e[e.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",e[e.K_TICKET_INVALID=7]="K_TICKET_INVALID",e[e.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",e[e.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",e[e.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",e[e.K_UID_BANNED=14]="K_UID_BANNED",e[e.K_IP_BANNED=15]="K_IP_BANNED",e[e.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",e[e.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",e[e.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",e[e.K_VOS_FALLBACK=30]="K_VOS_FALLBACK",e[e.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",e[e.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",e[e.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",e[e.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",e[e.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",e[e.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",e[e.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",e[e.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",e[e.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",e[e.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",e[e.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",e[e.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",e[e.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",e[e.ERR_INVALID_UID=117]="ERR_INVALID_UID",e[e.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",e[e.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",e[e.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",e[e.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",e[e.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",e[e.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",e[e.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",e[e.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",e[e.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",e[e.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",e[e.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",e[e.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",e[e.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",e[e.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",e[e.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",e[e.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",e[e.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",e[e.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",e[e.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",e[e.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",e[e.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",e[e.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",e[e.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",e[e.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",e[e.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",e[e.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",e[e.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",e[e.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",e[e.ERR_LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",e[e.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",e[e.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",e[e.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",e[e.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",e[e.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",e[e.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",e[e.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",e[e.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY",e}({}),vF=function(e){return e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed",e}({}),yF=function(e){return e.WS_CONNECTED="ws_connected",e.WS_RECONNECTING="ws_reconnecting",e.WS_CLOSED="ws_closed",e.WS_RECONNECT_CREATE_CONNECTION="ws_reconnect_create_connection",e.ON_BINARY_DATA="on_binary_data",e.REQUEST_RECOVER="request_recover",e.REQUEST_JOIN_INFO="request_join_info",e.REQUEST_JOIN_INFO_WITH_PRE_JOIN_RESPONSE="request_pre_join_response",e.REQUEST_REJOIN_INFO="req_rejoin_info",e.IS_P2P_DISCONNECTED="is_p2p_dis",e.DISCONNECT_P2P="dis_p2p",e.ABORT_P2P_EXECUTION="abort_p2p_execution",e.NEED_RENEW_SESSION="need-sid",e.REPORT_JOIN_GATEWAY="report_join_gateway",e.REQUEST_TIMEOUT="request_timeout",e.REQUEST_SUCCESS="request_success",e.JOIN_RESPONSE="join_response",e.PRE_CONNECT_PC="pre_connect_pc",e.DATACHANNEL_PRECONNECT="datachannel_preconnect",e.DATACHANNEL_CONNECTING="datachannel_connecting",e.DATACHANNEL_FAILBACK="datachannel_failback",e.P2P_CONNECTION="p2p_connection",e.P2P_REMOTE_CANDIDATE_UPDATE="p2p_remote_candidate_update",e.P2P_SUBSCRIBE="p2p_subscribe",e.P2P_UNSUBSCRIBE="p2p_unsubscribe",e.P2P_EXCHANGE_SDP="p2p_exchange_sdp",e.P2P_ON_ADD_VIDEO_STREAM="p2p_on_add_video_stream",e.P2P_ON_ADD_AUDIO_STREAM="p2p_on_add_audio_stream",e.RECOVER_NOTIFICATION="recover_notification",e.VOS_FALLBACK="vos_fallback",e.VOS_FALLBACK_PROMISE="vos_fallback_promise",e}({}),bF=function(e){return e.PING="ping",e.PING_BACK="ping_back",e.JOIN="join_v3",e.REJOIN="rejoin_v3",e.LEAVE="leave",e.SET_CLIENT_ROLE="set_client_role",e.PUBLISH="publish",e.PUBLISH_DATASTREAM="publish_datastream",e.UNPUBLISH="unpublish",e.UNPUBLISH_DATASTREAM="unpublish_datastream",e.SUBSCRIBE="subscribe",e.PRE_SUBSCRIBE="pre_subscribe",e.SUBSCRIBE_DATASTREAM="subscribe_datastream",e.SUBSCRIBE_STREAMS="subscribe_streams",e.UNSUBSCRIBE="unsubscribe",e.UNSUBSCRIBE_DATASTREAM="unsubscribe_datastream",e.UNSUBSCRIBE_STREAMS="unsubscribe_streams",e.SUBSCRIBE_CHANGE="subscribe_change",e.TRAFFIC_STATS="traffic_stats",e.RENEW_TOKEN="renew_token",e.SET_DUAL_STREAM_MODE="set_dual_stream_mode",e.SWITCH_VIDEO_STREAM="switch_video_stream",e.DEFAULT_VIDEO_STREAM="default_video_stream",e.SET_FALLBACK_OPTION="set_fallback_option",e.CONFIGURE="configure",e.GATEWAY_INFO="gateway_info",e.CONTROL="control",e.SEND_METADATA="send_metadata",e.DATA_STREAM="data_stream",e.PICK_SVC_LAYER="pick_svc_layer",e.RESTART_ICE="restart_ice",e.CONNECT_PC="connect_pc",e.SET_VIDEO_PROFILE="set_video_profile",e.SET_PARAMETER="set_parameter",e.SET_RTM2_FLAG="set_rtm2_flag",e.DOWNGRADE_CODEC="downgrade_codec",e}({}),CF=function(e){return e.WRTC_STATS="wrtc_stats",e.WS_INFLATE_DATA_LENGTH="ws_inflate_data_length",e.DENOISER_STATS="denoiser_stats",e.EXTENSION_USAGE_STATS="extension_usage_stats",e}({}),IF=function(e){return e.ON_USER_ONLINE="on_user_online",e.ON_USER_OFFLINE="on_user_offline",e.ON_STREAM_FALLBACK_UPDATE="on_stream_fallback_update",e.ON_PUBLISH_STREAM="on_publish_stream",e.ON_UPLINK_STATS="on_uplink_stats",e.ON_P2P_LOST="on_p2p_lost",e.ON_REMOVE_STREAM="on_remove_stream",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="on_token_privilege_will_expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="on_token_privilege_did_expire",e.ON_USER_BANNED="on_user_banned",e.ON_USER_LICENSE_BANNED="on_user_license_banned",e.ON_NOTIFICATION="on_notification",e.ON_CRYPT_ERROR="on_crypt_error",e.MUTE_AUDIO="mute_audio",e.MUTE_VIDEO="mute_video",e.UNMUTE_AUDIO="unmute_audio",e.UNMUTE_VIDEO="unmute_video",e.ON_P2P_OK="on_p2p_ok",e.RECEIVE_METADATA="receive_metadata",e.ON_DATA_STREAM="on_data_stream",e.ON_RTP_CAPABILITY_CHANGE="on_rtp_capability_change",e.ON_REMOTE_DATASTREAM_UPDATE="on_remote_datastream_update",e.ON_REMOTE_FULL_DATASTREAM_INFO="on_remote_full_datastream_info",e.ENABLE_LOCAL_VIDEO="enable_local_video",e.DISABLE_LOCAL_VIDEO="disable_local_video",e.ENABLE_LOCAL_AUDIO="enable_local_audio",e.DISABLE_LOCAL_AUDIO="disable_local_audio",e.ON_PUBLISHED_USER_LIST="on_published_user_list",e.ENABLE_MULTI_STREAM="enable_multi_stream",e.ON_USER_LIST="on_user_list",e}({}),AF=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({}),wF=function(e){return e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.CLOSED="websocket:closed",e.FAILED="websocket:failed",e.ON_MESSAGE="websocket:on_message",e.REQUEST_NEW_URLS="websocket:request_new_urls",e.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",e.ON_FALLBACK="websocket:on_fallback",e}({});function OF(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw FL.error("Invalid Channel Name ".concat(e)),new hk(JN.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _,  {, }, |, ~, ,")}function NF(e){if(!(t=e,"number"==typeof t&&Math.floor(t)===t&&0<=t&&t<=4294967295||iD(e,1,255)))throw new hk(JN.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");var t;"string"==typeof e&&FL.warn("You input a string as the user ID, to ensure better end-user experience, Agora highly suggests not using a string as the user ID.")}let DF=function(e){return e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e}({});const PF={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},LF={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function kF(e,t){eD(e.url,"".concat(t,".url"),1,1e3,!1),nD(e.x)||QN(e.x,"".concat(t,".x"),0,1e4),nD(e.y)||QN(e.y,"".concat(t,".y"),0,1e4),nD(e.width)||QN(e.width,"".concat(t,".width"),0,1e4),nD(e.height)||QN(e.height,"".concat(t,".height"),0,1e4),nD(e.zOrder)||QN(e.zOrder,"".concat(t,".zOrder"),0,255),nD(e.alpha)||QN(e.alpha,"".concat(t,".alpha"),0,1,!1)}const MF={audioBitrate:48,audioChannels:1,audioSampleRate:48e3,backgroundColor:0,height:360,lowLatency:!1,videoBitrate:400,videoCodecProfile:100,videoCodecType:1,videoFrameRate:15,videoGop:30,width:640,images:[],userConfigs:[],userConfigExtraInfo:""};let UF=function(e){return e.WARNING="@live_uap-warning",e.ERROR="@line_uap-error",e.PUBLISH_STREAM_STATUS="@live_uap-publish-status",e.WORKER_STATUS="@live_uap-worker-status",e.REQUEST_NEW_ADDRESS="@live_uap-request-address",e}({}),VF=function(e){return e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",e}({}),xF=function(e){return e[e.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",e[e.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",e[e.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",e[e.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",e[e.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",e[e.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",e[e.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",e[e.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",e[e.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",e[e.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",e[e.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",e[e.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",e[e.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",e[e.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",e[e.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",e[e.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN",e}({});function FF(e){if(!e.channelName)throw new hk(JN.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new hk(JN.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&eD(e.token,"info.token",1,2047),NF(e.uid),OF(e.channelName),!0}let BF=function(e){return e[e.SetSdkProfile=0]="SetSdkProfile",e[e.SetSourceChannel=1]="SetSourceChannel",e[e.SetSourceUserId=2]="SetSourceUserId",e[e.SetDestChannel=3]="SetDestChannel",e[e.StartPacketTransfer=4]="StartPacketTransfer",e[e.StopPacketTransfer=5]="StopPacketTransfer",e[e.UpdateDestChannel=6]="UpdateDestChannel",e[e.Reconnect=7]="Reconnect",e[e.SetVideoProfile=8]="SetVideoProfile",e}({}),jF=function(e){return e.NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",e.NETWORK_CONNECTED="NETWORK_CONNECTED",e.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",e.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",e.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",e.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",e.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",e.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",e.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",e.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE",e}({}),GF=function(e){return e.RELAY_STATE_IDLE="RELAY_STATE_IDLE",e.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",e.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",e.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE",e}({}),WF=function(e){return e.RELAY_OK="RELAY_OK",e.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",e.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",e.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED",e}({}),KF=function(e){return e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low",e}({}),HF=function(e){return e.DISCONNECT="disconnect",e.CONNECTION_STATE_CHANGE="connection-state-change",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGE="stream-type-change",e.IS_P2P_DISCONNECTED="is-p2p-dis",e.DISCONNECT_P2P="dis-p2p",e.REQUEST_NEW_GATEWAY_LIST="req-gate-url",e.NEED_RENEW_SESSION="need-sid",e.REQUEST_P2P_CONNECTION_PARAMS="request-p2p-connection-params",e.JOIN_RESPONSE="join-response",e.RESET_CONNECTION_EVENTS="reset-connection-events",e.PRE_CONNECT_PC="pre-connect_pc",e.UPDATE_GATEWAY_CONFIG="update-gateway-config",e.VOS_FALLBACK="vos-fallback",e.VOS_FALLBACK_PROMISE="vos-fallback-promise",e.RESET_SIGNAL="reset-signal",e.DATACHANNEL_FAILBACK="datachannel-failback",e}({}),YF=function(e){return e.P2P_DISCONNECTED="P2P_DISCONNECTED",e.A_ROUND_WS_FAILED="A_ROUND_WS_FAILED",e.TIMEOUT="TIMEOUT",e.UNKNOWN_REASON="UNKNOWN_REASON",e}({}),XF=function(e){return e[e.Nothing=0]="Nothing",e[e.Audio=1]="Audio",e[e.LowVideo=2]="LowVideo",e[e.Video=4]="Video",e[e.Data=8]="Data",e[e.DataStream0=256]="DataStream0",e[e.DataStream1=512]="DataStream1",e[e.DataStream2=1024]="DataStream2",e[e.DataStream3=2048]="DataStream3",e[e.DataStream4=4096]="DataStream4",e[e.DataStream5=8192]="DataStream5",e[e.DataStream6=16384]="DataStream6",e[e.DataStream7=32768]="DataStream7",e}({}),JF=function(e){return e.CHINA="CHINA",e.ASIA="ASIA",e.NORTH_AMERICA="NORTH_AMERICA",e.EUROPE="EUROPE",e.JAPAN="JAPAN",e.INDIA="INDIA",e.KOREA="KOREA",e.HKMC="HKMC",e.US="US",e.OCEANIA="OCEANIA",e.SOUTH_AMERICA="SOUTH_AMERICA",e.AFRICA="AFRICA",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="EXTENSIONS",e}({});const zF=[JF.AFRICA,JF.ASIA,JF.CHINA,JF.EUROPE,JF.GLOBAL,JF.INDIA,JF.JAPAN,JF.NORTH_AMERICA,JF.OCEANIA,JF.OVERSEA,JF.SOUTH_AMERICA];let ZF=function(e){return e.CHINA="CN",e.ASIA="AS",e.NORTH_AMERICA="NA",e.EUROPE="EU",e.JAPAN="JP",e.INDIA="IN",e.KOREA="KR",e.HKMC="HK",e.US="US",e.OCEANIA="OC",e.SOUTH_AMERICA="SA",e.AFRICA="AF",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="GLOBAL",e}({});const qF={CHINA:{},ASIA:{CODE:ZF.ASIA,WEBCS_DOMAIN:["ap-web-1-asia.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-asia.agora.io"],PROXY_CS:["proxy-ap-web-asia.agora.io"],CDS_AP:["cds-ap-web-asia.agora.io","cds-ap-web-asia2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-asia.agora.io","sua-ap-web-asia2.agora.io"],UAP_AP:["uap-ap-web-asia.agora.io","uap-ap-web-asia2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-asia.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-asia.agora.io"],LOG_UPLOAD_SERVER:["logservice-asia.agora.io"],PROXY_SERVER_TYPE3:["southeast-asia.webrtc-cloud-proxy.sd-rtn.com"]},NORTH_AMERICA:{CODE:ZF.NORTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-north-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-north-america.agora.io"],PROXY_CS:["proxy-ap-web-america.agora.io"],CDS_AP:["cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],UAP_AP:["uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-north-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-north-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-north-america.agora.io"],PROXY_SERVER_TYPE3:["east-usa.webrtc-cloud-proxy.sd-rtn.com"]},EUROPE:{CODE:ZF.EUROPE,WEBCS_DOMAIN:["ap-web-1-europe.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-europe.agora.io"],PROXY_CS:["proxy-ap-web-europe.agora.io"],CDS_AP:["cds-ap-web-europe.agora.io","cds-ap-web-europe2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-europe.agora.io","sua-ap-web-europe.agora.io"],UAP_AP:["uap-ap-web-europe.agora.io","uap-ap-web-europe2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-europe.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-europe.agora.io"],LOG_UPLOAD_SERVER:["logservice-europe.agora.io"],PROXY_SERVER_TYPE3:["europe.webrtc-cloud-proxy.sd-rtn.com"]},JAPAN:{CODE:ZF.JAPAN,WEBCS_DOMAIN:["ap-web-1-japan.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-japan.agora.io"],PROXY_CS:["proxy-ap-web-japan.agora.io"],CDS_AP:["cds-ap-web-japan.agora.io","cds-ap-web-japan2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-japan.agora.io","sua-ap-web-japan2.agora.io"],UAP_AP:["uap-ap-web-japan.agora.io","uap-ap-web-japan2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-japan.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-japan.agora.io"],LOG_UPLOAD_SERVER:["logservice-japan.agora.io"],PROXY_SERVER_TYPE3:["japan.webrtc-cloud-proxy.sd-rtn.com"]},INDIA:{CODE:ZF.INDIA,WEBCS_DOMAIN:["ap-web-1-india.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-india.agora.io"],PROXY_CS:["proxy-ap-web-india.agora.io"],CDS_AP:["cds-ap-web-india.agora.io","cds-ap-web-india2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-india.agora.io","sua-ap-web-india2.agora.io"],UAP_AP:["uap-ap-web-india.agora.io","uap-ap-web-india2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-india.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-india.agora.io"],LOG_UPLOAD_SERVER:["logservice-india.agora.io"],PROXY_SERVER_TYPE3:["india.webrtc-cloud-proxy.sd-rtn.com"]},KOREA:{CODE:ZF.KOREA,WEBCS_DOMAIN:["ap-web-1-korea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-korea.agora.io"],PROXY_CS:["proxy-ap-web-korea.agora.io"],CDS_AP:["cds-ap-web-korea.agora.io","cds-ap-web-korea2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-korea.agora.io","sua-ap-web-korea2.agora.io"],UAP_AP:["uap-ap-web-korea.agora.io","uap-ap-web-korea2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-korea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-korea.agora.io"],LOG_UPLOAD_SERVER:["logservice-korea.agora.io"],PROXY_SERVER_TYPE3:["korea.webrtc-cloud-proxy.sd-rtn.com"]},HKMC:{CODE:ZF.HKMC,WEBCS_DOMAIN:["ap-web-1-hkmc.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-hkmc.agora.io"],PROXY_CS:["proxy-ap-web-hkmc.agora.io"],CDS_AP:["cds-ap-web-hkmc.agora.io","cds-ap-web-hkmc2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-hkmc.agora.io","sua-ap-web-hkmc2.agora.io"],UAP_AP:["uap-ap-web-hkmc.agora.io","uap-ap-web-hkmc2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-hkmc.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-hkmc.agora.io"],LOG_UPLOAD_SERVER:["logservice-hkmc.agora.io"],PROXY_SERVER_TYPE3:["hkmc.webrtc-cloud-proxy.sd-rtn.com"]},US:{CODE:ZF.US,WEBCS_DOMAIN:["ap-web-1-us.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-us.agora.io"],PROXY_CS:["proxy-ap-web-us.agora.io"],CDS_AP:["cds-ap-web-us.agora.io","cds-ap-web-us2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-us.agora.io","sua-ap-web-us2.agora.io"],UAP_AP:["uap-ap-web-us.agora.io","uap-ap-web-us2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-us.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-us.agora.io"],LOG_UPLOAD_SERVER:["logservice-us.agora.io"],PROXY_SERVER_TYPE3:["us.webrtc-cloud-proxy.sd-rtn.com"]},OVERSEA:{CODE:ZF.OVERSEA,WEBCS_DOMAIN:["ap-web-1-oversea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oversea.agora.io"],PROXY_CS:["proxy-ap-web-oversea.agora.io"],CDS_AP:["cds-ap-web-oversea.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oversea.agora.io"],UAP_AP:["uap-ap-web-oversea.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oversea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oversea.agora.io"],LOG_UPLOAD_SERVER:["logservice-oversea.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.agora.io"]},GLOBAL:{CODE:ZF.GLOBAL,WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-ap-web-3.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-ap-web-3.agora.io"],UAP_AP:["uap-ap-web-1.agora.io","uap-ap-web-3.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2.agora.io"],LOG_UPLOAD_SERVER:["logservice.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com"]},OCEANIA:{CODE:ZF.OCEANIA,WEBCS_DOMAIN:["ap-web-1-oceania.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oceania.agora.io"],PROXY_CS:["proxy-ap-web-oceania.agora.io"],CDS_AP:["cds-ap-web-oceania.agora.io","cds-ap-web-oceania2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oceania.agora.io","sua-ap-web-oceania2.agora.io"],UAP_AP:["uap-ap-web-oceania.agora.io","uap-ap-web-oceania2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oceania.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oceania.agora.io"],LOG_UPLOAD_SERVER:["logservice-oceania.agora.io"],PROXY_SERVER_TYPE3:["oceania.webrtc-cloud-proxy.sd-rtn.com"]},SOUTH_AMERICA:{CODE:ZF.SOUTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-south-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-south-america.agora.io"],PROXY_CS:["proxy-ap-web-south-america.agora.io"],CDS_AP:["cds-ap-web-south-america.agora.io","cds-ap-web-south-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-south-america.agora.io","sua-ap-web-south-america2.agora.io"],UAP_AP:["uap-ap-web-south-america.agora.io","uap-ap-web-south-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-south-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-south-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-america.agora.io"],PROXY_SERVER_TYPE3:["south-america.webrtc-cloud-proxy.sd-rtn.com"]},AFRICA:{CODE:ZF.AFRICA,WEBCS_DOMAIN:["ap-web-1-africa.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-africa.agora.io"],PROXY_CS:["proxy-ap-web-africa.agora.io"],CDS_AP:["cds-ap-web-africa.agora.io","cds-ap-web-africa2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-africa.agora.io","sua-ap-web-africa2.agora.io"],UAP_AP:["uap-ap-web-africa.agora.io","uap-ap-web-africa2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-africa.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-africa.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-africa.agora.io"],PROXY_SERVER_TYPE3:["africa.webrtc-cloud-proxy.sd-rtn.com"]},EXTENSIONS:{}};zP&&(qF.CHINA={CODE:ZF.CHINA,WEBCS_DOMAIN:["webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["proxy-web.ap.sd-rtn.com"],CDS_AP:["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-web-2.ap.sd-rtn.com","uap-web-4.ap.sd-rtn.com"],EVENT_REPORT_DOMAIN:["web-3.statscollector.sd-rtn.com"],EVENT_REPORT_BACKUP_DOMAIN:["web-4.statscollector.sd-rtn.com"],LOG_UPLOAD_SERVER:["logservice-china.agora.io"],PROXY_SERVER_TYPE3:["east-cn.webrtc-cloud-proxy.sd-rtn.com"]});let QF=function(e){return e.UPDATE_BITRATE_LIMIT="update_bitrate_limit",e.UPDATE_CLIENT_ROLE_OPTIONS="update_client_role_options",e.UPDATE_REMOTE_VIDEO_STREAM_TYPE="update_remote_video_stream_type",e.FALLBACK_TO_HLS="fallback_to_hls",e.UPDATE_VOS_CONFIGURE="update_vos_configure",e}({});function $F(e){return!!e&&(!(!e.uplink||!e.id)&&(void 0!==e.uplink.max_bitrate&&void 0!==e.uplink.min_bitrate))}class eB extends hD{constructor(e,t){super(),GA(this,"onICEConnectionStateChange",void 0),GA(this,"onConnectionStateChange",void 0),GA(this,"onDTLSTransportStateChange",void 0),GA(this,"onDTLSTransportError",void 0),GA(this,"onICETransportStateChange",void 0),GA(this,"onFirstAudioReceived",void 0),GA(this,"onFirstVideoReceived",void 0),GA(this,"onFirstAudioDecoded",void 0),GA(this,"onFirstVideoDecoded",void 0),GA(this,"onFirstVideoRender",void 0),GA(this,"onFirstVideoBufferReady",void 0),GA(this,"onFirstVideoDecodedTimeout",void 0),GA(this,"onSelectedLocalCandidateChanged",void 0),GA(this,"onSelectedRemoteCandidateChanged",void 0),GA(this,"onICECandidateError",void 0),GA(this,"getLocalVideoStats",void 0)}}class tB extends eB{constructor(e,t){super(e,t),GA(this,"establishPromise",void 0)}}let nB=function(e){return e.VIDEO="video",e.AUDIO="audio",e}({}),iB=function(e){return e.UDP_RELAY="udp_relay",e.UDP_TCP_RELAY="udp_tcp_relay",e.TCP_RELAY="tcp_relay",e.RELAY="relay",e}({}),rB=function(e){return e[e.FIRST_CONNECTION=0]="FIRST_CONNECTION",e[e.UDP_TCP_RESTART=1]="UDP_TCP_RESTART",e[e.RELAY_RESTART=2]="RELAY_RESTART",e[e.TCP_RESTART=3]="TCP_RESTART",e[e.OLD_FIRST_CONNECTION=10]="OLD_FIRST_CONNECTION",e[e.OLD_RESTART=11]="OLD_RESTART",e[e.DISCONNECTED_OR_FAILED=20]="DISCONNECTED_OR_FAILED",e}({});const oB=["disconnected","failed"];let sB=function(e){return e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack",e}({}),aB=function(e){return e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected",e}({}),cB=function(e){return e.AudioMetadata="audioMetadata",e.AudioPts="audioPts",e.StateChange="stateChange",e.IceConnectionStateChange="iceConnectionStateChange",e.RequestMuteLocal="requestMuteLocal",e.RequestUnmuteLocal="requestUnmuteLocal",e.RequestRePublish="requestRePublish",e.RequestRePublishDataChannel="requestRePublishDataChannel",e.RequestReSubscribe="requestReSubscribe",e.RequestUploadStats="requestUploadStats",e.RequestUpload="requestUpload",e.MediaReconnectStart="MediaReconnectStart",e.MediaReconnectEnd="MediaReconnectEnd",e.NeedSignalRTT="NeedSignalRTT",e.RequestRestartICE="RequestRestartIce",e.PeerConnectionStateChange="PeerConnectionStateChange",e.RequestReconnect="RequestReconnect",e.RequestReconnectPC="RequestReconnectPC",e.RequestUnpublishForReconnectPC="RequestUnpublishForReconnectPC",e.P2PLost="P2PLost",e.UpdateVideoEncoder="UpdateVideoEncoder",e.ConnectionTypeChange="ConnectionTypeChange",e.RequestLowStreamParameter="RequestLowStreamParameter",e.QueryClientConnectionState="QueryClientConnectionState",e.LocalCandidate="LocalCandidate",e.RequestP2PMuteLocal="requestP2PMuteLocal",e.RequestP2PUnPublish="RequestP2PUnPublish",e.RequestP2PUnmuteRemote="RequestP2PUnmuteRemote",e.RequestP2PMuteRemote="RequestP2PMuteRemote",e.RequestP2PRestartICE="RequestP2PRestartICE",e.FirstVideoPreRender="FirstVideoPreRender",e.FirstVideoBufferReady="FirstVideoBufferReady",e}({}),dB=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),lB=function(e){return e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED",e}({}),uB=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}),hB=function(e){return e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK",e}({}),pB=function(e){return e.CONNECTED="transmitter:connected",e.RECONNECTING="transmitter:reconnecting",e.WILL_RECONNECT="transmitter:will_reconnect",e.CLOSED="transmitter:closed",e.FAILED="transmitter:failed",e.ON_MESSAGE="transmitter:on_message",e.REQUEST_NEW_URLS="transmitter:request_new_urls",e.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",e.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",e.FAILBACK="transmitter:failback",e.PRE_CONNECT_PC="transmitter:pre_connect_pc",e}({}),_B=function(e){return e.CAMERA_CHANGED="camera-changed",e.MICROPHONE_CHANGED="microphone-changed",e.PLAYBACK_DEVICE_CHANGED="playback-device-changed",e.AUDIO_AUTOPLAY_FAILED="audio-autoplay-failed",e.AUTOPLAY_FAILED="autoplay-failed",e.AUDIO_CONTEXT_STATE_CHANGED="audio-context-state-changed",e.SECURITY_POLICY_VIOLATION="security-policy-violation",e}({}),EB=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),mB=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}),fB=function(e){return e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED",e}({}),gB=function(e){return e.CALL="call",e.CANDIDATE="candidate",e.PUBLISH="publish",e.UNPUBLISH="unpublish",e.CONTROL="control",e.RESTART_ICE="restart_ice",e.ACK="ack",e.RESPONSE="response",e.JOIN="join",e.CHECK="check",e}({}),SB=function(e){return e.ABORT="abort",e}({}),TB=function(e){return e.MUTE_LOCAL_AUDIO="mute_local_audio",e.MUTE_LOCAL_VIDEO="mute_local_video",e.UNMUTE_LOCAL_AUDIO="unmute_local_audio",e.UNMUTE_LOCAL_VIDEO="unmute_local_video",e}({}),RB=function(e){return e.P2P_TOKEN_TIMEOUT="p2p_token_timeout",e.P2P_TOKEN_CHANGED="p2p_token_changed",e}({});const vB={[fF.ACCESS_POINT]:{[TF.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[TF.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[TF.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[TF.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[TF.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[TF.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[TF.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[TF.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[TF.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[TF.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[TF.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[TF.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[TF.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[TF.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[TF.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[TF.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[TF.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[TF.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[fF.UNILBS]:{[SF.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[SF.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[SF.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[SF.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[SF.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[SF.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[SF.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[SF.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[SF.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[SF.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[SF.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[SF.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1},[SF.REQ_DOWNGRADE_FALLBACK]:{desc:"request downgrade fallback",retry:!1}},[fF.STRING_UID_ALLOCATOR]:{[gF.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[gF.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[gF.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function yB(e){const t=vB[Math.floor(e/1e4)];if(!t)return{desc:"unknown error",retry:!1};const n=t[e%1e4];if(!n){if(Math.floor(e/1e4)===fF.ACCESS_POINT){const t=e%1e4;if("1"===t.toString()[0])return{desc:e.toString(),retry:!1};if("2"===t.toString()[0])return{desc:e.toString(),retry:!0}}return{desc:"unknown error",retry:!1}}return n}const bB={[RF.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[RF.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[RF.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[RF.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[RF.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[RF.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[RF.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[RF.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[RF.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[RF.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[RF.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[RF.DATASTREAM2_NOT_AVAILABLE]:{desc:"DATASTREAM2_NOT_AVAILABLE",action:"quit"},[RF.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[RF.K_VOS_FALLBACK]:{desc:"K_VOS_FALLBACK",action:"tryNext"},[RF.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[RF.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[RF.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[RF.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[RF.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[RF.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[RF.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[RF.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[RF.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[RF.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[RF.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[RF.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[RF.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[RF.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[RF.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[RF.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[RF.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[RF.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[RF.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[RF.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[RF.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[RF.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[RF.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[RF.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[RF.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[RF.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[RF.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[RF.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[RF.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[RF.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[RF.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[RF.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[RF.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[RF.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[RF.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[RF.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[RF.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[RF.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[RF.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[RF.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[RF.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[RF.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[RF.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[RF.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[RF.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[RF.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[RF.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[RF.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[RF.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[RF.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[RF.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function CB(e){const t=bB[e];return t||{desc:"UNKNOWN_ERROR_".concat(e),action:"failed"}}function IB(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function AB(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?IB(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):IB(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function wB(e,t){if("string"==typeof e)return e;const n=e.proxy,i=e.host,r=e.port;if(t){const e=rL("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===e?"wss://".concat(i,"/ws/?p=").concat(Number(r)+150):"wss://".concat(i,":").concat(e,"/ws/?p=").concat(Number(r)+150)}return n?"wss://".concat(n,"/ws/?h=").concat(i,"&p=").concat(r):"wss://".concat(i,":").concat(r)}const OB=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,NB=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,DB=/wss:\/\/(.+):([0-9]+)\/?/,PB=/wss:\/\/(.[^\/]+)\/?/;let LB=0;class kB{constructor(e,t){GA(this,"id",0),GA(this,"store",void 0),GA(this,"recordIndex",void 0),GA(this,"websockets",[]),GA(this,"try443PortDuration",2e3),GA(this,"forceCloseWSDuration",5e3),GA(this,"try443PortTimeout",null),GA(this,"forceCloseTimeout",null),GA(this,"isTry443PortFailed",!1),GA(this,"isNormalPortFailed",!1),GA(this,"useDoubleDomain",!1),GA(this,"useProxy",!1),GA(this,"startTime",Date.now()),this.id=++LB,this.try443PortDuration=rL("JOIN_GATEWAY_TRY_443PORT_DURATION")||2e3,this.forceCloseWSDuration=e||5e3,this.store=t}closeAllWebsockets(){this.websockets.forEach((e=>{e.onopen=null,e.onclose=null,e.onmessage=null,e.close()})),this.websockets.length=0}clearTimeout(){this.forceCloseTimeout&&clearTimeout(this.forceCloseTimeout),this.try443PortTimeout&&clearTimeout(this.try443PortTimeout),this.forceCloseTimeout=null,this.try443PortTimeout=null}logger(){var e;const t=Date.now()-this.startTime;for(var n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];FL.debug("[choose-best-ws ".concat(null===(e=this.store)||void 0===e?void 0:e.clientId," ").concat(this.id,"] ").concat(t,"ms:"),...i)}createWebSocket(e,t,n){this.logger("createWebSocket:",e,{isTry443Port:t,hasTimeoutDetection:n});const i=rL("GATEWAY_DOMAINS"),r=Date.now(),o=[],s=i.find((t=>{var n;return Vi(n=e.host).call(n,t)}));s||(this.useDoubleDomain=!1);const a=[];if(this.useDoubleDomain)i.forEach((n=>{a.push(wB(AB(AB({},e),{},{host:e.host.replace(s,n)}),t))}));else{const n=AB({},e);if(t&&s){const e=i.find((e=>e!==s));e&&(n.host=n.host.replace(s,e))}a.push(wB(n,t))}try{a.forEach((e=>{const t=new WebSocket(e);t.binaryType="arraybuffer",o.push(t),this.logger("ws is connecting:",t.url)}))}catch(i){if(this.logger("ws create failed"),o.forEach((e=>e.close())),o.length=0,this.useDoubleDomain)return this.useDoubleDomain=!1,this.createWebSocket(e,t,n);if(!t&&443!==Number(e.port))return this.createWebSocket(e,!0,n);throw new hk(JN.WS_ERR,"init websocket failed! Error: ".concat(i.toString()))}const c=eN();this.store&&this.store.recordJoinChannelService({urls:o.map((e=>e.url)),service:"gateway"},this.recordIndex),o.forEach((e=>{e.onopen=()=>{this.logger("onopen: ws ".concat(e.url," open cost ").concat(Date.now()-r,"ms")),this.websockets.forEach((t=>{t!==e&&(t.onopen=null,t.onclose=null,t.onmessage=null,t.close(),this.logger("close backup websocket: ".concat(t.url)))})),this.websockets.length=0,c.resolve(e)},e.onclose=n=>{this.logger("onclose: ws ".concat(e.url," closed cost ").concat(Date.now()-r,"ms state: ").concat(e.readyState));const i=o.every((e=>e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING));this.logger("".concat(t?"443":"47xx"," websocket closed, all failed: ").concat(i)),i&&(t||this.isTry443PortFailed||this.useProxy)?(this.logger("onclose: all websocket is closed, ".concat(n.reason)),c.reject({code:n.code,reason:YF.A_ROUND_WS_FAILED})):!t&&i&&!this.isNormalPortFailed&&this.try443PortTimeout&&(this.logger("all 47xx websocket is closed, try 443 port"),this.clearTimeout(),l()),t?this.isTry443PortFailed=i:this.isNormalPortFailed=i},e.onmessage=t=>this.logger("".concat(e.url," onmessage: ").concat(t.data))})),this.websockets.push(...o);const d=()=>{this.websockets.forEach((e=>e.readyState!==WebSocket.OPEN&&e.close()))},l=()=>{if(c.isResolved)return d();dN().os===rN.MAC_OS&&SN()&&d(),this.createWebSocket(e,!0,!0).then((e=>{c.resolve(e)})).catch((e=>{this.isNormalPortFailed&&c.reject(e),this.logger("try 443 port to create ws failed")})),this.forceCloseTimeout=window.setTimeout((()=>{this.logger("5s timeout close un-opens, isWebsocket created: ",c.isResolved),this.forceCloseTimeout=null,d()}),this.forceCloseWSDuration)};return n||(()=>{if(t||this.useProxy)return this.logger("add 5s timeout at ".concat(t?"try-443":"proxy"," condition")),this.forceCloseTimeout=window.setTimeout((()=>{this.forceCloseTimeout=null,d()}),this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout((()=>{this.logger("2s timeout, isWebsocket created: ",c.isResolved),this.try443PortTimeout=null,l()}),this.try443PortDuration)})(),c.promise}chooseBestWebsocket(e,t,n,i){return this.useDoubleDomain=!!t,"string"==typeof e&&(e=function(e){let t,n,i;var r=Hb(e.match(OB)||[],4);if(t=r[1],n=r[2],i=r[3],!t){var o=Hb(e.match(NB)||[],3);n=o[1],i=o[2]}if(!n||!i){var s=Hb(e.match(DB)||[],3);n=s[1],i=s[2]}return n&&i||(n=Hb(e.match(PB)||[],2)[1]),n||FL.warning("un-destructible url: ",e),{proxy:t,host:n,port:i||"443"}}(e)),this.recordIndex=i,this.useProxy=!!e.proxy,n&&this.useProxy&&(FL.warn("cannot use 443 only when use proxy"),n=!1),this.createWebSocket(e,!!n,!1).finally((()=>this.clearTimeout()))}}function MB(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}class UB extends hD{get url(){return this.websocket&&this.websocket.url||this._websocketUrl}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;Vi(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(wF.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(wF.CONNECTED):"closed"===this._state?this.emit(wF.CLOSED):"failed"===this._state&&this.emit(wF.FAILED))}resetReconnectCount(e){FL.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=arguments.length>5?arguments[5]:void 0;super(),GA(this,"_websocketUrl",null),GA(this,"connectionID",0),GA(this,"currentURLIndex",0),GA(this,"urls",[]),GA(this,"_reconnectMode","tryNext"),GA(this,"reconnectReason",void 0),GA(this,"_initMutex",void 0),GA(this,"name",void 0),GA(this,"_state","closed"),GA(this,"reconnectInterrupter",void 0),GA(this,"websocket",void 0),GA(this,"retryConfig",void 0),GA(this,"reconnectCount",0),GA(this,"forceCloseTimeout",5e3),GA(this,"onlineReconnectListener",void 0),GA(this,"useCompress",void 0),GA(this,"tryDoubleDomain",!1),GA(this,"use443PortOnly",!1),GA(this,"wsInflateLength",0),GA(this,"wsDeflateLength",0),GA(this,"closeEstablishingWs",(()=>{})),GA(this,"store",void 0),GA(this,"joinGatewayRecordIndex",void 0),this.store=o,this.name=e,this.retryConfig=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?MB(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):MB(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},t),this.useCompress=n,this.tryDoubleDomain=i,this.use443PortOnly=r,this._initMutex=new _P("websocket",o?o.clientId:void 0);const s=t.timeout,a=t.timeoutFactor,c=Math.max(300,Math.floor(3*s/5)),d=Math.max(1.2,Math.floor(8*a)/10);AD.ONLINE&&(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d),LD.on(wD.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===AD.ONLINE?(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d):(this.retryConfig.timeout=s,this.retryConfig.timeoutFactor=a))}))}getConnection(){return this.websocket||void 0}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=await this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{var i;const e=eN(),t=this.urls[this.currentURLIndex];null===(i=this.store)||void 0===i||i.beforeConnect(),(function(e){return!(mk()||rL("USE_NEW_TOKEN")||!rL("ENABLE_PREALLOC_PC")&&(null==e||!e.autoSubscribe||rL("FORCE_DISABLE_AUTO_SUB")))}(this.store)||rL("ENABLE_JOIN_V4"))&&this.emit(pB.PRE_CONNECT_PC),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(wF.CLOSED,(()=>{e.reject(new zN(JN.WS_DISCONNECT))})),this.once(wF.CONNECTED,e.resolve),await e.promise}catch(e){}finally{n()}}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this.reconnectInterrupter&&this.reconnectInterrupter(),this.websocket){this.websocket.onclose=null,this.websocket.onopen=null,this.websocket.onmessage=null;const e=this.websocket;t?setTimeout((()=>e.close()),500):e.close(),this.websocket=void 0,this._websocketUrl=null}this.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){if(!this.websocket)return void FL.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),FL.debug("[".concat(this.name,"] reconnect is triggered initiative")),"number"==typeof this.joinGatewayRecordIndex&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[new Error(t)]},this.joinGatewayRecordIndex);const n=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),n&&n.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new zN(JN.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new zN(JN.WS_ERR,"send websocket message error"+e.toString())}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength}getWsInflateData(){const e=this.wsInflateLength,t=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:e,wsDeflateLength:t}}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0}async createWebSocketConnection(e){var t;const n=eN();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const i=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),FL.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),n.resolve()},r=async e=>{var t;if(FL.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)n.reject(new zN(JN.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=DD(this,wF.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,i=await this.reconnectWithAction(t);if("closed"===this.state)return void FL.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!i)return n.reject(new zN(JN.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},o=e=>{this.emit(wF.ON_MESSAGE,e)},s=e=>{FL.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),rL("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=rL("GATEWAY_WSS_ADDRESS")),FL.debug("[".concat(this.name,"] start connect, url:"),e);const a=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var c;this._websocketUrl=wB(e);const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,i&&i(this.websocket.url),this.websocket.onclose=r,this.websocket.onmessage=o,this.websocket.onerror=s,null===(c=this.store)||void 0===c||c.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this.joinGatewayRecordIndex=a}catch(e){const t="closed"===this.state,i=e instanceof zN,o=i&&e.code===JN.WS_ABORT,s=i&&e.code===JN.WS_ERR,c=i?e.message:e&&(e.reason||e.toString());FL.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(c)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:o?"aborted":"error",errors:[e]},a),t||s?(n.reject(t?new zN(JN.WS_DISCONNECT,"websocket is closed: ".concat(c)):new zN(JN.WS_ERR,"init websocket failed: ".concat(c))),s&&FL.error("[".concat(this.name,"] init websocket failed: ").concat(c))):r&&r(e)}return n.promise}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount)return!1;if(0===this.urls.length)return!1;if("closed"===this.state)return!1;FL.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||LD.isOnline||!LD.onlineWaiter||(this.onlineReconnectListener=LD.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let n=!0;if(this.reconnectInterrupter=()=>n=!1,t){const t=fP(this.reconnectCount,this.retryConfig);FL.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await dp.race([$D(t),this.onlineReconnectListener||new dp((()=>{}))])}if("closed"===this._state||!n)return!1;this.reconnectCount+=1;const i=async(e,t)=>{this.emit(wF.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)await i(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);FL.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),await i(this.urls[this.currentURLIndex],e)}else"recover"===e&&(FL.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await OD(this,wF.REQUEST_NEW_URLS),this.currentURLIndex=0,await i(this.urls[this.currentURLIndex],e))}catch(n){var r;FL.error("[".concat(this.name,"] reconnect failed ").concat(n&&n.toString()));const i=null==n||null===(r=n.data)||void 0===r?void 0:r.desc;if(Array.isArray(i)){if(Vi(i).call(i,"dynamic key expired"))return this.emit(wF.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1;if(Vi(i).call(i,"request downgrade fallback"))return this.emit(wF.ON_FALLBACK),!1}return this.reconnectWithAction(e,t)}return!0}}class VB extends UB{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,t){const n=eN(),i=function(e,t){return new kB(e,t)}(this.forceCloseTimeout,this.store);this.closeEstablishingWs=()=>{FL.debug("[choose-best-ws] close establishing websockets"),i.closeAllWebsockets(),n.reject(new zN(JN.WS_ABORT,"choose best websocket aborted"))};const r=rL("GATEWAY_DOMAINS");return FL.debug("[choose-best-ws] currentDomain: ",e,", domains: ",r,"total: ".concat(this.urls.length),"current: ".concat(this.currentURLIndex+1)),i.chooseBestWebsocket(e,this.tryDoubleDomain,this.use443PortOnly,t).then(n.resolve).catch(n.reject),n.promise.finally((()=>{this.closeEstablishingWs=void 0}))}}class xB extends UB{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,t){return new dp(((n,i)=>{let r=!1;const o=[];this.closeEstablishingWs=()=>{FL.debug("[choose-best-ws] close establishing websockets"),o.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),i(new zN(JN.WS_ABORT,"choose best websocket aborted"))};const s=rL("GATEWAY_DOMAINS");let a;const c=e.indexOf("?h="),d=s.find((t=>-1!==c?Vi(e).call(e,t,c):Vi(e).call(e,t)));FL.debug("[choose-best-ws] currentDomain: ",d,", domains: ",s);let l=!this.tryDoubleDomain||!d;if(!l&&d){var u;const h=Date.now();try{s.forEach((t=>{const n=-1===c?e.replace(d,t):e.substr(0,c)+e.substr(c).replace(d,t),i=new WebSocket(n);i.binaryType="arraybuffer",o.push(i),FL.debug("[choose-best-ws] ws is connecting:",i.url)}))}catch(e){for(FL.debug("[choose-best-ws] ws create failed, fallback to single url"),o.forEach((e=>e.close()));o.length;)o.pop();l=!0}null===(u=this.store)||void 0===u||u.recordJoinChannelService({urls:o.map((e=>e.url)),service:"gateway"},t),o.forEach((e=>{e.onopen=()=>{if(r)return;const t=Date.now()-h;FL.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),o.filter((t=>t!==e)).forEach((e=>{FL.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),r=!0,n(e)},e.onclose=e=>{if(a=e,r)return;o.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(FL.debug("[choose-best-ws] all websocket is closed"),r=!0,i(a))},e.onmessage=t=>{FL.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),$D(this.forceCloseTimeout).then((()=>{o.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(l){var h;let r;FL.debug("[choose-best-ws] use single url: ",e),null===(h=this.store)||void 0===h||h.recordJoinChannelService({urls:[e],service:"gateway"},t);try{r=new WebSocket(e),o.push(r),r.binaryType="arraybuffer"}catch(e){const t=new zN(JN.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return FL.error("[".concat(this.name,"]").concat(t)),void i(t)}r.onopen=()=>{n(r)},r.onclose=e=>{i(e)},r.onmessage=e=>{FL.debug("[choose-best-ws]".concat(r.url," onmessage: ").concat(e.data))},$D(this.forceCloseTimeout).then((()=>{r&&r.readyState!==WebSocket.OPEN&&r.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}class FB extends hD{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===vF.CONNECTED?this.emit(yF.WS_CONNECTED):e===vF.RECONNECTING?this.emit(yF.WS_RECONNECTING,this._websocketReconnectReason):e===vF.CLOSED&&this.emit(yF.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),GA(this,"__name__","AgoraRTCSignal"),GA(this,"_disconnectedReason",void 0),GA(this,"_websocketReconnectReason",void 0),GA(this,"_connectionState",vF.CLOSED),GA(this,"reconnectToken",void 0),GA(this,"websocket",void 0),GA(this,"openConnectionTime",void 0),GA(this,"clientId",void 0),GA(this,"lastMsgTime",Date.now()),GA(this,"uploadCache",[]),GA(this,"uploadCacheInterval",void 0),GA(this,"rttRolling",new TP(5)),GA(this,"pingpongTimer",void 0),GA(this,"wsInflateDataTimer",void 0),GA(this,"pingpongTimeoutCount",0),GA(this,"ortc",void 0),GA(this,"joinResponse",void 0),GA(this,"multiIpOption",void 0),GA(this,"initError",void 0),GA(this,"spec",void 0),GA(this,"store",void 0),GA(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(yF.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")){if(this.emit(t._type,t._message),t._type===IF.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===IF.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(SD.UID_BANNED);break;case 15:this.close(SD.IP_BANNED);break;case 16:this.close(SD.CHANNEL_BANNED)}if(t._type===IF.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case RF.ERR_LICENSE_MISSING:this.close(SD.LICENSE_MISSING);break;case RF.ERR_LICENSE_EXPIRED:this.close(SD.LICENSE_EXPIRED);break;case RF.ERR_LICENSE_MINUTES_EXCEEDED:this.close(SD.LICENSE_MINUTES_EXCEEDED);break;case RF.ERR_LICENSE_PERIOD_INVALID:this.close(SD.LICENSE_PERIOD_INVALID);break;case RF.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(SD.LICENSE_MULTIPLE_SDK_SERVICE);break;case RF.ERR_LICENSE_ILLEGAL:this.close(SD.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new VB("gateway-".concat(this.clientId),this.spec.retryConfig,!0,rL("JOIN_GATEWAY_USE_DUAL_DOMAIN"),rL("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===vF.CONNECTED&&this.reconnect("retry",ID.OFFLINE)}))}async request(e,t,n,i){const r=eP(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new dp(((t,n)=>{if(this.connectionState===vF.CONNECTED)return t();const i=()=>{this.off(yF.WS_CLOSED,r),t()},r=()=>{this.off(yF.WS_CONNECTED,i),n(new hk(JN.WS_ABORT))};this.once(yF.WS_CONNECTED,i),this.once(yF.WS_CLOSED,r),e!==bF.PUBLISH&&e!==bF.PUBLISH_DATASTREAM&&e!==bF.SUBSCRIBE&&e!==bF.SUBSCRIBE_DATASTREAM&&e!==bF.UNSUBSCRIBE&&e!==bF.UNSUBSCRIBE_DATASTREAM&&e!==bF.UNPUBLISH&&e!==bF.UNPUBLISH_DATASTREAM&&e!==bF.CONTROL&&e!==bF.RESTART_ICE||this.once(yF.DISCONNECT_P2P,(()=>{n(new hk(JN.DISCONNECT_P2P))})),e!==bF.PUBLISH&&e!==bF.RESTART_ICE||this.once(yF.ABORT_P2P_EXECUTION,(()=>{n(new hk(JN.DISCONNECT_P2P))}))}));if(this.connectionState!==vF.CONNECTING&&this.connectionState!==vF.RECONNECTING||e===bF.JOIN||e===bF.REJOIN||await a(),this.websocket.sendMessage(o,!0),i)return;const c=new dp(((n,i)=>{let o=!1;const a=(i,r)=>{o=!0,n({isSuccess:"success"===i,message:r||{}}),this.off(yF.WS_CLOSED,c),this.off(yF.WS_RECONNECTING,c),this.emit(yF.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{i(new hk(JN.WS_ABORT,"type: ".concat(e))),this.off(yF.WS_CLOSED,c),this.off(yF.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(yF.WS_CLOSED,c),this.once(yF.WS_RECONNECTING,c),$D(rL("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(FL.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(yF.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(i){if(this.connectionState===vF.CLOSED||e===bF.LEAVE)throw new hk(JN.WS_ABORT);return!this.spec.forceWaitGatewayResponse||n?i.throw():e===bF.JOIN||e===bF.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=CB(l),h=new hk(JN.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:u.desc});return"success"===u.action?d.message:(FL.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===RF.ERR_TOO_MANY_BROADCASTERS?e===bF.JOIN||e===bF.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===RF.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,FL.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",ID.MULTI_IP)):this.reconnect(u.action,ID.SERVER_ERROR),e===bF.JOIN||e===bF.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new dp((n=>{const i=r=>{(!t||t(r))&&(this.off(e,i),n(r))};this.on(e,i)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void FL.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(CF.WRTC_STATS,t)}upload(e,t){const n={_type:e,_message:t};try{this.websocket.sendMessage(n)}catch(e){const t=rL("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(n),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==vF.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),rL("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const n={_type:e,_message:t};this.websocket.sendMessage(n)}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new dp(((t,n)=>{this.once(yF.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(yF.WS_CLOSED,(e=>n(this.initError||new hk(JN.WS_ABORT,e)))),this.connectionState=vF.CONNECTING,this.websocket.init(e).catch(n),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval((()=>{this.handleWsInflateData()}),2e4)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.wsInflateDataTimer&&(this.handleWsInflateData(),window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||SD.LEAVE,this.connectionState=vF.CLOSED,FL.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close()}async join(){if(!this.joinResponse){this.emit(yF.ABORT_P2P_EXECUTION),this.store.signalConnected();const e=await OD(this,yF.REQUEST_JOIN_INFO);this.store.joinReq();let t=await OD(this,yF.REQUEST_JOIN_INFO_WITH_PRE_JOIN_RESPONSE);if(t){FL.debug("join response from pre join response");const n=await this.request(bF.JOIN,e);n&&"ortc"in n&&(t=n)}else FL.debug("join response from request join_v3"),t=await this.request(bF.JOIN,e);if(this.ortc=null==e?void 0:e.ortc,this.store.joinRep(),!t)return this.emit(yF.REPORT_JOIN_GATEWAY,YF.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(yF.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=vF.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new hk(JN.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=PD(this,yF.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(bF.REJOIN,e);return!!t&&(this.connectionState=vF.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach((e=>{this.emit(IF.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(IF.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(IF.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(IF.MUTE_AUDIO,{uid:e.uid}):this.emit(IF.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(IF.MUTE_VIDEO,{uid:e.uid}):this.emit(IF.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(IF.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(IF.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(IF.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(IF.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(IF.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})})),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}async downgradeCodec(e){if(!this.ortc)return!1;const t={downgrade_codec:e,ortc:this.ortc};return!!await this.request(bF.DOWNGRADE_CODEC,t)}handleNotification(e){FL.debug("[".concat(this.clientId,"] receive notification: "),e);const t=CB(e.code);if(28===e.code&&"detail"in e&&(FL.info("[".concat(this.clientId,"] receive recover notification: "),e.detail),this.emit(yF.RECOVER_NOTIFICATION,e.detail)),"success"!==t.action){if("failed"!==t.action)return"quit"===t.action?e.code===RF.ERR_REPEAT_JOIN_CHANNEL&&rL("IGNORE_UID_CHECK")?void this.close(SD.UID_CONFLICT):("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(SD.UID_BANNED),void this.close()):e.code===RF.K_VOS_FALLBACK&&"detail"in e?(FL.info("[".concat(this.clientId,"] receive vos fallback notification: "),e.detail),"FALLBACKCN"===e.detail&&rL("ENABLE_QUALITY_FALLBACK")?void OD(this,yF.VOS_FALLBACK_PROMISE,e.detail).then((()=>{this.reconnect("recover",t.desc)})).catch((e=>{FL.debug("[".concat(this.clientId,"] cancel vos fallback cn, error: "),e)})):"fallback_hls"===e.detail&&rL("ENABLE_FALLBACK_TO_HLS")?(this.emit(yF.VOS_FALLBACK,e.detail),void this.close(SD.FALLBACK_TO_HLS)):this.reconnect(t.action,t.desc)):void this.reconnect(t.action,ID.SERVER_ERROR);FL.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=rL("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(FL.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>rL("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",ID.TIMEOUT):this.request(bF.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),rL("REPORT_STATS")&&this.send(bF.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWsInflateData(){const e=this.websocket.getWsInflateData(),t=e.wsInflateLength,n=e.wsDeflateLength;0!==t&&0!==n&&this.upload(CF.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:n,ws_inflate_length:t})}handleWebsocketEvents(){this.websocket.on(wF.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(yF.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(wF.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(wF.CLOSED,(()=>{this.connectionState=vF.CLOSED})),this.websocket.on(wF.FAILED,(()=>{this._disconnectedReason=SD.NETWORK_ERROR,this.connectionState=vF.CLOSED})),this.websocket.on(wF.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===vF.CONNECTED?this.connectionState=vF.RECONNECTING:this.connectionState=vF.CONNECTING})),this.websocket.on(wF.WILL_RECONNECT,((e,t,n)=>{const i=PD(this,yF.IS_P2P_DISCONNECTED),r=i||"retry"!==e;i&&"retry"===e&&(FL.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),e="tryNext",t=YF.P2P_DISCONNECTED),r&&(FL.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(e)),this.emit(yF.REPORT_JOIN_GATEWAY,t||YF.UNKNOWN_REASON,this.url||""),this.reconnectToken=void 0,this.emit(yF.DISCONNECT_P2P)),n(e)})),this.websocket.on(wF.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{FL.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",ID.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(yF.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof hk){if(e.code===JN.UNEXPECTED_RESPONSE&&e.data.code===RF.ERR_NO_AUTHORIZED)return this.initError=new hk(JN.TOKEN_EXPIRE,"dynamic key expired"),void this.close(SD.TOKEN_EXPIRE);FL.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",ID.SERVER_ERROR):(this.initError=e,this.close())}}))})),this.websocket.on(wF.REQUEST_NEW_URLS,((e,t)=>{OD(this,yF.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(wF.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(IF.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(pB.PRE_CONNECT_PC,(()=>{this.emit(yF.PRE_CONNECT_PC)})),this.websocket.on(wF.ON_FALLBACK,(()=>{rL("ENABLE_FALLBACK_TO_HLS")&&this.emit(yF.VOS_FALLBACK,"fallback_hls")}))}}var BB=l,jB=nC,GB=RegExp.prototype,WB=function(e){return e===GB||BB(GB,e)?jB(e):e.flags},KB=n(WB);function HB(e){let t=e.length;for(;--t>=0;)e[t]=0}const YB=256,XB=286,JB=30,zB=15,ZB=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),qB=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),QB=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),$B=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ej=new Array(576);HB(ej);const tj=new Array(60);HB(tj);const nj=new Array(512);HB(nj);const ij=new Array(256);HB(ij);const rj=new Array(29);HB(rj);const oj=new Array(JB);function sj(e,t,n,i,r){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=i,this.max_length=r,this.has_stree=e&&e.length}let aj,cj,dj;function lj(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}HB(oj);const uj=e=>e<256?nj[e]:nj[256+(e>>>7)],hj=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},pj=(e,t,n)=>{e.bi_valid>16-n?(e.bi_buf|=t<<e.bi_valid&65535,hj(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=n-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=n)},_j=(e,t,n)=>{pj(e,n[2*t],n[2*t+1])},Ej=(e,t)=>{let n=0;do{n|=1&e,e>>>=1,n<<=1}while(--t>0);return n>>>1},mj=(e,t,n)=>{const i=new Array(16);let r,o,s=0;for(r=1;r<=zB;r++)s=s+n[r-1]<<1,i[r]=s;for(o=0;o<=t;o++){let t=e[2*o+1];0!==t&&(e[2*o]=Ej(i[t]++,t))}},fj=e=>{let t;for(t=0;t<XB;t++)e.dyn_ltree[2*t]=0;for(t=0;t<JB;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},gj=e=>{e.bi_valid>8?hj(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},Sj=(e,t,n,i)=>{const r=2*t,o=2*n;return e[r]<e[o]||e[r]===e[o]&&i[t]<=i[n]},Tj=(e,t,n)=>{const i=e.heap[n];let r=n<<1;for(;r<=e.heap_len&&(r<e.heap_len&&Sj(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!Sj(t,i,e.heap[r],e.depth));)e.heap[n]=e.heap[r],n=r,r<<=1;e.heap[n]=i},Rj=(e,t,n)=>{let i,r,o,s,a=0;if(0!==e.sym_next)do{i=255&e.pending_buf[e.sym_buf+a++],i+=(255&e.pending_buf[e.sym_buf+a++])<<8,r=e.pending_buf[e.sym_buf+a++],0===i?_j(e,r,t):(o=ij[r],_j(e,o+YB+1,t),s=ZB[o],0!==s&&(r-=rj[o],pj(e,r,s)),i--,o=uj(i),_j(e,o,n),s=qB[o],0!==s&&(i-=oj[o],pj(e,i,s)))}while(a<e.sym_next);_j(e,256,t)},vj=(e,t)=>{const n=t.dyn_tree,i=t.stat_desc.static_tree,r=t.stat_desc.has_stree,o=t.stat_desc.elems;let s,a,c,d=-1;for(e.heap_len=0,e.heap_max=573,s=0;s<o;s++)0!==n[2*s]?(e.heap[++e.heap_len]=d=s,e.depth[s]=0):n[2*s+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=d<2?++d:0,n[2*c]=1,e.depth[c]=0,e.opt_len--,r&&(e.static_len-=i[2*c+1]);for(t.max_code=d,s=e.heap_len>>1;s>=1;s--)Tj(e,n,s);c=o;do{s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Tj(e,n,1),a=e.heap[1],e.heap[--e.heap_max]=s,e.heap[--e.heap_max]=a,n[2*c]=n[2*s]+n[2*a],e.depth[c]=(e.depth[s]>=e.depth[a]?e.depth[s]:e.depth[a])+1,n[2*s+1]=n[2*a+1]=c,e.heap[1]=c++,Tj(e,n,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const n=t.dyn_tree,i=t.max_code,r=t.stat_desc.static_tree,o=t.stat_desc.has_stree,s=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,c=t.stat_desc.max_length;let d,l,u,h,p,_,E=0;for(h=0;h<=zB;h++)e.bl_count[h]=0;for(n[2*e.heap[e.heap_max]+1]=0,d=e.heap_max+1;d<573;d++)l=e.heap[d],h=n[2*n[2*l+1]+1]+1,h>c&&(h=c,E++),n[2*l+1]=h,l>i||(e.bl_count[h]++,p=0,l>=a&&(p=s[l-a]),_=n[2*l],e.opt_len+=_*(h+p),o&&(e.static_len+=_*(r[2*l+1]+p)));if(0!==E){do{for(h=c-1;0===e.bl_count[h];)h--;e.bl_count[h]--,e.bl_count[h+1]+=2,e.bl_count[c]--,E-=2}while(E>0);for(h=c;0!==h;h--)for(l=e.bl_count[h];0!==l;)u=e.heap[--d],u>i||(n[2*u+1]!==h&&(e.opt_len+=(h-n[2*u+1])*n[2*u],n[2*u+1]=h),l--)}})(e,t),mj(n,d,e.bl_count)},yj=(e,t,n)=>{let i,r,o=-1,s=t[1],a=0,c=7,d=4;for(0===s&&(c=138,d=3),t[2*(n+1)+1]=65535,i=0;i<=n;i++)r=s,s=t[2*(i+1)+1],++a<c&&r===s||(a<d?e.bl_tree[2*r]+=a:0!==r?(r!==o&&e.bl_tree[2*r]++,e.bl_tree[32]++):a<=10?e.bl_tree[34]++:e.bl_tree[36]++,a=0,o=r,0===s?(c=138,d=3):r===s?(c=6,d=3):(c=7,d=4))},bj=(e,t,n)=>{let i,r,o=-1,s=t[1],a=0,c=7,d=4;for(0===s&&(c=138,d=3),i=0;i<=n;i++)if(r=s,s=t[2*(i+1)+1],!(++a<c&&r===s)){if(a<d)do{_j(e,r,e.bl_tree)}while(0!=--a);else 0!==r?(r!==o&&(_j(e,r,e.bl_tree),a--),_j(e,16,e.bl_tree),pj(e,a-3,2)):a<=10?(_j(e,17,e.bl_tree),pj(e,a-3,3)):(_j(e,18,e.bl_tree),pj(e,a-11,7));a=0,o=r,0===s?(c=138,d=3):r===s?(c=6,d=3):(c=7,d=4)}};let Cj=!1;const Ij=(e,t,n,i)=>{pj(e,0+(i?1:0),3),gj(e),hj(e,n),hj(e,~n),n&&e.pending_buf.set(e.window.subarray(t,t+n),e.pending),e.pending+=n};var Aj=e=>{Cj||((()=>{let e,t,n,i,r;const o=new Array(16);for(n=0,i=0;i<28;i++)for(rj[i]=n,e=0;e<1<<ZB[i];e++)ij[n++]=i;for(ij[n-1]=i,r=0,i=0;i<16;i++)for(oj[i]=r,e=0;e<1<<qB[i];e++)nj[r++]=i;for(r>>=7;i<JB;i++)for(oj[i]=r<<7,e=0;e<1<<qB[i]-7;e++)nj[256+r++]=i;for(t=0;t<=zB;t++)o[t]=0;for(e=0;e<=143;)ej[2*e+1]=8,e++,o[8]++;for(;e<=255;)ej[2*e+1]=9,e++,o[9]++;for(;e<=279;)ej[2*e+1]=7,e++,o[7]++;for(;e<=287;)ej[2*e+1]=8,e++,o[8]++;for(mj(ej,287,o),e=0;e<JB;e++)tj[2*e+1]=5,tj[2*e]=Ej(e,5);aj=new sj(ej,ZB,257,XB,zB),cj=new sj(tj,qB,0,JB,zB),dj=new sj(new Array(0),QB,0,19,7)})(),Cj=!0),e.l_desc=new lj(e.dyn_ltree,aj),e.d_desc=new lj(e.dyn_dtree,cj),e.bl_desc=new lj(e.bl_tree,dj),e.bi_buf=0,e.bi_valid=0,fj(e)},wj=(e,t,n,i)=>{let r,o,s=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,n=4093624447;for(t=0;t<=31;t++,n>>>=1)if(1&n&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<YB;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),vj(e,e.l_desc),vj(e,e.d_desc),s=(e=>{let t;for(yj(e,e.dyn_ltree,e.l_desc.max_code),yj(e,e.dyn_dtree,e.d_desc.max_code),vj(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*$B[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),r=e.opt_len+3+7>>>3,o=e.static_len+3+7>>>3,o<=r&&(r=o)):r=o=n+5,n+4<=r&&-1!==t?Ij(e,t,n,i):4===e.strategy||o===r?(pj(e,2+(i?1:0),3),Rj(e,ej,tj)):(pj(e,4+(i?1:0),3),((e,t,n,i)=>{let r;for(pj(e,t-257,5),pj(e,n-1,5),pj(e,i-4,4),r=0;r<i;r++)pj(e,e.bl_tree[2*$B[r]+1],3);bj(e,e.dyn_ltree,t-1),bj(e,e.dyn_dtree,n-1)})(e,e.l_desc.max_code+1,e.d_desc.max_code+1,s+1),Rj(e,e.dyn_ltree,e.dyn_dtree)),fj(e),i&&gj(e)},Oj=(e,t,n)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=n,0===t?e.dyn_ltree[2*n]++:(e.matches++,t--,e.dyn_ltree[2*(ij[n]+YB+1)]++,e.dyn_dtree[2*uj(t)]++),e.sym_next===e.sym_end),Nj=e=>{pj(e,2,3),_j(e,256,ej),(e=>{16===e.bi_valid?(hj(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(e)},Dj={_tr_init:Aj,_tr_stored_block:Ij,_tr_flush_block:wj,_tr_tally:Oj,_tr_align:Nj};var Pj=(e,t,n,i)=>{let r=65535&e|0,o=e>>>16&65535|0,s=0;for(;0!==n;){s=n>2e3?2e3:n,n-=s;do{r=r+t[i++]|0,o=o+r|0}while(--s);r%=65521,o%=65521}return r|o<<16|0};const Lj=new Uint32Array((()=>{let e,t=[];for(var n=0;n<256;n++){e=n;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t})());var kj=(e,t,n,i)=>{const r=Lj,o=i+n;e^=-1;for(let n=i;n<o;n++)e=e>>>8^r[255&(e^t[n])];return-1^e},Mj={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},Uj={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const Vj=Dj._tr_init,xj=Dj._tr_stored_block,Fj=Dj._tr_flush_block,Bj=Dj._tr_tally,jj=Dj._tr_align,Gj=Uj.Z_NO_FLUSH,Wj=Uj.Z_PARTIAL_FLUSH,Kj=Uj.Z_FULL_FLUSH,Hj=Uj.Z_FINISH,Yj=Uj.Z_BLOCK,Xj=Uj.Z_OK,Jj=Uj.Z_STREAM_END,zj=Uj.Z_STREAM_ERROR,Zj=Uj.Z_DATA_ERROR,qj=Uj.Z_BUF_ERROR,Qj=Uj.Z_DEFAULT_COMPRESSION,$j=Uj.Z_FILTERED,eG=Uj.Z_HUFFMAN_ONLY,tG=Uj.Z_RLE,nG=Uj.Z_FIXED,iG=Uj.Z_DEFAULT_STRATEGY,rG=Uj.Z_UNKNOWN,oG=Uj.Z_DEFLATED,sG=286,aG=30,cG=19,dG=2*sG+1,lG=15,uG=258,hG=262,pG=42,_G=113,EG=666,mG=(e,t)=>(e.msg=Mj[t],t),fG=e=>2*e-(e>4?9:0),gG=e=>{let t=e.length;for(;--t>=0;)e[t]=0},SG=e=>{let t,n,i,r=e.w_size;t=e.hash_size,i=t;do{n=e.head[--i],e.head[i]=n>=r?n-r:0}while(--t);t=r,i=t;do{n=e.prev[--i],e.prev[i]=n>=r?n-r:0}while(--t)};let TG=(e,t,n)=>(t<<e.hash_shift^n)&e.hash_mask;const RG=e=>{const t=e.state;let n=t.pending;n>e.avail_out&&(n=e.avail_out),0!==n&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+n),e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,0===t.pending&&(t.pending_out=0))},vG=(e,t)=>{Fj(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,RG(e.strm)},yG=(e,t)=>{e.pending_buf[e.pending++]=t},bG=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},CG=(e,t,n,i)=>{let r=e.avail_in;return r>i&&(r=i),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),n),1===e.state.wrap?e.adler=Pj(e.adler,t,r,n):2===e.state.wrap&&(e.adler=kj(e.adler,t,r,n)),e.next_in+=r,e.total_in+=r,r)},IG=(e,t)=>{let n,i,r=e.max_chain_length,o=e.strstart,s=e.prev_length,a=e.nice_match;const c=e.strstart>e.w_size-hG?e.strstart-(e.w_size-hG):0,d=e.window,l=e.w_mask,u=e.prev,h=e.strstart+uG;let p=d[o+s-1],_=d[o+s];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(n=t,d[n+s]===_&&d[n+s-1]===p&&d[n]===d[o]&&d[++n]===d[o+1]){o+=2,n++;do{}while(d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&o<h);if(i=uG-(h-o),o=h-uG,i>s){if(e.match_start=t,s=i,i>=a)break;p=d[o+s-1],_=d[o+s]}}}while((t=u[t&l])>c&&0!=--r);return s<=e.lookahead?s:e.lookahead},AG=e=>{const t=e.w_size;let n,i,r;do{if(i=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-hG)&&(e.window.set(e.window.subarray(t,t+t-i),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),SG(e),i+=t),0===e.strm.avail_in)break;if(n=CG(e.strm,e.window,e.strstart+e.lookahead,i),e.lookahead+=n,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=TG(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=TG(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<hG&&0!==e.strm.avail_in)},wG=(e,t)=>{let n,i,r,o=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,s=0,a=e.strm.avail_in;do{if(n=65535,r=e.bi_valid+42>>3,e.strm.avail_out<r)break;if(r=e.strm.avail_out-r,i=e.strstart-e.block_start,n>i+e.strm.avail_in&&(n=i+e.strm.avail_in),n>r&&(n=r),n<o&&(0===n&&t!==Hj||t===Gj||n!==i+e.strm.avail_in))break;s=t===Hj&&n===i+e.strm.avail_in?1:0,xj(e,0,0,s),e.pending_buf[e.pending-4]=n,e.pending_buf[e.pending-3]=n>>8,e.pending_buf[e.pending-2]=~n,e.pending_buf[e.pending-1]=~n>>8,RG(e.strm),i&&(i>n&&(i=n),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+i),e.strm.next_out),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i,e.block_start+=i,n-=i),n&&(CG(e.strm,e.strm.output,e.strm.next_out,n),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n)}while(0===s);return a-=e.strm.avail_in,a&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),s?4:t!==Gj&&t!==Hj&&0===e.strm.avail_in&&e.strstart===e.block_start?2:(r=e.window_size-e.strstart,e.strm.avail_in>r&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(CG(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water<e.strstart&&(e.high_water=e.strstart),r=e.bi_valid+42>>3,r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r,o=r>e.w_size?e.w_size:r,i=e.strstart-e.block_start,(i>=o||(i||t===Hj)&&t!==Gj&&0===e.strm.avail_in&&i<=r)&&(n=i>r?r:i,s=t===Hj&&0===e.strm.avail_in&&n===i?1:0,xj(e,e.block_start,n,s),e.block_start+=n,RG(e.strm)),s?3:1)},OG=(e,t)=>{let n,i;for(;;){if(e.lookahead<hG){if(AG(e),e.lookahead<hG&&t===Gj)return 1;if(0===e.lookahead)break}if(n=0,e.lookahead>=3&&(e.ins_h=TG(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==n&&e.strstart-n<=e.w_size-hG&&(e.match_length=IG(e,n)),e.match_length>=3)if(i=Bj(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=TG(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=TG(e,e.ins_h,e.window[e.strstart+1]);else i=Bj(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(i&&(vG(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===Hj?(vG(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(vG(e,!1),0===e.strm.avail_out)?1:2},NG=(e,t)=>{let n,i,r;for(;;){if(e.lookahead<hG){if(AG(e),e.lookahead<hG&&t===Gj)return 1;if(0===e.lookahead)break}if(n=0,e.lookahead>=3&&(e.ins_h=TG(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==n&&e.prev_length<e.max_lazy_match&&e.strstart-n<=e.w_size-hG&&(e.match_length=IG(e,n),e.match_length<=5&&(e.strategy===$j||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,i=Bj(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=TG(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,i&&(vG(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(i=Bj(e,0,e.window[e.strstart-1]),i&&vG(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(i=Bj(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===Hj?(vG(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(vG(e,!1),0===e.strm.avail_out)?1:2};function DG(e,t,n,i,r){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=i,this.func=r}const PG=[new DG(0,0,0,0,wG),new DG(4,4,8,4,OG),new DG(4,5,16,8,OG),new DG(4,6,32,32,OG),new DG(4,4,16,16,NG),new DG(8,16,32,32,NG),new DG(8,16,128,128,NG),new DG(8,32,128,256,NG),new DG(32,128,258,1024,NG),new DG(32,258,258,4096,NG)];function LG(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=oG,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(2*dG),this.dyn_dtree=new Uint16Array(2*(2*aG+1)),this.bl_tree=new Uint16Array(2*(2*cG+1)),gG(this.dyn_ltree),gG(this.dyn_dtree),gG(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(lG+1),this.heap=new Uint16Array(2*sG+1),gG(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*sG+1),gG(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const kG=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==pG&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==_G&&t.status!==EG?1:0},MG=e=>{if(kG(e))return mG(e,zj);e.total_in=e.total_out=0,e.data_type=rG;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?pG:_G,e.adler=2===t.wrap?0:1,t.last_flush=-2,Vj(t),Xj},UG=e=>{const t=MG(e);return t===Xj&&(e=>{e.window_size=2*e.w_size,gG(e.head),e.max_lazy_match=PG[e.level].max_lazy,e.good_match=PG[e.level].good_length,e.nice_match=PG[e.level].nice_length,e.max_chain_length=PG[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0})(e.state),t},VG=(e,t,n,i,r,o)=>{if(!e)return zj;let s=1;if(t===Qj&&(t=6),i<0?(s=0,i=-i):i>15&&(s=2,i-=16),r<1||r>9||n!==oG||i<8||i>15||t<0||t>9||o<0||o>nG||8===i&&1!==s)return mG(e,zj);8===i&&(i=9);const a=new LG;return e.state=a,a.strm=e,a.status=pG,a.wrap=s,a.gzhead=null,a.w_bits=i,a.w_size=1<<a.w_bits,a.w_mask=a.w_size-1,a.hash_bits=r+7,a.hash_size=1<<a.hash_bits,a.hash_mask=a.hash_size-1,a.hash_shift=~~((a.hash_bits+3-1)/3),a.window=new Uint8Array(2*a.w_size),a.head=new Uint16Array(a.hash_size),a.prev=new Uint16Array(a.w_size),a.lit_bufsize=1<<r+6,a.pending_buf_size=4*a.lit_bufsize,a.pending_buf=new Uint8Array(a.pending_buf_size),a.sym_buf=a.lit_bufsize,a.sym_end=3*(a.lit_bufsize-1),a.level=t,a.strategy=o,a.method=n,UG(e)};var xG=(e,t)=>{if(kG(e)||t>Yj||t<0)return e?mG(e,zj):zj;const n=e.state;if(!e.output||0!==e.avail_in&&!e.input||n.status===EG&&t!==Hj)return mG(e,0===e.avail_out?qj:zj);const i=n.last_flush;if(n.last_flush=t,0!==n.pending){if(RG(e),0===e.avail_out)return n.last_flush=-1,Xj}else if(0===e.avail_in&&fG(t)<=fG(i)&&t!==Hj)return mG(e,qj);if(n.status===EG&&0!==e.avail_in)return mG(e,qj);if(n.status===pG&&0===n.wrap&&(n.status=_G),n.status===pG){let t=oG+(n.w_bits-8<<4)<<8,i=-1;if(i=n.strategy>=eG||n.level<2?0:n.level<6?1:6===n.level?2:3,t|=i<<6,0!==n.strstart&&(t|=32),t+=31-t%31,bG(n,t),0!==n.strstart&&(bG(n,e.adler>>>16),bG(n,65535&e.adler)),e.adler=1,n.status=_G,RG(e),0!==n.pending)return n.last_flush=-1,Xj}if(57===n.status)if(e.adler=0,yG(n,31),yG(n,139),yG(n,8),n.gzhead)yG(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),yG(n,255&n.gzhead.time),yG(n,n.gzhead.time>>8&255),yG(n,n.gzhead.time>>16&255),yG(n,n.gzhead.time>>24&255),yG(n,9===n.level?2:n.strategy>=eG||n.level<2?4:0),yG(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(yG(n,255&n.gzhead.extra.length),yG(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=kj(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69;else if(yG(n,0),yG(n,0),yG(n,0),yG(n,0),yG(n,0),yG(n,9===n.level?2:n.strategy>=eG||n.level<2?4:0),yG(n,3),n.status=_G,RG(e),0!==n.pending)return n.last_flush=-1,Xj;if(69===n.status){if(n.gzhead.extra){let t=n.pending,i=(65535&n.gzhead.extra.length)-n.gzindex;for(;n.pending+i>n.pending_buf_size;){let r=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+r),n.pending),n.pending=n.pending_buf_size,n.gzhead.hcrc&&n.pending>t&&(e.adler=kj(e.adler,n.pending_buf,n.pending-t,t)),n.gzindex+=r,RG(e),0!==n.pending)return n.last_flush=-1,Xj;t=0,i-=r}let r=new Uint8Array(n.gzhead.extra);n.pending_buf.set(r.subarray(n.gzindex,n.gzindex+i),n.pending),n.pending+=i,n.gzhead.hcrc&&n.pending>t&&(e.adler=kj(e.adler,n.pending_buf,n.pending-t,t)),n.gzindex=0}n.status=73}if(73===n.status){if(n.gzhead.name){let t,i=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>i&&(e.adler=kj(e.adler,n.pending_buf,n.pending-i,i)),RG(e),0!==n.pending)return n.last_flush=-1,Xj;i=0}t=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,yG(n,t)}while(0!==t);n.gzhead.hcrc&&n.pending>i&&(e.adler=kj(e.adler,n.pending_buf,n.pending-i,i)),n.gzindex=0}n.status=91}if(91===n.status){if(n.gzhead.comment){let t,i=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>i&&(e.adler=kj(e.adler,n.pending_buf,n.pending-i,i)),RG(e),0!==n.pending)return n.last_flush=-1,Xj;i=0}t=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,yG(n,t)}while(0!==t);n.gzhead.hcrc&&n.pending>i&&(e.adler=kj(e.adler,n.pending_buf,n.pending-i,i))}n.status=103}if(103===n.status){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(RG(e),0!==n.pending))return n.last_flush=-1,Xj;yG(n,255&e.adler),yG(n,e.adler>>8&255),e.adler=0}if(n.status=_G,RG(e),0!==n.pending)return n.last_flush=-1,Xj}if(0!==e.avail_in||0!==n.lookahead||t!==Gj&&n.status!==EG){let i=0===n.level?wG(n,t):n.strategy===eG?((e,t)=>{let n;for(;;){if(0===e.lookahead&&(AG(e),0===e.lookahead)){if(t===Gj)return 1;break}if(e.match_length=0,n=Bj(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,n&&(vG(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===Hj?(vG(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(vG(e,!1),0===e.strm.avail_out)?1:2})(n,t):n.strategy===tG?((e,t)=>{let n,i,r,o;const s=e.window;for(;;){if(e.lookahead<=uG){if(AG(e),e.lookahead<=uG&&t===Gj)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,i=s[r],i===s[++r]&&i===s[++r]&&i===s[++r])){o=e.strstart+uG;do{}while(i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&r<o);e.match_length=uG-(o-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(n=Bj(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(n=Bj(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),n&&(vG(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===Hj?(vG(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(vG(e,!1),0===e.strm.avail_out)?1:2})(n,t):PG[n.level].func(n,t);if(3!==i&&4!==i||(n.status=EG),1===i||3===i)return 0===e.avail_out&&(n.last_flush=-1),Xj;if(2===i&&(t===Wj?jj(n):t!==Yj&&(xj(n,0,0,!1),t===Kj&&(gG(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),RG(e),0===e.avail_out))return n.last_flush=-1,Xj}return t!==Hj?Xj:n.wrap<=0?Jj:(2===n.wrap?(yG(n,255&e.adler),yG(n,e.adler>>8&255),yG(n,e.adler>>16&255),yG(n,e.adler>>24&255),yG(n,255&e.total_in),yG(n,e.total_in>>8&255),yG(n,e.total_in>>16&255),yG(n,e.total_in>>24&255)):(bG(n,e.adler>>>16),bG(n,65535&e.adler)),RG(e),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?Xj:Jj)},FG=(e,t)=>{let n=t.length;if(kG(e))return zj;const i=e.state,r=i.wrap;if(2===r||1===r&&i.status!==pG||i.lookahead)return zj;if(1===r&&(e.adler=Pj(e.adler,t,n,0)),i.wrap=0,n>=i.w_size){0===r&&(gG(i.head),i.strstart=0,i.block_start=0,i.insert=0);let e=new Uint8Array(i.w_size);e.set(t.subarray(n-i.w_size,n),0),t=e,n=i.w_size}const o=e.avail_in,s=e.next_in,a=e.input;for(e.avail_in=n,e.next_in=0,e.input=t,AG(i);i.lookahead>=3;){let e=i.strstart,t=i.lookahead-2;do{i.ins_h=TG(i,i.ins_h,i.window[e+3-1]),i.prev[e&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=e,e++}while(--t);i.strstart=e,i.lookahead=2,AG(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,e.next_in=s,e.input=a,e.avail_in=o,i.wrap=r,Xj},BG={deflateInit:(e,t)=>VG(e,t,oG,15,8,iG),deflateInit2:VG,deflateReset:UG,deflateResetKeep:MG,deflateSetHeader:(e,t)=>kG(e)||2!==e.state.wrap?zj:(e.state.gzhead=t,Xj),deflate:xG,deflateEnd:e=>{if(kG(e))return zj;const t=e.state.status;return e.state=null,t===_G?mG(e,Zj):Xj},deflateSetDictionary:FG,deflateInfo:"pako deflate (from Nodeca project)"};const jG=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var GG={assign:function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const n=t.shift();if(n){if("object"!=typeof n)throw new TypeError(n+"must be non-object");for(const t in n)jG(n,t)&&(e[t]=n[t])}}return e},flattenChunks:e=>{let t=0;for(let n=0,i=e.length;n<i;n++)t+=e[n].length;const n=new Uint8Array(t);for(let t=0,i=0,r=e.length;t<r;t++){let r=e[t];n.set(r,i),i+=r.length}return n}};let WG=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){WG=!1}const KG=new Uint8Array(256);for(let e=0;e<256;e++)KG[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;KG[254]=KG[254]=1;var HG={string2buf:e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,n,i,r,o,s=e.length,a=0;for(r=0;r<s;r++)n=e.charCodeAt(r),55296==(64512&n)&&r+1<s&&(i=e.charCodeAt(r+1),56320==(64512&i)&&(n=65536+(n-55296<<10)+(i-56320),r++)),a+=n<128?1:n<2048?2:n<65536?3:4;for(t=new Uint8Array(a),o=0,r=0;o<a;r++)n=e.charCodeAt(r),55296==(64512&n)&&r+1<s&&(i=e.charCodeAt(r+1),56320==(64512&i)&&(n=65536+(n-55296<<10)+(i-56320),r++)),n<128?t[o++]=n:n<2048?(t[o++]=192|n>>>6,t[o++]=128|63&n):n<65536?(t[o++]=224|n>>>12,t[o++]=128|n>>>6&63,t[o++]=128|63&n):(t[o++]=240|n>>>18,t[o++]=128|n>>>12&63,t[o++]=128|n>>>6&63,t[o++]=128|63&n);return t},buf2string:(e,t)=>{const n=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let i,r;const o=new Array(2*n);for(r=0,i=0;i<n;){let t=e[i++];if(t<128){o[r++]=t;continue}let s=KG[t];if(s>4)o[r++]=65533,i+=s-1;else{for(t&=2===s?31:3===s?15:7;s>1&&i<n;)t=t<<6|63&e[i++],s--;s>1?o[r++]=65533:t<65536?o[r++]=t:(t-=65536,o[r++]=55296|t>>10&1023,o[r++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&WG)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let n="";for(let i=0;i<t;i++)n+=String.fromCharCode(e[i]);return n})(o,r)},utf8border:(e,t)=>{(t=t||e.length)>e.length&&(t=e.length);let n=t-1;for(;n>=0&&128==(192&e[n]);)n--;return n<0||0===n?t:n+KG[e[n]]>t?n:t}};var YG=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const XG=Object.prototype.toString,JG=Uj.Z_NO_FLUSH,zG=Uj.Z_SYNC_FLUSH,ZG=Uj.Z_FULL_FLUSH,qG=Uj.Z_FINISH,QG=Uj.Z_OK,$G=Uj.Z_STREAM_END,eW=Uj.Z_DEFAULT_COMPRESSION,tW=Uj.Z_DEFAULT_STRATEGY,nW=Uj.Z_DEFLATED;function iW(e){this.options=GG.assign({level:eW,method:nW,chunkSize:16384,windowBits:15,memLevel:8,strategy:tW},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new YG,this.strm.avail_out=0;let n=BG.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==QG)throw new Error(Mj[n]);if(t.header&&BG.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?HG.string2buf(t.dictionary):"[object ArrayBuffer]"===XG.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,n=BG.deflateSetDictionary(this.strm,e),n!==QG)throw new Error(Mj[n]);this._dict_set=!0}}function rW(e,t){const n=new iW(t);if(n.push(e,!0),n.err)throw n.msg||Mj[n.err];return n.result}iW.prototype.push=function(e,t){const n=this.strm,i=this.options.chunkSize;let r,o;if(this.ended)return!1;for(o=t===~~t?t:!0===t?qG:JG,"string"==typeof e?n.input=HG.string2buf(e):"[object ArrayBuffer]"===XG.call(e)?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;)if(0===n.avail_out&&(n.output=new Uint8Array(i),n.next_out=0,n.avail_out=i),(o===zG||o===ZG)&&n.avail_out<=6)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else{if(r=BG.deflate(n,o),r===$G)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),r=BG.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===QG;if(0!==n.avail_out){if(o>0&&n.next_out>0)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else if(0===n.avail_in)break}else this.onData(n.output)}return!0},iW.prototype.onData=function(e){this.chunks.push(e)},iW.prototype.onEnd=function(e){e===QG&&(this.result=GG.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var oW={Deflate:iW,deflate:rW,deflateRaw:function(e,t){return(t=t||{}).raw=!0,rW(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,rW(e,t)},constants:Uj};const sW=16209;var aW=function(e,t){let n,i,r,o,s,a,c,d,l,u,h,p,_,E,m,f,g,S,T,R,v,y,b,C;const I=e.state;n=e.next_in,b=e.input,i=n+(e.avail_in-5),r=e.next_out,C=e.output,o=r-(t-e.avail_out),s=r+(e.avail_out-257),a=I.dmax,c=I.wsize,d=I.whave,l=I.wnext,u=I.window,h=I.hold,p=I.bits,_=I.lencode,E=I.distcode,m=(1<<I.lenbits)-1,f=(1<<I.distbits)-1;e:do{p<15&&(h+=b[n++]<<p,p+=8,h+=b[n++]<<p,p+=8),g=_[h&m];t:for(;;){if(S=g>>>24,h>>>=S,p-=S,S=g>>>16&255,0===S)C[r++]=65535&g;else{if(!(16&S)){if(0==(64&S)){g=_[(65535&g)+(h&(1<<S)-1)];continue t}if(32&S){I.mode=16191;break e}e.msg="invalid literal/length code",I.mode=sW;break e}T=65535&g,S&=15,S&&(p<S&&(h+=b[n++]<<p,p+=8),T+=h&(1<<S)-1,h>>>=S,p-=S),p<15&&(h+=b[n++]<<p,p+=8,h+=b[n++]<<p,p+=8),g=E[h&f];n:for(;;){if(S=g>>>24,h>>>=S,p-=S,S=g>>>16&255,!(16&S)){if(0==(64&S)){g=E[(65535&g)+(h&(1<<S)-1)];continue n}e.msg="invalid distance code",I.mode=sW;break e}if(R=65535&g,S&=15,p<S&&(h+=b[n++]<<p,p+=8,p<S&&(h+=b[n++]<<p,p+=8)),R+=h&(1<<S)-1,R>a){e.msg="invalid distance too far back",I.mode=sW;break e}if(h>>>=S,p-=S,S=r-o,R>S){if(S=R-S,S>d&&I.sane){e.msg="invalid distance too far back",I.mode=sW;break e}if(v=0,y=u,0===l){if(v+=c-S,S<T){T-=S;do{C[r++]=u[v++]}while(--S);v=r-R,y=C}}else if(l<S){if(v+=c+l-S,S-=l,S<T){T-=S;do{C[r++]=u[v++]}while(--S);if(v=0,l<T){S=l,T-=S;do{C[r++]=u[v++]}while(--S);v=r-R,y=C}}}else if(v+=l-S,S<T){T-=S;do{C[r++]=u[v++]}while(--S);v=r-R,y=C}for(;T>2;)C[r++]=y[v++],C[r++]=y[v++],C[r++]=y[v++],T-=3;T&&(C[r++]=y[v++],T>1&&(C[r++]=y[v++]))}else{v=r-R;do{C[r++]=C[v++],C[r++]=C[v++],C[r++]=C[v++],T-=3}while(T>2);T&&(C[r++]=C[v++],T>1&&(C[r++]=C[v++]))}break}}break}}while(n<i&&r<s);T=p>>3,n-=T,p-=T<<3,h&=(1<<p)-1,e.next_in=n,e.next_out=r,e.avail_in=n<i?i-n+5:5-(n-i),e.avail_out=r<s?s-r+257:257-(r-s),I.hold=h,I.bits=p};const cW=15,dW=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),lW=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),uW=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),hW=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var pW=(e,t,n,i,r,o,s,a)=>{const c=a.bits;let d,l,u,h,p,_,E=0,m=0,f=0,g=0,S=0,T=0,R=0,v=0,y=0,b=0,C=null;const I=new Uint16Array(16),A=new Uint16Array(16);let w,O,N,D=null;for(E=0;E<=cW;E++)I[E]=0;for(m=0;m<i;m++)I[t[n+m]]++;for(S=c,g=cW;g>=1&&0===I[g];g--);if(S>g&&(S=g),0===g)return r[o++]=20971520,r[o++]=20971520,a.bits=1,0;for(f=1;f<g&&0===I[f];f++);for(S<f&&(S=f),v=1,E=1;E<=cW;E++)if(v<<=1,v-=I[E],v<0)return-1;if(v>0&&(0===e||1!==g))return-1;for(A[1]=0,E=1;E<cW;E++)A[E+1]=A[E]+I[E];for(m=0;m<i;m++)0!==t[n+m]&&(s[A[t[n+m]]++]=m);if(0===e?(C=D=s,_=20):1===e?(C=dW,D=lW,_=257):(C=uW,D=hW,_=0),b=0,m=0,E=f,p=o,T=S,R=0,u=-1,y=1<<S,h=y-1,1===e&&y>852||2===e&&y>592)return 1;for(;;){w=E-R,s[m]+1<_?(O=0,N=s[m]):s[m]>=_?(O=D[s[m]-_],N=C[s[m]-_]):(O=96,N=0),d=1<<E-R,l=1<<T,f=l;do{l-=d,r[p+(b>>R)+l]=w<<24|O<<16|N|0}while(0!==l);for(d=1<<E-1;b&d;)d>>=1;if(0!==d?(b&=d-1,b+=d):b=0,m++,0==--I[E]){if(E===g)break;E=t[n+s[m]]}if(E>S&&(b&h)!==u){for(0===R&&(R=S),p+=f,T=E-R,v=1<<T;T+R<g&&(v-=I[T+R],!(v<=0));)T++,v<<=1;if(y+=1<<T,1===e&&y>852||2===e&&y>592)return 1;u=b&h,r[u]=S<<24|T<<16|p-o|0}}return 0!==b&&(r[p+b]=E-R<<24|64<<16|0),a.bits=S,0};const _W=Uj.Z_FINISH,EW=Uj.Z_BLOCK,mW=Uj.Z_TREES,fW=Uj.Z_OK,gW=Uj.Z_STREAM_END,SW=Uj.Z_NEED_DICT,TW=Uj.Z_STREAM_ERROR,RW=Uj.Z_DATA_ERROR,vW=Uj.Z_MEM_ERROR,yW=Uj.Z_BUF_ERROR,bW=Uj.Z_DEFLATED,CW=16180,IW=16190,AW=16191,wW=16192,OW=16194,NW=16199,DW=16200,PW=16206,LW=16209,kW=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function MW(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const UW=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode<CW||t.mode>16211?1:0},VW=e=>{if(UW(e))return TW;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=CW,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,fW},xW=e=>{if(UW(e))return TW;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,VW(e)},FW=(e,t)=>{let n;if(UW(e))return TW;const i=e.state;return t<0?(n=0,t=-t):(n=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?TW:(null!==i.window&&i.wbits!==t&&(i.window=null),i.wrap=n,i.wbits=t,xW(e))},BW=(e,t)=>{if(!e)return TW;const n=new MW;e.state=n,n.strm=e,n.window=null,n.mode=CW;const i=FW(e,t);return i!==fW&&(e.state=null),i};let jW,GW,WW=!0;const KW=e=>{if(WW){jW=new Int32Array(512),GW=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(pW(1,e.lens,0,288,jW,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;pW(2,e.lens,0,32,GW,0,e.work,{bits:5}),WW=!1}e.lencode=jW,e.lenbits=9,e.distcode=GW,e.distbits=5},HW=(e,t,n,i)=>{let r;const o=e.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new Uint8Array(o.wsize)),i>=o.wsize?(o.window.set(t.subarray(n-o.wsize,n),0),o.wnext=0,o.whave=o.wsize):(r=o.wsize-o.wnext,r>i&&(r=i),o.window.set(t.subarray(n-i,n-i+r),o.wnext),(i-=r)?(o.window.set(t.subarray(n-i,n),0),o.wnext=i,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=r))),0};var YW=(e,t)=>{let n,i,r,o,s,a,c,d,l,u,h,p,_,E,m,f,g,S,T,R,v,y,b=0;const C=new Uint8Array(4);let I,A;const w=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(UW(e)||!e.output||!e.input&&0!==e.avail_in)return TW;n=e.state,n.mode===AW&&(n.mode=wW),s=e.next_out,r=e.output,c=e.avail_out,o=e.next_in,i=e.input,a=e.avail_in,d=n.hold,l=n.bits,u=a,h=c,y=fW;e:for(;;)switch(n.mode){case CW:if(0===n.wrap){n.mode=wW;break}for(;l<16;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(2&n.wrap&&35615===d){0===n.wbits&&(n.wbits=15),n.check=0,C[0]=255&d,C[1]=d>>>8&255,n.check=kj(n.check,C,2,0),d=0,l=0,n.mode=16181;break}if(n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&d)<<8)+(d>>8))%31){e.msg="incorrect header check",n.mode=LW;break}if((15&d)!==bW){e.msg="unknown compression method",n.mode=LW;break}if(d>>>=4,l-=4,v=8+(15&d),0===n.wbits&&(n.wbits=v),v>15||v>n.wbits){e.msg="invalid window size",n.mode=LW;break}n.dmax=1<<n.wbits,n.flags=0,e.adler=n.check=1,n.mode=512&d?16189:AW,d=0,l=0;break;case 16181:for(;l<16;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(n.flags=d,(255&KB(n))!==bW){e.msg="unknown compression method",n.mode=LW;break}if(57344&KB(n)){e.msg="unknown header flags set",n.mode=LW;break}n.head&&(n.head.text=d>>8&1),512&KB(n)&&4&n.wrap&&(C[0]=255&d,C[1]=d>>>8&255,n.check=kj(n.check,C,2,0)),d=0,l=0,n.mode=16182;case 16182:for(;l<32;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.head&&(n.head.time=d),512&KB(n)&&4&n.wrap&&(C[0]=255&d,C[1]=d>>>8&255,C[2]=d>>>16&255,C[3]=d>>>24&255,n.check=kj(n.check,C,4,0)),d=0,l=0,n.mode=16183;case 16183:for(;l<16;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.head&&(n.head.xflags=255&d,n.head.os=d>>8),512&KB(n)&&4&n.wrap&&(C[0]=255&d,C[1]=d>>>8&255,n.check=kj(n.check,C,2,0)),d=0,l=0,n.mode=16184;case 16184:if(1024&KB(n)){for(;l<16;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.length=d,n.head&&(n.head.extra_len=d),512&KB(n)&&4&n.wrap&&(C[0]=255&d,C[1]=d>>>8&255,n.check=kj(n.check,C,2,0)),d=0,l=0}else n.head&&(n.head.extra=null);n.mode=16185;case 16185:if(1024&KB(n)&&(p=n.length,p>a&&(p=a),p&&(n.head&&(v=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(i.subarray(o,o+p),v)),512&KB(n)&&4&n.wrap&&(n.check=kj(n.check,i,p,o)),a-=p,o+=p,n.length-=p),n.length))break e;n.length=0,n.mode=16186;case 16186:if(2048&KB(n)){if(0===a)break e;p=0;do{v=i[o+p++],n.head&&v&&n.length<65536&&(n.head.name+=String.fromCharCode(v))}while(v&&p<a);if(512&KB(n)&&4&n.wrap&&(n.check=kj(n.check,i,p,o)),a-=p,o+=p,v)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=16187;case 16187:if(4096&KB(n)){if(0===a)break e;p=0;do{v=i[o+p++],n.head&&v&&n.length<65536&&(n.head.comment+=String.fromCharCode(v))}while(v&&p<a);if(512&KB(n)&&4&n.wrap&&(n.check=kj(n.check,i,p,o)),a-=p,o+=p,v)break e}else n.head&&(n.head.comment=null);n.mode=16188;case 16188:if(512&KB(n)){for(;l<16;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(4&n.wrap&&d!==(65535&n.check)){e.msg="header crc mismatch",n.mode=LW;break}d=0,l=0}n.head&&(n.head.hcrc=KB(n)>>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=AW;break;case 16189:for(;l<32;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}e.adler=n.check=kW(d),d=0,l=0,n.mode=IW;case IW:if(0===n.havedict)return e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,n.hold=d,n.bits=l,SW;e.adler=n.check=1,n.mode=AW;case AW:if(t===EW||t===mW)break e;case wW:if(n.last){d>>>=7&l,l-=7&l,n.mode=PW;break}for(;l<3;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}switch(n.last=1&d,d>>>=1,l-=1,3&d){case 0:n.mode=16193;break;case 1:if(KW(n),n.mode=NW,t===mW){d>>>=2,l-=2;break e}break;case 2:n.mode=16196;break;case 3:e.msg="invalid block type",n.mode=LW}d>>>=2,l-=2;break;case 16193:for(d>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if((65535&d)!=(d>>>16^65535)){e.msg="invalid stored block lengths",n.mode=LW;break}if(n.length=65535&d,d=0,l=0,n.mode=OW,t===mW)break e;case OW:n.mode=16195;case 16195:if(p=n.length,p){if(p>a&&(p=a),p>c&&(p=c),0===p)break e;r.set(i.subarray(o,o+p),s),a-=p,o+=p,c-=p,s+=p,n.length-=p;break}n.mode=AW;break;case 16196:for(;l<14;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(n.nlen=257+(31&d),d>>>=5,l-=5,n.ndist=1+(31&d),d>>>=5,l-=5,n.ncode=4+(15&d),d>>>=4,l-=4,n.nlen>286||n.ndist>30){e.msg="too many length or distance symbols",n.mode=LW;break}n.have=0,n.mode=16197;case 16197:for(;n.have<n.ncode;){for(;l<3;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.lens[w[n.have++]]=7&d,d>>>=3,l-=3}for(;n.have<19;)n.lens[w[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,I={bits:n.lenbits},y=pW(0,n.lens,0,19,n.lencode,0,n.work,I),n.lenbits=I.bits,y){e.msg="invalid code lengths set",n.mode=LW;break}n.have=0,n.mode=16198;case 16198:for(;n.have<n.nlen+n.ndist;){for(;b=n.lencode[d&(1<<n.lenbits)-1],m=b>>>24,f=b>>>16&255,g=65535&b,!(m<=l);){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(g<16)d>>>=m,l-=m,n.lens[n.have++]=g;else{if(16===g){for(A=m+2;l<A;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(d>>>=m,l-=m,0===n.have){e.msg="invalid bit length repeat",n.mode=LW;break}v=n.lens[n.have-1],p=3+(3&d),d>>>=2,l-=2}else if(17===g){for(A=m+3;l<A;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}d>>>=m,l-=m,v=0,p=3+(7&d),d>>>=3,l-=3}else{for(A=m+7;l<A;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}d>>>=m,l-=m,v=0,p=11+(127&d),d>>>=7,l-=7}if(n.have+p>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=LW;break}for(;p--;)n.lens[n.have++]=v}}if(n.mode===LW)break;if(0===n.lens[256]){e.msg="invalid code -- missing end-of-block",n.mode=LW;break}if(n.lenbits=9,I={bits:n.lenbits},y=pW(1,n.lens,0,n.nlen,n.lencode,0,n.work,I),n.lenbits=I.bits,y){e.msg="invalid literal/lengths set",n.mode=LW;break}if(n.distbits=6,n.distcode=n.distdyn,I={bits:n.distbits},y=pW(2,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,I),n.distbits=I.bits,y){e.msg="invalid distances set",n.mode=LW;break}if(n.mode=NW,t===mW)break e;case NW:n.mode=DW;case DW:if(a>=6&&c>=258){e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,n.hold=d,n.bits=l,aW(e,h),s=e.next_out,r=e.output,c=e.avail_out,o=e.next_in,i=e.input,a=e.avail_in,d=n.hold,l=n.bits,n.mode===AW&&(n.back=-1);break}for(n.back=0;b=n.lencode[d&(1<<n.lenbits)-1],m=b>>>24,f=b>>>16&255,g=65535&b,!(m<=l);){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(f&&0==(240&f)){for(S=m,T=f,R=g;b=n.lencode[R+((d&(1<<S+T)-1)>>S)],m=b>>>24,f=b>>>16&255,g=65535&b,!(S+m<=l);){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}d>>>=S,l-=S,n.back+=S}if(d>>>=m,l-=m,n.back+=m,n.length=g,0===f){n.mode=16205;break}if(32&f){n.back=-1,n.mode=AW;break}if(64&f){e.msg="invalid literal/length code",n.mode=LW;break}n.extra=15&f,n.mode=16201;case 16201:if(n.extra){for(A=n.extra;l<A;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.length+=d&(1<<n.extra)-1,d>>>=n.extra,l-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=16202;case 16202:for(;b=n.distcode[d&(1<<n.distbits)-1],m=b>>>24,f=b>>>16&255,g=65535&b,!(m<=l);){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(0==(240&f)){for(S=m,T=f,R=g;b=n.distcode[R+((d&(1<<S+T)-1)>>S)],m=b>>>24,f=b>>>16&255,g=65535&b,!(S+m<=l);){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}d>>>=S,l-=S,n.back+=S}if(d>>>=m,l-=m,n.back+=m,64&f){e.msg="invalid distance code",n.mode=LW;break}n.offset=g,n.extra=15&f,n.mode=16203;case 16203:if(n.extra){for(A=n.extra;l<A;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.offset+=d&(1<<n.extra)-1,d>>>=n.extra,l-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=LW;break}n.mode=16204;case 16204:if(0===c)break e;if(p=h-c,n.offset>p){if(p=n.offset-p,p>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=LW;break}p>n.wnext?(p-=n.wnext,_=n.wsize-p):_=n.wnext-p,p>n.length&&(p=n.length),E=n.window}else E=r,_=s-n.offset,p=n.length;p>c&&(p=c),c-=p,n.length-=p;do{r[s++]=E[_++]}while(--p);0===n.length&&(n.mode=DW);break;case 16205:if(0===c)break e;r[s++]=n.length,c--,n.mode=DW;break;case PW:if(n.wrap){for(;l<32;){if(0===a)break e;a--,d|=i[o++]<<l,l+=8}if(h-=c,e.total_out+=h,n.total+=h,4&n.wrap&&h&&(e.adler=n.check=KB(n)?kj(n.check,r,h,s-h):Pj(n.check,r,h,s-h)),h=c,4&n.wrap&&(KB(n)?d:kW(d))!==n.check){e.msg="incorrect data check",n.mode=LW;break}d=0,l=0}n.mode=16207;case 16207:if(n.wrap&&KB(n)){for(;l<32;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(4&n.wrap&&d!==(4294967295&n.total)){e.msg="incorrect length check",n.mode=LW;break}d=0,l=0}n.mode=16208;case 16208:y=gW;break e;case LW:y=RW;break e;case 16210:return vW;default:return TW}return e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,n.hold=d,n.bits=l,(n.wsize||h!==e.avail_out&&n.mode<LW&&(n.mode<PW||t!==_W))&&HW(e,e.output,e.next_out,h-e.avail_out),u-=e.avail_in,h-=e.avail_out,e.total_in+=u,e.total_out+=h,n.total+=h,4&n.wrap&&h&&(e.adler=n.check=KB(n)?kj(n.check,r,h,e.next_out-h):Pj(n.check,r,h,e.next_out-h)),e.data_type=n.bits+(n.last?64:0)+(n.mode===AW?128:0)+(n.mode===NW||n.mode===OW?256:0),(0===u&&0===h||t===_W)&&y===fW&&(y=yW),y},XW={inflateReset:xW,inflateReset2:FW,inflateResetKeep:VW,inflateInit:e=>BW(e,15),inflateInit2:BW,inflate:YW,inflateEnd:e=>{if(UW(e))return TW;let t=e.state;return t.window&&(t.window=null),e.state=null,fW},inflateGetHeader:(e,t)=>{if(UW(e))return TW;const n=e.state;return 0==(2&n.wrap)?TW:(n.head=t,t.done=!1,fW)},inflateSetDictionary:(e,t)=>{const n=t.length;let i,r,o;return UW(e)?TW:(i=e.state,0!==i.wrap&&i.mode!==IW?TW:i.mode===IW&&(r=1,r=Pj(r,t,n,0),r!==i.check)?RW:(o=HW(e,t,n,n),o?(i.mode=16210,vW):(i.havedict=1,fW)))},inflateInfo:"pako inflate (from Nodeca project)"};var JW=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const zW=Object.prototype.toString,ZW=Uj.Z_NO_FLUSH,qW=Uj.Z_FINISH,QW=Uj.Z_OK,$W=Uj.Z_STREAM_END,eK=Uj.Z_NEED_DICT,tK=Uj.Z_STREAM_ERROR,nK=Uj.Z_DATA_ERROR,iK=Uj.Z_MEM_ERROR;function rK(e){this.options=GG.assign({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new YG,this.strm.avail_out=0;let n=XW.inflateInit2(this.strm,t.windowBits);if(n!==QW)throw new Error(Mj[n]);if(this.header=new JW,XW.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=HG.string2buf(t.dictionary):"[object ArrayBuffer]"===zW.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=XW.inflateSetDictionary(this.strm,t.dictionary),n!==QW)))throw new Error(Mj[n])}function oK(e,t){const n=new rK(t);if(n.push(e),n.err)throw n.msg||Mj[n.err];return n.result}rK.prototype.push=function(e,t){const n=this.strm,i=this.options.chunkSize,r=this.options.dictionary;let o,s,a;if(this.ended)return!1;for(s=t===~~t?t:!0===t?qW:ZW,"[object ArrayBuffer]"===zW.call(e)?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){for(0===n.avail_out&&(n.output=new Uint8Array(i),n.next_out=0,n.avail_out=i),o=XW.inflate(n,s),o===eK&&r&&(o=XW.inflateSetDictionary(n,r),o===QW?o=XW.inflate(n,s):o===nK&&(o=eK));n.avail_in>0&&o===$W&&n.state.wrap>0&&0!==e[n.next_in];)XW.inflateReset(n),o=XW.inflate(n,s);switch(o){case tK:case nK:case eK:case iK:return this.onEnd(o),this.ended=!0,!1}if(a=n.avail_out,n.next_out&&(0===n.avail_out||o===$W))if("string"===this.options.to){let e=HG.utf8border(n.output,n.next_out),t=n.next_out-e,r=HG.buf2string(n.output,e);n.next_out=t,n.avail_out=i-t,t&&n.output.set(n.output.subarray(e,e+t),0),this.onData(r)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(o!==QW||0!==a){if(o===$W)return o=XW.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(0===n.avail_in)break}}return!0},rK.prototype.onData=function(e){this.chunks.push(e)},rK.prototype.onEnd=function(e){e===QW&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=GG.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var sK={Inflate:rK,inflate:oK,inflateRaw:function(e,t){return(t=t||{}).raw=!0,oK(e,t)},ungzip:oK,constants:Uj};var aK,cK=oW.deflate,dK=oW.deflateRaw,lK=sK.inflate,uK=sK.inflateRaw,hK=function(e){return e[e.CHOOSE_SERVER=11]="CHOOSE_SERVER",e[e.CLOUD_PROXY=18]="CLOUD_PROXY",e[e.CLOUD_PROXY_5=20]="CLOUD_PROXY_5",e[e.CLOUD_PROXY_FALLBACK=26]="CLOUD_PROXY_FALLBACK",e}(hK||{});function pK(e){let t=!1;const n=[];for(let i=0;i<e.length;i++){let r=e.charAt(i);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),n.push(r)}}return n.join("")}function _K(e){return e.replace(/[A-Z]/g,(e=>"_"+e.toLowerCase()))}const EK=new Set(["constructor","toString","toJSON","valueOf"]);function mK(e){return EK.has(e)?e+"$":e}var fK=void 0!==VC?VC:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function gK(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var SK,TK,RK=function(e){try{return!!e()}catch(e){return!0}},vK=!RK((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),yK=vK,bK=Function.prototype,CK=bK.call,IK=yK&&bK.bind.bind(CK,CK),AK=yK?IK:function(e){return function(){return CK.apply(e,arguments)}},wK=AK,OK=wK({}.toString),NK=wK("".slice),DK=function(e){return NK(OK(e),8,-1)},PK=RK,LK=DK,kK=Object,MK=AK("".split),UK=PK((function(){return!kK("z").propertyIsEnumerable(0)}))?function(e){return"String"===LK(e)?MK(e,""):kK(e)}:kK,VK=function(e){return null==e},xK=VK,FK=TypeError,BK=function(e){if(xK(e))throw new FK("Can't call method on "+e);return e},jK=UK,GK=BK,WK=function(e){return jK(GK(e))},KK={},HK=function(e){return e&&e.Math===Math&&e},YK=HK("object"==typeof VC&&VC)||HK("object"==typeof window&&window)||HK("object"==typeof self&&self)||HK("object"==typeof fK&&fK)||HK("object"==typeof fK&&fK)||function(){return this}()||Function("return this")(),XK="object"==typeof document&&document.all,JK=void 0===XK&&void 0!==XK?function(e){return"function"==typeof e||e===XK}:function(e){return"function"==typeof e},zK=JK,ZK=YK.WeakMap,qK=zK(ZK)&&/native code/.test(String(ZK)),QK=JK,$K=function(e){return"object"==typeof e?null!==e:QK(e)},eH=!RK((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]})),tH={},nH=$K,iH=YK.document,rH=nH(iH)&&nH(iH.createElement),oH=function(e){return rH?iH.createElement(e):{}},sH=oH,aH=!eH&&!RK((function(){return 7!==Object.defineProperty(sH("div"),"a",{get:function(){return 7}}).a})),cH=eH&&RK((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),dH=$K,lH=String,uH=TypeError,hH=function(e){if(dH(e))return e;throw new uH(lH(e)+" is not an object")},pH=vK,_H=Function.prototype.call,EH=pH?_H.bind(_H):function(){return _H.apply(_H,arguments)},mH={},fH=mH,gH=YK,SH=JK,TH=function(e){return SH(e)?e:void 0},RH=function(e,t){return arguments.length<2?TH(fH[e])||TH(gH[e]):fH[e]&&fH[e][t]||gH[e]&&gH[e][t]},vH=AK({}.isPrototypeOf),yH=YK.navigator,bH=yH&&yH.userAgent,CH=bH?String(bH):"",IH=YK,AH=CH,wH=IH.process,OH=IH.Deno,NH=wH&&wH.versions||OH&&OH.version,DH=NH&&NH.v8;DH&&(TK=(SK=DH.split("."))[0]>0&&SK[0]<4?1:+(SK[0]+SK[1])),!TK&&AH&&(!(SK=AH.match(/Edge\/(\d+)/))||SK[1]>=74)&&(SK=AH.match(/Chrome\/(\d+)/))&&(TK=+SK[1]);var PH=TK,LH=PH,kH=RK,MH=YK.String,UH=!!Object.getOwnPropertySymbols&&!kH((function(){var e=Symbol("symbol detection");return!MH(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&LH&&LH<41})),VH=UH&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,xH=RH,FH=JK,BH=vH,jH=Object,GH=VH?function(e){return"symbol"==typeof e}:function(e){var t=xH("Symbol");return FH(t)&&BH(t.prototype,jH(e))},WH=String,KH=function(e){try{return WH(e)}catch(e){return"Object"}},HH=JK,YH=KH,XH=TypeError,JH=function(e){if(HH(e))return e;throw new XH(YH(e)+" is not a function")},zH=JH,ZH=VK,qH=function(e,t){var n=e[t];return ZH(n)?void 0:zH(n)},QH=EH,$H=JK,eY=$K,tY=TypeError,nY={exports:{}},iY=YK,rY=Object.defineProperty,oY=YK,sY="__core-js_shared__",aY=nY.exports=oY[sY]||function(e,t){try{rY(iY,e,{value:t,configurable:!0,writable:!0})}catch(n){iY[e]=t}return t}(sY,{});(aY.versions||(aY.versions=[])).push({version:"3.49.0",mode:"pure",copyright:"© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.",license:"https://github.com/zloirock/core-js/blob/v3.49.0/LICENSE",source:"https://github.com/zloirock/core-js"});var cY=nY.exports,dY=cY,lY=function(e,t){return dY[e]||(dY[e]=t||{})},uY=BK,hY=Object,pY=function(e){return hY(uY(e))},_Y=pY,EY=AK({}.hasOwnProperty),mY=Object.hasOwn||function(e,t){return EY(_Y(e),t)},fY=AK,gY=0,SY=Math.random(),TY=fY(1.1.toString),RY=function(e){return"Symbol("+(void 0===e?"":e)+")_"+TY(++gY+SY,36)},vY=lY,yY=mY,bY=RY,CY=UH,IY=VH,AY=YK.Symbol,wY=vY("wks"),OY=IY?AY.for||AY:AY&&AY.withoutSetter||bY,NY=function(e){return yY(wY,e)||(wY[e]=CY&&yY(AY,e)?AY[e]:OY("Symbol."+e)),wY[e]},DY=EH,PY=$K,LY=GH,kY=qH,MY=TypeError,UY=NY("toPrimitive"),VY=function(e,t){if(!PY(e)||LY(e))return e;var n,i=kY(e,UY);if(i){if(void 0===t&&(t="default"),n=DY(i,e,t),!PY(n)||LY(n))return n;throw new MY("Can't convert object to primitive value")}return void 0===t&&(t="number"),function(e,t){var n,i;if("string"===t&&$H(n=e.toString)&&!eY(i=QH(n,e)))return i;if($H(n=e.valueOf)&&!eY(i=QH(n,e)))return i;if("string"!==t&&$H(n=e.toString)&&!eY(i=QH(n,e)))return i;throw new tY("Can't convert object to primitive value")}(e,t)},xY=GH,FY=function(e){var t=VY(e,"string");return xY(t)?t:t+""},BY=eH,jY=aH,GY=cH,WY=hH,KY=FY,HY=TypeError,YY=Object.defineProperty,XY=Object.getOwnPropertyDescriptor,JY="enumerable",zY="configurable",ZY="writable";tH.f=BY?GY?function(e,t,n){if(WY(e),t=KY(t),WY(n),"function"==typeof e&&"prototype"===t&&"value"in n&&ZY in n&&!n[ZY]){var i=XY(e,t);i&&i[ZY]&&(e[t]=n.value,n={configurable:zY in n?n[zY]:i[zY],enumerable:JY in n?n[JY]:i[JY],writable:!1})}return YY(e,t,n)}:YY:function(e,t,n){if(WY(e),t=KY(t),WY(n),jY)try{return YY(e,t,n)}catch(e){}if("get"in n||"set"in n)throw new HY("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var qY,QY,$Y,eX=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},tX=tH,nX=eX,iX=eH?function(e,t,n){return tX.f(e,t,nX(1,n))}:function(e,t,n){return e[t]=n,e},rX=RY,oX=lY("keys"),sX=function(e){return oX[e]||(oX[e]=rX(e))},aX={},cX=qK,dX=YK,lX=$K,uX=iX,hX=mY,pX=cY,_X=sX,EX=aX,mX="Object already initialized",fX=dX.TypeError,gX=dX.WeakMap;if(cX||pX.state){var SX=pX.state||(pX.state=new gX);SX.get=SX.get,SX.has=SX.has,SX.set=SX.set,qY=function(e,t){if(SX.has(e))throw new fX(mX);return t.facade=e,SX.set(e,t),t},QY=function(e){return SX.get(e)||{}},$Y=function(e){return SX.has(e)}}else{var TX=_X("state");EX[TX]=!0,qY=function(e,t){if(hX(e,TX))throw new fX(mX);return t.facade=e,uX(e,TX,t),t},QY=function(e){return hX(e,TX)?e[TX]:{}},$Y=function(e){return hX(e,TX)}}var RX={set:qY,get:QY,has:$Y,enforce:function(e){return $Y(e)?QY(e):qY(e,{})},getterFor:function(e){return function(t){var n;if(!lX(t)||(n=QY(t)).type!==e)throw new fX("Incompatible receiver, "+e+" required");return n}}},vX=vK,yX=Function.prototype,bX=yX.apply,CX=yX.call,IX="object"==typeof Reflect&&Reflect.apply||(vX?CX.bind(bX):function(){return CX.apply(bX,arguments)}),AX=DK,wX=AK,OX=function(e){if("Function"===AX(e))return wX(e)},NX={},DX={},PX={}.propertyIsEnumerable,LX=Object.getOwnPropertyDescriptor,kX=LX&&!PX.call({1:2},1);DX.f=kX?function(e){var t=LX(this,e);return!!t&&t.enumerable}:PX;var MX=eH,UX=EH,VX=DX,xX=eX,FX=WK,BX=FY,jX=mY,GX=aH,WX=Object.getOwnPropertyDescriptor;NX.f=MX?WX:function(e,t){if(e=FX(e),t=BX(t),GX)try{return WX(e,t)}catch(e){}if(jX(e,t))return xX(!UX(VX.f,e,t),e[t])};var KX=RK,HX=JK,YX=/#|\.prototype\./,XX=function(e,t){var n=zX[JX(e)];return n===qX||n!==ZX&&(HX(t)?KX(t):!!t)},JX=XX.normalize=function(e){return String(e).replace(YX,".").toLowerCase()},zX=XX.data={},ZX=XX.NATIVE="N",qX=XX.POLYFILL="P",QX=XX,$X=JH,eJ=vK,tJ=OX(OX.bind),nJ=function(e,t){return $X(e),void 0===t?e:eJ?tJ(e,t):function(){return e.apply(t,arguments)}},iJ=YK,rJ=IX,oJ=OX,sJ=JK,aJ=NX.f,cJ=QX,dJ=mH,lJ=nJ,uJ=iX,hJ=mY,pJ=function(e){var t=function(n,i,r){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(n);case 2:return new e(n,i)}return new e(n,i,r)}return rJ(e,this,arguments)};return t.prototype=e.prototype,t},_J=function(e,t){var n,i,r,o,s,a,c,d,l,u=e.target,h=e.global,p=e.stat,_=e.proto,E=h?iJ:p?iJ[u]:iJ[u]&&iJ[u].prototype,m=h?dJ:dJ[u]||uJ(dJ,u,{})[u],f=m.prototype;for(o in t)i=!(n=cJ(h?o:u+(p?".":"#")+o,e.forced))&&E&&hJ(E,o),a=m[o],i&&(c=e.dontCallGetSet?(l=aJ(E,o))&&l.value:E[o]),s=i&&c?c:t[o],(n||_||typeof a!=typeof s)&&(d=e.bind&&i?lJ(s,iJ):e.wrap&&i?pJ(s):_&&sJ(s)?oJ(s):s,(e.sham||s&&s.sham||a&&a.sham)&&uJ(d,"sham",!0),uJ(m,o,d),_&&(hJ(dJ,r=u+"Prototype")||uJ(dJ,r,{}),uJ(dJ[r],o,s),e.real&&f&&(n||!f[o])&&uJ(f,o,s)))},EJ=eH,mJ=mY,fJ=Function.prototype,gJ=EJ&&Object.getOwnPropertyDescriptor,SJ=mJ(fJ,"name"),TJ={EXISTS:SJ,PROPER:SJ&&"something"===function(){}.name,CONFIGURABLE:SJ&&(!EJ||EJ&&gJ(fJ,"name").configurable)},RJ={},vJ=Math.ceil,yJ=Math.floor,bJ=Math.trunc||function(e){var t=+e;return(t>0?yJ:vJ)(t)},CJ=function(e){var t=+e;return t!=t||0===t?0:bJ(t)},IJ=CJ,AJ=Math.max,wJ=Math.min,OJ=function(e,t){var n=IJ(e);return n<0?AJ(n+t,0):wJ(n,t)},NJ=CJ,DJ=Math.min,PJ=function(e){return function(e){var t=NJ(e);return t>0?DJ(t,9007199254740991):0}(e.length)},LJ=WK,kJ=OJ,MJ=PJ,UJ=function(e){return function(t,n,i){var r=LJ(t),o=MJ(r);if(0===o)return!e&&-1;var s,a=kJ(i,o);if(e&&n!=n){for(;o>a;)if((s=r[a++])!=s)return!0}else for(;o>a;a++)if((e||a in r)&&r[a]===n)return e||a||0;return!e&&-1}},VJ={includes:UJ(!0),indexOf:UJ(!1)},xJ=mY,FJ=WK,BJ=VJ.indexOf,jJ=aX,GJ=AK([].push),WJ=function(e,t){var n,i=FJ(e),r=0,o=[];for(n in i)!xJ(jJ,n)&&xJ(i,n)&&GJ(o,n);for(;t.length>r;)xJ(i,n=t[r++])&&(~BJ(o,n)||GJ(o,n));return o},KJ=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],HJ=WJ,YJ=KJ,XJ=Object.keys||function(e){return HJ(e,YJ)},JJ=eH,zJ=cH,ZJ=tH,qJ=hH,QJ=WK,$J=XJ;RJ.f=JJ&&!zJ?Object.defineProperties:function(e,t){qJ(e);for(var n,i=QJ(t),r=$J(t),o=r.length,s=0;o>s;)ZJ.f(e,n=r[s++],i[n]);return e};var ez,tz=RH("document","documentElement"),nz=hH,iz=RJ,rz=KJ,oz=aX,sz=tz,az=oH,cz="prototype",dz="script",lz=sX("IE_PROTO"),uz=function(){},hz=function(e){return"<"+dz+">"+e+"</"+dz+">"},pz=function(e){e.write(hz("")),e.close();var t=e.parentWindow.Object;return e=null,t},_z=function(){try{ez=new ActiveXObject("htmlfile")}catch(e){}var e,t,n;_z="undefined"!=typeof document?document.domain&&ez?pz(ez):(t=az("iframe"),n="java"+dz+":",t.style.display="none",sz.appendChild(t),t.src=String(n),(e=t.contentWindow.document).open(),e.write(hz("document.F=Object")),e.close(),e.F):pz(ez);for(var i=rz.length;i--;)delete _z[cz][rz[i]];return _z()};oz[lz]=!0;var Ez,mz,fz,gz=Object.create||function(e,t){var n;return null!==e?(uz[cz]=nz(e),n=new uz,uz[cz]=null,n[lz]=e):n=_z(),void 0===t?n:iz.f(n,t)},Sz=!RK((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Tz=mY,Rz=JK,vz=pY,yz=Sz,bz=sX("IE_PROTO"),Cz=Object,Iz=Cz.prototype,Az=yz?Cz.getPrototypeOf:function(e){var t=vz(e);if(Tz(t,bz))return t[bz];var n=t.constructor;return Rz(n)&&t instanceof n?n.prototype:t instanceof Cz?Iz:null},wz=iX,Oz=function(e,t,n,i){return i&&i.enumerable?e[t]=n:wz(e,t,n),e},Nz=RK,Dz=JK,Pz=$K,Lz=gz,kz=Az,Mz=Oz,Uz=NY("iterator"),Vz=!1;CL([])&&("next"in(fz=CL(aK=[]).call(aK))?(mz=kz(kz(fz)))!==Object.prototype&&(Ez=mz):Vz=!0);var xz=!Pz(Ez)||Nz((function(){var e={};return Ez[Uz].call(e)!==e}));Dz((Ez=xz?{}:Lz(Ez))[Uz])||Mz(Ez,Uz,(function(){return this}));var Fz={IteratorPrototype:Ez,BUGGY_SAFARI_ITERATORS:Vz},Bz={};Bz[NY("toStringTag")]="z";var jz="[object z]"===String(Bz),Gz=jz,Wz=JK,Kz=DK,Hz=NY("toStringTag"),Yz=Object,Xz="Arguments"===Kz(function(){return arguments}()),Jz=Gz?Kz:function(e){var t,n,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=Yz(e),Hz))?n:Xz?Kz(t):"Object"===(i=Kz(t))&&Wz(t.callee)?"Arguments":i},zz=Jz,Zz=jz?{}.toString:function(){return"[object "+zz(this)+"]"},qz=jz,Qz=tH.f,$z=iX,eZ=mY,tZ=Zz,nZ=NY("toStringTag"),iZ=function(e,t,n,i){var r=n?e:e&&e.prototype;r&&(eZ(r,nZ)||Qz(r,nZ,{configurable:!0,value:t}),i&&!qz&&$z(r,"toString",tZ))},rZ=Fz.IteratorPrototype,oZ=gz,sZ=eX,aZ=iZ,cZ=KK,dZ=function(){return this},lZ=_J,uZ=EH,hZ=Az,pZ=iZ,_Z=Oz,EZ=KK,mZ=TJ.PROPER,fZ=Fz.BUGGY_SAFARI_ITERATORS,gZ=NY("iterator"),SZ="keys",TZ="values",RZ="entries",vZ=function(){return this},yZ=function(e,t,n,i,r,o,s){!function(e,t,n,i){var r=t+" Iterator";e.prototype=oZ(rZ,{next:sZ(+!i,n)}),aZ(e,r,!1,!0),cZ[r]=dZ}(n,t,i);var a,c,d,l=function(e){if(e===r&&E)return E;if(!fZ&&e&&e in p)return p[e];switch(e){case SZ:case TZ:case RZ:return function(){return new n(this,e)}}return function(){return new n(this)}},u=t+" Iterator",h=!1,p=e.prototype,_=p[gZ]||p["@@iterator"]||r&&p[r],E=!fZ&&_||l(r),m="Array"===t&&p.entries||_;if(m&&(a=hZ(m.call(new e)))!==Object.prototype&&a.next&&(pZ(a,u,!0,!0),EZ[u]=vZ),mZ&&r===TZ&&_&&_.name!==TZ&&(h=!0,E=function(){return uZ(_,this)}),r)if(c={values:l(TZ),keys:o?E:l(SZ),entries:l(RZ)},s)for(d in c)(fZ||h||!(d in p))&&_Z(p,d,c[d]);else lZ({target:t,proto:!0,forced:fZ||h},c);return s&&p[gZ]!==E&&_Z(p,gZ,E,{name:r}),EZ[t]=E,c},bZ=function(e,t){return{value:e,done:t}},CZ=WK,IZ=KK,AZ=RX;tH.f;var wZ=yZ,OZ=bZ,NZ="Array Iterator",DZ=AZ.set,PZ=AZ.getterFor(NZ);wZ(Array,"Array",(function(e,t){DZ(this,{type:NZ,target:CZ(e),index:0,kind:t})}),(function(){var e=PZ(this),t=e.target,n=e.index++;if(!t||n>=t.length)return e.target=null,OZ(void 0,!0);switch(e.kind){case"keys":return OZ(n,!1);case"values":return OZ(t[n],!1)}return OZ([n,t[n]],!1)}),"values"),IZ.Arguments=IZ.Array;var LZ=YK,kZ=iZ,MZ=KK;for(var UZ in{CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0})kZ(LZ[UZ],UZ),MZ[UZ]=MZ.Array;var VZ=YK,xZ=mH,FZ=function(e,t){var n=xZ[e+"Prototype"],i=n&&n[t];if(i)return i;var r=VZ[e],o=r&&r.prototype;return o&&o[t]},BZ=FZ("Array","values"),jZ=Jz,GZ=mY,WZ=vH,KZ=BZ,HZ=Array.prototype,YZ={DOMTokenList:!0,NodeList:!0},XZ=gK((function(e){var t=gp(e);return e===HZ||WZ(HZ,e)&&t===gp(HZ)||GZ(YZ,jZ(e))?KZ:t})),JZ=YK;_J({global:!0,forced:JZ.globalThis!==JZ},{globalThis:JZ});var zZ=gK(YK);function ZZ(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,0==(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function qZ(e,t,n){for(let i=0;i<28;i+=7){const r=e>>>i,o=!(r>>>7==0&&0==t),s=255&(o?128|r:r);if(n.push(s),!o)return}const i=e>>>28&15|(7&t)<<4,r=!(t>>3==0);if(n.push(255&(r?128|i:i)),r){for(let e=3;e<31;e+=7){const i=t>>>e,r=!(i>>>7==0),o=255&(r?128|i:i);if(n.push(o),!r)return}n.push(t>>>31&1)}}const QZ=4294967296;function $Z(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let i=0,r=0;function o(t,o){const s=Number(e.slice(t,o));r*=n,i=i*n+s,i>=QZ&&(r+=i/QZ|0,i%=QZ)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),t?nq(i,r):tq(i,r)}function eq(e,t){var n=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t);if(e=n.lo,(t=n.hi)<=2097151)return String(QZ*t+e);const i=16777215&(e>>>24|t<<8),r=t>>16&65535;let o=(16777215&e)+6777216*i+6710656*r,s=i+8147497*r,a=2*r;const c=1e7;return o>=c&&(s+=Math.floor(o/c),o%=c),s>=c&&(a+=Math.floor(s/c),s%=c),a.toString()+iq(s)+iq(o)}function tq(e,t){return{lo:0|e,hi:0|t}}function nq(e,t){return t=~t,e?e=1+~e:t+=1,tq(e,t)}const iq=e=>{const t=String(e);return"0000000".slice(t.length)+t};function rq(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(127&e|128),e>>=7;t.push(1)}}function oq(){let e=this.buf[this.pos++],t=127&e;if(0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,0==(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;0!=(128&e)&&t<10;t++)e=this.buf[this.pos++];if(0!=(128&e))throw new Error("invalid varint");return this.assertBounds(),t>>>0}const sq=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&(zZ.Deno||"object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),n=BigInt("9223372036854775807"),i=BigInt("0"),r=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const i="bigint"==typeof e?e:BigInt(e);if(i>n||i<t)throw new Error("invalid int64: ".concat(e));return i},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>r||t<i)throw new Error("invalid uint64: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)),uDec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0))}}return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),aq(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),cq(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),aq(e),$Z(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),cq(e),$Z(e)),dec:(e,t)=>function(e,t){let n=tq(e,t);const i=2147483648&n.hi;i&&(n=nq(n.lo,n.hi));const r=eq(n.lo,n.hi);return i?"-"+r:r}(e,t),uDec:(e,t)=>eq(e,t)}}();function aq(e){if(!/^-?[0-9]+$/.test(e))throw new Error("invalid int64: "+e)}function cq(e){if(!/^[0-9]+$/.test(e))throw new Error("invalid uint64: "+e)}var dq;function lq(e,t){switch(e){case dq.STRING:return"";case dq.BOOL:return!1;case dq.DOUBLE:case dq.FLOAT:return 0;case dq.INT64:case dq.UINT64:case dq.SFIXED64:case dq.FIXED64:case dq.SINT64:return t?"0":sq.zero;case dq.BYTES:return new Uint8Array(0);default:return 0}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(dq||(dq={}));const uq=2,hq=Symbol.for("reflect unsafe local");function pq(e,t){const n=e[t.localName].case;return void 0===n?n:t.fields.find((e=>e.localName===n))}function _q(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&void 0!==e[t]}function Eq(e,t){if(t.oneof){const n=e[t.oneof.localName];return n.case===t.localName?n.value:void 0}return e[t.localName]}function mq(e,t,n){t.oneof?e[t.oneof.localName]={case:t.localName,value:n}:e[t.localName]=n}function fq(e){for(const t of e.field)_q(t,"jsonName")||(t.jsonName=pK(t.name));e.nestedType.forEach(fq)}var gq=DK,Sq=Array.isArray||function(e){return"Array"===gq(e)},Tq=_J,Rq=Sq,vq=AK(Tr([])),yq=[1,2];Tq({target:"Array",proto:!0,forced:String(yq)===String(Tr(yq).call(yq))},{reverse:function(){return Rq(this)&&(this.length=this.length),vq(this)}});var bq=FZ("Array","reverse"),Cq=vH,Iq=bq,Aq=Array.prototype,wq=gK((function(e){var t=Tr(e);return e===Aq||Cq(Aq,e)&&t===Tr(Aq)?Iq:t}));function*Oq(e){switch(e.kind){case"file":for(const t of e.messages)yield t,yield*Oq(t);yield*e.enums,yield*e.services,yield*e.extensions;break;case"message":for(const t of e.nestedMessages)yield t,yield*Oq(t);yield*e.nestedEnums,yield*e.nestedExtensions}}function Nq(){const e=function(){const e=new Map,t=new Map,n=new Map;return{kind:"registry",types:e,extendees:t,[Symbol.iterator]:()=>XZ(e).call(e),get files(){return XZ(n).call(n)},addFile(e,t,i){if(n.set(e.proto.name,e),!t)for(const t of Oq(e))this.add(t);if(i)for(const n of e.dependencies)this.addFile(n,t,i)},add(n){if("extension"==n.kind){let e=t.get(n.extendee.typeName);e||t.set(n.extendee.typeName,e=new Map),e.set(n.number,n)}e.set(n.typeName,n)},get:t=>e.get(t),getFile:e=>n.get(e),getMessage(t){const n=e.get(t);return"message"==(null==n?void 0:n.kind)?n:void 0},getEnum(t){const n=e.get(t);return"enum"==(null==n?void 0:n.kind)?n:void 0},getExtension(t){const n=e.get(t);return"extension"==(null==n?void 0:n.kind)?n:void 0},getExtensionFor(e,n){var i;return null===(i=t.get(e.typeName))||void 0===i?void 0:i.get(n)},getService(t){const n=e.get(t);return"service"==(null==n?void 0:n.kind)?n:void 0}}}();for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];if(!n.length)return e;if("$typeName"in n[0]&&"google.protobuf.FileDescriptorSet"==n[0].$typeName){for(const t of n[0].file)Qq(t,e);return e}if("$typeName"in n[0]){const t=n[0],i=n[1],o=new Set;for(const n of wq(r=[t,...function t(n){const r=[];for(const t of n.dependency){if(null!=e.getFile(t))continue;if(o.has(t))continue;const s=i(t);if(!s)throw new Error("Unable to resolve ".concat(t,", imported by ").concat(n.name));"kind"in s?e.addFile(s,!1,!0):(o.add(s.name),r.push(s))}return r.concat(...r.map(t))}(t)]).call(r)){var r;Qq(n,e)}}else for(const t of n)for(const n of t.files)e.addFile(n);return e}const Dq=998,Pq=999,Lq=9999,kq=9,Mq=10,Uq=11,Vq=12,xq=14,Fq=3,Bq=2,jq=1,Gq=0,Wq=1,Kq=2,Hq=3,Yq=1,Xq=2,Jq=1,zq=2,Zq=1001,qq={998:{fieldPresence:1,enumType:2,repeatedFieldEncoding:2,utf8Validation:3,messageEncoding:1,jsonFormat:2,enforceNamingStyle:2,defaultSymbolVisibility:1},999:{fieldPresence:2,enumType:1,repeatedFieldEncoding:1,utf8Validation:2,messageEncoding:1,jsonFormat:1,enforceNamingStyle:2,defaultSymbolVisibility:1},1e3:{fieldPresence:1,enumType:1,repeatedFieldEncoding:1,utf8Validation:2,messageEncoding:1,jsonFormat:1,enforceNamingStyle:2,defaultSymbolVisibility:1},1001:{fieldPresence:1,enumType:1,repeatedFieldEncoding:1,utf8Validation:2,messageEncoding:1,jsonFormat:1,enforceNamingStyle:1,defaultSymbolVisibility:2}};function Qq(e,t){var n,i;const r={kind:"file",proto:e,deprecated:null!==(i=null===(n=e.options)||void 0===n?void 0:n.deprecated)&&void 0!==i&&i,edition:sQ(e),name:e.name.replace(/\.proto$/,""),dependencies:aQ(e,t),enums:[],messages:[],extensions:[],services:[],toString:()=>"file ".concat(e.name)},o=new Map,s={get:e=>o.get(e),add(e){var t;EQ(!0===(null===(t=e.proto.options)||void 0===t?void 0:t.mapEntry)),o.set(e.typeName,e)}};for(const n of e.enumType)tQ(n,r,void 0,t);for(const n of e.messageType)nQ(n,r,void 0,t,s);for(const n of e.service)iQ(n,r,t);$q(r,t);for(const e of XZ(o).call(o))eQ(e,t,s);for(const e of r.messages)eQ(e,t,s),$q(e,t);t.addFile(r,!0)}function $q(e,t){switch(e.kind){case"file":for(const n of e.proto.extension){const i=oQ(n,e,t);e.extensions.push(i),t.add(i)}break;case"message":for(const n of e.proto.extension){const i=oQ(n,e,t);e.nestedExtensions.push(i),t.add(i)}for(const n of e.nestedMessages)$q(n,t)}}function eQ(e,t,n){const i=e.proto.oneofDecl.map((t=>function(e,t){return{kind:"oneof",proto:e,deprecated:!1,parent:t,fields:[],name:e.name,localName:mK(pK(e.name)),toString(){return"oneof ".concat(t.typeName,".").concat(this.name)}}}(t,e))),r=new Set;for(const o of e.proto.field){const s=lQ(o,i),a=oQ(o,e,t,s,n);e.fields.push(a),e.field[a.localName]=a,void 0===s?e.members.push(a):(s.fields.push(a),r.has(s)||(r.add(s),e.members.push(s)))}for(const t of i.filter((e=>r.has(e))))e.oneofs.push(t);for(const i of e.nestedMessages)eQ(i,t,n)}function tQ(e,t,n,i){var r,o,s,a,c;const d=function(e,t){const n=((i=e).substring(0,1)+i.substring(1).replace(/[A-Z]/g,(e=>"_"+e))).toLowerCase()+"_";var i;for(const e of t){if(!e.name.toLowerCase().startsWith(n))return;const t=e.name.substring(n.length);if(0==t.length)return;if(/^\d/.test(t))return}return n}(e.name,e.value),l={kind:"enum",proto:e,deprecated:null!==(o=null===(r=e.options)||void 0===r?void 0:r.deprecated)&&void 0!==o&&o,file:t,parent:n,open:!0,name:e.name,typeName:cQ(e,n,t),value:{},values:[],sharedPrefix:d,toString(){return"enum ".concat(this.typeName)}};l.open=function(e){var t;return Jq==_Q("enumType",{proto:e.proto,parent:null!==(t=e.parent)&&void 0!==t?t:e.file})}(l),i.add(l);for(const t of e.value){const e=t.name;XZ(l).push(l.value[t.number]={kind:"enum_value",proto:t,deprecated:null!==(a=null===(s=t.options)||void 0===s?void 0:s.deprecated)&&void 0!==a&&a,parent:l,name:e,localName:mK(null==d?e:e.substring(d.length)),number:t.number,toString:()=>"enum value ".concat(l.typeName,".").concat(e)})}(null!==(c=null==n?void 0:n.nestedEnums)&&void 0!==c?c:t.enums).push(l)}function nQ(e,t,n,i,r){var o,s,a,c;const d={kind:"message",proto:e,deprecated:null!==(s=null===(o=e.options)||void 0===o?void 0:o.deprecated)&&void 0!==s&&s,file:t,parent:n,name:e.name,typeName:cQ(e,n,t),fields:[],field:{},oneofs:[],members:[],nestedEnums:[],nestedMessages:[],nestedExtensions:[],toString(){return"message ".concat(this.typeName)}};!0===(null===(a=e.options)||void 0===a?void 0:a.mapEntry)?r.add(d):((null!==(c=null==n?void 0:n.nestedMessages)&&void 0!==c?c:t.messages).push(d),i.add(d));for(const n of e.enumType)tQ(n,t,d,i);for(const n of e.nestedType)nQ(n,t,d,i,r)}function iQ(e,t,n){var i,r;const o={kind:"service",proto:e,deprecated:null!==(r=null===(i=e.options)||void 0===i?void 0:i.deprecated)&&void 0!==r&&r,file:t,name:e.name,typeName:cQ(e,void 0,t),methods:[],method:{},toString(){return"service ".concat(this.typeName)}};t.services.push(o),n.add(o);for(const t of e.method){const e=rQ(t,o,n);o.methods.push(e),o.method[e.localName]=e}}function rQ(e,t,n){var i,r,o,s;let a;a=e.clientStreaming&&e.serverStreaming?"bidi_streaming":e.clientStreaming?"client_streaming":e.serverStreaming?"server_streaming":"unary";const c=n.getMessage(dQ(e.inputType)),d=n.getMessage(dQ(e.outputType));EQ(c,"invalid MethodDescriptorProto: input_type ".concat(e.inputType," not found")),EQ(d,"invalid MethodDescriptorProto: output_type ".concat(e.inputType," not found"));const l=e.name;return{kind:"rpc",proto:e,deprecated:null!==(r=null===(i=e.options)||void 0===i?void 0:i.deprecated)&&void 0!==r&&r,parent:t,name:l,localName:mK(l.length?mK(l[0].toLowerCase()+l.substring(1)):l),methodKind:a,input:c,output:d,idempotency:null!==(s=null===(o=e.options)||void 0===o?void 0:o.idempotencyLevel)&&void 0!==s?s:Gq,toString:()=>"rpc ".concat(t.typeName,".").concat(l)}}function oQ(e,t,n,i,r){var o,s,a;const c=void 0===r,d={kind:"field",proto:e,deprecated:null!==(s=null===(o=e.options)||void 0===o?void 0:o.deprecated)&&void 0!==s&&s,name:e.name,number:e.number,scalar:void 0,message:void 0,enum:void 0,presence:uQ(e,i,c,t),utf8Validation:pQ(e,t),listKind:void 0,mapKind:void 0,mapKey:void 0,delimitedEncoding:void 0,packed:void 0,longAsString:!1,getDefaultValue:void 0};if(c){const i="file"==t.kind?t:t.file,r="file"==t.kind?void 0:t,o=cQ(e,r,i);d.kind="extension",d.file=i,d.parent=r,d.oneof=void 0,d.typeName=o,d.jsonName="[".concat(o,"]"),d.toString=()=>"extension ".concat(o);const s=n.getMessage(dQ(e.extendee));EQ(s,"invalid FieldDescriptorProto: extendee ".concat(e.extendee," not found")),d.extendee=s}else{const n=t;EQ("message"==n.kind),d.parent=n,d.oneof=i,d.localName=i?pK(e.name):mK(pK(e.name)),d.jsonName=e.jsonName,d.toString=()=>"field ".concat(n.typeName,".").concat(e.name)}const l=e.label,u=e.type,h=null===(a=e.options)||void 0===a?void 0:a.jstype;if(l===Fq){const i=u==Uq?null==r?void 0:r.get(dQ(e.typeName)):void 0;if(i){d.fieldKind="map";const e=function(e){const t=e.fields.find((e=>1===e.number)),n=e.fields.find((e=>2===e.number));return EQ(t&&"scalar"==t.fieldKind&&t.scalar!=dq.BYTES&&t.scalar!=dq.FLOAT&&t.scalar!=dq.DOUBLE&&n&&"list"!=n.fieldKind&&"map"!=n.fieldKind),{key:t,value:n}}(i),t=e.key,n=e.value;return d.mapKey=t.scalar,d.mapKind=n.fieldKind,d.message=n.message,d.delimitedEncoding=!1,d.enum=n.enum,d.scalar=n.scalar,d}switch(d.fieldKind="list",u){case Uq:case Mq:d.listKind="message",d.message=n.getMessage(dQ(e.typeName)),EQ(d.message),d.delimitedEncoding=hQ(e,t);break;case xq:d.listKind="enum",d.enum=n.getEnum(dQ(e.typeName)),EQ(d.enum);break;default:d.listKind="scalar",d.scalar=u,d.longAsString=h==jq}return d.packed=function(e,t){if(e.label!=Fq)return!1;switch(e.type){case kq:case Vq:case Mq:case Uq:return!1}const n=e.options;return n&&_q(n,"packed")?n.packed:Yq==_Q("repeatedFieldEncoding",{proto:e,parent:t})}(e,t),d}switch(u){case Uq:case Mq:d.fieldKind="message",d.message=n.getMessage(dQ(e.typeName)),EQ(d.message,"invalid FieldDescriptorProto: type_name ".concat(e.typeName," not found")),d.delimitedEncoding=hQ(e,t),d.getDefaultValue=()=>{};break;case xq:{const t=n.getEnum(dQ(e.typeName));EQ(void 0!==t,"invalid FieldDescriptorProto: type_name ".concat(e.typeName," not found")),d.fieldKind="enum",d.enum=n.getEnum(dQ(e.typeName)),d.getDefaultValue=()=>_q(e,"defaultValue")?function(e,t){const n=XZ(e).find((e=>e.name===t));if(!n)throw new Error("cannot parse ".concat(e," default value: ").concat(t));return n.number}(t,e.defaultValue):void 0;break}default:d.fieldKind="scalar",d.scalar=u,d.longAsString=h==jq,d.getDefaultValue=()=>_q(e,"defaultValue")?function(e,t){switch(e){case dq.STRING:return t;case dq.BYTES:{const n=function(e){const t=[],n={tail:e,c:"",next(){return 0!=this.tail.length&&(this.c=this.tail[0],this.tail=this.tail.substring(1),!0)},take(e){if(this.tail.length>=e){const t=this.tail.substring(0,e);return this.tail=this.tail.substring(e),t}return!1}};for(;n.next();)if("\\"===n.c){if(n.next())switch(n.c){case"\\":t.push(n.c.charCodeAt(0));break;case"b":t.push(8);break;case"f":t.push(12);break;case"n":t.push(10);break;case"r":t.push(13);break;case"t":t.push(9);break;case"v":t.push(11);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{const e=n.c,i=n.take(2);if(!1===i)return!1;const r=parseInt(e+i,8);if(Number.isNaN(r))return!1;t.push(r);break}case"x":{const e=n.c,i=n.take(2);if(!1===i)return!1;const r=parseInt(e+i,16);if(Number.isNaN(r))return!1;t.push(r);break}case"u":{const e=n.c,i=n.take(4);if(!1===i)return!1;const r=parseInt(e+i,16);if(Number.isNaN(r))return!1;const o=new Uint8Array(4);new DataView(o.buffer).setInt32(0,r,!0),t.push(o[0],o[1],o[2],o[3]);break}case"U":{const e=n.c,i=n.take(8);if(!1===i)return!1;const r=sq.uEnc(e+i),o=new Uint8Array(8),s=new DataView(o.buffer);s.setInt32(0,r.lo,!0),s.setInt32(4,r.hi,!0),t.push(o[0],o[1],o[2],o[3],o[4],o[5],o[6],o[7]);break}}}else t.push(n.c.charCodeAt(0));return new Uint8Array(t)}(t);if(!1===n)throw new Error("cannot parse ".concat(dq[e]," default value: ").concat(t));return n}case dq.INT64:case dq.SFIXED64:case dq.SINT64:return sq.parse(t);case dq.UINT64:case dq.FIXED64:return sq.uParse(t);case dq.DOUBLE:case dq.FLOAT:switch(t){case"inf":return Number.POSITIVE_INFINITY;case"-inf":return Number.NEGATIVE_INFINITY;case"nan":return Number.NaN;default:return parseFloat(t)}case dq.BOOL:return"true"===t;case dq.INT32:case dq.UINT32:case dq.SINT32:case dq.FIXED32:case dq.SFIXED32:return parseInt(t,10)}}(u,e.defaultValue):void 0}return d}function sQ(e){switch(e.syntax){case"":case"proto2":return Dq;case"proto3":return Pq;case"editions":if(e.edition===Lq)return Zq;if(e.edition in qq)return e.edition;throw new Error("".concat(e.name,": unsupported edition"));default:throw new Error("".concat(e.name,': unsupported syntax "').concat(e.syntax,'"'))}}function aQ(e,t){return e.dependency.map((n=>{const i=t.getFile(n);if(!i)throw new Error("Cannot find ".concat(n,", imported by ").concat(e.name));return i}))}function cQ(e,t,n){let i;return i=t?"".concat(t.typeName,".").concat(e.name):n.proto.package.length>0?"".concat(n.proto.package,".").concat(e.name):"".concat(e.name),i}function dQ(e){return e.startsWith(".")?e.substring(1):e}function lQ(e,t){if(!_q(e,"oneofIndex"))return;if(e.proto3Optional)return;const n=t[e.oneofIndex];return EQ(n,"invalid FieldDescriptorProto: oneof #".concat(e.oneofIndex," for field #").concat(e.number," not found")),n}function uQ(e,t,n,i){if(e.label==Bq)return Hq;if(e.label==Fq)return Kq;if(t||e.proto3Optional)return Wq;if(n)return Wq;const r=_Q("fieldPresence",{proto:e,parent:i});return r!=Kq||e.type!=Uq&&e.type!=Mq?r:Wq}function hQ(e,t){return e.type==Mq||Xq==_Q("messageEncoding",{proto:e,parent:t})}function pQ(e,t){return zq==_Q("utf8Validation",{proto:e,parent:t})}function _Q(e,t){var n,i;const r=null===(n=t.proto.options)||void 0===n?void 0:n.features;if(r){const t=r[e];if(0!=t)return t}if("kind"in t){if("message"==t.kind)return _Q(e,null!==(i=t.parent)&&void 0!==i?i:t.file);const n=qq[t.edition];if(!n)throw new Error("feature default for edition ".concat(t.edition," not found"));return n[e]}return _Q(e,t.parent)}function EQ(e,t){if(!e)throw new Error(t)}function mQ(e){var t,n,i,r,o,s,a,c;const d=Object.create({visibility:0});return Object.assign(d,{$typeName:"google.protobuf.DescriptorProto",name:e.name,field:null!==(n=null===(t=e.field)||void 0===t?void 0:t.map(fQ))&&void 0!==n?n:[],extension:[],nestedType:null!==(r=null===(i=e.nestedType)||void 0===i?void 0:i.map(mQ))&&void 0!==r?r:[],enumType:null!==(s=null===(o=e.enumType)||void 0===o?void 0:o.map(SQ))&&void 0!==s?s:[],extensionRange:null!==(c=null===(a=e.extensionRange)||void 0===a?void 0:a.map((e=>Object.assign({$typeName:"google.protobuf.DescriptorProto.ExtensionRange"},e))))&&void 0!==c?c:[],oneofDecl:[],reservedRange:[],reservedName:[]})}function fQ(e){const t=Object.create({label:1,typeName:"",extendee:"",defaultValue:"",oneofIndex:0,jsonName:"",proto3Optional:!1});return Object.assign(t,Object.assign(Object.assign({$typeName:"google.protobuf.FieldDescriptorProto"},e),{options:e.options?gQ(e.options):void 0}))}function gQ(e){var t,n,i;const r=Object.create({ctype:0,packed:!1,jstype:0,lazy:!1,unverifiedLazy:!1,deprecated:!1,weak:!1,debugRedact:!1,retention:0});return Object.assign(r,Object.assign(Object.assign({$typeName:"google.protobuf.FieldOptions"},e),{targets:null!==(t=e.targets)&&void 0!==t?t:[],editionDefaults:null!==(i=null===(n=e.editionDefaults)||void 0===n?void 0:n.map((e=>Object.assign({$typeName:"google.protobuf.FieldOptions.EditionDefault"},e))))&&void 0!==i?i:[],uninterpretedOption:[]}))}function SQ(e){const t=Object.create({visibility:0});return Object.assign(t,{$typeName:"google.protobuf.EnumDescriptorProto",name:e.name,reservedName:[],reservedRange:[],value:e.value.map((e=>Object.assign({$typeName:"google.protobuf.EnumValueDescriptorProto"},e)))})}function TQ(e){const t=function(){if(!yQ){yQ=[];const e=bQ("std");for(let t=0;t<e.length;t++)yQ[e[t].charCodeAt(0)]=t;yQ["-".charCodeAt(0)]=e.indexOf("+"),yQ["_".charCodeAt(0)]=e.indexOf("/")}return yQ}();let n=3*e.length/4;"="==e[e.length-2]?n-=2:"="==e[e.length-1]&&(n-=1);let i,r=new Uint8Array(n),o=0,s=0,a=0;for(let n=0;n<e.length;n++){if(i=t[e.charCodeAt(n)],void 0===i)switch(e[n]){case"=":s=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string")}switch(s){case 0:a=i,s=1;break;case 1:r[o++]=a<<2|(48&i)>>4,a=i,s=2;break;case 2:r[o++]=(15&a)<<4|(60&i)>>2,a=i,s=3;break;case 3:r[o++]=(3&a)<<6|i,s=0}}if(1==s)throw Error("invalid base64 string");return r.subarray(0,o)}let RQ,vQ,yQ;function bQ(e){return RQ||(RQ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),vQ=RQ.slice(0,-2).concat("-","_")),"url"==e?vQ:RQ}_J({target:"Array",stat:!0},{isArray:Sq});var CQ=gK(mH.Array.isArray),IQ=TypeError,AQ=function(e){if(e>9007199254740991)throw new IQ("Maximum allowed index exceeded");return e},wQ=eH,OQ=tH,NQ=eX,DQ=function(e,t,n){wQ?OQ.f(e,t,NQ(0,n)):e[t]=n},PQ=eH,LQ=Sq,kQ=TypeError,MQ=Object.getOwnPropertyDescriptor,UQ=PQ&&!function(){if(void 0!==this)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(e){return e instanceof TypeError}}()?function(e,t){if(LQ(e)&&!MQ(e,"length").writable)throw new kQ("Cannot set read only .length");return e.length=t}:function(e,t){return e.length=t},VQ=JK,xQ=cY,FQ=AK(Function.toString);VQ(xQ.inspectSource)||(xQ.inspectSource=function(e){return FQ(e)});var BQ=xQ.inspectSource,jQ=AK,GQ=RK,WQ=JK,KQ=Jz,HQ=BQ,YQ=function(){},XQ=RH("Reflect","construct"),JQ=/^\s*(?:class|function)\b/,zQ=jQ(JQ.exec),ZQ=!JQ.test(YQ),qQ=function(e){if(!WQ(e))return!1;try{return XQ(YQ,[],e),!0}catch(e){return!1}},QQ=function(e){if(!WQ(e))return!1;switch(KQ(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return ZQ||!!zQ(JQ,HQ(e))}catch(e){return!0}};QQ.sham=!0;var $Q=!XQ||GQ((function(){var e;return qQ(qQ.call)||!qQ(Object)||!qQ((function(){e=!0}))||e}))?QQ:qQ,e$=Sq,t$=$Q,n$=$K,i$=NY("species"),r$=Array,o$=function(e,t){return new(function(e){var t;return e$(e)&&(t=e.constructor,(t$(t)&&(t===r$||e$(t.prototype))||n$(t)&&null===(t=t[i$]))&&(t=void 0)),void 0===t?r$:t}(e))(0===t?0:t)},s$=RK,a$=PH,c$=NY("species"),d$=function(e){return a$>=51||!s$((function(){var t=[];return(t.constructor={})[c$]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},l$=_J,u$=RK,h$=Sq,p$=$K,_$=pY,E$=PJ,m$=AQ,f$=DQ,g$=UQ,S$=o$,T$=d$,R$=PH,v$=NY("isConcatSpreadable"),y$=R$>=51||!u$((function(){var e=[];return e[v$]=!1,e.concat()[0]!==e})),b$=function(e){if(!p$(e))return!1;var t=e[v$];return void 0!==t?!!t:h$(e)};l$({target:"Array",proto:!0,arity:1,forced:!y$||!T$("concat")},{concat:function(e){var t,n,i,r,o,s=_$(this),a=S$(s,0),c=0;for(t=-1,i=arguments.length;t<i;t++)if(b$(o=-1===t?s:arguments[t]))for(r=E$(o),m$(c+r),n=0;n<r;n++,c++)n in o&&f$(a,c,o[n]);else m$(c+1),f$(a,c++,o);return g$(a,c),a}});var C$=Jz,I$=String,A$=function(e){if("Symbol"===C$(e))throw new TypeError("Cannot convert a Symbol value to a string");return I$(e)},w$={},O$=WJ,N$=KJ.concat("length","prototype");w$.f=Object.getOwnPropertyNames||function(e){return O$(e,N$)};var D$={},P$=AK([].slice),L$=DK,k$=WK,M$=w$.f,U$=P$,V$="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];D$.f=function(e){return V$&&"Window"===L$(e)?function(e){try{return M$(e)}catch(e){return U$(V$)}}(e):M$(k$(e))};var x$={};x$.f=Object.getOwnPropertySymbols;var F$=tH,B$={},j$=NY;B$.f=j$;var G$=mH,W$=mY,K$=B$,H$=tH.f,Y$=function(e){var t=G$.Symbol||(G$.Symbol={});W$(t,e)||H$(t,e,{value:K$.f(e)})},X$=EH,J$=RH,z$=NY,Z$=Oz,q$=function(){var e=J$("Symbol"),t=e&&e.prototype,n=t&&t.valueOf,i=z$("toPrimitive");t&&!t[i]&&Z$(t,i,(function(e){return X$(n,this)}),{arity:1})},Q$=nJ,$$=UK,e0=pY,t0=PJ,n0=o$,i0=DQ,r0=function(e){var t=1===e,n=2===e,i=3===e,r=4===e,o=6===e,s=7===e,a=5===e||o;return function(c,d,l){for(var u,h,p=e0(c),_=$$(p),E=t0(_),m=Q$(d,l),f=0,g=0,S=t?n0(c,E):n||s?n0(c,0):void 0;E>f;f++)if((a||f in _)&&(h=m(u=_[f],f,p),e))if(t)i0(S,f,h);else if(h)switch(e){case 3:return!0;case 5:return u;case 6:return f;case 2:i0(S,g++,u)}else switch(e){case 4:return!1;case 7:i0(S,g++,u)}return o?-1:i||r?r:S}},o0={forEach:r0(0),map:r0(1),filter:r0(2),some:r0(3),every:r0(4),find:r0(5),findIndex:r0(6),filterReject:r0(7)},s0=_J,a0=YK,c0=EH,d0=AK,l0=eH,u0=UH,h0=RK,p0=mY,_0=vH,E0=hH,m0=WK,f0=FY,g0=A$,S0=eX,T0=gz,R0=XJ,v0=w$,y0=D$,b0=x$,C0=NX,I0=tH,A0=RJ,w0=DX,O0=Oz,N0=lY,D0=aX,P0=RY,L0=NY,k0=B$,M0=Y$,U0=q$,V0=iZ,x0=RX,F0=o0.forEach,B0=sX("hidden"),j0="Symbol",G0="prototype",W0=x0.set,K0=x0.getterFor(j0),H0=Object[G0],Y0=a0.Symbol,X0=Y0&&Y0[G0],J0=a0.RangeError,z0=a0.TypeError,Z0=a0.QObject,q0=C0.f,Q0=I0.f,$0=y0.f,e1=w0.f,t1=d0([].push),n1=N0("symbols"),i1=N0("op-symbols"),r1=N0("wks"),o1=!Z0||!Z0[G0]||!Z0[G0].findChild,s1=function(e,t,n){var i=q0(H0,t);return i&&delete H0[t],Q0(e,t,n),i&&e!==H0&&Q0(H0,t,i),e},a1=l0&&h0((function(){return 7!==T0(Q0({},"a",{get:function(){return Q0(this,"a",{value:7}).a}})).a}))?s1:Q0,c1=function(e,t){var n=n1[e]=T0(X0);return W0(n,{type:j0,tag:e,description:t}),l0||(n.description=t),n},d1=function(e,t,n){e===H0&&d1(i1,t,n),E0(e);var i=f0(t);return E0(n),p0(n1,i)?(("enumerable"in n?!n.enumerable:!p0(e,i)||p0(e,B0)&&e[B0][i])?(p0(e,B0)||Q0(e,B0,S0(1,T0(null))),e[B0][i]=!0):(p0(e,B0)&&e[B0][i]&&(e[B0][i]=!1),n=T0(n,{enumerable:S0(0,!1)})),a1(e,i,n)):Q0(e,i,n)},l1=function(e,t){E0(e);var n=m0(t),i=R0(n).concat(_1(n));return F0(i,(function(t){l0&&!c0(u1,n,t)||d1(e,t,n[t])})),e},u1=function(e){var t=f0(e),n=c0(e1,this,t);return!(this===H0&&p0(n1,t)&&!p0(i1,t))&&(!(n||!p0(this,t)||!p0(n1,t)||p0(this,B0)&&this[B0][t])||n)},h1=function(e,t){var n=m0(e),i=f0(t);if(n!==H0||!p0(n1,i)||p0(i1,i)){var r=q0(n,i);return!r||!p0(n1,i)||p0(n,B0)&&n[B0][i]||(r.enumerable=!0),r}},p1=function(e){var t=$0(m0(e)),n=[];return F0(t,(function(e){p0(n1,e)||p0(D0,e)||t1(n,e)})),n},_1=function(e){var t=e===H0,n=$0(t?i1:m0(e)),i=[];return F0(n,(function(e){!p0(n1,e)||t&&!p0(H0,e)||t1(i,n1[e])})),i};u0||(O0(X0=(Y0=function(){if(_0(X0,this))throw new z0("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?g0(arguments[0]):void 0,t=P0(e),n=function(e){var i=void 0===this?a0:this;i===H0&&c0(n,i1,e),p0(i,B0)&&p0(i[B0],t)&&(i[B0][t]=!1);var r=S0(1,e);try{a1(i,t,r)}catch(e){if(!(e instanceof J0))throw e;s1(i,t,r)}};return l0&&o1&&a1(H0,t,{configurable:!0,set:n}),c1(t,e)})[G0],"toString",(function(){return K0(this).tag})),O0(Y0,"withoutSetter",(function(e){return c1(P0(e),e)})),w0.f=u1,I0.f=d1,A0.f=l1,C0.f=h1,v0.f=y0.f=p1,b0.f=_1,k0.f=function(e){return c1(L0(e),e)},l0&&function(e,t,n){F$.f(e,t,n)}(X0,"description",{configurable:!0,get:function(){return K0(this).description}})),s0({global:!0,constructor:!0,wrap:!0,forced:!u0,sham:!u0},{Symbol:Y0}),F0(R0(r1),(function(e){M0(e)})),s0({target:j0,stat:!0,forced:!u0},{useSetter:function(){o1=!0},useSimple:function(){o1=!1}}),s0({target:"Object",stat:!0,forced:!u0,sham:!l0},{create:function(e,t){return void 0===t?T0(e):l1(T0(e),t)},defineProperty:d1,defineProperties:l1,getOwnPropertyDescriptor:h1}),s0({target:"Object",stat:!0,forced:!u0},{getOwnPropertyNames:p1}),U0(),V0(Y0,j0),D0[B0]=!0;var E1=UH&&!!Symbol.for&&!!Symbol.keyFor,m1=_J,f1=RH,g1=mY,S1=A$,T1=lY,R1=E1,v1=T1("string-to-symbol-registry"),y1=T1("symbol-to-string-registry");m1({target:"Symbol",stat:!0,forced:!R1},{for:function(e){var t=S1(e);if(g1(v1,t))return v1[t];var n=f1("Symbol")(t);return v1[t]=n,y1[n]=t,n}});var b1=_J,C1=mY,I1=GH,A1=KH,w1=E1,O1=lY("symbol-to-string-registry");b1({target:"Symbol",stat:!0,forced:!w1},{keyFor:function(e){if(!I1(e))throw new TypeError(A1(e)+" is not a symbol");if(C1(O1,e))return O1[e]}});var N1=$K,D1=RX.get,P1=AK,L1=mY,k1=SyntaxError,M1=parseInt,U1=String.fromCharCode,V1=P1("".charAt),x1=P1("".slice),F1=P1(/./.exec),B1={'\\"':'"',"\\\\":"\\","\\/":"/","\\b":"\b","\\f":"\f","\\n":"\n","\\r":"\r","\\t":"\t"},j1=/^[\da-f]{4}$/i,G1=/^[\u0000-\u001F]$/,W1=!RK((function(){var e="9007199254740993",t=JSON.rawJSON(e);return!JSON.isRawJSON(t)||JSON.stringify(t)!==e})),K1=_J,H1=RH,Y1=IX,X1=EH,J1=AK,z1=RK,Z1=Sq,q1=JK,Q1=GH,$1=DK,e2=A$,t2=P$,n2=function(e,t){for(var n=!0,i="";t<e.length;){var r=V1(e,t);if("\\"===r){var o=x1(e,t,t+2);if(L1(B1,o))i+=B1[o],t+=2;else{if("\\u"!==o)throw new k1('Unknown escape sequence: "'+o+'"');var s=x1(e,t+=2,t+4);if(!F1(j1,s))throw new k1("Bad Unicode escape at: "+t);i+=U1(M1(s,16)),t+=4}}else{if('"'===r){n=!1,t++;break}if(F1(G1,r))throw new k1("Bad control character in string literal at: "+t);i+=r,t++}}if(n)throw new k1("Unterminated string at: "+t);return{value:i,end:t}},i2=RY,r2=UH,o2=W1,s2=String,a2=H1("JSON","stringify"),c2=J1(/./.exec),d2=J1("".charAt),l2=J1("".charCodeAt),u2=J1("".replace),h2=J1("".slice),p2=J1([].push),_2=J1(1.1.toString),E2=/[\uD800-\uDFFF]/g,m2=/^[\uD800-\uDBFF]$/,f2=/^[\uDC00-\uDFFF]$/,g2=i2(),S2=g2.length,T2=!r2||z1((function(){var e=H1("Symbol")("stringify detection");return"[null]"!==a2([e])||"{}"!==a2({a:e})||"{}"!==a2(Object(e))})),R2=z1((function(){return'"\\udf06\\ud834"'!==a2("\udf06\ud834")||'"\\udead"'!==a2("\udead")})),v2=T2?function(e,t){var n=t2(arguments),i=b2(t);if(q1(i)||void 0!==e&&!Q1(e))return n[1]=function(e,t){if(q1(i)&&(t=X1(i,this,s2(e),t)),!Q1(t))return t},Y1(a2,null,n)}:a2,y2=function(e,t,n){var i=d2(n,t-1),r=d2(n,t+1);return c2(m2,e)&&!c2(f2,r)||c2(f2,e)&&!c2(m2,i)?"\\u"+_2(l2(e,0),16):e},b2=function(e){if(q1(e))return e;if(Z1(e)){for(var t=e.length,n=[],i=0;i<t;i++){var r=e[i];"string"==typeof r?p2(n,r):"number"!=typeof r&&"Number"!==$1(r)&&"String"!==$1(r)||p2(n,e2(r))}var o=n.length,s=!0;return function(e,t){if(s)return s=!1,t;if(Z1(this))return t;for(var i=0;i<o;i++)if(n[i]===e)return t}}};a2&&K1({target:"JSON",stat:!0,arity:3,forced:T2||R2||!o2},{stringify:function(e,t,n){var i=b2(t),r=[],o=v2(e,(function(e,t){var n=q1(i)?X1(i,this,s2(e),t):t;return!o2&&function(e){if(!N1(e))return!1;var t=D1(e);return!!t&&"RawJSON"===t.type}(n)?g2+(p2(r,n.rawJSON)-1):n}),n);if("string"!=typeof o)return o;if(R2&&(o=u2(o,E2,y2)),o2)return o;for(var s="",a=o.length,c=0;c<a;c++){var d=d2(o,c);if('"'===d){var l=n2(o,++c).end-1,u=h2(o,c,l);s+=h2(u,0,S2)===g2?r[h2(u,S2)]:'"'+u+'"',c=l}else s+=d}return s}});var C2=x$,I2=pY;_J({target:"Object",stat:!0,forced:!UH||RK((function(){C2.f(1)}))},{getOwnPropertySymbols:function(e){var t=C2.f;return t?t(I2(e)):[]}}),Y$("asyncDispose"),Y$("asyncIterator"),Y$("dispose"),Y$("hasInstance"),Y$("isConcatSpreadable"),Y$("iterator"),Y$("match"),Y$("matchAll"),Y$("replace"),Y$("search"),Y$("species"),Y$("split");var A2=q$;Y$("toPrimitive"),A2();var w2=RH,O2=iZ;Y$("toStringTag"),O2(w2("Symbol"),"Symbol"),Y$("unscopables"),iZ(YK.JSON,"JSON",!0);var N2=mH.Symbol,D2=NY,P2=tH.f,L2=D2("metadata"),k2=Function.prototype;void 0===k2[L2]&&P2(k2,L2,{value:null}),Y$("metadata");var M2=N2,U2=AK,V2=RH("Symbol"),x2=V2.keyFor,F2=U2(V2.prototype.valueOf),B2=V2.isRegisteredSymbol||function(e){try{return void 0!==x2(F2(e))}catch(e){return!1}};_J({target:"Symbol",stat:!0},{isRegisteredSymbol:B2});for(var j2=lY,G2=RH,W2=AK,K2=GH,H2=NY,Y2=G2("Symbol"),X2=Y2.isWellKnownSymbol,J2=G2("Object","getOwnPropertyNames"),z2=W2(Y2.prototype.valueOf),Z2=j2("wks"),q2=0,Q2=J2(Y2),$2=Q2.length;q2<$2;q2++)try{var e3=Q2[q2];K2(Y2[e3])&&H2(e3)}catch(FC){}var t3=function(e){if(X2&&X2(e))return!0;try{for(var t=z2(e),n=0,i=J2(Z2),r=i.length;n<r;n++)if(Z2[i[n]]==t)return!0}catch(e){}return!1};_J({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:t3}),Y$("customMatcher"),Y$("observable"),_J({target:"Symbol",stat:!0,name:"isRegisteredSymbol"},{isRegistered:B2}),_J({target:"Symbol",stat:!0,name:"isWellKnownSymbol",forced:!0},{isWellKnown:t3}),Y$("matcher"),Y$("metadataKey"),Y$("patternMatch"),Y$("replaceAll");var n3=gK(M2),i3=AK,r3=CJ,o3=A$,s3=BK,a3=i3("".charAt),c3=i3("".charCodeAt),d3=i3("".slice),l3=function(e){return function(t,n){var i,r,o=o3(s3(t)),s=r3(n),a=o.length;return s<0||s>=a?e?"":void 0:(i=c3(o,s))<55296||i>56319||s+1===a||(r=c3(o,s+1))<56320||r>57343?e?a3(o,s):i:e?d3(o,s,s+2):r-56320+(i-55296<<10)+65536}},u3=(l3(!1),l3(!0)),h3=A$,p3=RX,_3=yZ,E3=bZ,m3="String Iterator",f3=p3.set,g3=p3.getterFor(m3);_3(String,"String",(function(e){f3(this,{type:m3,string:h3(e),index:0})}),(function(){var e,t=g3(this),n=t.string,i=t.index;return i>=n.length?E3(void 0,!0):(e=u3(n,i),t.index+=e.length,E3(e,!1))}));var S3=Jz,T3=qH,R3=VK,v3=KK,y3=NY("iterator"),b3=function(e){if(!R3(e))return T3(e,y3)||T3(e,"@@iterator")||v3[S3(e)]},C3=gK(b3),I3=pY,A3=PJ,w3=UQ,O3=AQ;_J({target:"Array",proto:!0,arity:1,forced:RK((function(){return 4294967297!==[].push.call({length:4294967296},1)}))||!function(){try{Object.defineProperty([],"length",{writable:!1}).push()}catch(e){return e instanceof TypeError}}()},{push:function(e){var t=I3(this),n=A3(t),i=arguments.length;O3(n+i);for(var r=0;r<i;r++)t[n]=arguments[r],n++;return w3(t,n),n}});var N3=FZ("Array","push"),D3=vH,P3=N3,L3=Array.prototype,k3=gK((function(e){var t=e.push;return e===L3||D3(L3,e)&&t===L3.push?P3:t})),M3=_J,U3=Sq,V3=$Q,x3=$K,F3=OJ,B3=PJ,j3=WK,G3=DQ,W3=UQ,K3=NY,H3=P$,Y3=d$("slice"),X3=K3("species"),J3=Array,z3=Math.max;M3({target:"Array",proto:!0,forced:!Y3},{slice:function(e,t){var n,i,r,o=j3(this),s=B3(o),a=F3(e,s),c=F3(void 0===t?s:t,s);if(U3(o)&&(n=o.constructor,(V3(n)&&(n===J3||U3(n.prototype))||x3(n)&&null===(n=n[X3]))&&(n=void 0),n===J3||void 0===n))return H3(o,a,c);for(i=new(void 0===n?J3:n)(z3(c-a,0)),r=0;a<c;a++,r++)a in o&&G3(i,r,o[a]);return W3(i,r),i}});var Z3=FZ("Array","slice"),q3=vH,Q3=Z3,$3=Array.prototype,e5=gK((function(e){var t=e.slice;return e===$3||q3($3,e)&&t===$3.slice?Q3:t})),t5=EH,n5=hH,i5=qH,r5=function(e,t,n){var i,r;n5(e);try{if(!(i=i5(e,"return"))){if("throw"===t)throw n;return n}i=t5(i,e)}catch(e){r=!0,i=e}if("throw"===t)throw n;if(r)throw i;return n5(i),n},o5=hH,s5=r5,a5=KK,c5=NY("iterator"),d5=Array.prototype,l5=EH,u5=JH,h5=hH,p5=KH,_5=b3,E5=TypeError,m5=nJ,f5=EH,g5=pY,S5=function(e,t,n,i){try{return i?t(o5(n)[0],n[1]):t(n)}catch(t){s5(e,"throw",t)}},T5=function(e){return void 0!==e&&(a5.Array===e||d5[c5]===e)},R5=$Q,v5=PJ,y5=DQ,b5=UQ,C5=function(e,t){var n=arguments.length<2?_5(e):t;if(u5(n))return h5(l5(n,e));throw new E5(p5(e)+" is not iterable")},I5=b3,A5=r5,w5=Array,O5=NY("iterator"),N5=!1;try{var D5=0,P5={next:function(){return{done:!!D5++}},return:function(){N5=!0}};P5[O5]=function(){return this},Array.from(P5,(function(){throw 2}))}catch(FC){}_J({target:"Array",stat:!0,forced:!function(e,t){try{if(!t&&!N5)return!1}catch(e){return!1}var n=!1;try{var i={};i[O5]=function(){return{next:function(){return{done:n=!0}}}},e(i)}catch(e){}return n}((function(e){Array.from(e)}))},{from:function(e){var t=R5(this),n=arguments.length,i=n>1?arguments[1]:void 0,r=void 0!==i;r&&(i=m5(i,n>2?arguments[2]:void 0));var o,s,a,c,d,l,u=g5(e),h=I5(u),p=0;if(!h||this===w5&&T5(h))for(o=v5(u),s=t?new this(o):w5(o);o>p;p++)l=r?i(u[p],p):u[p],y5(s,p,l);else for(s=t?new this:[],d=(c=C5(u,h)).next;!(a=f5(d,c)).done;p++){l=r?S5(c,i,[a.value,p],!0):a.value;try{y5(s,p,l)}catch(e){A5(c,"throw",e)}}return b5(s,p),s}});var L5=gK(mH.Array.from);function k5(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function M5(e,t){return function(e){if(CQ(e))return e}(e)||function(e,t){var n=null==e?null:void 0!==n3&&C3(e)||e["@@iterator"];if(null!=n){var i,r,o,s,a=[],c=!0,d=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=o.call(n)).done)&&(k3(a).call(a,i.value),a.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw r}}return a}}(e,t)||function(e,t){if(e){var n;if("string"==typeof e)return k5(e,t);var i=e5(n={}.toString.call(e)).call(n,8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?L5(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?k5(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var U5=KH,V5=TypeError,x5=P$,F5=Math.floor,B5=function(e,t){var n=e.length;if(n<8)for(var i,r,o=1;o<n;){for(r=o,i=e[o];r&&t(e[r-1],i)>0;)e[r]=e[--r];r!==o++&&(e[r]=i)}else for(var s=F5(n/2),a=B5(x5(e,0,s),t),c=B5(x5(e,s),t),d=a.length,l=c.length,u=0,h=0;u<d||h<l;)e[u+h]=u<d&&h<l?t(a[u],c[h])<=0?a[u++]:c[h++]:u<d?a[u++]:c[h++];return e},j5=B5,G5=RK,W5=function(e,t){var n=[][e];return!!n&&G5((function(){n.call(null,t||function(){return 1},1)}))},K5=CH.match(/firefox\/(\d+)/i),H5=!!K5&&+K5[1],Y5=/MSIE|Trident/.test(CH),X5=CH.match(/AppleWebKit\/(\d+)\./),J5=!!X5&&+X5[1],z5=_J,Z5=AK,q5=JH,Q5=pY,$5=PJ,e4=function(e,t){if(!delete e[t])throw new V5("Cannot delete property "+U5(t)+" of "+U5(e))},t4=A$,n4=RK,i4=j5,r4=W5,o4=H5,s4=Y5,a4=PH,c4=J5,d4=[],l4=Z5(n_(d4)),u4=Z5(d4.push),h4=n4((function(){n_(d4).call(d4,void 0)})),p4=n4((function(){n_(d4).call(d4,null)})),_4=r4("sort"),E4=!n4((function(){if(a4)return a4<70;if(!(o4&&o4>3)){if(s4)return!0;if(c4)return c4<603;var e,t,n,i,r="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(i=0;i<47;i++)d4.push({k:t+i,v:n})}for(n_(d4).call(d4,(function(e,t){return t.v-e.v})),i=0;i<d4.length;i++)t=d4[i].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return"DGBEFHACIJK"!==r}}));z5({target:"Array",proto:!0,forced:h4||!p4||!_4||!E4},{sort:function(e){void 0!==e&&q5(e);var t=Q5(this);if(E4)return void 0===e?l4(t):l4(t,e);var n,i,r=[],o=$5(t);for(i=0;i<o;i++)i in t&&u4(r,t[i]);for(i4(r,function(e){return function(t,n){if(void 0===n)return-1;if(void 0===t)return 1;if(void 0!==e)return+e(t,n)||0;var i=t4(t),r=t4(n);return i===r?0:i>r?1:-1}}(e)),n=$5(r),i=0;i<n;)t[i]=r[i++];for(;i<o;)e4(t,i++);return t}});var m4=FZ("Array","sort"),f4=vH,g4=m4,S4=Array.prototype,T4=gK((function(e){var t=n_(e);return e===S4||f4(S4,e)&&t===n_(S4)?g4:t})),R4=FZ("Array","keys"),v4=Jz,y4=mY,b4=vH,C4=R4,I4=Array.prototype,A4={DOMTokenList:!0,NodeList:!0},w4=gK((function(e){var t=CL(e);return e===I4||b4(I4,e)&&t===CL(I4)||y4(A4,v4(e))?C4:t}));function O4(e,t){return!(null===e||"object"!=typeof e||!("$typeName"in e)||"string"!=typeof e.$typeName||void 0!==t&&t.typeName!==e.$typeName)}var N4=_J,D4=Vi(VJ),P4=RK,L4=P4((function(){var e;return!Vi(e=Array(1)).call(e)})),k4=P4((function(){var e;return Vi(e=[,1]).call(e,void 0,1)}));N4({target:"Array",proto:!0,forced:L4||k4},{includes:function(e){return D4(this,e,arguments.length>1?arguments[1]:void 0)}});var M4=FZ("Array","includes"),U4=$K,V4=DK,x4=NY("match"),F4=TypeError,B4=NY("match"),j4=_J,G4=function(e){if(function(e){var t;return U4(e)&&(void 0!==(t=e[x4])?!!t:"RegExp"===V4(e))}(e))throw new F4("The method doesn't accept regular expressions");return e},W4=BK,K4=A$,H4=AK("".indexOf);j4({target:"String",proto:!0,forced:!function(e){var t=/./;try{"/./"[e](t)}catch(n){try{return t[B4]=!1,"/./"[e](t)}catch(e){}}return!1}("includes")},{includes:function(e){return!!~H4(K4(W4(this)),K4(G4(e)),arguments.length>1?arguments[1]:void 0)}});var Y4=FZ("String","includes"),X4=vH,J4=M4,z4=Y4,Z4=Array.prototype,q4=String.prototype,Q4=gK((function(e){var t=Vi(e);return e===Z4||X4(Z4,e)&&t===Vi(Z4)?J4:"string"==typeof e||e===q4||X4(q4,e)&&t===Vi(q4)?z4:t}));const $4=["FieldValueInvalidError","FieldListRangeError","ForeignFieldError"];class e6 extends Error{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"FieldValueInvalidError";super(t),this.name=n,this.field=()=>e}}function t6(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function n6(e,t){var n,i,r,o;if(t6(e)&&hq in e&&"add"in e&&"field"in e&&"function"==typeof e.field){if(void 0!==t){const s=t,a=e.field();return s.listKind==a.listKind&&s.scalar===a.scalar&&(null===(n=s.message)||void 0===n?void 0:n.typeName)===(null===(i=a.message)||void 0===i?void 0:i.typeName)&&(null===(r=s.enum)||void 0===r?void 0:r.typeName)===(null===(o=a.enum)||void 0===o?void 0:o.typeName)}return!0}return!1}function i6(e,t){var n,i,r,o;if(t6(e)&&hq in e&&"has"in e&&"field"in e&&"function"==typeof e.field){if(void 0!==t){const s=t,a=e.field();return s.mapKey===a.mapKey&&s.mapKind==a.mapKind&&s.scalar===a.scalar&&(null===(n=s.message)||void 0===n?void 0:n.typeName)===(null===(i=a.message)||void 0===i?void 0:i.typeName)&&(null===(r=s.enum)||void 0===r?void 0:r.typeName)===(null===(o=a.enum)||void 0===o?void 0:o.typeName)}return!0}return!1}function r6(e,t){return t6(e)&&hq in e&&"desc"in e&&t6(e.desc)&&"message"===e.desc.kind&&(void 0===t||e.desc.typeName==t.typeName)}const o6=Symbol.for("@bufbuild/protobuf/text-encoding");function s6(){if(null==zZ[o6]){const e=new zZ.TextEncoder,t=new zZ.TextDecoder;let n;zZ[o6]={encodeUtf8:t=>e.encode(t),decodeUtf8:(e,i)=>i?(void 0===n&&(n=new zZ.TextDecoder("utf-8",{fatal:!0})),n.decode(e)):t.decode(e),checkUtf8(e){try{return encodeURIComponent(e),!0}catch(e){return!1}}}}return zZ[o6]}var a6;!function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(a6||(a6={}));const c6=34028234663852886e22,d6=-34028234663852886e22,l6=4294967295,u6=2147483647,h6=-2147483648;class p6{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:s6().encodeUtf8;this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(m6(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return E6(e),rq(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.encodeUtf8(e);return this.uint32(t.byteLength),this.raw(t)}float(e){!function(e){if("string"==typeof e){const t=e;if(e=Number(e),Number.isNaN(e)&&"NaN"!==t)throw new Error("invalid float32: "+t)}else if("number"!=typeof e)throw new Error("invalid float32: "+typeof e);if(Number.isFinite(e)&&(e>c6||e<d6))throw new Error("invalid float32: "+e)}(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){m6(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){E6(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return E6(e),rq(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=sq.enc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=sq.uEnc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=sq.enc(e);return qZ(t.lo,t.hi,this.buf),this}sint64(e){const t=sq.enc(e),n=t.hi>>31;return qZ(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){const t=sq.uEnc(e);return qZ(t.lo,t.hi,this.buf),this}}class _6{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s6().decodeUtf8;this.decodeUtf8=t,this.varint64=ZZ,this.uint32=oq,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){const e=this.pos,t=this.uint32(),n=this.pos-e;if(n>5||5==n&&this.buf[this.pos-1]>15)throw new Error("illegal tag: varint overflows uint32");const i=t>>>3,r=7&t;if(i<=0||r>5)throw new Error("illegal tag: field no "+i+" wire type "+r);return[i,r]}skip(e,t){let n=this.pos;switch(e){case a6.Varint:for(;128&this.buf[this.pos++];);break;case a6.Bit64:this.pos+=4;case a6.Bit32:this.pos+=4;break;case a6.LengthDelimited:let n=this.uint32();this.pos+=n;break;case a6.StartGroup:for(;;){const e=M5(this.tag(),2),n=e[0],i=e[1];if(i===a6.EndGroup){if(void 0!==t&&n!==t)throw new Error("invalid end group tag");break}this.skip(i,n)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return sq.dec(...this.varint64())}uint64(){return sq.uDec(...this.varint64())}sint64(){let e=M5(this.varint64(),2),t=e[0],n=e[1],i=-(1&t);return t=(t>>>1|(1&n)<<31)^i,n=n>>>1^i,sq.dec(t,n)}bool(){let e=M5(this.varint64(),2),t=e[0],n=e[1];return 0!==t||0!==n}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return sq.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return sq.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(e){return this.decodeUtf8(this.bytes(),e)}}function E6(e){if("string"==typeof e)e=Number(e);else if("number"!=typeof e)throw new Error("invalid int32: "+typeof e);if(!Number.isInteger(e)||e>u6||e<h6)throw new Error("invalid int32: "+e)}function m6(e){if("string"==typeof e)e=Number(e);else if("number"!=typeof e)throw new Error("invalid uint32: "+typeof e);if(!Number.isInteger(e)||e>l6||e<0)throw new Error("invalid uint32: "+e)}function f6(e,t){const n="list"==e.fieldKind?n6(t,e):"map"==e.fieldKind?i6(t,e):S6(e,t);if(!0===n)return;let i;switch(e.fieldKind){case"list":i="expected ".concat(b6(e),", got ").concat(v6(t));break;case"map":i="expected ".concat(C6(e),", got ").concat(v6(t));break;default:i=R6(e,t,n)}return new e6(e,i)}function g6(e,t,n){const i=S6(e,n);if(!0!==i)return new e6(e,"list item #".concat(t+1,": ").concat(R6(e,n,i)))}function S6(e,t){return void 0!==e.scalar?T6(t,e.scalar):void 0!==e.enum?e.enum.open?Number.isInteger(t):XZ(e.enum).some((e=>e.number===t)):r6(t,e.message)}function T6(e,t){switch(t){case dq.DOUBLE:return"number"==typeof e;case dq.FLOAT:return"number"==typeof e&&(!(!Number.isNaN(e)&&Number.isFinite(e))||!(e>c6||e<d6)||"".concat(e.toFixed()," out of range"));case dq.INT32:case dq.SFIXED32:case dq.SINT32:return!("number"!=typeof e||!Number.isInteger(e))&&(!(e>u6||e<h6)||"".concat(e.toFixed()," out of range"));case dq.FIXED32:case dq.UINT32:return!("number"!=typeof e||!Number.isInteger(e))&&(!(e>l6||e<0)||"".concat(e.toFixed()," out of range"));case dq.BOOL:return"boolean"==typeof e;case dq.STRING:return"string"==typeof e&&(s6().checkUtf8(e)||"invalid UTF8");case dq.BYTES:return e instanceof Uint8Array;case dq.INT64:case dq.SFIXED64:case dq.SINT64:if("bigint"==typeof e||"number"==typeof e||"string"==typeof e&&e.length>0)try{return sq.parse(e),!0}catch(t){return"".concat(e," out of range")}return!1;case dq.FIXED64:case dq.UINT64:if("bigint"==typeof e||"number"==typeof e||"string"==typeof e&&e.length>0)try{return sq.uParse(e),!0}catch(t){return"".concat(e," out of range")}return!1}}function R6(e,t,n){return n="string"==typeof n?": ".concat(n):", got ".concat(v6(t)),void 0!==e.scalar?"expected ".concat(function(e){switch(e){case dq.STRING:return"string";case dq.BOOL:return"boolean";case dq.INT64:case dq.SINT64:case dq.SFIXED64:return"bigint (int64)";case dq.UINT64:case dq.FIXED64:return"bigint (uint64)";case dq.BYTES:return"Uint8Array";case dq.DOUBLE:return"number (float64)";case dq.FLOAT:return"number (float32)";case dq.FIXED32:case dq.UINT32:return"number (uint32)";case dq.INT32:case dq.SFIXED32:case dq.SINT32:return"number (int32)"}}(e.scalar))+n:void 0!==e.enum?"expected ".concat(e.enum.toString())+n:"expected ".concat(y6(e.message))+n}function v6(e){switch(typeof e){case"object":return null===e?"null":e instanceof Uint8Array?"Uint8Array(".concat(e.length,")"):Array.isArray(e)?"Array(".concat(e.length,")"):n6(e)?b6(e.field()):i6(e)?C6(e.field()):r6(e)?y6(e.desc):O4(e)?"message ".concat(e.$typeName):"object";case"string":return e.length>30?"string":'"'.concat(e.split('"').join('\\"'),'"');case"boolean":case"number":return String(e);case"bigint":return String(e)+"n";default:return typeof e}}function y6(e){return"ReflectMessage (".concat(e.typeName,")")}function b6(e){switch(e.listKind){case"message":return"ReflectList (".concat(e.message.toString(),")");case"enum":return"ReflectList (".concat(e.enum.toString(),")");case"scalar":return"ReflectList (".concat(dq[e.scalar],")")}}function C6(e){switch(e.mapKind){case"message":return"ReflectMap (".concat(dq[e.mapKey],", ").concat(e.message.toString(),")");case"enum":return"ReflectMap (".concat(dq[e.mapKey],", ").concat(e.enum.toString(),")");case"scalar":return"ReflectMap (".concat(dq[e.mapKey],", ").concat(dq[e.scalar],")")}}function I6(e){const t=e.fields[0];return w6(e.typeName)&&void 0!==t&&"scalar"==t.fieldKind&&"value"==t.name&&1==t.number}function A6(e){switch(e.typeName){case"google.protobuf.Any":case"google.protobuf.Timestamp":case"google.protobuf.Duration":case"google.protobuf.FieldMask":case"google.protobuf.Struct":case"google.protobuf.Value":case"google.protobuf.ListValue":return!0;default:return I6(e)}}function w6(e){var t;return e.startsWith("google.protobuf.")&&Q4(t=["DoubleValue","FloatValue","Int64Value","UInt64Value","Int32Value","UInt32Value","BoolValue","StringValue","BytesValue"]).call(t,e.substring(16))}const O6=999,N6=998,D6=2;function P6(e,t){if(O4(t,e))return t;const n=function(e){let t;if(function(e){switch(e.file.edition){case O6:return!1;case N6:return!0;default:return e.fields.some((e=>e.presence!=D6&&"message"!=e.fieldKind&&!e.oneof))}}(e)){const n=B6.get(e);let i,r;if(n)i=n.prototype,r=n.members;else{i={},r=new Set;for(const t of e.members)"oneof"!=t.kind&&("scalar"!=t.fieldKind&&"enum"!=t.fieldKind||t.presence!=D6&&(r.add(t),i[t.localName]=j6(t)));B6.set(e,{prototype:i,members:r})}t=Object.create(i),t.$typeName=e.typeName;for(const n of e.members)if(!r.has(n)){if("field"==n.kind){if("message"==n.fieldKind)continue;if(("scalar"==n.fieldKind||"enum"==n.fieldKind)&&n.presence!=D6)continue}t[n.localName]=j6(n)}}else{t={$typeName:e.typeName};for(const n of e.members)"oneof"!=n.kind&&n.presence!=D6||(t[n.localName]=j6(n))}return t}(e);return void 0!==t&&function(e,t,n){for(const i of e.members){let e,r=n[i.localName];if(null!=r){if("oneof"==i.kind){const t=pq(n,i);if(!t)continue;e=t,r=Eq(n,t)}else e=i;switch(e.fieldKind){case"message":r=U6(e,r);break;case"scalar":r=L6(e,r);break;case"list":r=M6(e,r);break;case"map":r=k6(e,r)}mq(t,e,r)}}}(e,n,t),n}function L6(e,t){return e.scalar==dq.BYTES?V6(t):t}function k6(e,t){if(t6(t)){if(e.scalar==dq.BYTES)return x6(t,V6);if("message"==e.mapKind)return x6(t,(t=>U6(e,t)))}return t}function M6(e,t){if(Array.isArray(t)){if(e.scalar==dq.BYTES)return t.map(V6);if("message"==e.listKind)return t.map((t=>U6(e,t)))}return t}function U6(e,t){if("message"==e.fieldKind&&!e.oneof&&I6(e.message))return L6(e.message.fields[0],t);if(t6(t)){if("google.protobuf.Struct"==e.message.typeName&&"google.protobuf.Value"!==e.parent.typeName)return t;if(!O4(t,e.message))return P6(e.message,t)}return t}function V6(e){return Array.isArray(e)?new Uint8Array(e):e}function x6(e,t){const n={};for(const i of Object.entries(e))n[i[0]]=t(i[1]);return n}const F6=Symbol(),B6=new WeakMap;function j6(e){if("oneof"==e.kind)return{case:void 0};if("list"==e.fieldKind)return[];if("map"==e.fieldKind)return{};if("message"==e.fieldKind)return F6;const t=e.getDefaultValue();return void 0!==t?"scalar"==e.fieldKind&&e.longAsString?t.toString():t:"scalar"==e.fieldKind?lq(e.scalar,e.longAsString):XZ(e.enum)[0].number}function G6(e,t){return new K6(e,t,!(arguments.length>2&&void 0!==arguments[2])||arguments[2])}const W6=new WeakMap;class K6{get sortedFields(){var e;const t=W6.get(this.desc);if(t)return t;const n=T4(e=this.desc.fields.concat()).call(e,((e,t)=>e.number-t.number));return W6.set(this.desc,n),n}constructor(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];this.lists=new Map,this.maps=new Map,this.check=n,this.desc=e,this.message=this[hq]=null!=t?t:P6(e),this.fields=e.fields,this.oneofs=e.oneofs,this.members=e.members}findNumber(e){return this._fieldsByNumber||(this._fieldsByNumber=new Map(this.desc.fields.map((e=>[e.number,e])))),this._fieldsByNumber.get(e)}oneofCase(e){return H6(this.message,e),pq(this.message,e)}isSet(e){return H6(this.message,e),function(e,t){const n=t.localName;if(t.oneof)return e[t.oneof.localName].case===n;if(t.presence!=uq)return void 0!==e[n]&&Object.prototype.hasOwnProperty.call(e,n);switch(t.fieldKind){case"list":return e[n].length>0;case"map":return Object.keys(e[n]).length>0;case"scalar":return!function(e,t){switch(e){case dq.BOOL:return!1===t;case dq.STRING:return""===t;case dq.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(t.scalar,e[n]);case"enum":return e[n]!==XZ(t.enum)[0].number}throw new Error("message field with implicit presence")}(this.message,e)}clear(e){H6(this.message,e),function(e,t){const n=t.localName;if(t.oneof){const i=t.oneof.localName;e[i].case===n&&(e[i]={case:void 0})}else if(t.presence!=uq)delete e[n];else switch(t.fieldKind){case"map":e[n]={};break;case"list":e[n]=[];break;case"enum":e[n]=XZ(t.enum)[0].number;break;case"scalar":e[n]=lq(t.scalar,t.longAsString)}}(this.message,e)}get(e){H6(this.message,e);const t=Eq(this.message,e);switch(e.fieldKind){case"list":let n=this.lists.get(e);return n&&n[hq]===t||this.lists.set(e,n=new Y6(e,t,this.check)),n;case"map":let i=this.maps.get(e);return i&&i[hq]===t||this.maps.set(e,i=new X6(e,t,this.check)),i;case"message":return z6(e,t,this.check);case"scalar":return void 0===t?lq(e.scalar,!1):t9(e,t);case"enum":return null!=t?t:XZ(e.enum)[0].number}}set(e,t){if(H6(this.message,e),this.check){const n=f6(e,t);if(n)throw n}let n;n="message"==e.fieldKind?J6(e,t):i6(t)||n6(t)?t[hq]:n9(e,t),mq(this.message,e,n)}getUnknown(){return this.message.$unknown}setUnknown(e){this.message.$unknown=e}}function H6(e,t){if(t.parent.typeName!==e.$typeName)throw new e6(t,"cannot use ".concat(t.toString()," with message ").concat(e.$typeName),"ForeignFieldError")}class Y6{field(){return this._field}get size(){return this._arr.length}constructor(e,t,n){this._field=e,this._arr=this[hq]=t,this.check=n}get(e){const t=this._arr[e];return void 0===t?void 0:q6(this._field,t,this.check)}set(e,t){if(e<0||e>=this._arr.length)throw new e6(this._field,"list item #".concat(e+1,": out of range"));if(this.check){const n=g6(this._field,e,t);if(n)throw n}this._arr[e]=Z6(this._field,t)}add(e){if(this.check){const t=g6(this._field,this._arr.length,e);if(t)throw t}this._arr.push(Z6(this._field,e))}clear(){this._arr.splice(0,this._arr.length)}[Symbol.iterator](){return XZ(this).call(this)}keys(){var e;return w4(e=this._arr).call(e)}*values(){for(const e of this._arr)yield q6(this._field,e,this.check)}*entries(){for(let e=0;e<this._arr.length;e++)yield[e,q6(this._field,this._arr[e],this.check)]}}class X6{constructor(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];this.obj=this[hq]=null!=t?t:{},this.check=n,this._field=e}field(){return this._field}set(e,t){if(this.check){const n=function(e,t,n){const i=T6(t,e.mapKey);if(!0!==i)return new e6(e,"invalid map key: ".concat(R6({scalar:e.mapKey},t,i)));const r=S6(e,n);return!0!==r?new e6(e,"map entry ".concat(v6(t),": ").concat(R6(e,n,r))):void 0}(this._field,e,t);if(n)throw n}return this.obj[$6(e)]=function(e,t){return"message"==e.mapKind?J6(e,t):n9(e,t)}(this._field,t),this}delete(e){const t=$6(e),n=Object.prototype.hasOwnProperty.call(this.obj,t);return n&&delete this.obj[t],n}clear(){for(const e of Object.keys(this.obj))delete this.obj[e]}get(e){let t=this.obj[$6(e)];return void 0!==t&&(t=Q6(this._field,t,this.check)),t}has(e){return Object.prototype.hasOwnProperty.call(this.obj,$6(e))}*keys(){for(const e of Object.keys(this.obj))yield e9(e,this._field.mapKey)}*entries(){for(const e of Object.entries(this.obj))yield[e9(e[0],this._field.mapKey),Q6(this._field,e[1],this.check)]}[Symbol.iterator](){return this.entries()}get size(){return Object.keys(this.obj).length}*values(){for(const e of Object.values(this.obj))yield Q6(this._field,e,this.check)}forEach(e,t){for(const n of this.entries())e.call(t,n[1],n[0],this)}}function J6(e,t){return r6(t)?w6(t.message.$typeName)&&!e.oneof&&"message"==e.fieldKind?t.message.value:"google.protobuf.Struct"==t.desc.typeName&&"google.protobuf.Value"!=e.parent.typeName?r9(t.message):t.message:t}function z6(e,t,n){return void 0!==t&&(I6(e.message)&&!e.oneof&&"message"==e.fieldKind?t={$typeName:e.message.typeName,value:t9(e.message.fields[0],t)}:"google.protobuf.Struct"==e.message.typeName&&"google.protobuf.Value"!=e.parent.typeName&&t6(t)&&(t=i9(t))),new K6(e.message,t,n)}function Z6(e,t){return"message"==e.listKind?J6(e,t):n9(e,t)}function q6(e,t,n){return"message"==e.listKind?z6(e,t,n):t9(e,t)}function Q6(e,t,n){return"message"==e.mapKind?z6(e,t,n):t}function $6(e){return"string"==typeof e||"number"==typeof e?e:String(e)}function e9(e,t){switch(t){case dq.STRING:return e;case dq.INT32:case dq.FIXED32:case dq.UINT32:case dq.SFIXED32:case dq.SINT32:{const t=Number.parseInt(e);if(Number.isFinite(t))return t;break}case dq.BOOL:switch(e){case"true":return!0;case"false":return!1}break;case dq.UINT64:case dq.FIXED64:try{return sq.uParse(e)}catch(e){}break;default:try{return sq.parse(e)}catch(e){}}return e}function t9(e,t){switch(e.scalar){case dq.INT64:case dq.SFIXED64:case dq.SINT64:"longAsString"in e&&e.longAsString&&"string"==typeof t&&(t=sq.parse(t));break;case dq.FIXED64:case dq.UINT64:"longAsString"in e&&e.longAsString&&"string"==typeof t&&(t=sq.uParse(t))}return t}function n9(e,t){switch(e.scalar){case dq.INT64:case dq.SFIXED64:case dq.SINT64:"longAsString"in e&&e.longAsString?t=String(t):"string"!=typeof t&&"number"!=typeof t||(t=sq.parse(t));break;case dq.FIXED64:case dq.UINT64:"longAsString"in e&&e.longAsString?t=String(t):"string"!=typeof t&&"number"!=typeof t||(t=sq.uParse(t))}return t}function i9(e){const t={$typeName:"google.protobuf.Struct",fields:{}};if(t6(e))for(const i of Object.entries(e)){var n=M5(i,2);const e=n[0],r=n[1];t.fields[e]=s9(r)}return t}function r9(e){const t={};for(const i of Object.entries(e.fields)){var n=M5(i,2);const e=n[0],r=n[1];t[e]=o9(r)}return t}function o9(e){switch(e.kind.case){case"structValue":return r9(e.kind.value);case"listValue":return XZ(e.kind.value).map(o9);case"nullValue":case void 0:return null;default:return e.kind.value}}function s9(e){const t={$typeName:"google.protobuf.Value",kind:{case:void 0}};switch(typeof e){case"number":t.kind={case:"numberValue",value:e};break;case"string":t.kind={case:"stringValue",value:e};break;case"boolean":t.kind={case:"boolValue",value:e};break;case"object":if(null===e){const e=0;t.kind={case:"nullValue",value:e}}else if(Array.isArray(e)){const n={$typeName:"google.protobuf.ListValue",values:[]};if(Array.isArray(e))for(const t of e)XZ(n).push(s9(t));t.kind={case:"listValue",value:n}}else t.kind={case:"structValue",value:i9(e)}}return t}const a9=3,c9={writeUnknownFields:!0};function d9(e,t,n){return l9(new p6,function(e){return e?Object.assign(Object.assign({},c9),e):c9}(n),G6(e,t)).finish()}function l9(e,t,n){var i;for(const i of n.sortedFields)if(n.isSet(i))u9(e,t,n,i);else if(i.presence==a9)throw new Error("cannot encode ".concat(i," to binary: required field not set"));if(t.writeUnknownFields)for(const t of null!==(i=n.getUnknown())&&void 0!==i?i:[]){const n=t.no,i=t.wireType,r=t.data;e.tag(n,i).raw(r)}return e}function u9(e,t,n,i){var r;switch(i.fieldKind){case"scalar":case"enum":h9(e,n.desc.typeName,i.name,null!==(r=i.scalar)&&void 0!==r?r:dq.INT32,i.number,n.get(i));break;case"list":!function(e,t,n,i){var r;if("message"==n.listKind){for(const r of i)p9(e,t,n,r);return}const o=null!==(r=n.scalar)&&void 0!==r?r:dq.INT32;if(n.packed){if(!i.size)return;e.tag(n.number,a6.LengthDelimited).fork();for(const t of i)E9(e,n.parent.typeName,n.name,o,t);e.join()}else for(const t of i)h9(e,n.parent.typeName,n.name,o,n.number,t)}(e,t,i,n.get(i));break;case"message":p9(e,t,i,n.get(i));break;case"map":for(const r of n.get(i)){var o=M5(r,2);_9(e,t,i,o[0],o[1])}}}function h9(e,t,n,i,r,o){E9(e.tag(r,function(e){switch(e){case dq.BYTES:case dq.STRING:return a6.LengthDelimited;case dq.DOUBLE:case dq.FIXED64:case dq.SFIXED64:return a6.Bit64;case dq.FIXED32:case dq.SFIXED32:case dq.FLOAT:return a6.Bit32;default:return a6.Varint}}(i)),t,n,i,o)}function p9(e,t,n,i){n.delimitedEncoding?l9(e.tag(n.number,a6.StartGroup),t,i).tag(n.number,a6.EndGroup):l9(e.tag(n.number,a6.LengthDelimited).fork(),t,i).join()}function _9(e,t,n,i,r){var o;switch(e.tag(n.number,a6.LengthDelimited).fork(),h9(e,n.parent.typeName,n.name,n.mapKey,1,i),n.mapKind){case"scalar":case"enum":h9(e,n.parent.typeName,n.name,null!==(o=n.scalar)&&void 0!==o?o:dq.INT32,2,r);break;case"message":l9(e.tag(2,a6.LengthDelimited).fork(),t,r).join()}e.join()}function E9(e,t,n,i,r){try{switch(i){case dq.STRING:e.string(r);break;case dq.BOOL:e.bool(r);break;case dq.DOUBLE:e.double(r);break;case dq.FLOAT:e.float(r);break;case dq.INT32:e.int32(r);break;case dq.INT64:e.int64(r);break;case dq.UINT64:e.uint64(r);break;case dq.FIXED64:e.fixed64(r);break;case dq.BYTES:e.bytes(r);break;case dq.FIXED32:e.fixed32(r);break;case dq.SFIXED32:e.sfixed32(r);break;case dq.SFIXED64:e.sfixed64(r);break;case dq.SINT64:e.sint64(r);break;case dq.UINT32:e.uint32(r);break;case dq.SINT32:e.sint32(r)}}catch(e){if(e instanceof Error)throw new Error("cannot encode field ".concat(t,".").concat(n," to binary: ").concat(e.message));throw e}}var m9=JH,f9=pY,g9=UK,S9=PJ,T9=TypeError,R9="Reduce of empty array with no initial value",v9=function(e){return function(t,n,i,r){var o=f9(t),s=g9(o),a=S9(o);if(m9(n),0===a&&i<2)throw new T9(R9);var c=e?a-1:0,d=e?-1:1;if(i<2)for(;;){if(c in s){r=s[c],c+=d;break}if(c+=d,e?c<0:a<=c)throw new T9(R9)}for(;e?c>=0:a>c;c+=d)c in s&&(r=n(r,s[c],c,o));return r}},y9={left:v9(!1),right:v9(!0)},b9=YK,C9=CH,I9=DK,A9=function(e){return C9.slice(0,e.length)===e},w9=A9("Bun/")?"BUN":A9("Cloudflare-Workers")?"CLOUDFLARE":A9("Deno/")?"DENO":A9("Node.js/")?"NODE":b9.Bun&&"string"==typeof Bun.version?"BUN":b9.Deno&&"object"==typeof Deno.version?"DENO":"process"===I9(b9.process)?"NODE":b9.window&&b9.document?"BROWSER":"REST",O9=y9.left;_J({target:"Array",proto:!0,forced:!("NODE"===w9)&&PH>79&&PH<83||!W5("reduce")},{reduce:function(e){var t=arguments.length;return O9(this,e,t,t>1?arguments[1]:void 0)}});var N9=FZ("Array","reduce"),D9=vH,P9=N9,L9=Array.prototype,k9=gK((function(e){var t=ar(e);return e===L9||D9(L9,e)&&t===ar(L9)?P9:t}));function M9(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return k9(i).call(i,((e,t)=>e.nestedMessages[t]),e.messages[t])}const U9=M9(function(e){const t=function(e){const t=Object.create({syntax:"",edition:0});return Object.assign(t,Object.assign(Object.assign({$typeName:"google.protobuf.FileDescriptorProto",dependency:[],publicDependency:[],weakDependency:[],optionDependency:[],service:[],extension:[]},e),{messageType:e.messageType.map(mQ),enumType:e.enumType.map(SQ)}))}(e);return t.messageType.forEach(fq),Nq(t,(()=>{})).getFile(t.name)}({name:"google/protobuf/descriptor.proto",package:"google.protobuf",messageType:[{name:"FileDescriptorSet",field:[{name:"file",number:1,type:11,label:3,typeName:".google.protobuf.FileDescriptorProto"}],extensionRange:[{start:536e6,end:536000001}]},{name:"FileDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"package",number:2,type:9,label:1},{name:"dependency",number:3,type:9,label:3},{name:"public_dependency",number:10,type:5,label:3},{name:"weak_dependency",number:11,type:5,label:3},{name:"option_dependency",number:15,type:9,label:3},{name:"message_type",number:4,type:11,label:3,typeName:".google.protobuf.DescriptorProto"},{name:"enum_type",number:5,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto"},{name:"service",number:6,type:11,label:3,typeName:".google.protobuf.ServiceDescriptorProto"},{name:"extension",number:7,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"options",number:8,type:11,label:1,typeName:".google.protobuf.FileOptions"},{name:"source_code_info",number:9,type:11,label:1,typeName:".google.protobuf.SourceCodeInfo"},{name:"syntax",number:12,type:9,label:1},{name:"edition",number:14,type:14,label:1,typeName:".google.protobuf.Edition"}]},{name:"DescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"field",number:2,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"extension",number:6,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"nested_type",number:3,type:11,label:3,typeName:".google.protobuf.DescriptorProto"},{name:"enum_type",number:4,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto"},{name:"extension_range",number:5,type:11,label:3,typeName:".google.protobuf.DescriptorProto.ExtensionRange"},{name:"oneof_decl",number:8,type:11,label:3,typeName:".google.protobuf.OneofDescriptorProto"},{name:"options",number:7,type:11,label:1,typeName:".google.protobuf.MessageOptions"},{name:"reserved_range",number:9,type:11,label:3,typeName:".google.protobuf.DescriptorProto.ReservedRange"},{name:"reserved_name",number:10,type:9,label:3},{name:"visibility",number:11,type:14,label:1,typeName:".google.protobuf.SymbolVisibility"}],nestedType:[{name:"ExtensionRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.ExtensionRangeOptions"}]},{name:"ReservedRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1}]}]},{name:"ExtensionRangeOptions",field:[{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"},{name:"declaration",number:2,type:11,label:3,typeName:".google.protobuf.ExtensionRangeOptions.Declaration",options:{retention:2}},{name:"features",number:50,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"verification",number:3,type:14,label:1,typeName:".google.protobuf.ExtensionRangeOptions.VerificationState",defaultValue:"UNVERIFIED",options:{retention:2}}],nestedType:[{name:"Declaration",field:[{name:"number",number:1,type:5,label:1},{name:"full_name",number:2,type:9,label:1},{name:"type",number:3,type:9,label:1},{name:"reserved",number:5,type:8,label:1},{name:"repeated",number:6,type:8,label:1}]}],enumType:[{name:"VerificationState",value:[{name:"DECLARATION",number:0},{name:"UNVERIFIED",number:1}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"FieldDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"number",number:3,type:5,label:1},{name:"label",number:4,type:14,label:1,typeName:".google.protobuf.FieldDescriptorProto.Label"},{name:"type",number:5,type:14,label:1,typeName:".google.protobuf.FieldDescriptorProto.Type"},{name:"type_name",number:6,type:9,label:1},{name:"extendee",number:2,type:9,label:1},{name:"default_value",number:7,type:9,label:1},{name:"oneof_index",number:9,type:5,label:1},{name:"json_name",number:10,type:9,label:1},{name:"options",number:8,type:11,label:1,typeName:".google.protobuf.FieldOptions"},{name:"proto3_optional",number:17,type:8,label:1}],enumType:[{name:"Type",value:[{name:"TYPE_DOUBLE",number:1},{name:"TYPE_FLOAT",number:2},{name:"TYPE_INT64",number:3},{name:"TYPE_UINT64",number:4},{name:"TYPE_INT32",number:5},{name:"TYPE_FIXED64",number:6},{name:"TYPE_FIXED32",number:7},{name:"TYPE_BOOL",number:8},{name:"TYPE_STRING",number:9},{name:"TYPE_GROUP",number:10},{name:"TYPE_MESSAGE",number:11},{name:"TYPE_BYTES",number:12},{name:"TYPE_UINT32",number:13},{name:"TYPE_ENUM",number:14},{name:"TYPE_SFIXED32",number:15},{name:"TYPE_SFIXED64",number:16},{name:"TYPE_SINT32",number:17},{name:"TYPE_SINT64",number:18}]},{name:"Label",value:[{name:"LABEL_OPTIONAL",number:1},{name:"LABEL_REPEATED",number:3},{name:"LABEL_REQUIRED",number:2}]}]},{name:"OneofDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"options",number:2,type:11,label:1,typeName:".google.protobuf.OneofOptions"}]},{name:"EnumDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"value",number:2,type:11,label:3,typeName:".google.protobuf.EnumValueDescriptorProto"},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.EnumOptions"},{name:"reserved_range",number:4,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto.EnumReservedRange"},{name:"reserved_name",number:5,type:9,label:3},{name:"visibility",number:6,type:14,label:1,typeName:".google.protobuf.SymbolVisibility"}],nestedType:[{name:"EnumReservedRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1}]}]},{name:"EnumValueDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"number",number:2,type:5,label:1},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.EnumValueOptions"}]},{name:"ServiceDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"method",number:2,type:11,label:3,typeName:".google.protobuf.MethodDescriptorProto"},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.ServiceOptions"}]},{name:"MethodDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"input_type",number:2,type:9,label:1},{name:"output_type",number:3,type:9,label:1},{name:"options",number:4,type:11,label:1,typeName:".google.protobuf.MethodOptions"},{name:"client_streaming",number:5,type:8,label:1,defaultValue:"false"},{name:"server_streaming",number:6,type:8,label:1,defaultValue:"false"}]},{name:"FileOptions",field:[{name:"java_package",number:1,type:9,label:1},{name:"java_outer_classname",number:8,type:9,label:1},{name:"java_multiple_files",number:10,type:8,label:1,defaultValue:"false",options:{}},{name:"java_generate_equals_and_hash",number:20,type:8,label:1,options:{deprecated:!0}},{name:"java_string_check_utf8",number:27,type:8,label:1,defaultValue:"false"},{name:"optimize_for",number:9,type:14,label:1,typeName:".google.protobuf.FileOptions.OptimizeMode",defaultValue:"SPEED"},{name:"go_package",number:11,type:9,label:1},{name:"cc_generic_services",number:16,type:8,label:1,defaultValue:"false"},{name:"java_generic_services",number:17,type:8,label:1,defaultValue:"false"},{name:"py_generic_services",number:18,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:23,type:8,label:1,defaultValue:"false"},{name:"cc_enable_arenas",number:31,type:8,label:1,defaultValue:"true"},{name:"objc_class_prefix",number:36,type:9,label:1},{name:"csharp_namespace",number:37,type:9,label:1},{name:"swift_prefix",number:39,type:9,label:1},{name:"php_class_prefix",number:40,type:9,label:1},{name:"php_namespace",number:41,type:9,label:1},{name:"php_metadata_namespace",number:44,type:9,label:1},{name:"ruby_package",number:45,type:9,label:1},{name:"features",number:50,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],enumType:[{name:"OptimizeMode",value:[{name:"SPEED",number:1},{name:"CODE_SIZE",number:2},{name:"LITE_RUNTIME",number:3}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"MessageOptions",field:[{name:"message_set_wire_format",number:1,type:8,label:1,defaultValue:"false"},{name:"no_standard_descriptor_accessor",number:2,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"map_entry",number:7,type:8,label:1},{name:"deprecated_legacy_json_field_conflicts",number:11,type:8,label:1,options:{deprecated:!0}},{name:"features",number:12,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"FieldOptions",field:[{name:"ctype",number:1,type:14,label:1,typeName:".google.protobuf.FieldOptions.CType",defaultValue:"STRING"},{name:"packed",number:2,type:8,label:1},{name:"jstype",number:6,type:14,label:1,typeName:".google.protobuf.FieldOptions.JSType",defaultValue:"JS_NORMAL"},{name:"lazy",number:5,type:8,label:1,defaultValue:"false"},{name:"unverified_lazy",number:15,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"weak",number:10,type:8,label:1,defaultValue:"false",options:{deprecated:!0}},{name:"debug_redact",number:16,type:8,label:1,defaultValue:"false"},{name:"retention",number:17,type:14,label:1,typeName:".google.protobuf.FieldOptions.OptionRetention"},{name:"targets",number:19,type:14,label:3,typeName:".google.protobuf.FieldOptions.OptionTargetType"},{name:"edition_defaults",number:20,type:11,label:3,typeName:".google.protobuf.FieldOptions.EditionDefault"},{name:"features",number:21,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"feature_support",number:22,type:11,label:1,typeName:".google.protobuf.FieldOptions.FeatureSupport"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],nestedType:[{name:"EditionDefault",field:[{name:"edition",number:3,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"value",number:2,type:9,label:1}]},{name:"FeatureSupport",field:[{name:"edition_introduced",number:1,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"edition_deprecated",number:2,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"deprecation_warning",number:3,type:9,label:1},{name:"edition_removed",number:4,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"removal_error",number:5,type:9,label:1}]}],enumType:[{name:"CType",value:[{name:"STRING",number:0},{name:"CORD",number:1},{name:"STRING_PIECE",number:2}]},{name:"JSType",value:[{name:"JS_NORMAL",number:0},{name:"JS_STRING",number:1},{name:"JS_NUMBER",number:2}]},{name:"OptionRetention",value:[{name:"RETENTION_UNKNOWN",number:0},{name:"RETENTION_RUNTIME",number:1},{name:"RETENTION_SOURCE",number:2}]},{name:"OptionTargetType",value:[{name:"TARGET_TYPE_UNKNOWN",number:0},{name:"TARGET_TYPE_FILE",number:1},{name:"TARGET_TYPE_EXTENSION_RANGE",number:2},{name:"TARGET_TYPE_MESSAGE",number:3},{name:"TARGET_TYPE_FIELD",number:4},{name:"TARGET_TYPE_ONEOF",number:5},{name:"TARGET_TYPE_ENUM",number:6},{name:"TARGET_TYPE_ENUM_ENTRY",number:7},{name:"TARGET_TYPE_SERVICE",number:8},{name:"TARGET_TYPE_METHOD",number:9}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"OneofOptions",field:[{name:"features",number:1,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"EnumOptions",field:[{name:"allow_alias",number:2,type:8,label:1},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"deprecated_legacy_json_field_conflicts",number:6,type:8,label:1,options:{deprecated:!0}},{name:"features",number:7,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"EnumValueOptions",field:[{name:"deprecated",number:1,type:8,label:1,defaultValue:"false"},{name:"features",number:2,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"debug_redact",number:3,type:8,label:1,defaultValue:"false"},{name:"feature_support",number:4,type:11,label:1,typeName:".google.protobuf.FieldOptions.FeatureSupport"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"ServiceOptions",field:[{name:"features",number:34,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"deprecated",number:33,type:8,label:1,defaultValue:"false"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"MethodOptions",field:[{name:"deprecated",number:33,type:8,label:1,defaultValue:"false"},{name:"idempotency_level",number:34,type:14,label:1,typeName:".google.protobuf.MethodOptions.IdempotencyLevel",defaultValue:"IDEMPOTENCY_UNKNOWN"},{name:"features",number:35,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],enumType:[{name:"IdempotencyLevel",value:[{name:"IDEMPOTENCY_UNKNOWN",number:0},{name:"NO_SIDE_EFFECTS",number:1},{name:"IDEMPOTENT",number:2}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"UninterpretedOption",field:[{name:"name",number:2,type:11,label:3,typeName:".google.protobuf.UninterpretedOption.NamePart"},{name:"identifier_value",number:3,type:9,label:1},{name:"positive_int_value",number:4,type:4,label:1},{name:"negative_int_value",number:5,type:3,label:1},{name:"double_value",number:6,type:1,label:1},{name:"string_value",number:7,type:12,label:1},{name:"aggregate_value",number:8,type:9,label:1}],nestedType:[{name:"NamePart",field:[{name:"name_part",number:1,type:9,label:2},{name:"is_extension",number:2,type:8,label:2}]}]},{name:"FeatureSet",field:[{name:"field_presence",number:1,type:14,label:1,typeName:".google.protobuf.FeatureSet.FieldPresence",options:{retention:1,targets:[4,1],editionDefaults:[{value:"EXPLICIT",edition:900},{value:"IMPLICIT",edition:999},{value:"EXPLICIT",edition:1e3}]}},{name:"enum_type",number:2,type:14,label:1,typeName:".google.protobuf.FeatureSet.EnumType",options:{retention:1,targets:[6,1],editionDefaults:[{value:"CLOSED",edition:900},{value:"OPEN",edition:999}]}},{name:"repeated_field_encoding",number:3,type:14,label:1,typeName:".google.protobuf.FeatureSet.RepeatedFieldEncoding",options:{retention:1,targets:[4,1],editionDefaults:[{value:"EXPANDED",edition:900},{value:"PACKED",edition:999}]}},{name:"utf8_validation",number:4,type:14,label:1,typeName:".google.protobuf.FeatureSet.Utf8Validation",options:{retention:1,targets:[4,1],editionDefaults:[{value:"NONE",edition:900},{value:"VERIFY",edition:999}]}},{name:"message_encoding",number:5,type:14,label:1,typeName:".google.protobuf.FeatureSet.MessageEncoding",options:{retention:1,targets:[4,1],editionDefaults:[{value:"LENGTH_PREFIXED",edition:900}]}},{name:"json_format",number:6,type:14,label:1,typeName:".google.protobuf.FeatureSet.JsonFormat",options:{retention:1,targets:[3,6,1],editionDefaults:[{value:"LEGACY_BEST_EFFORT",edition:900},{value:"ALLOW",edition:999}]}},{name:"enforce_naming_style",number:7,type:14,label:1,typeName:".google.protobuf.FeatureSet.EnforceNamingStyle",options:{retention:2,targets:[1,2,3,4,5,6,7,8,9],editionDefaults:[{value:"STYLE_LEGACY",edition:900},{value:"STYLE2024",edition:1001}]}},{name:"default_symbol_visibility",number:8,type:14,label:1,typeName:".google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility",options:{retention:2,targets:[1],editionDefaults:[{value:"EXPORT_ALL",edition:900},{value:"EXPORT_TOP_LEVEL",edition:1001}]}}],nestedType:[{name:"VisibilityFeature",enumType:[{name:"DefaultSymbolVisibility",value:[{name:"DEFAULT_SYMBOL_VISIBILITY_UNKNOWN",number:0},{name:"EXPORT_ALL",number:1},{name:"EXPORT_TOP_LEVEL",number:2},{name:"LOCAL_ALL",number:3},{name:"STRICT",number:4}]}]}],enumType:[{name:"FieldPresence",value:[{name:"FIELD_PRESENCE_UNKNOWN",number:0},{name:"EXPLICIT",number:1},{name:"IMPLICIT",number:2},{name:"LEGACY_REQUIRED",number:3}]},{name:"EnumType",value:[{name:"ENUM_TYPE_UNKNOWN",number:0},{name:"OPEN",number:1},{name:"CLOSED",number:2}]},{name:"RepeatedFieldEncoding",value:[{name:"REPEATED_FIELD_ENCODING_UNKNOWN",number:0},{name:"PACKED",number:1},{name:"EXPANDED",number:2}]},{name:"Utf8Validation",value:[{name:"UTF8_VALIDATION_UNKNOWN",number:0},{name:"VERIFY",number:2},{name:"NONE",number:3}]},{name:"MessageEncoding",value:[{name:"MESSAGE_ENCODING_UNKNOWN",number:0},{name:"LENGTH_PREFIXED",number:1},{name:"DELIMITED",number:2}]},{name:"JsonFormat",value:[{name:"JSON_FORMAT_UNKNOWN",number:0},{name:"ALLOW",number:1},{name:"LEGACY_BEST_EFFORT",number:2}]},{name:"EnforceNamingStyle",value:[{name:"ENFORCE_NAMING_STYLE_UNKNOWN",number:0},{name:"STYLE2024",number:1},{name:"STYLE_LEGACY",number:2}]}],extensionRange:[{start:1e3,end:9995},{start:9995,end:1e4},{start:1e4,end:10001}]},{name:"FeatureSetDefaults",field:[{name:"defaults",number:1,type:11,label:3,typeName:".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault"},{name:"minimum_edition",number:4,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"maximum_edition",number:5,type:14,label:1,typeName:".google.protobuf.Edition"}],nestedType:[{name:"FeatureSetEditionDefault",field:[{name:"edition",number:3,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"overridable_features",number:4,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"fixed_features",number:5,type:11,label:1,typeName:".google.protobuf.FeatureSet"}]}]},{name:"SourceCodeInfo",field:[{name:"location",number:1,type:11,label:3,typeName:".google.protobuf.SourceCodeInfo.Location"}],nestedType:[{name:"Location",field:[{name:"path",number:1,type:5,label:3,options:{packed:!0}},{name:"span",number:2,type:5,label:3,options:{packed:!0}},{name:"leading_comments",number:3,type:9,label:1},{name:"trailing_comments",number:4,type:9,label:1},{name:"leading_detached_comments",number:6,type:9,label:3}]}],extensionRange:[{start:536e6,end:536000001}]},{name:"GeneratedCodeInfo",field:[{name:"annotation",number:1,type:11,label:3,typeName:".google.protobuf.GeneratedCodeInfo.Annotation"}],nestedType:[{name:"Annotation",field:[{name:"path",number:1,type:5,label:3,options:{packed:!0}},{name:"source_file",number:2,type:9,label:1},{name:"begin",number:3,type:5,label:1},{name:"end",number:4,type:5,label:1},{name:"semantic",number:5,type:14,label:1,typeName:".google.protobuf.GeneratedCodeInfo.Annotation.Semantic"}],enumType:[{name:"Semantic",value:[{name:"NONE",number:0},{name:"SET",number:1},{name:"ALIAS",number:2}]}]}]}],enumType:[{name:"Edition",value:[{name:"EDITION_UNKNOWN",number:0},{name:"EDITION_LEGACY",number:900},{name:"EDITION_PROTO2",number:998},{name:"EDITION_PROTO3",number:999},{name:"EDITION_2023",number:1e3},{name:"EDITION_2024",number:1001},{name:"EDITION_UNSTABLE",number:9999},{name:"EDITION_1_TEST_ONLY",number:1},{name:"EDITION_2_TEST_ONLY",number:2},{name:"EDITION_99997_TEST_ONLY",number:99997},{name:"EDITION_99998_TEST_ONLY",number:99998},{name:"EDITION_99999_TEST_ONLY",number:99999},{name:"EDITION_MAX",number:2147483647}]},{name:"SymbolVisibility",value:[{name:"VISIBILITY_UNSET",number:0},{name:"VISIBILITY_LOCAL",number:1},{name:"VISIBILITY_EXPORT",number:2}]}]}),1);var V9,x9,F9,B9,j9,G9,W9,K9,H9,Y9,X9,J9,z9,Z9,q9,Q9,$9,e8,t8,n8;!function(e){e[e.DECLARATION=0]="DECLARATION",e[e.UNVERIFIED=1]="UNVERIFIED"}(V9||(V9={})),function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.GROUP=10]="GROUP",e[e.MESSAGE=11]="MESSAGE",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.ENUM=14]="ENUM",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(x9||(x9={})),function(e){e[e.OPTIONAL=1]="OPTIONAL",e[e.REPEATED=3]="REPEATED",e[e.REQUIRED=2]="REQUIRED"}(F9||(F9={})),function(e){e[e.SPEED=1]="SPEED",e[e.CODE_SIZE=2]="CODE_SIZE",e[e.LITE_RUNTIME=3]="LITE_RUNTIME"}(B9||(B9={})),function(e){e[e.STRING=0]="STRING",e[e.CORD=1]="CORD",e[e.STRING_PIECE=2]="STRING_PIECE"}(j9||(j9={})),function(e){e[e.JS_NORMAL=0]="JS_NORMAL",e[e.JS_STRING=1]="JS_STRING",e[e.JS_NUMBER=2]="JS_NUMBER"}(G9||(G9={})),function(e){e[e.RETENTION_UNKNOWN=0]="RETENTION_UNKNOWN",e[e.RETENTION_RUNTIME=1]="RETENTION_RUNTIME",e[e.RETENTION_SOURCE=2]="RETENTION_SOURCE"}(W9||(W9={})),function(e){e[e.TARGET_TYPE_UNKNOWN=0]="TARGET_TYPE_UNKNOWN",e[e.TARGET_TYPE_FILE=1]="TARGET_TYPE_FILE",e[e.TARGET_TYPE_EXTENSION_RANGE=2]="TARGET_TYPE_EXTENSION_RANGE",e[e.TARGET_TYPE_MESSAGE=3]="TARGET_TYPE_MESSAGE",e[e.TARGET_TYPE_FIELD=4]="TARGET_TYPE_FIELD",e[e.TARGET_TYPE_ONEOF=5]="TARGET_TYPE_ONEOF",e[e.TARGET_TYPE_ENUM=6]="TARGET_TYPE_ENUM",e[e.TARGET_TYPE_ENUM_ENTRY=7]="TARGET_TYPE_ENUM_ENTRY",e[e.TARGET_TYPE_SERVICE=8]="TARGET_TYPE_SERVICE",e[e.TARGET_TYPE_METHOD=9]="TARGET_TYPE_METHOD"}(K9||(K9={})),function(e){e[e.IDEMPOTENCY_UNKNOWN=0]="IDEMPOTENCY_UNKNOWN",e[e.NO_SIDE_EFFECTS=1]="NO_SIDE_EFFECTS",e[e.IDEMPOTENT=2]="IDEMPOTENT"}(H9||(H9={})),function(e){e[e.DEFAULT_SYMBOL_VISIBILITY_UNKNOWN=0]="DEFAULT_SYMBOL_VISIBILITY_UNKNOWN",e[e.EXPORT_ALL=1]="EXPORT_ALL",e[e.EXPORT_TOP_LEVEL=2]="EXPORT_TOP_LEVEL",e[e.LOCAL_ALL=3]="LOCAL_ALL",e[e.STRICT=4]="STRICT"}(Y9||(Y9={})),function(e){e[e.FIELD_PRESENCE_UNKNOWN=0]="FIELD_PRESENCE_UNKNOWN",e[e.EXPLICIT=1]="EXPLICIT",e[e.IMPLICIT=2]="IMPLICIT",e[e.LEGACY_REQUIRED=3]="LEGACY_REQUIRED"}(X9||(X9={})),function(e){e[e.ENUM_TYPE_UNKNOWN=0]="ENUM_TYPE_UNKNOWN",e[e.OPEN=1]="OPEN",e[e.CLOSED=2]="CLOSED"}(J9||(J9={})),function(e){e[e.REPEATED_FIELD_ENCODING_UNKNOWN=0]="REPEATED_FIELD_ENCODING_UNKNOWN",e[e.PACKED=1]="PACKED",e[e.EXPANDED=2]="EXPANDED"}(z9||(z9={})),function(e){e[e.UTF8_VALIDATION_UNKNOWN=0]="UTF8_VALIDATION_UNKNOWN",e[e.VERIFY=2]="VERIFY",e[e.NONE=3]="NONE"}(Z9||(Z9={})),function(e){e[e.MESSAGE_ENCODING_UNKNOWN=0]="MESSAGE_ENCODING_UNKNOWN",e[e.LENGTH_PREFIXED=1]="LENGTH_PREFIXED",e[e.DELIMITED=2]="DELIMITED"}(q9||(q9={})),function(e){e[e.JSON_FORMAT_UNKNOWN=0]="JSON_FORMAT_UNKNOWN",e[e.ALLOW=1]="ALLOW",e[e.LEGACY_BEST_EFFORT=2]="LEGACY_BEST_EFFORT"}(Q9||(Q9={})),function(e){e[e.ENFORCE_NAMING_STYLE_UNKNOWN=0]="ENFORCE_NAMING_STYLE_UNKNOWN",e[e.STYLE2024=1]="STYLE2024",e[e.STYLE_LEGACY=2]="STYLE_LEGACY"}($9||($9={})),function(e){e[e.NONE=0]="NONE",e[e.SET=1]="SET",e[e.ALIAS=2]="ALIAS"}(e8||(e8={})),function(e){e[e.EDITION_UNKNOWN=0]="EDITION_UNKNOWN",e[e.EDITION_LEGACY=900]="EDITION_LEGACY",e[e.EDITION_PROTO2=998]="EDITION_PROTO2",e[e.EDITION_PROTO3=999]="EDITION_PROTO3",e[e.EDITION_2023=1e3]="EDITION_2023",e[e.EDITION_2024=1001]="EDITION_2024",e[e.EDITION_UNSTABLE=9999]="EDITION_UNSTABLE",e[e.EDITION_1_TEST_ONLY=1]="EDITION_1_TEST_ONLY",e[e.EDITION_2_TEST_ONLY=2]="EDITION_2_TEST_ONLY",e[e.EDITION_99997_TEST_ONLY=99997]="EDITION_99997_TEST_ONLY",e[e.EDITION_99998_TEST_ONLY=99998]="EDITION_99998_TEST_ONLY",e[e.EDITION_99999_TEST_ONLY=99999]="EDITION_99999_TEST_ONLY",e[e.EDITION_MAX=2147483647]="EDITION_MAX"}(t8||(t8={})),function(e){e[e.VISIBILITY_UNSET=0]="VISIBILITY_UNSET",e[e.VISIBILITY_LOCAL=1]="VISIBILITY_LOCAL",e[e.VISIBILITY_EXPORT=2]="VISIBILITY_EXPORT"}(n8||(n8={}));const i8={readUnknownFields:!0};function r8(e,t,n){const i=G6(e,void 0,!1);return o8(i,new _6(t),function(e){return e?Object.assign(Object.assign({},i8),e):i8}(n),!1,t.byteLength),i.message}function o8(e,t,n,i,r){var o;const s=i?t.len:t.pos+r;let a,c;const d=null!==(o=e.getUnknown())&&void 0!==o?o:[];for(;t.pos<s;){var l=M5(t.tag(),2);if(a=l[0],c=l[1],i&&c==a6.EndGroup)break;const r=e.findNumber(a);if(r)s8(e,t,r,c,n);else{const e=t.skip(c,a);n.readUnknownFields&&d.push({no:a,wireType:c,data:e})}}if(i&&(c!=a6.EndGroup||a!==r))throw new Error("invalid end group tag");d.length>0&&e.setUnknown(d)}function s8(e,t,n,i,r){var o;switch(n.fieldKind){case"scalar":e.set(n,c8(t,n.scalar,n.utf8Validation));break;case"enum":const s=c8(t,dq.INT32);if(n.enum.open)e.set(n,s);else if(XZ(n.enum).some((e=>e.number===s)))e.set(n,s);else if(r.readUnknownFields){const t=[];rq(s,t);const r=null!==(o=e.getUnknown())&&void 0!==o?o:[];r.push({no:n.number,wireType:i,data:new Uint8Array(t)}),e.setUnknown(r)}break;case"message":e.set(n,a8(t,r,n,e.get(n)));break;case"list":!function(e,t,n,i){var r;const o=n.field();if("message"===o.listKind)return void n.add(a8(e,i,o));const s=null!==(r=o.scalar)&&void 0!==r?r:dq.INT32;if(!(t==a6.LengthDelimited&&s!=dq.STRING&&s!=dq.BYTES))return void n.add(c8(e,s,o.utf8Validation));const a=e.uint32()+e.pos;for(;e.pos<a;)n.add(c8(e,s,o.utf8Validation))}(t,i,e.get(n),r);break;case"map":!function(e,t,n){const i=t.field();let r,o;const s=e.uint32(),a=e.pos+s;for(;e.pos<a;)switch(M5(e.tag(),1)[0]){case 1:r=c8(e,i.mapKey,i.utf8Validation);break;case 2:switch(i.mapKind){case"scalar":o=c8(e,i.scalar,i.utf8Validation);break;case"enum":o=e.int32();break;case"message":o=a8(e,n,i)}}if(void 0===r&&(r=lq(i.mapKey,!1)),void 0===o)switch(i.mapKind){case"scalar":o=lq(i.scalar,!1);break;case"enum":o=XZ(i.enum)[0].number;break;case"message":o=G6(i.message,void 0,!1)}t.set(r,o)}(t,e.get(n),r)}}function a8(e,t,n,i){const r=n.delimitedEncoding,o=null!=i?i:G6(n.message,void 0,!1);return o8(o,e,t,r,r?n.number:e.uint32()),o}function c8(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];switch(t){case dq.STRING:return e.string(n);case dq.BOOL:return e.bool();case dq.DOUBLE:return e.double();case dq.FLOAT:return e.float();case dq.INT32:return e.int32();case dq.INT64:return e.int64();case dq.UINT64:return e.uint64();case dq.FIXED64:return e.fixed64();case dq.BYTES:return e.bytes();case dq.FIXED32:return e.fixed32();case dq.SFIXED32:return e.sfixed32();case dq.SFIXED64:return e.sfixed64();case dq.SINT64:return e.sint64();case dq.UINT32:return e.uint32();case dq.SINT32:return e.sint32()}}function d8(e,t){var n;const i=r8(U9,TQ(e));return i.messageType.forEach(fq),i.dependency=null!==(n=null==t?void 0:t.map((e=>e.proto.name)))&&void 0!==n?n:[],Nq(i,(e=>null==t?void 0:t.find((t=>t.proto.name===e)))).getFile(i.name)}const l8=M9(d8("Chlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvEg9nb29nbGUucHJvdG9idWYiJgoDQW55EhAKCHR5cGVfdXJsGAEgASgJEg0KBXZhbHVlGAIgASgMQnYKE2NvbS5nb29nbGUucHJvdG9idWZCCEFueVByb3RvUAFaLGdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL2FueXBiogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM"),0);function u8(e){const t=e.lastIndexOf("/"),n=t>=0?e.substring(t+1):e;if(!n.length)throw new Error("invalid type url: ".concat(e));return n}const h8=d8("Chxnb29nbGUvcHJvdG9idWYvc3RydWN0LnByb3RvEg9nb29nbGUucHJvdG9idWYihAEKBlN0cnVjdBIzCgZmaWVsZHMYASADKAsyIy5nb29nbGUucHJvdG9idWYuU3RydWN0LkZpZWxkc0VudHJ5GkUKC0ZpZWxkc0VudHJ5EgsKA2tleRgBIAEoCRIlCgV2YWx1ZRgCIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZToCOAEi6gEKBVZhbHVlEjAKCm51bGxfdmFsdWUYASABKA4yGi5nb29nbGUucHJvdG9idWYuTnVsbFZhbHVlSAASFgoMbnVtYmVyX3ZhbHVlGAIgASgBSAASFgoMc3RyaW5nX3ZhbHVlGAMgASgJSAASFAoKYm9vbF92YWx1ZRgEIAEoCEgAEi8KDHN0cnVjdF92YWx1ZRgFIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3RIABIwCgpsaXN0X3ZhbHVlGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLkxpc3RWYWx1ZUgAQgYKBGtpbmQiMwoJTGlzdFZhbHVlEiYKBnZhbHVlcxgBIAMoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZSobCglOdWxsVmFsdWUSDgoKTlVMTF9WQUxVRRAAQn8KE2NvbS5nb29nbGUucHJvdG9idWZCC1N0cnVjdFByb3RvUAFaL2dvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL3N0cnVjdHBi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM"),p8=M9(h8,0),_8=M9(h8,1),E8=M9(h8,2);var m8;!function(e){e[e.NULL_VALUE=0]="NULL_VALUE"}(m8||(m8={}));const f8=d8("CgpvcnRjLnByb3RvEgtpby5hZ29yYS5wYiKoAQoET1JUQxILCgNpY2UYASADKAkSJQoEZHRscxgCIAMoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QSIQoEc2VuZBgDIAEoCzITLmlvLmFnb3JhLnBiLlJ0cENhcBIhCgRyZWN2GAQgASgLMhMuaW8uYWdvcmEucGIuUnRwQ2FwEiYKCXNlbmRfcmVjdhgFIAEoCzITLmlvLmFnb3JhLnBiLlJ0cENhcCLQAQoGUnRwQ2FwEjMKDGF1ZGlvX2NvZGVjcxgBIAMoCzIdLmlvLmFnb3JhLnBiLlBheWxvYWRBdHRyaWJ1dGUSMwoMdmlkZW9fY29kZWNzGAIgAygLMh0uaW8uYWdvcmEucGIuUGF5bG9hZEF0dHJpYnV0ZRItChBhdWRpb19leHRlbnNpb25zGAMgAygLMhMuaW8uYWdvcmEucGIuRXh0bWFwEi0KEHZpZGVvX2V4dGVuc2lvbnMYBCADKAsyEy5pby5hZ29yYS5wYi5FeHRtYXAiqQEKBkV4dG1hcBINCgVlbnRyeRgBIAEoDRIuCg5leHRlbnNpb25fbmFtZRgCIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZRIWCglkaXJlY3Rpb24YAyABKAlIAIgBARIhChRleHRlbnNpb25fYXR0cmlidXRlcxgEIAEoCUgBiAEBQgwKCl9kaXJlY3Rpb25CFwoVX2V4dGVuc2lvbl9hdHRyaWJ1dGVzIp4BChBQYXlsb2FkQXR0cmlidXRlEiQKB3J0cF9tYXAYASABKAsyEy5pby5hZ29yYS5wYi5SdHBNYXASHwoEZm10cBgCIAEoCzIRLmlvLmFnb3JhLnBiLkZtdHASLQoOcnRjcF9mZWVkYmFja3MYAyADKAsyFS5pby5hZ29yYS5wYi5GZWVkYmFjaxIUCgxwYXlsb2FkX3R5cGUYBCABKA0i4gEKBlJ0cE1hcBIfChJlbnVtX2VuY29kaW5nX25hbWUYASABKA1IAIgBARIhChRzdHJpbmdfZW5jb2RpbmdfbmFtZRgCIAEoCUgBiAEBEioKCmNsb2NrX3JhdGUYAyABKAsyFi5nb29nbGUucHJvdG9idWYuVmFsdWUSIAoTZW5jb2RpbmdfcGFyYW1ldGVycxgEIAEoDUgCiAEBQhUKE19lbnVtX2VuY29kaW5nX25hbWVCFwoVX3N0cmluZ19lbmNvZGluZ19uYW1lQhYKFF9lbmNvZGluZ19wYXJhbWV0ZXJzIqoCCgRGbXRwEj4KD2VudW1fcGFyYW1ldGVycxgBIAMoCzIlLmlvLmFnb3JhLnBiLkZtdHAuRW51bVBhcmFtZXRlcnNFbnRyeRJCChFzdHJpbmdfcGFyYW1ldGVycxgCIAMoCzInLmlvLmFnb3JhLnBiLkZtdHAuU3RyaW5nUGFyYW1ldGVyc0VudHJ5Gk0KE0VudW1QYXJhbWV0ZXJzRW50cnkSCwoDa2V5GAEgASgNEiUKBXZhbHVlGAIgASgLMhYuZ29vZ2xlLnByb3RvYnVmLlZhbHVlOgI4ARpPChVTdHJpbmdQYXJhbWV0ZXJzRW50cnkSCwoDa2V5GAEgASgJEiUKBXZhbHVlGAIgASgLMhYuZ29vZ2xlLnByb3RvYnVmLlZhbHVlOgI4ASLMAQoIRmVlZGJhY2sSFgoJZW51bV90eXBlGAEgASgNSACIAQESGAoLc3RyaW5nX3R5cGUYAiABKAlIAYgBARIWCglwYXJhbWV0ZXIYAyABKAlIAogBARIXCgphZGRpdGlvbmFsGAQgASgJSAOIAQESFQoIaW50ZXJ2YWwYBSABKAlIBIgBAUIMCgpfZW51bV90eXBlQg4KDF9zdHJpbmdfdHlwZUIMCgpfcGFyYW1ldGVyQg0KC19hZGRpdGlvbmFsQgsKCV9pbnRlcnZhbCKBAQoRUnRwQ2FwQmVmb3JlTWVyZ2USIQoEc2VuZBgBIAEoCzITLmlvLmFnb3JhLnBiLlJ0cENhcBIhCgRyZWN2GAIgASgLMhMuaW8uYWdvcmEucGIuUnRwQ2FwEiYKCXNlbmRfcmVjdhgDIAEoCzITLmlvLmFnb3JhLnBiLlJ0cENhcCKrEQoPT3J0Y05lZ290aWF0aW9uEk4KE2luX291dF9hdWRpb19wdF9tYXAYASADKAsyMS5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uSW5PdXRBdWRpb1B0TWFwRW50cnkSTgoTaW5fb3V0X3ZpZGVvX3B0X21hcBgCIAMoCzIxLmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5Jbk91dFZpZGVvUHRNYXBFbnRyeRJOChNvdXRfaW5fYXVkaW9fcHRfbWFwGAMgAygLMjEuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uLk91dEluQXVkaW9QdE1hcEVudHJ5Ek4KE291dF9pbl92aWRlb19wdF9tYXAYBCADKAsyMS5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uT3V0SW5WaWRlb1B0TWFwRW50cnkSYwoeaW5fb3V0X2F1ZGlvX2hlYWRlcl9leHRlbnNfbWFwGAUgAygLMjsuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uLkluT3V0QXVkaW9IZWFkZXJFeHRlbnNNYXBFbnRyeRJjCh5vdXRfaW5fYXVkaW9faGVhZGVyX2V4dGVuc19tYXAYBiADKAsyOy5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uT3V0SW5BdWRpb0hlYWRlckV4dGVuc01hcEVudHJ5EmMKHmluX291dF92aWRlb19oZWFkZXJfZXh0ZW5zX21hcBgHIAMoCzI7LmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5Jbk91dFZpZGVvSGVhZGVyRXh0ZW5zTWFwRW50cnkSYwoeb3V0X2luX3ZpZGVvX2hlYWRlcl9leHRlbnNfbWFwGAggAygLMjsuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uLk91dEluVmlkZW9IZWFkZXJFeHRlbnNNYXBFbnRyeRJQChRydHBfcnR4X2F1ZGlvX3B0X21hcBgJIAMoCzIyLmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5SdHBSdHhBdWRpb1B0TWFwRW50cnkSUAoUcnRwX3J0eF92aWRlb19wdF9tYXAYCiADKAsyMi5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uUnRwUnR4VmlkZW9QdE1hcEVudHJ5ElAKFHJ0eF9ydHBfYXVkaW9fcHRfbWFwGAsgAygLMjIuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uLlJ0eFJ0cEF1ZGlvUHRNYXBFbnRyeRJQChRydHhfcnRwX3ZpZGVvX3B0X21hcBgMIAMoCzIyLmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5SdHhSdHBWaWRlb1B0TWFwRW50cnkSRQoOcnRwX3JlZF9wdF9tYXAYDSADKAsyLS5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uUnRwUmVkUHRNYXBFbnRyeRJFCg5yZWRfcnRwX3B0X21hcBgOIAMoCzItLmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5SZWRSdHBQdE1hcEVudHJ5Eg8KB2NmZ19ydHgYDyABKAgSFQoNaGFzX2F1ZGlvX3J0eBgQIAEoCBIVCg1oYXNfdmlkZW9fcnR4GBEgASgIEhAKCGNmZ19ycnRyGBIgASgIEhYKDmhhc192aWRlb19ycnRyGBMgASgIEhYKDmhhc19hdWRpb19ycnRyGBQgASgIEg8KB2NmZ19yZWQYFSABKAgSFQoNaGFzX2F1ZGlvX3JlZBgWIAEoCBIRCglpbl9yZWRfcHQYFyADKA0aNgoUSW5PdXRBdWRpb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo2ChRJbk91dFZpZGVvUHRNYXBFbnRyeRILCgNrZXkYASABKA0SDQoFdmFsdWUYAiABKA06AjgBGjYKFE91dEluQXVkaW9QdE1hcEVudHJ5EgsKA2tleRgBIAEoDRINCgV2YWx1ZRgCIAEoDToCOAEaNgoUT3V0SW5WaWRlb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARpACh5Jbk91dEF1ZGlvSGVhZGVyRXh0ZW5zTWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARpACh5PdXRJbkF1ZGlvSGVhZGVyRXh0ZW5zTWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARpACh5Jbk91dFZpZGVvSGVhZGVyRXh0ZW5zTWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARpACh5PdXRJblZpZGVvSGVhZGVyRXh0ZW5zTWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo3ChVSdHBSdHhBdWRpb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo3ChVSdHBSdHhWaWRlb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo3ChVSdHhSdHBBdWRpb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo3ChVSdHhSdHBWaWRlb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARoyChBSdHBSZWRQdE1hcEVudHJ5EgsKA2tleRgBIAEoDRINCgV2YWx1ZRgCIAEoDToCOAEaMgoQUmVkUnRwUHRNYXBFbnRyeRILCgNrZXkYASABKA0SDQoFdmFsdWUYAiABKA06AjgBKtACChJWaWRlb0V4dGVuc2lvbk5hbWUSGQoVVklERU9fRVhUX0hEUl9UT0ZGU0VUEAASGwoXVklERU9fRVhUX0FCU19TRU5EX1RJTUUQARIZChVWSURFT19FWFRfT1JJRU5UQVRJT04QAhISCg5WSURFT19FWFRfVFdDQxADEhsKF1ZJREVPX0VYVF9QTEFZT1VUX0RFTEFZEAQSGgoWVklERU9fRVhUX0NPTlRFTlRfVFlQRRAFEhoKFlZJREVPX0VYVF9WSURFT19USU1JTkcQBhIZChVWSURFT19FWFRfQ09MT1JfU1BBQ0UQBxIWChJWSURFT19FWFRfU0RFU19NSUQQCBIgChxWSURFT19FWFRfU0RFU19SVFBfU1RSRUFNX0lEEAkSKQolVklERU9fRVhUX1NERURfUkVQQUlSRURfUlRQX1NUUkVBTV9JRBAKKsQBChJBdWRpb0V4dGVuc2lvbk5hbWUSGQoVQVVESU9fRVhUX0FVRElPX0xFVkVMEAASGwoXQVVESU9fRVhUX0FCU19TRU5EX1RJTUUQARISCg5BVURJT19FWFRfVFdDQxACEhYKEkFVRElPX0VYVF9TREVTX01JRBADEiAKHEFVRElPX0VYVF9TREVTX1JUUF9TVFJFQU1fSUQQBBIoCiRBVURJT19FWFRfU0RTX1JFUEFJUkVEX1JUUF9TVFJFQU1fSUQQBSqBAwoMRW5jb2RpbmdOYW1lEh0KGUVOQ09ESU5HX05BTUVfVU5TUEVDSUZJRUQQABIVChFFTkNPRElOR19OQU1FX1ZQOBABEhUKEUVOQ09ESU5HX05BTUVfVlA5EAISFgoSRU5DT0RJTkdfTkFNRV9IMjY0EAMSFgoSRU5DT0RJTkdfTkFNRV9IMjY1EAQSFQoRRU5DT0RJTkdfTkFNRV9BVjEQBRIWChJFTkNPRElOR19OQU1FX0c3MTEQBhIWChJFTkNPRElOR19OQU1FX0c3MjIQBxIWChJFTkNPRElOR19OQU1FX09QVVMQCBIWChJFTkNPRElOR19OQU1FX1BDTVUQCRIWChJFTkNPRElOR19OQU1FX1BDTUEQChIUChBFTkNPRElOR19OQU1FX0NOEAsSIQodRU5DT0RJTkdfTkFNRV9URUxFUEhPTkVfRVZFTlQQDBIVChFFTkNPRElOR19OQU1FX1JUWBANEhUKEUVOQ09ESU5HX05BTUVfUkVEEA4qrgMKDUZtdHBQYXJhbWV0ZXISHgoaRk1UUF9QQVJBTUVURVJfVU5TUEVDSUZJRUQQABIbChdGTVRQX1BBUkFNRVRFUl9NSU5QVElNRRABEh8KG0ZNVFBfUEFSQU1FVEVSX1VTRUlOQkFOREZFQxACEhsKF0ZNVFBfUEFSQU1FVEVSX0xFVkVMX0lEEAMSHQoZRk1UUF9QQVJBTUVURVJfUFJPRklMRV9JRBAEEhwKGEZNVFBfUEFSQU1FVEVSX1RJRVJfRkxBRxAFEhoKFkZNVFBfUEFSQU1FVEVSX1RYX01PREUQBhIqCiZGTVRQX1BBUkFNRVRFUl9MRVZFTF9BU1lNTUVUUllfQUxMT1dFRBAHEiUKIUZNVFBfUEFSQU1FVEVSX1BBQ0tFVElaQVRJT05fTU9ERRAIEiMKH0ZNVFBfUEFSQU1FVEVSX1BST0ZJTEVfTEVWRUxfSUQQCRIcChhGTVRQX1BBUkFNRVRFUl9MRVZFTF9JRFgQChIaChZGTVRQX1BBUkFNRVRFUl9QUk9GSUxFEAsSFwoTRk1UUF9QQVJBTUVURVJfVElFUhAMKrEBCgxGZWVkYmFja1R5cGUSHQoZRkVFREJBQ0tfVFlQRV9VTlNQRUNJRklFRBAAEhsKF0ZFRURCQUNLX1RZUEVfR09PR19SRU1CEAESHgoaRkVFREJBQ0tfVFlQRV9UUkFOU1BPUlRfQ0MQAhIVChFGRUVEQkFDS19UWVBFX0NDTRADEhYKEkZFRURCQUNLX1RZUEVfTkFDSxAEEhYKEkZFRURCQUNLX1RZUEVfUlJUUhAFYgZwcm90bzM",[h8]);let g8=function(e){return e[e.VIDEO_EXT_HDR_TOFFSET=0]="VIDEO_EXT_HDR_TOFFSET",e[e.VIDEO_EXT_ABS_SEND_TIME=1]="VIDEO_EXT_ABS_SEND_TIME",e[e.VIDEO_EXT_ORIENTATION=2]="VIDEO_EXT_ORIENTATION",e[e.VIDEO_EXT_TWCC=3]="VIDEO_EXT_TWCC",e[e.VIDEO_EXT_PLAYOUT_DELAY=4]="VIDEO_EXT_PLAYOUT_DELAY",e[e.VIDEO_EXT_CONTENT_TYPE=5]="VIDEO_EXT_CONTENT_TYPE",e[e.VIDEO_EXT_VIDEO_TIMING=6]="VIDEO_EXT_VIDEO_TIMING",e[e.VIDEO_EXT_COLOR_SPACE=7]="VIDEO_EXT_COLOR_SPACE",e[e.VIDEO_EXT_SDES_MID=8]="VIDEO_EXT_SDES_MID",e[e.VIDEO_EXT_SDES_RTP_STREAM_ID=9]="VIDEO_EXT_SDES_RTP_STREAM_ID",e[e.VIDEO_EXT_SDED_REPAIRED_RTP_STREAM_ID=10]="VIDEO_EXT_SDED_REPAIRED_RTP_STREAM_ID",e}({}),S8=function(e){return e[e.AUDIO_EXT_AUDIO_LEVEL=0]="AUDIO_EXT_AUDIO_LEVEL",e[e.AUDIO_EXT_ABS_SEND_TIME=1]="AUDIO_EXT_ABS_SEND_TIME",e[e.AUDIO_EXT_TWCC=2]="AUDIO_EXT_TWCC",e[e.AUDIO_EXT_SDES_MID=3]="AUDIO_EXT_SDES_MID",e[e.AUDIO_EXT_SDES_RTP_STREAM_ID=4]="AUDIO_EXT_SDES_RTP_STREAM_ID",e[e.AUDIO_EXT_SDS_REPAIRED_RTP_STREAM_ID=5]="AUDIO_EXT_SDS_REPAIRED_RTP_STREAM_ID",e}({}),T8=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.VP8=1]="VP8",e[e.VP9=2]="VP9",e[e.H264=3]="H264",e[e.H265=4]="H265",e[e.AV1=5]="AV1",e[e.G711=6]="G711",e[e.G722=7]="G722",e[e.OPUS=8]="OPUS",e[e.PCMU=9]="PCMU",e[e.PCMA=10]="PCMA",e[e.CN=11]="CN",e[e.TELEPHONE_EVENT=12]="TELEPHONE_EVENT",e[e.RTX=13]="RTX",e[e.RED=14]="RED",e}({}),R8=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.MINPTIME=1]="MINPTIME",e[e.USEINBANDFEC=2]="USEINBANDFEC",e[e.LEVEL_ID=3]="LEVEL_ID",e[e.PROFILE_ID=4]="PROFILE_ID",e[e.TIER_FLAG=5]="TIER_FLAG",e[e.TX_MODE=6]="TX_MODE",e[e.LEVEL_ASYMMETRY_ALLOWED=7]="LEVEL_ASYMMETRY_ALLOWED",e[e.PACKETIZATION_MODE=8]="PACKETIZATION_MODE",e[e.PROFILE_LEVEL_ID=9]="PROFILE_LEVEL_ID",e[e.LEVEL_IDX=10]="LEVEL_IDX",e[e.PROFILE=11]="PROFILE",e[e.TIER=12]="TIER",e}({}),v8=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.GOOG_REMB=1]="GOOG_REMB",e[e.TRANSPORT_CC=2]="TRANSPORT_CC",e[e.CCM=3]="CCM",e[e.NACK=4]="NACK",e[e.RRTR=5]="RRTR",e}({});const y8=d8("CgxzaWduYWwucHJvdG8SC2lvLmFnb3JhLnBiIuUFCg5Vc2VyQXR0cmlidXRlcxIVCghmZWF0dXJlMRgBIAEoDUgAiAEBEhUKCGZlYXR1cmUyGAIgASgNSAGIAQESHAoPdG9wblNtb290aExldmVsGAMgASgNSAKIAQESIAoTdG9wbk5ld1NwZWFrZXJEZWxheRgEIAEoDUgDiAEBEh0KEHRvcG5Td2l0Y2hIb2xkTXMYBSABKA1IBIgBARIaCg10b3BuQXVkaW9HYWluGAYgASgNSAWIAQESHAoPbWF4U3Vic2NyaXB0aW9uGAcgASgNSAaIAQESJQoYc3Vic2NyaWJlQXVkaW9GaWx0ZXJUb3BOGAggASgNSAeIAQESFQoIcnRtMkZsYWcYCSABKA1ICIgBARIWCglwcmVTdWJOdW0YCiABKA1ICYgBARIpCglwcmVTdWJVaWQYCyADKAsyFi5nb29nbGUucHJvdG9idWYuVmFsdWUSFAoMZW5hYmxlU3ViU1ZDGAwgAygJEhkKEWVuYWJsZVN2Y0V4dGVuZGVkGA0gAygJEhsKDmF1ZGlvRHVwbGljYXRlGA4gASgNSAqIAQESGwoObnRwRml4ZWRPZmZzZXQYDyABKAVIC4gBARIxCgtleHBlcmltZW50cxgQIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3RIDIgBAUILCglfZmVhdHVyZTFCCwoJX2ZlYXR1cmUyQhIKEF90b3BuU21vb3RoTGV2ZWxCFgoUX3RvcG5OZXdTcGVha2VyRGVsYXlCEwoRX3RvcG5Td2l0Y2hIb2xkTXNCEAoOX3RvcG5BdWRpb0dhaW5CEgoQX21heFN1YnNjcmlwdGlvbkIbChlfc3Vic2NyaWJlQXVkaW9GaWx0ZXJUb3BOQgsKCV9ydG0yRmxhZ0IMCgpfcHJlU3ViTnVtQhEKD19hdWRpb0R1cGxpY2F0ZUIRCg9fbnRwRml4ZWRPZmZzZXRCDgoMX2V4cGVyaW1lbnRzIrcBChZVc2VyQXR0cmlidXRlc1Jlc3BvbnNlEiwKC3ByZVN1YlNzcmNzGAEgAygLMhcuaW8uYWdvcmEucGIuUHJlU3ViU3NyYxIlChhzdWJzY3JpYmVBdWRpb0ZpbHRlclRvcE4YAiABKA1IAIgBARIrCgpleHRlbnNpb25zGAMgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdEIbChlfc3Vic2NyaWJlQXVkaW9GaWx0ZXJUb3BOInIKClByZVN1YlNzcmMSKAoDdWlkGAEgASgLMhYuZ29vZ2xlLnByb3RvYnVmLlZhbHVlSACIAQESCQoBYRgCIAEoDRINCgVhX3J0eBgDIAEoDRIJCgF2GAQgASgNEg0KBXZfcnR4GAUgASgNQgYKBF91aWQizwYKDVNpZ25hbFJlcXVlc3QSFAoHbGljZW5zZRgBIAEoCUgAiAEBEg4KBnAycF9pZBgCIAEoDRISCgpzZXNzaW9uX2lkGAMgASgJEg4KBmFwcF9pZBgEIAEoCRITCgtjaGFubmVsX2tleRgFIAEoCRIUCgxjaGFubmVsX25hbWUYBiABKAkSEwoLc2RrX3ZlcnNpb24YByABKAkSFAoHYnJvd3NlchgIIAEoCUgBiAEBEioKCnByb2Nlc3NfaWQYCSABKAsyFi5nb29nbGUucHJvdG9idWYuVmFsdWUSDAoEbW9kZRgKIAEoCRINCgVjb2RlYxgLIAEoCRIRCgRyb2xlGAwgASgJSAKIAQESIAoTaGFzX2NoYW5nZWRfZ2F0ZXdheRgNIAEoCEgDiAEBEhMKBmV4dGVuZBgOIAEoCUgEiAEBEhkKDGNzZXJ2aWNlX21hcBgPIAEoCUgFiAEBEhoKDW9wdGlvbmFsX2luZm8YECABKAlIBogBARIZCgxhcHBfc2NlbmFyaW8YESABKAlIB4gBARIvCgphdHRyaWJ1dGVzGBIgASgLMhsuaW8uYWdvcmEucGIuVXNlckF0dHJpYnV0ZXMSEgoKcmVxdWVzdF90cxgTIAEoBBIXCgpzdHJpbmdfdWlkGBQgASgJSAiIAQESFQoIYWVzX21vZGUYFSABKAlICYgBARIXCgphZXNfc2VjcmV0GBYgASgJSAqIAQESGAoLYWVzX2VuY3J5cHQYFyABKAhIC4gBARIVCghhZXNfc2FsdBgYIAEoCUgMiAEBEiEKFGRlZmF1bHRfdmlkZW9fc3RyZWFtGBkgASgNSA2IAQFCCgoIX2xpY2Vuc2VCCgoIX2Jyb3dzZXJCBwoFX3JvbGVCFgoUX2hhc19jaGFuZ2VkX2dhdGV3YXlCCQoHX2V4dGVuZEIPCg1fY3NlcnZpY2VfbWFwQhAKDl9vcHRpb25hbF9pbmZvQg8KDV9hcHBfc2NlbmFyaW9CDQoLX3N0cmluZ191aWRCCwoJX2Flc19tb2RlQg0KC19hZXNfc2VjcmV0Qg4KDF9hZXNfZW5jcnlwdEILCglfYWVzX3NhbHRCFwoVX2RlZmF1bHRfdmlkZW9fc3RyZWFtIl8KEk11bHRpVW5pbGJzUmVxdWVzdBILCgN1cmkYASABKA0SJwoGZGV0YWlsGAIgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdBITCgtzZXJ2aWNlX2lkcxgDIAMoDSKtAQoSU2RwRW5kcG9pbnRSZXF1ZXN0Ei8KBnVuaWxicxgBIAMoCzIfLmlvLmFnb3JhLnBiLk11bHRpVW5pbGJzUmVxdWVzdBILCgN1aWQYAiABKA0SDAoEb3BpZBgDIAEoBBIqCgZzaWduYWwYBCABKAsyGi5pby5hZ29yYS5wYi5TaWduYWxSZXF1ZXN0Eh8KBG9ydGMYBSABKAsyES5pby5hZ29yYS5wYi5PUlRDIvQCChNTZHBFbmRwb2ludFJlc3BvbnNlEicKBmRldGFpbBgBIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QSEAoIZW50ZXJfdHMYAiABKAQSEAoIbGVhdmVfdHMYAyABKAQSDAoEb3BpZBgEIAEoBBI5Cg91bmlsYnNfcmVzcG9uc2UYBSADKAsyIC5pby5hZ29yYS5wYi5NdWx0aVVuaWxic1Jlc3BvbnNlEgsKA3VpZBgGIAEoDRJAChNhdHRyaWJ1dGVzX3Jlc3BvbnNlGAcgASgLMiMuaW8uYWdvcmEucGIuVXNlckF0dHJpYnV0ZXNSZXNwb25zZRIUCgxyZWpvaW5fdG9rZW4YCCABKAkSMAoIYWRkX29ydGMYCSABKAsyHi5pby5hZ29yYS5wYi5SdHBDYXBCZWZvcmVNZXJnZRIwCghkZWxfb3J0YxgKIAEoCzIeLmlvLmFnb3JhLnBiLlJ0cENhcEJlZm9yZU1lcmdlIq4BChNNdWx0aVVuaWxic1Jlc3BvbnNlEgwKBGNlcnQYASABKAkSCwoDY2lkGAIgASgNEgwKBGNvZGUYAyABKA0SJwoGZGV0YWlsGAQgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdBIqCghzZXJ2aWNlcxgFIAMoCzIYLmlvLmFnb3JhLnBiLlNlcnZpY2VJbmZvEgwKBGZsYWcYBiABKA0SCwoDdXJpGAcgASgNIkkKC1NlcnZpY2VJbmZvEgoKAmlwGAEgASgJEgwKBHBvcnQYAiABKA0SEwoLZmluZ2VycHJpbnQYAyABKAkSCwoDaWNlGAQgAygJIn0KCkFQUmVzcG9uc2USCwoDdWlkGAEgASgNEgsKA2NpZBgCIAEoDRIMCgRjZXJ0GAMgASgJEicKBmRldGFpbBgEIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QSEwoGdGlja2V0GAUgASgJSACIAQFCCQoHX3RpY2tldCK9AQoNSm9pbkZvcndhcmRlchISCgpyZWpvaW5fa2V5GAEgASgJEioKBnNpZ25hbBgCIAEoCzIaLmlvLmFnb3JhLnBiLlNpZ25hbFJlcXVlc3QSCwoDaWNlGAMgAygJEjEKC25lZ290aWF0aW9uGAQgASgLMhwuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uEiwKC2FwX3Jlc3BvbnNlGAUgASgLMhcuaW8uYWdvcmEucGIuQVBSZXNwb25zZSrbBQoVVXNlckF0dHJpYnV0ZUZlYXR1cmUxEg8KC1VOU1BFQ0lGSUVEEAASGgoWZW5hYmxlRW5jb2RlZFRyYW5zZm9ybRABEhcKE2VuYWJsZUF1ZGlvTWV0YWRhdGEQAhISCg5lbmFibGVBdWRpb1B0cxAEEh0KGWVuYWJsZU5ldHdvcmtRdWFsaXR5UHJvYmUQCBIbChdlbmFibGVQdWJsaXNoZWRVc2VyTGlzdBAQEhwKGGVuYWJsZVB1Ymxpc2hBdWRpb0ZpbHRlchAgEhoKFmVuYWJsZVVzZXJMaWNlbnNlQ2hlY2sQQBIOCgllbmFibGVSVFgQgAESFAoPZW5hYmxlTlRQUmVwb3J0EIACEhcKEmVuYWJsZUluc3RhbnRWaWRlbxCABBIZChRlbmFibGVGdWxsbGlua0F2U3luYxCACBIWChFlbmFibGVEYXRhU3RyZWFtMhCAEBIWChFlbmFibGVBdXRGZWVkYmFjaxCAIBIhChxlbmFibGVVc2VyQXV0b1JlYmFsYW5jZUNoZWNrEIBAEg4KCGVuYWJsZVhSEICAARIYChJlbmFibGVMb3NzYmFzZWRCd2UQgIACEhEKC2VuYWJsZUF1dENDEICABBIWChBlbmFibGVDQ0ZhbGxiYWNrEICACBIWChBlbmFibGVQcmVhbGxvY1BDEICAEBITCg1lbmFibGVQdWJUV0NDEICAIBITCg1lbmFibGVTdWJUV0NDEICAQBITCgxlbmFibGVQdWJSVFgQgICAARITCgxlbmFibGVTdWJSVFgQgICAAhIcChVlbmFibGVRdWFsaXR5RmFsbGJhY2sQgICABBIcChVzZW50dHNVc2VzQWJzU2VuZFRpbWUQgICACBIbChRlbmFibGVEdWFsU3RyZWFtRmxhZxCAgIAQEhEKCmRpc2FibGVGRUMQgICAIBIYChFlbmFibGVWb3NGYWxsYmFjaxCAgIBAYgZwcm90bzM",[h8,f8]),b8=M9(y8,5),C8=M9(y8,6);let I8=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.enableEncodedTransform=1]="enableEncodedTransform",e[e.enableAudioMetadata=2]="enableAudioMetadata",e[e.enableAudioPts=4]="enableAudioPts",e[e.enableNetworkQualityProbe=8]="enableNetworkQualityProbe",e[e.enablePublishedUserList=16]="enablePublishedUserList",e[e.enablePublishAudioFilter=32]="enablePublishAudioFilter",e[e.enableUserLicenseCheck=64]="enableUserLicenseCheck",e[e.enableRTX=128]="enableRTX",e[e.enableNTPReport=256]="enableNTPReport",e[e.enableInstantVideo=512]="enableInstantVideo",e[e.enableFulllinkAvSync=1024]="enableFulllinkAvSync",e[e.enableDataStream2=2048]="enableDataStream2",e[e.enableAutFeedback=4096]="enableAutFeedback",e[e.enableUserAutoRebalanceCheck=8192]="enableUserAutoRebalanceCheck",e[e.enableXR=16384]="enableXR",e[e.enableLossbasedBwe=32768]="enableLossbasedBwe",e[e.enableAutCC=65536]="enableAutCC",e[e.enableCCFallback=131072]="enableCCFallback",e[e.enablePreallocPC=262144]="enablePreallocPC",e[e.enablePubTWCC=524288]="enablePubTWCC",e[e.enableSubTWCC=1048576]="enableSubTWCC",e[e.enablePubRTX=2097152]="enablePubRTX",e[e.enableSubRTX=4194304]="enableSubRTX",e[e.enableQualityFallback=8388608]="enableQualityFallback",e[e.senttsUsesAbsSendTime=16777216]="senttsUsesAbsSendTime",e[e.enableDualStreamFlag=33554432]="enableDualStreamFlag",e[e.disableFEC=67108864]="disableFEC",e[e.enableVosFallback=134217728]="enableVosFallback",e}({});const A8={VP8:T8.VP8,VP9:T8.VP9,H264:T8.H264,H265:T8.H265,AV1:T8.AV1,G711:T8.G711,G722:T8.G722,opus:T8.OPUS,PCMU:T8.PCMU,PCMA:T8.PCMA,CN:T8.CN,"telephone-event":T8.TELEPHONE_EVENT,rtx:T8.RTX,red:T8.RED};const w8={minptime:R8.MINPTIME,useinbandfec:R8.USEINBANDFEC,"level-id":R8.LEVEL_ID,"profile-id":R8.PROFILE_ID,"tier-flag":R8.TIER_FLAG,"tx-mode":R8.TX_MODE,"level-asymmetry-allowed":R8.LEVEL_ASYMMETRY_ALLOWED,"packetization-mode":R8.PACKETIZATION_MODE,"profile-level-id":R8.PROFILE_LEVEL_ID,"level-idx":R8.LEVEL_IDX,profile:R8.PROFILE,tier:R8.TIER};const O8={"goog-remb":v8.GOOG_REMB,"transport-cc":v8.TRANSPORT_CC,ccm:v8.CCM,nack:v8.NACK,rrtr:v8.RRTR};function N8(e){if(e)return Object.keys(O8).find((t=>O8[t]===e))}const D8={"urn:ietf:params:rtp-hdrext:toffset":g8.VIDEO_EXT_HDR_TOFFSET,"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time":g8.VIDEO_EXT_ABS_SEND_TIME,"urn:3gpp:video-orientation":g8.VIDEO_EXT_ORIENTATION,"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01":g8.VIDEO_EXT_TWCC,"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay":g8.VIDEO_EXT_PLAYOUT_DELAY,"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type":g8.VIDEO_EXT_CONTENT_TYPE,"http://www.webrtc.org/experiments/rtp-hdrext/video-timing":g8.VIDEO_EXT_VIDEO_TIMING,"http://www.webrtc.org/experiments/rtp-hdrext/color-space":g8.VIDEO_EXT_COLOR_SPACE,"urn:ietf:params:rtp-hdrext:sdes:mid":g8.VIDEO_EXT_SDES_MID,"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id":g8.VIDEO_EXT_SDES_RTP_STREAM_ID,"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id":g8.VIDEO_EXT_SDED_REPAIRED_RTP_STREAM_ID},P8={"urn:ietf:params:rtp-hdrext:ssrc-audio-level":S8.AUDIO_EXT_AUDIO_LEVEL,"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time":S8.AUDIO_EXT_ABS_SEND_TIME,"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01":S8.AUDIO_EXT_TWCC,"urn:ietf:params:rtp-hdrext:sdes:mid":S8.AUDIO_EXT_SDES_MID,"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id":S8.AUDIO_EXT_SDES_RTP_STREAM_ID,"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id":S8.AUDIO_EXT_SDS_REPAIRED_RTP_STREAM_ID};function L8(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function k8(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function M8(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?k8(Object(n),!0).forEach((function(t){L8(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):k8(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function U8(e,t){return typeof rL(e)===t?rL(e):void 0}function V8(){try{const e=rL("EXPERIMENTS")||{};return"string"==typeof e||Array.isArray(e)?{}:M8({},e)}catch(e){return FL.debug("handle gateway attributes failed: ",e),{}}}function x8(e,t,n){var i,r;let o=n.mode,s=n.codec,a=n.joinGatewayStartTime,c=n.hasChangeBGPAddress;const d="apResponse"in t?Object.assign({},t.apResponse):void 0;let l=!1;var u,h;d&&(l=!!rL("ENABLE_AP_MULTI_IP")&&"multi-ip"===(null===(u=d.detail)||void 0===u?void 0:u[5]),"CN"===(null===(h=d.detail)||void 0===h?void 0:h[3])&&rL("ENABLE_QUALITY_FALLBACK")&&rL("ENABLE_QUALITY_FALLBACK"));let p=rL("REPORT_APP_SCENARIO");if("string"!=typeof p)try{p=JSON.stringify(p)}catch(e){p=void 0}p&&p.length>128&&(p=void 0);const _="proxy3"===t.cloudProxyServer?"1":"proxy5"===t.cloudProxyServer?"2":void 0,E=function(e,t,n,i,r){var o,s,a,c;n=Object.assign({},n);const d=gk(e),l=Sk(e),u=(null===(o=e.preSubOptions)||void 0===o?void 0:o.length)||0,h=u>0?null===(s=e.preSubOptions)||void 0===s?void 0:s.map((e=>e.uid)):void 0,p=U8("PRE_SUB_NUM","number")||1,_=u>p?u:p,E=V8(),m=(fN()||AN(18,4,!1))&&ON(18,6,!0)&&"h264"===t&&rL("ENABLE_ABSSENDTIME_AS_SENTTS"),f=!("CN"!==(null===(a=n.detail)||void 0===a?void 0:a[3])||!rL("ENABLE_QUALITY_FALLBACK"))&&rL("ENABLE_QUALITY_FALLBACK"),g=M8(M8({enableEncodedTransform:(!!rL("ENABLE_AUDIO_METADATA")||!!rL("ENABLE_AUDIO_PTS"))&&F8||!!rL("ENABLE_AUDIO_TOPN")&&yN(oN.CHROME,87,116)||void 0,enableAudioMetadata:!!rL("ENABLE_AUDIO_METADATA")&&F8,enableAudioPts:!!rL("ENABLE_AUDIO_PTS")&&F8,topnSmoothLevel:rL("TOPN_SMOOTH_LEVEL"),topnNewSpeakerDelay:rL("TOPN_NEW_SPEAKER_DELAY"),topnSwitchHoldMs:rL("TOPN_SWITCH_HOLD_MS"),topnAudioGain:rL("TOPN_AUDIO_GAIN"),enableNetworkQualityProbe:e.networkQualityProbe,enablePublishedUserList:rL("ENABLE_PUBLISHED_USER_LIST"),enableUserList:rL("ENABLE_USER_LIST"),maxSubscription:rL("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:U8("SUBSCRIBE_AUDIO_FILTER_TOPN","number"),enablePublishAudioFilter:U8("ENABLE_PUBLISH_AUDIO_FILTER","boolean"),enableUserLicenseCheck:U8("ENABLE_USER_LICENSE_CHECK","boolean"),enableRTX:!0===rL("USE_PUB_RTX")||!0===rL("USE_SUB_RTX")||void 0,disableFEC:rL("DISABLE_FEC"),enableNTPReport:!!rL("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:l,enableFulllinkAvSync:!!rL("ENABLE_FULL_LINK_AV_SYNC")||void 0,enableDataStream2:U8("ENABLE_DATASTREAM_2","boolean"),enableAutFeedback:Rk(),rtm2Flag:"number"==typeof i?i:void 0,enableUserAutoRebalanceCheck:!!rL("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:U8("USE_XR","boolean"),enableLossbasedBwe:U8("ENABLE_LOSSBASED_BWE","boolean"),enableAutCC:Tk(),enableCCFallback:U8("ENABLE_CC_FALLBACK","boolean"),preSubUid:d?h:void 0,preSubNum:d?_:void 0,enablePubTWCC:U8("PUBLISH_TWCC","boolean"),enableSubTWCC:U8("SUBSCRIBE_TWCC","boolean"),enablePubRTX:U8("USE_PUB_RTX","boolean"),enableSubRTX:U8("USE_SUB_RTX","boolean"),enableSubSVC:rL("ENABLE_SVC")?rL("ENABLE_SVC_DEFAULT_CODECS"):Array.isArray(rL("SVC"))&&0!==rL("SVC").length?rL("SVC"):void 0,enableSvcExtended:rL("ENABLE_SVC")&&Array.isArray(rL("SVC_EXTENDED"))&&0!==rL("SVC_EXTENDED").length?rL("SVC_EXTENDED"):void 0,enableVosFallback:rL("ENABLE_VOS_FALLBACK"),enableQualityFallback:f},E),{},{audioDuplicate:U8("ENABLE_AUDIO_RED","boolean")?null!==(c=U8("AUDIO_DUPLICATE_NUM","number"))&&void 0!==c?c:2:void 0,senttsUsesAbsSendTime:!!m||void 0,enableDualStreamFlag:U8("ENABLE_DUAL_STREAM_FLAG","boolean")});for(const e in g)void 0===g[e]&&delete g[e],Array.isArray(g[e])&&0===g[e].length&&delete g[e],"enablePreallocPC"===e&&delete g[e];return g.enablePreallocPC=!0,g}(e,s,d,t.rtmFlag),m=M8(M8(M8(M8(M8({},t.license?{license:t.license}:{}),{},{p2pId:e.p2pId,sessionId:t.sid,appId:t.appId,channelKey:null!==(i=t.token)&&void 0!==i?i:t.appId,channelName:t.cname,sdkVersion:JP,processId:rL("PROCESS_ID"),mode:e.useP2P?"p2p":o,codec:s,role:null!==(r=t.role)&&void 0!==r?r:"audience",hasChangedGateway:l||c,extend:rL("JOIN_EXTEND")},_?{cservice_map:_}:{}),t.optionalInfo?{optionalInfo:t.optionalInfo}:{}),p?{appScenario:p}:{}),{},{attributes:B8(E),requestTs:(f=a,Number(f))});var f;return t.stringUid&&(m.stringUid=t.stringUid),t.aesmode&&t.aespassword&&(m.aesMode=t.aesmode,rL("ENCRYPT_AES")?(m.aesSecret=t.aespassword,m.aesEncrypt=!0):m.aesSecret=t.aespassword,t.aessalt&&(m.aesSalt=t.aessalt)),void 0!==t.defaultVideoStream&&(m.defaultVideoStream=t.defaultVideoStream),m}const F8=RN(87)||mN()||CN(117);function B8(e){const t={enableSubSVC:[],enableSvcExtended:[]},n=["topnSmoothLevel","topnNewSpeakerDelay","topnSwitchHoldMs","topnAudioGain","maxSubscription","subscribeAudioFilterTopN","rtm2Flag","preSubNum","enableSubSVC","enableSvcExtended","audioDuplicate","preSubUid"],i={};for(const e in I8){const t=I8[e];"number"==typeof t&&0!==t&&(i[e]=t)}const r=[],o={};for(const s in e){const a=e[s];if(s in i&&!0===a){const e=i[s];let t,n;for(e<4294967296?(t=0,n=e):(t=1,n=1<<Math.floor(Math.log2(e))-32);r.length<=t;)r.push(0);r[t]|=n}else Vi(n).call(n,s)?t[s]=a:s in i||(o[s]=a)}r.length>0&&r.forEach(((e,n)=>{void 0!==e&&0!==e&&(t["feature".concat(n+1)]=e)}));const s=Object.keys(o);s.length>0&&(t.experiments=o,s.forEach((e=>{e in t&&delete t[e]})));for(const e in t)void 0===t[e]&&delete t[e],Array.isArray(t[e])&&0===t[e].length&&delete t[e];return t}function j8(e){var t,n,i,r;const o=function(e){if(e)return A8[e]||void 0}(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName),s=o||null===(n=e.rtpMap)||void 0===n?void 0:n.encodingName,a=null===(i=e.rtpMap)||void 0===i?void 0:i.encodingParameters,c=null===(r=e.fmtp)||void 0===r?void 0:r.parameters;let d,l;c&&Object.keys(c).forEach((e=>{const t=function(e){if(e)return w8[e]||void 0}(e);t?(d||(d={}),d[t]=c[e]+""):(l||(l={}),l[e]=c[e]+"")}));const u=d||l?M8(M8({},d?{enumParameters:d}:{}),l?{stringParameters:l}:{}):void 0;return M8(M8({payloadType:e.payloadType,rtpMap:e.rtpMap?M8(M8(M8({},o?{enumEncodingName:o}:{}),s?{stringEncodingName:s}:{}),{},{clockRate:e.rtpMap.clockRate+""},a?{encodingParameters:a}:{}):void 0},u?{fmtp:u}:{}),{},{rtcpFeedbacks:e.rtcpFeedbacks.map((e=>{const t=function(e){if(e)return O8[e]||void 0}(e.type),n=M8(M8(M8({},"parameter"in e&&e.parameter?{parameter:e.parameter}:{}),"additional"in e&&e.additional?{additional:e.additional}:{}),"interval"in e&&e.interval?{interval:e.interval}:{});return M8(t?{enumType:t}:{stringType:e.type},n)}))})}function G8(e){let t;if(e.rtpMap){const n=e.rtpMap,i=n.enumEncodingName,r=n.stringEncodingName,o=n.clockRate,s=n.encodingParameters,a=i?function(e){if(e)return Object.keys(A8).find((t=>A8[t]===e))}(i):r;t={encodingName:null!=a?a:"",clockRate:(null==o?void 0:o.kind.value)+"",encodingParameters:s}}const n={parameters:{}};if(e.fmtp){const t=e.fmtp,i=t.enumParameters,r=t.stringParameters;i&&Object.keys(i).forEach((e=>{const t=function(e){if(e)return Object.keys(w8).find((t=>w8[t]===e))}(e);t&&(n.parameters[t]=i[e].kind.value+"")})),r&&Object.keys(r).forEach((e=>{n.parameters[e]=r[e].kind.value+""}))}let i=[];return e.rtcpFeedbacks&&(i=e.rtcpFeedbacks.map((e=>{const t=e.enumType,n=e.stringType,i=e.parameter,r=e.additional,o=e.interval,s=M8(M8(M8({},i?{parameter:i}:{}),r?{additional:r}:{}),o?{interval:o}:{});return M8(t?{type:N8(t)+""}:{type:n+""},s)}))),{payloadType:e.payloadType,rtpMap:t,fmtp:n,rtcpFeedbacks:i}}function W8(e,t){const n=function(e,t){if("video"===e){const e=D8[t];return"number"==typeof e?e:void 0}if("audio"===e){const e=D8[t];return"number"==typeof e?e:void 0}}(e,t.extensionName);return{entry:t.entry,extensionName:"number"==typeof n?n:t.extensionName}}function K8(e,t){var n,i;const r=function(e,t){if(t||"number"==typeof t)return"video"===e?Object.keys(D8).find((e=>D8[e]===t)):Object.keys(P8).find((e=>P8[e]===t))}(e,Number(null===(n=t.extensionName)||void 0===n?void 0:n.kind.value))||(null===(i=t.extensionName)||void 0===i?void 0:i.kind.value);return{entry:t.entry,extensionName:r+""}}function H8(e){var t,n,i,r,o,s,a,c,d,l,u,h,p,_,E,m,f,g,S,T,R,v,y,b;const C={audioCodecs:null!==(t=null===(n=e.rtpCapabilities.send)||void 0===n?void 0:n.audioCodecs.map((e=>j8(e))))&&void 0!==t?t:[],videoCodecs:null!==(i=null===(r=e.rtpCapabilities.send)||void 0===r?void 0:r.videoCodecs.map((e=>j8(e))))&&void 0!==i?i:[],audioExtensions:null!==(o=null===(s=e.rtpCapabilities.send)||void 0===s?void 0:s.audioExtensions.map((e=>W8("audio",e))))&&void 0!==o?o:[],videoExtensions:null!==(a=null===(c=e.rtpCapabilities.send)||void 0===c?void 0:c.videoExtensions.map((e=>W8("video",e))))&&void 0!==a?a:[]},I={audioCodecs:null!==(d=null===(l=e.rtpCapabilities.recv)||void 0===l?void 0:l.audioCodecs.map((e=>j8(e))))&&void 0!==d?d:[],videoCodecs:null!==(u=null===(h=e.rtpCapabilities.recv)||void 0===h?void 0:h.videoCodecs.map((e=>j8(e))))&&void 0!==u?u:[],audioExtensions:null!==(p=null===(_=e.rtpCapabilities.recv)||void 0===_?void 0:_.audioExtensions.map((e=>W8("audio",e))))&&void 0!==p?p:[],videoExtensions:null!==(E=null===(m=e.rtpCapabilities.recv)||void 0===m?void 0:m.videoExtensions.map((e=>W8("video",e))))&&void 0!==E?E:[]},A={audioCodecs:null!==(f=null===(g=e.rtpCapabilities.sendrecv)||void 0===g?void 0:g.audioCodecs.map((e=>j8(e))))&&void 0!==f?f:[],videoCodecs:null!==(S=null===(T=e.rtpCapabilities.sendrecv)||void 0===T?void 0:T.videoCodecs.map((e=>j8(e))))&&void 0!==S?S:[],audioExtensions:null!==(R=null===(v=e.rtpCapabilities.sendrecv)||void 0===v?void 0:v.audioExtensions.map((e=>W8("audio",e))))&&void 0!==R?R:[],videoExtensions:null!==(y=null===(b=e.rtpCapabilities.sendrecv)||void 0===b?void 0:b.videoExtensions.map((e=>W8("video",e))))&&void 0!==y?y:[]};return{ice:[e.iceParameters.iceUfrag,e.iceParameters.icePwd],dtls:e.dtlsParameters.fingerprints.map((e=>({[e.hashFunction]:e.fingerprint}))),send:C,recv:I,sendRecv:A}}function Y8(e,t,n){var i,r,o,s,a,c,d,l,u,h,p,_,E,m,f,g,S,T,R,v,y,b,C,I,A,w,O,N,D,P,L,k;t&&t.sendRecv&&(t.send={$typeName:"io.agora.pb.RtpCap",audioCodecs:[...(null===(S=t.send)||void 0===S?void 0:S.audioCodecs)||[],...t.sendRecv.audioCodecs],videoCodecs:[...(null===(T=t.send)||void 0===T?void 0:T.videoCodecs)||[],...t.sendRecv.videoCodecs],audioExtensions:[...(null===(R=t.send)||void 0===R?void 0:R.audioExtensions)||[],...t.sendRecv.audioExtensions],videoExtensions:[...(null===(v=t.send)||void 0===v?void 0:v.videoExtensions)||[],...t.sendRecv.videoExtensions]},t.recv={$typeName:"io.agora.pb.RtpCap",audioCodecs:[...(null===(y=t.recv)||void 0===y?void 0:y.audioCodecs)||[],...t.sendRecv.audioCodecs],videoCodecs:[...(null===(b=t.recv)||void 0===b?void 0:b.videoCodecs)||[],...t.sendRecv.videoCodecs],audioExtensions:[...(null===(C=t.recv)||void 0===C?void 0:C.audioExtensions)||[],...t.sendRecv.audioExtensions],videoExtensions:[...(null===(I=t.recv)||void 0===I?void 0:I.videoExtensions)||[],...t.sendRecv.videoExtensions]}),n&&n.sendRecv&&(n.send={$typeName:"io.agora.pb.RtpCap",audioCodecs:[...(null===(A=n.send)||void 0===A?void 0:A.audioCodecs)||[],...n.sendRecv.audioCodecs],videoCodecs:[...(null===(w=n.send)||void 0===w?void 0:w.videoCodecs)||[],...n.sendRecv.videoCodecs],audioExtensions:[...(null===(O=n.send)||void 0===O?void 0:O.audioExtensions)||[],...n.sendRecv.audioExtensions],videoExtensions:[...(null===(N=n.send)||void 0===N?void 0:N.videoExtensions)||[],...n.sendRecv.videoExtensions]},n.recv={$typeName:"io.agora.pb.RtpCap",audioCodecs:[...(null===(D=n.recv)||void 0===D?void 0:D.audioCodecs)||[],...n.sendRecv.audioCodecs],videoCodecs:[...(null===(P=n.recv)||void 0===P?void 0:P.videoCodecs)||[],...n.sendRecv.videoCodecs],audioExtensions:[...(null===(L=n.recv)||void 0===L?void 0:L.audioExtensions)||[],...n.sendRecv.audioExtensions],videoExtensions:[...(null===(k=n.recv)||void 0===k?void 0:k.videoExtensions)||[],...n.sendRecv.videoExtensions]});const M=t?{send:{audioCodecs:(null===(i=t.send)||void 0===i?void 0:i.audioCodecs.map((e=>G8(e))))||[],videoCodecs:(null===(r=t.send)||void 0===r?void 0:r.videoCodecs.map((e=>G8(e))))||[],audioExtensions:(null===(o=t.send)||void 0===o?void 0:o.audioExtensions.map((e=>K8("audio",e))))||[],videoExtensions:(null===(s=t.send)||void 0===s?void 0:s.videoExtensions.map((e=>K8("video",e))))||[]},recv:{audioCodecs:(null===(a=t.recv)||void 0===a?void 0:a.audioCodecs.map((e=>G8(e))))||[],videoCodecs:(null===(c=t.recv)||void 0===c?void 0:c.videoCodecs.map((e=>G8(e))))||[],audioExtensions:(null===(d=t.recv)||void 0===d?void 0:d.audioExtensions.map((e=>K8("audio",e))))||[],videoExtensions:(null===(l=t.recv)||void 0===l?void 0:l.videoExtensions.map((e=>K8("video",e))))||[]}}:void 0,U=n?{send:{audioCodecs:(null===(u=n.send)||void 0===u?void 0:u.audioCodecs.map((e=>G8(e))))||[],videoCodecs:(null===(h=n.send)||void 0===h?void 0:h.videoCodecs.map((e=>G8(e))))||[],audioExtensions:(null===(p=n.send)||void 0===p?void 0:p.audioExtensions.map((e=>K8("audio",e))))||[],videoExtensions:(null===(_=n.send)||void 0===_?void 0:_.videoExtensions.map((e=>K8("video",e))))||[]},recv:{audioCodecs:(null===(E=n.recv)||void 0===E?void 0:E.audioCodecs.map((e=>G8(e))))||[],videoCodecs:(null===(m=n.recv)||void 0===m?void 0:m.videoCodecs.map((e=>G8(e))))||[],audioExtensions:(null===(f=n.recv)||void 0===f?void 0:f.audioExtensions.map((e=>K8("audio",e))))||[],videoExtensions:(null===(g=n.recv)||void 0===g?void 0:g.videoExtensions.map((e=>K8("video",e))))||[]}}:void 0,V={send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},x=e.send,F=e.recv,B=e.sendrecv;return x&&(V.send.audioCodecs.push(...x.audioCodecs),V.send.videoCodecs.push(...x.videoCodecs),V.send.audioExtensions.push(...x.audioExtensions),V.send.videoExtensions.push(...x.videoExtensions)),F&&(V.recv.audioCodecs.push(...F.audioCodecs),V.recv.videoCodecs.push(...F.videoCodecs),V.recv.audioExtensions.push(...F.audioExtensions),V.recv.videoExtensions.push(...F.videoExtensions)),B&&(V.send.audioCodecs.push(...B.audioCodecs),V.send.videoCodecs.push(...B.videoCodecs),V.send.audioExtensions.push(...B.audioExtensions),V.send.videoExtensions.push(...B.videoExtensions),V.recv.audioCodecs.push(...B.audioCodecs),V.recv.videoCodecs.push(...B.videoCodecs),V.recv.audioExtensions.push(...B.audioExtensions),V.recv.videoExtensions.push(...B.videoExtensions)),M&&(V.send.audioCodecs.push(...M.send.audioCodecs),V.send.videoCodecs.push(...M.send.videoCodecs),V.send.audioExtensions.push(...M.send.audioExtensions),V.send.videoExtensions.push(...M.send.videoExtensions),V.recv.audioCodecs.push(...M.recv.audioCodecs),V.recv.videoCodecs.push(...M.recv.videoCodecs),V.recv.audioExtensions.push(...M.recv.audioExtensions),V.recv.videoExtensions.push(...M.recv.videoExtensions)),U&&(U.send.audioCodecs.forEach((e=>{V.send.audioCodecs=V.send.audioCodecs.filter((t=>t.payloadType!==e.payloadType))})),U.send.videoCodecs.forEach((e=>{V.send.videoCodecs=V.send.videoCodecs.filter((t=>t.payloadType!==e.payloadType))})),U.send.audioExtensions.forEach((e=>{V.send.audioExtensions=V.send.audioExtensions.filter((t=>t.entry!==e.entry))})),U.send.videoExtensions.forEach((e=>{V.send.videoExtensions=V.send.videoExtensions.filter((t=>t.entry!==e.entry))})),U.recv.audioCodecs.forEach((e=>{V.recv.audioCodecs=V.recv.audioCodecs.filter((t=>t.payloadType!==e.payloadType))})),U.recv.videoCodecs.forEach((e=>{V.recv.videoCodecs=V.recv.videoCodecs.filter((t=>t.payloadType!==e.payloadType))}))),{send:V.recv,recv:V.send}}function X8(e,t){Z8(t,e);const n=function(e,t){if(void 0===e)return[];if("enum"===t.fieldKind||"scalar"===t.fieldKind){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.number)return[e[n]];return[]}return e.filter((e=>e.no===t.number))}(e.$unknown,t),i=M5(z8(t),3),r=i[0],o=i[1],s=i[2];for(const e of n)s8(r,new _6(e.data),o,e.wireType,{readUnknownFields:!0});return s()}function J8(e,t,n){var i;Z8(t,e);const r=(null!==(i=e.$unknown)&&void 0!==i?i:[]).filter((e=>e.no!==t.number)),o=M5(z8(t,n),2),s=o[0],a=o[1],c=new p6;u9(c,{writeUnknownFields:!0},s,a);const d=new _6(c.finish());for(;d.pos<d.len;){const e=M5(d.tag(),2),t=e[0],n=e[1],i=d.skip(n,t);r.push({no:t,wireType:n,data:i})}e.$unknown=r}function z8(e,t){const n=e.typeName,i=Object.assign(Object.assign({},e),{kind:"field",parent:e.extendee,localName:n}),r=Object.assign(Object.assign({},e.extendee),{fields:[i],members:[i],oneofs:[]}),o=P6(r,void 0!==t?{[n]:t}:void 0);return[G6(r,o),i,()=>{const t=o[n];if(void 0===t){const t=e.message;return I6(t)?lq(t.fields[0].scalar,t.fields[0].longAsString):P6(t)}return t}]}function Z8(e,t){if(e.extendee.typeName!=t.$typeName)throw new Error("extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}const q8=3,Q8=2,$8={alwaysEmitImplicit:!1,enumAsInteger:!1,useProtoFieldName:!1};function e7(e,t){var n;const i=o7(e,t);if(void 0!==i)return i;const r={};for(const n of e.sortedFields){if(!e.isSet(n)){if(n.presence==q8)throw new Error("cannot encode ".concat(n," to JSON: required field not set"));if(!t.alwaysEmitImplicit||n.presence!==Q8)continue}const i=t7(n,e.get(n),t);void 0!==i&&(r[r7(n,t)]=i)}if(t.registry){const i=new Set;for(const o of null!==(n=e.getUnknown())&&void 0!==n?n:[]){const n=o.no;if(!i.has(n)){i.add(n);const o=t.registry.getExtensionFor(e.desc,n);if(!o)continue;const s=M5(z8(o,X8(e.message,o)),2),a=s[0],c=s[1],d=t7(c,a.get(c),t);void 0!==d&&(r[o.jsonName]=d)}}}return r}function t7(e,t,n){switch(e.fieldKind){case"scalar":return i7(e,t);case"message":return e7(t,n);case"enum":return n7(e.enum,t,n.enumAsInteger);case"list":return function(e,t){const n=e.field(),i=[];switch(n.listKind){case"scalar":for(const t of e)i.push(i7(n,t));break;case"enum":for(const r of e)i.push(n7(n.enum,r,t.enumAsInteger));break;case"message":for(const n of e)i.push(e7(n,t))}return t.alwaysEmitImplicit||i.length>0?i:void 0}(t,n);case"map":return function(e,t){const n=e.field(),i={};switch(n.mapKind){case"scalar":for(const t of e){var r=M5(t,2);const e=r[0],o=r[1];i[e]=i7(n,o)}break;case"message":for(const n of e){var o=M5(n,2);const e=o[0],r=o[1];i[e]=e7(r,t)}break;case"enum":for(const r of e){var s=M5(r,2);const e=s[0],o=s[1];i[e]=n7(n.enum,o,t.enumAsInteger)}}return t.alwaysEmitImplicit||e.size>0?i:void 0}(t,n)}}function n7(e,t,n){var i;if("number"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: expected number, got ").concat(v6(t)));if("google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const r=e.value[t];return null!==(i=null==r?void 0:r.name)&&void 0!==i?i:t}function i7(e,t){var n,i,r,o,s,a;switch(e.scalar){case dq.INT32:case dq.SFIXED32:case dq.SINT32:case dq.FIXED32:case dq.UINT32:if("number"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(n=f6(e,t))||void 0===n?void 0:n.message));return t;case dq.FLOAT:case dq.DOUBLE:if("number"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(i=f6(e,t))||void 0===i?void 0:i.message));return Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case dq.STRING:if("string"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(r=f6(e,t))||void 0===r?void 0:r.message));return t;case dq.BOOL:if("boolean"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(o=f6(e,t))||void 0===o?void 0:o.message));return t;case dq.UINT64:case dq.FIXED64:case dq.INT64:case dq.SFIXED64:case dq.SINT64:if("bigint"==typeof t||"string"==typeof t||"number"==typeof t&&Number.isInteger(t))return t.toString();throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(s=f6(e,t))||void 0===s?void 0:s.message));case dq.BYTES:if(t instanceof Uint8Array)return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"std";const n=bQ(t),i="std"==t;let r,o="",s=0,a=0;for(let t=0;t<e.length;t++)switch(r=e[t],s){case 0:o+=n[r>>2],a=(3&r)<<4,s=1;break;case 1:o+=n[a|r>>4],a=(15&r)<<2,s=2;break;case 2:o+=n[a|r>>6],o+=n[63&r],s=0}return s&&(o+=n[a],i&&(o+="=",1==s&&(o+="="))),o}(t);throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(a=f6(e,t))||void 0===a?void 0:a.message))}}function r7(e,t){return t.useProtoFieldName?e.name:e.jsonName}function o7(e,t){var n;if(e.desc.typeName.startsWith("google.protobuf."))switch(e.desc.typeName){case"google.protobuf.Any":return function(e,t){if(""===e.typeUrl)return{};const n=t.registry;let i,r;if(n&&(i=function(e,t){if(""===e.typeUrl)return;const n="message"==t.kind?t:t.getMessage(u8(e.typeUrl));return n&&function(e,t){return""!==e.typeUrl&&("string"==typeof t?t:t.typeName)===u8(e.typeUrl)}(e,n)?r8(n,e.value):void 0}(e,n),i&&(r=n.getMessage(i.$typeName))),!r||!i)throw new Error("cannot encode message ".concat(e.$typeName,' to JSON: "').concat(e.typeUrl,'" is not in the type registry'));const o=G6(r,i),s=A6(r)?{value:o7(o,t)}:e7(o,t);return s["@type"]=e.typeUrl,s}(e.message,t);case"google.protobuf.Timestamp":return function(e){const t=1e3*Number(e.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode message ".concat(e.$typeName," to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive"));if(e.nanos<0)throw new Error("cannot encode message ".concat(e.$typeName," to JSON: nanos must not be negative"));if(e.nanos>999999999)throw new Error("cannot encode message ".concat(e.$typeName," to JSON: nanos must not be greater than 99999999"));let n="Z";if(e.nanos>0){const t=(e.nanos+1e9).toString().substring(1);n="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(t).toISOString().replace(".000Z",n)}(e.message);case"google.protobuf.Duration":return function(e){const t=Number(e.seconds),n=e.nanos;if(t>315576e6||t<-315576e6)throw new Error("cannot encode message ".concat(e.$typeName," to JSON: value out of range"));if(t>0&&n<0||t<0&&n>0)throw new Error("cannot encode message ".concat(e.$typeName," to JSON: nanos sign must match seconds sign"));let i=e.seconds.toString();if(0!==n){let e=Math.abs(n).toString();e="0".repeat(9-e.length)+e,"000000"===e.substring(3)?e=e.substring(0,3):"000"===e.substring(6)&&(e=e.substring(0,6)),i+="."+e,n<0&&0==t&&(i="-"+i)}return i+"s"}(e.message);case"google.protobuf.FieldMask":return(n=e.message).paths.map((e=>{if(_K(pK(e))!==e)throw new Error("cannot encode message ".concat(n.$typeName,' to JSON: lowerCamelCase of path name "').concat(e,'" is irreversible'));return pK(e)})).join(",");case"google.protobuf.Struct":return s7(e.message);case"google.protobuf.Value":return a7(e.message);case"google.protobuf.ListValue":return c7(e.message);default:if(I6(e.desc)){const t=e.desc.fields[0];return i7(t,e.get(t))}return}}function s7(e){const t={};for(const i of Object.entries(e.fields)){var n=M5(i,2);const e=n[0],r=n[1];t[e]=a7(r)}return t}function a7(e){switch(e.kind.case){case"nullValue":return null;case"numberValue":if(!Number.isFinite(e.kind.value))throw new Error("".concat(e.$typeName," cannot be NaN or Infinity"));return e.kind.value;case"boolValue":case"stringValue":return e.kind.value;case"structValue":return s7(e.kind.value);case"listValue":return c7(e.kind.value);default:throw new Error("".concat(e.$typeName," must have a value"))}}function c7(e){return XZ(e).map(a7)}var d7="\t\n\v\f\r                　\u2028\u2029\ufeff",l7=BK,u7=A$,h7=d7,p7=AK("".replace),_7=RegExp("^["+h7+"]+"),E7=RegExp("(^|[^"+h7+"])["+h7+"]+$"),m7=function(e){return function(t){var n=u7(l7(t));return 1&e&&(n=p7(n,_7,"")),2&e&&(n=p7(n,E7,"$1")),n}},f7={start:m7(1),end:m7(2),trim:m7(3)},g7=TJ.PROPER,S7=RK,T7=d7,R7=ZS(f7);_J({target:"String",proto:!0,forced:function(e){return S7((function(){return!!T7[e]()||"​᠎"!=="​᠎"[e]()||g7&&T7[e].name!==e}))}("trim")},{trim:function(){return R7(this)}});var v7=FZ("String","trim"),y7=vH,b7=v7,C7=String.prototype,I7=gK((function(e){var t=ZS(e);return"string"==typeof e||e===C7||y7(C7,e)&&t===ZS(C7)?b7:t}));const A7={ignoreUnknownFields:!1};const w7=new WeakMap;function O7(e,t){var n;if(!w7.has(e)){const t=new Map;for(const n of e.fields)t.set(n.name,n).set(n.jsonName,n);w7.set(e,t)}return null===(n=w7.get(e))||void 0===n?void 0:n.get(t)}function N7(e,t,n){var i;if(function(e,t,n){if(!e.desc.typeName.startsWith("google.protobuf."))return!1;switch(e.desc.typeName){case"google.protobuf.Any":return function(e,t,n){var i;if(null===t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: expected object but got ").concat(v6(t)));if(0==Object.keys(t).length)return;const r=t["@type"];if("string"!=typeof r||""==r)throw new Error("cannot decode message ".concat(e.$typeName,' from JSON: "@type" is empty'));const o=Q4(r).call(r,"/")?r.substring(r.lastIndexOf("/")+1):r;if(!o.length)throw new Error("cannot decode message ".concat(e.$typeName,' from JSON: "@type" is invalid'));const s=null===(i=n.registry)||void 0===i?void 0:i.getMessage(o);if(!s)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(r," is not in the type registry"));const a=G6(s);if(A6(s)&&Object.prototype.hasOwnProperty.call(t,"value"))N7(a,t.value,n);else{const e=Object.assign({},t);delete e["@type"],N7(a,e,n)}!function(e,t,n){var i;n||(n=P6(l8)),n.value=d9(e,t),n.typeUrl=(i=t.$typeName,"type.googleapis.com/".concat(i))}(a.desc,a.message,e)}(e.message,t,n),!0;case"google.protobuf.Timestamp":return function(e,t){if("string"!=typeof t)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(v6(t)));const n=t.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]{1,9}))?(?:Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: invalid RFC 3339 string"));const i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("cannot decode message ".concat(e.$typeName," from JSON: invalid RFC 3339 string"));if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message ".concat(e.$typeName," from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive"));e.seconds=sq.parse(i/1e3),e.nanos=0,n[7]&&(e.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9)}(e.message,t),!0;case"google.protobuf.Duration":return function(e,t){if("string"!=typeof t)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(v6(t)));const n=t.match(/^(-?[0-9]+)(?:\.([0-9]+))?s/);if(null===n)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(v6(t)));const i=Number(n[1]);if(i>315576e6||i<-315576e6)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(v6(t)));if(e.seconds=sq.parse(i),"string"!=typeof n[2])return;const r=n[2]+"0".repeat(9-n[2].length);e.nanos=parseInt(r),(i<0||Object.is(i,-0))&&(e.nanos=-e.nanos)}(e.message,t),!0;case"google.protobuf.FieldMask":return function(e,t){if("string"!=typeof t)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(v6(t)));""!==t&&(e.paths=t.split(",").map((t=>{if(Q4(t).call(t,"_"))throw new Error("cannot decode message ".concat(e.$typeName," from JSON: path names must be lowerCamelCase"));return _K(t)})))}(e.message,t),!0;case"google.protobuf.Struct":return F7(e.message,t),!0;case"google.protobuf.Value":return B7(e.message,t),!0;case"google.protobuf.ListValue":return j7(e.message,t),!0;default:if(I6(e.desc)){const n=e.desc.fields[0];return null===t?e.clear(n):e.set(n,U7(n,t)),!0}return!1}}(e,t,n))return;if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode ".concat(e.desc," from JSON: ").concat(v6(t)));const r=new Map;for(const s of Object.entries(t)){var o=M5(s,2);const t=o[0],a=o[1],c=O7(e.desc,t);if(c){if(c.oneof){if(null===a&&"scalar"==c.fieldKind)continue;const e=r.get(c.oneof);if(void 0!==e)throw new e6(c.oneof,"oneof set multiple times by ".concat(e.name," and ").concat(c.name));r.set(c.oneof,c)}D7(e,c,a,n)}else{let r;if(t.startsWith("[")&&t.endsWith("]")&&(r=null===(i=n.registry)||void 0===i?void 0:i.getExtension(t.substring(1,t.length-1)))&&r.extendee.typeName===e.desc.typeName){const t=M5(z8(r),3),i=t[0],o=t[1],s=t[2];D7(i,o,a,n),J8(e.message,r,s())}if(!r&&!n.ignoreUnknownFields)throw new Error("cannot decode ".concat(e.desc,' from JSON: key "').concat(t,'" is unknown'))}}}function D7(e,t,n,i){switch(t.fieldKind){case"scalar":!function(e,t,n){null===n?e.clear(t):e.set(t,U7(t,n))}(e,t,n);break;case"enum":!function(e,t,n,i){if(L7(t,n))return void e.clear(t);const r=M7(t.enum,n,i.ignoreUnknownFields);r!==k7&&e.set(t,r)}(e,t,n,i);break;case"message":!function(e,t,n,i){if(L7(t,n))return void e.clear(t);const r=e.isSet(t)?e.get(t):G6(t.message);N7(r,n,i),e.set(t,r)}(e,t,n,i);break;case"list":!function(e,t,n){if(null===t)return;const i=e.field();if(!Array.isArray(t))throw new e6(i,"expected Array, got "+v6(t));for(const r of t){const t=P7(i,r,n);t!==k7&&e.add(t)}}(e.get(t),n,i);break;case"map":!function(e,t,n){if(null===t)return;const i=e.field();if("object"!=typeof t||Array.isArray(t))throw new e6(i,"expected object, got "+v6(t));for(const o of Object.entries(t)){var r=M5(o,2);const t=r[0],s=r[1],a=V7(i.mapKey,t),c=P7(i,s,n);c!==k7&&e.set(a,c)}}(e.get(t),n,i)}}function P7(e,t,n){if(e.scalar&&null!==t)return U7(e,t);if(e.message&&!L7(e,t)){const i=G6(e.message);return N7(i,t,n),i}if(e.enum&&!L7(e,t))return M7(e.enum,t,n.ignoreUnknownFields);throw new e6(e,"".concat("list"===e.fieldKind?"list item":"map value"," must not be null"))}function L7(e,t){var n,i;return null===t&&"google.protobuf.Value"!=(null===(n=e.message)||void 0===n?void 0:n.typeName)&&"google.protobuf.NullValue"!=(null===(i=e.enum)||void 0===i?void 0:i.typeName)}const k7=Symbol();function M7(e,t,n){if(null===t)return XZ(e)[0].number;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const i=XZ(e).find((e=>e.name===t));if(void 0!==i)return i.number;if(n)return k7}throw new Error("cannot decode ".concat(e," from JSON: ").concat(v6(t)))}function U7(e,t){switch(e.scalar){case dq.DOUBLE:case dq.FLOAT:if("NaN"===t)return NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if("number"==typeof t){if(Number.isNaN(t))throw new e6(e,"unexpected NaN number");if(!Number.isFinite(t))throw new e6(e,"unexpected infinite number");break}if("string"==typeof t){if(""===t)break;if(I7(t).call(t).length!==t.length)break;const e=Number(t);if(!Number.isFinite(e))break;return e}break;case dq.INT32:case dq.FIXED32:case dq.SFIXED32:case dq.SINT32:case dq.UINT32:return x7(t);case dq.BYTES:if("string"==typeof t){if(""===t)return new Uint8Array(0);try{return TQ(t)}catch(t){const n=t instanceof Error?t.message:String(t);throw new e6(e,n)}}}return t}function V7(e,t){switch(e){case dq.BOOL:switch(t){case"true":return!0;case"false":return!1}return t;case dq.INT32:case dq.FIXED32:case dq.UINT32:case dq.SFIXED32:case dq.SINT32:return x7(t);default:return t}}function x7(e){if("string"==typeof e){if(""===e)return e;if(I7(e).call(e).length!==e.length)return e;const t=Number(e);return Number.isNaN(t)?e:t}return e}function F7(e,t){if("object"!=typeof t||null==t||Array.isArray(t))throw new Error("cannot decode message ".concat(e.$typeName," from JSON ").concat(v6(t)));for(const i of Object.entries(t)){var n=M5(i,2);const t=n[0],r=n[1],o=P6(_8);B7(o,r),e.fields[t]=o}}function B7(e,t){switch(typeof t){case"number":e.kind={case:"numberValue",value:t};break;case"string":e.kind={case:"stringValue",value:t};break;case"boolean":e.kind={case:"boolValue",value:t};break;case"object":if(null===t)e.kind={case:"nullValue",value:m8.NULL_VALUE};else if(Array.isArray(t)){const n=P6(E8);j7(n,t),e.kind={case:"listValue",value:n}}else{const n=P6(p8);F7(n,t),e.kind={case:"structValue",value:n}}break;default:throw new Error("cannot decode message ".concat(e.$typeName," from JSON ").concat(v6(t)))}return e}function j7(e,t){if(!Array.isArray(t))throw new Error("cannot decode message ".concat(e.$typeName," from JSON ").concat(v6(t)));for(const n of t){const t=P6(_8);B7(t,n),XZ(e).push(t)}}function G7(e,t,n,i,r){let o,s=r.opid,a=r.mode,c=r.codec,d=r.hasChangeBGPAddress,l=void 0!==d&&d,u=r.ortc;t.multiIP&&t.multiIP.gateway_ip&&(o=JSON.stringify({vocs_ip:[t.multiIP.uni_lbs_ip],vos_ip:[t.multiIP.gateway_ip]}));const h="host"===t.role?"1":"audience"===t.role?"2":void 0,p={opid:s,unilbs:[{uri:22,detail:M8(M8(M8(M8(M8(M8({},n?{11:n,22:n}:{}),o?{5:o}:{}),rL("USE_NEW_TOKEN")?{12:"1"}:{}),h?{17:h}:{}),t.apRequestDetail?{33:t.apRequestDetail}:{}),t.apRTM?{26:"RTM2"}:{}),serviceIds:i}],uid:t.uid||0,signal:x8(e,t,{mode:a,codec:c,joinGatewayStartTime:Date.now(),hasChangeBGPAddress:l}),ortc:H8(u)},_=function(e,t,n){const i=G6(e);try{N7(i,t,function(e){return e?Object.assign(Object.assign({},A7),e):A7}(n))}catch(e){if((r=e)instanceof Error&&Q4($4).call($4,r.name)&&"field"in r&&"function"==typeof r.field)throw new Error("cannot decode ".concat(e.field()," from JSON: ").concat(e.message),{cause:e});throw e}var r;return i.message}(b8,p),E=d9(b8,_),m=rL("ENABLE_AP_COMPRESS")?dK(E,{raw:!0}):E;return rL("ENABLE_SDP_ENDPOINT_LOG")&&FL.debug("[sdp-endpoint] request json",p," sdpEndpointRequestJson,length is ".concat(m.length)),m}function W7(e,t,n){var i,r,o;const s=rL("ENABLE_AP_COMPRESS")?uK(n,{raw:!0}):n,a=r8(C8,new Uint8Array(s));rL("ENABLE_SDP_ENDPOINT_LOG")&&FL.debug("[sdp-endpoint] response json",function(e,t,n){return e7(G6(e,t),function(e){return e?Object.assign(Object.assign({},$8),e):$8}(n))}(C8,a)," sdpEndpointResponseJson,length is ".concat(n.byteLength));const c=(null===(i=a.attributesResponse)||void 0===i?void 0:i.preSubSsrcs.map((e=>({a:e.a,a_rtx:e.aRtx,v:e.v,v_rtx:e.vRtx}))))||[],d=null===(r=a.attributesResponse)||void 0===r?void 0:r.subscribeAudioFilterTopN,l=null===(o=a.attributesResponse)||void 0===o?void 0:o.extensions,u=a.unilbsResponse[0].detail?Number(a.unilbsResponse[0].detail[8]):void 0;return{detail:a.detail,enter_ts:Number(a.enterTs),leave_ts:Number(a.leaveTs),opid:Number(a.opid),response_body:a.unilbsResponse.map((t=>({buffer:{cert:t.cert,cid:t.cid,cname:e.cname,code:t.code,detail:t.detail||{},edges_services:t.services.map((e=>({ip:e.ip,port:e.port,fingerprint:e.fingerprint,iceUfrag:e.ice[0],icePwd:e.ice[1]}))),flag:t.flag,uid:a.uid},uri:t.uri}))),signalResponse:{attributes:{userAttributes:M8(M8({preSubSsrcs:c},"number"==typeof d?{subscribeAudioFilterTopN:d}:{}),l)},rejoin_token:a.rejoinToken,return_vosip:!1,uid:e.stringUid?e.stringUid:a.uid,intUid:a.uid,vid:u,rtpCapabilities:Y8(t.rtpCapabilities,a.addOrtc,a.delOrtc)}}}function K7(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function H7(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?K7(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):K7(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let Y7=0;function X7(e){const t=rL("TURN_DOMAINS");Y7=(Y7+1)%t.length;const n=t[Y7]||"edge.agora.io";return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(n):(FL.debug("Cannot recognized as ip address: ".concat(e,", use as host2")),e)}function J7(e){try{const t=rL("TURN_DOMAINS"),n=rL("GATEWAY_DOMAINS").concat(t).find((t=>Vi(e).call(e,t)));if(n){return e.split(".".concat(n))[0].replace(/-/g,".")}return e}catch(t){return FL.debug("serverUrlToIp error, fallback to url",e),e}}function z7(e,t){e.addresses||(e.addresses=[]);const n=function(e,t){if(rL("CONNECT_GATEWAY_WITHOUT_DOMAIN"))return e.map((e=>{let t=e.ip,n=e.port;return{address:"".concat(t,":").concat(n)}}));const n=rL("GATEWAY_DOMAINS");let i=n[1]&&Vi(t).call(t,n[1])?1:0;return e.map((e=>{let t=e.domain_prefix,r=e.port,o=e.ip;if(t)return{address:"".concat(t,".").concat(n[i++%n.length],":").concat(r)};const s=/^[\.\:\d]+$/.test(o),a=s?"".concat(o.replace(/[^\d]/g,"-"),".").concat(n[i++%n.length],":").concat(r):"".concat(o,":").concat(r);return s||FL.debug("Cannot recognized as ip address: ".concat(o,", use as host3")),{ip:o,port:r,address:a}}))}(e.addresses,t),i=Array.isArray(e.detail)&&e.detail[18];if(i&&"string"==typeof i){const e=i.split(";");for(let t=0;t<e.length;t++){var r;const i=ZS(r=e[t]).call(r);n[t]&&i&&(n[t].ip6=i)}}const o=e.detail&&e.detail.candidate;let s;if(o){const e=Hb(o.split(":"),2),t=e[0],n=e[1];t&&n&&(s={port:Number(n),ip:t,address:"".concat(t,":").concat(n)})}return{gatewayAddrs:n,apGatewayAddress:s,uid:e.uid,cid:e.cid,cert:e.cert,vid:e.detail&&e.detail[8],uni_lbs_ip:e.detail&&e.detail[1],res:e,csIp:e.detail&&e.detail[502]}}function Z7(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function q7(e){const t=e._encoderConfig;if(!t)return{};const n={resolution:t.width&&t.height?"".concat(Z7(t.width),"x").concat(Z7(t.height)):void 0,maxVideoBW:t.bitrateMax,minVideoBW:t.bitrateMin};return"number"==typeof t.frameRate?(n.maxFrameRate=t.frameRate,n.minFrameRate=t.frameRate):t.frameRate&&(n.maxFrameRate=t.frameRate.max||t.frameRate.ideal||t.frameRate.exact||t.frameRate.min,n.minFrameRate=t.frameRate.min||t.frameRate.ideal||t.frameRate.exact||t.frameRate.max),n}function Q7(e){return e>=0&&e<.17?1:e>=.17&&e<.36?2:e>=.36&&e<.59?3:e>=.59&&e<=1?4:e>1?5:0}function $7(e,t){let n,i,r;switch(t){case hK.CHOOSE_SERVER:i=4096,r="choose server";break;case hK.CLOUD_PROXY:i=1048576,r="proxy";break;case hK.CLOUD_PROXY_5:i=4194304,r="proxy5";break;case hK.CLOUD_PROXY_FALLBACK:i=4194310,r="proxy fallback";break;default:throw new hk(JN.UNEXPECTED_ERROR,"multi unlibs response transformer get unknown service id",{csIp:e.detail&&e.detail[502],retry:!1})}if(e.response_body.forEach((t=>{t.buffer&&t.buffer.flag===i&&(n={code:t.buffer.code,addresses:(t.buffer.edges_services||[]).map((e=>H7(H7({},e),{},{ticket:t.buffer.cert}))),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:H7(H7({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert,signalResponse:"signalResponse"in e?e.signalResponse:void 0})})),!n)throw new hk(JN.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(r," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return n}async function eee(e,t){return await dp.all(e.addresses.map((async e=>({address:X7(e.ip),tcpport:e.port,udpport:e.port,username:t&&rL("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():qP.username,password:t&&rL("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await uD(t.toString()):qP.password}))))}function tee(e,t){const n=t.getMediaStreamTrack(!0).getSettings(),i=t.videoHeight||n.height,r=t.videoWidth||n.width;return i&&r?Math.max(Math.min(i,r)/Math.min(Z7(e.height),Z7(e.width)),1):(FL.warning("can't get ori-track's height, default scale down 4 times for low stream"),4)}function nee(e){let t=e.candidateType,n=e.relayProtocol,i=e.type,r=e.address,o=e.port;const s={candidateType:t,relayProtocol:n,protocol:e.protocol};if("local-candidate"!==i){const e=r.split(".");e.length>=4&&(e[1]="*",e[2]="*"),s.address=e.join("."),s.port=o}return s}function iee(e){const t=e.split(":"),n=e.split(/[-.]/),i=Vi(e).call(e,"-")?"-":".";let r=e;return t.length>1?n.length>1?(n[1]="**",r=n[0]+i+"**:"+t[t.length-1]):r=t.length>2?t[0]+i+"**:"+t[t.length-1]:"**:"+t[t.length-1]:n.length>1&&(r=n[0]+i+"**"),r}function ree(e,t){return e.getTransceivers().find((e=>e.sender.track===t||e.receiver.track===t))}function oee(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:rL("SVC_MODE");if(rL("ENABLE_SVC"))return function(e){return e in xP}(e)?e:xP.L1T3}const see={[nB.VIDEO]:[{key:"abs-send-time",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"},{key:"video-orientation",extensionName:"urn:3gpp:video-orientation"},{key:"draft-holmer-rmcat-transport-wide-cc-extensions-01",extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"},{key:"playout-delay",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"},{key:"video-content-type",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type"},{key:"color-space",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/color-space"},{key:"video-timing",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing"}],[nB.AUDIO]:[{key:"ssrc-audio-level",extensionName:"urn:ietf:params:rtp-hdrext:ssrc-audio-level"},{key:"draft-holmer-rmcat-transport-wide-cc-extensions-01",extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"},{key:"abs-send-time",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"}]};function aee(e){e.send&&(lee(nB.VIDEO,e.send.videoExtensions),lee(nB.AUDIO,e.send.audioExtensions)),e.recv&&(lee(nB.VIDEO,e.recv.videoExtensions),lee(nB.AUDIO,e.recv.audioExtensions)),e.sendrecv&&(lee(nB.VIDEO,e.sendrecv.videoExtensions),lee(nB.AUDIO,e.sendrecv.audioExtensions))}function cee(e,t){e.send&&(dee(nB.VIDEO,e.send.videoExtensions,t.send.videoExtensions),dee(nB.AUDIO,e.send.audioExtensions,t.send.audioExtensions)),e.recv&&(dee(nB.VIDEO,e.recv.videoExtensions,t.recv.videoExtensions),dee(nB.AUDIO,e.recv.audioExtensions,t.recv.audioExtensions))}function dee(e,t,n){t.forEach((t=>{var i;const r=see[e].find((e=>{var n;let i=e.key;return Vi(n=t.extensionName).call(n,i)}));if(!r)return;const o=n.find((e=>{let t=e.extensionName;return Vi(t).call(t,r.key)}));o&&Vi(i=o.extensionName).call(i,"gdpr_forbidden")&&(t.extensionName=o.extensionName)}))}function lee(e,t){t.forEach((t=>{var n;const i=see[e].find((e=>{var n;let i=e.key;return Vi(n=t.extensionName).call(n,i)}));Vi(n=t.extensionName).call(n,"gdpr_forbidden")&&i&&(t.extensionName=i.extensionName)}))}function uee(e){return"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e||Vi(e).call(e,"abs-send-time")}function hee(e){return"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e||Vi(e).call(e,"draft-holmer-rmcat-transport-wide-cc-extensions-01")}function pee(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function _ee(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?pee(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):pee(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function Eee(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=arguments.length>3?arguments[3]:void 0;const r=t.filterRTX,o=t.filterVideoFec,s=t.filterAudioFec,a=t.filterAudioCodec,c=t.filterVideoCodec,d=t.unsupportedVideoUplinkCodec,l=t.unsupportedVideoDownlinkCodec,u=n.useXR;let h=[],p=[],_=[],E=[],m=!1,f=!1;if(EL(e).mediaDescriptions.forEach((e=>{i&&i!==e.attributes.direction||("video"!==e.media.mediaType||m||(p=e.attributes.payloads,E=e.attributes.extmaps,m=!0),"audio"!==e.media.mediaType||f||(h=e.attributes.payloads,_=e.attributes.extmaps,f=!0))})),!E||0===p.length)throw new Error("Cannot get video capabilities from SDP.");if(!_||0===h.length)throw new Error("Cannot get audio capabilities from SDP.");if(p.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),u&&e.rtcpFeedbacks.push({type:"rrtr"})})),h.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),u&&e.rtcpFeedbacks.push({type:"rrtr"})})),r&&(h=h.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})),p=p.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}))),o){const e=p.filter((e=>{var t;return/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")})),t=Mee(e,p).map((e=>e.payloadType)),n=[...e.map((e=>e.payloadType)),...t];p=p.filter((e=>!Vi(n).call(n,e.payloadType)))}if(s&&(h=h.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),a&&(null==a?void 0:a.length)>0&&(h=h.filter((e=>{var t;return Vi(a).call(a,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}))),c&&(null==c?void 0:c.length)>0){const e=p.filter((e=>{var t;return Vi(c).call(c,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}));p=e.concat(r?[]:Mee(e,p))}const g=rL("UNSUPPORTED_VIDEO_CODEC");if(g&&g.length>0){const e=p.filter((e=>e.rtpMap&&Vi(g).call(g,e.rtpMap.encodingName.toLowerCase()))),t=Mee(e,p),n=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!Vi(n).call(n,e.payloadType))),FL.debug("unsupportedVideoCodec: ".concat(g,", toBeRemoved: ").concat(n))}if(d&&d.length>0&&"sendonly"===i){const e=p.filter((e=>e.rtpMap&&Vi(d).call(d,e.rtpMap.encodingName.toLowerCase()))),t=Mee(e,p),n=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!Vi(n).call(n,e.payloadType))),FL.debug("unsupportedVideoUplinkCodec: ".concat(d,", toBeRemoved: ").concat(n))}if(l&&l.length>0&&"recvonly"===i){const e=p.filter((e=>e.rtpMap&&Vi(l).call(l,e.rtpMap.encodingName.toLowerCase()))),t=Mee(e,p),n=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!Vi(n).call(n,e.payloadType))),FL.debug("unsupportedVideoDownlinkCodec: ".concat(l,", toBeRemoved: ").concat(n))}return{audioCodecs:h,videoCodecs:p,audioExtensions:_,videoExtensions:E}}function mee(e){const t=EL(e);let n,i;for(const e of t.mediaDescriptions){if(!n){const t=e.attributes.iceUfrag,i=e.attributes.icePwd;if(!t||!i)throw new Error("Cannot get iceUfrag or icePwd from SDP.");n={iceUfrag:t,icePwd:i}}if(!i){const t=e.attributes.fingerprints;t.length>0&&(i={fingerprints:t})}}if(!i&&t.attributes.fingerprints.length>0&&(i={fingerprints:t.attributes.fingerprints}),!i||!n)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return{iceParameters:n,dtlsParameters:i}}function fee(e,t){const n=[],i=e.attributes.ssrcGroups.filter((e=>"FID"===e.semantic)),r=e.attributes.ssrcGroups.find((e=>"SIM"===e.semantic)),o=e.attributes.ssrcs;if(r)r.ssrcIds.forEach((e=>{var r;const o=null===(r=i.find((t=>t.ssrcIds[0]===e)))||void 0===r?void 0:r.ssrcIds[1];n.push({ssrcId:e,rtx:t?o:void 0})}));else if(i.length>0){const e=i[0].ssrcIds[0],r=i[0].ssrcIds[1];n.push({ssrcId:e,rtx:t?r:void 0})}else{if(0===o.length)throw new Error("No ssrcs found on local media description.");n.push({ssrcId:o[0].ssrcId})}return n}function gee(e,t,n){const i=e.cname;let r=[];t&&(r=Tee(t)),0===r.length&&(r=e.iceParameters.candidates.map((e=>({foundation:e.foundation,componentId:"1",transport:e.protocol,priority:e.priority.toString(),connectionAddress:e.ip,port:e.port.toString(),type:e.type,extension:{}}))),FL.debug("Using candidates from gateway."));const o={fingerprints:e.dtlsParameters.fingerprints.map((e=>({hashFunction:e.algorithm,fingerprint:e.fingerprint})))},s={iceUfrag:e.iceParameters.iceUfrag,icePwd:e.iceParameters.icePwd};let a;switch(e.dtlsParameters.role){case"server":a="passive";break;case"client":a="active";break;case"auto":a="actpass"}return{dtlsParameters:o,iceParameters:s,candidates:r,rtpCapabilities:Pee(e.rtpCapabilities),setup:a,cname:i,preSSRCs:See(n)}}function See(e){const t=[];return Array.isArray(e)&&e.length>0&&e.forEach((e=>{t.push({kind:nB.VIDEO,ssrcMsg:[{ssrcId:e.v,rtx:e.v_rtx}],mslabel:"".concat(e.v,"_").concat(e.a)},{kind:nB.AUDIO,ssrcMsg:[{ssrcId:e.a}],mslabel:"".concat(e.v,"_").concat(e.a)})})),t}function Tee(e){let t=[];return e.ip&&"number"==typeof e.port&&(t=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip,port:e.port.toString(),type:"host",extension:{}}],FL.debug("Using remote candidate from AP ".concat(iee(e.ip),":").concat(e.port)),e.ip6&&(t.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip6,port:e.port.toString(),type:"host",extension:{}}),FL.debug("Using IPV6 remote candidate from AP ".concat(iee(e.ip6),":").concat(e.port)))),t}function Ree(e,t,n){const i=[],r=[];return e.forEach((e=>{let o=e.ssrcId,s=e.rtx;const a=eP(8,"track-"),c={ssrcId:o,attributes:_ee({label:a,mslabel:n=n||eP(10,""),msid:"".concat(n," ").concat(a)},t&&{cname:t})};if(i.push(c),void 0!==s){const e={ssrcId:s,attributes:_ee({label:a,mslabel:n,msid:"".concat(n," ").concat(a)},t&&{cname:t})};i.push(e),r.push({semantic:"FID",ssrcIds:[o,s]})}})),e.length>1&&r.push({semantic:"SIM",ssrcIds:e.map((e=>e.ssrcId))}),{ssrcs:i,ssrcGroups:r}}function vee(e,t){t instanceof YU&&e.attributes.payloads.forEach((e=>{var n;const i=null===(n=e.rtpMap)||void 0===n?void 0:n.encodingName.toLowerCase();if(!i||-1===["opus","pcmu","pcma","g722"].indexOf(i))return;e.fmtp||(e.fmtp={parameters:{}}),"opus"===i&&"number"==typeof rL("OPUS_PTIME")?e.fmtp.parameters.ptime=rL("OPUS_PTIME"):e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const r=t._encoderConfig;r&&("pcmu"!==i&&"pcma"!==i&&"g722"!==i&&(r.bitrate&&!SN()&&(e.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*r.bitrate))),r.sampleRate&&(e.fmtp.parameters.maxplaybackrate="".concat(r.sampleRate),e.fmtp.parameters["sprop-maxcapturerate"]="".concat(r.sampleRate)),r.stereo&&(e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1")),t instanceof XU&&"opus"===i&&t._config.DTX&&(e.fmtp.parameters.usedtx="1"))}))}function yee(e){const t=e.attributes.unrecognized.findIndex((e=>"x-google-flag"===e.attField&&"conference"===e.attValue));-1!==t&&e.attributes.unrecognized.splice(t,1)}function bee(e,t){var n;if(e.attributes.payloads.forEach((e=>{var t;"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())&&e.fmtp&&e.fmtp.parameters&&rL("ENABLE_UP_SPS_PPS")&&(e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")})),!(t instanceof BV&&t._encoderConfig&&-1===t._hints.indexOf(jk.SCREEN_TRACK)))return;const i=t._encoderConfig;_k().supportMinBitrate&&i.bitrateMin&&e.attributes.payloads.forEach((e=>{var t,n;Vi(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(n=e.rtpMap)||void 0===n?void 0:n.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-min-bitrate"]="".concat(i.bitrateMin))})),_k().supportMinBitrate&&!Vi(n=t._hints).call(n,jk.LOW_STREAM)&&i.bitrateMax&&e.attributes.payloads.forEach((e=>{var t,n;Vi(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(n=e.rtpMap)||void 0===n?void 0:n.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-start-bitrate"]="".concat(rL("X_GOOGLE_START_BITRATE")||Math.floor(i.bitrateMax)))}))}function Cee(e){if("video"!==e.media.mediaType)return;const t=dN();if(t.name!==oN.SAFARI&&t.os!==rN.IOS)return;const n=e.attributes.extmaps.findIndex((e=>/video-orientation/g.test(e.extensionName)));-1!==n&&e.attributes.extmaps.splice(n,1)}function Iee(e,t,n){if(!t)return;let i,r;if("video"===e.media.mediaType?(i=n.videoExtensions,r=n.videoCodecs):(i=n.audioExtensions,r=n.audioCodecs),!0===t.twcc){const t=i.find((e=>hee(e.extensionName)));if(t){const n=t.extensionName;e.attributes.extmaps.find((e=>hee(e.extensionName)))||e.attributes.extmaps.push({entry:t.entry,extensionName:n});const i=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))))))}(r,e.attributes.payloads);i.forEach((e=>{e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))||e.rtcpFeedbacks.push({type:"transport-cc"})}))}}else if(!1===t.twcc){const t=e.attributes.extmaps.findIndex((e=>hee(e.extensionName)));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"transport-cc"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}if(!0===t.remb){const t=i.find((e=>uee(e.extensionName)));if(t){const n=t.extensionName;e.attributes.extmaps.find((e=>e.extensionName===n))||e.attributes.extmaps.push({entry:t.entry,extensionName:n});const i=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))))))}(r,e.attributes.payloads);i.forEach((e=>{e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))||e.rtcpFeedbacks.push({type:"goog-remb"})}))}}else if(!1===t.remb){const t=e.attributes.extmaps.findIndex((e=>uee(e.extensionName)));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"goog-remb"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}}function Aee(e,t,n){if(SN())return;if("video"!==e.media.mediaType)return;if(!(t instanceof BV))return;if("vp9"!==n&&"vp8"!==n)return;if("vp8"===n&&!rL("SIMULCAST"))return;if("vp9"===n&&rL("ENABLE_SVC"))return;if(void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;const i="vp8"===n?2:t._scalabilityMode.numSpatialLayers,r=e.attributes.ssrcs[0],o=e.attributes.ssrcGroups.find((e=>"FID"===e.semantic&&e.ssrcIds[0]===r.ssrcId)),s={semantic:"SIM",ssrcIds:[r.ssrcId]};for(let t=1;t<i;t++)e.attributes.ssrcs.push({ssrcId:r.ssrcId+t,attributes:GD(r.attributes)}),s.ssrcIds.push(r.ssrcId+t),o&&(e.attributes.ssrcs.push({ssrcId:o.ssrcIds[1]+t,attributes:GD(r.attributes)}),e.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[r.ssrcId+t,o.ssrcIds[1]+t]}));e.attributes.ssrcGroups.unshift(s)}async function wee(){try{const e=new RTCPeerConnection;e.addTransceiver("video",{direction:"sendonly",sendEncodings:[{scalabilityMode:xP.L1T3}]});const t=await e.createOffer();if(!t.sdp)return void e.close();const n=EL(t.sdp).mediaDescriptions[0];if(!n)return;const i=n.attributes.extmaps.find((e=>"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"===e.extensionName));return e.close(),i}catch(e){return}}async function Oee(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=new RTCPeerConnection;n.addTransceiver("video",{direction:"sendonly"}),n.addTransceiver("audio",{direction:"sendonly"}),n.addTransceiver("video",{direction:"recvonly"}),n.addTransceiver("audio",{direction:"recvonly"});const i=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0;const i=Eee(n,e,t,"sendonly"),r=Eee(n,e,t,"recvonly"),o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Dee(i,r,"videoExtensions",o,s,a),Dee(i,r,"videoCodecs",o,s,a),Dee(i,r,"audioExtensions",o,s,a),Dee(i,r,"audioCodecs",o,s,a),rL("RAISE_H264_BASELINE_PRIORITY")){const e=[],t=[];if(a.videoCodecs.forEach(((n,i)=>{var r;if("h264"===(null===(r=n.rtpMap)||void 0===r?void 0:r.encodingName.toLocaleLowerCase())){var o,s;const r=a.videoCodecs[i+1],c=r&&jee(n,r),d=null===(o=n.fmtp)||void 0===o?void 0:o.parameters["profile-level-id"],l=null===(s=n.fmtp)||void 0===s?void 0:s.parameters["packetization-mode"];!d||d!==rL("FIRST_H264_PROFILE_LEVEL_ID")||rL("FIRST_PACKETIZATION_MODE")&&l!==rL("FIRST_PACKETIZATION_MODE")?c?t.push([n,r]):t.push([n]):c?e.push([n,r]):e.push([n])}})),e.length>0&&t.length>0){FL.debug("raising H264 baseline profile priority"),a.videoCodecs.forEach(((n,i)=>{var r;if("h264"===(null===(r=n.rtpMap)||void 0===r?void 0:r.encodingName.toLocaleLowerCase())){const r=jee(n,a.videoCodecs[i+1]),o=e.shift()||t.shift()||[];o.length>0&&(r?a.videoCodecs.splice(i,2,...o):a.videoCodecs.splice(i,1,...o))}}));const n=s.videoCodecs.filter((e=>{var t,n;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&(null===(n=e.fmtp)||void 0===n?void 0:n.parameters["profile-level-id"])!==rL("FIRST_H264_PROFILE_LEVEL_ID")}));if(n.length>0){const e=Mee(n,s.videoCodecs).map((e=>e.payloadType)),t=[...n.map((e=>e.payloadType)),...e];s.videoCodecs=s.videoCodecs.filter((e=>!Vi(t).call(t,e.payloadType)))}rL("FILTER_SEND_H264_BASELINE")&&(o.videoCodecs=o.videoCodecs.filter((e=>{var t,n;return!("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&(null===(n=e.fmtp)||void 0===n?void 0:n.parameters["profile-level-id"])!==rL("FIRST_H264_PROFILE_LEVEL_ID"))})))}return{send:o,recv:s,sendrecv:a}}return{send:o,recv:s,sendrecv:a}}(e,t,(await n.createOffer()).sdp),r=i.send,o=i.recv,s=i.sendrecv;try{n.close()}catch(e){}return{send:r,recv:o,sendrecv:s}}function Nee(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=Eee(arguments.length>2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},"recvonly"),n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Dee(e,t,"videoExtensions",n,i,r),Dee(e,t,"videoCodecs",n,i,r),Dee(e,t,"audioExtensions",n,i,r),Dee(e,t,"audioCodecs",n,i,r),rL("RAISE_H264_BASELINE_PRIORITY")){const e=r.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"===e.fmtp.parameters["profile-level-id"]));if(-1!==e){const t=r.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()));if(t<e){FL.debug("raising H264 baseline profile priority");const n=r.videoCodecs[e];r.videoCodecs.splice(e,1),r.videoCodecs.splice(t,0,n)}-1!==t&&(i.videoCodecs=i.videoCodecs.filter((e=>!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"]))))}}return{send:n,recv:i,sendrecv:r}}function Dee(e,t,n,i,r,o){if("videoExtensions"===n||"audioExtensions"===n){const s=[];return e[n].forEach((e=>{t[n].some(((t,n)=>{if(e.entry===t.entry&&e.extensionName===t.extensionName)return s.push(n),!0}))?o[n].push(e):i[n].push(e)})),void t[n].forEach(((e,t)=>{-1===s.indexOf(t)&&r[n].push(e)}))}if("videoCodecs"===n||"audioCodecs"===n){const s=[];return e[n].forEach((e=>{t[n].some(((t,n)=>{if(e.payloadType===t.payloadType&&JSON.stringify(e)===JSON.stringify(t))return s.push(n),!0}))?o[n].push(e):i[n].push(e)})),void t[n].forEach(((e,t)=>{-1===s.indexOf(t)&&r[n].push(e)}))}}function Pee(e){const t=e.send,n=e.recv,i=e.sendrecv;if(!i){if(!t||!n)throw new Error("cannot merge rtp capabilities because one of send or recv is empty!");return{send:t,recv:n}}let r,o;return t?(r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r.audioCodecs=[...t.audioCodecs,...i.audioCodecs],r.videoCodecs=[...t.videoCodecs,...i.videoCodecs],r.audioExtensions=[...t.audioExtensions,...i.audioExtensions],r.videoExtensions=[...t.videoExtensions,...i.videoExtensions]):r=GD(i),n?(o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o.audioCodecs=[...n.audioCodecs,...i.audioCodecs],o.videoCodecs=[...n.videoCodecs,...i.videoCodecs],o.audioExtensions=[...n.audioExtensions,...i.audioExtensions],o.videoExtensions=[...n.videoExtensions,...i.videoExtensions]):o=GD(i),{send:r,recv:o}}function Lee(e){if("audio"!==e.media.mediaType)return;e.attributes.payloads.filter((e=>{var t;return"opus"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})).forEach((e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"}))}function kee(e,t,n,i){let r=[];if(e===nB.VIDEO){if(rL("H264_PROFILE_LEVEL_ID")&&"h264"===i&&(r=t.videoCodecs.filter((e=>{var t;return Vi(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,i)&&e&&e.fmtp&&e.fmtp.parameters["profile-level-id"]===rL("H264_PROFILE_LEVEL_ID")}))),!Array.isArray(r)||0===r.length){let e=[];const o=[],s=[],a=[];if(n.videoCodecs.forEach((t=>{const n=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"";Vi(n).call(n,i)?e.push(t):Vi(n).call(n,"vp9")?o.push(t):Vi(n).call(n,"vp8")?s.push(t):Vi(n).call(n,"h264")&&a.push(t)})),0===e.length){let t="";0!==o.length?(e=o,t="vp9"):0!==s.length?(e=s,t="vp8"):0!==a.length&&(e=a,t="h264"),FL.warning("codec ".concat(i," not included in rtpCapabilities, fallback to default payloads: ").concat(t))}0!==e.length&&(r=t.videoCodecs.filter((t=>e.some((e=>e.payloadType===t.payloadType)))))}if(0===r.length&&(FL.warning("codec ".concat(i," not included in rtpCapabilities, fallback to default payloads: ").concat(t.videoCodecs[0].rtpMap&&t.videoCodecs[0].rtpMap.encodingName)),r=t.videoCodecs),rL("USE_PUB_RTX")||rL("USE_SUB_RTX")){const e=Mee(r,t.videoCodecs);r=[...r,...e]}}else{r=t.audioCodecs.filter((e=>{var t;return Vi(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,i)}));const e=t.audioCodecs.filter((e=>{var t;return Vi(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,"red")}));0===r.length&&(FL.warning("codec ".concat(i," not included in rtpCapabilities, fallback to opus")),r=t.audioCodecs.filter((e=>{var t;return Vi(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,"opus")}))),rL("ENABLE_AUDIO_RED")&&0!==e.length&&(r=[...e,...r])}return r}function Mee(e,t){const n=e.map((e=>e.payloadType.toString()));return t.filter((e=>e.rtpMap&&"rtx"===e.rtpMap.encodingName&&e.fmtp&&e.fmtp.parameters.apt&&Vi(n).call(n,e.fmtp&&e.fmtp.parameters.apt)))}async function Uee(e,t,n){const i=t.toString(),r=xee(i,"offer","remote","exchangeSDP");await e.setRemoteDescription({type:"offer",sdp:i});const o=await e.createAnswer();if(!o.sdp)throw new Error("cannot get answer sdp");let s=o.sdp;s=Vee(s,n||{}),null==r||r(s||""),await e.setLocalDescription({type:"answer",sdp:s})}function Vee(e,t,n){if(rL("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const i=EL(e),r=t.useXR;return i.mediaDescriptions.forEach((e=>{var t;e.attributes.mid&&(Array.isArray(n)&&!Vi(n).call(n,e.attributes.mid)||("audio"===e.media.mediaType&&Lee(e),"video"===e.media.mediaType&&function(e){if("video"!==e.media.mediaType)return;if(!rL("ENABLE_DOWN_SPS_PPS"))return;e.attributes.payloads.filter((e=>{var t;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})).forEach((e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1"}))}(e),r&&Vi(t=["audio","video"]).call(t,e.media.mediaType)&&e.attributes.payloads.forEach((e=>{-1===e.rtcpFeedbacks.findIndex((e=>"rrtr"===e.type))&&e.rtcpFeedbacks.push({type:"rrtr"})}))))})),mL(i)}function xee(e,t,n,i){if(rL("SDP_LOGGING"))return FL.upload("exchanging ".concat(n," ").concat(t," SDP during P2PConnection.").concat(i,"\n"),e),"offer"===t?e=>{xee(e,"answer","local"===n?"remote":"local",i)}:void 0}async function Fee(e,t,n){try{var i;if(!_k().supportSetRtpSenderParameters)return;if(!function(e){return"vp9"===e||"av1"===e}(e)||!rL("ENABLE_SVC"))return;const r={},o={},s=t.getParameters(),a=null===(i=s.encodings)||void 0===i?void 0:i[0];o.scalabilityMode=oee(n),a&&Object.assign(a,o),Object.assign(s,r),await t.setParameters(s),FL.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode success: ".concat(JSON.stringify(s.encodings)))}catch(e){FL.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode failed",e)}}function Bee(e){const t=rL("COMPATIBLE_SDP_EXTENSION");return!!(Array.isArray(t)&&t.length>0)&&t.some((t=>Vi(e).call(e,t)))}function jee(e,t){try{var n;return(null===(n=e.fmtp)||void 0===n?void 0:n.parameters.apt)===t.payloadType.toString()}catch(e){return!1}}const Gee={};function Wee(e){(!(arguments.length>1&&void 0!==arguments[1])||arguments[1])&&FL.debug("install service ".concat(e.name)),Gee[e.name]=e}function Kee(e){const t=Gee[e];if(!t)throw new zN(JN.INVALID_OPERATION,"".concat(e," not found, please use AgoraRTC.use(").concat(e,"Service) to load it first"));return t}function Hee(e,t){return Kee("DataStream").create(e,t)}function Yee(){return Kee("InterceptFrame").create()}function Xee(e,t){return!(e.length<4||e.length>256)&&!(t.length<22||t.length>256)}function Jee(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function zee(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Jee(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Jee(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const Zee=new Map;class qee extends hD{get state(){return this._state}set state(e){if(e===this._state)return;const t=this._state;this._state=e,"DISCONNECTED"===e&&this._disconnectedReason?this.emit(HF.CONNECTION_STATE_CHANGE,e,t,this._disconnectedReason):this.emit(HF.CONNECTION_STATE_CHANGE,e,t)}get joinGatewayStartTime(){return this._joinGatewayStartTime}set joinGatewayStartTime(e){FL.debug("[".concat(this.store.clientId,"] set joinGatewayStartTime at ").concat(e)),this._joinGatewayStartTime=e}constructor(e,t){var n,i,r;super(),GA(this,"store",void 0),GA(this,"joinInfo",void 0),GA(this,"key",void 0),GA(this,"ntpOffset",0),GA(this,"usingProxy",!1),GA(this,"signal",void 0),GA(this,"role",void 0),GA(this,"isPreallocation",void 0),GA(this,"isPreSub",void 0),GA(this,"inChannelInfo",{joinAt:null,duration:0}),GA(this,"spec",void 0),GA(this,"_state","DISCONNECTED"),GA(this,"_statsCollector",void 0),GA(this,"_disconnectedReason",void 0),GA(this,"isSignalRecover",!1),GA(this,"hasChangeBGPAddress",!1),GA(this,"trafficStatsInterval",void 0),GA(this,"networkQualityInterval",void 0),GA(this,"_joinGatewayStartTime",0),GA(this,"_signalTimeout",!1),GA(this,"_clientRoleOptions",void 0),GA(this,"_isProactiveJoin",!1),this.store=e,this.spec=t,this.signal=this.store.useP2P?(n={spec:zee(zee({},t),{},{retryConfig:t.websocketRetryConfig}),store:e},null===(i=(r=Kee("P2PChannel")).createSubmodule)||void 0===i?void 0:i.call(r,n)):this.store.useDcSignal?function(e){return Kee("DataChannelSignal").create(e)}({spec:zee(zee({},t),{},{retryConfig:t.websocketRetryConfig}),store:e}):new FB(zee(zee({},t),{},{retryConfig:t.websocketRetryConfig}),e),this._statsCollector=t.statsCollector,this.role=t.role||"audience",this._clientRoleOptions=t.clientRoleOptions,this.handleSignalEvents()}setUsingProxy(e){this.usingProxy=e}async join(e,t,n){if(this.store.useDcSignal){let t=!1;const n=e.apResponse.addresses[0],i=n.iceUfrag||"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert),r=n.icePwd||"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert);"disabled"!==e.cloudProxyServer?(FL.debug("[".concat(this.store.clientId,"] Dc is not supported, because cloudProxyServer are not supported (").concat(e.cloudProxyServer,")")),t=!0):Xee(i,r)?e.apResponse.addresses.some((e=>e.fingerprint))||rL("FINGERPRINT")||(FL.debug("[".concat(this.store.clientId,"] Dc is not supported, because fingerprint does not exist")),t=!0):(FL.debug("[".concat(this.store.clientId,"] Dc is not supported, because ticket length is incorrect, it has to be between 22 and 255")),t=!0),t&&this.resetSignal()}this.store.joinGatewayStart(),"disabled"!==e.cloudProxyServer&&(this.hasChangeBGPAddress=!0);const i=Date.now();let r=Zee.get(e.cname);if(r||(r=new Map,Zee.set(e.cname,r)),this._isProactiveJoin=!0,r.has(e.uid)){const t=new hk(JN.UID_CONFLICT);throw uk.joinGateway(e.sid,{lts:i,succ:!1,ec:t.code,addr:null,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,isProxy:!!e.proxyServer||this.usingProxy,signalChannel:this.store.useDcSignal?"1":"0",preload:e.preload}),t}r.set(e.uid,!0),this.joinInfo=e,this.key=t;let o=0;this.joinGatewayStartTime=i;const s=e.proxyServer,a=this.store.useDcSignal?"datachannel":"websocket";try{FL.debug("[".concat(this.store.clientId,"] use ").concat(a," join uid ").concat(o));const t=e.gatewayAddrs.map((t=>{const n=Hb(t.address.split(":"),2),i={host:n[0],port:n[1]};return e.proxyServer&&(i.proxy=e.proxyServer),i}));let n;n=this.store.useDcSignal?await this.signal.init(e.apResponse.addresses):await this.signal.init(t),o=n.uid,FL.debug("[".concat(this.store.clientId,"] ").concat(a," join uid ").concat(o," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(t){var c;if(t.code===JN.INIT_DATACHANNEL_TIMEOUT&&"AgoraRTCSignal"===this.signal.__name__);else uk.joinGateway(e.sid,{lts:i,succ:!1,ec:(null===(c=t.data)||void 0===c?void 0:c.desc)||t.code,errorMsg:t.message,addr:this.signal.url,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,isProxy:!!s||this.usingProxy,signalChannel:"DataChannelSignal"===this.signal.__name__?"1":"0",preload:e.preload});if(t&&t.code===JN.INIT_DATACHANNEL_TIMEOUT)throw FL.warning("[".concat(this.store.clientId,"] User join datachannel failed"),t.toString()),this.resetSignal(),t;throw FL.error("[".concat(this.store.clientId,"] User join failed"),t.toString()),r.delete(e.uid),this.signal.close(),t}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),FL.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval((()=>{this.updateTrafficStats().catch((e=>{FL.warning("[".concat(this.store.clientId,"] get traffic stats error"),e.toString())}))}),3e3),this.networkQualityInterval=window.setInterval((()=>{navigator&&void 0!==navigator.onLine&&!navigator.onLine?this.emit(HF.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(HF.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(HF.NETWORK_QUALITY,{uplinkNetworkQuality:Q7(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:Q7(this._statsCollector.trafficStats.B_dnq)}):this.emit(HF.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})}),2e3),this.store.joinGatewayEnd(),o}async leave(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;if("DISCONNECTED"!==this.state){t!==SD.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==vF.CONNECTED||await function(e,t){return t===1/0?e:dp.race([e,QD(t)])}(this.signal.request(bF.LEAVE,void 0,!0),3e3)}catch(e){FL.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e)}this.signal.close(t),t!==SD.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(e,t,n){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new hk(JN.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const i={state:"offer",p2p_id:this.store.p2pId,ortc:t,mode:this.spec.mode,extend:rL("PUB_EXTEND"),twcc:!!rL("PUBLISH_TWCC"),rtx:!!rL("USE_PUB_RTX")};try{return(await this.signal.request(bF.PUBLISH,i,!0))._message}catch(i){if(n&&i.data&&i.data.code===RF.ERR_PUBLISH_REQUEST_INVALID)return FL.warning("[".concat(this.store.clientId,"] receive publish error code, retry"),i.toString()),await this.tryUnpubBeforeRepub(e,t),this.publish(e,t,!1);throw i}}async publishDataChannel(e,t,n){var i;if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new hk(JN.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const r={stream_id:t.streamId,ordered:t.ordered?1:0,max_retrans_times:null!==(i=t.maxRetransmits)&&void 0!==i?i:10,channel_id:t.channelId,metadata:t.metadata};try{await this.signal.request(bF.PUBLISH_DATASTREAM,r,!0)}catch(i){if(n&&i.data&&i.data.code===RF.ERR_PUBLISH_REQUEST_INVALID)return FL.warning("[".concat(this.store.clientId,"] receive publish datachannels error code, retry"),i.toString()),await this.tryUnpubDataChannelBeforeRepub(e,t),this.publishDataChannel(e,t,!1);throw i}}async unpublish(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new hk(JN.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(bF.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){FL.warning("[".concat(this.store.clientId,"] unpublish warning: "),e)}}async unpublishDataChannel(e){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new hk(JN.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await dp.all(e.map((e=>this.signal.request(bF.UNPUBLISH_DATASTREAM,{channel_id:e},!0))))}catch(e){FL.warning("unpublish datachannels warning: ",e)}}async presubscribe(e,t,n){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new hk(JN.INVALID_OPERATION,"can not presubscribe when connection state is ".concat(this.state));const i={stream_id:e,stream_type:t,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!rL("SUBSCRIBE_TWCC"),rtx:!!rL("USE_SUB_RTX")||void 0,extend:rL("SUB_EXTEND"),svc:Array.isArray(rL("SVC"))&&0!==rL("SVC").length?rL("SVC"):void 0};try{return await this.signal.request(bF.PRE_SUBSCRIBE,i,!0)}catch(i){if(n&&i.data&&i.data.code===RF.ERR_SUBSCRIBE_REQUEST_INVALID)return FL.warning("[".concat(this.store.clientId,"] pre-subscribe error, retry"),i.toString()),this.presubscribe(e,t,!1);throw i}}async subscribe(e,t,n){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new hk(JN.INVALID_OPERATION,"can not subscribe when connection state is ".concat(this.state));const i={stream_id:e,stream_type:t.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!rL("SUBSCRIBE_TWCC"),rtx:!!rL("USE_SUB_RTX"),extend:rL("SUB_EXTEND"),ssrcId:t.ssrcId,svc:Array.isArray(rL("SVC"))&&0!==rL("SVC").length?rL("SVC"):void 0};try{return(await this.signal.request(bF.SUBSCRIBE,i,!0))._message}catch(i){if(n&&i.data&&i.data.code===RF.ERR_SUBSCRIBE_REQUEST_INVALID)return FL.warning("[".concat(this.store.clientId,"] receiver subscribe error code, retry"),i.toString()),await this.tryUnsubBeforeResub(e,t),await this.subscribe(e,t,!1);throw i}}async subscribeDataChannel(e,t,n){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new hk(JN.INVALID_OPERATION,"can not subscribe datachannel when connection state is ".concat(this.state));const i={uid:e,stream_id:t.id,channel_id:t.datachannelId};try{return void await this.signal.request(bF.SUBSCRIBE_DATASTREAM,i,!0)}catch(i){if(n&&i.data&&i.data.code===RF.ERR_SUBSCRIBE_REQUEST_INVALID)return FL.warning("[".concat(this.store.clientId,"] receiver subscribe datachannel error code, retry"),i.toString()),await this.tryUnsubDataChannelBeforeResub(e,t),await this.subscribeDataChannel(e,t,!1);throw i}}async subscribeAll(e,t){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new hk(JN.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const n={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!rL("USE_SUB_RTX"),twcc:!!rL("SUBSCRIBE_TWCC"),svc:Array.isArray(rL("SVC"))&&0!==rL("SVC").length?rL("SVC"):void 0};try{return await this.signal.request(bF.SUBSCRIBE_STREAMS,n,!0)}catch(n){if(t&&n.data&&n.data.code===RF.ERR_SUBSCRIBE_REQUEST_INVALID)return FL.warning("[".concat(this.store.clientId,"] receiver massSubscribe error code, retry"),n.toString()),await this.tryMassUnsubBeforeResub(e),await this.subscribeAll(e,!1);throw n}}async setVideoProfile(e){const t=function(e){if(!(e.bitrateMax&&e.bitrateMin&&e.frameRate&&e.height&&e.width))return;let t=e.frameRate,n=e.width,i=e.height,r=!0;return"number"!=typeof t&&(t=t.exact||t.ideal||t.max||t.min||0,t||(r=!1)),"number"!=typeof n&&(n=n.exact||n.ideal||n.max||n.min||0,n||(r=!1)),"number"!=typeof i&&(i=i.exact||i.ideal||i.max||i.min||0,t||(r=!1)),r?{stream_type:0,width:n,height:i,fps:t,start_bps:1e3*e.bitrateMax,min_bps:1e3*e.bitrateMin,target_bps:1e3*e.bitrateMax}:void 0}(e);if(t)return this.signal.request(bF.SET_VIDEO_PROFILE,t);FL.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(e,t){try{await this.signal.request(bF.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){FL.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),e)}}async unsubscribeDataChannel(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new hk(JN.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await dp.all(e.map((e=>this.signal.request(bF.UNSUBSCRIBE_DATASTREAM,{stream_id:e,uid:t},!0))))}catch(e){FL.warning("unsubscribeDataChannel warning: ",e)}}async massUnsubscribe(e){try{await this.signal.request(bF.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){FL.warning("[".concat(this.store.clientId,"] massUnsubscribeAll warning: "),e)}}async reconnectPC(e){const t=e.iceParameters,n=e.dtlsParameters,i=e.rtpCapabilities;return{gatewayEstablishParams:await this.signal.request(bF.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:t,dtlsParameters:n,rtpCapabilities:i}},!0),gatewayAddress:this.getCurrentGatewayAddress()}}getGatewayInfo(){return this.signal.request(bF.GATEWAY_INFO)}async renewToken(e){await this.signal.request(bF.RENEW_TOKEN,e),this.key=e.token}updateClientRole(e,t){t&&(this._clientRoleOptions=Object.assign({},t)),rL("CLIENT_ROLE_OPTIONS")&&(FL.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(rL("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," ")),this._clientRoleOptions=Object.assign({},rL("CLIENT_ROLE_OPTIONS"))),this.role=e}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),rL("CLIENT_ROLE_OPTIONS")&&(this._clientRoleOptions=Object.assign({},rL("CLIENT_ROLE_OPTIONS")),FL.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(rL("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," "))),"CONNECTED"!==this.state)return void(this.role=e);let n,i=0;"audience"===e?this._clientRoleOptions&&this._clientRoleOptions.delay?(n=this._clientRoleOptions.delay,i=1):i=this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:i=0;const r=Object.assign({},t);delete r.delay,delete r.level,await this.signal.request(bF.SET_CLIENT_ROLE,zee(zee({role:e,level:i,delay:n},r),{},{client_ts:Date.now()})),this.role=e}async setDualStreamMode(e,t,n){await this.signal.request(bF.SET_DUAL_STREAM_MODE,{mode:e},n,t)}async setRemoteVideoStreamType(e,t){await this.signal.request(bF.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(bF.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(bF.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(bF.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialLayer,temporal_layer:t.temporalLayer})}async setRTM2Flag(e){await this.signal.request(bF.SET_RTM2_FLAG,{rtm2_flag:e})}async sendExtensionMessage(e,t,n){if(this.store.useP2P)return this.signal.sendExtensionMessage(e,t,n)}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),zee({},this.inChannelInfo)}async setConfigure(e){if(e&&Array.isArray(e)&&0!==e.length)return this.signal.request(bF.CONFIGURE,e)}async getGatewayVersion(){return(await this.signal.request(bF.GATEWAY_INFO)).version}reset(){if(this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt,this.inChannelInfo.joinAt=null),this.trafficStatsInterval&&(window.clearInterval(this.trafficStatsInterval),this.trafficStatsInterval=void 0),this.joinInfo){const e=Zee.get(this.joinInfo.cname);e&&e.delete(this.joinInfo.uid)}this.joinInfo=void 0,this.key=void 0,this.networkQualityInterval&&(window.clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0),this.usingProxy=!1}updateTurnConfigFromSignal(){if(!this.joinInfo)return;const e=function(e){let t;return t=e.startsWith("dc")?e.match(/(dc\:\/\/)?([^:]+):(\d+)/):e.match(/(wss\:\/\/)?([^:]+):(\d+)/),t?{username:qP.username,password:qP.password,turnServerURL:t[2],tcpport:parseInt(t[3])+30,udpport:parseInt(t[3])+30,forceturn:!1}:null}(("disabled"===this.joinInfo.cloudProxyServer?this.signal.url:this.joinInfo.gatewayAddrs[this.signal.currentURLIndex].address)||"");this.joinInfo.turnServer.serversFromGateway=[],e&&"off"!==this.joinInfo.turnServer.mode&&"disabled"===this.joinInfo.cloudProxyServer&&this.joinInfo.turnServer.serversFromGateway.push(zee(zee({},qP),{},{turnServerURL:e.turnServerURL,tcpport:e.tcpport,udpport:e.udpport,username:this.joinInfo.uid.toString(),password:this.joinInfo.token}))}async updateTrafficStats(){if("CONNECTED"!==this.state)return;const e=await this.signal.request(bF.TRAFFIC_STATS,void 0,!0);e.timestamp=Date.now(),null!=e.ntp_offset&&(this.ntpOffset=e.ntp_offset),e.peer_delay.forEach((e=>{const t=this._statsCollector.trafficStats&&this._statsCollector.trafficStats.peer_delay.find((t=>t.peer_uid===e.peer_uid));t&&t.B_st!==e.B_st&&jD((()=>{this.emit(HF.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)}))})),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){var t,n;if(!this.joinInfo||!this.key)throw new hk(JN.UNEXPECTED_ERROR,"can not generate join message, no join info");this.store.hasStartJoinChannel=!0,this.store.isABTestSuccess||this.emit(HF.UPDATE_GATEWAY_CONFIG),n=this.store.clientId,Vi(qx).call(qx,n)||qx.push(n);const i=function(e,t,n,i){var r,o,s,a,c;let d=i.key,l=i.role,u=i.joinGatewayStartTime,h=i.hasChangeBGPAddress,p=i.isPreallocation,_=i.ortc,E=i.currentURLIndex;const m=Object.assign({},t.apResponse);let f=!1;"signalResponse"in m&&m.signalResponse&&(1===e.p2pId&&(f=!0),p=!1,delete m.signalResponse);let g=rL("REPORT_APP_SCENARIO");if("string"!=typeof g)try{g=JSON.stringify(g)}catch(e){g=void 0}g&&g.length>128&&(g=void 0);const S=gk(e),T=Sk(e),R=(null===(r=e.preSubOptions)||void 0===r?void 0:r.length)||0,v=R>0?null===(o=e.preSubOptions)||void 0===o?void 0:o.map((e=>e.uid)):void 0,y=U8("PRE_SUB_NUM","number")||1,b=R>y?R:y,C=V8(),I=RN(87)||mN()||CN(117),A=(fN()||AN(18,4,!1))&&ON(18,6,!0)&&"h264"===n.codec&&rL("ENABLE_ABSSENDTIME_AS_SENTTS"),w=!("CN"!==(null===(s=m.detail)||void 0===s?void 0:s[3])||!rL("ENABLE_QUALITY_FALLBACK"))&&rL("ENABLE_QUALITY_FALLBACK"),O=!!rL("ENABLE_AP_MULTI_IP")&&"multi-ip"===(null===(a=m.detail)||void 0===a?void 0:a[5]),N={license:t.license,p2p_id:e.p2pId,session_id:t.sid,app_id:t.appId,channel_key:d,channel_name:t.cname,sdk_version:JP,browser:navigator.userAgent,process_id:rL("PROCESS_ID"),mode:e.useP2P?"p2p":n.mode,codec:n.codec,role:l,has_changed_gateway:O||h,ap_response:m,extend:rL("JOIN_EXTEND"),details:{6:t.stringUid,cservice_map:"proxy3"===t.cloudProxyServer?"1":"proxy5"===t.cloudProxyServer?"2":void 0},features:M8({rejoin:!0},f?{multi_signaling:f}:{}),optionalInfo:t.optionalInfo,appScenario:g,attributes:{userAttributes:M8(M8({enableEncodedTransform:(!!rL("ENABLE_AUDIO_METADATA")||!!rL("ENABLE_AUDIO_PTS"))&&I||!!rL("ENABLE_AUDIO_TOPN")&&yN(oN.CHROME,87,116)||void 0,enableAudioMetadata:!!rL("ENABLE_AUDIO_METADATA")&&I,enableAudioPts:!!rL("ENABLE_AUDIO_PTS")&&I,topnSmoothLevel:rL("TOPN_SMOOTH_LEVEL"),topnNewSpeakerDelay:rL("TOPN_NEW_SPEAKER_DELAY"),topnSwitchHoldMs:rL("TOPN_SWITCH_HOLD_MS"),topnAudioGain:rL("TOPN_AUDIO_GAIN"),enableNetworkQualityProbe:e.networkQualityProbe,enablePublishedUserList:rL("ENABLE_PUBLISHED_USER_LIST"),enableUserList:rL("ENABLE_USER_LIST"),maxSubscription:rL("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:U8("SUBSCRIBE_AUDIO_FILTER_TOPN","number"),enablePublishAudioFilter:U8("ENABLE_PUBLISH_AUDIO_FILTER","boolean"),enableUserLicenseCheck:U8("ENABLE_USER_LICENSE_CHECK","boolean"),enableRTX:!0===rL("USE_PUB_RTX")||!0===rL("USE_SUB_RTX")||void 0,disableFEC:rL("DISABLE_FEC"),enableNTPReport:!!rL("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:T,enableFulllinkAvSync:!!rL("ENABLE_FULL_LINK_AV_SYNC")||void 0,enableDataStream2:U8("ENABLE_DATASTREAM_2","boolean"),enableAutFeedback:Rk(),rtm2Flag:"number"==typeof t.rtmFlag?t.rtmFlag:void 0,enableUserAutoRebalanceCheck:!!rL("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:U8("USE_XR","boolean"),enableLossbasedBwe:U8("ENABLE_LOSSBASED_BWE","boolean"),enableAutCC:Tk(),enableCCFallback:U8("ENABLE_CC_FALLBACK","boolean"),enablePreallocPC:p,preSubUid:S?v:void 0,preSubNum:S?b:void 0,enablePubTWCC:U8("PUBLISH_TWCC","boolean"),enableSubTWCC:U8("SUBSCRIBE_TWCC","boolean"),enablePubRTX:U8("USE_PUB_RTX","boolean"),enableSubRTX:U8("USE_SUB_RTX","boolean"),enableSubSVC:rL("ENABLE_SVC")?rL("ENABLE_SVC_DEFAULT_CODECS"):Array.isArray(rL("SVC"))&&0!==rL("SVC").length?rL("SVC"):void 0,enableSvcExtended:rL("ENABLE_SVC")&&Array.isArray(rL("SVC_EXTENDED"))&&0!==rL("SVC_EXTENDED").length?rL("SVC_EXTENDED"):void 0,enableVosFallback:rL("ENABLE_VOS_FALLBACK"),enableQualityFallback:w},C),{},{audioDuplicate:U8("ENABLE_AUDIO_RED","boolean")?null!==(c=U8("AUDIO_DUPLICATE_NUM","number"))&&void 0!==c?c:2:void 0,senttsUsesAbsSendTime:!!A||void 0,enableDualStreamFlag:U8("ENABLE_DUAL_STREAM_FLAG","boolean")})},join_ts:u,ortc:_||{}};return t.stringUid&&(N.string_uid=t.stringUid),t.aesmode&&t.aespassword&&(N.aes_mode=t.aesmode,rL("ENCRYPT_AES")?(N.aes_secret=t.aespassword,N.aes_encrypt=!0):N.aes_secret=t.aespassword,t.aessalt&&(N.aes_salt=t.aessalt)),m.addresses[E]&&(N.ap_response.ticket=m.addresses[E].ticket,delete m.addresses),void 0!==t.defaultVideoStream&&(N.default_video_stream=t.defaultVideoStream),N}(this.store,this.joinInfo,this.spec,{key:this.key,role:this.role,joinGatewayStartTime:this.joinGatewayStartTime,hasChangeBGPAddress:this.hasChangeBGPAddress,isPreallocation:!(null===(t=this.isPreallocation)||void 0===t||!t.call(this)),ortc:e,currentURLIndex:this.signal.currentURLIndex});return i}getRejoinMessage(){if(!this.joinInfo)throw new hk(JN.UNEXPECTED_ERROR,"can not generate rejoin message, no join info");return{session_id:this.joinInfo.sid,channel_name:this.joinInfo.cname,cid:this.joinInfo.cid,uid:this.joinInfo.uid,vid:Number(this.joinInfo.vid)}}handleSignalEvents(){this.signal.on(yF.WS_RECONNECT_CREATE_CONNECTION,(e=>{this.joinGatewayStartTime=Date.now()})),this.signal.on(yF.WS_RECONNECTING,(e=>{this.joinInfo&&uk.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||ID.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",uk.sessionInit(this.joinInfo.sid,{lts:(new Date).getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0},cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode,stringUid:this.joinInfo.stringUid,channelProfile:"live"===this.spec.mode?1:0,channelMode:0,lsid:this.joinInfo.sid,clientRole:"audience"===this.role?2:1,buildFormat:2}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now())})),this.signal.on(yF.WS_CLOSED,(e=>{let t;switch(e){case SD.LEAVE:t=ID.LEAVE;break;case SD.UID_BANNED:case SD.IP_BANNED:case SD.CHANNEL_BANNED:case SD.SERVER_ERROR:t=ID.SERVER_ERROR;break;case SD.FALLBACK:t=ID.FALLBACK;break;case SD.LICENSE_MISSING:case SD.LICENSE_EXPIRED:case SD.LICENSE_MINUTES_EXCEEDED:case SD.LICENSE_PERIOD_INVALID:case SD.LICENSE_MULTIPLE_SDK_SERVICE:case SD.LICENSE_ILLEGAL:case SD.TOKEN_EXPIRE:t=e;break;default:t=ID.NETWORK_ERROR}FL.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(t||"undefined -> "+ID.NETWORK_ERROR)),this.joinInfo&&uk.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===SD.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==SD.FALLBACK&&(this.state="DISCONNECTED"),this.reset()})),this.signal.on(yF.WS_CONNECTED,(()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo){if("audience"===this.role){const e=rL("CLIENT_ROLE_OPTIONS")||this._clientRoleOptions;e&&(e.level||e.delay)&&(FL.debug("[".concat(this.store.clientId,"] patch to send set client role, role: ").concat(this.role,", mode: ").concat(this.spec.mode,", level: ").concat(e.level,", delay: ").concat(e.delay)),this.setClientRole(this.role,e))}if(uk.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!0,ec:null,vid:this.joinInfo.vid,addr:this.signal.url,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,isProxy:!!this.joinInfo.proxyServer||this.usingProxy,signalChannel:"DataChannelSignal"===this.signal.__name__?"1":"0",preload:this.joinInfo.preload,isABTestSuccess:this.store.isABTestSuccess}),this._isProactiveJoin=!1,this.joinInfo.useLocalAccessPoint&&1===this.joinInfo.setLocalAPVersion){const e=this.signal.url&&this.signal.url.match(/wss\:\/\/([^:]+):(\d+)/);if(!e)return void FL.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));iL("EVENT_REPORT_DOMAIN",e[1]),iL("EVENT_REPORT_BACKUP_DOMAIN",e[1]),iL("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}}})),this.signal.on(IF.ON_UPLINK_STATS,(e=>{this._statsCollector.updateUplinkStats(e)})),this.signal.on(yF.REQUEST_RECOVER,((e,t,n)=>{if(!this.joinInfo)return n(new hk(JN.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,OD(this,HF.REQUEST_NEW_GATEWAY_LIST).then(t).catch(n)})),this.signal.on(yF.REQUEST_JOIN_INFO,(async(e,t,n)=>{var i,r,o;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage());const s=GD(null===(i=this.joinInfo)||void 0===i?void 0:i.turnServer);if(rL("NEW_TURN_MODE")&&s&&"disabled"===(null===(r=this.joinInfo)||void 0===r?void 0:r.cloudProxyServer)){var a;let e=s.servers.map((e=>"turnServerURL"in e&&rL("USE_TURN_IP")?zee(zee({},e),{},{turnServerURL:J7(e.turnServerURL)}):e)),t=null===(a=s.serversFromGateway)||void 0===a?void 0:a.map((e=>rL("USE_TURN_IP")?zee(zee({},e),{},{turnServerURL:J7(e.turnServerURL)}):e));const n=this.signal.currentURLIndex;if(e.length>0){e=[e[n%e.length]],s.servers=e}Array.isArray(t)&&t.length>0&&(t=[t[0]],s.serversFromGateway=t),FL.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(n))}const c=await OD(this,HF.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:s,cloudProxyServer:null===(o=this.joinInfo)||void 0===o?void 0:o.cloudProxyServer}),d=c.iceParameters,l=c.dtlsParameters,u=c.rtpCapabilities;try{e(this.getJoinMessage({iceParameters:d,dtlsParameters:l,rtpCapabilities:u,version:"2"}))}catch(e){t(e)}})),this.signal.on(yF.REQUEST_JOIN_INFO_WITH_PRE_JOIN_RESPONSE,((e,t)=>{if(this.joinInfo&&this.joinInfo.signalResponse){const t=this.joinInfo.apResponse.addresses[this.signal.currentURLIndex],n=this.joinInfo.signalResponse,i=rL("FINGERPRINT")||t.fingerprint;if(!t.iceUfrag||!t.icePwd||!i)return FL.debug("cannot get iceUfrag or icePwd or fingerprint from serverAddress"),void e(void 0);const r=zee(zee({},n),{},{ortc:{dtlsParameters:{role:"client",fingerprints:[{algorithm:"sha-256",fingerprint:rL("FINGERPRINT")||t.fingerprint}]},iceParameters:{candidates:[],iceUfrag:t.iceUfrag,icePwd:t.icePwd},rtpCapabilities:n.rtpCapabilities,cname:"o/i14u9pJrxRKAsu"}});this.joinInfo&&delete this.joinInfo.signalResponse,e(r)}else e(void 0)})),this.signal.on(yF.REQUEST_REJOIN_INFO,(e=>{e(this.getRejoinMessage())})),this.signal.on(yF.REPORT_JOIN_GATEWAY,((e,t)=>{if(!this.joinInfo)return;let n,i="";var r;e instanceof hk?(n=(null===(r=e.data)||void 0===r?void 0:r.desc)||e.code,i=e.message):n=e;uk.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:n,errorMsg:i,addr:t,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,isProxy:!!this.joinInfo.proxyServer||this.usingProxy,signalChannel:"DataChannelSignal"===this.signal.__name__?"1":"0",preload:this.joinInfo.preload})})),this.signal.on(yF.IS_P2P_DISCONNECTED,(e=>{e(PD(this,HF.IS_P2P_DISCONNECTED))})),this.signal.on(yF.DISCONNECT_P2P,(()=>{this.emit(HF.DISCONNECT_P2P)})),this.signal.on(yF.REQUEST_SUCCESS,(()=>{this._signalTimeout=!1})),this.signal.on(yF.REQUEST_TIMEOUT,(()=>{this._signalTimeout=!0})),this.signal.on(yF.JOIN_RESPONSE,(e=>{const t=this.getCurrentGatewayAddress();this.emit(HF.JOIN_RESPONSE,e,t)})),this.signal.on(yF.PRE_CONNECT_PC,(async(e,t)=>{if(this.joinInfo){var n,i;this.updateTurnConfigFromSignal();const o=this.getCurrentGatewayAddress(),s=GD(null===(n=this.joinInfo)||void 0===n?void 0:n.turnServer);if(rL("NEW_TURN_MODE")&&s&&"disabled"===(null===(i=this.joinInfo)||void 0===i?void 0:i.cloudProxyServer)){var r;let e=s.servers.map((e=>"turnServerURL"in e&&rL("USE_TURN_IP")?zee(zee({},e),{},{turnServerURL:J7(e.turnServerURL)}):e)),t=null===(r=s.serversFromGateway)||void 0===r?void 0:r.map((e=>rL("USE_TURN_IP")?zee(zee({},e),{},{turnServerURL:J7(e.turnServerURL)}):e));const n=this.signal.currentURLIndex;if(e.length>0){e=[e[n%e.length]],s.servers=e}Array.isArray(t)&&t.length>0&&(t=[t[0]],s.serversFromGateway=t),FL.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(n,",in pre pc"))}const a=this.joinInfo.apResponse.addresses[this.signal.currentURLIndex],c=rL("FINGERPRINT")||a.fingerprint;if(o&&c){const n=Tee(o);OD(this,HF.PRE_CONNECT_PC,{candidates:n,fingerprint:c,turnServer:s,iceUfrag:a.iceUfrag,icePwd:a.icePwd}).then((t=>{null==e||e(t)})).catch(t||(()=>{}))}}})),this.signal.on(yF.RECOVER_NOTIFICATION,(e=>{this.joinInfo&&"string"==typeof rL("AP_REQUEST_DETAIL")&&(this.joinInfo.apRequestDetail="".concat(rL("AP_REQUEST_DETAIL"),";").concat(e))})),this.signal.on(yF.VOS_FALLBACK,(e=>{this.emit(HF.VOS_FALLBACK,e)})),this.signal.on(yF.DATACHANNEL_FAILBACK,(e=>{FL.warning("[".concat(this.store.clientId,"] User join datachannel failed")),this.reset(),this.resetSignal(),this.emit(HF.DATACHANNEL_FAILBACK)}))}async tryUnsubBeforeResub(e,t){try{await this.signal.request(bF.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw FL.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),e),e}}async tryUnsubDataChannelBeforeResub(e,t){try{await this.signal.request(bF.UNSUBSCRIBE,{stream_id:t.id},!0)}catch(e){throw FL.warning("unsubscribe datachannel warning",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(bF.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw FL.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),e),e}}async tryUnpubDataChannelBeforeRepub(e,t){try{await this.signal.request(bF.UNPUBLISH_DATASTREAM,{channnel_id:t.channelId},!0)}catch(e){throw FL.warning("unpublish datastream warning: ",e),e}}async tryMassUnsubBeforeResub(e){const t={users:e.map((e=>({stream_id:e.stream_id,stream_type:e.stream_type})))};try{await this.signal.request(bF.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw FL.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),e),e}}async muteLocal(e,t){const n={action:e.find((e=>e.stream_type===KF.Audio))?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(bF.CONTROL,n,!0,!0)}catch(e){throw FL.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),e),e}}async unmuteLocal(e,t){const n={action:e.find((e=>e.stream_type===KF.Audio))?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(bF.CONTROL,n,!0,!0)}catch(e){throw FL.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),e),e}}async muteRemote(e,t){const n={action:e===nB.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(bF.CONTROL,n,!0,!0)}catch(e){throw FL.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),e),e}}async unmuteRemote(e,t){const n={action:e===nB.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(bF.CONTROL,n,!0,!0)}catch(e){throw FL.warning("[".concat(this.store.clientId,"] gateway unmuteRemote warning: "),e),e}}uploadWRTCStats(e){this.signal.uploadWRTCStats(e)}upload(e,t){this.signal.upload(e,t)}getSignalRTT(){return this.signal.rtt}async restartICE(e){const t={p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:e};try{return await this.signal.request(bF.RESTART_ICE,t,!0)}catch(e){throw FL.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),e),e}}reconnect(e,t){"CONNECTED"===this.state&&this.signal.reconnect(e||void 0,t||ID.P2P_FAILED)}getCurrentGatewayAddress(){var e,t;if(!rL("GATEWAY_WSS_ADDRESS"))return rL("USE_CANDIDATE_FROM_AP_DETAIL")&&null!==(e=this.joinInfo)&&void 0!==e&&e.apGatewayAddress?(FL.debug("[".concat(this.store.clientId,"] use candidate from ap detail, ").concat(JSON.stringify(this.joinInfo.apGatewayAddress))),this.joinInfo.apGatewayAddress):null!==(t=this.joinInfo)&&void 0!==t&&t.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0}async setPublishAudioFilterEnabled(e){await this.signal.request(bF.SET_PARAMETER,{enablePublishAudioFilter:e})}downgradeCodec(e){this.signal.downgradeCodec(e)}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close(SD.FALLBACK)),this.store.useDcSignal=!1,this.signal=new FB(zee(zee({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}),this.store),this.handleSignalEvents(),this.emit(HF.RESET_SIGNAL)}}let Qee=function(e){return e.NATIVE_RTC="native_rtc",e.NATIVE_RTM="native_rtm",e.WEB_RTC="web_rtc",e.WEB_RTM="web_rtm",e}({}),$ee=0,ete=0;function tte(e,t,n,i){return new dp(((r,o)=>{t.timeout=t.timeout||rL("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),$ee+=ZD(t.data)):n&&(t.data.size?$ee+=t.data.size:t.data instanceof FormData?$ee+=qD(t.data):$ee+=ZD(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,QO.request(t).then((e=>{"string"==typeof e.data?ete+=ZD(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?ete+=e.data.byteLength:ete+=ZD(JSON.stringify(e.data)),i&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{QO.isCancel(e)?o(new hk(JN.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new hk(JN.NETWORK_TIMEOUT,e.message)):e.response?o(new hk(JN.NETWORK_RESPONSE_ERROR,e.response.status)):o(new hk(JN.NETWORK_ERROR,e.message))}))}))}
/*! formdata-polyfill. MIT License. Jimmy W?rting <https://jimmy.warting.se/opensource> */!function(){var e;function n(e){var t=0;return function(){return t<e.length?{done:!1,value:e[t++]}:{done:!0}}}var i="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,n){return e==Array.prototype||e==Object.prototype||(e[t]=n.value),e};var r,o=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof t&&t];for(var n=0;n<e.length;++n){var i=e[n];if(i&&i.Math==Math)return i}throw Error("Cannot find global object")}(this);function s(e,t){if(t)e:{var n=o;e=e.split(".");for(var r=0;r<e.length-1;r++){var s=e[r];if(!(s in n))break e;n=n[s]}(t=t(r=n[e=e[e.length-1]]))!=r&&null!=t&&i(n,e,{configurable:!0,writable:!0,value:t})}}function a(e){return(e={next:e})[Symbol.iterator]=function(){return this},e}function c(e){var t="undefined"!=typeof Symbol&&Symbol.iterator&&e[Symbol.iterator];return t?t.call(e):{next:n(e)}}if(s("Symbol",(function(e){function t(e,t){this.A=e,i(this,"description",{configurable:!0,writable:!0,value:t})}if(e)return e;t.prototype.toString=function(){return this.A};var n="jscomp_symbol_"+(1e9*Math.random()>>>0)+"_",r=0;return function e(i){if(this instanceof e)throw new TypeError("Symbol is not a constructor");return new t(n+(i||"")+"_"+r++,i)}})),s("Symbol.iterator",(function(e){if(e)return e;e=Symbol("Symbol.iterator");for(var t="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),r=0;r<t.length;r++){var s=o[t[r]];"function"==typeof s&&"function"!=typeof s.prototype[e]&&i(s.prototype,e,{configurable:!0,writable:!0,value:function(){return a(n(this))}})}return e})),"function"==typeof Object.setPrototypeOf)r=Object.setPrototypeOf;else{var d;e:{var l={};try{l.__proto__={a:!0},d=l.a;break e}catch(e){}d=!1}r=d?function(e,t){if(e.__proto__=t,e.__proto__!==t)throw new TypeError(e+" is not extensible");return e}:null}var u=r;function h(){this.m=!1,this.j=null,this.v=void 0,this.h=1,this.u=this.C=0,this.l=null}function p(e){if(e.m)throw new TypeError("Generator is already running");e.m=!0}function _(e,t){return e.h=3,{value:t}}function E(e){this.g=new h,this.G=e}function m(e,t,n,i){try{var r=t.call(e.g.j,n);if(!(r instanceof Object))throw new TypeError("Iterator result "+r+" is not an object");if(!r.done)return e.g.m=!1,r;var o=r.value}catch(t){return e.g.j=null,e.g.s(t),f(e)}return e.g.j=null,i.call(e.g,o),f(e)}function f(e){for(;e.g.h;)try{var t=e.G(e.g);if(t)return e.g.m=!1,{value:t.value,done:!1}}catch(t){e.g.v=void 0,e.g.s(t)}if(e.g.m=!1,e.g.l){if(t=e.g.l,e.g.l=null,t.F)throw t.D;return{value:t.return,done:!0}}return{value:void 0,done:!0}}function g(e){this.next=function(t){return e.o(t)},this.throw=function(t){return e.s(t)},this.return=function(t){return function(e,t){p(e.g);var n=e.g.j;return n?m(e,"return"in n?n.return:function(e){return{value:e,done:!0}},t,e.g.return):(e.g.return(t),f(e))}(e,t)},this[Symbol.iterator]=function(){return this}}function S(e,t){return t=new g(new E(t)),u&&e.prototype&&u(t,e.prototype),t}if(h.prototype.o=function(e){this.v=e},h.prototype.s=function(e){this.l={D:e,F:!0},this.h=this.C||this.u},h.prototype.return=function(e){this.l={return:e},this.h=this.u},E.prototype.o=function(e){return p(this.g),this.g.j?m(this,this.g.j.next,e,this.g.o):(this.g.o(e),f(this))},E.prototype.s=function(e){return p(this.g),this.g.j?m(this,this.g.j.throw,e,this.g.o):(this.g.s(e),f(this))},s("Array.prototype.entries",(function(e){return e||function(){return function(e,t){e instanceof String&&(e+="");var n=0,i=!1,r={next:function(){if(!i&&n<e.length){var r=n++;return{value:t(r,e[r]),done:!1}}return i=!0,{done:!0,value:void 0}}};return r[Symbol.iterator]=function(){return r},r}(this,(function(e,t){return[e,t]}))}})),"undefined"!=typeof Blob&&("undefined"==typeof FormData||!FormData.prototype.keys)){var T=function(e,t){for(var n=0;n<e.length;n++)t(e[n])},R=function(e){return e.replace(/\r?\n|\r/g,"\r\n")},v=function(e,t,n){return t instanceof Blob?(n=void 0!==n?String(n+""):"string"==typeof t.name?t.name:"blob",t.name===n&&"[object Blob]"!==Object.prototype.toString.call(t)||(t=new File([t],n)),[String(e),t]):[String(e),String(t)]},y=function(e,t){if(e.length<t)throw new TypeError(t+" argument required, but only "+e.length+" present.")},b="object"==typeof globalThis?globalThis:"object"==typeof window?window:"object"==typeof self?self:this,C=b.FormData,I=b.XMLHttpRequest&&b.XMLHttpRequest.prototype.send,A=b.Request&&b.fetch,w=b.navigator&&b.navigator.sendBeacon,O=b.Element&&b.Element.prototype,N=b.Symbol&&Symbol.toStringTag;N&&(Blob.prototype[N]||(Blob.prototype[N]="Blob"),"File"in b&&!File.prototype[N]&&(File.prototype[N]="File"));try{new File([],"")}catch(e){b.File=function(e,t,n){return e=new Blob(e,n||{}),Object.defineProperties(e,{name:{value:t},lastModified:{value:+(n&&void 0!==n.lastModified?new Date(n.lastModified):new Date)},toString:{value:function(){return"[object File]"}}}),N&&Object.defineProperty(e,N,{value:"File"}),e}}var D=function(e){return e.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22")},P=function(e){this.i=[];var t=this;e&&T(e.elements,(function(e){if(e.name&&!e.disabled&&"submit"!==e.type&&"button"!==e.type&&!e.matches("form fieldset[disabled] *"))if("file"===e.type){var n=e.files&&e.files.length?e.files:[new File([],"",{type:"application/octet-stream"})];T(n,(function(n){t.append(e.name,n)}))}else"select-multiple"===e.type||"select-one"===e.type?T(e.options,(function(n){!n.disabled&&n.selected&&t.append(e.name,n.value)})):"checkbox"===e.type||"radio"===e.type?e.checked&&t.append(e.name,e.value):(n="textarea"===e.type?R(e.value):e.value,t.append(e.name,n))}))};if((e=P.prototype).append=function(e,t,n){y(arguments,2),this.i.push(v(e,t,n))},e.delete=function(e){y(arguments,1);var t=[];e=String(e),T(this.i,(function(n){n[0]!==e&&t.push(n)})),this.i=t},e.entries=function e(){var t,n=this;return S(e,(function(e){if(1==e.h&&(t=0),3!=e.h)return t<n.i.length?e=_(e,n.i[t]):(e.h=0,e=void 0),e;t++,e.h=2}))},e.forEach=function(e,t){y(arguments,1);for(var n=c(this),i=n.next();!i.done;i=n.next()){var r=c(i.value);i=r.next().value,r=r.next().value,e.call(t,r,i,this)}},e.get=function(e){y(arguments,1);var t=this.i;e=String(e);for(var n=0;n<t.length;n++)if(t[n][0]===e)return t[n][1];return null},e.getAll=function(e){y(arguments,1);var t=[];return e=String(e),T(this.i,(function(n){n[0]===e&&t.push(n[1])})),t},e.has=function(e){y(arguments,1),e=String(e);for(var t=0;t<this.i.length;t++)if(this.i[t][0]===e)return!0;return!1},e.keys=function e(){var t,n,i,r,o=this;return S(e,(function(e){if(1==e.h&&(t=c(o),n=t.next()),3!=e.h)return n.done?void(e.h=0):(i=n.value,r=c(i),_(e,r.next().value));n=t.next(),e.h=2}))},e.set=function(e,t,n){y(arguments,2),e=String(e);var i=[],r=v(e,t,n),o=!0;T(this.i,(function(t){t[0]===e?o&&(o=!i.push(r)):i.push(t)})),o&&i.push(r),this.i=i},e.values=function e(){var t,n,i,r,o=this;return S(e,(function(e){if(1==e.h&&(t=c(o),n=t.next()),3!=e.h)return n.done?void(e.h=0):(i=n.value,(r=c(i)).next(),_(e,r.next().value));n=t.next(),e.h=2}))},P.prototype._asNative=function(){for(var e=new C,t=c(this),n=t.next();!n.done;n=t.next()){var i=c(n.value);n=i.next().value,i=i.next().value,e.append(n,i)}return e},P.prototype._blob=function(){var e="----formdata-polyfill-"+Math.random(),t=[],n="--"+e+'\r\nContent-Disposition: form-data; name="';return this.forEach((function(e,i){return"string"==typeof e?t.push(n+D(R(i))+'"\r\n\r\n'+R(e)+"\r\n"):t.push(n+D(R(i))+'"; filename="'+D(e.name)+'"\r\nContent-Type: '+(e.type||"application/octet-stream")+"\r\n\r\n",e,"\r\n")})),t.push("--"+e+"--"),new Blob(t,{type:"multipart/form-data; boundary="+e})},P.prototype[Symbol.iterator]=function(){return this.entries()},P.prototype.toString=function(){return"[object FormData]"},O&&!O.matches&&(O.matches=O.matchesSelector||O.mozMatchesSelector||O.msMatchesSelector||O.oMatchesSelector||O.webkitMatchesSelector||function(e){for(var t=(e=(this.document||this.ownerDocument).querySelectorAll(e)).length;0<=--t&&e.item(t)!==this;);return-1<t}),N&&(P.prototype[N]="FormData"),I){var L=b.XMLHttpRequest.prototype.setRequestHeader;b.XMLHttpRequest.prototype.setRequestHeader=function(e,t){L.call(this,e,t),"content-type"===e.toLowerCase()&&(this.B=!0)},b.XMLHttpRequest.prototype.send=function(e){e instanceof P?(e=e._blob(),this.B||this.setRequestHeader("Content-Type",e.type),I.call(this,e)):I.call(this,e)}}A&&(b.fetch=function(e,t){return t&&t.body&&t.body instanceof P&&(t.body=t.body._blob()),A.call(this,e,t)}),w&&(b.navigator.sendBeacon=function(e,t){return t instanceof P&&(t=t._asNative()),w.call(this,e,t)}),b.FormData=P}}();const nte=()=>{const e=rL("AREAS");0===e.length&&e.push(JF.GLOBAL);return ar(e).call(e,((e,t,n)=>{const i=ite(t);return i?0===n?i:"".concat(e,",").concat(i):e}),"")},ite=e=>e===JF.OVERSEA?"".concat(ZF.ASIA,",").concat(ZF.EUROPE,",").concat(ZF.AFRICA,",").concat(ZF.NORTH_AMERICA,",").concat(ZF.SOUTH_AMERICA,",").concat(ZF.OCEANIA):ZF[e],rte=e=>{const t={CODE:"",WEBCS_DOMAIN:[],WEBCS_DOMAIN_BACKUP_LIST:[],PROXY_CS:[],CDS_AP:[],ACCOUNT_REGISTER:[],UAP_AP:[],EVENT_REPORT_DOMAIN:[],EVENT_REPORT_BACKUP_DOMAIN:[],LOG_UPLOAD_SERVER:[],PROXY_SERVER_TYPE3:[]};return e.map((e=>{const n=qF[e],i=Object.keys(n);i&&i.map((e=>{"CODE"!==e&&(t[e]=t[e].concat(n[e]))}))})),t},ote={GLOBAL:{ASIA:[JF.CHINA,JF.JAPAN,JF.INDIA,JF.KOREA,JF.HKMC],EUROPE:[],NORTH_AMERICA:[JF.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},ste=Object.keys(ote[JF.GLOBAL]),ate=[JF.CHINA,JF.NORTH_AMERICA,JF.EUROPE,JF.ASIA,JF.JAPAN,JF.INDIA,JF.OCEANIA,JF.SOUTH_AMERICA,JF.AFRICA,JF.KOREA,JF.HKMC,JF.US],cte=function(e,t){let n=[];if(Vi(e).call(e,JF.GLOBAL)){const o=[JF.GLOBAL,JF.OVERSEA],s=Object.keys(qF);if(t===JF.GLOBAL)throw new hk(JN.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===JF.CHINA)n=[JF.OVERSEA];else if(r=t,Vi(ste).call(ste,r)){const e=(i=t,ote[JF.GLOBAL][i]||[]),r=[...o,t,...e];n=s.filter((e=>!Vi(r).call(r,e)))}else if(function(e){let t=!1;return ste.forEach((n=>{var i;Vi(i=ote[JF.GLOBAL][n]).call(i,e)&&(t=!0)})),t}(t)){const e=function(e){let t;return ste.forEach((n=>{var i;Vi(i=ote[JF.GLOBAL][n]).call(i,e)&&(t=n)})),t}(t),i=[...o,e,t];n=s.filter((e=>!Vi(i).call(i,e)))}else n=e;n=function(e){const t=[];return ate.forEach((n=>{Vi(e).call(e,n)&&t.push(n)})),t.concat(e.filter((e=>!Vi(ate).call(ate,e))))}(n)}else n=e;var i,r;return n};function dte(e){var t,n;if(!e&&Vi(t=rL("AREAS")).call(t,JF.EXTENSIONS))return FL.debug("update area from ap : reset"),void lte(Jx,!0);if(!Vi(n=rL("AREAS")).call(n,JF.GLOBAL)||!e)return;let i=qF.EXTENSIONS;i&&(i={CODE:ite(JF.EXTENSIONS),WEBCS_DOMAIN:["ap-web-1-".concat(e,".agora.io")],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-".concat(e,".ap.sd-rtn.com")],PROXY_CS:["proxy-ap-web-".concat(e,".agora.io")],CDS_AP:["cds-ap-web-1-".concat(e,".agora.io"),"cds-ap-web-2-".concat(e,".ap.sd-rtn.com")],ACCOUNT_REGISTER:["sua-ap-web-1-".concat(e,".agora.io"),"sua-ap-web-2-".concat(e,".ap.sd-rtn.com")],UAP_AP:["uap-ap-web-1-".concat(e,".agora.io"),"uap-ap-web-2-".concat(e,".ap.sd-rtn.com")],EVENT_REPORT_DOMAIN:["statscollector-1-".concat(e,".agora.io")],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-".concat(e,".agora.io")],LOG_UPLOAD_SERVER:["logservice-".concat(e,".agora.io")],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy-".concat(e,".agora.io")]},FL.debug("update area from ap success: ".concat(e,",config is "),i),iL("AREAS",[JF.EXTENSIONS],!0),Object.keys(i).map((e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){iL(e,i[e][0])}else iL(e,i[e])})))}function lte(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=uk.reportApiInvoke(null,{name:ED.SET_AREA,options:e,tag:mD.TRACER});try{let i=[];if("string"==typeof e&&(i=[e]),Array.isArray(e)&&(e.forEach((e=>{if(!Vi(zF).call(zF,e))throw new hk(JN.INVALID_PARAMS,"invalid area code")})),i=e),"[object Object]"===Object.prototype.toString.call(e)){const t=e,n=t.areaCode,r=t.excludedArea;if(!n)throw new hk(JN.INVALID_PARAMS,"area code is needed");let o=n;"string"==typeof n&&(o=[n]),i=r?cte(o,r):o}if(!t){if(sL.AREAS){const e=new hk(JN.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return n.onError(e),void FL.warning("setArea is prohibited because of config-distribute")}if(Vi(i).call(i,JF.GLOBAL)&&rL("AREAS")===JF.EXTENSIONS){const e=new hk(JN.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return n.onError(e),void FL.warning("setArea is prohibited because of ap extensions")}}iL("AREAS",i,t);const r=rte(i);Object.keys(r).map((e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){iL(e,r[e][0])}else iL(e,r[e])})),FL.debug("set area success:",i.join(","))}catch(e){throw n.onError(e),e}n.onSuccess()}function ute(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function hte(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ute(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ute(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let pte=1;function _te(e,t,n,i,r){pte+=1;const o={sid:n.sid,command:"convergeAllocateEdge",uid:"666",appId:n.appId,ts:Math.floor(Date.now()/1e3),seq:pte,requestId:pte,version:JP,cname:n.cname},s={service_name:t,json_body:JSON.stringify(o)};let a,c,d=e[0];return gP((async()=>{a=Date.now();const e=await tte(d,{data:s,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(c=Date.now()-a,0!==e.code){const t=new hk(JN.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:c});throw FL.error(t.toString()),t}const n=JSON.parse(e.json_body);if(200!==n.code){const e=new hk(JN.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(n.code,", reason: ").concat(n.reason),{code:n.code,responseTime:c});throw FL.error(e.toString()),e}if(!n.servers||0===n.servers.length){const e=new hk(JN.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:n.code,responseTime:c});throw FL.error(e.toString()),e}const r=function(e,t){return{addressList:e.servers.map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(rL("WORKER_DOMAIN"),":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t)))),workerToken:e.workerToken,vid:e.vid}}(n,t);return rL("LIVE_STREAMING_ADDRESS")&&(r.addressList=rL("LIVE_STREAMING_ADDRESS")instanceof Array?rL("LIVE_STREAMING_ADDRESS"):[rL("LIVE_STREAMING_ADDRESS")]),hte(hte({},r),{},{responseTime:c})}),((i,r)=>(uk.apworkerEvent(n.sid,{success:!0,sc:200,serviceName:t,responseDetail:JSON.stringify(i.addressList),firstSuccess:0===r,responseTime:c,serverIp:e[r%e.length]}),!1)),((i,r)=>(uk.apworkerEvent(n.sid,{success:!1,sc:i.data&&i.data.code||200,serviceName:t,responseTime:c,serverIp:e[r%e.length]}),!!(i.code!==JN.OPERATION_ABORTED&&i.code!==JN.UNEXPECTED_RESPONSE||i.data&&i.data.retry)&&(d=e[(r+1)%e.length],!0))),r)}let Ete=1;function mte(e,t,n,i,r,o,s){let a=e.url,c=e.areaCode;const d=Date.now();let l;const u=n.role,h=Hb(yte(r,n,i,c,Array.isArray(t)?t:[t]),2),p=h[0],_=h[1];let E=LD.networkState;return gP((async()=>{E&&LD.networkState===AD.OFFLINE&&LD.onlineWaiter&&await dp.race([LD.onlineWaiter,$D(s&&s.maxRetryTimeout||mP.maxRetryTimeout)]),E=LD.networkState;const e=await tte(a,{data:p,cancelToken:o,responseType:"arraybuffer",headers:{"Content-Type":"application/x-protobuf;"}},!0,!0),r=e.data,c=e.headers;let u;l="1"===c.http3?1:-1,uk.reportResourceTiming(a,n.sid);const h=c["content-type"]||c["Content-Type"]||"",_=Vi(h).call(h,"application/json");try{u=_?function(e){const t=rL("ENABLE_AP_COMPRESS")?uK(e,{raw:!0}):e,n=(new TextDecoder).decode(t);return JSON.parse(n)}(r):W7(n,i,r)}catch(e){throw new hk(JN.PB_ERROR,"sdp enpoint response transformer get unknown res",{retry:!1})}Ste(u,a,n,d,Array.isArray(t)?t:[t],l);const m=$7(u,hK.CHOOSE_SERVER);let f;Array.isArray(t)&&t.length>1&&(f=$7(u,"proxy5"===n.cloudProxyServer?hK.CLOUD_PROXY_5:"proxy3"===n.cloudProxyServer||"proxy4"===n.cloudProxyServer?hK.CLOUD_PROXY:hK.CLOUD_PROXY_FALLBACK));const g=performance.getEntriesByName(a),S=g[g.length-1];let T;return S&&(T={name:S.name,protocol:"nextHopProtocol"in S?S.nextHopProtocol:"",dnscost:"domainLookupEnd"in S&&"domainLookupStart"in S&&"number"==typeof S.domainLookupEnd&&"number"==typeof S.domainLookupStart?S.domainLookupEnd-S.domainLookupStart:-1,tcpTlsCost:"connectEnd"in S&&"connectStart"in S&&"number"==typeof S.connectEnd&&"number"==typeof S.connectStart?S.connectEnd-S.connectStart:-1,reqCost:"requestStart"in S&&"number"==typeof S.requestStart&&"responseEnd"in S&&"number"==typeof S.responseEnd?S.responseEnd-S.requestStart:-1,handleCost:"leave_ts"in u&&"enter_ts"in u&&"number"==typeof u.leave_ts&&"number"==typeof u.enter_ts?u.leave_ts-u.enter_ts:-1}),Tte(m),Array.isArray(t)?{gatewayInfo:z7(m,a),proxyInfo:f,url:a,resourceTimingInfo:T}:z7(m,a)}),(e=>{const i="gatewayInfo"in e?e.gatewayInfo:e,r="proxyInfo"in e?e.proxyInfo:void 0,o="resourceTimingInfo"in e?e.resourceTimingInfo:void 0;return i&&uk.joinChooseServer(n.sid,{role:u,lts:d,succ:!0,csAddr:a,serverList:i.gatewayAddrs.map((e=>e.address)),ec:null,opid:_,cid:i.cid.toString(),uid:i.uid.toString(),csIp:i.csIp,unilbsServerIds:t.toString(),isHttp3:l,corssRegionTagReq:n.apRequestDetail,corssRegionTagRes:i.res.detail&&i.res.detail[38],vid:null==i?void 0:i.vid,resourceTimingInfo:o?JSON.stringify(o):void 0}),r&&uk.joinWebProxyAP(n.sid,{lts:d,sucess:1,apServerAddr:a,turnServerAddrList:r.addresses.map((e=>e.ip)).join(","),errorCode:null,eventType:n.cloudProxyServer,unilbsServerIds:t.toString()}),!1}),(e=>e.code!==JN.PB_ERROR&&(e.code!==JN.OPERATION_ABORTED&&(e.code===JN.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(uk.joinWebProxyAP(n.sid,{lts:d,sucess:0,apServerAddr:a,turnServerAddrList:null,errorCode:e.code,eventType:n.cloudProxyServer,unilbsServerIds:t.toString(),extend:JSON.stringify({networkState:E})}),FL.warning("[".concat(n.clientId,"] multi unilbs network error, retry"),e),!0)))),s)}function fte(e,t,n,i){let r=e.url,o=e.areaCode;const s=t.clientId,a=t.sid,c=Date.now();let d;const l=t.role,u=Hb(vte(t,o,[hK.CHOOSE_SERVER]),2),h=u[0],p=u[1];let _=LD.networkState;return gP((async()=>{_&&LD.networkState===AD.OFFLINE&&LD.onlineWaiter&&await dp.race([LD.onlineWaiter,$D(i&&i.maxRetryTimeout||mP.maxRetryTimeout)]),_=LD.networkState;const e=await tte(r,{data:h,cancelToken:n,headers:{"Content-Type":"multipart/form-data;"}},!0,!0),o=e.data,s=e.headers;d="1"===s.http3?1:-1,uk.reportResourceTiming(r,a),Ste(o,r,t,c,[hK.CHOOSE_SERVER],d);const l=$7(o,hK.CHOOSE_SERVER);return Tte(l),z7(l,r)}),(e=>(e&&uk.joinChooseServer(a,{role:l,lts:c,succ:!0,csAddr:r,opid:p,serverList:e.gatewayAddrs.map((e=>e.address)),ec:null,cid:e.cid.toString(),uid:e.uid.toString(),csIp:e.csIp,unilbsServerIds:[hK.CHOOSE_SERVER].toString(),isHttp3:d,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.res.detail&&e.res.detail[38],vid:e.vid}),!1)),(e=>e.code!==JN.OPERATION_ABORTED&&(e.code===JN.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(uk.joinChooseServer(a,{role:l,lts:c,succ:!1,csAddr:r,serverList:null,opid:p,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[hK.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:_}),isHttp3:d,corssRegionTagReq:t.apRequestDetail}),FL.warning("[".concat(s||"sid-".concat(a.slice(0,6)),"] Choose server network error, retry"),e),!0))),i)}function gte(e,t,n,i){let r,o=e.url,s=e.areaCode,a=e.serviceIds;const c=Date.now(),d=t.role,l=Hb(vte(t,s,a),2),u=l[0],h=l[1];let p;return gP((async()=>{p&&LD.networkState===AD.OFFLINE&&LD.onlineWaiter&&await dp.race([LD.onlineWaiter,$D(i&&i.maxRetryTimeout||mP.maxRetryTimeout)]),p=LD.networkState;const e=await tte(o,{data:u,cancelToken:n,headers:{"Content-Type":"multipart/form-data;"}},!0,!0),s=e.data,d=e.headers;r="1"===d.http3?1:-1,uk.reportResourceTiming(o,t.sid),Ste(s,o,t,c,a,r);const l=$7(s,hK.CHOOSE_SERVER),h=$7(s,"proxy5"===t.cloudProxyServer?hK.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?hK.CLOUD_PROXY:hK.CLOUD_PROXY_FALLBACK),_=performance.getEntriesByName(o),E=_[_.length-1];let m;return E&&(m={name:E.name,protocol:"nextHopProtocol"in E?E.nextHopProtocol:"",dnscost:"domainLookupEnd"in E&&"domainLookupStart"in E&&"number"==typeof E.domainLookupEnd&&"number"==typeof E.domainLookupStart?E.domainLookupEnd-E.domainLookupStart:-1,tcpTlsCost:"connectEnd"in E&&"connectStart"in E&&"number"==typeof E.connectEnd&&"number"==typeof E.connectStart?E.connectEnd-E.connectStart:-1,reqCost:"requestStart"in E&&"number"==typeof E.requestStart&&"responseEnd"in E&&"number"==typeof E.responseEnd?E.responseEnd-E.requestStart:-1,handleCost:"leave_ts"in s&&"enter_ts"in s&&"number"==typeof s.leave_ts&&"number"==typeof s.enter_ts?s.leave_ts-s.enter_ts:-1}),Tte(l),{gatewayInfo:z7(l,o),proxyInfo:h,url:o,resourceTimingInfo:m}}),(e=>{var n;return e.gatewayInfo&&uk.joinChooseServer(t.sid,{role:d,lts:c,succ:!0,csAddr:o,serverList:e.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,opid:h,cid:e.gatewayInfo.cid.toString(),uid:e.gatewayInfo.uid.toString(),csIp:e.gatewayInfo.csIp,unilbsServerIds:a.toString(),isHttp3:r,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.gatewayInfo.res.detail&&e.gatewayInfo.res.detail[38],vid:null===(n=e.gatewayInfo)||void 0===n?void 0:n.vid,resourceTimingInfo:e.resourceTimingInfo?JSON.stringify(e.resourceTimingInfo):void 0}),e.proxyInfo&&uk.joinWebProxyAP(t.sid,{lts:c,sucess:1,apServerAddr:o,turnServerAddrList:e.proxyInfo.addresses.map((e=>e.ip)).join(","),errorCode:null,eventType:t.cloudProxyServer,unilbsServerIds:a.toString()}),!1}),(e=>e.code!==JN.OPERATION_ABORTED&&(e.code===JN.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(uk.joinWebProxyAP(t.sid,{lts:c,sucess:0,apServerAddr:o,turnServerAddrList:null,errorCode:e.code,eventType:t.cloudProxyServer,unilbsServerIds:a.toString(),extend:JSON.stringify({networkState:p})}),FL.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0))),i)}const Ste=(e,t,n,i,r,o)=>{const s=n.sid,a=n.clientId,c=n.cloudProxyServer,d=[],l=a=>{4096===a.flag?uk.joinChooseServer(s,{role:n.role,lts:i,succ:!1,csAddr:t,opid:e.opid,serverList:null,ec:a.error.message,csIp:a.error.data&&a.error.data.csIp,unilbsServerIds:r.toString(),isHttp3:o,corssRegionTagReq:n.apRequestDetail}):1048576!==a.flag&&4194304!==a.flag&&4194310!==a.flag||uk.joinWebProxyAP(s,{lts:i,sucess:0,apServerAddr:t,turnServerAddrList:null,errorCode:a.error.code,eventType:c,unilbsServerIds:r.toString()})};if(e.response_body.forEach((t=>{const n=t.buffer.code;if(23===t.uri&&0===n&&!t.buffer.edges_services)if(4194310===t.buffer.flag)FL.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers"),t.buffer.edges_services=[];else{const n={error:new hk(JN.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:rL("NO_EDGES_RETRY"),csIp:e.detail[502]}),flag:t.buffer.flag};d.push(n),l(n)}if(0!==n){const i=yB(n),r={error:new hk(JN.CAN_NOT_GET_GATEWAY_SERVER,i.desc,{desc:i.desc,retry:i.retry,csIp:e.detail[502]}),flag:t.buffer.flag};4194310===t.buffer.flag?FL.warning(r.error.toString()):d.push(r),l(r)}})),d.length)throw FL.warning("[".concat(a||"sid-".concat(s.slice(0,6)),"] multi unilbs ").concat(t," failed, ").concat(d.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message,", retry: ").concat(e.error.data.retry))).join(" | "))),new hk(JN.CAN_NOT_GET_GATEWAY_SERVER,d.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message))).join(" | "),{retry:!!d.find((e=>e.error.data.retry)),csIp:e.detail[502],desc:[...new Set(d.map((e=>{var t;return null==e||null===(t=e.error)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.desc})).filter((e=>!!e)))]})},Tte=e=>{var t,n,i,r;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new hk(JN.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});rL("AP_AREA")&&(null!==(i=e.detail)&&void 0!==i&&i[23]&&"string"==typeof(null===(r=e.detail)||void 0===r?void 0:r[23])?dte(e.detail[23].toLowerCase()):dte());if(null!==(t=e.detail)&&void 0!==t&&t[19]&&"string"==typeof(null===(n=e.detail)||void 0===n?void 0:n[19])){const t=e.detail[19],n=null==t?void 0:t.split(";");for(let t=0;t<n.length;t++){var o;const i=ZS(o=n[t]).call(o),r=e.addresses[t];r&&n&&!r.fingerprint&&(e.addresses[t].fingerprint=i)}}if(rL("GATEWAY_ADDRESS")&&rL("GATEWAY_ADDRESS").length>0){FL.debug("assign gateway address to",rL("GATEWAY_ADDRESS"));const t=rL("GATEWAY_ADDRESS").map((t=>{var n,i,r,o;const s=null!==(n=null===(i=e.addresses.find((e=>e.ip===t.ip&&e.port===t.port)))||void 0===i?void 0:i.fingerprint)&&void 0!==n?n:"";return{ip:t.ip,port:t.port,ticket:e.addresses[0]&&e.addresses[0].ticket,fingerprint:s,iceUfrag:null===(r=e.addresses[0])||void 0===r?void 0:r.iceUfrag,icePwd:null===(o=e.addresses[0])||void 0===o?void 0:o.icePwd}}));e.addresses=t}},Rte=(e,t)=>{if(e.response_body&&e.response_body.length){const t=e.response_body[0];if(0!==t.buffer.code){const e=yB(t.buffer.code);throw new hk(JN.UPDATE_TICKET_FAILED,"[".concat(t.buffer.code,"]: ").concat(e.desc),{retry:e.retry})}return t.buffer.ticket}throw FL.debug("update ticket request received ap response without response body:",t),new hk(JN.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},vte=(e,t,n)=>{const i=Math.floor(Math.random()*10**12),r="host"===e.role?"1":"audience"===e.role?"2":void 0,o={appid:e.appId,client_ts:Date.now(),opid:i,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:hte(hte(hte({6:e.stringUid,11:t,12:rL("USE_NEW_TOKEN")?"1":void 0},r?{17:r}:{}),{},{22:t},e.apRequestDetail?{33:e.apRequestDetail}:{}),e.apRTM?{26:"RTM2"}:{}),key:e.token,service_ids:n,uid:e.uid||0}}]};o.request_bodies.forEach((t=>{e.multiIP&&e.multiIP.gateway_ip&&(t.buffer.detail[5]=JSON.stringify({vocs_ip:[e.multiIP.uni_lbs_ip],vos_ip:[e.multiIP.gateway_ip]}))}));const s=new FormData;return s.append("request",JSON.stringify(o)),[s,i]},yte=(e,t,n,i,r)=>{const o=Math.floor(Math.random()*10**12);return[G7(e,t,i,r,{opid:o,mode:e.mode,codec:e.codec,hasChangeBGPAddress:!1,ortc:n}),o]},bte=(e,t)=>{const n=Math.floor(Math.random()*10**12),i={appid:e.appId,client_ts:Date.now(),opid:n,sid:e.sid,request_bodies:[{uri:28,buffer:{cname:e.cname,detail:{1:"",6:e.stringUid,12:"1"},token:e.token,service_ids:t,uid:e.uid||0,edges_services:e.apResponse.addresses.map((e=>({ip:e.ip,port:e.port})))}}]},r=new FormData;return r.append("request",JSON.stringify(i)),[r,n]};let Cte=0;function Ite(e){return dp.all(e.map((e=>e.then((e=>{throw e}),(e=>e))))).then((e=>{throw e}),(e=>e))}const Ate=async e=>{let t=e.fragementLength,n=e.referenceList,i=e.asyncMapHandler,r=e.allFailedhandler,o=e.promisesCollector,s=0;const a=t;let c,d=0;const l=async()=>{const e=(()=>{const e=s*a,t=e+a;return n.slice(e,t).map(i)})();o&&o.push(...e);try{c=await Ite(e)}catch(e){if(d+=a,s++,!(d>=n.length))return void await l();r(e)}e.forEach((e=>e.cancel()))};return await l(),c},wte=async e=>{let t=e.referenceList,n=e.asyncMapHandler,i=e.closeFn;const r=t.length;let o=0;const s=async()=>{const e=n(t.shift());try{return await e}catch(e){if(o++,o>=r||null!=i&&i(e))throw e;return s()}};return s()};async function Ote(){if("undefined"==typeof VideoDecoder)return!0;let e;const t=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,85,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,149,160,133,4,144,43,122,168,159,120,159,205,39,82,131,57,52,87,187,68,23,248,134,204,226,97,17,49,183,55,236,219,249,221,98,208,215,190,59,179,167,213,47,1,246,150,14,194,245,159,83,35,64,103,218,38,21,82,3,135,21,185,84,248,134],n=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,87,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,148,62,134,140,92,172,141,77,35,94,181,164,65,169,65,156,154,43,221,162,11,252,67,102,113,48,136,137,219,62,43,113,239,23,126,250,186,252,10,138,218,25,193,244,74,68,194,209,107,23,52,206,199,78,72,98,103,151,71,96,62,51,210,158,72,231,158],i=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,87,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,143,233,163,51,196,98,95,151,224,22,134,33,240,150,248,67,18,34,196,142,81,238,173,140,80,205,232,132,144,67,12,131,157,4,171,243,86,122,35,6,166,184,243,85,126,13,206,103,152,62,168,160,187,2,241,138,52,211,72,121,128,151,63,147,128,19,42],r=[18,0,50,138,1,48,192,64,253,248,65,17,67,192,32,0,16,0,0,0,0,0,0,0,195,12,48,144,64,32,0,209,75,61,9,204,25,115,79,226,115,63,63,208,70,210,220,153,126,241,237,37,107,195,153,1,99,112,230,189,209,169,130,10,11,22,167,215,159,205,197,7,183,162,26,48,254,141,134,103,32,16,235,45,1,15,18,119,169,110,206,251,51,115,202,60,148,1,46,39,109,25,28,86,168,15,77,211,239,2,58,43,146,26,230,184,81,48,140,226,226,250,222,146,171,133,164,13,188,180,64,122,142,146,32,208,238,170,193,35,53,44,225],o=[18,0,50,107,48,0,133,125,248,65,26,195,64,62,32,31,16,0,0,0,0,0,1,4,16,64,144,64,32,0,204,24,122,65,56,165,18,52,206,218,4,187,51,97,9,29,191,90,253,106,185,31,197,155,52,205,245,185,203,131,20,226,25,124,95,113,220,113,141,15,15,104,211,144,152,237,150,157,127,51,143,24,231,218,171,255,176,241,128,229,149,150,148,66,245,228,91,27,182,228,136,61,182,237,133,45,220,24,103,214,152],s=[18,0,50,122,48,1,9,253,248,65,26,67,64,62,32,31,16,0,0,0,0,0,1,4,16,64,144,64,32,0,198,182,231,242,220,235,163,140,12,36,36,166,46,132,210,4,71,23,218,132,27,30,17,45,244,79,31,243,195,136,100,169,76,88,142,85,204,217,121,168,29,163,198,17,251,223,73,12,212,244,139,123,151,179,75,216,96,208,136,40,229,42,59,149,10,116,228,85,99,93,221,108,255,140,248,20,30,167,122,109,206,164,108,197,110,251,23,243,133,160,63,13,207,177,12,128],a=await new dp(((a,c)=>{let d;!async function(){e&&"closed"!==e.state||await async function(){e=new VideoDecoder({output:e=>{e.close(),clearTimeout(d),a(!0)},error:e=>{clearTimeout(d),a(!1)}}),await e.configure({codec:"av01.0.05M.08",width:160,height:90})}();const c=[t,n,i,r,o,s];for(let t=0;t<c.length;t++){const n=new EncodedVideoChunk({type:0==t?"key":"delta",timestamp:33333*t,duration:33333,data:new Uint8Array(c[t])});try{await e.decode(n)}catch(e){return void a(!1)}}}(),d=setTimeout((()=>{a(!1)}),5e3)}));return a}async function Nte(e,t,n,i){const r=async function(e,t,n,i){let r=null;const o=[],s=async()=>{const r=rL("WEBCS_DOMAIN").slice(0,rL("AJAX_REQUEST_CONCURRENT")).map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:nte()}))),s=i.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),a=await Ate({fragementLength:rL("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:i=>(FL.debug("[".concat(e.clientId,"] Connect to choose_server:"),i.url),fte(i,e,t,n)),allFailedhandler:e=>{throw i.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},s),e[0]},promisesCollector:o});return i.recordJoinChannelService({endTs:Date.now(),status:"success"},s),a},a=async()=>{if(await $D(1e3),null!==r)return r;const s=rL("WEBCS_DOMAIN_BACKUP_LIST").map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:nte()}))),a=i.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:s.map((e=>e.url))}),c=await Ate({fragementLength:rL("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:i=>(FL.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),i.url),fte(i,e,t,n)),allFailedhandler:e=>{throw i.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},a),e[0]},promisesCollector:o});return i.recordJoinChannelService({endTs:Date.now(),status:"success"},a),c};try{return r=await Ite([s(),a()]),o.length&&o.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),r}catch(e){throw e[0]}}(e,t,n,i);return{gatewayInfo:await r}}async function Dte(e,t,n,i,r){const o=e.cloudProxyServer;if("disabled"===o){if(!i)return;if(e.useLocalAccessPoint)return await Nte(e,t,n,r);if(rL("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const i=await Vte(e,t,n,r),o=i.gatewayInfo,a=i.proxyInfo;if(e.turnServer&&"auto"!==e.turnServer.mode)return{gatewayInfo:o};const c=a.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||qP.tcpport,udpport:e.udpport||qP.udpport,username:e.username||qP.username,password:e.password||qP.password,forceturn:!1,security:!0})));if(r.useP2P){var s;const t=null!==(s=e.uid)&&void 0!==s?s:o.uid,n="glb:".concat(t.toString()),i=await uD(n),r=a.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||qP.tcpport,udpport:e.udpport||qP.udpport,username:n,password:i,forceturn:!1,security:!0})));c.push(...r)}return e.turnServer={mode:"manual",servers:c},{gatewayInfo:o}}return await Nte(e,t,n,r)}const a=await Vte(e,t,n,r),c=a.proxyInfo,d=a.gatewayInfo,l={gatewayInfo:d},u=c.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport?e.tcpport:qP.tcpport,udpport:"proxy4"===o?void 0:e.udpport?e.udpport:qP.udpport,username:e.username||qP.username,password:e.password||qP.password,forceturn:"proxy4"!==o,security:"proxy5"===o})));if(r.useP2P){var h;const t=null!==(h=e.uid)&&void 0!==h?h:d.uid,n="glb:".concat(t.toString()),i=await uD(n),r=c.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport||qP.tcpport,udpport:"proxy4"===o?void 0:e.udpport||qP.udpport,username:n,password:i,forceturn:"proxy4"!==o,security:"proxy5"===o})));u.push(...r)}return e.turnServer={mode:"manual",servers:u},FL.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(o)),l}async function Pte(e,t,n,i,r){const o=e.cloudProxyServer;if("disabled"===o){if(e.useLocalAccessPoint)return await Nte(e,t,n,i);if(rL("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const o=await Vte(e,t,n,i,r),s=o.gatewayInfo,a=o.proxyInfo;if(e.turnServer&&"auto"!==e.turnServer.mode)return{gatewayInfo:s};const c=a.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||qP.tcpport,udpport:e.udpport||qP.udpport,username:e.username||qP.username,password:e.password||qP.password,forceturn:!1,security:!0})));return e.turnServer={mode:"manual",servers:c},{gatewayInfo:s}}{const o=async function(e,t,n,i,r){let o=null;const s=[],a=async()=>{const o=rL("SDP_ENDPOINT_DOMAIN").slice(0,rL("AJAX_REQUEST_CONCURRENT")).map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v3/transpond/webrtc?v=3"):"https://".concat(t,"/api/v3/transpond/webrtc?v=3"),areaCode:nte()}))),a=r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map((e=>e.url))}),c=await Ate({fragementLength:rL("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:o=>(FL.debug("[".concat(e.clientId,"] Connect to choose_server:"),o.url),mte(o,hK.CHOOSE_SERVER,e,t,r,n,i)),allFailedhandler:e=>{throw r.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},a),e[0]},promisesCollector:s});return r.recordJoinChannelService({endTs:Date.now(),status:"success"},a),c},c=async()=>{if(await $D(1e3),null!==o)return o;const a=rL("SDP_ENDPOINT_DOMAIN_BACKUP_LIST").map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v3/transpond/webrtc?v=3"):"https://".concat(t,"/api/v3/transpond/webrtc?v=3"),areaCode:nte()}))),c=r.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:a.map((e=>e.url))}),d=await Ate({fragementLength:rL("FRAGEMENT_LENGTH"),referenceList:a,asyncMapHandler:o=>(FL.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),o.url),mte(o,hK.CHOOSE_SERVER,e,t,r,n,i)),allFailedhandler:e=>{throw r.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},c),e[0]},promisesCollector:s});return r.recordJoinChannelService({endTs:Date.now(),status:"success"},c),d};try{return o=await Ite([a(),c()]),s.length&&s.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),o}catch(e){throw e[0]}}(e,r,t,n,i);return{gatewayInfo:await o}}}const s=await Vte(e,t,n,i),a=s.proxyInfo,c={gatewayInfo:s.gatewayInfo},d=a.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport?e.tcpport:qP.tcpport,udpport:"proxy4"===o?void 0:e.udpport?e.udpport:qP.udpport,username:e.username||qP.username,password:e.password||qP.password,forceturn:"proxy4"!==o,security:"proxy5"===o})));return e.turnServer={mode:"manual",servers:d},FL.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(o)),c}async function Lte(e,t,n,i,r){const o=rL("ACCOUNT_REGISTER").slice(0,rL("AJAX_REQUEST_CONCURRENT"));let s=[];s=t.proxyServer?o.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):o.map((e=>"https://".concat(e,"/api/v1")));const a=null==r?void 0:r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:s});try{const o=await async function(e,t,n,i,r){const o=Date.now(),s={sid:n.sid,opid:10,appid:n.appId,string_uid:t};let a=e[0];const c=await gP((()=>tte(a+"".concat(-1===a.indexOf("?")?"?":"&","action=stringuid"),{data:s,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}})),((n,i)=>{if(0===n.code){if(n.uid<=0||n.uid>=Math.pow(2,32))throw FL.error("Invalid Uint Uid ".concat(t," => ").concat(n.uid),n),uk.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:n.uid,errorCode:JN.INVALID_UINT_UID_FROM_STRING_UID,extend:s}),new hk(JN.INVALID_UINT_UID_FROM_STRING_UID);return uk.reqUserAccount(s.sid,{lts:o,success:!0,serverAddr:a,stringUid:s.string_uid,uid:n.uid,errorCode:null,extend:s}),!1}const r=yB(n.code);return r.retry&&(a=e[(i+1)%e.length]),uk.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:n.uid,errorCode:r.desc,extend:s}),r.retry}),((t,n)=>t.code!==JN.OPERATION_ABORTED&&(uk.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:null,errorCode:t.code,extend:s}),a=e[(n+1)%e.length],!0)),r);if(0!==c.code){const e=yB(c.code);throw new hk(JN.UNEXPECTED_RESPONSE,e.desc)}return c}(s,e,t,n,i);return null==r||r.recordJoinChannelService({status:"success",endTs:Date.now()},a),o.uid}catch(e){throw null==r||r.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},a),e}}async function kte(e,t,n){const i=rL("ACCOUNT_REGISTER");let r=[];r=t.proxyServer?i.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):i.map((e=>"https://".concat(e,"/api/v1")));try{const i=await wte({referenceList:r,asyncMapHandler:i=>async function(e,t,n,i){const r=Date.now(),o={sid:n.sid,opid:10,appid:n.appId,string_uid:t};try{const t=await tte(e+"".concat(-1===e.indexOf("?")?"?":"&","action=stringuid"),{data:o,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}});if(0!==t.code){const e=yB(t.code);throw new hk(JN.UNEXPECTED_RESPONSE,"preload sua error:".concat(e.desc),e)}if(t.uid<=0||t.uid>=Math.pow(2,32))throw new hk(JN.INVALID_UINT_UID_FROM_STRING_UID);return{requestTime:r,url:e,req:o,uid:t.uid,elapse:Date.now()-r}}catch(e){throw e}}(i,e,t,n),closeFn:e=>e.code===JN.OPERATION_ABORTED||e.code===JN.UNEXPECTED_RESPONSE&&!e.data.retry});return i}catch(e){throw e}}async function Mte(e,t,n){const i=rL("CDS_AP").slice(0,rL("AJAX_REQUEST_CONCURRENT")).map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1"):"https://".concat(t,"/api/v1?action=config"))),r=i.map((i=>function(e,t,n,i){const r=dN(),o={flag:64,cipher_method:0,features:hte(hte(hte(hte(hte({install_id:XP(),device:r.name,system:r.os,system_general:navigator.userAgent,vendor:t.appId,version:JP,cname:t.cname,session_id:t.sid,proxyServer:t.proxyServer,sdk_type:Qee.WEB_RTC,browser_name:r.name,browser_version:r.version,user_agent:navigator.userAgent,channel_name:t.cname},t.stringUid&&{string_uid:t.stringUid}),t.uid&&{uid:t.uid+""}),r.os&&{os_name:r.os}),r.osVersion&&{os_version:r.osVersion}),{},{detail:""})};return gP((()=>tte(e,{data:o,timeout:1e3,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}})),void 0,(e=>e.code!==JN.OPERATION_ABORTED),i)}(i,e,t,n)));let o=null,s=null,a={};try{o=await Ite(r)}catch(e){if(e.code===JN.OPERATION_ABORTED)throw e;s=e}r.forEach((e=>e.cancel()));if(uk.reportApiInvoke(e.sid,{name:ED.REQUEST_CONFIG_DISTRIBUTE,options:{error:s,res:o}}).onSuccess(),o&&o.test_tags)try{a=function(e){if(!e.test_tags)return{};const t=e.test_tags,n=Object.keys(t),i={};return n.forEach((e=>{var n;const r=ZS(n=e.slice(4)).call(n),o=JSON.parse(t[e]),s=o[1];i[r]={tag:o[0]||"",value:s}})),i}(o)}catch(e){}return a}async function Ute(e,t){const n=rL("WEBCS_DOMAIN").concat(rL("WEBCS_DOMAIN_BACKUP_LIST")).map((e=>({url:"https://".concat(e,"/api/v2/transpond/webrtc?v=2"),areaCode:nte(),serviceIds:[hK.CHOOSE_SERVER,hK.CLOUD_PROXY_FALLBACK]})));try{const i=await wte({referenceList:n,asyncMapHandler:n=>async function(e,t,n){let i,r=e.url,o=e.areaCode,s=e.serviceIds;const a=Date.now(),c=Hb(vte(t,o,s),2),d=c[0],l=c[1];let u=LD.networkState;try{u&&LD.networkState===AD.OFFLINE&&LD.onlineWaiter&&await dp.race([LD.onlineWaiter,$D(mP.maxRetryTimeout)]),u=LD.networkState;const e=await tte(r,{data:d,cancelToken:n,headers:{"Content-Type":"multipart/form-data;"}},!0,!0),t=e.data;i="1"===e.headers.http3?1:-1;const o=e=>{const t=[];if(e.response_body.forEach((n=>{const i=n.buffer.code;if(23===n.uri&&0===i&&!n.buffer.edges_services)if(4194310===n.buffer.flag)n.buffer.edges_services=[];else{const i={error:new hk(JN.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:rL("NO_EDGES_RETRY"),csIp:e.detail[502]}),flag:n.buffer.flag};t.push(i)}if(0!==i){const r=yB(i),o={error:new hk(JN.CAN_NOT_GET_GATEWAY_SERVER,r.desc,{desc:r.desc,retry:r.retry,csIp:e.detail[502]}),flag:n.buffer.flag};4194310===n.buffer.flag?FL.warning(o.error.toString()):t.push(o)}})),t.length)throw new hk(JN.CAN_NOT_GET_GATEWAY_SERVER,t.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message))).join(" | "),{retry:!!t.find((e=>e.error.data.retry)),csIp:e.detail[502],desc:[...new Set(t.map((e=>{var t;return null==e||null===(t=e.error)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.desc})).filter((e=>!!e)))]})};o(t);const s=$7(t,hK.CHOOSE_SERVER),c=$7(t,hK.CLOUD_PROXY_FALLBACK);return Tte(s),{gatewayInfo:z7(s,r),proxyInfo:c,opid:l,requestTime:a,url:r,isHttp3:i,elapse:Date.now()-a}}catch(e){throw e}}(n,e,t),closeFn:e=>e.code===JN.OPERATION_ABORTED||e.code===JN.CAN_NOT_GET_GATEWAY_SERVER&&!e.data.retry});return i}catch(e){throw e}}async function Vte(e,t,n,i,r){const o=rL("PROXY_SERVER_TYPE3"),s=(e,t,n)=>{let i=n||o;return Array.isArray(i)&&(i=t%2==0&&o[1]||o[0]),"https://".concat(i,"/ap/?url=").concat(e)};let a=null;const c=[],d=async()=>{const o=rL(r?"SDP_ENDPOINT_DOMAIN":"WEBCS_DOMAIN").slice(0,rL("AJAX_REQUEST_CONCURRENT")).map(((t,n)=>{let i;return i="disabled"===e.cloudProxyServer&&e.proxyServer?s("".concat(t,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"),n,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"):s("".concat(t,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"),n),{url:i,areaCode:nte(),serviceIds:[hK.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?hK.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?hK.CLOUD_PROXY:hK.CLOUD_PROXY_FALLBACK]}})),a=i.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map((e=>e.url))}),d=await Ate({fragementLength:rL("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:o=>(FL.debug("[".concat(e.clientId,"] Connect to choose_server:"),o.url),r?mte(o,o.serviceIds,e,r,i,t,n):gte(o,e,t,n)),allFailedhandler:e=>{throw i.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},a),e[0]},promisesCollector:c});return i.recordJoinChannelService({endTs:Date.now(),status:"success"},a),d},l=async()=>{if(await $D(1e3),null!==a)return a;const o=rL(r?"SDP_ENDPOINT_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN_BACKUP_LIST").map(((t,n)=>{let i;return i="disabled"===e.cloudProxyServer&&e.proxyServer?s("".concat(t,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"),n,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"):s("".concat(t,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"),n),{url:i,areaCode:nte(),serviceIds:[hK.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?hK.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?hK.CLOUD_PROXY:hK.CLOUD_PROXY_FALLBACK]}})),d=i.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map((e=>e.url))}),l=await Ate({fragementLength:rL("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:o=>(FL.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),o.url),r?mte(o,o.serviceIds,e,r,i,t,n):gte(o,e,t,n)),allFailedhandler:e=>{throw i.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},d),e[0]},promisesCollector:c});return i.recordJoinChannelService({endTs:Date.now(),status:"success"},d),l};let u,h,p;try{var _=await Ite([d(),l()]);u=_.gatewayInfo,h=_.proxyInfo,p=_.url}catch(e){throw e[0]}if(c.length&&c.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),!u||!h)throw new hk(JN.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(e.apUrl=p,"disabled"!==e.cloudProxyServer&&Array.isArray(o)&&p){const t=/^https?:\/\/(.+?)(\/.*)?$/.exec(p)[1];Vi(o).call(o,t)&&(e.proxyServer=t,FL.setProxyServer(t),uk.setProxyServer(t))}return a={gatewayInfo:u,proxyInfo:await eee(h,u.uid)},a}async function xte(e,t,n){const i=rL("UAP_AP").slice(0,rL("AJAX_REQUEST_CONCURRENT")).map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1?action=uap"):"https://".concat(t,"/api/v1?action=uap"))),r=i.map((i=>function(e,t,n,i){const r={command:"convergeAllocateEdge",sid:t.sid,appId:t.appId,token:t.token,ts:Date.now(),version:JP,cname:t.cname,uid:t.uid.toString(),requestId:Ete,seq:Ete};Ete+=1;const o={service_name:"tele_channel",json_body:JSON.stringify(r)};return gP((async()=>{const t=await tte(e,{data:o,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==t.code){const e=new hk(JN.UNEXPECTED_RESPONSE,"cross channel ap error, code"+t.code,{retry:!0});throw FL.error(e.toString()),e}const i=JSON.parse(t.json_body);if(200!==i.code){const e=new hk(JN.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(i.code,", reason: ").concat(i.reason));throw FL.error(e.toString()),e}if(!i.servers||0===i.servers.length){const e=new hk(JN.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw FL.error(e.toString()),e}return{vid:i.vid,workerToken:i.workerToken,addressList:(rL("CHANNEL_MEDIA_RELAY_SERVERS")||i.servers).map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(rL("WORKER_DOMAIN"),":").concat(e.wss)))}}),void 0,(e=>!!(e.code!==JN.OPERATION_ABORTED&&e.code!==JN.UNEXPECTED_RESPONSE||e.data&&e.data.retry)),i)}(i,e,t,n)));try{const e=await Ite(r);return r.forEach((e=>e.cancel())),e}catch(e){throw e[0]}}async function Fte(e,t,n){let i=null;const r=[],o=async o=>{const s=rL(o?"WEBCS_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN").map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2")));return o&&(await $D(1e3),null!==i)?i:await Ate({fragementLength:rL("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:i=>(FL.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(o?"backup":""," choose_server:"),i),function(e,t,n,i){const r=Hb(bte(t,[hK.CHOOSE_SERVER]),1)[0];let o=LD.networkState;return gP((async()=>{o&&LD.networkState===AD.OFFLINE&&LD.onlineWaiter&&await dp.race([LD.onlineWaiter,$D(i&&i.maxRetryTimeout||mP.maxRetryTimeout)]),o=LD.networkState;const t=await tte(e,{data:r,cancelToken:n,headers:{"Content-Type":"multipart/form-data;"}},!0);return Rte(t,e)}),(()=>!1),(e=>e.code!==JN.OPERATION_ABORTED&&(e.code===JN.UPDATE_TICKET_FAILED?e.data.retry:(FL.warning("[".concat(t.clientId,"] update ticket network error, retry"),e),!0))),i)}(i,e,t,n)),allFailedhandler:e=>{throw e[0]},promisesCollector:r})};try{return i=await Ite([o(!1),o(!0)]),r.length&&r.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),i}catch(e){throw e[0]}}function Bte(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function jte(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Bte(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Bte(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class Gte extends hD{get isSuccess(){return!!this.configs}constructor(e,t){super(),GA(this,"configs",void 0),GA(this,"store",void 0),GA(this,"joinInfo",void 0),GA(this,"cancelToken",void 0),GA(this,"retryConfig",{timeout:3e3,timeoutFactor:1.5,maxRetryCount:1,maxRetryTimeout:1e4}),GA(this,"interval",void 0),GA(this,"mutex",void 0),GA(this,"mutableParamsRead",!1),GA(this,"configCache",{}),GA(this,"limit_bitrate",void 0),this.mutex=new _P("config-distribute",e),this.store=t}startGetConfigDistribute(e,t){this.joinInfo=e,this.cancelToken=t,this.interval&&this.stopGetConfigDistribute(),rL("ENABLE_CONFIG_DISTRIBUTE")&&(this.updateConfigDistribute(),this.interval=window.setInterval((()=>{this.updateConfigDistribute()}),rL("CONFIG_DISTRIBUTE_INTERVAL")))}stopGetConfigDistribute(){this.interval&&clearInterval(this.interval),this.interval=void 0,this.joinInfo=void 0,this.cancelToken=void 0,this.configs=void 0,this.limit_bitrate=void 0}async awaitConfigDistributeComplete(){if(!this.mutex.isLocked)return;(await this.mutex.lock())()}async updateConfigDistribute(){if(!this.mutableParamsRead){this.mutableParamsRead=!0;uk.reportApiInvoke(null,{options:void 0,name:ED.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:mD.TRACER}).onSuccess(JSON.stringify(sL))}if(!this.joinInfo||!this.cancelToken||!this.retryConfig)return void FL.debug("[config-distribute] get config distribute interrupted have no joininfo");let e;const t=await this.mutex.lock();try{e=await Mte(this.joinInfo,this.cancelToken,this.retryConfig),FL.debug("[config-distribute] get config distribute",JSON.stringify(e));const n=function(e){var t;const n=n_(t=Object.keys(e).filter((e=>/^webrtc_ng_global_parameter/.test(e)))).call(t);for(let t=0;t<n.length;t++)for(let i=n.length-1;i>t;i--){const t=n[i],r=e[t].value;if("number"==typeof r.__priority){const o=r.__priority,s=n[i-1],a=e[s].value;if("number"==typeof a.__priority){if(!(o>a.__priority))continue;{const e=t;n[i]=n[i-1],n[i-1]=e}}else{const e=t;n[i]=n[i-1],n[i-1]=e}}}const i=Date.now(),r={};return n.forEach((t=>{const n=e[t].value.__expires;n&&n<=i||(r[t]=e[t])})),r}(e);this.cacheGlobalParameterConfig(n),this.store.hasStartJoinChannel||(this.store.isABTestSuccess=!0),this.configs=n}catch(e){const t=new hk(JN.NETWORK_RESPONSE_ERROR,e);FL.warning("[config-distribute] ".concat(t.toString()))}finally{t()}}getBitrateLimit(){return this.limit_bitrate||void 0}handleBitrateLimit(e){$F(e)&&(this.limit_bitrate?this.limit_bitrate&&this.limit_bitrate.id!==e.id&&this.emit(QF.UPDATE_BITRATE_LIMIT,e):this.emit(QF.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.limit_bitrate&&jte({},this.limit_bitrate.low_stream_uplink)}handleABTestConfigDistribute(e){try{const t={},n=Object.keys(e),i=[];n.forEach((n=>{const r=e[n].value;t[n]=r;const o=r.__id;if(o&&this.configCache[n]&&this.configCache[n].__id===o)return;const s=r.__type,a=e[n].value,c=e[n].tag;let d=0;s?s===oL.REALTIME&&(d=1):Object.keys(a).some((e=>Object.prototype.hasOwnProperty.call(tL,e)||!$x()&&Object.prototype.hasOwnProperty.call(QP,e)?(d=1,!0):void 0)),i.push({tag:c,isApplied:d,feature:n,params:JSON.stringify(r)})})),i.forEach((e=>{let t=e.tag,n=e.feature,i=e.params,r=e.isApplied;this.store.sessionId&&uk.abTest(this.store.sessionId,{intSucc:1,isApplied:r,tag:t,feature:n,params:i,cid:this.store.cid,uid:this.store.intUid})})),this.configCache=t}catch(e){FL.debug("handleABTestConfigDistribute error",e)}}cacheGlobalParameterConfig(e){const t=function(e){const t={};return Object.keys(e).forEach((n=>{const i=e[n].value,r=i.__expires,o=i.__type;Object.keys(i).forEach((e=>{"__id"===e||"__type"===e||"__priority"===e||"__expires"===e||Object.prototype.hasOwnProperty.call(t,e)||(t[e]=jte(jte({value:i[e]},r&&{expires:r}),o&&{type:o}))}))})),t}(e);try{var n;const i=null===(n=t.LIMIT_BITRATE)||void 0===n?void 0:n.value;if(delete t.LIMIT_BITRATE,i&&$F(i)&&this.handleBitrateLimit(i),this.limit_bitrate=i,this.handleGlobalParameterConfig(t),this.handleABTestConfigDistribute(e),function(e){try{const t=Date.now();Object.keys(e).forEach((n=>{const i=e[n],r=i.value,o=i.type,s=i.expires;s&&s<=t||((o===oL.REALTIME||Object.prototype.hasOwnProperty.call(tL,n))&&(sL[n]=r,nL[n]=r,FL.debug("Update realtime parameters from config distribute",n,r)),o||$x()||!Object.prototype.hasOwnProperty.call(QP,n)||(sL[n]=r,nL[n]=r,FL.debug("Update gateway parameters from config distribute",n,r)))}))}catch(t){FL.error("Error update config immediately: ".concat(e),t.message)}}(t),function(e){try{var t;if(!rL("ENABLE_CONFIG_RESTORE"))return!1;const n=tk(e),i=window.localStorage.getItem(ZL);if(!i)return!1;const r=JSON.parse(i),o=rL("BLOCKED_CONFIG_MAX_TIME");return Date.now()-r.timestamp>o?(dk(),!1):Vi(t=r.configHashes).call(t,n)}catch(e){return FL.debug("[error] ".concat(JL," error checking blocked config:"),e),!1}}(t))return FL.debug("[warning] [config-distribute] blocked config detected and skipped"),void uk.reportAlarm(this.store.sessionId||null,{type:WL.CONFIG_DISTRIBUTE,status:GL.RECOVER,message:"Blocked config detected and skipped"});!function(e){try{const t=tk(e),n=nk();if(n.currentConfigHash&&n.currentConfigHash===t)return ik({currentConfigHash:t,configVerified:!0}),sk(),dk(),void FL.debug("".concat(JL," config verified as safe, skip further checks"));ik({currentConfigHash:t,configVerified:!1}),sk(),dk()}catch(e){FL.debug("[error] ".concat(JL," error on config applied:"),e)}}(t);const r=JSON.stringify(t),o=window.btoa(r);window.localStorage.setItem("websdk_ng_global_parameter",o),FL.debug("Caching global parameters ".concat(r))}catch(e){FL.error("Error caching global parameters:",e.message)}}handleGlobalParameterConfig(e){try{const t=Date.now();Object.keys(e).forEach((n=>{switch(n){case"CLIENT_ROLE_OPTIONS":if(Object.prototype.hasOwnProperty.call(nL,n)){const i=e[n],r=i.value,o=i.expires;if(o&&o<=t)return;dP(nL[n],r)||(sL[n]=r,nL[n]=r,this.emit(QF.UPDATE_CLIENT_ROLE_OPTIONS,r),FL.debug("Updating client role options: ".concat(JSON.stringify(r))))}break;case"REMOTE_VIDEO_STREAM_TYPE":if(Object.prototype.hasOwnProperty.call(nL,n)){var i;const r=e[n],o=r.value,s=r.expires;if(s&&s<=t)return;"number"==typeof o&&Vi(i=[0,1,4,5,6,7,8,9]).call(i,o)&&(sL[n]={value:o},nL[n]=o,this.emit(QF.UPDATE_REMOTE_VIDEO_STREAM_TYPE,o),FL.debug("Updating client remote stream type: ".concat(JSON.stringify(o))))}break;case"ENABLE_FORCE_HLS":if(Object.prototype.hasOwnProperty.call(nL,n)){const i=e[n],r=i.value,o=i.expires;if(o&&o<=t)return;dP(nL[n],r)||(sL[n]=r,nL[n]=r,this.emit(QF.FALLBACK_TO_HLS,r),FL.debug("Updating enable force hls: ".concat(JSON.stringify(r))))}break;case"VOS_CONFIGURE":if(Object.prototype.hasOwnProperty.call(nL,n)){const i=e[n],r=i.value,o=i.expires;if(o&&o<=t)return;dP(nL[n],r)||(sL[n]=r,nL[n]=r,this.emit(QF.UPDATE_VOS_CONFIGURE,r),FL.debug("Updating vos configure: ".concat(JSON.stringify(r))))}}}))}catch(e){FL.error("Error handling global parameter config:",e.message)}}}class Wte extends hD{constructor(){super(...arguments),GA(this,"resultStorage",new Map)}setLocalAudioStats(e,t,n){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",e,this.checkAudioInputLevel(n,t)),this.record("SEND_AUDIO_BITRATE_TOO_LOW",e,this.checkSendAudioBitrate(n,t))}setLocalVideoStats(e,t,n){this.record("SEND_VIDEO_BITRATE_TOO_LOW",e,this.checkSendVideoBitrate(n,t)),this.record("FRAMERATE_INPUT_TOO_LOW",e,this.checkFramerateInput(n,t)),this.record("FRAMERATE_SENT_TOO_LOW",e,this.checkFramerateSent(n)),!t.muted&&this.record("VIDEO_ENCODE_FAILED",e,this.checResolutionSent(n))}setRemoteAudioStats(e,t){const n=e.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",n,this.checkAudioOutputLevel(t))}setRemoteVideoStats(e,t){const n=e.getUserId();this.record("RECV_VIDEO_DECODE_FAILED",n,this.checkVideoDecode(t))}record(e,t,n){if(rL("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});const i=this.resultStorage.get(e);if(!i)return;i.result.push(n);const r="VIDEO_ENCODE_FAILED"===e?rL("ENCODE_EXCEPTION_TIMES"):5;if(i.result.length>=r){var o;const n=Vi(o=i.result).call(o,!0);i.isPrevNormal&&!n&&this.emit("exception",Kte[e],e,t),!i.isPrevNormal&&n&&this.emit("exception",Kte[e]+2e3,e+"_RECOVER",t),i.isPrevNormal=n,i.result=[]}}checkAudioOutputLevel(e){return!(e.receiveBitrate>0&&0===e.receiveLevel)}checkAudioInputLevel(e,t){return t instanceof zU&&!t.isActive||(!!t.muted||0!==e.sendVolumeLevel)}checkFramerateInput(e,t){let n=null;t._encoderConfig&&t._encoderConfig.frameRate&&(n=Z7(t._encoderConfig.frameRate));const i=e.captureFrameRate;return!n||!i||!(n>10&&i<5||n<10&&n>=5&&i<=1)}checkFramerateSent(e){return!(e.captureFrameRate&&e.sendFrameRate&&e.captureFrameRate>5&&e.sendFrameRate<=1)}checResolutionSent(e){var t;return!(!e.codecType||Vi(t=rL("ENCODE_EXCEPTION_VALIDATE_CODEC")).call(t,e.codecType.toLocaleLowerCase()))||(!e.captureFrameRate||0!==e.sendFrameRate||0!==e.sendResolutionWidth||0!==e.sendResolutionHeight)}checkSendVideoBitrate(e,t){return!!t.muted||0!==e.sendBitrate}checkSendAudioBitrate(e,t){return t instanceof zU&&!t.isActive||(!!t.muted||0!==e.sendBitrate)}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}const Kte={FRAMERATE_INPUT_TOO_LOW:1001,FRAMERATE_SENT_TOO_LOW:1002,SEND_VIDEO_BITRATE_TOO_LOW:1003,RECV_VIDEO_DECODE_FAILED:1005,AUDIO_INPUT_LEVEL_TOO_LOW:2001,AUDIO_OUTPUT_LEVEL_TOO_LOW:2002,SEND_AUDIO_BITRATE_TOO_LOW:2003,VIDEO_ENCODE_FAILED:2004};const Hte=new class{markSubscribeStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/subscribe-").concat(t))}markPublishStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/publish-").concat(t))}measureFromSubscribeStart(e,t){const n=performance.getEntriesByName("agora-web-sdk/".concat(e,"/subscribe-").concat(t));if(n.length>0){const e=n[n.length-1];return Math.round(performance.now()-e.startTime)}return 0}measureFromPublishStart(e,t){const n=performance.getEntriesByName("agora-web-sdk/".concat(e,"/publish-").concat(t));if(n.length>0){const e=n[n.length-1];return Math.round(performance.now()-e.startTime)}return 0}};function Yte(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Xte(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Yte(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Yte(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class Jte{constructor(e){GA(this,"store",void 0),GA(this,"onStatsException",void 0),GA(this,"onUploadPublishDuration",void 0),GA(this,"onStatsChanged",void 0),GA(this,"onVideoCodecChanged",void 0),GA(this,"localStats",new Map),GA(this,"remoteStats",new Map),GA(this,"updateStatsInterval",void 0),GA(this,"trafficStats",void 0),GA(this,"trafficStatsPeerList",[]),GA(this,"uplinkStats",void 0),GA(this,"exceptionMonitor",void 0),GA(this,"p2pChannel",void 0),GA(this,"scalabilityMode",xP.L1T1),GA(this,"updateStats",(()=>{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))})),this.store=e,this.exceptionMonitor=new Wte,this.exceptionMonitor.on("exception",((e,t,n)=>{this.onStatsException&&this.onStatsException(e,t,n)}))}startUpdateStats(){this.updateStatsInterval||(this.updateStatsInterval=window.setInterval(this.updateStats,1e3))}stopUpdateStats(){this.updateStatsInterval&&(window.clearInterval(this.updateStatsInterval),this.updateStatsInterval=void 0)}reset(){this.localStats=new Map,this.remoteStats=new Map,this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0}getLocalAudioTrackStats(){return this.localStats.get(sB.LocalAudioTrack)||Xte({},Zk)}getLocalVideoTrackStats(){return this.localStats.get(sB.LocalVideoTrack)||Xte({},qk)}getRemoteAudioTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const n=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return n&&(t.publishDuration=n.B_ppad+(Date.now()-this.trafficStats.timestamp)),t},n={};if(e){var i;const r=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.audioStats;r&&(n[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let i=Hb(e,2),r=i[0],o=i[1].audioStats;o&&(n[r]=t(r,o))}));return n}getRemoteNetworkQualityStats(e){const t={};if(e){var n;const i=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.networkStats;i&&(t[e]=i)}else Array.from(this.remoteStats.entries()).forEach((e=>{let n=Hb(e,2),i=n[0],r=n[1].networkStats;r&&(t[i]=r)}));return t}getNetworkQuality(){let e=0,t=0;return this.trafficStats&&(e=Q7(this.trafficStats.B_unq),t=Q7(this.trafficStats.B_dnq)),{uplinkNetworkQuality:e,downlinkNetworkQuality:t}}getRemoteVideoTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const n=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return n&&(t.publishDuration=n.B_ppvd+(Date.now()-this.trafficStats.timestamp)),t},n={};if(e){var i;const r=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.videoStats;r&&(n[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let i=Hb(e,2),r=i[0],o=i[1].videoStats;o&&(n[r]=t(r,o))}));return n}getRTCStats(){let e=0,t=0,n=0,i=0;const r=this.localStats.get(sB.LocalAudioTrack);r&&(e+=r.sendBytes,t+=r.sendBitrate);const o=this.localStats.get(sB.LocalVideoTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate);const s=this.localStats.get(sB.LocalVideoLowTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate),this.remoteStats.forEach((e=>{let t=e.audioStats,r=e.videoStats;t&&(n+=t.receiveBytes,i+=t.receiveBitrate),r&&(n+=r.receiveBytes,i+=r.receiveBitrate)}));let a=1;return this.trafficStats&&(a+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:a,SendBitrate:t,SendBytes:e,RecvBytes:n,RecvBitrate:i,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1e3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0}}addLocalStats(e){this.localStats.set(e,void 0)}removeLocalStats(e){e?this.localStats.delete(e):this.localStats.clear()}addRemoteStats(e){this.remoteStats.set(e,{})}removeRemoteStats(e){e?this.remoteStats.delete(e):this.remoteStats.clear()}addP2PChannel(e){this.p2pChannel=e}updateTrafficStats(e){e.peer_delay=e.peer_delay.filter((e=>void 0!==e.B_ppad||void 0!==e.B_ppvd));e.peer_delay.filter((e=>-1===this.trafficStatsPeerList.indexOf(e.peer_uid))).forEach((e=>{var t;const n=null===(t=this.p2pChannel)||void 0===t?void 0:t.getRemoteMedia(e.peer_uid),i=null!=n&&n.videoSSRC?Hte.measureFromSubscribeStart(this.store.clientId,n.videoSSRC):0,r=null!=n&&n.audioSSRC?Hte.measureFromSubscribeStart(this.store.clientId,n.audioSSRC):0;void 0!==e.B_ppad&&void 0!==e.B_ppvd&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(e.peer_uid,e.B_ppad,e.B_ppvd,i>r?i:r),this.trafficStatsPeerList.push(e.peer_uid))})),this.trafficStats=e}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&FL.debug("[".concat(this.store.clientId,"]: Period fir changes to ").concat(e.B_fir)),this.uplinkStats=e}static isRemoteVideoFreeze(e,t,n){if(!e)return!1;const i=!!n&&t.framesDecodeFreezeTime>n.framesDecodeFreezeTime,r=!n||t.framesDecodeCount>n.framesDecodeCount;return i||!r}static isRemoteAudioFreeze(e){return!!e&&e._isFreeze()}isLocalVideoFreeze(e){return!(!e.inputFrame||!e.sentFrame)&&(e.inputFrame.frameRate>5&&e.sentFrame.frameRate<3)}updateLocalStats(e){Array.from(this.localStats.entries()).forEach((t=>{let n=Hb(t,2),i=n[0],r=n[1];switch(i){case sB.LocalVideoTrack:case sB.LocalVideoLowTrack:{const t=r,n=Xte({},qk),a=e.getStats(),c=e.getLocalMedia(i);if(a){const i=a.videoSend.find((e=>e.ssrc===(null==c?void 0:c.ssrcs[0].ssrcId)));if(i){const r=e.getLocalVideoSize(),s=e.getEncoderConfig(sB.LocalVideoTrack);var o;if("H264"===i.codec||"H265"===i.codec||"VP8"===i.codec||"VP9"===i.codec||"AV1X"===i.codec||"AV1"===i.codec)if(n.codecType=i.codec,(null==t?void 0:t.codecType)!==i.codec)null===(o=this.onVideoCodecChanged)||void 0===o||o.call(this,i.codec.toLocaleLowerCase());n.sendBytes=i.bytes,n.sendBitrate=t?8*Math.max(0,n.sendBytes-t.sendBytes):0,i.inputFrame?(n.captureFrameRate=i.inputFrame.frameRate,n.captureResolutionHeight=i.inputFrame.height,n.captureResolutionWidth=i.inputFrame.width):r&&(n.captureResolutionWidth=r.width,n.captureResolutionHeight=r.height),i.sentFrame?(n.sendFrameRate=i.sentFrame.frameRate,n.sendResolutionHeight=i.sentFrame.height,n.sendResolutionWidth=i.sentFrame.width):r&&(n.sendResolutionWidth=r.width,n.sendResolutionHeight=r.height),i.avgEncodeMs&&(n.encodeDelay=i.avgEncodeMs),s&&s.bitrateMax?n.targetSendBitrate=1e3*s.bitrateMax:i.targetBitrate&&(n.targetSendBitrate=i.targetBitrate),n.sendPackets=i.packets,n.sendPacketsLost=i.packetsLost,n.sendJitterMs=i.jitterMs,n.sendRttMs=i.rttMs,n.totalDuration=t?t.totalDuration+1:1,n.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(i)&&(n.totalFreezeTime+=1),i.scalabilityMode&&this.scalabilityMode!==i.scalabilityMode&&(FL.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(i.scalabilityMode)),this.scalabilityMode=i.scalabilityMode)}this.trafficStats&&(n.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}var s;if(this.localStats.set(i,n),(null==t?void 0:t.sendResolutionWidth)!==n.sendResolutionWidth||(null==t?void 0:t.sendResolutionHeight)!==n.sendResolutionHeight)null===(s=this.onStatsChanged)||void 0===s||s.call(this,"resolution",{width:n.sendResolutionWidth,height:n.sendResolutionHeight});n&&c&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,c.track,n);break}case sB.LocalAudioTrack:{const t=r,n=Xte({},Zk),o=e.getStats(),s=e.getLocalMedia(i);if(o){const i=o.audioSend.find((e=>e.ssrc===(null==s?void 0:s.ssrcs[0].ssrcId)));if(i){if("opus"!==i.codec&&"aac"!==i.codec&&"PCMU"!==i.codec&&"PCMA"!==i.codec&&"G722"!==i.codec||(n.codecType=i.codec),i.inputLevel)n.sendVolumeLevel=Math.round(32767*i.inputLevel);else{const t=e.getLocalAudioVolume();t&&(n.sendVolumeLevel=Math.round(32767*t))}n.sendBytes=i.bytes,n.sendPackets=i.packets,n.sendPacketsLost=i.packetsLost,n.sendJitterMs=i.jitterMs,n.sendRttMs=i.rttMs,n.sendBitrate=t?8*Math.max(0,n.sendBytes-t.sendBytes):0}}this.trafficStats&&(n.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(sB.LocalAudioTrack,n),n&&s&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,s.track,n);break}}}))}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach((t=>{var n,i;let r=Hb(t,2),o=r[0],s=r[1],a=s.videoStats;const c=s.audioStats,d=a,l=s.videoPcStats,u=Xte({},Qk),h=Xte({},eM),p=Xte({},$k),_=e.getRemoteMedia(o),E=_.audioTrack,m=_.videoTrack,f=_.audioSSRC,g=_.videoSSRC;let S;S=this.store.useP2P?e.getStats(!0):e.getStats();const T=null===(n=S)||void 0===n?void 0:n.audioRecv.find((e=>e.ssrc===f)),R=null===(i=S)||void 0===i?void 0:i.videoRecv.find((e=>e.ssrc===g)),v=this.trafficStats&&this.trafficStats.peer_delay.find((e=>e.peer_uid===o));if(T&&("opus"!==T.codec&&"aac"!==T.codec&&"PCMU"!==T.codec&&"PCMA"!==T.codec&&"G722"!==T.codec||(u.codecType=T.codec),T.outputLevel?u.receiveLevel=Math.round(32767*T.outputLevel):E&&(u.receiveLevel=Math.round(32767*E.getVolumeLevel())),u.receiveBytes=T.bytes,u.receivePackets=T.packets,u.receivePacketsLost=T.packetsLost,u.receivePacketsDiscarded=T.packetsDiscarded,u.packetLossRate=u.receivePacketsLost/(u.receivePackets+u.receivePacketsLost),u.receiveBitrate=c?8*Math.max(0,u.receiveBytes-c.receiveBytes):0,u.totalDuration=c?c.totalDuration+1:1,u.totalFreezeTime=c?c.totalFreezeTime:0,u.freezeRate=u.totalFreezeTime/u.totalDuration,u.receiveDelay=T.jitterBufferMs,u.totalDuration>10&&Jte.isRemoteAudioFreeze(E)&&(u.totalFreezeTime+=1)),R){"H264"!==R.codec&&"H265"!==R.codec&&"VP8"!==R.codec&&"VP9"!==R.codec&&"AV1X"!==R.codec&&"AV1"!==R.codec||(h.codecType=R.codec),h.receiveBytes=R.bytes,h.receiveBitrate=d?8*Math.max(0,h.receiveBytes-d.receiveBytes):0,h.decodeFrameRate=R.decodeFrameRate<0?0:R.decodeFrameRate,h.renderFrameRate=R.decodeFrameRate<0?0:R.decodeFrameRate,R.outputFrame&&(h.renderFrameRate=R.outputFrame.frameRate),R.receivedFrame?(h.receiveFrameRate=R.receivedFrame.frameRate,h.receiveResolutionHeight=R.receivedFrame.height,h.receiveResolutionWidth=R.receivedFrame.width):m&&(h.receiveResolutionHeight=m._videoHeight||0,h.receiveResolutionWidth=m._videoWidth||0),void 0!==R.framesRateFirefox&&(h.receiveFrameRate=Math.round(R.framesRateFirefox)),h.receivePackets=R.packets,h.receivePacketsLost=R.packetsLost,h.packetLossRate=h.receivePacketsLost/(h.receivePackets+h.receivePacketsLost),h.receiveDelay=R.jitterBufferMs||0;const t=!!g&&e.getRemoteVideoIsReady(g),n=d?d.totalFreezeTime:0,i=d?d.totalDuration:0;var y;if(h.totalDuration=d?d.totalDuration+1:1,1===rL("REMOTE_VIDEO_FREEZE_TIME_VERSION"))m&&t&&m._player&&(h.totalFreezeTime=m._player.totalFreezeTime/1e3);else h.totalFreezeTime=null!==(y=R.totalFreezesDuration)&&void 0!==y?y:n||0,void 0===R.totalFreezesDuration&&m&&t&&Jte.isRemoteVideoFreeze(m,R,l)&&(h.totalFreezeTime+=1);h.freezeRate=Math.max(0,Math.min((h.totalFreezeTime-n)/(h.totalDuration-i),1))}v&&(u.end2EndDelay=v.B_ad,h.end2EndDelay=v.B_vd,u.transportDelay=v.B_ed,h.transportDelay=v.B_ed,u.currentPacketLossRate=v.B_ealr4/100,h.currentPacketLossRate=v.B_evlr4/100,p.uplinkNetworkQuality=v.B_punq?v.B_punq:0,p.downlinkNetworkQuality=v.B_pdnq?v.B_pdnq:0),this.remoteStats.set(o,{audioStats:u,videoStats:h,videoPcStats:R,networkStats:p}),E&&this.exceptionMonitor.setRemoteAudioStats(E,u),m&&this.exceptionMonitor.setRemoteVideoStats(m,h)}))}}class zte{constructor(){GA(this,"destChannelMediaInfos",new Map),GA(this,"srcChannelMediaInfo",void 0)}setSrcChannelInfo(e){FF(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){FF(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){OF(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function Zte(e){if(!(e instanceof zte)){return new hk(JN.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw()}const t=e.getSrcChannelMediaInfo(),n=e.getDestChannelMediaInfo();if(!t){return new hk(JN.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw()}if(0===n.size){return new hk(JN.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw()}}class qte{get hasVideo(){return this._video_enabled_&&!this._video_muted_&&this._video_added_}get hasAudio(){return this._audio_enabled_&&!this._audio_muted_&&this._audio_added_}get audioTrack(){if(this.hasAudio||this._audio_pre_subscribed)return this._audioTrack}get videoTrack(){if(this.hasVideo||this._video_pre_subscribed)return this._videoTrack}get dataChannels(){return this._dataChannels}constructor(e,t){GA(this,"uid",void 0),GA(this,"_uintid",void 0),GA(this,"_trust_in_room_",!0),GA(this,"_trust_audio_enabled_state_",!0),GA(this,"_trust_video_enabled_state_",!0),GA(this,"_trust_audio_mute_state_",!0),GA(this,"_trust_video_mute_state_",!0),GA(this,"_audio_muted_",!1),GA(this,"_video_muted_",!1),GA(this,"_audio_enabled_",!0),GA(this,"_video_enabled_",!0),GA(this,"_audio_added_",!1),GA(this,"_video_added_",!1),GA(this,"_is_pre_created",!1),GA(this,"_video_pre_subscribed",!1),GA(this,"_audio_pre_subscribed",!1),GA(this,"_trust_video_stream_added_state_",!0),GA(this,"_trust_audio_stream_added_state_",!0),GA(this,"_audioTrack",void 0),GA(this,"_videoTrack",void 0),GA(this,"_dataChannels",[]),GA(this,"_audioSSRC",void 0),GA(this,"_videoSSRC",void 0),GA(this,"_audioOrtc",void 0),GA(this,"_videoOrtc",void 0),GA(this,"_cname",void 0),GA(this,"_rtxSsrcId",void 0),GA(this,"_videoMid",void 0),GA(this,"_audioMid",void 0),this.uid=e,this._uintid=t}}function Qte(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function $te(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Qte(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Qte(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const ene=e=>"v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1 2\na=msid-semantic: WMS\na=ice-lite".concat(e?"\na=extmap-allow-mixed":"","\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP4 127.0.0.1\na=mid:2\n"),tne="9",nne=2e4,ine=4e4;let rne=class{get localCapabilities(){return GD(this._localCapabilities)}get rtpCapabilities(){return GD(this._rtpCapabilities)}get candidates(){return GD(this._candidates)}get iceParameters(){return GD(this._iceParameters)}get dtlsParameters(){return GD(this._dtlsParameters)}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];GA(this,"sessionDesc",void 0),GA(this,"_localCapabilities",void 0),GA(this,"_rtpCapabilities",void 0),GA(this,"_candidates",void 0),GA(this,"_originCandidates",void 0),GA(this,"_iceParameters",void 0),GA(this,"_isUseExtmapAllowMixed",void 0),GA(this,"_isUseLocalCodecs",void 0),GA(this,"_isUseDataChannel",void 0),GA(this,"_dtlsParameters",void 0),GA(this,"setup",void 0),GA(this,"currentMidIndex",void 0),GA(this,"cname",void 0),GA(this,"useLocalCodecsMids",[]),GA(this,"preloadSsrcs",[]),GA(this,"firefoxSsrcMidMap",new Map),this._isUseExtmapAllowMixed=t,this._isUseLocalCodecs=n,this._isUseDataChannel=i;const r=e=GD(e),o=r.iceParameters,s=r.dtlsParameters,a=r.candidates,c=r.rtpCapabilities,d=r.setup,l=r.localCapabilities,u=r.cname;this._rtpCapabilities=c,this._candidates=a,this._originCandidates=GD(a),this._iceParameters=o,this._dtlsParameters=s,this._localCapabilities=l,this.setup=d,this.cname=u;var h=Hb(this.updateRemoteRTPCapabilities(c),1);this.sessionDesc=h[0],this.currentMidIndex=this.sessionDesc.mediaDescriptions.length-1}checkPreloadSsrcs(e){return e.length===this.preloadSsrcs.length&&e.every((e=>{var t;return Vi(t=this.preloadSsrcs).call(t,e)}))}preloadRemoteMedia(e){let t=0;const n=[],i=[];for(;e>0;){const r=[$te({ssrcId:ine+t},rL("USE_SUB_RTX")?{rtx:ine+t+1}:{})],o="".concat(ine+t,"_").concat(nne+t),s=Ree(r,this.cname,rL("SYNC_GROUP")?o:void 0),a=s.ssrcs,c=s.ssrcGroups,d=this.preCreateOrRecycleSendMedia("video",a,c,void 0),l=[{ssrcId:nne+t}],u="".concat(ine+t,"_").concat(nne+t),h=Ree(l,this.cname,rL("SYNC_GROUP")?u:void 0),p=h.ssrcs,_=h.ssrcGroups,E=this.preCreateOrRecycleSendMedia("audio",p,_,void 0);e--,t+=2,n.push(d,E),i.push(a[0].ssrcId,p[0].ssrcId)}return this.useLocalCodecsMids.push(...n),this.preloadSsrcs=i,{mids:n,preSSRCs:i,isAvailable:!0}}preCreateOrRecycleSendMedia(e,t,n,i){const r=this.rtpCapabilities.send.videoCodecs,o=this._isUseLocalCodecs||0===r.length?this.localCapabilities.recv:this.rtpCapabilities.send;FL.debug("create or recycle send media without remote rtp capabilities, ssrcs ",t[0].ssrcId);const s=e===nB.VIDEO?o.videoCodecs:o.audioCodecs,a=e===nB.VIDEO?o.videoExtensions:o.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:tne,protos:["UDP","TLS","RTP","SAVPF"],fmts:s.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:a,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:n,rtcpFeedbackWildcards:[],payloads:s,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};return d=this.mungSendMediaDesc(d,i),this.sessionDesc.mediaDescriptions.push(d),this.updateBundleMids(),c}toString(){return mL(this.sessionDesc)}send(e,t,n,i){const r=Ree(t,this.cname,rL("SYNC_GROUP")?n:void 0),o=r.ssrcs,s=r.ssrcGroups,a=this.findPreloadMediaDesc(o);if(a){if(SN()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,a.attributes.mid),i&&(i.twcc||i.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(a);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(a,i),{mid:a.attributes.mid,needExchangeSDP:!0}}return{mid:a.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,o);let n;return-1===t||1===t&&(EN()||function(){const e=dN();return!(e.name!==oN.CHROME||!e.osVersion)&&Number(e.version)<=90}()||RN(143)||bN(143)||rL("RESERVE_MID_1_MLINE")||rL("ENABLE_ENCODED_TRANSFORM")&&_N())||0===t&&!function(e){const t=dN();return!(t.name!==oN.FIREFOX||!t.osVersion)&&Number(t.version)===e}(138)&&rL("USE_SUB_RTX")||DN()?(n=this.createOrRecycleSendMedia(e,o,s,"sendonly",i),this.updateBundleMids()):(n=GD(this.sessionDesc.mediaDescriptions[t]),n.attributes.direction="sendonly",n.attributes.ssrcs=o,n.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(n,i)),SN()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,n.attributes.mid),{mid:n.attributes.mid,needExchangeSDP:!0}}}sendDataChannel(){const e=this.createOrRecycleDataChannel(),t=e.mediaDesc,n=e.needExchangeSDP;return this.updateBundleMids(),{mid:t.attributes.mid,needExchangeSDP:n}}batchSend(e){const t=e.map((e=>{let t=e.kind,n=e.ssrcMsg,i=e.mslabel;return this.send(t,n,i)})),n=[];let i=!1;return t.forEach((e=>{let t=e.mid;e.needExchangeSDP&&(i=!0),n.push(t)})),{mids:n,needExchangeSDP:i}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach((e=>{"0"===e.attributes.mid||SN()||DN()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction="inactive",e.media.port="0")})),this.updateBundleMids()}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Vi(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="inactive"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Vi(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="recvonly"}))}receive(e,t,n,i){e.forEach(((e,r)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,n,i[r])})),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach((e=>{e.media.port="0",e.attributes.direction="inactive"})),this.updateBundleMids()}updateRemoteRTPCapabilities(e){const t=this.sessionDesc||EL((n=this._isUseExtmapAllowMixed,this._isUseDataChannel?ene(n):"v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=ice-lite".concat(n?"\na=extmap-allow-mixed":"","\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n")));var n;this._rtpCapabilities=e;let i=!1;const r=this.rtpCapabilities.send,o=this.localCapabilities.send,s=this.localCapabilities.recv,a=s.videoCodecs,c=s.audioCodecs,d=s.videoExtensions,l=s.audioExtensions;for(const e of t.mediaDescriptions){var u;if("sendonly"!==e.attributes.direction||"string"!=typeof e.attributes.mid||!Vi(u=this.useLocalCodecsMids).call(u,e.attributes.mid)){if(i=!0,e.attributes.iceUfrag=this._iceParameters.iceUfrag,e.attributes.icePwd=this._iceParameters.icePwd,e.attributes.fingerprints=this._dtlsParameters.fingerprints,e.attributes.candidates=this._candidates,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType)if(this._isUseLocalCodecs&&"sendonly"===e.attributes.direction){var h;e.media.fmts=a.map((e=>e.payloadType.toString(10))),e.attributes.payloads=a,e.attributes.extmaps=d;const t=e.attributes.mid;"string"!=typeof t||Vi(h=this.useLocalCodecsMids).call(h,t)||this.useLocalCodecsMids.push(t)}else if(0===r.videoCodecs.length){const t=o.videoCodecs.filter((e=>{var t,n;return null===(t=e.rtpMap)||void 0===t?void 0:Vi(n=t.encodingName.toLowerCase()).call(n,"vp8")}));0===t.length&&t.push(o.videoCodecs[0]),e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=r.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=r.videoCodecs,e.attributes.extmaps=r.videoExtensions;if("audio"===e.media.mediaType)if(this._isUseLocalCodecs&&"sendonly"===e.attributes.direction){var p;e.media.fmts=c.map((e=>e.payloadType.toString(10))),e.attributes.payloads=c,e.attributes.extmaps=l;const t=e.attributes.mid;"string"!=typeof t||Vi(p=this.useLocalCodecsMids).call(p,t)||this.useLocalCodecsMids.push(t)}else if(0===r.audioCodecs.length){const t=o.audioCodecs.filter((e=>{var t,n;return null===(t=e.rtpMap)||void 0===t?void 0:Vi(n=t.encodingName.toLowerCase()).call(n,"opus")}))||[o.audioCodecs[0]];e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=r.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=r.audioCodecs,e.attributes.extmaps=r.audioExtensions,Lee(e)}}return this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1,[this.sessionDesc,i]}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),n=[];if(t.forEach((e=>{n.push($te($te({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case iB.TCP_RELAY:this._candidates=n;break;case iB.UDP_TCP_RELAY:case iB.RELAY:this._candidates=[...t,...n];break;default:this._candidates=t}for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){let t=!1;return e=GD(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((n=>{n.attributes.iceUfrag===e.iceUfrag&&n.attributes.icePwd===e.icePwd||(t=!0),n.attributes.iceUfrag=e.iceUfrag,n.attributes.icePwd=e.icePwd})),t}predictReceivingMids(e){const t=[];for(let n=0;n<e;n++)t.push((this.currentMidIndex+n+1).toString(10));return t}findAvailableMediaIndex(e,t){return this.sessionDesc.mediaDescriptions.findIndex((n=>{const i=n.media.mediaType===e&&"0"!==n.media.port&&("sendonly"===n.attributes.direction||"sendrecv"===n.attributes.direction)&&0===n.attributes.ssrcs.length;if(SN()){if(i){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||"0"!==n.attributes.mid&&"1"!==n.attributes.mid)||!(!e||e!==n.attributes.mid)}return!1}return i}))}createOrRecycleDataChannel(){for(const e of this.sessionDesc.mediaDescriptions)if("application"===e.media.mediaType)return{mediaDesc:e,needExchangeSDP:!1};this.currentMidIndex+=1;const e="".concat(this.currentMidIndex),t={media:{mediaType:"application",port:tne,protos:["UDP","DTLS","SCTP"],fmts:["webrtc-datachannel"]},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:[],fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[],rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,mid:"".concat(e),sctpPort:"5000"}};return this.sessionDesc.mediaDescriptions.push(t),{mediaDesc:t,needExchangeSDP:!0}}createOrRecycleRecvMedia(e,t,n,i,r,o){const s=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=kee(s,a,this.localCapabilities.send,s===nB.VIDEO?i:r),d=s===nB.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let u={media:{mediaType:s,port:tne,protos:["UDP","TLS","RTP","SAVPF"],fmts:c.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(l)}};u=this.mungRecvMediaDsec(u,e,o);const h=this.findFirstClosedMedia(s);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=u}else this.sessionDesc.mediaDescriptions.push(u);return u}updateRemoteDtlsParameters(e){const t=new Set(this._dtlsParameters.fingerprints.map((e=>e.fingerprint))),n=new Set(e.map((e=>e.fingerprint)));let i=!1;t.size!==n.size&&(i=!0);for(const e of t)n.has(e)||(i=!0);return i}updateRemoteCodec(e,t,n){const i=[...new Set(this._rtpCapabilities.recv.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Vi(t=Object.keys(cL)).call(t,e)})))],r=new Set(t);if(i.every((e=>r.has(e))))return FL.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(t)),!1;const o=this._rtpCapabilities.recv.videoCodecs.filter((e=>t.some((t=>{var n;return Vi(n=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(n,t)}))));if(0===o.length)return FL.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(i," codecs: ").concat(t)),!1;const s=[...new Set(o.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")))];let a;if(FL.debug("updateRemoteCodec, from ".concat(i," to ").concat(s)),0===e.length)a=this.sessionDesc.mediaDescriptions.filter((e=>"video"===e.media.mediaType&&"recvonly"===e.attributes.direction));else if(a=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&"video"===t.media.mediaType&&Vi(e).call(e,t.attributes.mid)&&"recvonly"===t.attributes.direction)),a.length!==e.length)return FL.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;if(rL("USE_PUB_RTX")||rL("USE_SUB_RTX")){const e=Mee(o,this.rtpCapabilities.recv.videoCodecs);o.push(...e)}this._rtpCapabilities.recv.videoCodecs=o;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=kee(nB.VIDEO,d,c,n);return a.forEach((e=>{const t=l.map((e=>e.payloadType.toString(10)));FL.debug("updateRemoteCodec mid: ".concat(e.attributes.mid,", from"),e.attributes.payloads,"to",l),e.attributes.payloads=l,e.media.fmts=t})),FL.debug("updateRemoteCodec success, mids: ".concat(e,", codecs: ").concat(t,", remote recv: ").concat(this._rtpCapabilities.recv.videoCodecs.length,", remote send: ").concat(this._rtpCapabilities.send.videoCodecs.length)),!0}createOrRecycleSendMedia(e,t,n,i,r){const o=this.rtpCapabilities.send.videoCodecs,s=this._isUseLocalCodecs||0===o.length?this.localCapabilities.recv:this.rtpCapabilities.send,a=e===nB.VIDEO?s.videoCodecs:s.audioCodecs,c=e===nB.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const d="".concat(this.currentMidIndex);let l={media:{mediaType:e,port:tne,protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:n,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};l=this.mungSendMediaDesc(l,r);const u=this.findFirstClosedMedia(e);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>"0"!==e.media.port)).map((e=>e.attributes.mid))}mungRecvMediaDsec(e,t,n){const i=GD(e);return yee(i),vee(i,t),bee(i,t),Cee(i),Iee(i,n,this.localCapabilities.send),i}mungSendMediaDesc(e,t){const n=GD(e);return n.attributes&&n.attributes.payloads&&Array.isArray(n.attributes.payloads)&&n.attributes.payloads.length>0&&n.attributes.payloads.forEach((e=>{e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&rL("ENABLE_DOWN_SPS_PPS")&&(e.fmtp&&e.fmtp.parameters||(e.fmtp={parameters:{}}),e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")})),Iee(n,t,this.localCapabilities.recv),Lee(n),n}updateRecvMedia(e,t){const n=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==n){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],t);this.sessionDesc.mediaDescriptions[n]=e}}bumpMid(e){this.currentMidIndex+=e}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>SN()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var n;return(null===(n=t.attributes)||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId)===e[0].ssrcId}))}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===t?void 0:t.attributes.ssrcs}};function one(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function sne(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?one(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):one(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var ane=function(e){return e[e.DOWN=0]="DOWN",e[e.UP=1]="UP",e}(ane||{});const cne=new Map;function dne(e,t,n,i){let r=e.scale;if(0===r&&i===ane.UP||r>=t.length-1&&i===ane.DOWN)return e;let o=sne(sne({},e),{},{scale:i===ane.DOWN?++r:--r});switch(n){case"maintain-framerate":o=sne(sne({},o),t[r].motion);break;case"maintain-resolution":o=sne(sne({},o),t[r].detail);break;case"balanced":o=sne(sne({},o),t[r].balanced)}return o}function lne(e,t){if(t){const n={overUse:0,underUse:0,adaptationList:une(t)};cne.set(e,n)}else cne.delete(e)}function une(e){const t=sne({},e),n=t.bitrateMax,i=t.frameRate,r=t.scaleResolutionDownBy,o=t.bitrateMin,s=$P.MIN_FRAME_RATE,a=$P.MAX_THRESHOLD_FRAMERATE,c=$P.MAX_SCALE,d=$P.BITRATE_MIN_THRESHOLD,l=$P.BITRATE_MAX_THRESHOLD,u=$P.BWE_SCALE_UP_THRESHOLD,h=$P.BWE_SCALE_DOWN_THRESHOLD,p=$P.PERF_SCALE_DOWN_THRESHOLD,_=$P.PERF_SCALE_UP_THRESHOLD,E=$P.BALANCE_BITRATE_FACTOR,m=$P.BALANCE_FRAMERATE_FACTOR,f=$P.BALANCE_RESOLUTION_FACTOR,g=$P.MOTION_RESOLUTION_FACTOR,S=$P.MOTION_BITRATE_FACTOR,T=$P.DETAIL_FRAMERATE_FACTOR,R=$P.DETAIL_BITRATE_FACTOR,v=Math.min(t.frameRate,a),y=[{scale:0,threshold:{bwe_down:Math.round(Math.pow(h,1)*n),bwe_up:n,fps_down:Math.round(Math.pow(p,1)*v),fps_up:i},balanced:{scaleResolutionDownBy:1,frameRate:i,bitrateMax:n,bitrateMin:o},motion:{scaleResolutionDownBy:1,frameRate:i,bitrateMax:n,bitrateMin:o},detail:{scaleResolutionDownBy:1,frameRate:i,bitrateMax:n,bitrateMin:o}}];for(let e=1;e<=c;e++){const t={bwe_up:Math.round(Math.pow(u,e)*n),bwe_down:Math.round(Math.pow(h,e+1)*n),fps_up:Math.round(Math.pow(_,e)*v),fps_down:Math.round(Math.pow(p,e+1)*v)},a={scaleResolutionDownBy:r/Math.pow(f,e),frameRate:Math.max(Math.round(Math.pow(m,e)*i),s),bitrateMax:Math.max(Math.round(Math.pow(E,e)*n),l),bitrateMin:Math.max(Math.round(Math.pow(E,e)*o),d)},c={scaleResolutionDownBy:r/Math.pow(g,e),frameRate:i,bitrateMax:Math.max(Math.round(Math.pow(S,e)*n),l),bitrateMin:Math.max(Math.round(Math.pow(S,e)*o),d)},b={scaleResolutionDownBy:1,frameRate:Math.max(Math.round(Math.pow(T,e)*i),s),bitrateMax:Math.max(Math.round(Math.pow(R,e)*n),l),bitrateMin:Math.max(Math.round(Math.pow(R,e)*o),d)};y.push({scale:e,threshold:t,balanced:a,motion:c,detail:b})}return y}function hne(e,t,n,i,r,o){const s=cne.get(e)||{overUse:0,underUse:0,adaptationList:une(r)},a=s.adaptationList;cne.set(e,s);const c=$P.OVERUSE_TIMES_THRESHOLD,d=$P.UNDERUSE_TIMES_THRESHOLD,l=i.scale;let u,h;return"number"==typeof t&&t>0&&function(e,t,n,i){if(t>=n.length)return!1;let r=n[t].threshold.fps_down;return rL("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===i&&(r=n[0].threshold.fps_down),e<r}(t,l,a,o)&&(s.overUse++,h=VP.CPU,s.overUse>c)||"number"==typeof n&&n>0&&function(e,t,n){return!(t>=n.length)&&e<n[t].threshold.bwe_down}(n,l,a)&&(s.overUse++,h=VP.BANDWIDTH,s.overUse>c)?(s.overUse=0,s.underUse=0,u=dne(i,a,o,ane.DOWN),[u,h]):("number"==typeof t&&t>0&&"number"==typeof n&&n>0&&function(e,t,n,i){if(0===t)return;let r=n[t].threshold.fps_up;return rL("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===i&&(r=n[1].threshold.fps_up),e>r}(t,l,a,o)&&function(e,t,n){if(0===t)return;return e>n[t].threshold.bwe_up}(n,l,a)&&(s.underUse++,s.underUse>d&&(s.overUse=0,s.underUse=0,u=dne(i,a,o,ane.UP),0===u.scale&&(h=VP.NONE))),[u,h])}function pne(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function _ne(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?pne(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):pne(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function Ene(e){var t;return!!rL("ENABLE_AG_ADAPTATION")&&(!!(e instanceof jV||Vi(t=e._hints).call(t,jk.CUSTOM_TRACK))&&(!!rL("FORCE_SUPPORT_AG_ADAPTATION")||!!(AN(14,0,!1)&&wN(17,4,!0)||IN(14)&&ON(17,4,!0))))}const mne=new Map;function fne(e,t,n,i,r,o){if(gne(e,n),r(t),"balanced"!==i&&"maintain-framerate"!==i&&"maintain-resolution"!==i)return;let s=-1;lne(e,t);const a=window.setInterval((()=>{const a=mne.get(e);if(!rL("ENABLE_AG_ADAPTATION")||!a)return gne(e,n),void r(t);const c=o();if(c.sendPackets>0&&c.OutgoingAvailableBandwidth>0){if(-1===s)return void(s=Date.now());if(Date.now()-s<1e3)return;const o=c.sendFrameRate,d=c.OutgoingAvailableBandwidth,l=Hb(hne(e,o,d,a.adaptationConfig,t,i),2),u=l[0],h=l[1];h&&(n.qualityLimitationReason=h),u&&a.adaptationConfig.scale!==u.scale&&(FL.debug("[".concat(e,"] applyAdaptation: ").concat(n.qualityLimitationReason,"\n           sendFps ").concat(o,", bwe ").concat(d,", switch from ").concat(a.adaptationConfig.scale," to ").concat(u.scale," ")),a.adaptationConfig=_ne(_ne({},a.adaptationConfig),u),r(u))}}),rL("CHECK_LOCAL_STATS_INTERVAL")),c=_ne({},t);mne.set(e,{timer:a,adaptationConfig:c,originConfig:t,adaptationFunc:r}),FL.debug("[".concat(e,"] start adaptation, originConfig: ").concat(JSON.stringify(t),", degradationPreference: ").concat(i))}function gne(e,t){const n=mne.get(e);if(n){const t=n.timer;window.clearTimeout(t),mne.delete(e)}t.qualityLimitationReason=VP.NONE,lne(e)}function Sne(e,t){var n;let i;switch(t){case sB.LocalAudioTrack:i=KF.Audio;break;case sB.LocalVideoTrack:i=Vi(n=e._hints).call(n,jk.SCREEN_TRACK)?KF.Screen:KF.High;break;case sB.LocalVideoLowTrack:i=KF.Low}return i}function Tne(e){const t=_k();if(e.some((e=>e._bypassWebAudio)))throw new zN(JN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");if(!t.webAudioMediaStreamDest)throw new zN(JN.NOT_SUPPORTED,"cannot publish multiple tracks because your browser does not support audio mixing")}function Rne(e,t){Tne(e);const n=t||new zU;return e.forEach((e=>n.addAudioTrack(e))),n}const vne=!_k().supportUnifiedPlan||rL("CHROME_FORCE_PLAN_B")&&FN();function yne(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e.useDcSignal)return n={spec:t,store:e},Kee("DataChannelConnection").create(n);var n;const i=vne?function(e){return Kee("PlanBConnection").create(e)}({spec:t,store:e}):new One(t,e);return i}function bne(e){return e&&("disconnected"===e.iceConnectionState||"checking"===e.iceConnectionState||"failed"===e.iceConnectionState)}function Cne(e){try{if(e.iceServers)return!1;if(e.turnServer&&"off"!==e.turnServer.mode){if(TD(e.turnServer.servers))return!1;if(rL("FORCE_TURN_TCP")||e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).some((e=>e.forceturn)))return!0}return!1}catch(e){return!1}}var Ine;function Ane(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function wne(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Ane(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Ane(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let One=(Ine=class e extends tB{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!==(e=null===(t=this.peerConnection.getReceivers()[0])||void 0===t||null===(t=t.transport)||void 0===t?void 0:t.state)&&void 0!==e?e:null}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.send.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Vi(t=Object.keys(cL)).call(t,e)})))]}constructor(t,n){super(t,n),GA(this,"id",eP(5,"connection-")),GA(this,"store",void 0),GA(this,"peerConnection",void 0),GA(this,"forceTurn",!1),GA(this,"remoteSDP",void 0),GA(this,"initialOffer",void 0),GA(this,"transportEventReceiver",void 0),GA(this,"statsFilter",void 0),GA(this,"extension",{useXR:rL("USE_XR")}),GA(this,"localCapabilities",void 0),GA(this,"remoteCodecs",void 0),GA(this,"localCandidateCount",0),GA(this,"allCandidatesReceived",!1),GA(this,"isPreallocation",!1),GA(this,"isPreRender",!1),GA(this,"preMediaMap",new Map),GA(this,"dataStreamChannelMap",new Map),GA(this,"establishPromise",void 0),GA(this,"recoveredDataChannelIds",[]),GA(this,"currentDataChannelId",1),GA(this,"supportAV1RtpSpec",!1),GA(this,"mutex",void 0),GA(this,"qualityLimitationReason",VP.NONE),GA(this,"isFirstConnected",!1),this.store=n,this.forceTurn=Cne(t),this.mutex=new _P("P2PConnection-mutex",n.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.isFirstConnected=!1,this.statsFilter=HP(this.peerConnection,rL("STATS_UPDATE_INTERVAL"),void 0,SN()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,t.isPreallocation&&(this.isPreallocation=!0),this.establishPromise=this.establish()}getPreMedia(e){return this.preMediaMap.get(e)}isPreSub(){return this.preMediaMap.size>0}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void FL.debug("[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);const n=this.remoteSDP.toString();null==t||t(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}else FL.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const t=await this.peerConnection.createOffer();if(!t.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const n=mee(t.sdp),i=await Oee({filterRTX:!rL("USE_PUB_RTX")&&!rL("USE_SUB_RTX"),filterVideoFec:rL("FILTER_VIDEO_FEC"),filterAudioFec:rL("FILTER_AUDIO_FEC"),filterVideoCodec:rL("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:rL("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:rL("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=Pee(i),this.initialOffer=t,rL("ENABLE_SVC")&&"av1"==this.store.codec){const t=await wee();var e;if(t)this.supportAV1RtpSpec=!0,null===(e=i.send)||void 0===e||e.videoExtensions.push(t)}let r;return t.sdp&&Bee(t.sdp)&&(r=GD(i),aee(r)),wne(wne({},n),{},{rtpCapabilities:r||i,offerSDP:t.sdp})}catch(e){throw new zN(JN.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");if(this.initialOffer.sdp&&Bee(this.initialOffer.sdp)&&cee(e.rtpCapabilities,this.localCapabilities),this.remoteSDP=new rne(wne(wne({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!rL("ENABLE_PRE_SUB_WITH_PRE_PC")||!rL("PRE_USE_LOCAL_CODECS"))&&gk(this.store)),e.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec),fk()&&gk(this.store)){var t;const e=(null===(t=this.store.preSubOptions)||void 0===t?void 0:t.length)||0,n=rL("PRE_SUB_NUM")||1,i=e>n?e:n,r=this.remoteSDP.preloadRemoteMedia(i),o=r.mids,s=r.preSSRCs,a=Vee(this.initialOffer.sdp,this.extension),c=this.logSDPExchange(a||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:a}),null==c||c(a),new Array(i).fill(0).forEach((()=>{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})}));const d=await this.peerConnection.createOffer(),l=this.logSDPExchange(d.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(d);const u=this.remoteSDP.toString();null==l||l(u),await this.peerConnection.setRemoteDescription({type:"answer",sdp:u}),FL.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media with icc/dtls, add preload ssrcs ").concat(s)),this.presetMedia(o,s);const h=this.peerConnection.getTransceivers()[0];null!=h&&h.receiver&&this.tryBindTransportEvents(h.receiver)}else{const t=this.remoteSDP.toString(),i=Vee(this.initialOffer.sdp,this.extension),r=this.logSDPExchange(i||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==r||r(t),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t});const o=this.peerConnection.getTransceivers()[0];if(null!=o&&o.receiver&&this.tryBindTransportEvents(o.receiver),gk(this.store))if(e.preallocation&&rL("ENABLE_PRE_SUB_WITH_PRE_PC")){var n;const e=(null===(n=this.store.preSubOptions)||void 0===n?void 0:n.length)||0,t=rL("PRE_SUB_NUM")||1,i=e>t?e:t,r=this.remoteSDP.preloadRemoteMedia(i),o=r.mids,s=r.preSSRCs;await Uee(this.peerConnection,this.remoteSDP,this.extension),FL.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(s)),this.presetMedia(o,s)}else{const t=e.preSSRCs,n=void 0===t?[]:t,i=n.map((e=>e.ssrcMsg[0].ssrcId));if(0===n.length)return;const r=this.remoteSDP.batchSend(n.map((e=>Object.assign({},e)))).mids;await Uee(this.peerConnection,this.remoteSDP,this.extension),FL.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(i)),this.presetMedia(r,i)}}}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}presetMedia(e,t){e.forEach(((e,n)=>{this.peerConnection.getTransceivers().forEach((i=>{if(null!=i.mid&&e===i.mid&&i.receiver.track){const s=i.receiver.track;if(rL("PRE_PLAYOUT_DELAY_HINT")){const e=i.receiver;"playoutDelayHint"in e&&(e.playoutDelayHint=rL("PRE_PLAYOUT_DELAY_HINT"),FL.debug("[".concat(this.store.clientId,"] [P2PConnection] presetMedia set playoutDelayHint to ").concat(rL("PRE_PLAYOUT_DELAY_HINT"))))}let a;if("video"===s.kind&&rL("ENABLE_PRE_RENDER")){var r,o;let e=null===(r=this.store.preSubOptions)||void 0===r||null===(r=r[n])||void 0===r?void 0:r.element;const i=(null===(o=this.store.preSubOptions)||void 0===o||null===(o=o[n])||void 0===o?void 0:o.config)||{};FL.debug("try to play pre sub video","string"==typeof e?e:"element","config: ".concat(JSON.stringify(i))),"string"==typeof e&&(e=document.getElementById(e)||void 0),a=e instanceof HTMLVideoElement?new $U(wne({trackId:"track-".concat(s.kind,"-unknown-").concat(this.store.clientId,"_").concat(eP(5,"")),element:e},i)):new tV(wne({trackId:"track-".concat(s.kind,"-unknown-").concat(this.store.clientId,"_").concat(eP(5,"")),element:e},i),!e),a.updateVideoTrack(s),a.onFirstVideoFrameRender=()=>{var e;a&&(a.onFirstVideoFrameRender=void 0);const i=this.preMediaMap.get(t[n]);i&&(i.firstVideoRender=Date.now()),null===(e=this.onFirstVideoRender)||void 0===e||e.call(this,t[n])},a.onVideoBufferReady=()=>{var e;null===(e=this.onFirstVideoBufferReady)||void 0===e||e.call(this,t[n])},a.play(this.store.sessionId||void 0),this.isPreRender=!0}this.preMediaMap.set(t[n],{mid:e,track:s,player:a,transceiver:i})}})),this.store.peerReceiver()}))}checkDtlsParameters(e){return!!this.remoteSDP&&(e.length>0&&this.remoteSDP.updateRemoteDtlsParameters(e))}checkIceParameters(e){if(!this.remoteSDP)return!1;return this.remoteSDP.restartICE(e)}async updateRemoteConnect(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateRemoteConnect before remote SDP created");let t=!1;const n=e.rtpCapabilities;if(t=Hb(this.remoteSDP.updateRemoteRTPCapabilities(n),2)[1],Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);t=t||e}const i=e.preSSRCs,r=void 0===i?[]:i,o=r.map((e=>e.ssrcMsg[0].ssrcId));if(!this.remoteSDP.checkPreloadSsrcs(o)){const e=[],t=[];if(Array.from(this.preMediaMap.entries()).every((n=>{let i=Hb(n,2),r=i[0],o=i[1],s=o.mid,a=o.player;o.track;return e.push(s),t.push(r),this.preMediaMap.delete(r),a&&a.destroy(),!0})),e.length>0&&(this.remoteSDP.stopSending(e),await Uee(this.peerConnection,this.remoteSDP,this.extension),FL.warn("[P2PConnection.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(t)),uk.reportApiInvoke(this.store.sessionId,{name:ED.PRELOAD_MEDIA_FAILED,options:[r,t],tag:mD.TRACER}).onSuccess()),r.length>0){const e=this.remoteSDP.batchSend(r.map((e=>Object.assign({},e)))).mids;await Uee(this.peerConnection,this.remoteSDP,this.extension),FL.debug("[P2PConnection.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(o)),this.presetMedia(e,o)}}t?(await Uee(this.peerConnection,this.remoteSDP,this.extension),FL.debug("[P2PConnection] updateRemoteConnect by exchanging SDP.")):FL.debug("[P2PConnection] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,n){var i=this;return mO((function*(){const r=yield gO(i.mutex.lock("From P2PConnection.send"));try{if(!i.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=[],s=oee();e.forEach((e=>{const t=i.peerConnection.addTransceiver(e._mediaStreamTrack,wne({direction:"sendonly"},"video"===e.trackMediaType&&i.supportAV1RtpSpec&&s?{sendEncodings:[{scalabilityMode:s}]}:{}));o.push(t),e._updateRtpTransceiver(t)})),SN()&&!0===rL("SIMULCAST")&&(yield gO(i.applySimulcastForFirefox(o,e)));const a=yield gO(i.peerConnection.createOffer()),c=i.remoteSDP.predictReceivingMids(e.length),d=i.mungSendOfferSDP(a.sdp,e,c),l=EL(d),u=c.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return fee(t,rL("USE_PUB_RTX"))}));let h;try{h=yield u}catch(r){h=[],i.remoteSDP.receive(e,t,n,h);const o=i.remoteSDP.toString();throw yield gO(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield gO(i.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield gO(i.stopSending(c,!0)),r}i.remoteSDP.receive(e,t,n,h);const p=i.remoteSDP.toString(),_=i.logSDPExchange(d,"offer","local","send");return yield gO(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield gO(i.applySimulcastEncodings(o,e)),yield gO(i.applySendEncodings(o,e)),null==_||_(p),yield gO(i.peerConnection.setRemoteDescription({type:"answer",sdp:p})),o.map(((e,t)=>{const n=c[t];return{localSSRC:u[t],id:n,transceiver:e}}))}catch(e){throw e instanceof zN?e:new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{r()}}))()}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.createDataChannels before remote SDP created");let n=this.dataStreamChannelMap.get(e);if(n&&"open"===n.readyState)FL.debug("[P2PConnection] Channels are already available and can be reused directly.");else{const t=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if("number"!=typeof t)throw new Error("create DataChannel error, because cannot get dc id");n=this.peerConnection.createDataChannel("datastream-channel",{id:t,negotiated:!0,ordered:!1,maxRetransmits:rL("DATASTREAM_MAX_RETRANSMITS")}),n.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,n)}t.forEach((e=>{e._updateOriginDataChannel(n)}));const i=this.remoteSDP.sendDataChannel();if(i.needExchangeSDP){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),FL.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else FL.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof zN?e:new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.createDataChannels failed; ".concat(e.toString()))}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return t&&(t.id&&this.recoveredDataChannelIds.push(t.id),t.close()),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof zN?e:new zN(JN.DATACHANNEL_FAILED,"P2PConnection.stopDataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){const n=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map((e=>{var t;gne(this.id+e.mid,this),e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==r||r(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{n&&n()}}async receive(e,t,n,i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const r=this.remoteSDP.send(e,t,n,i),o=r.mid;r.needExchangeSDP&&(await Uee(this.peerConnection,this.remoteSDP,this.extension),FL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP.")));const s=this.peerConnection.getTransceivers().find((e=>e.mid===o));if(!s)throw new Error("Cannot get transceiver after setLocalDescription.");if(rL("PRE_PLAYOUT_DELAY_HINT")){const t=s.receiver;"playoutDelayHint"in t&&(t.playoutDelayHint=rL("PRE_PLAYOUT_DELAY_HINT"),FL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," set playoutDelayHint to ").concat(rL("PRE_PLAYOUT_DELAY_HINT"))))}return{track:s.receiver.track,id:o,transceiver:s}}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e),n=t.mids;return t.needExchangeSDP&&(await Uee(this.peerConnection,this.remoteSDP,this.extension),FL.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive by exchanging SDP."))),n.map((e=>{const t=this.peerConnection.getTransceivers().find((t=>t.mid===e));if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");if(rL("PRE_PLAYOUT_DELAY_HINT")){const e=t.receiver;"playoutDelayHint"in e&&(e.playoutDelayHint=rL("PRE_PLAYOUT_DELAY_HINT"),FL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e.track.kind," set playoutDelayHint to ").concat(rL("PRE_PLAYOUT_DELAY_HINT"))))}return{track:t.receiver.track,id:e,transceiver:t}}))}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");e.forEach((e=>{Array.from(this.preMediaMap.entries()).some((t=>{let n=Hb(t,2),i=n[0],r=n[1],o=r.mid,s=r.player;if(o===e)return this.preMediaMap.delete(i),s&&s.destroy(),!0}))})),this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==i||i(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((async(e,t)=>{e.direction="sendonly"}));const n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.unmuteRemote(e),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(e,this.remoteCodecs,this.store.codec);const r=this.remoteSDP.toString();null==i||i(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return mO((function*(){const n=yield gO(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const i=_k().supportPCSetConfiguration,r=rL("FORCE_TURN_TCP")||t.forceTurn;if(e===iB.RELAY&&!i)return;if(i&&!r){const n=e===iB.RELAY?"relay":"all",i=t.peerConnection.getConfiguration();i.iceTransportPolicy!==n&&(FL.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}t.remoteSDP.updateCandidates(e);const o=yield gO(t.peerConnection.createOffer({iceRestart:!0}));if(!o.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const s=mee(o.sdp),a=(yield s.iceParameters).remoteIceParameters;t.remoteSDP.restartICE(a);const c=t.remoteSDP.toString(),d=t.logSDPExchange(o.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield gO(t.peerConnection.setLocalDescription(o)),null==d||d(c),yield gO(t.peerConnection.setRemoteDescription({type:"answer",sdp:c}))}catch(e){FL.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{n()}}))()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const e=await this.mutex.lock("From P2PConnection.extendCandidate");try{this.remoteSDP.updateCandidates(iB.TCP_RELAY),await Uee(this.peerConnection,this.remoteSDP,this.extension)}catch(e){FL.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e;this.peerConnection.getTransceivers().forEach((e=>{gne(this.id+e.mid,this)})),this.preMediaMap.forEach((e=>{let t=e.player;t&&t.destroy()})),this.preMediaMap.clear(),this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1}getStats(){return wne(wne({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason})}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const n=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(n.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(i,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const n=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===n.length&&(this.isVP8Simulcast(t)?SN()||await this.applySimulcastEncodings(n,[t]):await this.applySendEncodings(n,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const n=this.peerConnection.getTransceivers().find((e=>e.mid===t));n&&await n.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport.getSelectedCandidatePair(),n=t.local,i=t.remote;return{local:wne(wne({},OP),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port}),remote:wne(wne({},OP),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.isFirstConnected=!0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidateerror=e=>{if(e&&(e.errorCode||e.errorText)){var t;const n="code: ".concat(e.errorCode,", message: ").concat(e.errorText),i=e.port?"local: ".concat(e.port):"",r=iee(e.url||"");FL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICECandidateError(").concat(n,"), url: ").concat(r||"",", host_candidate:").concat(i)),null===(t=this.onICECandidateError)||void 0===t||t.call(this,n)}},this.peerConnection.onicegatheringstatechange=e=>{e&&e.target&&"iceGatheringState"in e.target&&FL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] RTCPeerConnection.onicegatheringstatechange(").concat(e.target.iceGatheringState,")"))},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,FL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,FL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),rL("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const n={iceServers:[]},i=t.cloudProxyServer||"disabled";return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&(TD(t.turnServer.servers)?n.iceServers=t.turnServer.servers:rL("NEW_TURN_MODE")&&n.iceServers&&"disabled"===i?(rL("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&n.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):n.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),rL("NEW_FORCE_TURN")&&(n.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(n.iceServers&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),rL("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),rL("FORCE_TURN_TCP")?n.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(n.iceTransportPolicy="relay")})))),rL("ENABLE_ENCODED_TRANSFORM")&&_k().supportWebRTCEncodedTransform&&(n.encodedInsertableStreams=!0),n}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(X7(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!rL("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}static newTurnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{const n=rL("NEW_TURN_MODE");1===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}):2===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}):3===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(X7(e.turnServerURL),":443?transport=tcp")}):4===n&&(t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(X7(e.turnServerURL),":443?transport=tcp")}))})),t}tryBindTransportEvents(e){const t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,t.state))},t.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const n=t.iceTransport;n&&(n.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var n;e&&(null===(n=this.onICETransportStateChange)||void 0===n||n.call(this,e))},n.getSelectedCandidatePair&&(n.onselectedcandidatepairchange=()=>{if(n.getSelectedCandidatePair()){const e=n.getSelectedCandidatePair()||{},t=e.local,i=e.remote;if(t&&i){const e=t.address+":"+t.port,n=i.address+":"+i.port;FL.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(iee(e)),", remote ").concat(JSON.stringify(iee(n))))}}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var n,i;if(!t){const n=this.peerConnection.getSenders();t=n.find((t=>t.track===e._mediaStreamTrack))}if(!t)return FL.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return FL.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!_k().supportSetRtpSenderParameters)return FL.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const r={},o={};switch(e._optimizationMode){case"motion":r.degradationPreference="maintain-framerate";break;case"detail":r.degradationPreference="maintain-resolution";break;case"balanced":r.degradationPreference="balanced"}const s=ree(this.peerConnection,e._mediaStreamTrack),a=nU(e);if(Ene(e)&&s&&t&&a&&this.getLocalVideoStats&&Vi(n=["vp8","vp9"]).call(n,this.store.codec)){var c;const n=r.degradationPreference||(Vi(c=e._hints).call(c,jk.CUSTOM_TRACK)?rL("CUSTOM_ADAPTATION_DEFAULT_MODE"):"maintain-framerate");fne(this.id+s.mid,a,this,n,(e=>{t&&this.updateAdaptation(t,e)}),this.getLocalVideoStats.bind(this))}if(e._encoderConfig){var d;const t=e._encoderConfig,n=t.bitrateMax,i=t.frameRate,r=t.scaleResolutionDownBy;n&&(o.maxBitrate=1e3*n),(Vi(d=e._hints).call(d,jk.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(o.maxFramerate=Z7(i)),r&&r>=1&&(o.scaleResolutionDownBy=r))}const l=rL("ENCODER_CONFIG_LIMIT").maxFramerate;if(l&&"number"==typeof l&&(o.maxFramerate=o.maxFramerate?Math.min(o.maxFramerate,l):l),rL("DSCP_TYPE")&&FN()){var u;const e=rL("DSCP_TYPE");Vi(u=["very-low","low","medium","high"]).call(u,e)&&(o.networkPriority=e)}const h=t.getParameters(),p=null===(i=h.encodings)||void 0===i?void 0:i[0];SN()&&!p&&(r.encodings=[o]),p&&Object.assign(p,o),Object.assign(h,r),FL.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(h.encodings))),await t.setParameters(h),await Fee(this.store.codec,t,rL("SVC_MODE"))}async updateAdaptation(e,t){var n,i;if(!e)return FL.debug("[updateAdaptation] no rtpSender found");if(!_k().supportSetRtpSenderParameters)return FL.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const r={},o=t.bitrateMax,s=t.frameRate,a=t.scaleResolutionDownBy;o&&(r.maxBitrate=1e3*o),s&&(r.maxFramerate=Z7(s)),a&&a>=1&&Vi(n=["vp8","vp9"]).call(n,this.store.codec)&&(r.scaleResolutionDownBy=a);const c=e.getParameters(),d=null===(i=c.encodings)||void 0===i?void 0:i[0];d&&Object.assign(d,r),Object.assign(c,{});try{await e.setParameters(c),FL.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(c.encodings)))}catch(t){!("transport"in e)||e.transport&&"connected"===e.transport.state?"connected"!==this.peerConnectionState?FL.debug("[updateAdaptation] peerConnection not connected}"):FL.debug("[updateAdaptation] updateRtpSenderEncodings failed",t):FL.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(e,t){try{if(!_k().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let n=0;n<e.length;n++){const i=e[n],r=t[n];r instanceof BV&&!this.isVP8Simulcast(r)&&await this.updateRtpSenderEncodings(r,i.sender)}}catch(e){FL.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,n){if(rL("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const i=EL(e);return t.forEach(((e,t)=>{const r=n[t],o=i.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(vee(o,e),Aee(o,e,this.store.codec))})),mL(i)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,n)=>{var i;null===(i=this.onFirstVideoDecoded)||void 0===i||i.call(this,e,t,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedLocalCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a<e.length;a++){var n,i,r,o,s;const c=e[a],d=t[a];if(d instanceof BV&&!Vi(n=d._hints).call(n,jk.LOW_STREAM)&&null!==(i=d._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(r=d._encoderConfig)||void 0===r?void 0:r.bitrateMax)>200&&null!==(o=d._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(s=d._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const n=c.sender.getParameters();await c.sender.setParameters(Object.assign(n,e))}}}async applySimulcastEncodings(e,t){if(!SN()&&e.length===t.length)for(let n=0;n<e.length;n++){const i=t[n];if(i instanceof BV&&this.isVP8Simulcast(i)){const t=e[n],r={},o={high:1e3*(i._encoderConfig.bitrateMax-50),medium:5e4};r.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:o.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:o.medium,scaleResolutionDownBy:4}];const s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,r))}}}isVP8Simulcast(e){var t,n,i,r,o;return!!(e instanceof BV&&rL("SIMULCAST")&&"vp8"===this.store.codec&&!Vi(t=e._hints).call(t,jk.LOW_STREAM)&&null!==(n=e._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(i=e._encoderConfig)||void 0===i?void 0:i.bitrateMax)>200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(o=e._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,n,i){if(rL("SDP_LOGGING"))return FL.upload("[".concat(this.store.clientId,"] exchanging ").concat(n," ").concat(t," SDP during P2PConnection.").concat(i,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===n?"remote":"local",i)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return t&&0!==t.length?t[0].ssrcId:void 0}setConfiguration(t){if(_k().supportPCSetConfiguration){const n=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(n)}t.isPreallocation&&(this.isPreallocation=!0)}},mF(Ine.prototype,"updateRemoteRTPCapabilities",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"updateRemoteRTPCapabilities"),Ine.prototype),mF(Ine.prototype,"connect",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"connect"),Ine.prototype),mF(Ine.prototype,"updateRemoteConnect",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"updateRemoteConnect"),Ine.prototype),mF(Ine.prototype,"createDataChannels",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"createDataChannels"),Ine.prototype),mF(Ine.prototype,"receive",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"receive"),Ine.prototype),mF(Ine.prototype,"batchReceive",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"batchReceive"),Ine.prototype),mF(Ine.prototype,"stopReceiving",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"stopReceiving"),Ine.prototype),mF(Ine.prototype,"muteRemote",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"muteRemote"),Ine.prototype),mF(Ine.prototype,"unmuteRemote",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"unmuteRemote"),Ine.prototype),mF(Ine.prototype,"muteLocal",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"muteLocal"),Ine.prototype),mF(Ine.prototype,"unmuteLocal",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"unmuteLocal"),Ine.prototype),mF(Ine.prototype,"close",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"close"),Ine.prototype),mF(Ine.prototype,"updateEncoderConfig",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"updateEncoderConfig"),Ine.prototype),mF(Ine.prototype,"updateSendParameters",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"updateSendParameters"),Ine.prototype),mF(Ine.prototype,"replaceTrack",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"replaceTrack"),Ine.prototype),mF(Ine.prototype,"updateAdaptation",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"updateAdaptation"),Ine.prototype),mF(Ine.prototype,"getRemoteSSRC",[Nne],Object.getOwnPropertyDescriptor(Ine.prototype,"getRemoteSSRC"),Ine.prototype),Ine);function Nne(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=await e.lock("From P2PConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await i.apply(this,o)}finally{n()}},n}function Dne(e,t){let n=document.createElement("video"),i=document.createElement("canvas");n.setAttribute("style","display:none"),i.setAttribute("style","display:none"),n.setAttribute("muted",""),n.muted=!0,n.setAttribute("autoplay",""),n.autoplay=!0,n.setAttribute("playsinline",""),i.width=Z7(t.width),i.height=Z7(t.height);const r=Z7(t.framerate||15);document.body.append(n),document.body.append(i);let o=e._mediaStreamTrack;n.srcObject=new MediaStream([o]),n.play().catch(nP);const s=i.getContext("2d");if(!s)throw new hk(JN.UNEXPECTED_ERROR,"can not get canvas context");const a=_k(),c=i.captureStream(a.supportRequestFrame?0:r).getVideoTracks()[0];c.canvas||(c.canvas=i),i.startCapture=()=>{if(!n)return i.stopCapture&&i.stopCapture();if(n.paused&&n.play(),n.videoHeight>2&&n.videoWidth>2){const e=n.videoWidth,t=n.videoHeight/e,r=i.width*t;Math.abs(r-i.height)>=2&&(FL.debug("adjust low stream resolution","".concat(i.width,"x").concat(i.height," -> ").concat(i.width,"x").concat(r)),i.height=r)}s.drawImage(n,0,0,i.width,i.height),c.requestFrame&&c.requestFrame(),o!==e._mediaStreamTrack&&(o=e._mediaStreamTrack,n.srcObject=new MediaStream([o]))},i.stopCapture=bM((()=>i.startCapture&&i.startCapture()),r);const d=c.stop;return c.stop=()=>{d.call(c),n&&(n.remove(),n.srcObject=null,n=null),i&&(i.width=0,i.remove(),i.stopCapture&&i.stopCapture(),i.startCapture=void 0,i.stopCapture=void 0,i=null),FL.debug("clean low stream renderer")},c}var Pne=function(e){return e[e.Video_Send_Type=190]="Video_Send_Type",e}(Pne||{}),Lne=function(e){return e[e.Video_Send_Qp_Sum=2143]="Video_Send_Qp_Sum",e[e.Video_Send_Freeze=2082]="Video_Send_Freeze",e[e.Video_Send_Codec=2240]="Video_Send_Codec",e[e.Video_Send_Power_Efficient_Encoder=2241]="Video_Send_Power_Efficient_Encoder",e[e.Video_Recv_Qp_Sum=2144]="Video_Recv_Qp_Sum",e[e.Video_Recv_Freeze=2084]="Video_Recv_Freeze",e[e.Video_Recv_Codec=2242]="Video_Recv_Codec",e[e.Video_Recv_Power_Efficient_Decoder=2243]="Video_Recv_Power_Efficient_Decoder",e[e.Video_Render_Freeze_Time=2109]="Video_Render_Freeze_Time",e[e.Video_Render_Freeze_Time_Render=2147]="Video_Render_Freeze_Time_Render",e[e.Video_Render_Freeze_Time_Render2=2223]="Video_Render_Freeze_Time_Render2",e[e.Audio_Recv_Freeze=2083]="Audio_Recv_Freeze",e}(Lne||{}),kne=function(e){return e[e.Video_Send_Retransmit=2062]="Video_Send_Retransmit",e[e.Video_Send_Target_Encoded=2064]="Video_Send_Target_Encoded",e[e.Video_Send_Actual_Encoded=2060]="Video_Send_Actual_Encoded",e[e.Video_Send_Transmit=2066]="Video_Send_Transmit",e[e.Video_Send_Bandwidth=2061]="Video_Send_Bandwidth",e[e.Video_Capture_Height=2033]="Video_Capture_Height",e[e.Video_Capture_Width=2035]="Video_Capture_Width",e[e.Video_Capture_Frame_Rate=2034]="Video_Capture_Frame_Rate",e[e.Video_Send_Low_Height=2073]="Video_Send_Low_Height",e[e.Video_Send_Low_Frame_Rate=2075]="Video_Send_Low_Frame_Rate",e[e.Video_Send_Low_Width=2077]="Video_Send_Low_Width",e[e.Video_Send_Low_Bitrate=2069]="Video_Send_Low_Bitrate",e[e.Video_Send_Low_Package_Lost=2070]="Video_Send_Low_Package_Lost",e[e.Video_Send_Low_Package_Rate=2071]="Video_Send_Low_Package_Rate",e[e.Video_Send_Frame_Rate=2002]="Video_Send_Frame_Rate",e[e.Video_Send_Width=2003]="Video_Send_Width",e[e.Video_Send_Height=2004]="Video_Send_Height",e[e.Video_Send_Disabled=2095]="Video_Send_Disabled",e[e.Video_Send_Adaptation=2032]="Video_Send_Adaptation",e[e.Video_Send_Player_Status=2128]="Video_Send_Player_Status",e[e.Video_Send_Nacks=2009]="Video_Send_Nacks",e[e.Video_Send_Plis=2010]="Video_Send_Plis",e[e.Video_Send_Firs=2011]="Video_Send_Firs",e[e.Video_Send_Avg_Encode=2007]="Video_Send_Avg_Encode",e[e.Video_Send_Huge_Frame_Sent=2174]="Video_Send_Huge_Frame_Sent",e[e.Video_Send_Bytes_Retransmit=2173]="Video_Send_Bytes_Retransmit",e[e.Video_Send_Packages_Retransmit=2172]="Video_Send_Packages_Retransmit",e[e.Video_Send_Key_Frames_Encoded=2207]="Video_Send_Key_Frames_Encoded",e[e.Video_Send_Bitrate=2012]="Video_Send_Bitrate",e[e.Video_Send_Package_Rate=2031]="Video_Send_Package_Rate",e[e.Video_Send_Package_Lost=2005]="Video_Send_Package_Lost",e[e.Audio_Capture_PCM_Level=2104]="Audio_Capture_PCM_Level",e[e.Audio_Send_Level=2038]="Audio_Send_Level",e[e.Audio_Send_Bitrate=2039]="Audio_Send_Bitrate",e[e.Audio_Send_Package_Rate=2040]="Audio_Send_Package_Rate",e[e.Audio_Send_AEC_Return_Loss=2041]="Audio_Send_AEC_Return_Loss",e[e.Audio_Send_AEC_Return_Loss_Enhancement=2042]="Audio_Send_AEC_Return_Loss_Enhancement",e[e.Audio_Send_Freeze=2081]="Audio_Send_Freeze",e[e.Audio_Send_Disabled=2096]="Audio_Send_Disabled",e[e.Audio_Send_Bytes_Retransmit=2179]="Audio_Send_Bytes_Retransmit",e[e.Audio_Send_Packages_Retransmit=2180]="Audio_Send_Packages_Retransmit",e[e.Video_Recv_Height=2019]="Video_Recv_Height",e[e.Video_Recv_Width=2018]="Video_Recv_Width",e[e.Video_Recv_Frame_Rate_Output=2155]="Video_Recv_Frame_Rate_Output",e[e.Video_Recv_Jitter_Buffer=2023]="Video_Recv_Jitter_Buffer",e[e.Video_Recv_Current_Delay=2024]="Video_Recv_Current_Delay",e[e.Video_Recv_Nacks=2026]="Video_Recv_Nacks",e[e.Video_Recv_Plis=2027]="Video_Recv_Plis",e[e.Video_Recv_Firs=2028]="Video_Recv_Firs",e[e.Video_Recv_Disabled=2101]="Video_Recv_Disabled",e[e.Video_Recv_Player_Status=2129]="Video_Recv_Player_Status",e[e.Video_Recv_I_Frame_Delay=2149]="Video_Recv_I_Frame_Delay",e[e.Video_Render_Frame_Rate_Render=2022]="Video_Render_Frame_Rate_Render",e[e.Video_Render_Freeze_Duration=2156]="Video_Render_Freeze_Duration",e[e.Audio_Render_Level=2043]="Audio_Render_Level",e[e.Audio_Render_Freeze_Time_80ms=2226]="Audio_Render_Freeze_Time_80ms",e[e.Audio_Render_Freeze_Time_200ms=2227]="Audio_Render_Freeze_Time_200ms",e[e.Audio_Render_Freeze_Samples_80ms=2228]="Audio_Render_Freeze_Samples_80ms",e[e.Audio_Render_Freeze_Samples_200ms=2229]="Audio_Render_Freeze_Samples_200ms",e[e.Audio_Recv_PCM_Level=2105]="Audio_Recv_PCM_Level",e[e.Audio_Recv_Disabled=2102]="Audio_Recv_Disabled",e[e.Audio_Recv_Jitter_Buffer=2054]="Audio_Recv_Jitter_Buffer",e[e.Audio_Recv_Current_Delay=2047]="Audio_Recv_Current_Delay",e[e.Audio_Recv_Player_Status=2130]="Audio_Recv_Player_Status",e[e.Audio_Recv_Bitrate=2044]="Audio_Recv_Bitrate",e[e.Audio_Recv_Concealed_Samples=2148]="Audio_Recv_Concealed_Samples",e[e.Audio_Recv_Total_Samples_Received=2224]="Audio_Recv_Total_Samples_Received",e}(kne||{}),Mne=function(e){return e[e.Video_Render_Frame_Rate_Decode=2021]="Video_Render_Frame_Rate_Decode",e[e.Video_Recv_Frame_Rate=2020]="Video_Recv_Frame_Rate",e[e.Video_Recv_Frame_Dropped=2181]="Video_Recv_Frame_Dropped",e[e.Video_Recv_Bytes_Retransmit=2175]="Video_Recv_Bytes_Retransmit",e[e.Video_Recv_Packages_Retransmit=2176]="Video_Recv_Packages_Retransmit",e[e.Video_Recv_Packages_Discarded=2198]="Video_Recv_Packages_Discarded",e[e.Video_Recv_Avg_Decode=2200]="Video_Recv_Avg_Decode",e[e.Video_Recv_Avg_Processing_Delay=2202]="Video_Recv_Avg_Processing_Delay",e[e.Video_Recv_Avg_Assembly_Time=2203]="Video_Recv_Avg_Assembly_Time",e[e.Video_Recv_Avg_Inter_Frame_Delay=2204]="Video_Recv_Avg_Inter_Frame_Delay",e[e.Video_Recv_Key_Frames_Decoded=2206]="Video_Recv_Key_Frames_Decoded",e[e.Video_Recv_Package_Lost=2014]="Video_Recv_Package_Lost",e[e.Video_Recv_Bitrate=2029]="Video_Recv_Bitrate",e[e.Video_Recv_Package_Rate=2078]="Video_Recv_Package_Rate",e[e.Audio_Recv_Jitter=2055]="Audio_Recv_Jitter",e[e.Audio_Recv_Bytes_Retransmit=2178]="Audio_Recv_Bytes_Retransmit",e[e.Audio_Recv_Packages_Retransmit=2177]="Audio_Recv_Packages_Retransmit",e[e.Audio_Recv_Packages_Discarded=2199]="Audio_Recv_Packages_Discarded",e[e.Audio_Recv_Avg_Processing_Delay=2201]="Audio_Recv_Avg_Processing_Delay",e[e.Audio_Recv_Package_Rate=2046]="Audio_Recv_Package_Rate",e[e.Audio_Recv_Package_Lost=2045]="Audio_Recv_Package_Lost",e[e.Audio_Recv_AV_Sync_TIME=2237]="Audio_Recv_AV_Sync_TIME",e}(Mne||{}),Une=function(e){return e[e.RTT=2006]="RTT",e[e.CONN_TYPE=801]="CONN_TYPE",e[e.STATS_UPDATE_INTERVAL=2205]="STATS_UPDATE_INTERVAL",e}(Une||{}),Vne=function(e){return e[e.RTC_PEER_CONNECTION_STATE=2219]="RTC_PEER_CONNECTION_STATE",e[e.PAGE_VISIBILITY=2233]="PAGE_VISIBILITY",e}(Vne||{}),xne=function(e){return e[e.Transport_Send_Bitrate=2234]="Transport_Send_Bitrate",e[e.Transport_Recv_Bitrate=2235]="Transport_Recv_Bitrate",e}(xne||{});const Fne=1e3,Bne=6,jne=3,Gne=Math.max(Bne,jne,60);function Wne(e){return e=e.toLowerCase(),Vi(e).call(e,"vp8")?1:Vi(e).call(e,"h264")?2:Vi(e).call(e,"vp9")?3:Vi(e).call(e,"av1")?4:Vi(e).call(e,"h265")?5:0}function Kne(e,t,n){null!=n&&Number.isFinite(n)&&(e[t]=Math.round(Math.max(0,n)))}function Hne(e){const t={[Une.CONN_TYPE]:0,[Une.RTT]:e.rtt,[Une.STATS_UPDATE_INTERVAL]:e.updateInterval?Math.round(Math.max(0,e.updateInterval)):void 0};switch(e.selectedCandidatePair.localCandidate.candidateType){case"relay":{const n=e.selectedCandidatePair.localCandidate.relayProtocol;"udp"===n&&(t[Une.CONN_TYPE]=1),"tcp"===n&&(t[Une.CONN_TYPE]=3),"tls"===n&&(t[Une.CONN_TYPE]=4);break}case"srflx":t[Une.CONN_TYPE]=2;break;case"unknown":t[Une.CONN_TYPE]=5;break;default:t[Une.CONN_TYPE]=0}return t}function Yne(e){let t=0;switch(e){case"none":t=0;break;case"cpu":t=1;break;case"bandwidth":t=2;break;case"other":t=3}return t}class Xne extends hD{constructor(e){super(),GA(this,"store",void 0),GA(this,"uploadWRTCStatsTimer",void 0),GA(this,"uploadOutboundDenoiserStatsTimer",void 0),GA(this,"uploadExtStatsTimer",void 0),GA(this,"uploadExtUsageStatsTimer",void 0),GA(this,"uploadInboundExtStatsTimer",void 0),GA(this,"requestStats",void 0),GA(this,"requestTransportStats",void 0),GA(this,"requestLocalMedia",void 0),GA(this,"requestRemoteMedia",void 0),GA(this,"requestAllTracks",void 0),GA(this,"requestVideoIsReady",void 0),GA(this,"requestUploadStats",void 0),GA(this,"requestUpload",void 0),GA(this,"uploadOutboundStarted",!1),GA(this,"uploadInboundStarted",!1),GA(this,"uploadTransportStarted",!1),GA(this,"uploadBaseStatsStarted",!1),GA(this,"uploadExtensionUsageStarted",!1),GA(this,"lastRecvStats",void 0),GA(this,"lastSendStats",void 0),GA(this,"lastRefRecvStats",void 0),GA(this,"lastRefSendStats",void 0),GA(this,"lastNormalRecvStats",void 0),GA(this,"lastNormalSendStats",void 0),GA(this,"lastExtendStats",{}),GA(this,"needUploadStats",{}),GA(this,"needUploadRenderFreezeTime",!0),GA(this,"lastUploadCompensateTime",-1),GA(this,"uploadCompensateDeltaTime",0),this.store=e}uploadWRTCStats(e){if(!this.requestStats||!this.requestUploadStats)return;const t=e%jne==0,n=e%Bne==0,i=e%60==0;let r,o;if(this.uploadTransportStarted&&(r=this.requestStats(),this.store.useP2P&&(o=this.requestStats(!0))),!r&&this.uploadOutboundStarted&&(r=this.requestStats()),!o&&this.uploadInboundStarted&&(o=this.requestStats(!0)),r||o){var s;const a={};if(this.uploadTransportStarted&&r){const e=this.getTransportStats(r,t?this.lastRefSendStats:void 0,o,t);e&&(a.misc=[e])}if(this.uploadOutboundStarted&&r){const e=this.getOutboundStats(r,n?this.lastNormalSendStats:void 0,t?this.lastRefSendStats:void 0,this.lastSendStats,i);e&&(a.outbound=[e])}if(this.uploadInboundStarted&&o){this.uploadCompensateStats(e);const i=this.getInboundStats(o,n?this.lastNormalRecvStats:void 0,t?this.lastRefRecvStats:void 0,this.lastRecvStats);i&&(a.inbound=i)}const c=null===(s=this.requestTransportStats)||void 0===s?void 0:s.call(this).connectState;if(c&&(Array.isArray(a.misc)?a.misc[0]&&a.misc[0].addition&&(a.misc[0].addition[Vne.RTC_PEER_CONNECTION_STATE]=FP[c]):a.misc=[{addition:{[Vne.RTC_PEER_CONNECTION_STATE]:FP[c]}}]),sx.needUploadStats.length>0||n){const e=sx.needUploadStats.shift()||("visible"===sx.visibility?1:0);Array.isArray(a.misc)?a.misc[0]&&a.misc[0].addition&&(a.misc[0].addition[Vne.PAGE_VISIBILITY]=e):a.misc=[{addition:{[Vne.PAGE_VISIBILITY]:e}}]}this.needUploadStats.sendType&&(Array.isArray(a.outbound)&&a.outbound[0]&&a.outbound[0].high&&(a.outbound[0].high[Pne.Video_Send_Type]=this.needUploadStats.sendType),this.needUploadStats.sendType=void 0),this.requestUploadStats(a)}this.lastRecvStats=o,this.lastSendStats=r,n&&(this.lastNormalRecvStats=o,this.lastNormalSendStats=r),t&&(this.lastRefRecvStats=o,this.lastRefSendStats=r)}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;this.uploadBaseStatsStarted=!0,sx.startCollectStats();let e=1;this.uploadWRTCStatsTimer=window.setInterval((()=>{if(!this.uploadTransportStarted&&!this.uploadInboundStarted&&!this.uploadOutboundStarted){if(this.uploadBaseStatsStarted){var t,n;const e=null===(t=this.requestTransportStats)||void 0===t?void 0:t.call(this);return void(e&&(null===(n=this.requestUploadStats)||void 0===n||n.call(this,{misc:[{addition:{[Vne.RTC_PEER_CONNECTION_STATE]:FP[e.connectState]}}]})))}return this.stopUploadWRTCStats()}this.uploadWRTCStats(e),++e===Gne+1&&(e=1)}),Fne)}uploadCompensateStats(e){if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const t=e%jne==0&&this.needUploadRenderFreezeTime;if(!this.uploadInboundStarted||!t)return;if(-1===this.lastUploadCompensateTime)return void(this.lastUploadCompensateTime=Date.now());const n=Math.max(-6e3,Date.now()-this.lastUploadCompensateTime-6e3);if(this.uploadCompensateDeltaTime+=n,this.lastUploadCompensateTime=Date.now(),this.uploadCompensateDeltaTime<6e3)return;const i=Math.min(Math.floor(this.uploadCompensateDeltaTime/6e3),10);this.uploadCompensateDeltaTime-=6e3*i;const r=this.requestStats(!0);new Array(i).fill(0).forEach((()=>{if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const e={};if(this.uploadInboundStarted&&r){const t=this.requestRemoteMedia()||[],n=[];t.forEach((e=>{let t=Hb(e,2),i=t[0],o=t[1];const s={peer:i.uid};if((i._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(i._videoSSRC)||!1)&&o.has(nB.VIDEO)&&i.videoTrack){const e=function(e,t,n){if(!t.videoRecv.find((t=>t.ssrc===e)))return;const i={};if(n&&n._player){const e=n._player,t=e.renderFreezeAccTime2,r=e.videoElementStatus;if("visible"===sx.visibility&&r===oM.PLAYING&&_k().supportRequestVideoFrameCallback){const n=Math.min(6e3,t);e.renderFreezeAccTime2=Math.max(0,t-n),Kne(i,Lne.Video_Render_Freeze_Time_Render2,n),rL("USE_NEW_RENDER_FREEZE_TIME")&&Kne(i,Lne.Video_Render_Freeze_Time_Render,n)}}return i}(i._videoSSRC,r,i.videoTrack);e&&(s.video=e)}s.video&&n.push(s)})),n.length>0&&(e.inbound=n,this.requestUploadStats(e))}}))}stopUploadWRTCStats(){window.clearInterval(this.uploadWRTCStatsTimer),this.uploadWRTCStatsTimer=void 0,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0),this.lastRefSendStats&&(this.lastRefSendStats.videoSend=[],this.lastRefSendStats.audioSend=[],this.lastRefSendStats=void 0),this.lastRefRecvStats&&(this.lastRefRecvStats.videoRecv=[],this.lastRefRecvStats.audioRecv=[],this.lastRefRecvStats=void 0),this.lastNormalSendStats&&(this.lastNormalSendStats.videoSend=[],this.lastNormalSendStats.audioSend=[],this.lastNormalSendStats=void 0),this.lastNormalRecvStats&&(this.lastNormalRecvStats.videoRecv=[],this.lastNormalRecvStats.audioRecv=[],this.lastNormalRecvStats=void 0),this.lastExtendStats={},this.needUploadStats={},this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0}getTransportStats(e,t,n,i){if(!this.requestStats)return;if(!i)return null==e.rtt?void 0:{addition:{[Une.RTT]:e.rtt,[Une.CONN_TYPE]:void 0,[Une.STATS_UPDATE_INTERVAL]:e.updateInterval||void 0}};const r=Hne(e);if(this.store.useP2P){if(n){const e=Hne(n);r[Une.CONN_TYPE]&&e[Une.CONN_TYPE]&&(r[Une.CONN_TYPE]+=e[Une.CONN_TYPE]<<3)}r[Une.CONN_TYPE]?r[Une.CONN_TYPE]+=110:r[Une.CONN_TYPE]=110}else{r[Une.CONN_TYPE]?r[Une.CONN_TYPE]+=100:r[Une.CONN_TYPE]=100;const n=function(e,t){if(t)return[Math.ceil(8*(e.transport.bytesSent-t.transport.bytesSent)/(e.timestamp-t.timestamp)),Math.ceil(8*(e.transport.bytesReceived-t.transport.bytesReceived)/(e.timestamp-t.timestamp))];return[0,0]}(e,t);r[xne.Transport_Send_Bitrate]=n[0],r[xne.Transport_Recv_Bitrate]=n[1]}return{addition:r}}getOutboundStats(e,t,n,i,r){if(!this.requestUploadStats||!this.requestLocalMedia)return;const o=this.requestLocalMedia();if(!o||0===o.length)return;let s,a,c;return o.forEach((i=>{let o=Hb(i,2),d=o[0],l=o[1],u=l.track,h=l.ssrcs;switch(d){case sB.LocalVideoLowTrack:case sB.LocalVideoTrack:if(d===sB.LocalVideoTrack){var p;const i=function(e,t,n,i,r,o){const s=t.videoSend.find((t=>t.ssrc===e));if(!s)return;const a={},c=s.sentFrame,d=s.inputFrame;if(i&&(Kne(a,Lne.Video_Send_Qp_Sum,s.qpSumPerFrame),s.codec&&Kne(a,Lne.Video_Send_Codec,Wne(s.codec)),"number"==typeof s.powerEfficientEncoder&&Kne(a,Lne.Video_Send_Power_Efficient_Encoder,s.powerEfficientEncoder),d&&c)){const e=d.frameRate,t=c.frameRate;a[Lne.Video_Send_Freeze]=function(e,t){let n=!0;return n=!(e<=5)&&(e<=10?t<3:e<=20?t<4:t<5),n}(e,t)?1:0}if(r){switch(c&&(Kne(a,kne.Video_Send_Height,c.height),Kne(a,kne.Video_Send_Width,c.width),Kne(a,kne.Video_Send_Frame_Rate,c.frameRate)),a[kne.Video_Send_Disabled]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0,s.adaptionChangeReason){case"none":a[kne.Video_Send_Adaptation]=0;break;case"cpu":a[kne.Video_Send_Adaptation]=1;break;case"bandwidth":a[kne.Video_Send_Adaptation]=2;break;case"other":a[kne.Video_Send_Adaptation]=3}let i=0;s.adaptionChangeReason&&(i+=Yne(s.adaptionChangeReason)),t.qualityLimitationReason&&(i+=Yne(t.qualityLimitationReason)<<3),a[kne.Video_Send_Adaptation]=i,a[kne.Video_Send_Player_Status]=aM[n._player?n._player.videoElementStatus:"uninit"],Kne(a,kne.Video_Send_Nacks,s.nacksCount),Kne(a,kne.Video_Send_Plis,s.plisCount),Kne(a,kne.Video_Send_Firs,s.firsCount),Kne(a,kne.Video_Send_Avg_Encode,s.avgEncodeMs),Kne(a,kne.Video_Send_Huge_Frame_Sent,s.hugeFramesSent),Kne(a,kne.Video_Send_Bytes_Retransmit,s.retransmittedBytesSent),Kne(a,kne.Video_Send_Packages_Retransmit,s.retransmittedPacketsSent),Kne(a,kne.Video_Send_Key_Frames_Encoded,s.keyFramesEncoded);const o=r.videoSend.find((t=>t.ssrc===e));if(o){let e=Fne*jne;o.timestamp&&s.timestamp&&(e=s.timestamp-o.timestamp),null!=o.packets&&null!=s.packets&&Kne(a,kne.Video_Send_Package_Rate,1e3*(s.packets-o.packets)/e),null!=s.packetsLost&&null!=o.packetsLost&&Kne(a,kne.Video_Send_Package_Lost,s.packetsLost-o.packetsLost),null!=o.bytes&&null!=s.bytes&&Kne(a,kne.Video_Send_Bitrate,8*(s.bytes-o.bytes)/e)}}return a}(h[0].ssrcId,e,u,t,n),o="CameraVideoTrack"===u.__className__?3:Vi(p=u._hints).call(p,jk.SCREEN_TRACK)?7:10;(this.lastExtendStats.sendType!==o||r)&&(this.needUploadStats={sendType:o},this.lastExtendStats.sendType=o);const s=u&&function(e,t,n,i){const r=t.videoSend.find((t=>t.ssrc===e));if(!r)return null;const o={};if(i){const e=r.inputFrame,t=e&&e.height||n.videoHeight||0,i=e&&e.width||n.videoWidth||0,s=e&&e.frameRate||0;Kne(o,kne.Video_Capture_Height,t),Kne(o,kne.Video_Capture_Width,i),Kne(o,kne.Video_Capture_Frame_Rate,s)}return o}(h[0].ssrcId,e,u,!!n),c=function(e,t){const n={};return t&&(Kne(n,kne.Video_Send_Retransmit,e.bitrate.retransmit),Kne(n,kne.Video_Send_Target_Encoded,e.bitrate.targetEncoded),Kne(n,kne.Video_Send_Actual_Encoded,e.bitrate.actualEncoded),Kne(n,kne.Video_Send_Transmit,e.bitrate.transmit),Kne(n,kne.Video_Send_Bandwidth,e.sendBandwidth)),n}(e,!!n);a=Object.assign({},i,s,c)}else c=function(e,t,n,i,r){const o=t.videoSend.find((t=>t.ssrc===e));if(!o)return;const s={};if(i){const t=o.sentFrame;t&&(Kne(s,kne.Video_Send_Low_Height,t.height),Kne(s,kne.Video_Send_Low_Width,t.width),Kne(s,kne.Video_Send_Low_Frame_Rate,t.frameRate));const n=i.videoSend.find((t=>t.ssrc===e));if(n){let e=Fne*Bne;n.timestamp&&o.timestamp&&(e=o.timestamp-n.timestamp),null!=n.packets&&null!=o.packets&&Kne(s,kne.Video_Send_Low_Package_Rate,1e3*(o.packets-n.packets)/e),null!=o.packetsLost&&null!=n.packetsLost&&Kne(s,kne.Video_Send_Low_Package_Lost,o.packetsLost-n.packetsLost),null!=n.bytes&&null!=o.bytes&&Kne(s,kne.Video_Send_Low_Bitrate,8*(o.bytes-n.bytes)/e)}}return s}(h[0].ssrcId,e,0,n);break;case sB.LocalAudioTrack:s=u&&function(e,t,n,i,r,o){const s=t.audioSend.find((t=>t.ssrc===e));if(!s)return;const a={};if(r){a[kne.Audio_Send_Disabled]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0;const t=100*n._source.getAccurateVolumeLevel(),i=s.inputLevel;if(null!=i){const e=Math.ceil(50*Math.log10(100*i+1));Kne(a,kne.Audio_Send_Level,e)}Kne(a,kne.Audio_Capture_PCM_Level,t),Kne(a,kne.Audio_Send_AEC_Return_Loss,s.aecReturnLoss),Kne(a,kne.Audio_Send_AEC_Return_Loss_Enhancement,s.aecReturnLossEnhancement),Kne(a,kne.Audio_Send_Bytes_Retransmit,s.retransmittedBytesSent),Kne(a,kne.Audio_Send_Packages_Retransmit,s.retransmittedPacketsSent),a[kne.Audio_Send_Freeze]=0;const o=r.audioSend.find((t=>t.ssrc===e));if(o){let e=Fne*Bne;o.timestamp&&s.timestamp&&(e=s.timestamp-o.timestamp),null!=o.bytes&&null!=s.bytes&&Kne(a,kne.Audio_Send_Bitrate,8*(s.bytes-o.bytes)/e),null!=o.packets&&null!=s.packets&&Kne(a,kne.Audio_Send_Package_Rate,1e3*(s.packets-o.packets)/e)}}return a}(h[0].ssrcId,e,u,0,n)}})),{high:a,low:c,audio:s}}getInboundStats(e,t,n,i){if(!this.requestRemoteMedia)return;const r=this.requestRemoteMedia()||[],o=[];return r.forEach((r=>{let s=Hb(r,2),a=s[0],c=s[1];const d={peer:a.uid};let l;if(c.has(nB.VIDEO)&&a.videoTrack){const r=a._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(a._videoSSRC)||!1,o=a.videoTrack?function(e,t,n,i,r,o,s,a){const c=t.videoRecv.find((t=>t.ssrc===e));if(!c)return;const d={},l=c.receivedFrame,u=c.outputFrame,h=c.decodeFrameRate;Kne(d,Mne.Video_Render_Frame_Rate_Decode,h),c.framesRateFirefox&&Kne(d,Mne.Video_Recv_Frame_Rate,c.framesRateFirefox),l&&Kne(d,Mne.Video_Recv_Frame_Rate,l.frameRate),Kne(d,Mne.Video_Recv_Frame_Dropped,c.framesDroppedCount),Kne(d,Mne.Video_Recv_Bytes_Retransmit,c.retransmittedBytesReceived),Kne(d,Mne.Video_Recv_Packages_Retransmit,c.retransmittedPacketsReceived),Kne(d,Mne.Video_Recv_Packages_Discarded,c.packetsDiscarded),Kne(d,Mne.Video_Recv_Avg_Decode,c.avgDecodeMs),Kne(d,Mne.Video_Recv_Avg_Processing_Delay,c.avgProcessingDelayMs),Kne(d,Mne.Video_Recv_Avg_Assembly_Time,c.avgFramesAssembledFromMultiplePacketsMs),Kne(d,Mne.Video_Recv_Avg_Inter_Frame_Delay,c.avgInterFrameDelayMs),Kne(d,Mne.Video_Recv_Key_Frames_Decoded,c.keyFramesDecoded);const p=a&&a.videoRecv.find((t=>t.ssrc===e));if(p){const e=t.timestamp-a.timestamp||Fne;null!=c.packetsLost&&null!=p.packetsLost&&Kne(d,Mne.Video_Recv_Package_Lost,c.packetsLost-p.packetsLost),null!=p.bytes&&null!=c.bytes&&Kne(d,Mne.Video_Recv_Bitrate,8*(c.bytes-p.bytes)/e),null!=p.packets&&null!=c.packets&&Kne(d,Mne.Video_Recv_Package_Rate,1e3*(c.packets-p.packets)/e)}const _=o&&o.videoRecv.find((t=>t.ssrc===e));if(_&&(Kne(d,Lne.Video_Recv_Qp_Sum,c.qpSumPerFrame),c.codec&&Kne(d,Lne.Video_Recv_Codec,Wne(c.codec)),"number"==typeof c.powerEfficientDecoder&&Kne(d,Lne.Video_Recv_Power_Efficient_Decoder,c.powerEfficientDecoder),d[Lne.Video_Recv_Freeze]=i&&Jte.isRemoteVideoFreeze(n,c,_)?1:0),s){var E;const t=s.videoRecv.find((t=>t.ssrc===e));l?(Kne(d,kne.Video_Recv_Height,l.height),Kne(d,kne.Video_Recv_Width,l.width)):n&&(Kne(d,kne.Video_Recv_Height,n._videoHeight||0),Kne(d,kne.Video_Recv_Width,n._videoWidth||0)),u&&Kne(d,kne.Video_Recv_Frame_Rate_Output,u.frameRate);const i=null===(E=n._player)||void 0===E?void 0:E.rendFrameRate.toFixed(0);if(i&&Kne(d,kne.Video_Render_Frame_Rate_Render,+i),Kne(d,kne.Video_Recv_Jitter_Buffer,c.jitterBufferMs),Kne(d,kne.Video_Recv_Current_Delay,c.currentDelayMs),Kne(d,kne.Video_Recv_Firs,c.firsCount),Kne(d,kne.Video_Recv_Nacks,c.nacksCount),Kne(d,kne.Video_Recv_Plis,c.plisCount),n){d[kne.Video_Recv_Disabled]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1;const e=n._player;if(e){const n=e.freezeTimeCounterList,i=e.renderFreezeAccTime,o=e.renderFreezeAccTime2,s=e.videoElementStatus;if(n&&n.length>0&&Kne(d,Lne.Video_Render_Freeze_Time,n.splice(0,1)[0]),r&&"visible"===sx.visibility&&s===oM.PLAYING&&_k().supportRequestVideoFrameCallback){const t=Math.min(6e3,o);e.renderFreezeAccTime2=Math.max(0,o-t),Kne(d,Lne.Video_Render_Freeze_Time_Render2,t);const n=Math.min(6e3,i);e.renderFreezeAccTime=Math.max(0,i-n),Kne(d,Lne.Video_Render_Freeze_Time_Render,rL("USE_NEW_RENDER_FREEZE_TIME")?t:n)}if("number"==typeof c.totalFreezesDuration){const e=t&&t.totalFreezesDuration?c.totalFreezesDuration-t.totalFreezesDuration:c.totalFreezesDuration;Kne(d,kne.Video_Render_Freeze_Duration,1e3*e)}}}if(d[kne.Video_Recv_Player_Status]=aM[n._player?n._player.videoElementStatus:"uninit"],t&&void 0!==c.totalInterFrameDelay&&void 0!==c.totalSquaredInterFrameDelay&&void 0!==t.totalInterFrameDelay&&void 0!==t.totalSquaredInterFrameDelay){const e=c.totalInterFrameDelay-t.totalInterFrameDelay,n=c.totalSquaredInterFrameDelay-t.totalSquaredInterFrameDelay,i=c.framesDecodeCount-t.framesDecodeCount,r=e/i*1e3,o=Math.round(1e3*Math.sqrt((n-Math.pow(e,2)/i)/i));!isNaN(o)&&r+o>Math.max(3*r,r+150)&&(d[kne.Video_Recv_I_Frame_Delay]=o)}}return d}(a._videoSSRC,e,a.videoTrack,!0===r,this.needUploadRenderFreezeTime,t,n,i):void 0;if(o&&(d.video=o),a.videoTrack){const t=e.videoRecv.find((e=>e.ssrc===a._videoSSRC));t&&t.estimatedPlayoutTimestamp&&(l=t.estimatedPlayoutTimestamp)}}if(c.has(nB.AUDIO)&&a.audioTrack){const r=!a.hasAudio,o=a.audioTrack?function(e,t,n,i,r,o){let s=arguments.length>6&&void 0!==arguments[6]&&arguments[6];const a=t.audioRecv.find((t=>t.ssrc===e));if(!a)return;const c={};Kne(c,Mne.Audio_Recv_Jitter,a.jitterMs),Kne(c,Mne.Audio_Recv_Bytes_Retransmit,a.retransmittedBytesReceived),Kne(c,Mne.Audio_Recv_Packages_Retransmit,a.retransmittedPacketsReceived),Kne(c,Mne.Audio_Recv_Packages_Discarded,a.packetsDiscarded),Kne(c,Mne.Audio_Recv_Avg_Processing_Delay,a.avgProcessingDelayMs);const d=o&&o.audioRecv.find((t=>t.ssrc===e));if(d){const e=Fne;null!=a.packets&&null!=d.packets&&Kne(c,Mne.Audio_Recv_Package_Rate,1e3*(a.packets-d.packets)/e),null!=a.packetsLost&&null!=d.packetsLost&&Kne(c,Mne.Audio_Recv_Package_Lost,a.packetsLost-d.packetsLost)}if(i){const e=a.receivedFrames,t=a.droppedFrames;null!=e&&null!=t&&(c[Lne.Audio_Recv_Freeze]=0===(l=e)||100*t/l>20?1:0)}var l;if(r){const t=100*n._source.getAccurateVolumeLevel(),i=a.outputLevel;if(null!=i){const e=Math.ceil(50*Math.log10(100*i+1));Kne(c,kne.Audio_Render_Level,e)}Kne(c,kne.Audio_Recv_PCM_Level,t),n&&(c[kne.Audio_Recv_Disabled]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1),Kne(c,kne.Audio_Recv_Jitter_Buffer,a.jitterBufferMs),Kne(c,kne.Audio_Recv_Current_Delay,a.jitterBufferMs),c[kne.Audio_Recv_Player_Status]=aM[KM.getPlayerState(n.getTrackId())];const o=r.audioRecv.find((t=>t.ssrc===e));if(o&&(null!=o.bytes&&null!=a.bytes&&Kne(c,kne.Audio_Recv_Bitrate,8*(a.bytes-o.bytes)/(Fne*jne)),!s)){const e=a.concealedSamples-o.concealedSamples;e>0&&Kne(c,kne.Audio_Recv_Concealed_Samples,e);const t=a.totalSamplesReceived-o.totalSamplesReceived;t>0&&Kne(c,kne.Audio_Recv_Total_Samples_Received,t);const n=a.freezeSamples80-o.freezeSamples80;n>0&&Kne(c,kne.Audio_Render_Freeze_Samples_80ms,n);const i=a.freezeSamples200-o.freezeSamples200;i>0&&Kne(c,kne.Audio_Render_Freeze_Samples_200ms,i);const r=a.freezeMs80-o.freezeMs80;Kne(c,kne.Audio_Render_Freeze_Time_80ms,r<0?0:r);const s=a.freezeMs200-o.freezeMs200;Kne(c,kne.Audio_Render_Freeze_Time_200ms,s<0?0:s)}}return c}(a._audioSSRC,e,a.audioTrack,t,n,i,r):void 0;if(o&&(d.audio=o),a.audioTrack&&l){const t=e.audioRecv.find((e=>e.ssrc===a._audioSSRC));if(t&&t.estimatedPlayoutTimestamp){const e=t.estimatedPlayoutTimestamp-l;d.audio?d.audio[Mne.Audio_Recv_AV_Sync_TIME]=e:d.audio={[Mne.Audio_Recv_AV_Sync_TIME]:e}}}}(d.video||d.audio)&&o.push(d)})),this.needUploadRenderFreezeTime=!this.needUploadRenderFreezeTime,o}startUploadTransportStats(){this.uploadTransportStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats()}stopUploadTransportStats(){this.uploadTransportStarted=!1}startUploadOutboundStats(){this.uploadOutboundStarted||(this.uploadOutboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=window.setInterval((()=>{if(!this.requestAllTracks||!this.requestUpload)return;const e=(this.requestAllTracks()||[]).find((e=>e instanceof XU));if(e&&e._external.getDenoiserStats){const t=e._external.getDenoiserStats();t&&this.requestUpload(CF.DENOISER_STATS,t)}}),2e3),this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=window.setInterval((()=>{if(!this.requestAllTracks||!this.requestUpload)return;this.requestAllTracks().forEach((e=>{e.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}))}),2e3))}stopUploadOutboundStats(){this.uploadOutboundStarted&&(this.uploadOutboundStarted=!1,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRefSendStats&&(this.lastRefSendStats.videoSend=[],this.lastRefSendStats.audioSend=[],this.lastRefSendStats=void 0),this.lastNormalSendStats&&(this.lastNormalSendStats.videoSend=[],this.lastNormalSendStats.audioSend=[],this.lastNormalSendStats=void 0),this.lastExtendStats={},this.needUploadStats={},this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=void 0,this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=void 0)}startUploadInboundStats(){this.uploadInboundStarted||(this.uploadInboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=window.setInterval((()=>{if(!this.requestUpload||!this.requestRemoteMedia)return;(this.requestRemoteMedia()||[]).forEach((e=>{let t=Hb(e,2),n=t[0],i=t[1];if(i.has(nB.VIDEO)&&n.videoTrack){n.videoTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}if(i.has(nB.AUDIO)&&n.audioTrack){n.audioTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}}))}),2e3))}stopUploadInboundStats(){this.uploadInboundStarted&&(this.uploadInboundStarted=!1,this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0),this.lastRefRecvStats&&(this.lastRefRecvStats.videoRecv=[],this.lastRefRecvStats.audioRecv=[],this.lastRefRecvStats=void 0),this.lastNormalRecvStats&&(this.lastNormalRecvStats.videoRecv=[],this.lastNormalRecvStats.audioRecv=[],this.lastNormalRecvStats=void 0),this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0,this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=void 0)}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer);const e=new Map;this.uploadExtUsageStatsTimer=window.setInterval((async()=>{const t=Date.now(),n={connectionInterval:rL("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:t};let i=[];const r=this.requestAllTracks&&this.requestAllTracks()||[];for(const e of r)!e.muted&&e.enabled&&(i=i.concat(await e.getProcessorUsage()));const o=this.requestRemoteMedia&&this.requestRemoteMedia()||[];for(const e of o){var s=Hb(e,2);const t=s[0],n=s[1];n.has(nB.VIDEO)&&t.videoTrack&&(i=i.concat(await t.videoTrack.getProcessorUsage())),n.has(nB.AUDIO)&&t.audioTrack&&(i=i.concat(await t.audioTrack.getProcessorUsage()))}if(0===i.length)return;n.details=function(e,t){const n={};for(const s of e){var i;const e=s.id,a=s.value,c=s.level,d=s.direction,l=null!==(i=t.get(e))&&void 0!==i?i:0,u=2===a?l+rL("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:l;var r,o;t.set(e,u),n[e]?(2===a&&(n[e].value=a),c>n[e].level&&(n[e].level=c),"remote"===d&&(n[e].remoteUidCount+=1),n[e].totalTs=null!==(r=t.get(e))&&void 0!==r?r:0):n[e]={value:a,level:c,remoteUidCount:"local"===d?0:1,totalTs:null!==(o=t.get(e))&&void 0!==o?o:0}}return Object.keys(n).map((e=>{const t=n[e];return{id:e,level:t.level,value:t.value,totalTs:t.totalTs}}))}(i,e);const a=Date.now(),c=a>t?a:t+1;this.requestUpload&&this.requestUpload(CF.EXTENSION_USAGE_STATS,{usageStats:n,sendTs:c})}),rL("EXTENSION_USAGE_UPLOAD_INTERVAL"))}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0)}stopUploadBaseStats(){this.uploadBaseStatsStarted=!1,sx.stopCollectStats()}}const Jne=rL("ICE_RESTART_INTERVAL");let zne=new Map,Zne=new Map,qne=[iB.UDP_TCP_RELAY,iB.TCP_RELAY,iB.RELAY],Qne=rL("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&_k().supportPCSetConfiguration;function $ne(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=zne.get(e.id);n&&(window.clearTimeout(n),zne.delete(e.id));const i=Zne.get(e.id);t&&i&&i.index===qne.length-1&&(FL.debug("[".concat(e.id,"] reset ICE restart policy")),Zne.delete(e.id))}function eie(e,t,n){if(0===zne.size&&0===Zne.size&&(Array.isArray(rL("RESTART_SEQUENCE"))&&rL("RESTART_SEQUENCE").length>0&&!function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n];if(e.filter((e=>e===i)).length!==t.filter((e=>e===i)).length)return!1}return!0}(qne,rL("RESTART_SEQUENCE"))&&(qne=rL("RESTART_SEQUENCE").filter((e=>{var t;if(Vi(t=Object.values(iB)).call(t,e))return!0})),FL.debug("use reconnection policy from config distribution, queues: ".concat(qne.join(" => ")))),Qne=rL("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&_k().supportPCSetConfiguration),0===qne.length)return void n();let i,r=Zne.get(e.id)||{},o=r.index,s=void 0===o?0:o,a=r.type;if(Qne&&a===iB.RELAY)return void n();let c=a&&s>=qne.length-1;if(Qne)a=iB.RELAY;else{if(c)return void n();a?(s++,a=qne[s]):(a=qne[0],s=0)}FL.debug("[".concat(e.id,"] choose ICE restart policy: ").concat(a,", index: ").concat(s)),t(a),Zne.set(e.id,{index:s,type:a}),i=window.setTimeout((()=>eie(e,t,n)),Jne),zne.set(e.id,i)}var tie;function nie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function iie(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?nie(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):nie(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function rie(e){var t,n,i,r=2;for("undefined"!=typeof Symbol&&(n=TO,i=Symbol.iterator);r--;){if(n&&null!=(t=e[n]))return t.call(e);if(i&&null!=(t=e[i]))return new oie(t.call(e));n="@@asyncIterator",i="@@iterator"}throw new TypeError("Object is not async iterable")}function oie(e){function t(e){if(Object(e)!==e)return dp.reject(new TypeError(e+" is not an object."));var t=e.done;return dp.resolve(e.value).then((function(e){return{value:e,done:t}}))}return oie=function(e){this.s=e,this.n=e.next},oie.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return void 0===n?dp.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return void 0===n?dp.reject(e):t(n.apply(this.s,arguments))}},new oie(e)}let sie=(tie=class extends hD{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(cB.StateChange,t,this._state)}constructor(e,t){super(),GA(this,"isPlanB",void 0),GA(this,"store",void 0),GA(this,"statsUploader",void 0),GA(this,"connection",void 0),GA(this,"localTrackMap",new Map),GA(this,"remoteUserMap",new Map),GA(this,"localDataChannels",[]),GA(this,"remoteDataChannelMap",new Map),GA(this,"pendingLocalTracks",[]),GA(this,"pendingRemoteTracks",[]),GA(this,"pendingLocalDataChannels",[]),GA(this,"pendingRemoteDataChannels",[]),GA(this,"statsCollector",void 0),GA(this,"shouldForwardP2PCreation",void 0),GA(this,"iceFailedCount",0),GA(this,"dtlsFailedCount",0),GA(this,"mutex",void 0),GA(this,"_state",aB.Disconnected),GA(this,"_p2pBySDPEndPoint",!1),GA(this,"_pcStatsUploadType",rL("NEW_ICE_RESTART")?rB.FIRST_CONNECTION:rB.OLD_FIRST_CONNECTION),GA(this,"_isStartRestartIce",!1),GA(this,"_restartTimer",void 0),GA(this,"_isTryConnecting",!1),GA(this,"_iceError",null),GA(this,"_forceTurn",!1),GA(this,"_isWaitPcToRePub",!1),GA(this,"handleMuteLocalTrack",(async(e,t,n)=>{const i=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==aB.Connected)return void n(new zN(JN.INVALID_OPERATION,"Cannot call P2PChannel.handleMuteLocalTrack before connection established."));const r=this.filterTobeMutedTracks(e);if(0===r.length)return void t();const o=r.find((e=>"videoLowTrack"===e[0]));if(o){const e=o[1];this.store.enableInstantMuteRestore?(e.track._originMediaStreamTrack.enabled=!1,FL.info("[".concat(this.store.clientId,"] P2PChannel muteLocalLowTrack without close sender because enableInstantMuteRestore is true"))):e.track._originMediaStreamTrack.stop()}this.store.enableInstantMuteRestore?FL.info("[".concat(this.store.clientId,"] P2PChannel muteLocalTrack without close sender because enableInstantMuteRestore is true")):await this.connection.muteLocal(r.map((e=>Hb(e,2)[1].id)));const s=this.createMuteMessage(r);await ND(this,cB.RequestMuteLocal,s),t()}catch(e){n(e)}finally{i()}})),GA(this,"handleUnmuteLocalTrack",(async(e,t,n)=>{const i=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==aB.Connected)return void n(new zN(JN.INVALID_OPERATION,"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established."));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();const o=r.find((e=>"videoLowTrack"===e[0]));if(o){const t=o[1];if(this.store.enableInstantMuteRestore)t.track._originMediaStreamTrack.enabled=!0,FL.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalLowTrack without close sender because enableInstantMuteRestore is true"));else{if(t.track._originMediaStreamTrack.stop(),!rL("DISABLE_DUAL_STREAM_USE_ENCODING")&&_k().supportDualStreamEncoding){const n=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=n,t.track._originMediaStreamTrack=n}else{const n=Dne(e,PD(this,cB.RequestLowStreamParameter));t.track._mediaStreamTrack=n,t.track._originMediaStreamTrack=n}await new dp(((e,n)=>{this.handleReplaceTrack(t.track,e,n,!0)}))}}this.store.enableInstantMuteRestore?FL.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalTrack without close sender because enableInstantMuteRestore is true")):await this.connection.unmuteLocal(r.map((e=>Hb(e,2)[1].id)));const s=this.createUnmuteMessage(r);await ND(this,cB.RequestUnmuteLocal,s),t()}catch(e){n(e)}finally{i()}})),GA(this,"handleUpdateVideoEncoder",(async(e,t,n,i)=>{let r;i||(r=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoEncoder"));try{const n=this.localTrackMap.get(sB.LocalVideoTrack);if(!this.connection||!n||n.track!==e||this.state!==aB.Connected)return void t();const i=n.id,s=n.track;await this.connection.updateSendParameters(i,s),await this.connection.updateEncoderConfig(i,s),this.emit(cB.UpdateVideoEncoder,s),t()}catch(e){n(e)}finally{var o;null===(o=r)||void 0===o||o()}})),GA(this,"handleUpdateVideoSendParameters",(async(e,t,n)=>{const i=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoSendParameters");try{const n=this.localTrackMap.get(sB.LocalVideoTrack);if(!this.connection||!n||n.track!==e||this.state!==aB.Connected)return void t();const r=n.id,o=n.track;await this.connection.updateSendParameters(r,o),t()}catch(e){n(e)}finally{i()}})),GA(this,"handleReplaceMixingTrack",(async(e,t,n,i)=>{if(!this.connection||this.state!==aB.Connected)return void t();const r=Rne([e]);let o;FL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(r.getTrackId(),"]")),"boolean"==typeof i&&i||(o=await this.mutex.lock("From P2PChannel.handleReplaceMixingTrack"));try{await this.replaceTrack(e,r),t()}catch(e){n(e)}finally{var s;null===(s=o)||void 0===s||s()}})),GA(this,"handleReplaceTrack",(async(e,t,n,i)=>{let r;FL.debug("[".concat(this.store.clientId,"] P2PChannel handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof i&&i||(r=await this.mutex.lock("From P2PChannel.handleReplaceTrack"));try{var o;const n=Array.from(this.localTrackMap.entries()).find((t=>{let n=Hb(t,2)[1].track;return e===n}));if(!this.connection||!n||this.state!==aB.Connected)return void t();if(await(null===(o=this.connection)||void 0===o?void 0:o.replaceTrack(e,n[1].id)),this.isPlanB){const t=n[1];t.id=e._mediaStreamTrack.id,this.localTrackMap.set(n[0],t)}if(n[0]===sB.LocalVideoTrack&&!rL("DISABLE_DUAL_STREAM_USE_ENCODING")&&_k().supportDualStreamEncoding){const t=this.localTrackMap.get(sB.LocalVideoLowTrack);if(t){const n=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=n,t.track._originMediaStreamTrack=n,await new dp(((e,n)=>{this.handleReplaceTrack(t.track,e,n,!0)}))}}t()}catch(e){n(e)}finally{var s;null===(s=r)||void 0===s||s()}})),GA(this,"handleGetRTCStats",(e=>{e(this.statsCollector.getRTCStats())})),GA(this,"handleGetLocalVideoStats",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),GA(this,"handleGetLocalAudioStats",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),GA(this,"handleGetRemoteVideoStats",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),GA(this,"handleGetRemoteAudioStats",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new Xne(this.store),this.bindStatsUploaderEvents(),this.mutex=new _P("P2PChannel-mutex",this.store.clientId),this.isPlanB=!_k().supportUnifiedPlan||rL("CHROME_FORCE_PLAN_B")&&FN(),this.shouldForwardP2PCreation=rL("FORWARD_P2P_CREATION")&&_k().supportPCSetConfiguration&&xN(),this.shouldForwardP2PCreation&&this.recreateConnection()}async startP2PConnection(e,t){var n;this.state=aB.New,this._forceTurn=Cne(e),FL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] forceTurn: ").concat(this._forceTurn));const i=this.shouldForwardP2PCreation&&"closed"===(null===(n=this.connection)||void 0===n?void 0:n.peerConnectionState);if((!this.shouldForwardP2PCreation||i||t)&&((i||t)&&this.connection&&(FL.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.resetConnection(this.connection)),this.recreateConnection(e)),!this.connection)throw new zN(JN.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=rL("NEW_ICE_RESTART")?rB.FIRST_CONNECTION:rB.OLD_FIRST_CONNECTION,this._isTryConnecting=!0,this._isStartRestartIce=!1,this._iceError=null,this.connection.setConfiguration(e),this.connection.establishPromise}updateConnectionConfiguration(e){var t;null===(t=this.connection)||void 0===t||t.setConfiguration(e),this._p2pBySDPEndPoint=!0}async connect(e){if(!this.connection)throw new zN(JN.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");if(!this.isPreallocation()||this.state!==aB.Connected){this.store.peerConnectionStart();const t=await this.connection.connect(e);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=aB.Connected,t}if(this.connection instanceof One||this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name){const t=this.connection.checkDtlsParameters(e.dtlsParameters.fingerprints),n=Xee(e.iceParameters.iceUfrag,e.iceParameters.icePwd);n||FL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] ice parameters mismatch, length: ").concat(e.iceParameters.iceUfrag.length," / ").concat(e.iceParameters.icePwd.length));const i=this.connection.checkIceParameters(e.iceParameters),r=t||!n||i&&!(this.connection instanceof One);if(r||i){FL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] dtls parameters mismatch, ").concat(r?"try next":"restart ICE"));uk.reportApiInvoke(this.store.sessionId,{name:t?ED.MISMATCH_DTLS_PARAMETERS:ED.MISMATCH_ICE_PARAMETERS,options:t?[e.dtlsParameters.fingerprints]:[e.iceParameters],tag:mD.TRACER}).onSuccess(),setTimeout((()=>{r?this.emit(cB.RequestReconnect):i&&this.emit(cB.RequestRestartICE,iB.UDP_RELAY)}))}}await this.connection.updateRemoteConnect(e)}updateRemoteRTPCapabilities(e){const t=Array.from(this.localTrackMap.entries()).filter((e=>{var t;let n=Hb(e,1)[0];return Vi(t=[sB.LocalVideoLowTrack,sB.LocalVideoTrack]).call(t,n)})),n=t.map((e=>Hb(e,2)[1].id)),i=t.map((e=>Hb(e,1)[0]));if(this.connection instanceof One||this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name){if(uk.updateRemoteRTPCapabilities(this.store.sessionId,{trackTypes:JSON.stringify(i),localCodecs:JSON.stringify(this.connection.localCodecs),remoteCodecs:JSON.stringify(e)}),!Vi(e).call(e,this.store.codec)){const t=["vp9","vp8","h264"].find((t=>Vi(e).call(e,t)));t&&(this.store.codec=t,FL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId," updateRemoteRTPCapabilities] default codec is not available, hence the fallback to ").concat(t,".")))}this.connection.updateRemoteRTPCapabilities(n,e)}}async getEstablishParams(){var e;return this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name&&"closed"!==this.connection.peerConnectionState||this.connection instanceof One&&"closed"!==this.connection.peerConnectionState&&Vi(e=[aB.New,aB.Connected]).call(e,this.state)?this.connection.establishPromise:void 0}async publishDataChannel(e){if(!this.connection||this.state!==aB.Connected){if(this.state===aB.Disconnected)throw new zN(JN.UNEXPECTED_ERROR,"PeerConnection already disconnected.");return e.forEach((e=>{var t;Vi(t=this.pendingLocalDataChannels).call(t,e)||this.pendingLocalDataChannels.push(e)})),[]}const t=this.filterTobePublishedDataChannels(e);return 0===t.length?[]:(t.forEach((e=>{const t=Date.now();this.store.publish(e.id.toString(),"datachannel",t)})),await this.connection.createDataChannels(this.store.uid,t),t.forEach((e=>{this.localDataChannels.push(e);const t=Date.now();this.store.publish(e.id+"","datachannel",void 0,t)})),e.map((e=>({streamId:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,metadata:e.metadata,channelId:e._originDataChannelId}))))}publish(e,t,n){var i=this;return mO((function*(){const r=yield gO(i.mutex.lock("From P2PChannel.publish"));try{var o;const s=i.connection&&Vi(o=["disconnected","failed"]).call(o,i.connection.peerConnectionState);if(!i.connection||i.state!==aB.Connected||s){if(i.state===aB.Disconnected)throw new zN(JN.UNEXPECTED_ERROR,"PeerConnection already disconnected.");i.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===i.pendingLocalTracks.indexOf(e)));return i.pendingLocalTracks=i.pendingLocalTracks.concat(t),void(s&&(i._isWaitPcToRePub=!0))}i.store.pubId=i.store.pubId+1,Hte.markPublishStart(i.store.clientId,i.store.pubId);const a=i.filterTobePublishedTracks(e,t,n);if(0===a.length)return void(yield gO(i.tryToUnmuteAudio(e)));yield*SO(rie(i.doPublish(i.connection,a)))}finally{r()}}))()}doPublish(e,t){var n=this;return mO((function*(){t.forEach((e=>{let t=e.track,i=e.type;const r=Date.now();n.store.publish(t.getTrackId(),i===sB.LocalAudioTrack?"audio":"video",r)})),n.bindLocalTrackEvents(t);const i=t.map((e=>e.track)),r=yield gO(e.send(i,n.store.codec,n.store.audioCodec)),o=(yield gO(r.next())).value,s=n.createGatewayPublishMessage(t,o);let a;try{a=yield s}catch(e){throw r.throw(e),(null==e?void 0:e.code)===JN.WS_ABORT&&t.forEach((e=>{let t=e.track;-1===n.pendingLocalTracks.indexOf(t)&&n.pendingLocalTracks.push(t)})),n.unbindLocalTrackEvents(t),e}const c=n.mapPubResToRemoteConfig(s,a,i),d=(yield gO(r.next(c))).value;if(n.state===aB.Disconnected)throw new zN(JN.UNEXPECTED_ERROR,"PeerConnection already disconnected.");rL("ENABLE_VIDEO_SEI");const l=rL("ENABLE_ENCODED_TRANSFORM"),u=rL("ENABLE_AUDIO_METADATA");i.forEach((async e=>{const t=e.getRTCRtpTransceiver();if(!t||!l)return;const n=Yee(),i=n.interceptLocalVideoFrame,r=n.interceptLocalAudioFrame;e.trackMediaType===nB.VIDEO?await i(t.sender,e):e.trackMediaType===nB.AUDIO&&await r(t.sender,{metadata:u?()=>{const t=e.metadata.shift();return t&&t.value}:void 0})})),t.forEach((e=>{let t=e.type;n.statsCollector.addLocalStats(t)})),n.assignLocalTracks(t,d),n.statsUploader.startUploadOutboundStats(),t.forEach((e=>{let t=e.track,i=e.type;const r=Date.now();n.store.publish(t.getTrackId(),i===sB.LocalAudioTrack?"audio":"video",void 0,r)}))}))()}async updateVideoStreamParameter(e,t){const n=this.localTrackMap.get(t);if(!n||!this.connection)return;if(!(n.track instanceof BV))return FL.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");const i=n.track,r=function(e,t){const n={};return e.height&&e.width&&(n.scaleResolutionDownBy=tee(e,t)),n.maxFramerate=e.framerate?Z7(e.framerate):void 0,n.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,n}(e,i);if(i._encoderConfig||(i._encoderConfig={}),t!==sB.LocalVideoLowTrack||!rL("DISABLE_DUAL_STREAM_USE_ENCODING")&&_k().supportDualStreamEncoding)null!=r.scaleResolutionDownBy&&(i._encoderConfig.scaleResolutionDownBy=r.scaleResolutionDownBy);else{const t=i._originMediaStreamTrack;if(!t.canvas)return FL.warn("[".concat(i.getTrackId(),"] no canvas on track"));!function(e,t){const n=e.canvas;t.width&&(n.width=Z7(t.width)),t.height&&(n.height=Z7(t.height)),t.framerate&&(n.stopCapture&&n.stopCapture(),n.stopCapture=bM((()=>{!n.startCapture&&n.stopCapture&&n.stopCapture(),n.startCapture&&n.startCapture()}),Z7(t.framerate)))}(t,e)}null!=r.maxBitrate&&(i._encoderConfig.bitrateMax=r.maxBitrate/1e3),null!=r.maxFramerate&&(i._encoderConfig.frameRate&&"object"==typeof i._encoderConfig.frameRate?i._encoderConfig.frameRate.max=r.maxFramerate:i._encoderConfig.frameRate={max:r.maxFramerate}),FL.debug("[".concat(i.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(i._encoderConfig))),await this.connection.updateRtpSenderEncodings(i)}publishLowStream(e){var t=this;return mO((function*(){if(!t.connection||t.state!==aB.Connected)return;const n=yield gO(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const r=t.localTrackMap.get(sB.LocalVideoTrack);if(!r)throw new zN(JN.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(sB.LocalVideoLowTrack))throw new zN(JN.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const o=[{track:t.getLowVideoTrack(r.track,e),type:sB.LocalVideoLowTrack}];if(yield*SO(rie(t.doPublish(t.connection,o))),r.track.muted||!r.track.enabled){var i;const e=null===(i=t.localTrackMap.get(sB.LocalVideoLowTrack))||void 0===i?void 0:i.id;void 0!==e&&(yield gO(t.connection.muteLocal([e])))}}finally{n()}}))()}async republish(){this.pendingLocalTracks.length>0&&(FL.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await OD(this,cB.RequestRePublish,this.pendingLocalTracks),this.emit(cB.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(FL.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await OD(this,cB.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[]),this._isWaitPcToRePub=!1}async reSubscribe(e){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){const t=this.pendingRemoteTracks[e],n=t.user,i=t.kind;(i!==nB.AUDIO||n._audio_added_&&n._audioSSRC)&&(i!==nB.VIDEO||n._video_added_&&n._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await OD(this,cB.RequestReSubscribe,this.pendingRemoteTracks);else for(const e of this.pendingRemoteTracks){const t=e.user,n=e.kind;await this.subscribe(t,n,n===nB.VIDEO?t._videoSSRC:t._audioSSRC)}this.pendingRemoteTracks.forEach((e=>{let t=e.user;this.emit(cB.MediaReconnectEnd,t.uid)})),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==aB.Connected)return void e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const n=t.find((e=>"videoLowTrack"===e[0]));if(n){n[1].track.close()}return this.doUnpublish(this.connection,t)}async unpublishDataChannel(e){if(!this.connection||this.state!==aB.Connected)return void e.forEach((e=>{const t=this.pendingLocalDataChannels.indexOf(e);-1!==t&&this.pendingLocalDataChannels.splice(t,1)}));const t=this.filterTobeUnpublishedDataChannels(e);return 0!==t.length?(t.forEach((e=>{const t=this.localDataChannels.indexOf(e);-1!==t&&this.localDataChannels.splice(t,1)})),0===this.localDataChannels.length&&await this.connection.stopDataChannels(this.store.uid),t.map((e=>e.id))):void 0}async unpublishLowStream(){if(!this.connection||this.state!==aB.Connected)return;const e=this.localTrackMap.get(sB.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[sB.LocalVideoLowTrack,e]];return this.doUnpublish(this.connection,t)}async doUnpublish(e,t){const n=this.createGatewayUnpublishMessage(t);return await e.stopSending(t.map((e=>Hb(e,2)[1].id))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let t=Hb(e,2);return{type:t[0],track:t[1].track}}))),t.forEach((e=>{let t=Hb(e,1)[0];this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&this.statsUploader.stopUploadOutboundStats(),n}async subscribeDataChannel(e,t){if(!this.connection||this.state!==aB.Connected)throw new zN(JN.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");const n=t.filter((t=>{var n;return!(null!==(n=this.remoteDataChannelMap.get(e))&&void 0!==n&&n.get(t.id))}));if(0!==n.length)return await this.connection.createDataChannels(e.uid,n),n.forEach((t=>{var n;this.remoteDataChannelMap.has(e)?null===(n=this.remoteDataChannelMap.get(e))||void 0===n||n.set(t.id,t):this.remoteDataChannelMap.set(e,new Map([[t.id,t]]));const i=this.pendingRemoteDataChannels.findIndex((n=>{let i=n.user,r=n.id;return i.uid===e.uid&&r===t.id}));-1!==i&&this.pendingRemoteDataChannels.splice(i,1)})),n.map((e=>e.id))}async subscribe(e,t,n,i,r){var o;if(!this.connection||this.state!==aB.Connected)throw new zN(JN.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if(null!==(o=this.remoteUserMap.get(e))&&void 0!==o&&o.has(t))return;let s,a,c,d;const l=this.connection.getPreMedia(n);if(l)FL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] preSSRCMap has ssrcId: ").concat(n,", no need to send sub to gateway.")),c=l.transceiver,s=l.track,a=l.mid,d=l.player,l.firstVideoRender&&this.store.firstVideoFrameDecoded(e.uid,{firstPreRender:l.firstVideoRender});else if(r){const n=r.find((e=>e.stream_type===t));if(!n)throw new zN(JN.UNEXPECTED_ERROR,"Cannot subscribe to remote ".concat(t," for user: ").concat(e.uid," because subscribe answer from gateway does not contain stream_type: ").concat(t,"."));const i=await this.connection.receive(t,n.ssrcs,String(e._uintid),n.attributes);(this.connection instanceof One||"name"in this.connection&&"DataChannelConnection"===this.connection.name)&&(c=i.transceiver),s=i.track,a=i.id}else{const r=await this.connection.receive(t,[{ssrcId:n,rtx:i}],String(e._uintid),void 0);(this.connection instanceof One||"name"in this.connection&&"DataChannelConnection"===this.connection.name)&&(c=r.transceiver),s=r.track,a=r.id}if(t===nB.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new ox(s,e.uid,e._uintid,this.store),FL.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new rx(s,e.uid,e._uintid,this.store,d),FL.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId())),e._videoTrack.once(Xk.PLAY_START,(()=>{this.store.firstVideoFrameDecoded(e.uid,{playStart:Date.now()})})),e._videoTrack.once(Xk.PLAY_END,(()=>{this.store.firstVideoFrameDecoded(e.uid,{playEnd:Date.now()}),this.reportVideoFirstFrameRender(e)})),d?e._videoTrack.once(Xk.FIRST_FRAME_RENDER,(()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)})):e._videoTrack.once(Xk.FIRST_FRAME_DECODED,(()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)}))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack)),c&&rL("ENABLE_ENCODED_TRANSFORM")){const n=Yee(),i=n.interceptRemoteVideoFrame,r=n.interceptRemoteAudioFrame;t==nB.VIDEO?await i(c.receiver,{onSei:rL("ENABLE_VIDEO_SEI")&&(t=>{var n;return null===(n=e._videoTrack)||void 0===n?void 0:n._onSei(t)}),onFirstFrame:e=>{var t;const n=Array.from(CL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e.ssrc));n&&this.store.firstVideoFrameDecoded(n.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):t==nB.AUDIO&&await r(c.receiver,{enableTopn:!!rL("ENABLE_AUDIO_TOPN"),enableMetadata:!!rL("ENABLE_AUDIO_METADATA"),enablePts:!!rL("ENABLE_AUDIO_PTS"),onMetadata:e=>{this.safeEmit(cB.AudioMetadata,e)},onPts:e=>{this.safeEmit(cB.AudioPts,e)}})}const u=this.remoteUserMap.get(e);u?u.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const h=this.pendingRemoteTracks.findIndex((n=>{let i=n.user,r=n.kind;return i.uid===e.uid&&t===r}));-1!==h&&(this.pendingRemoteTracks.splice(h,1),this.emit(cB.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==aB.Connected)throw new zN(JN.INVALID_OPERATION,"Cannot subscribeAll remote users when peerConnection disconnected.");e=e.filter((e=>{var t;let n=e.user,i=e.mediaType;return!(null!==(t=this.remoteUserMap.get(n))&&void 0!==t&&t.has(i))}));const t=[],n=new Map;e.forEach((e=>{if(!this.connection)return;const i=this.connection.getPreMedia(e.ssrcId);if(i){const t=i.track,r=i.mid,o=i.transceiver,s=i.player;n.set(e.ssrcId,{track:t,id:r,transceiver:o,player:s})}else t.push(e)}));const i=await this.connection.batchReceive(t.map((e=>{let t=e.user;return{kind:e.mediaType,ssrcMsg:[{ssrcId:e.ssrcId,rtx:e.rtxSsrcId}],mslabel:String(t._uintid)}})));t.forEach(((e,t)=>{n.set(e.ssrcId,i[t])}));for(const t of e){const e=t.user,i=t.mediaType,r=t.ssrcId,o=n.get(r);if(!o)return void FL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] cannot find ").concat(e.uid," subscribe data,").concat(i,", ").concat(r));const s=o.track,a=o.id,c=o.transceiver,d=o.player;if(c&&rL("ENABLE_ENCODED_TRANSFORM")){const t=Yee(),n=t.interceptRemoteVideoFrame,r=t.interceptRemoteAudioFrame;i==nB.VIDEO?await n(c.receiver,{onSei:rL("ENABLE_VIDEO_SEI")&&(t=>{var n;return null===(n=e._videoTrack)||void 0===n?void 0:n._onSei(t)}),onFirstFrame:e=>{var t;const n=Array.from(CL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e.ssrc));n&&this.store.firstVideoFrameDecoded(n.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):i==nB.AUDIO&&await r(c.receiver,{enableTopn:!!rL("ENABLE_AUDIO_TOPN"),enableMetadata:!!rL("ENABLE_AUDIO_METADATA"),enablePts:!!rL("ENABLE_AUDIO_PTS"),onMetadata:e=>{this.safeEmit(cB.AudioMetadata,e)},onPts:e=>{this.safeEmit(cB.AudioPts,e)}})}if(i===nB.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new ox(s,e.uid,e._uintid,this.store),FL.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new rx(s,e.uid,e._uintid,this.store,d),FL.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack)),rL("ENABLE_VIDEO_SEI")&&c){const t=Yee(),n=t.interceptRemoteVideoFrame,r=t.interceptRemoteAudioFrame;i==nB.VIDEO?await n(c.receiver,{onSei:t=>{var n;null===(n=e._videoTrack)||void 0===n||n._onSei(t)},onFirstFrame:e=>{var t;const n=Array.from(CL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e.ssrc));n&&this.store.firstVideoFrameDecoded(n.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):i==nB.AUDIO&&await r(c.receiver)}const l=this.remoteUserMap.get(e);l?l.set(i,a):this.remoteUserMap.set(e,new Map([[i,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const u=this.pendingRemoteTracks.findIndex((t=>{let n=t.user,r=t.kind;return n.uid===e.uid&&i===r}));-1!==u&&(this.pendingRemoteTracks.splice(u,1),this.emit(cB.MediaReconnectEnd,e.uid))}}async unsubscribe(e,t,n){const i=this.pendingRemoteTracks.filter((n=>{let i=n.user,r=n.kind;return void 0!==t?i.uid===e.uid&&t===r:i.uid===e.uid}));if(i.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.connection&&this.state===aB.Connected||n||i.forEach((t=>{let n=t.kind;var i;if(n===nB.AUDIO)null===(i=e._audioTrack)||void 0===i||i._destroy(),e._audioTrack=void 0;else if(n===nB.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.connection||this.state!==aB.Connected)return;const r=this.filterTobeUnSubscribedTracks(e,t);if(0===r.length)return;await this.connection.stopReceiving(r.map((e=>Hb(e,2)[1].id)));const o=this.createUnsubscribeMessage(r);return this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),r.forEach((e=>{let t=Hb(e,2),i=t[0],r=t[1].kind;var o,s;r===nB.VIDEO&&i._videoSSRC&&(null===(o=this.connection)||void 0===o||o.setStatsRemoteVideoIsReady(i._videoSSRC,!1));if(r===nB.VIDEO)this.unbindRemoteTrackEvents(i._videoTrack),n||(null===(s=i._videoTrack)||void 0===s||s._destroy(),i._videoTrack=void 0);else if(r===nB.AUDIO){var a;if(this.unbindRemoteTrackEvents(i._audioTrack),!n)null===(a=i._audioTrack)||void 0===a||a._destroy(),i._audioTrack=void 0}})),o}async unsubscribeDataChannel(e,t){if(t.forEach((e=>{const t=this.pendingRemoteDataChannels.findIndex((t=>t.id===e.id));-1!==t&&this.pendingRemoteDataChannels.splice(t,1)})),!this.connection)return;const n=this.filterTobeUnSubscribedDataChannels(e,t);if(0===n.length)return;t.forEach((e=>{e._close()}));const i=this.remoteDataChannelMap.get(e);return n.forEach((e=>{i&&i.delete(e.id)})),i&&0===i.size&&(this.remoteDataChannelMap.delete(e),await this.connection.stopDataChannels(e.uid)),n.map((e=>e.id))}async massUnsubscribe(e){return this.massUnsubscribeNoLock(e)}async massUnsubscribeNoLock(e){let t=[];for(const n of e){const e=n.user,i=n.mediaType,r=this.pendingRemoteTracks.filter((t=>{let n=t.user,r=t.kind;return void 0!==i?n.uid===e.uid&&i===r:n.uid===e.uid}));r.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),t=t.concat(r)}if(!this.connection||this.state!==aB.Connected)return void t.forEach((e=>{let t=e.user,n=e.kind;var i;if(n===nB.AUDIO)null===(i=t._audioTrack)||void 0===i||i._destroy(),t._audioTrack=void 0;else if(n===nB.VIDEO){var r;null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0}}));const n=ar(e).call(e,((e,t)=>{let n=t.user,i=t.mediaType;const r=this.filterTobeUnSubscribedTracks(n,i);return e.concat(r)}),[]);if(0===n.length)return;await this.connection.stopReceiving(n.map((e=>Hb(e,2)[1].id)));const i=this.createUnsubscribeAllMessage(n);return this.withdrawRemoteTracks(n),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),n.forEach((e=>{let t=Hb(e,2),n=t[0],i=t[1].kind;var r,o;i===nB.VIDEO&&n._videoSSRC&&(null===(r=this.connection)||void 0===r||r.setStatsRemoteVideoIsReady(n._videoSSRC,!1));if(i===nB.VIDEO)this.unbindRemoteTrackEvents(n._videoTrack),null===(o=n._videoTrack)||void 0===o||o._destroy(),n._videoTrack=void 0;else if(i===nB.AUDIO){var s;this.unbindRemoteTrackEvents(n._audioTrack),null===(s=n._audioTrack)||void 0===s||s._destroy(),n._audioTrack=void 0}})),i}isPreSubScribe(e){if(!this.connection||this.state!==aB.Connected)return!1;return!!this.connection.getPreMedia(e)}async muteRemote(e,t){if(!this.connection)return;const n=this.remoteUserMap.get(e);if(!n)return void FL.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid,"."));if(!n.get(t))return void FL.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const i=t===nB.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==i&&this.connection.setStatsRemoteVideoIsReady(i,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.connection)return;const n=this.remoteUserMap.get(e);if(!n)return void FL.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid,"."));n.get(t)||FL.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."))}addAudioMetadata(e){const t=this.localTrackMap.get(sB.LocalAudioTrack),n=t&&t.track;n&&n.metadata.push(e)}getAllTracks(e){const t=this.localTrackMap.get(sB.LocalAudioTrack);if((null==t?void 0:t.track)instanceof zU){const n=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>Hb(e,1)[0]!==sB.LocalAudioTrack)).filter((t=>{let n=Hb(t,1)[0];return!(e&&n===sB.LocalVideoLowTrack)})).map((e=>Hb(e,2)[1].track)).concat(n.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let n=Hb(t,1)[0];return!(e&&n===sB.LocalVideoLowTrack)})).map((e=>Hb(e,2)[1].track))}getAllDataChannels(){return this.localDataChannels}reportPublishEvent(e,t,n,i,r){if(e){const n=this.localTrackMap.get(sB.LocalAudioTrack),o=i?this.localTrackMap.get(sB.LocalVideoLowTrack):this.localTrackMap.get(sB.LocalVideoTrack);uk.publish(this.store.sessionId,{eventElapse:Hte.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==n?void 0:n.track.getTrackLabel(),videoName:null==o?void 0:o.track.getTrackLabel(),screenshare:-1!==(null==o?void 0:o.track._hints.indexOf(jk.SCREEN_TRACK)),audio:!!n,video:!!o,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var o;n||(n=[]);const s=n.find((e=>e instanceof YU)),a=i?null===(o=this.localTrackMap.get(sB.LocalVideoTrack))||void 0===o?void 0:o.track:n.find((e=>e instanceof BV));uk.publish(this.store.sessionId,{eventElapse:Hte.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==s?void 0:s.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(jk.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,n,i){const r=i===nB.VIDEO?n._videoSSRC:n._audioSSRC;r&&uk.subscribe(this.store.sessionId,{succ:e,ec:t,video:i===nB.VIDEO,audio:i===nB.AUDIO,peerid:n.uid,subscribeRequestid:r,p2pid:this.store.p2pId,eventElapse:Hte.measureFromSubscribeStart(this.store.clientId,r),preSsrc:this.isPreSubScribe(r)})}reset(){FL.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new _P("P2PChannel-mutex",this.store.clientId),this.connection&&(this.resetConnection(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&this.recreateConnection(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.statsUploader.stopUploadBaseStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(sB.LocalAudioTrack);if((null==e?void 0:e.track)instanceof zU){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach((e=>{t.removeAudioTrack(e)}))}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.iceFailedCount=0,this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.localDataChannels=[],this.remoteDataChannelMap.clear(),this.pendingLocalDataChannels=[],this.pendingRemoteDataChannels=[],this.state=aB.Disconnected}getStats(){var e;return null===(e=this.connection)||void 0===e?void 0:e.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.connection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(sB.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(sB.LocalVideoTrack);if(e)return{width:e.track.videoWidth||0,height:e.track.videoHeight||0}}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof BV||t&&t.track instanceof YU?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const n=this.remoteUserMap.get(e);return!!n&&(!t||n.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const n=this.remoteUserMap.get(e);return!!n&&(!t||n.has(t))}getRemoteMedia(e){var t;const n=Array.from(CL(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return n?{audioTrack:n.audioTrack,audioSSRC:n._audioSSRC,videoTrack:n.videoTrack,videoSSRC:n._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let t=Hb(e,1)[0];return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(sB.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=n_(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.connection&&(FL.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=aB.Reconnecting,rL("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=Hb(e,1)[0];var n;t._videoTrack&&t._videoTrack._player&&(null===(n=t._videoTrack._player.getVideoElement())||void 0===n||n.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.resetConnection(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&this.recreateConnection(),0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{var t;let n=Hb(e,2),i=n[0],r=n[1].track;switch(i){case sB.LocalVideoTrack:Vi(t=r._hints).call(t,jk.LOW_STREAM)?r.close():this.pendingLocalTracks.push(r);break;case sB.LocalAudioTrack:r instanceof zU?this.pendingLocalTracks=this.pendingLocalTracks.concat(r.trackList):this.pendingLocalTracks.push(r);case sB.LocalVideoLowTrack:}})),this.emit(cB.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=Hb(e,2),n=t[0],i=t[1];Array.from(CL(i).call(i)).forEach((e=>{this.setPendingRemoteMedia(n,e)})),this.emit(cB.MediaReconnectStart,n.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),0!==this.localDataChannels.length&&(this.localDataChannels.forEach((e=>{this.pendingLocalDataChannels.push(e)})),this.localDataChannels.length=0),0!==this.remoteDataChannelMap.size&&(Array.from(this.remoteDataChannelMap.entries()).forEach((e=>{let t=Hb(e,2),n=t[0],i=t[1];Array.from(CL(i).call(i)).forEach((e=>{this.setPendingRemoteDataChannel(n,e)}))})),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),FL.debug("[".concat(this.store.clientId,"] P2PChannel disconnected, waiting to reconnect.")))}hasPendingRemoteDataChannel(e,t){for(const n of this.pendingRemoteDataChannels){const i=n.user,r=n.id;if((e instanceof qte?e.uid:e)===i.uid&&r===t)return!0}return!1}setPendingRemoteDataChannel(e,t){this.hasPendingRemoteDataChannel(e,t)||this.pendingRemoteDataChannels.push({user:e,id:t})}hasPendingRemoteMedia(e,t){for(const n of this.pendingRemoteTracks){const i=n.user,r=n.kind;if((e instanceof qte?e.uid:e)===i.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}restartICE(e){var t=this;return mO((function*(){if(!t.connection||t.state!==aB.Connected)return;const n=yield gO(t.mutex.lock("From P2PChannel.restartICE"));let i;try{i=yield gO(t.connection.restartICE(e));const r=yield gO(i.next());if(r.done)return;const o=r.value,s=yield o;switch(bne(t.connection)&&t.reportPCStats(Date.now(),!1,t._pcStatsUploadType),e){case iB.UDP_TCP_RELAY:t._pcStatsUploadType=rB.UDP_TCP_RESTART;break;case iB.TCP_RELAY:t._pcStatsUploadType=rB.TCP_RESTART;break;case iB.RELAY:t._pcStatsUploadType=rB.RELAY_RESTART;break;default:t._pcStatsUploadType=rB.OLD_RESTART}t._isTryConnecting=!0,i.next(s)}catch(e){var r;null===(r=i)||void 0===r||r.throw(e)}finally{n()}}))()}getUplinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats(),t=this.localTrackMap.get(sB.LocalVideoTrack),n=this.localTrackMap.get(sB.LocalAudioTrack),i=e.videoSend.find((e=>e.ssrc===(null==t?void 0:t.ssrcs[0].ssrcId))),r=e.audioSend.find((e=>e.ssrc===(null==n?void 0:n.ssrcs[0].ssrcId)));if(!i||!r)return 1;const o=DD(this,cB.NeedSignalRTT),s=i?i.rttMs:void 0,a=r?r.rttMs:void 0,c=s&&a?(s+a)/2:s||a,d=(c&&o?(c+o)/2:c||o)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(jk.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,n=e.bitrate.actualEncoded;if(t&&n){const e=(1e3*t-n)/(1e3*t);return zx[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u]}}return u}getDownlinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((n=>{let i=Hb(n,1)[0];const r=i._audioSSRC,o=i._videoSSRC,s=e.audioRecv.find((e=>e.ssrc===r)),a=e.videoRecv.find((e=>e.ssrc===o));if(!s&&!a)return void(t+=1);const c=DD(this,cB.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=s?s.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new dp(((t,n)=>{this.handleMuteLocalTrack(e,t,n)}))}async replaceTrack(e,t){var n;if(FL.debug("[".concat(this.store.clientId,"] P2PChannel replaceTrack from [").concat(e.getTrackId(),"] to [").concat(t.getTrackId(),"]")),!this.connection||this.state!==aB.Connected)return;const i=Array.from(this.localTrackMap.entries()).find((t=>{let n=Hb(t,2)[1].track;return e===n}));if(!i)return;const r=i[0];if(e!==t&&(this.unbindLocalTrackEvents([{track:e,type:r}]),this.bindLocalTrackEvents([{track:t,type:r}]),i[1].track=t),await(null===(n=this.connection)||void 0===n?void 0:n.replaceTrack(t,i[1].id)),this.isPlanB){const e=i[1];e.id=t._mediaStreamTrack.id,this.localTrackMap.set(r,e)}if(r===sB.LocalVideoTrack&&!rL("DISABLE_DUAL_STREAM_USE_ENCODING")&&_k().supportDualStreamEncoding){const t=this.localTrackMap.get(sB.LocalVideoLowTrack);if(t){const n=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=n,t.track._originMediaStreamTrack=n,await new dp(((e,n)=>{this.handleReplaceTrack(t.track,e,n,!0)}))}}}filterTobePublishedTracks(e,t,n){const i=[],r=this.getAllTracks();e=BD(e=e.filter((e=>-1===r.indexOf(e))));let o,s=!1;const a=this.localTrackMap.get(sB.LocalAudioTrack);for(const r of e){if(r instanceof BV&&(this.localTrackMap.has(sB.LocalVideoTrack)||s?new zN(JN.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(i.push({track:r,type:sB.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(r,n);i.push({track:e,type:sB.LocalVideoLowTrack})}if(r instanceof YU)if(a){const e=a.track;if(e instanceof zU)Tne([r]),e.addAudioTrack(r),this.bindLocalAudioTrackEvents(r,!0);else{const t=Rne([e,r]);FL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(t.getTrackId(),"]")),this.replaceTrack(e,t)}}else if(o instanceof zU)Tne([r]),o.addAudioTrack(r);else if(o||!r._useAudioElement&&_k().webAudioMediaStreamDest&&!r._bypassWebAudio){o=Rne(o?[r,o]:[r])}else o=r}return o&&(FL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will send audioTrack [").concat(o.getTrackId(),"]")),i.push({track:o,type:sB.LocalAudioTrack})),i}filterTobeUnpublishedTracks(e){const t=[],n=this.getAllTracks();e=BD(e=e.filter((e=>-1!==n.indexOf(e))));for(const n of e){if(n instanceof YU){const e=this.localTrackMap.get(sB.LocalAudioTrack);if(!e)continue;e.track instanceof zU?(e.track.removeAudioTrack(n),this.unbindLocalAudioTrackEvents(n),0===e.track.trackList.length&&(t.push([sB.LocalAudioTrack,e]),e.track.close())):t.push([sB.LocalAudioTrack,e])}if(n instanceof BV){const e=this.localTrackMap.get(sB.LocalVideoTrack);if(!e)continue;t.push([sB.LocalVideoTrack,e]);const n=this.localTrackMap.get(sB.LocalVideoLowTrack);n&&t.push([sB.LocalVideoLowTrack,n])}}return t}filterTobePublishedDataChannels(e){return e=(e=BD(e)).filter((e=>-1===this.localDataChannels.findIndex((t=>t.id===e.id))))}filterTobeUnpublishedDataChannels(e){return e=(e=(e=BD(e)).filter((e=>-1!==this.localDataChannels.indexOf(e)))).filter((e=>e._originDataChannel))}bindLocalTrackEvents(e){e.forEach((e=>{let t=e.track;switch(e.type){case sB.LocalVideoTrack:t.addListener(Bk.GET_STATS,this.handleGetLocalVideoStats),t.addListener(Bk.GET_RTC_STATS,this.handleGetRTCStats),t.addListener(Bk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(Bk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(Bk.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(Bk.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(Bk.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(Bk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(Bk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case sB.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case sB.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof zU?e.trackList.forEach((e=>{e.addListener(Bk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(Bk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(Bk.GET_STATS,this.handleGetLocalAudioStats),e.addListener(Bk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(Bk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(Bk.GET_STATS,this.handleGetLocalAudioStats),e.addListener(Bk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(Bk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(Bk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(Bk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(Bk.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(Bk.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack)))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let t=Hb(e,2),n=t[0];return{track:t[1].track,type:n}}))),e.forEach((e=>{let t=e.track;switch(e.type){case sB.LocalVideoTrack:t.off(Bk.GET_STATS,this.handleGetLocalVideoStats),t.off(Bk.GET_RTC_STATS,this.handleGetRTCStats),t.off(Bk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(Bk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(Bk.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(Bk.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(Bk.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(Bk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(Bk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case sB.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case sB.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof zU?e.trackList.forEach((e=>{e.off(Bk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(Bk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(Bk.GET_STATS,this.handleGetLocalAudioStats),e.off(Bk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(Bk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(Bk.GET_STATS,this.handleGetLocalAudioStats),e.off(Bk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(Bk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(Bk.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(Bk.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(Bk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(Bk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof rx&&t.addListener(Bk.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof ox&&t.addListener(Bk.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(Bk.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=Hb(e,2),n=t[0],i=t[1];i.has(nB.AUDIO)&&this.unbindRemoteTrackEvents(n._audioTrack),i.has(nB.VIDEO)&&this.unbindRemoteTrackEvents(n._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,n)=>{var i;let r,o,s=e.track;switch(e.type){case sB.LocalAudioTrack:r=KF.Audio,o={dtx:s instanceof XU&&s._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case sB.LocalVideoTrack:r=Vi(i=s._hints).call(i,jk.SCREEN_TRACK)?KF.Screen:KF.High,o=iie(iie({},q7(s)),{},{codec:this.store.codec,svc_mode:oee()});break;case sB.LocalVideoLowTrack:r=KF.Low,o=iie(iie({},q7(s)),{},{codec:this.store.codec,svc_mode:oee()})}return{stream_type:r,attributes:o,ssrcs:t[n]}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let n,i=Hb(e,2),r=i[0],o=i[1],s=o.track,a=o.ssrcs,c=o.id;switch(r){case sB.LocalVideoTrack:n=Vi(t=s._hints).call(t,jk.SCREEN_TRACK)?KF.Screen:KF.High;break;case sB.LocalAudioTrack:n=KF.Audio;break;case sB.LocalVideoLowTrack:n=KF.Low}return{stream_type:n,ssrcs:a,mid:c}}))}assignLocalTracks(e,t){e.forEach(((e,n)=>{let i=e.track,r=e.type;this.localTrackMap.set(r,{track:i,id:t[n].id,ssrcs:t[n].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let t=Hb(e,1)[0];this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{if(FL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(cB.PeerConnectionStateChange,t),"connecting"===t&&e instanceof One&&!SN()&&rL("FIRST_TCP_CANDIDATE")&&window.setTimeout((()=>{"connecting"===t&&e.extendCandidate()}),rL("FIRST_TCP_CANDIDATE_INTERVAL")),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t){this._restartTimer&&(window.clearTimeout(this._restartTimer),this._restartTimer=void 0),e instanceof One&&$ne(e,!0),this._isTryConnecting&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isTryConnecting=!1,this._isStartRestartIce=!1,this._pcStatsUploadType=rB.DISCONNECTED_OR_FAILED;if("CONNECTED"===DD(this,cB.QueryClientConnectionState)&&this._isWaitPcToRePub){const e=this.pendingLocalTracks.map((e=>e.getTrackId())),t=this.pendingLocalDataChannels.map((e=>"dc_".concat(e.id)));uk.reportApiInvoke(this.store.sessionId,{name:ED.REPUB_AFTER_PC_CONNECTED,options:e.concat(t),tag:mD.TRACER}).onSuccess(),this.republish()}}if(rL("NEW_ICE_RESTART")&&e instanceof One&&!SN()&&!this._forceTurn&&!this.store.useDcSignal){if(Vi(oB).call(oB,t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const t=t=>{if(bne(e)){FL.debug("[".concat(this.store.clientId,"] [P2PChannel] try to restartICE, type is ").concat(t));"CONNECTED"===DD(this,cB.QueryClientConnectionState)&&this.emit(cB.RequestRestartICE,t)}},n=()=>{bne(e)&&(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),FL.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout((()=>this.emit(cB.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())};return void(this._restartTimer=window.setTimeout((()=>{eie(e,t,n)}),800))}}else{if("disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout((()=>{if("disconnected"===e.iceConnectionState&&rL("ICE_RESTART")){"CONNECTED"===DD(this,cB.QueryClientConnectionState)&&this.emit(cB.RequestRestartICE)}}),800),void setTimeout((()=>{"disconnected"===e.peerConnectionState&&(FL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection disconnected timeout 4000ms, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isTryConnecting=!1,setTimeout((()=>this.emit(cB.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())}),4e3);"failed"===t&&(FL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection state failed, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),setTimeout((()=>this.emit(cB.P2PLost)),0),this.iceFailedCount+=1,await this.requestReconnect())}},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),FL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),uk.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:mD.TRACER}).onSuccess(),this.emit(cB.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{FL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{FL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{FL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t;const n=Array.from(CL(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));var i;n&&(this.store.subscribe(n.uid,"audio",void 0,void 0,void 0,Date.now()),null===(i=n.audioTrack)||void 0===i||i.emit(Xk.FIRST_FRAME_DECODED),uk.firstRemoteFrame(this.store.sessionId,HL.FIRST_AUDIO_DECODE,YL.FIRST_AUDIO_DECODE,{peer:n._uintid,subscribeElapse:Hte.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const n=Array.from(CL(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));n&&uk.firstRemoteFrame(this.store.sessionId,HL.FIRST_AUDIO_RECEIVED,YL.FIRST_AUDIO_RECEIVED,{peer:n._uintid,subscribeElapse:Hte.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,n)=>{var i;const r=Array.from(CL(i=this.remoteUserMap).call(i)).find((t=>t._videoSSRC===e));r&&this.store.firstVideoFrameDecoded(r.uid,{firstDecoded:Date.now()}),this.reportVideoFirstFrameDecoded(e,t,n)},e.onFirstVideoRender=e=>{var t;const n=Array.from(CL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));n&&(this.store.firstVideoFrameDecoded(n.uid,{firstPreRender:Date.now()}),this.reportVideoFirstFrameRender(n),this.emit(cB.FirstVideoPreRender,n.uid,e))},e.onFirstVideoReceived=e=>{var t;const n=Array.from(CL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));n&&(this.store.firstVideoFrameDecoded(n.uid,{firstReceived:Date.now()}),uk.firstRemoteFrame(this.store.sessionId,HL.FIRST_VIDEO_RECEIVED,YL.FIRST_VIDEO_RECEIVED,{peer:n._uintid,subscribeElapse:Hte.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstVideoBufferReady=e=>{var t;const n=Array.from(CL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));n&&this.emit(cB.FirstVideoBufferReady,n.uid,e)},e.onSelectedLocalCandidateChanged=(e,t)=>{const n="relay"===e.candidateType,i="relay"===t.candidateType;"unknown"!==t.candidateType&&n===i||this.emit(cB.ConnectionTypeChange,n),FL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(nee(t))," -> ").concat(JSON.stringify(nee(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{FL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(nee(t))," -> ").concat(JSON.stringify(nee(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.getLocalVideoStats=()=>{const e=this.statsCollector.getLocalVideoTrackStats(),t=this.statsCollector.getRTCStats();return iie(iie({},e),t)},e.onICECandidateError=e=>{this._iceError=e}}fallbackConnection(){FL.debug("[".concat(this.store.clientId,"] [P2PChannel] try to fallback connection")),this.state===aB.Connected?(FL.debug("[".concat(this.store.clientId,"] [P2PChannel] fallback to websocket but P2PChannel state still connected, disconnect first")),this.disconnectForReconnect()):(this.connection&&this.resetConnection(this.connection),this.shouldForwardP2PCreation&&this.recreateConnection())}resetConnection(e){e instanceof One&&function(e){Zne.delete(e.id),$ne(e)}(e),e.close(),this.emit(cB.PeerConnectionStateChange,"closed"),function(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.getLocalVideoStats=void 0}(e),this._isWaitPcToRePub=!1}recreateConnection(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._p2pBySDPEndPoint=!1,this.connection=yne(this.store,e),this.emit(cB.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const n=this.localTrackMap.get(sB.LocalAudioTrack);if(e instanceof YU&&(null==n?void 0:n.track)instanceof zU)return n.track.isActive||t.push([sB.LocalAudioTrack,n]),t;const i=Array.from(this.localTrackMap.entries()).find((t=>{let n=Hb(t,2)[1].track;return e===n}));if(i&&(t.push(i),i[0]===sB.LocalVideoTrack)){const e=this.localTrackMap.get(sB.LocalVideoLowTrack);e&&t.push([sB.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],n=this.localTrackMap.get(sB.LocalAudioTrack);if(e instanceof YU&&(null==n?void 0:n.track)instanceof zU)return n.track.isActive&&t.push([sB.LocalAudioTrack,n]),t;const i=Array.from(this.localTrackMap.entries()).find((t=>{let n=Hb(t,2)[1].track;return e===n}));if(i)if(i[0]===sB.LocalVideoTrack){t.push(i);const e=this.localTrackMap.get(sB.LocalVideoLowTrack);e&&t.push([sB.LocalVideoLowTrack,e])}else t.push(i);return t}createMuteMessage(e){return e.map((e=>{var t;let n,i=Hb(e,2),r=i[0],o=i[1],s=o.track,a=o.ssrcs,c=o.id;switch(r){case sB.LocalAudioTrack:n=KF.Audio;break;case sB.LocalVideoTrack:n=Vi(t=s._hints).call(t,jk.SCREEN_TRACK)?KF.Screen:KF.High;break;case sB.LocalVideoLowTrack:n=KF.Low}return{stream_type:n,ssrcs:a,mid:c}}))}createUnmuteMessage(e){return e.map((e=>{var t;let n,i=Hb(e,2),r=i[0],o=i[1],s=o.track,a=o.ssrcs,c=o.id;switch(r){case sB.LocalAudioTrack:n=KF.Audio;break;case sB.LocalVideoTrack:n=Vi(t=s._hints).call(t,jk.SCREEN_TRACK)?KF.Screen:KF.High;break;case sB.LocalVideoLowTrack:n=KF.Low}return{stream_type:n,ssrcs:a,mid:c}}))}filterTobeUnSubscribedTracks(e,t){const n=[],i=this.remoteUserMap.get(e);if(!i)return n;if(t){const r=i.get(t);if(!r)return n;n.push([e,{kind:t,id:r}])}else Array.from(i.entries()).forEach((t=>{let i=Hb(t,2),r=i[0],o=i[1];n.push([e,{kind:r,id:o}])}));return n}filterTobeUnSubscribedDataChannels(e,t){const n=[];return t.forEach((t=>{var i;null!==(i=this.remoteDataChannelMap.get(e))&&void 0!==i&&i.has(t.id)&&n.push(t)})),n}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let n=Hb(e,2),i=n[0],r=n[1],o=r.kind;switch(r.id,o){case nB.VIDEO:return void(i._videoSSRC&&t.push({stream_type:nB.VIDEO,ssrcId:i._videoSSRC}));case nB.AUDIO:return void(i._audioSSRC&&t.push({stream_type:nB.AUDIO,ssrcId:i._audioSSRC}))}})),t}createUnsubscribeAllMessage(e){const t=new Map;return e.forEach((e=>{let n=Hb(e,2),i=n[0],r=n[1].kind;if(t.has(i)){let e=t.get(i);r===nB.VIDEO?e|=XF.Video:e|=XF.Audio,t.set(i,e)}else r===nB.VIDEO?t.set(i,XF.Video):t.set(i,XF.Audio)})),{users:Array.from(t.entries()).map((e=>{let t=Hb(e,2),n=t[0],i=t[1];return{stream_id:n.uid,stream_type:i}}))}}withdrawRemoteTracks(e){e.forEach((e=>{let t=Hb(e,2),n=t[0],i=t[1].kind;const r=this.remoteUserMap.get(n);r&&(r.delete(i),0===Array.from(r.entries()).length&&this.remoteUserMap.delete(n))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(sB.LocalVideoTrack),n=this.localTrackMap.get(sB.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new dp(((e,n)=>{this.handleUpdateVideoEncoder(t.track,e,n,!0)}))),n&&e.low_stream_uplink&&(await n.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new dp(((e,t)=>{this.handleUpdateVideoEncoder(n.track,e,t,!0)})))}isP2PDisconnected(){if(this.connection){return"connected"!==this.connection.peerConnectionState}return!0}isPreallocation(){return!(!this.connection||!("name"in this.connection)||"DataChannelConnection"!==this.connection.name||"closed"===this.connection.peerConnectionState)||this.connection instanceof One&&this.connection.isPreallocation}isPreSub(){return(this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name&&"closed"!==this.connection.peerConnectionState||this.connection instanceof One)&&this.connection.isPreSub()}isPreRender(){return this.connection instanceof One&&this.connection.isPreRender}mapPubResToRemoteConfig(e,t,n){return e.map(((e,i)=>{var r;let o=e.stream_type;const s=null===(r=t.find((e=>{let t=e.stream_type;return o===t})))||void 0===r?void 0:r.attributes;if(s&&rL("DISABLE_SCREEN_SHARE_REMB")){const e=n[i]._hints;(Vi(e).call(e,jk.SCREEN_TRACK)||Vi(e).call(e,jk.SCREEN_LOW_TRACK))&&(s.remb=!1,FL.debug("disable remb for screen share, hints:",e))}return s}))}async tryToUnmuteAudio(e){for(let n=0;n<e.length;n++)if(e[n]instanceof YU){var t;const i=this.filterTobeUnmutedTracks(e[n]);if(0===i.length)continue;await(null===(t=this.connection)||void 0===t?void 0:t.unmuteLocal(i.map((e=>Hb(e,2)[1].id))));const r=this.createUnmuteMessage(i);return void await ND(this,cB.RequestUnmuteLocal,r)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=()=>this.getStats(),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null===(t=this.connection)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(cB.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(cB.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks(),this.statsUploader.requestTransportStats=()=>{var e;return{connectState:(null===(e=this.connection)||void 0===e?void 0:e.peerConnectionState)||"closed"}}}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await $D(fP(this.dtlsFailedCount,mP)),this.emit(cB.RequestReconnect)}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await OD(this,cB.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(cB.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(sB.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof BV))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof BV)).length>1)throw new zN(JN.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof YU)).length>1&&(e.some((e=>e instanceof YU&&e._bypassWebAudio))||!_k().webAudioMediaStreamDest))throw new zN(JN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const t of e){if(t instanceof BV&&this.pendingLocalTracks.some((e=>e instanceof BV)))throw new zN(JN.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof YU&&this.pendingLocalTracks.some((e=>e instanceof YU))&&(!_k().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof YU&&e._bypassWebAudio))))throw new zN(JN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){var n;const i=!rL("DISABLE_DUAL_STREAM_USE_ENCODING")&&_k().supportDualStreamEncoding,r=iie(iie({},{width:160,height:120,framerate:15,bitrate:50}),t);let o;o=i?e._mediaStreamTrack.clone():Dne(e,r);const s=eP(8,"track-low-"),a=new BV(o,iie(iie({},i&&{scaleResolutionDownBy:tee(r,e)}),{},{frameRate:r.framerate,bitrateMax:r.bitrate,bitrateMin:r.bitrate}),void 0,void 0,s);return a.on(Hk.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,Gk.LOW_STREAM)})),a._hints.push(jk.LOW_STREAM),Vi(n=e._hints).call(n,jk.SCREEN_TRACK)&&a._hints.push(jk.SCREEN_LOW_TRACK),e.on("sei-to-send",(e=>{a.emit("sei-to-send",e)})),e.addListener(Bk.NEED_CLOSE,(()=>{a.close()})),a}async globalLock(){return this.mutex.lock("From P2PChannel.globalLock")}async reportPCStats(e,t,n){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(this.connection&&this.connection instanceof One){var r,o,s,a;const c=this.store.keyMetrics.descriptionStart||0,d=this.connection,l=d.iceConnectionState,u=d.dtlsTransportState,h=d.peerConnectionState,p=await this.connection.getSelectedCandidatePair(),_=p.local,E=p.remote;uk.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:l,dtlsstate:u,connectionstate:h,intSucc:t?1:2,error:this._iceError||i||"",selectedLocalCandidateProtocol:null!==(r=null==_?void 0:_.protocol)&&void 0!==r?r:"",selectedLocalCandidateType:null!==(o=_.candidateType)&&void 0!==o?o:"",selectedLocalCandidateAddress:"".concat(_.address,":").concat(_.port),selectedRemoteCandidateProtocol:null!==(s=E.protocol)&&void 0!==s?s:"",selectedRemoteCandidateType:null!==(a=E.candidateType)&&void 0!==a?a:"",selectedRemoteCandidateAddress:"".concat(E.address,":").concat(E.port),restartCnt:n,preallocation:this.connection.isPreallocation,sdpEndPoint:this._p2pBySDPEndPoint?1:0}),this._iceError=null}}reportVideoFirstFrameRender(e){const t=this.store.keyMetrics,n=t.firstVideoFrameDecoded.find((t=>t.userId===e.uid));if(!n)return;const i=n.isInternalUpload,r=n.isExternalUpload;if(i&&r)return;const o=n.subscribeEnd,s=n.firstPreRender,a=n.peerPublishDuration,c=n.peerPubStatusMs;let d=n.firstRender,l=void 0===d?0:d;if(o&&(l||s)&&a&&c){n.isInternalUpload=!0;const i=n.playEnd;i&&(n.isExternalUpload=!0);const r=n.firstPreRender,s=void 0===r?0:r;l=s||l;const d=e.videoTrack,u={peer:e._uintid,width:(null==d?void 0:d._videoWidth)||0,height:(null==d?void 0:d._videoHeight)||0,ssrc:e._videoSSRC||0,p2pid:this.store.p2pId,peerPublishDuration:a,peerPubStatusMs:c,joinChannelStart:t.joinStart||0,preloadStart:t.preloadStart||0,preloadEnd:t.preloadEnd||0,apStart:t.requestAPStart||0,apEnd:t.requestAPEnd||0,suaEnd:t.requestSUAEnd||0,beforeConnect:t.beforeConnect||0,peerReceiver:t.peerReceiver||0,ice:t.iceConnectionEnd||0,pc:t.peerConnectionEnd||0,signalConnected:t.signalConnected||0,joinReq:t.joinReq||0,joinRes:t.joinRep||0,userJoinNotify:n.userJoinNotify||0,videoAddNotify:n.videoAddNotify||0,subscribeStart:n.subscribeStart||0,subscribeEnd:n.subscribeEnd||0,firstReceived:n.firstReceived||0,firstDecoded:n.firstDecoded||0,firstPreRender:s||0,firstRender:i?Math.max(l,i):Math.max(l,o),playStart:n.playStart||0,playEnd:n.playEnd||0,isPreSub:!(!e._videoSSRC||!this.isPreSubScribe(e._videoSSRC)),isPrePc:this.isPreallocation(),isPreInstantVideo:Sk(this.store),firstReceivedEncodedFrame:n.firstReceivedEncodedFrame||0,frameType:n.frameType||"",rtpTimestamp:n.rtpTimestamp||0,framePayloadType:n.framePayloadType||0,frameDataLength:n.frameDataLength||0,mimeType:n.mimeType||"",sdpEndPoint:this._p2pBySDPEndPoint};uk.firstXLAPeerFirstVideoFrame(this.store.sessionId,u)}}reportVideoFirstFrameDecoded(e,t,n,i){var r;const o=Array.from(CL(r=this.remoteUserMap).call(r)).find((t=>t._videoSSRC===e));if(o){i||this.store.subscribe(o.uid,"video",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,s=r.subscribe.find((e=>e.userId===o.uid&&"video"===e.type));uk.firstRemoteVideoDecode(this.store.sessionId,HL.FIRST_VIDEO_DECODE,YL.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:n,subscribeElapse:Hte.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==s?void 0:s.subscribeEnd)||0,subscriberStart:(null==s?void 0:s.subscribeStart)||0,videoAddNotify:(null==s?void 0:s.streamAdded)||0,state:i?1:0,firstFrame:(null==s?void 0:s.firstFrame)||0})}}async remoteMediaSsrcChanged(e,t,n){if(!this.connection)return!1;const i=this.remoteUserMap.get(e);if(!i)return!1;const r=i.get(t);if(!r)return!1;const o=await this.connection.getRemoteSSRC(r);return void 0!==o&&o!==n}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let t=Hb(e,2),n=t[0],i=t[1].track;n===sB.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,Gk.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}},mF(tie.prototype,"startP2PConnection",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"startP2PConnection"),tie.prototype),mF(tie.prototype,"connect",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"connect"),tie.prototype),mF(tie.prototype,"updateRemoteRTPCapabilities",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"updateRemoteRTPCapabilities"),tie.prototype),mF(tie.prototype,"publishDataChannel",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"publishDataChannel"),tie.prototype),mF(tie.prototype,"unpublish",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"unpublish"),tie.prototype),mF(tie.prototype,"unpublishDataChannel",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"unpublishDataChannel"),tie.prototype),mF(tie.prototype,"unpublishLowStream",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"unpublishLowStream"),tie.prototype),mF(tie.prototype,"subscribeDataChannel",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"subscribeDataChannel"),tie.prototype),mF(tie.prototype,"subscribe",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"subscribe"),tie.prototype),mF(tie.prototype,"massSubscribe",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"massSubscribe"),tie.prototype),mF(tie.prototype,"unsubscribe",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"unsubscribe"),tie.prototype),mF(tie.prototype,"unsubscribeDataChannel",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"unsubscribeDataChannel"),tie.prototype),mF(tie.prototype,"massUnsubscribe",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"massUnsubscribe"),tie.prototype),mF(tie.prototype,"muteRemote",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"muteRemote"),tie.prototype),mF(tie.prototype,"unmuteRemote",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"unmuteRemote"),tie.prototype),mF(tie.prototype,"hasRemoteMediaWithLock",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"hasRemoteMediaWithLock"),tie.prototype),mF(tie.prototype,"disconnectForReconnect",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"disconnectForReconnect"),tie.prototype),mF(tie.prototype,"updateBitrateLimit",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"updateBitrateLimit"),tie.prototype),mF(tie.prototype,"remoteMediaSsrcChanged",[aie],Object.getOwnPropertyDescriptor(tie.prototype,"remoteMediaSsrcChanged"),tie.prototype),tie);function aie(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=await e.lock("From P2PChannel.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await i.apply(this,o)}finally{n()}},n}function cie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function die(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?cie(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):cie(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const lie=Date.now(),uie=20,hie=new Map,pie=new Map;async function _ie(e){const t=hie.get(e),n=Array.isArray(t)&&t[t.length-1],i=pie.get(e);if(!n)return void(i.isSyncing=!1);const r={uid:n.uid,payload:n.payload};0===i.firstRecvTs&&(i.firstRecvTs=n.recvTs,i.firstSendTs=n.sendTs);const o=n.sendTs-i.firstSendTs,s=o-(Date.now()-i.firstRecvTs);s>0&&(i.firstRecvTs=Date.now()-o);let a=n.mediaDelay+s;a<=0?(t.pop(),Eie(n.context,r),a=0):a=Math.min(a,uie),setTimeout((()=>t.length&&_ie(e)),a)}function Eie(e,t){e.safeEmit(bD.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t)}function mie(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2?arguments[2]:void 0;if(!e.syncWithAudio)return Eie(n,{uid:e.uid,payload:e.payload});const i="".concat(n.id,"-").concat(e.uid),r=hie.get(i)||[],o=r.findIndex((t=>e.sendTs>=t.sendTs)),s=die(die({},e),{},{context:n,mediaDelay:t,recvTs:Date.now()});-1===o?r.push(s):r.splice(o,0,s),hie.set(i,r);let a=!1;var c;pie.has(i)?a=!(null===(c=pie.get(i))||void 0===c||!c.isSyncing):pie.set(i,{isSyncing:a,firstRecvTs:0,firstSendTs:0});a||_ie(i)}const fie=dN().name;function gie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Sie(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?gie(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):gie(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const Tie="websdk_ng_cache_parameter",Rie=rL("MAX_PRELOAD_ASYNC_LENGTH"),vie=1e4,yie=new Map,bie=[];let Cie=null,Iie=0,Aie=0;const wie=new Map,Oie=new Uint8Array([241,141,127,212,103,139,200,225,251,157,127,139,143,2,22,163]),Nie=function(e,t){const n=[];let i=0;const r=async()=>{const e=n.shift();e&&await e(),n.length>0&&i<t?r():i--};return async function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];return new dp((async(o,a)=>{n.push((async()=>{try{const t=await e(...s);o(t)}catch(e){a(e)}})),i<t&&(i++,r())}))}}(Lie,Rie),Die=QO.CancelToken.source();class Pie{constructor(){GA(this,"_audioContext",null)}createMuteAudioTrack(){this._audioContext=new AudioContext;const e=this._audioContext.sampleRate,t=10*e,n=this._audioContext.createBuffer(2,t,e),i=this._audioContext.createBufferSource();i.buffer=n;const r=this._audioContext.createMediaStreamDestination();i.connect(r),i.start();return r.stream.getAudioTracks()[0]}close(){this._audioContext&&(this._audioContext.close(),this._audioContext=null)}}async function Lie(e,t,n,i,r,o,s){try{if(!rL("ENABLE_PRELOAD"))return;if(!_k().supportWebCrypto)return void HD((()=>{FL.warn("Your browser does not support preloading, this feature  be run in a secure environment")}),"preload_webcrypto_not_supported");if(!n&&null!==n)throw new zN(JN.INVALID_PARAMS,"Invalid token: ".concat(n,". If you don not use token, set it to null"));n&&eD(n,"token",1,2047),eD(e,"appid",1,2047),OF(t),i&&NF(i);const c=tP();FL.debug("preload channel ".concat(t,", uid is ").concat(i));const d={appId:e,cname:t,token:n||e,uid:"string"!=typeof i?i:null,sid:c,proxyServer:r,role:s};let l,u;if("string"==typeof i){d.stringUid=i;var a=Hb(await dp.all([kte(i,{sid:c,appId:e},Die.token),Ute(Sie(Sie({},d),{},{token:n||e,uid:0}),Die.token)]),2);u=a[0],l=a[1],d.uid=u.uid,l.gatewayInfo.uid=d.uid,l.gatewayInfo.res.uid=d.uid}else o&&(d.stringUid=o),l=await Ute(d,Die.token);const h={sid:c,appId:e,cname:t,token:n||e,uid:d.stringUid||i,intUid:d.uid||l.gatewayInfo.uid,stringUid:d.stringUid,ts:Date.now(),sua:u,ap:l};await Uie(h),Iie++}catch(e){throw Aie++,function(e){Cie||(Cie=window.setTimeout((()=>{let t="";wie.forEach(((e,n)=>{t+="".concat(n,": ").concat(e," ;")})),uk.reportApiInvoke(null,{name:ED.PRELOAD,options:{success:Iie,failed:Aie,err:t}}).onError(e),Iie=0,Aie=0,wie.clear(),Cie=null}),vie));const t=wie.get(e.code)||0;wie.set(e.code,t+1)}(e),e}}async function kie(e){try{if(rL("AP_REQUEST_DETAIL")||rL("ENABLE_ROLE_SELECT_EDGE")||rL("ENABLE_JOIN_V4"))return;const t=Mie(e);if(!t||"disabled"!==e.cloudProxyServer)return;const n=await async function(e,t){try{const n=await window.crypto.subtle.importKey("raw",JD(t),"AES-GCM",!1,["decrypt"]),i=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:Oie},n,YD(e));return JSON.parse(window.atob(XD(new Uint8Array(i))))}catch(e){return}}(t,e.token||e.appId);if(!n)return;if(!function(e,t){const n=e.cname===t.cname&&e.appId===t.appId&&e.token===t.token;if(!n)return!1;return t.stringUid?e.stringUid===t.stringUid:"number"==typeof t.uid?e.uid===t.uid:e.uid==t.uid}(n,e))return;if(n&&Date.now()-n.ts<rL("AP_CACHE_LIFETIME"))return n}catch(e){FL.warn("Error get preloadInfo",e.message)}}function Mie(e){let t;try{if(t=Bie(Tie),!t)return;const n=JSON.parse(t),i=Gie(e),r=function(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}(n,(e=>i in e));if(-1===r)return;const o=n.splice(r,1)[0];return jie(Tie,JSON.stringify(n)),o[i]}catch(e){FL.warn("Error delete preload info: ".concat(t),e.message),jie(Tie,"")}}async function Uie(e){let t;try{e.uid&&Mie({appId:e.appId,cname:e.cname,token:e.token,uid:e.uid,stringUid:e.stringUid});const n=Gie(e),i=await async function(e,t){try{const n=await window.crypto.subtle.importKey("raw",JD(t),"AES-GCM",!1,["encrypt"]),i=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:Oie},n,YD(window.btoa(JSON.stringify(e))));return XD(new Uint8Array(i))}catch(e){return}}(e,e.token||e.appId);if(!i)return;t=Bie(Tie);const r=t?JSON.parse(t):[];r.push({[n]:i}),r.length>rL("AP_CACHE_NUM")&&r.shift(),jie(Tie,JSON.stringify(r))}catch(e){FL.warn("Error caching server parameters:",e.message),jie(Tie,"")}}function Vie(e){if(e){let t=yie.get(e);t&&(window.clearTimeout(t),t=null,yie.delete(e)),Vi(bie).call(bie,e)||"disabled"!==e.cloudProxyServer||bie.push(e)}if(yie.size<rL("AP_CACHE_NUM")&&bie.length>0){const e=bie.shift();yie.set(e,window.setTimeout((async()=>{const t=e.appId,n=e.cname,i=e.token,r=e.stringUid,o=e.uid,s=e.proxyServer,a=e.role;try{await Nie(t,n,i,o,s,r,a),yie.has(e)&&Vie(e)}catch(t){FL.warn("update preload failed",t.message),xie(e)}}),rL("AP_UPDATE_INTERVAL")))}}function xie(e){const t=bie.indexOf(e);-1!==t&&bie.splice(t,1);let n=yie.get(e);n&&(window.clearTimeout(n),n=null,yie.delete(e),Vie())}function Fie(e,t){const n=e.sua,i=e.ap;t&&n&&uk.reqUserAccount(e.sid,{lts:n.requestTime,elapse:n.elapse,success:!0,serverAddr:n.url,stringUid:t,uid:e.intUid,errorCode:null,extend:n.req}),uk.reportResourceTiming(e.ap.url,e.sid),uk.joinWebProxyAP(e.sid,{lts:i.requestTime,elapse:i.elapse,sucess:1,apServerAddr:i.url,turnServerAddrList:i.proxyInfo.addresses.map((e=>e.ip)).join(","),eventType:"disabled",unilbsServerIds:[hK.CHOOSE_SERVER,hK.CLOUD_PROXY_FALLBACK].toString()}),uk.joinChooseServer(e.sid,{lts:i.requestTime,elapse:i.elapse,succ:!0,csAddr:i.url,opid:i.opid,serverList:i.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,cid:i.gatewayInfo.cid.toString(),uid:i.gatewayInfo.uid.toString(),csIp:i.gatewayInfo.csIp,unilbsServerIds:[hK.CHOOSE_SERVER].toString(),isHttp3:i.isHttp3})}function Bie(e){return window.atob(window.localStorage.getItem(e)||"")}function jie(e,t){window.localStorage.setItem(e,window.btoa(t))}function Gie(e){let t="".concat(e.appId,"_").concat(e.cname);return"string"==typeof e.uid&&(t+="_s_".concat(e.uid)),"number"==typeof e.uid&&(t+="_".concat(e.uid)),e.token&&(t+="_".concat(e.token)),uP(t)}function Wie(e){let t=function(){const e=Xie.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}();return function(e,t){let n=e.appId;void 0!==n&&(rre(t,10),ere(t,n));let i=e.cid;void 0!==i&&(rre(t,16),rre(t,i));let r=e.cname;void 0!==r&&(rre(t,26),ere(t,r));let o=e.deviceId;void 0!==o&&(rre(t,34),ere(t,o));let s=e.elapse;void 0!==s&&(rre(t,40),sre(t,s));let a=e.fileSize;void 0!==a&&(rre(t,48),sre(t,Yie(a)));let c=e.height;void 0!==c&&(rre(t,56),sre(t,Yie(c)));let d=e.jpg;void 0!==d&&(rre(t,66),rre(t,d.length),Qie(t,d));let l=e.networkType;void 0!==l&&(rre(t,72),sre(t,Yie(l)));let u=e.osType;void 0!==u&&(rre(t,80),sre(t,Yie(u)));let h=e.requestId;void 0!==h&&(rre(t,90),ere(t,h));let p=e.sdkVersion;void 0!==p&&(rre(t,98),ere(t,p));let _=e.sequence;void 0!==_&&(rre(t,104),sre(t,Yie(_)));let E=e.sid;void 0!==E&&(rre(t,114),ere(t,E));let m=e.timestamp;void 0!==m&&(rre(t,120),sre(t,m));let f=e.uid;void 0!==f&&(rre(t,128),rre(t,f));let g=e.vid;void 0!==g&&(rre(t,136),rre(t,g));let S=e.width;void 0!==S&&(rre(t,144),sre(t,Yie(S)));let T=e.service;void 0!==T&&(rre(t,152),rre(t,T));let R=e.callbackData;void 0!==R&&(rre(t,162),rre(t,R.length),Qie(t,R));let v=e.ticket;void 0!==v&&(rre(t,170),ere(t,v));let y=e.vendorConfigs;void 0!==y&&(rre(t,178),ere(t,y))}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function Kie(e){return function(e){let t={};e:for(;!zie(e);){let n=ire(e);switch(n>>>3){case 0:break e;case 1:t.code=ire(e);break;case 2:t.msg=$ie(e,ire(e));break;case 3:t.requestId=$ie(e,ire(e));break;case 4:t.timestamp=ore(e,!1);break;default:Hie(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function Hie(e,t){switch(t){case 0:for(;128&tre(e););break;case 2:Jie(e,ire(e));break;case 5:Jie(e,4);break;case 1:Jie(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function Yie(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let Xie=[];function Jie(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function zie(e){return e.offset>=e.limit}function Zie(e,t){let n=e.bytes,i=e.offset,r=e.limit,o=i+t;if(o>n.length){let t=new Uint8Array(2*o);t.set(n),e.bytes=t}return e.offset=o,o>r&&(e.limit=o),i}function qie(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function Qie(e,t){let n=Zie(e,t.length);e.bytes.set(t,n)}function $ie(e,t){let n=qie(e,t),i=String.fromCharCode,r=e.bytes,o="�",s="";for(let e=0;e<t;e++){let a,c,d,l,u=r[e+n];0==(128&u)?s+=i(u):192==(224&u)?e+1>=t?s+=o:(a=r[e+n+1],128!=(192&a)?s+=o:(l=(31&u)<<6|63&a,l<128?s+=o:(s+=i(l),e++))):224==(240&u)?e+2>=t?s+=o:(a=r[e+n+1],c=r[e+n+2],32896!=(49344&(a|c<<8))?s+=o:(l=(15&u)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?s+=o:(s+=i(l),e+=2))):240==(248&u)?e+3>=t?s+=o:(a=r[e+n+1],c=r[e+n+2],d=r[e+n+3],8421504!=(12632256&(a|c<<8|d<<16))?s+=o:(l=(7&u)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?s+=o:(l-=65536,s+=i(55296+(l>>10),56320+(1023&l)),e+=3))):s+=o}return s}function ere(e,t){let n=t.length,i=0;for(let e=0;e<n;e++){let r=t.charCodeAt(e);r>=55296&&r<=56319&&e+1<n&&(r=(r<<10)+t.charCodeAt(++e)-56613888),i+=r<128?1:r<2048?2:r<65536?3:4}rre(e,i);let r=Zie(e,i),o=e.bytes;for(let e=0;e<n;e++){let i=t.charCodeAt(e);i>=55296&&i<=56319&&e+1<n&&(i=(i<<10)+t.charCodeAt(++e)-56613888),i<128?o[r++]=i:(i<2048?o[r++]=i>>6&31|192:(i<65536?o[r++]=i>>12&15|224:(o[r++]=i>>18&7|240,o[r++]=i>>12&63|128),o[r++]=i>>6&63|128),o[r++]=63&i|128)}}function tre(e){return e.bytes[qie(e,1)]}function nre(e,t){let n=Zie(e,1);e.bytes[n]=t}function ire(e){let t,n=0,i=0;do{t=tre(e),n<32&&(i|=(127&t)<<n),n+=7}while(128&t);return i}function rre(e,t){for(t>>>=0;t>=128;)nre(e,127&t|128),t>>>=7;nre(e,t)}function ore(e,t){let n,i=0,r=0,o=0;return n=tre(e),i=127&n,128&n&&(n=tre(e),i|=(127&n)<<7,128&n&&(n=tre(e),i|=(127&n)<<14,128&n&&(n=tre(e),i|=(127&n)<<21,128&n&&(n=tre(e),r=127&n,128&n&&(n=tre(e),r|=(127&n)<<7,128&n&&(n=tre(e),r|=(127&n)<<14,128&n&&(n=tre(e),r|=(127&n)<<21,128&n&&(n=tre(e),o=127&n,128&n&&(n=tre(e),o|=(127&n)<<7))))))))),{low:i|r<<28,high:r>>>4|o<<24,unsigned:t}}function sre(e,t){let n=t.low>>>0,i=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,o=0===r?0===i?n<16384?n<128?1:2:n<1<<21?3:4:i<16384?i<128?5:6:i<1<<21?7:8:r<128?9:10,s=Zie(e,o),a=e.bytes;switch(o){case 10:a[s+9]=r>>>7&1;case 9:a[s+8]=9!==o?128|r:127&r;case 8:a[s+7]=8!==o?i>>>21|128:i>>>21&127;case 7:a[s+6]=7!==o?i>>>14|128:i>>>14&127;case 6:a[s+5]=6!==o?i>>>7|128:i>>>7&127;case 5:a[s+4]=5!==o?128|i:127&i;case 4:a[s+3]=4!==o?n>>>21|128:n>>>21&127;case 3:a[s+2]=3!==o?n>>>14|128:n>>>14&127;case 2:a[s+1]=2!==o?n>>>7|128:n>>>7&127;case 1:a[s]=1!==o?128|n:127&n}}const are={},cre={},dre=4294967296,lre=dre*dre,ure=lre/2,hre=fre(0,!0),pre=fre(0),_re=gre(0,-2147483648,!1),Ere=gre(-1,2147483647,!1),mre=gre(-1,-1,!0);function fre(e,t){let n,i,r;return t?(r=0<=(e>>>=0)&&e<256)&&(i=cre[e],i)?i:(n=gre(e,0,!0),r&&(cre[e]=n),n):(r=-128<=(e|=0)&&e<128)&&(i=are[e],i)?i:(n=gre(e,e<0?-1:0,!1),r&&(are[e]=n),n)}function gre(e,t,n){return{low:0|e,high:0|t,unsigned:!!n}}function Sre(e,t){if(isNaN(e))return t?hre:pre;if(t){if(e<0)return hre;if(e>=lre)return mre}else{if(e<=-ure)return _re;if(e+1>=ure)return Ere}return e<0?t?hre:pre:gre(e%dre|0,e/dre|0,t)}function Tre(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}class Rre extends hD{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(mB.CONNECTION_STATE_CHANGE,e,t)}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this._qualityTimer&&(window.clearTimeout(this._qualityTimer),this._qualityTimer=null),this._quality>=1||(this._qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this._qualityRatio}),6e4))}constructor(e){var t;super(),GA(this,"name","AgoraRTCImageModeration"),GA(this,"_connectionState",EB.CONNECTING),GA(this,"_sequence",0),GA(this,"_moderationStartTime",void 0),GA(this,"_workerConnection",void 0),GA(this,"_workerMessageLengthLimit",void 0),GA(this,"_qualityRatio",void 0),GA(this,"_connectInfo",void 0),GA(this,"_cancelTokenSource",QO.CancelToken.source()),GA(this,"_retryConfig",void 0),GA(this,"_moderationInterval",void 0),GA(this,"_moderationTimer",null),GA(this,"_moderationMode",1),GA(this,"_quality",1),GA(this,"_qualityTimer",null),GA(this,"_ticket",void 0),GA(this,"_moderationIntervalMinimum",void 0),GA(this,"_uploadFailedNum",0),GA(this,"_uploadNum",0),GA(this,"_uploadTimer",null),GA(this,"_extraInfo",void 0),GA(this,"_vendor",""),GA(this,"_encoder",new TextEncoder),GA(this,"_moderationId",void 0),GA(this,"inspectImage",(()=>{if(this.connectionState!==EB.CONNECTED)throw new hk(JN.OPERATION_ABORTED,"image moderation service connection status is ".concat(this.connectionState));this._moderationTimer&&(window.clearInterval(this._moderationTimer),this._moderationTimer=null),this._moderationTimer=window.setInterval((()=>{this.connectionState===EB.CONNECTED?this.requestToInspectImage():FL.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState)}),this._moderationInterval<this._moderationIntervalMinimum?this._moderationIntervalMinimum:this._moderationInterval),this.requestToInspectImage()})),this._moderationId=eP(5,"image-moderation-"),this._workerMessageLengthLimit=rL("IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT"),this._moderationIntervalMinimum=rL("IMAGE_MODERATION_INTERVAL_MINIMUM"),this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),this._qualityRatio=rL("IMAGE_MODERATION_QUALITY_RATIO"),this._moderationStartTime=Number(Date.now()),this._workerConnection=new xB("worker-"+this._moderationId,mP),this.on(mB.STATE_CHANGE,((e,t)=>{FL.debug("[".concat(this._moderationId,"] Moderation operation :").concat(fB[e]," ").concat(t||""))})),this.handleWorkerEvents()}async init(e,t){this.emit(mB.STATE_CHANGE,fB.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new dp(((i,r)=>{this.on(mB.CONNECTION_STATE_CHANGE,((e,t)=>{e===EB.CONNECTED&&i()})),this.requestAP(e,n,t).then((e=>{this.connectWorker(e)})).catch((e=>{r(e)}))}))}updateConfig(e){var t;this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),FL.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===EB.CONNECTED&&this.inspectImage()}async requestAP(e,t,n){const i=rL("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),r=await function(e,t,n,i){let r=t.appId,o=t.areaCode,s=t.cname,a=t.sid,c=t.token,d=t.uid;Cte++;const l="moderation_plugin",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:o,cname:s,command:"allocateEdge",requestId:Cte,seq:Cte,sid:a,appToken:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return gP((async()=>{h=Date.now();const e=await tte(_,{data:u,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-h,0!==e.code){const t=new hk(JN.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+e.code,{retry:!0,responseTime:p});throw FL.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new hk(JN.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw FL.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new hk(JN.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:t.code,responseTime:p});throw FL.error(e.toString()),e}if(!t.servers.some((e=>!!e.wss))){const e=new hk(JN.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:t.code,responseTime:p});throw FL.error(e.toString()),e}const i=rL("IMAGE_MODERATION_WORKER_WSS");if(i)return{addressList:[i],workerToken:t.workerToken,vid:t.vid,responseTime:p};const r=rL("IMAGE_MODERATION_WORKER_HOST"),o=t.servers.map((e=>{let t=e.address,n=e.wss;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(r,":").concat(n,"/moderation")})).filter((e=>!!e));return{addressList:o,workerToken:t.workerToken,vid:t.vid,ticket:t.appTicket,responseTime:p}}),((t,n)=>(uk.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:p,serverIp:e[n%e.length]}),!1)),((t,n)=>(uk.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[n%e.length]}),!!(t.code!==JN.OPERATION_ABORTED&&t.code!==JN.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(n+1)%e.length],!0))),i)}(i,e,t,n);this.emit(mB.STATE_CHANGE,fB.AP_CONNECTED);const o=r.addressList,s=r.ticket;return this._ticket=s,o}async connectWorker(e){this.emit(mB.STATE_CHANGE,fB.CONNECT_WORKER),await this._workerConnection.init(e,1e4)}handleWorkerEvents(){this._workerConnection.on(wF.CONNECTED,(async()=>{this.emit(mB.STATE_CHANGE,fB.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=EB.CONNECTED})),this._workerConnection.on(wF.CLOSED,(()=>{this.connectionState=EB.CLOSED})),this._workerConnection.on(wF.FAILED,(()=>{this.connectionState=EB.CLOSED})),this._workerConnection.on(wF.RECONNECTING,(()=>{this.connectionState=this.connectionState===EB.CONNECTED?EB.RECONNECTING:EB.CONNECTING})),this._workerConnection.on(wF.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=Kie(new Uint8Array(e.data));rL("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&FL.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(t)),this._uploadNum++,void 0===t.code||0===t.code||(this._uploadFailedNum++,FL.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(t.code,", msg is ").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout((()=>{uk.reportApiInvoke(this._connectInfo.sid||null,{name:ED.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:mD.TRACER}).onError(new hk(JN.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null}),rL("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else FL.error("[".concat(this._moderationId,"] Unexpected message type from worker"))})),this._workerConnection.on(wF.WILL_RECONNECT,((e,t,n)=>{"recover"===e&&n(e),n("tryNext")})),this._workerConnection.on(wF.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}async requestToInspectImage(){const e=DD(this,mB.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void(rL("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&FL.debug("Only the track being played can be inspected"));this._sequence++;const n=await this.generateRequestData(e,t);this._workerConnection.sendMessage(n,!0,!0)}else rL("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&FL.debug("Only the track being published can be inspected")}async generateRequestData(e,t){let n=t.appId,i=t.cname,r=t.cid,o=t.vid,s=t.sid,a=t.uid;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await iU(d,n,i),u=this._sequence+"-"+r+"-"+a+"-"+c+"-"+eP(12,""),h={appId:n,cid:r,cname:i,deviceId:"",elapse:Rre.intToLong(Number(c-this._moderationStartTime)),fileSize:d.buffer.byteLength,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:"4.24.4",sequence:this._sequence,sid:s,timestamp:Sre(c),uid:a,vid:o,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};void 0===this._extraInfo&&delete h.callbackData;const p=Wie(h);if(p.byteLength<this._workerMessageLengthLimit){if(rL("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")){const e=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Tre(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Tre(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},h);delete e.jpg,FL.debug("[".concat(this._moderationId,"] Request message for worker of image moderation service: "),JSON.stringify(e))}return p}{const t=this.quality*this._qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:n,cname:i,cid:r,vid:o,sid:s,uid:a})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=QO.CancelToken.source(),this._workerConnection&&this._workerConnection.close(),this._moderationTimer&&window.clearInterval(this._moderationTimer),this._moderationTimer=null,this._uploadTimer&&window.clearTimeout(this._uploadTimer),this._uploadTimer=null,this.connectionState=EB.CLOSED,this.emit(mB.STATE_CHANGE,fB.CLOSED)}}function vre(e){if(QN(e.interval,"interval",1e3,1/0),e&&e.extraInfo&&e.extraInfo.length>1024)throw new hk(JN.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e&&e.vendor&&e.vendor.length>1024)throw new hk(JN.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}const yre={name:"ImageModeration",create:function(e){let t=e.config;return vre(t),new Rre(t)}};var bre,Cre,Ire,Are,wre,Ore,Nre,Dre,Pre,Lre,kre,Mre,Ure,Vre,xre,Fre,Bre,jre,Gre,Wre,Kre,Hre,Yre,Xre,Jre,zre,Zre,qre,Qre,$re,eoe,toe,noe,ioe,roe,ooe,soe,aoe,coe,doe,loe,uoe,hoe;function poe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function _oe(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?poe(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):poe(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}_P.setLogger(FL);let Eoe=(bre=lk(),Cre=lk({argsMap:(e,t)=>{if(!Array.isArray(t)){if(!(t instanceof mM))return[t];t=[t]}return t.map((e=>e?Object(e).toString():"null"))}}),Ire=lk({argsMap:(e,t)=>(t||(t=[]),Array.isArray(t)||t.trackMediaType!==Jk.DATA?(Array.isArray(t)||(t=[t]),t.map((e=>e.getTrackId()))):[t.getChannelId()])}),Are=lk({argsMap:(e,t,n,i)=>["object"==typeof t?t.uid:t,n,i]}),wre=lk({argsMap:(e,t,n)=>[t,n]}),Ore=lk({argsMap:(e,t)=>t.map((e=>{let t=e.user,n=e.mediaType;return[null==t?void 0:t.uid,n]}))}),Nre=lk({argsMap:(e,t,n,i)=>["object"==typeof t?t.uid:t,n,i]}),Dre=lk({argsMap:(e,t)=>t.map((e=>{let t=e.user,n=e.mediaType;return{uid:null==t?void 0:t.uid,mediaType:n}}))}),Pre=lk(),Lre=lk(),kre=lk(),Mre=lk(),Ure=lk(),Vre=lk(),xre=lk(),Fre=lk(),Bre=lk(),jre=lk(),Gre=lk(),Wre=lk(),Kre=lk(),Hre=lk(),Yre=lk(),Xre=lk(),Jre=lk({argsMap:(e,t)=>[t]}),zre=lk(),Zre=lk(),qre=lk(),Qre=lk(),$re=lk(),eoe=lk(),toe=lk(),noe=lk(),ioe=lk({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),roe=lk(),ooe=lk(),soe=lk(),aoe=lk(),coe=lk(),doe=lk(),loe=lk({reportResult:!0}),uoe=lk(),hoe=class extends hD{get connectionState(){return this._gateway.state}get remoteUsers(){return this._users}get localTracks(){return this._p2pChannel.getAllTracks(!0)}get uid(){return this._uid}get channelName(){return this._channelName}get localDataChannels(){return this._p2pChannel.getAllDataChannels()}get mode(){return this._config.mode}get role(){var e;return(null===(e=this._config)||void 0===e?void 0:e.role)||"audience"}get codec(){return this._config.codec}get audioCodec(){return this._config.audioCodec||"opus"}get isStringUID(){return!!this._joinInfo&&!!this._joinInfo.stringUid}get __className__(){return"Client"}constructor(e,t){let n;if(super(),GA(this,"store",void 0),GA(this,"_uid",void 0),GA(this,"_channelName",void 0),GA(this,"_uintUid",void 0),GA(this,"_users",[]),GA(this,"_config",void 0),GA(this,"_clientId",void 0),GA(this,"_appId",void 0),GA(this,"_sessionId",null),GA(this,"_key",void 0),GA(this,"_rtmConfig",{}),GA(this,"_joinInfo",void 0),GA(this,"_gateway",void 0),GA(this,"_statsCollector",void 0),GA(this,"_configDistribute",void 0),GA(this,"_leaveMutex",void 0),GA(this,"_publishMutex",void 0),GA(this,"_renewTokenMutex",void 0),GA(this,"_subscribeMutex",void 0),GA(this,"_encryptionMode","none"),GA(this,"_encryptionSecret",null),GA(this,"_encryptionSalt",null),GA(this,"_encryptDataStream",!1),GA(this,"_encryptDataStreamKey",null),GA(this,"_encryptDataStreamIv",null),GA(this,"_proxyServer",void 0),GA(this,"_turnServer",{servers:[],mode:"auto"}),GA(this,"_cloudProxyServerMode","disabled"),GA(this,"_isDualStreamEnabled",!1),GA(this,"_defaultStreamFallbackType",void 0),GA(this,"_lowStreamParameter",void 0),GA(this,"_streamFallbackTypeCacheMap",new Map),GA(this,"_remoteStreamTypeCacheMap",new Map),GA(this,"_axiosCancelSource",QO.CancelToken.source()),GA(this,"_audioVolumeIndicationInterval",void 0),GA(this,"_networkQualityInterval",void 0),GA(this,"_userOfflineTimeout",void 0),GA(this,"_streamRemovedTimeout",void 0),GA(this,"_rteDetailInterval",void 0),GA(this,"_liveTranscodeStreamingClient",void 0),GA(this,"_liveRawStreamingClient",void 0),GA(this,"_channelMediaRelayClient",void 0),GA(this,"_networkQualitySensitivity","normal"),GA(this,"_p2pChannel",void 0),GA(this,"_useLocalAccessPoint",!1),GA(this,"_setLocalAPVersion",void 0),GA(this,"_joinAndNotLeaveYet",!1),GA(this,"_numberOfJoinCount",0),GA(this,"_joinResponse",null),GA(this,"_remoteDefaultVideoStreamType",void 0),GA(this,"_inspect",void 0),GA(this,"_moderation",void 0),GA(this,"_license",void 0),GA(this,"_pendingPublishedUsers",[]),GA(this,"ntpAlignErrorCount",0),GA(this,"remoteInboundOffset",0),GA(this,"_peerConnectionState",void 0),GA(this,"_pendingRtpCapabilityChange",void 0),GA(this,"_fallbackServerInfo",void 0),GA(this,"_dualStreamMode",void 0),GA(this,"_handleLocalTrackEnable",((e,t,n)=>{this.publish(e,!1).then(t).catch(n)})),GA(this,"_handleLocalTrackDisable",((e,t,n)=>{this.unpublish(e).then(t).catch(n)})),GA(this,"_handleUserOnline",(e=>{if(rL("BLOCK_LOCAL_CLIENT")&&Qx(e.uid,this.channelName))return void FL.debug("[".concat(e.uid,"] will be ignored in local"));this.isStringUID&&"string"!=typeof e.uid&&FL.error("[".concat(this._clientId,"] StringUID is Mixed with UintUID"));const t=this._users.find((t=>t.uid===e.uid));if(t)t._trust_in_room_=!0,t._is_pre_created&&(t._is_pre_created=!1,this.safeEmit(bD.USER_JOINED,t));else{const t=new qte(e.uid,e.uint_id||e.uid);this._users.push(t),FL.debug("[".concat(this._clientId,"] user online"),e.uid),this.store.firstVideoFrameDecoded(t.uid,{userJoinNotify:Date.now()}),this.safeEmit(bD.USER_JOINED,t)}})),GA(this,"_handleUserOffline",(e=>{if(rL("BLOCK_LOCAL_CLIENT")&&Qx(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));t&&(this._handleRemoveStream(e),this._handleRemoveDataChannels(e),t._audio_pre_subscribed||t._video_pre_subscribed?t._is_pre_created=!0:FD(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),FL.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.safeEmit(bD.USER_LEAVED,t,e.reason))})),GA(this,"_handleAddAudioOrVideoStream",((e,t,n,i,r,o,s,a)=>{if(rL("BLOCK_LOCAL_CLIENT")&&Qx(t,this.channelName))return;const c=this._users.find((e=>e.uid===t));if(!c)return void FL.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));FL.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(c.uid,e,void 0,void 0,void 0,Date.now()),"video"===e&&this.store.firstVideoFrameDecoded(c.uid,{videoAddNotify:Date.now()});const d="audio"===e?c.hasAudio:c.hasVideo;c._uintid||(c._uintid=o||t),"audio"===e?c._trust_audio_stream_added_state_=!0:c._trust_video_stream_added_state_=!0,"audio"===e?(c._audio_added_=!0,void 0!==n&&(c._audioSSRC=n),void 0!==i&&(c._cname=i),s&&(c._audioOrtc=s)):(c._video_added_=!0,void 0!==n&&(c._videoSSRC=n),void 0!==i&&(c._cname=i),void 0!==a&&(c._rtxSsrcId=a),s&&(c._videoOrtc=s)),("audio"===e?c.hasAudio:c.hasVideo)&&!d&&(FL.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published ").concat(e)),this.safeEmit(bD.USER_PUBLISHED,c,e)),"video"===e?uk.onGatewayStream(this._sessionId,HL.ON_ADD_VIDEO_STREAM,YL.ON_ADD_VIDEO_STREAM,{peer:o||t,ssrc:c._videoSSRC}):uk.onGatewayStream(this._sessionId,HL.ON_ADD_AUDIO_STREAM,YL.ON_ADD_AUDIO_STREAM,{peer:o||t,ssrc:c._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(c,e,n).then((t=>{if(t&&(FL.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(c.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof sie))return this._p2pChannel.unsubscribe(c,e,!0).then((()=>this._subscribe(c,e,!0).catch((e=>{FL.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))))})),this._p2pChannel.hasPendingRemoteMedia(c,e)&&(FL.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(c.uid," after reconnect.")),this._subscribe(c,e,!0).catch((e=>{FL.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})));const l=this._getEncodingName(r);"video"===e&&("unknown"===l?this.safeEmit(bD.AV1_DECODABLE_RESULT,!1):EN()||TN()||(null==l?void 0:l.toLocaleLowerCase())!==cL.av1||Ote().then((e=>{rL("FLS_ENABLE_AV1_DECODE_DETECT")&&this.safeEmit(bD.AV1_DECODABLE_RESULT,e),e||this._gateway.downgradeCodec(l)})))})),GA(this,"_handleRemoveStream",(e=>{if(rL("BLOCK_LOCAL_CLIENT")&&Qx(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));if(!t)return void FL.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));FL.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let n=()=>{};t.hasAudio&&t.hasVideo?n=()=>{FL.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(bD.USER_UNPUBLISHED,t,"audio"),FL.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(bD.USER_UNPUBLISHED,t,"video")}:t.hasVideo?n=()=>{FL.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(bD.USER_UNPUBLISHED,t,"video")}:t.hasAudio&&(n=()=>{FL.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(bD.USER_UNPUBLISHED,t,"audio")}),t._video_pre_subscribed||t._audio_pre_subscribed||(t._trust_audio_stream_added_state_=!0,t._trust_video_stream_added_state_=!0,t._audio_added_=!1,t._video_added_=!1,this._p2pChannel instanceof sie&&this._p2pChannel.unsubscribe(t).then((e=>{if(e)return this._gateway.unsubscribe(e,t.uid)})),t._audioSSRC=void 0,t._videoSSRC=void 0,t._audioOrtc=void 0,t._videoOrtc=void 0,t._rtxSsrcId=void 0),uk.onGatewayStream(this._sessionId,HL.ON_REMOVE_STREAM,YL.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),n()})),GA(this,"_handleSetStreamLocalEnable",((e,t,n)=>{if(rL("BLOCK_LOCAL_CLIENT")&&Qx(t,this.channelName))return;const i=this._users.find((e=>e.uid===t));if(!i)return void FL.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));FL.debug("[".concat(this._clientId,"] local ").concat(e," ").concat(n?"enabled":"disabled"," with uid ").concat(t));const r="audio"===e?i.hasAudio:i.hasVideo;if("audio"===e){i._trust_audio_enabled_state_=!0;const e=i._audio_enabled_;if(i._audio_enabled_=n,i._audio_enabled_===e)return;{const e=i._audio_enabled_?"enable-local-audio":"disable-local-audio";FL.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(bD.USER_INFO_UPDATED,t,e)}}else{i._trust_video_enabled_state_=!0;const e=i._video_enabled_;if(i._video_enabled_=n,i._video_enabled_===e)return;{const e=i._video_enabled_?"enable-local-video":"disable-local-video";FL.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(bD.USER_INFO_UPDATED,t,e)}}const o="audio"===e?i.hasAudio:i.hasVideo;return r!==o?!r&&o?(FL.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.safeEmit(bD.USER_PUBLISHED,i,e)):("video"===e&&i._videoTrack&&i._videoTrack._destroy(),"audio"===e&&i._audioTrack,this._p2pChannel.muteRemote(i,e),FL.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.safeEmit(bD.USER_UNPUBLISHED,i,e)):void 0})),GA(this,"_handleMuteStream",((e,t,n)=>{if(rL("BLOCK_LOCAL_CLIENT")&&Qx(e,this.channelName))return;FL.debug("[".concat(this._clientId,"] receive mute message"),e,t,n);const i=this._users.find((t=>t.uid===e));if(!i)return void FL.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(e));const r="audio"===t?i.hasAudio:i.hasVideo;if("audio"===t){i._trust_audio_mute_state_=!0;const t=i._audio_muted_;if(i._audio_muted_=n,i._audio_muted_===t)return;{const t=i._audio_muted_?"mute-audio":"unmute-audio";FL.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(bD.USER_INFO_UPDATED,e,t)}}else{i._trust_video_mute_state_=!0;const t=i._video_muted_;if(i._video_muted_=n,i._video_muted_===t)return;{const t=i._video_muted_?"mute-video":"unmute-video";FL.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(bD.USER_INFO_UPDATED,e,t)}}const o="audio"===t?i.hasAudio:i.hasVideo;if(r!==o){if(!r&&o){return("audio"===t?i._audioSSRC:i._videoSSRC)?(FL.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.safeEmit(bD.USER_PUBLISHED,i,t)):void FL.warning("[".concat(this._clientId,"] remote user ").concat(e," receive ").concat(t," unmute message  before add stream message, ").concat(t," SSRC doesn't exist yet."))}"video"===t&&i._videoTrack&&!i._video_pre_subscribed&&i._videoTrack._destroy(),"audio"===t&&i._audioTrack,this._p2pChannel.muteRemote(i,t),FL.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.safeEmit(bD.USER_UNPUBLISHED,i,t)}})),GA(this,"_handleP2PLost",(async e=>{FL.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():FL.warning("[".concat(this._clientId,"] P2PLost stream not found"),e)})),GA(this,"_handleTokenWillExpire",(()=>{FL.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(bD.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)})),GA(this,"_handleBeforeUnload",(e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),FL.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))})),GA(this,"_handleUpdateNetworkQuality",(()=>{if("normal"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.safeEmit(bD.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(bD.NETWORK_QUALITY,e)})),GA(this,"_handleP2PAddAudioOrVideoStream",((e,t,n,i)=>{const r=this._users.find((e=>e.uid===t));if(!r)return void FL.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));FL.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(r.uid,e,void 0,void 0,void 0,Date.now());const o="audio"===e?r.hasAudio:r.hasVideo;"audio"===e?r._trust_audio_stream_added_state_=!0:r._trust_video_stream_added_state_=!0,"audio"===e?(r._audio_added_=!0,void 0!==n&&(r._audioSSRC=n),void 0!==i&&(r._audioMid=i)):(r._video_added_=!0,void 0!==n&&(r._videoSSRC=n),void 0!==i&&(r._videoMid=i)),("audio"===e?r.hasAudio:r.hasVideo)&&!o&&(FL.info("[".concat(this._clientId,"] remote user ").concat(r.uid," published ").concat(e)),this.safeEmit(bD.USER_PUBLISHED,r,e)),this._p2pChannel.hasPendingRemoteMedia(r,e)&&(FL.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(r.uid," after reconnect.")),this._subscribe(r,e,!0).catch((e=>{FL.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})))})),this._config=e,this._clientId=t||eP(5,"client-"),this.store=new class{constructor(e,t,n,i,r){KN(this,"state",void 0),this.state={codec:e,audioCodec:t,mode:n,clientId:i,sessionId:null,p2pId:0,dcId:0,pubId:0,subId:0,keyMetrics:{publish:[],subscribe:[],firstVideoFrameDecoded:[]},joinChannelServiceRecords:[],cloudProxyServerMode:"disabled",useP2P:!1,p2pTransport:ZP.Default,hasStartJoinChannel:!1,isABTestSuccess:!1,rteUrl:void 0,rteSid:void 0,autoSubscribe:!1,enableInstantMuteRestore:!1,networkQualityProbe:!1,useDcSignal:!!r,preSubOptions:void 0}}dispatch(e){this.state=function(e,t){switch(t.type){case aL.SET_SESSION_ID:return YN(YN({},e),{},{sessionId:t.sessionId});case aL.SET_P2P_ID:return YN(YN({},e),{},{p2pId:t.p2pId});case aL.SET_UID:return YN(YN({},e),{},{uid:t.uid});case aL.SET_INT_UID:return YN(YN({},e),{},{intUid:t.intUid});case aL.SET_PUB_ID:return YN(YN({},e),{},{pubId:t.pubId});case aL.KEY_METRIC_CLIENT_CREATED:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{clientCreated:t.metric})});case aL.KEY_METRIC_JOIN_START:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{joinStart:t.metric})});case aL.KEY_METRIC_PRELOAD_START:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{preloadStart:t.metric})});case aL.KEY_METRIC_PRELOAD_END:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{preloadEnd:t.metric})});case aL.KEY_METRIC_JOIN_END:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{joinEnd:t.metric})});case aL.KEY_METRIC_REQUEST_AP_START:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{requestAPStart:t.metric})});case aL.KEY_METRIC_REQUEST_AP_END:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{requestAPEnd:t.metric})});case aL.KEY_METRIC_REQUEST_SUA_END:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{requestSUAEnd:t.metric})});case aL.KEY_METRIC_BEFORE_CONNECT:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{beforeConnect:t.metric})});case aL.KEY_METRIC_PEER_RECEIVER:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{peerReceiver:t.metric})});case aL.KEY_METRIC_SIGNAL_CONNECTED:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{signalConnected:t.metric})});case aL.KEY_METRIC_JOIN_REQ:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{joinReq:t.metric})});case aL.KEY_METRIC_JOIN_REP:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{joinRep:t.metric})});case aL.KEY_METRIC_JOIN_GATEWAY_START:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{joinGatewayStart:t.metric})});case aL.KEY_METRIC_JOIN_GATEWAY_END:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{joinGatewayEnd:t.metric})});case aL.KEY_METRIC_PEER_CONNECTION_START:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{peerConnectionStart:t.metric})});case aL.KEY_METRIC_PEER_CONNECTION_END:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{peerConnectionEnd:t.metric})});case aL.KEY_METRIC_DESCRIPTION_START:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{descriptionStart:t.metric})});case aL.KEY_METRIC_SIGNAL_CHANNEL_OPEN:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{signalChannelOpen:t.metric})});case aL.KEY_METRIC_ICE_CONNECTION_END:return YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{iceConnectionEnd:t.metric})});case aL.KEY_METRIC_PUBLISH:{const n=e.keyMetrics.publish,i=n.findIndex((e=>e.trackId===t.metric.trackId));return-1!==i?(n[i]=YN(YN({},n[i]),t.metric),YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{publish:[...n]})})):YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{publish:[...e.keyMetrics.publish,t.metric]})})}case aL.KEY_METRIC_SUBSCRIBE:{const n=e.keyMetrics.subscribe,i=n.findIndex((e=>e.userId===t.metric.userId&&e.type===t.metric.type));return-1!==i?(n[i]=YN(YN({},n[i]),t.metric),YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{subscribe:[...n]})})):YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{subscribe:[...e.keyMetrics.subscribe,t.metric]})})}case aL.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED:{const n=e.keyMetrics.firstVideoFrameDecoded,i=n.findIndex((e=>e.userId===t.metric.userId));return-1!==i?(n[i]=YN(YN({},n[i]),t.metric),YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{firstVideoFrameDecoded:[...n]})})):YN(YN({},e),{},{keyMetrics:YN(YN({},e.keyMetrics),{},{firstVideoFrameDecoded:[...e.keyMetrics.firstVideoFrameDecoded,t.metric]})})}case aL.RESET_FIRST_VIDEO_FRAME_DECODED:return e.keyMetrics.firstVideoFrameDecoded=[],e;case aL.SET_CLOUD_PROXY_SERVER_MODE:return e.cloudProxyServerMode=t.mode,e;case aL.RECORD_JOIN_CHANNEL_SERVICE:return"number"!=typeof t.index?e.joinChannelServiceRecords=[...e.joinChannelServiceRecords,t.record]:(e.joinChannelServiceRecords[t.index]=YN(YN({},e.joinChannelServiceRecords[t.index]),t.record),e.joinChannelServiceRecords=[...e.joinChannelServiceRecords]),e;case aL.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return e.joinChannelServiceRecords=[],e;case aL.RESET_KEY_METRICS:return e.keyMetrics={publish:[],subscribe:[],firstVideoFrameDecoded:[]},e;case aL.SET_USE_P2P:return YN(YN({},e),{},{useP2P:t.val});case aL.SET_TRANSPORT_TYPE:return YN(YN({},e),{},{p2pTransport:t.val});case aL.SET_RTE_URL:return YN(YN({},e),{},{rteUrl:t.rteUrl});case aL.SET_RTE_SID:return YN(YN({},e),{},{rteSid:t.rteSid});default:return e}}(this.state,e)}get useDcSignal(){return this.state.useDcSignal}set useDcSignal(e){this.state.useDcSignal=e}set autoSubscribe(e){this.state.autoSubscribe=e}get autoSubscribe(){return this.state.autoSubscribe}set enableInstantMuteRestore(e){this.state.enableInstantMuteRestore=e}get enableInstantMuteRestore(){return this.state.enableInstantMuteRestore}set networkQualityProbe(e){this.state.networkQualityProbe=e}get networkQualityProbe(){return this.state.networkQualityProbe}set preSubOptions(e){this.state.preSubOptions=e}get preSubOptions(){return this.state.preSubOptions}set sessionId(e){this.dispatch({type:aL.SET_SESSION_ID,sessionId:e})}get sessionId(){return this.state.sessionId}set rteUrl(e){this.dispatch({type:aL.SET_RTE_URL,rteUrl:e})}get rteUrl(){return this.state.rteUrl}set rteSid(e){this.dispatch({type:aL.SET_RTE_SID,rteSid:e})}get rteSid(){return this.state.rteSid}set cid(e){this.state.cid=e}get cid(){return this.state.cid}set codec(e){this.state.codec=e}get codec(){return this.state.codec}get mode(){return this.state.mode}get audioCodec(){return this.state.audioCodec}get clientId(){return this.state.clientId}set p2pId(e){this.dispatch({type:aL.SET_P2P_ID,p2pId:e})}get p2pId(){return this.state.p2pId}set dcId(e){this.dispatch({type:aL.SET_DC_ID,dcId:e})}get dcId(){return this.state.dcId}set uid(e){this.dispatch({type:aL.SET_UID,uid:e})}get uid(){return this.state.uid}set intUid(e){this.dispatch({type:aL.SET_INT_UID,intUid:e})}get intUid(){return this.state.intUid}set pubId(e){this.dispatch({type:aL.SET_PUB_ID,pubId:e})}get pubId(){return this.state.pubId}set cloudProxyServerMode(e){this.dispatch({type:aL.SET_CLOUD_PROXY_SERVER_MODE,mode:e})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}set useP2P(e){this.dispatch({type:aL.SET_USE_P2P,val:e})}get useP2P(){return this.state.useP2P}set p2pTransport(e){this.dispatch({type:aL.SET_TRANSPORT_TYPE,val:e})}get p2pTransport(){return this.state.p2pTransport}set hasStartJoinChannel(e){this.state.hasStartJoinChannel=e}get hasStartJoinChannel(){return this.state.hasStartJoinChannel}set isABTestSuccess(e){this.state.isABTestSuccess=e}get isABTestSuccess(){return this.state.isABTestSuccess}clientCreated(){this.dispatch({type:aL.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:aL.KEY_METRIC_JOIN_START,metric:Date.now()})}preloadStart(){this.dispatch({type:aL.KEY_METRIC_PRELOAD_START,metric:Date.now()})}preloadEnd(){this.dispatch({type:aL.KEY_METRIC_PRELOAD_END,metric:Date.now()})}joinEnd(){this.dispatch({type:aL.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:aL.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:aL.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}requestSUAEnd(){this.dispatch({type:aL.KEY_METRIC_REQUEST_SUA_END,metric:Date.now()})}beforeConnect(){this.dispatch({type:aL.KEY_METRIC_BEFORE_CONNECT,metric:Date.now()})}peerReceiver(){this.dispatch({type:aL.KEY_METRIC_PEER_RECEIVER,metric:Date.now()})}signalConnected(){this.dispatch({type:aL.KEY_METRIC_SIGNAL_CONNECTED,metric:Date.now()})}joinReq(){this.dispatch({type:aL.KEY_METRIC_JOIN_REQ,metric:Date.now()})}joinRep(){this.dispatch({type:aL.KEY_METRIC_JOIN_REP,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:aL.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:aL.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:aL.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:aL.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}firstVideoFrameDecoded(e,t){this.dispatch({type:aL.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED,metric:YN({userId:e},t)})}descriptionStart(){this.dispatch({type:aL.KEY_METRIC_DESCRIPTION_START,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:aL.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:aL.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(e,t,n,i){this.dispatch({type:aL.KEY_METRIC_PUBLISH,metric:YN(YN({trackId:e,type:t},n&&{publishStart:n}),i&&{publishEnd:i})})}subscribe(e,t,n,i,r,o,s){this.dispatch({type:aL.KEY_METRIC_SUBSCRIBE,metric:YN(YN(YN(YN(YN({userId:e,type:t},n&&{subscribeStart:n}),i&&{subscribeEnd:i}),r&&{firstFrame:r}),o&&{streamAdded:o}),s&&{firstDecoded:s})})}massSubscribe(e,t,n,i){e.forEach((e=>{this.dispatch({type:aL.KEY_METRIC_SUBSCRIBE,metric:YN(YN(YN({userId:e.userId,type:e.type},t&&{subscribeStart:t}),n&&{subscribeEnd:n}),i&&{firstFrame:i})})}))}get keyMetrics(){return this.state.keyMetrics}recordJoinChannelService(e,t){"gateway"===e.service&&Array.isArray(e.urls)&&(e.urls=e.urls.map((e=>e.replace(/(\d+)-\d+-\d+-(\d+)/,"$1-*-*-$2"))));try{return"number"!=typeof t?(this.dispatch({type:aL.RECORD_JOIN_CHANNEL_SERVICE,record:YN(YN({},e),{},{sessionId:this.sessionId,cloudProxyMode:this.cloudProxyServerMode,uid:this.uid})}),this.state.joinChannelServiceRecords.length-1):(t<0||t>=this.state.joinChannelServiceRecords.length||this.dispatch({type:aL.RECORD_JOIN_CHANNEL_SERVICE,record:e,index:t}),t)}catch(e){return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:aL.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:aL.RESET_KEY_METRICS})}resetFirstVideoFrameDecoded(){this.dispatch({type:aL.RESET_FIRST_VIDEO_FRAME_DECODED})}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords}catch(e){return[]}}}(e.codec,e.audioCodec,e.mode,this._clientId,1===rL("SIGNAL_CHANNEL")),this._leaveMutex=new _P("client-leave",this._clientId),this._publishMutex=new _P("client-publish",this._clientId),this._renewTokenMutex=new _P("client-renewtoken",this._clientId),this._subscribeMutex=new _P("client-subscribe",this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),FL.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(JP," build: ").concat(eL,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),e.clientRoleOptions)try{yD(e.clientRoleOptions),n=Object.assign({},e.clientRoleOptions)}catch(e){FL.warning("[".concat(this._clientId,"] ").concat(e.toString()))}var i;this._statsCollector=new Jte(this.store),this._statsCollector.onStatsException=(e,t,n)=>{FL.warn("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(n)),e===Kte.VIDEO_ENCODE_FAILED&&this.localTracks.forEach((e=>{e instanceof jV&&rL("ENABLE_ENCODE_EXCEPTION")&&e.findClosestProfile()})),this.safeEmit(bD.EXCEPTION,{code:e,msg:t,uid:n})},this._statsCollector.onUploadPublishDuration=(e,t,n,i)=>{const r=this._users.find((t=>t.uid===e));if(r){this.store.keyMetrics&&(this.store.firstVideoFrameDecoded(r.uid,{peerPublishDuration:n,peerPubStatusMs:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(r)),uk.peerPublishStatus(this._sessionId,{subscribeElapse:i,audioPublishDuration:t,videoPublishDuration:n,peer:r._uintid})}},this._statsCollector.onVideoCodecChanged=e=>{if(rL("VIDEO_STANDARD_BITRATE_VERSION")&&("av1"===e||"h265"===e||"h264"===e)){const t=this.localTracks.find((e=>e instanceof BV));t&&1!==t._saveEncodeBitrateRatio&&t.setSaveEncodeBitrateRatio("h264"===e?rL("BASELINE_MORE_H264_BITRATE_RATIO"):void 0)}},this.store.useP2P="p2p"===e.mode,this._gateway=new qee(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:e.websocketRetryConfig||mP,httpRetryConfig:e.httpRetryConfig||mP,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:n}),this._configDistribute=new Gte(this._clientId,this.store),this.store.useP2P?(this._p2pChannel=(i={store:this.store,statsCollector:this._statsCollector},Kee("P2PChannel").create(i)),this._handleP2PEvents()):this._p2pChannel=new sie(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents()}async joinMeta(e,t,n,i,r){let o=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],s=arguments.length>6&&void 0!==arguments[6]&&arguments[6];iL("JOIN_GATEWAY_USE_443PORT_ONLY",o),iL("JOIN_GATEWAY_USE_DUAL_DOMAIN",s);const a=this._gateway.signal.websocket;return a instanceof VB&&(a.use443PortOnly=o,a.tryDoubleDomain=s),async function(e,t,n){tN.get(e)||tN.set(e,[]),nN.get(e)||nN.set(e,t),iN.get(e)||iN.set(e,0);const i=tN.get(e),r=nN.get(e);if(!i||!r)throw new Error("concurrent: deferQueue or maxConcurrency is null");if(iN.get(e)===r){const e=eN();i.push(e),await e.promise}iN.set(e,iN.get(e)+1);for(var o=arguments.length,s=new Array(o>3?o-3:0),a=3;a<o;a++)s[a-3]=arguments[a];const c=await n(...s);return iN.set(e,iN.get(e)-1),iN.get(e)===r-1&&i.length>0&&(i[0].resolve(),i.shift()),0===iN.get(e)&&(tN.set(e,[]),nN.set(e,0),iN.set(e,0)),c}("client.join",rL("JOIN_MAX_CONCURRENCY"),this.join.bind(this),e,t,n,i,r)}async join(e,t,n,i,r){const o=++this._numberOfJoinCount;this.store.joinStart(),i&&(this.store.uid=i);const s="HTTPS"===(SP||SP||(SP=(window.location.protocol.split(":")[0]||"").toUpperCase(),SP)),a=CP()?window.isSecureContext:"Browser Not Support";if(!CP()&&!s||!window.isSecureContext){const e="The website must be running in a secure context (About secure context: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts ), otherwise the media collection will be restricted by the browser";FL.warning(e)}let c;uk.setAppId(e);try{if(!n&&null!==n)throw new hk(JN.INVALID_PARAMS,"Invalid token: ".concat(n,". If you don not use token, set it to null"));if(n&&eD(n,"token",1,2047),eD(e,"appid",1,2047),OF(t),i&&NF(i),r)if("string"==typeof r)eD(r,"optionalInfo",1,256),c=r;else{if("object"!=typeof r)throw new hk(JN.INVALID_PARAMS,"Invalid options: options is not a string or object");{const e=r.autoSubscribe,t=r.enableInstantMuteRestore,n=r.networkQualityProbe,i=r.preSubOptions;e&&(ZN(e,"autoSubscribe"),FL.info("[".concat(this._clientId,"] join: autoSubscribe: ").concat(e)),this.store.autoSubscribe=e),t&&(ZN(t,"enableInstantMuteRestore"),FL.info("[".concat(this._clientId,"] join: enableInstantMuteRestore: ").concat(t)),this.store.enableInstantMuteRestore=t),n&&(ZN(n,"networkQualityProbe"),FL.info("[".concat(this._clientId,"] join: networkQualityProbe: ").concat(n)),this.store.networkQualityProbe=n),Array.isArray(i)&&(tD(i,"preSubOptions"),i.forEach((e=>{NF(e.uid),function(e,t){if("string"!=typeof e&&!(e instanceof HTMLElement||e instanceof HTMLVideoElement))throw new zN(JN.INVALID_PARAMS,"".concat(t," should be a string or a HTML element"))}(e.element,"element")})),FL.info("[".concat(this._clientId,"] join: preSubOptions: ").concat(i.map((e=>"".concat(e.uid,": ").concat("string"==typeof e.element?e.element:e.element.id))).join(","))),this.store.preSubOptions=i)}}}catch(r){throw uk.reportApiInvoke(tP(),{name:ED.JOIN,options:[e,t,n,i],states:{isHttps:s,isSecureContext:a},tag:mD.TRACER}).onError(r),r}if(this._leaveMutex.isLocked){FL.debug("[".concat(this._clientId,"] join: waiting leave operation"));(await this._leaveMutex.lock())(),FL.debug("[".concat(this._clientId,"] join: continue"))}if(this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){const r=new hk(JN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw uk.reportApiInvoke(tP(),{name:ED.JOIN,options:[e,t,n,i],states:{isHttps:s,isSecureContext:a},tag:mD.TRACER}).onError(r),r}this._gateway.state="CONNECTING",this.store.preloadStart();const d=await kie({appId:e,cname:t,uid:i,stringUid:"string"==typeof i?i:void 0,token:n||e,cloudProxyServer:this._cloudProxyServerMode});if(this.store.preloadEnd(),!this._joinAndNotLeaveYet)throw new hk(JN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));const l=(null==d?void 0:d.sid)||tP();FL.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(o)),this._sessionId||(this._sessionId=l,this.store.sessionId=this._sessionId);const u=uk.reportApiInvoke(this._sessionId,{id:this._clientId,name:ED.JOIN,options:[e,t,n,i],states:{isHttps:s,isSecureContext:a},tag:mD.TRACER}),h=_oe(_oe(_oe({},this._rtmConfig),{},{role:this.role,clientId:this._clientId,appId:e,sid:this._sessionId,cname:t,uid:"string"!=typeof i?i:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:n||e,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:c,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint,preload:!!d},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType}),{},{apRequestDetail:rL("AP_REQUEST_DETAIL")||void 0});if(this._useLocalAccessPoint&&(h.setLocalAPVersion=this._setLocalAPVersion),"string"==typeof i&&(h.stringUid=i,this._uintUid?(h.uid=this._uintUid,this._uintUid=void 0):h.uid=0),"none"!==this._encryptionMode&&this._encryptionSecret){if(h.aesmode=this._encryptionMode,h.aespassword=await(async e=>{const t=function(e){const t=window.atob("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCMnXAHkKIGAM+x4N22gCI+Wyu\nSTM9ztkT3uYslTT2PuKmZfPzhH6kVdO7PTjGCOZnAsyb3oTtWat0KcxQ4jxvqQV+\nHvYl3iI1Yd4vl2c3qRMJPLtRDfNxa2Mcxgq7e9aEUibzdd0st+OJAy3tOj/Y0aVy\nxQiYDz3vqa6bP29adwIDAQAB"),n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}(),n=await window.crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"]),i=dD(e),r=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},n,i);return function(e){let t="";for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return window.btoa(t)}(new Uint8Array(r))})(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new hk(JN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this._encryptionSalt&&(h.aessalt=this._encryptionSalt)}if(this._encryptDataStream&&("aes-128-gcm2"===this._encryptionMode||"aes-256-gcm2"===this._encryptionMode))if(this._encryptionSalt&&this._encryptionSecret)if(window.crypto.subtle){const e=new TextEncoder,t=rL("USE_PURE_ENCRYPTION_MASTER_KEY")?e.encode(h.appId+this._encryptionSecret+this._encryptionSecret):e.encode(h.appId+h.cname+this._encryptionSecret);this._encryptDataStreamIv=await async function(e,t,n){const i=await window.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits","deriveKey"]),r="aes-128-gcm2"===e?128:256,o=await window.crypto.subtle.deriveBits({name:"PBKDF2",iterations:uL,hash:"SHA-256",salt:n},i,r+lL);return new Uint8Array(o).subarray(r/8)}(this._encryptionMode,t,YD(this._encryptionSalt)),this._encryptDataStreamKey=await async function(e,t,n){const i=await window.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits","deriveKey"]),r="aes-128-gcm2"===e?128:256;return await window.crypto.subtle.deriveKey({name:"PBKDF2",iterations:uL,hash:"SHA-256",salt:n},i,{name:"AES-GCM",length:r},!0,["encrypt","decrypt"])}(this._encryptionMode,t,YD(this._encryptionSalt))}else a?FL.warning("[".concat(this._clientId,"] encrypt datastream must be running in a secure context, fallback to plain data stream")):FL.warning("[".concat(this._clientId,"] current browser do not support WebCrypto ,fallback to plain data stream")),this._encryptDataStream=!1;else this._encryptDataStream=!1,FL.debug("[".concat(this._clientId,"] no salt / secret, cannot support encrypt data stream, fallback to plain data stream"));this._startSession(this._sessionId,{channel:t,appId:e,stringUid:h.stringUid});const p=this._sessionId;setTimeout((()=>{"CONNECTING"===this.connectionState&&p===this._sessionId&&uk.joinChannelTimeout(this._sessionId,5)}),5e3);try{var _;let i;const r=h.cloudProxyServer;if(Vi(_=["proxy3","proxy4","proxy5"]).call(_,r)){const e=rL("PROXY_SERVER_TYPE3");Array.isArray(e)?h.proxyServer=e[0]:h.proxyServer=e}if(uk.setProxyServer(h.proxyServer),FL.setProxyServer(h.proxyServer),this.store.requestAPStart(),rL("ENABLE_JOIN_V4")&&"disabled"===h.cloudProxyServer)try{h.stringUid&&!h.uid&&(h.uid=await Lte(h.stringUid,h,this._axiosCancelSource.token,this._config.httpRetryConfig||mP,this.store).finally((()=>{this.store.requestSUAEnd()})),FL.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(h.stringUid," => ").concat(h.uid))),FL.debug("[".concat(this._clientId,"] try use best first frame line"));const e=await this._p2pChannel.startP2PConnection({isPreallocation:!0});i=await Pte(h,this._axiosCancelSource.token,this._config.httpRetryConfig||mP,this.store,e),FL.debug("[".concat(this._clientId,"] get serverInfo from sdp endpoint")),rL("ENABLE_SDP_ENDPOINT_LOG")&&FL.debug("[".concat(this._clientId,"] serverInfo: "),i)}catch(e){i=void 0,FL.debug("[".concat(this._clientId,"] join channel with sdp endpoint failed, fallback to normal join ap"),e)}if(i);else if(d){if(FL.debug("[".concat(this._clientId,"] get serverInfo Success from Preload Cache ").concat(h.stringUid?", ".concat(h.stringUid," => ").concat(d.intUid):""," ")),h.stringUid&&!h.uid&&(h.uid=d.intUid),i={gatewayInfo:d.ap.gatewayInfo},rL("JOIN_WITH_FALLBACK_MEDIA_PROXY")&&"auto"===h.turnServer.mode)if(0===d.ap.proxyInfo.addresses.length)FL.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers");else{const e=(await eee(d.ap.proxyInfo,d.ap.gatewayInfo.uid)).map((e=>({turnServerURL:e.address,tcpport:e.tcpport||qP.tcpport,udpport:e.udpport||qP.udpport,username:e.username||qP.username,password:e.password||qP.password,forceturn:!1,security:!0})));h.turnServer={mode:"manual",servers:e}}Fie(d,h.stringUid)}else{if(h.stringUid&&!h.uid){let e;var E=Hb(await dp.all([Lte(h.stringUid,h,this._axiosCancelSource.token,this._config.httpRetryConfig||mP,this.store).finally((()=>{this.store.requestSUAEnd()})),Dte(h,this._axiosCancelSource.token,this._config.httpRetryConfig||mP,!0,this.store).finally((()=>{this.store.requestAPEnd()}))]),2);e=E[0],i=E[1],FL.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(h.stringUid," => ").concat(e)),h.uid=e,i.gatewayInfo.uid=e,i.gatewayInfo.res.uid=e}else i=await Dte(h,this._axiosCancelSource.token,this._config.httpRetryConfig||mP,!0,this.store);if(!this._joinAndNotLeaveYet)throw new hk(JN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"))}this.store.requestAPEnd(),setTimeout((()=>{this._configDistribute.startGetConfigDistribute(h,this._axiosCancelSource.token),this._configDistribute.on(QF.UPDATE_BITRATE_LIMIT,(e=>{this._p2pChannel.updateBitrateLimit(e)})),this._configDistribute.on(QF.UPDATE_CLIENT_ROLE_OPTIONS,(e=>{this._setClientRoleOptions(e)})),this._configDistribute.on(QF.UPDATE_REMOTE_VIDEO_STREAM_TYPE,(e=>{var t;Vi(t=[0,1,4,5,6,7,8,9]).call(t,e)&&(this.remoteUsers.forEach((t=>{this._remoteStreamTypeCacheMap.get(t.uid)!==e&&this.setRemoteVideoStreamType(t.uid,e)})),this.setRemoteDefaultVideoStreamType(e))})),this._configDistribute.on(QF.FALLBACK_TO_HLS,(e=>{e&&this.safeEmit(bD.FALLBACK_TO_HLS,CD.CONFIG)})),this._configDistribute.on(QF.UPDATE_VOS_CONFIGURE,(e=>{this._gateway.setConfigure(e).catch((e=>{FL.debug("[".concat(this._clientId,"] auto set vos config failed"),e)}))}))}),0),this._key=n||e;const o=i.gatewayInfo,s=h.uid?h.uid:o.uid;this._joinInfo=_oe(_oe({},h),{},{cid:o.cid,uid:s,vid:o.vid,apResponse:o.res,apGatewayAddress:o.apGatewayAddress,uni_lbs_ip:o.uni_lbs_ip,gatewayAddrs:o.gatewayAddrs,signalResponse:o.res.signalResponse}),this.store.intUid=s,this.store.cid=o.cid;const a=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new hk(JN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));u.onSuccess(a),this._appId=e,this._channelName=h.cname,this._uid=a,this.store.uid=a,setTimeout((()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),!EN()&&this.store.useDcSignal?(window.addEventListener("beforeunload",this._handleBeforeUnload),window.addEventListener("pagehide",this._handleBeforeUnload)):window.addEventListener(EN()?"beforeunload":"pagehide",this._handleBeforeUnload),this._statsCollector.startUpdateStats()}),0);const c=h.stringUid?"string uid: ".concat(h.stringUid,",uid: ").concat(h.uid):"uid: ".concat(this._uid);return FL.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(c)),setTimeout((()=>{FL.startUpload()}),5e3),this.store.joinEnd(),m=this,Vi(Zx).call(Zx,m)||Zx.push(m),"disabled"===this._cloudProxyServerMode&&_k().supportWebCrypto&&rL("ENABLE_PRELOAD")&&Vie(this._joinInfo),this._rteDetailInterval&&(window.clearInterval(this._rteDetailInterval),this._rteDetailInterval=void 0),this._sessionId&&uk.reportRteDetail(this._sessionId),this._rteDetailInterval=window.setInterval((()=>{this._sessionId&&uk.reportRteDetail(this._sessionId)}),rL("RTE_DETAIL_REPORT_INTERVAL")||6e4),a}catch(e){const t=Array.isArray(e)?e[0]:e;throw t&&t.code===JN.OPERATION_ABORTED?FL.warning("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),t):FL.error("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),t),t.code!==JN.OPERATION_ABORTED&&this._numberOfJoinCount===o&&(this._gateway.state="DISCONNECTED",this._reset()),u.onError(t),t}var m}async _joinGateway(){if(!this._joinInfo||!this._key)throw new hk(JN.INVALID_OPERATION);try{return await this._gateway.join(this._joinInfo,this._key,!("disabled"!==this._joinInfo.cloudProxyServer||this._joinInfo.proxyServer||!rL("JOIN_WITH_FALLBACK_SIGNAL_PROXY")))}catch(e){if(e.code===JN.INIT_DATACHANNEL_TIMEOUT){if(this._gateway.leave(!0,SD.FALLBACK),FL.debug("[".concat(this._clientId,"] join by datachannel timeout, fallback to websocket")),!this._joinInfo||!this._key)throw new hk(JN.INVALID_OPERATION);return uk.reportApiInvoke(this._sessionId,{name:ED.DATACHANNEL_FAILBACK,options:[this.store.clientId],tag:mD.TRACER}).onSuccess(),await this._joinGateway()}throw e}}async leave(){FL.info("[".concat(this._clientId,"] Leaving channel"));const e=()=>{!EN()&&this.store.useDcSignal?(window.addEventListener("beforeunload",this._handleBeforeUnload),window.addEventListener("pagehide",this._handleBeforeUnload)):window.addEventListener(EN()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){const t=Zx.indexOf(e);-1!==t&&Zx.splice(t,1)}(this),this._statsCollector.stopUpdateStats()};this.store.useDcSignal||e();const t=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return FL.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void t();await this._gateway.leave("CONNECTED"!==this.connectionState,SD.LEAVE),FL.info("[".concat(this._clientId,"] Leaving channel success")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),t(),this.store.useDcSignal&&e()}async publish(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Array.isArray(e)){if(!(e instanceof mM))return this._publishDataChannel(e);e=[e]}if(0===e.length)throw new hk(JN.INVALID_PARAMS,"param list is empty");const n=e;if("audience"===this._gateway.role)throw new hk(JN.INVALID_OPERATION,"audience can not publish stream");for(const e of n){if(!(e instanceof mM))throw new hk(JN.INVALID_PARAMS,"parameter is not local track");if(!e._enabled&&t)throw new hk(JN.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(e.getTrackId()))}FL.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(n.map((e=>"".concat(e.getTrackId()," ")))));const i=await this._publishMutex.lock();await this._configDistribute.awaitConfigDistributeComplete(),t&&n.forEach((e=>{const t=this._configDistribute.getBitrateLimit();e instanceof BV&&t&&e.setBitrateLimit(t.uplink)}));try{await this._publishHighStream(n),FL.info("[".concat(this._clientId,"] Publish success, id ").concat(n.map((e=>"".concat(e.getTrackId()," ")))))}catch(e){throw FL.error("[".concat(this._clientId,"] publish error"),e.toString()),e}finally{i()}}async _publishDataChannel(e){if(null==e)throw new hk(JN.INVALID_PARAMS,"parameter is not local track or datachannel config, config is ".concat(JSON.stringify(e)));QN(e.id,"id",0,65535,!0),ZN(e.ordered,"ordered"),eD(e.metadata,"metadata",0,512),FL.info("[".concat(this._clientId,"] Publishing datachannels, id ").concat(e.id));const t=await this._publishMutex.lock();try{if(-1!==this._p2pChannel.getAllDataChannels().findIndex((t=>t.id===e.id)))throw new hk(JN.INVALID_PARAMS,"Invalid id: ".concat(e.id,". If you want to republish the datachannel, unpublish first"));if(!this._joinInfo||void 0===this._uid)throw new hk(JN.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new hk(JN.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&rL("FORCE_TURN")&&!rL("TURN_ENABLE_TCP")&&!rL("TURN_ENABLE_UDP"))throw new hk(JN.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");const n=function(e){return Hee(e,!1)}(e),i=await this._p2pChannel.publishDataChannel([n]);if(i.length>0){if("number"!=typeof n._originDataChannelId)throw FL.error("[".concat(this._clientId,"] can not publish with mediaType datachannel, cannot get RTCDatachannel id")),new hk(JN.CREATE_DATACHANNEL_ERROR);try{await dp.all(i.map((e=>this._uid&&this._gateway.publishDataChannel(this._uid,e,!0)))),await n._waitTillOpen()}catch(e){if(e.code!==JN.DISCONNECT_P2P)throw e}}return FL.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(n.id)),n}catch(e){throw FL.error("[".concat(this._clientId,"] publish datachannels error"),e.toString()),e}finally{t()}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new hk(JN.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let t=[];if(e)if(Array.isArray(e))t=e;else{if(!(e instanceof mM))return this._unpublishDataChannel([e]);t=[e]}else this.store.useP2P||await this._unpublishDataChannel(),t=this._p2pChannel.getAllTracks(!0);FL.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(t.map((e=>"".concat(e.getTrackId()," ")))," "));const n=await this._publishMutex.lock();try{if(this.store.useP2P){const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.sendExtensionMessage(gB.UNPUBLISH,{unpubMsg:e},!0)}else{const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.unpublish(e,this._uid),FL.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(t.map((e=>"".concat(e.getTrackId())))))}}catch(e){throw FL.error("[".concat(this._clientId,"] unpublish error"),e.toString()),e}finally{n&&n()}}async _unpublishDataChannel(e){void 0!==e&&0!==e.length||(e=this._p2pChannel.getAllDataChannels()),FL.info("[".concat(this._clientId,"] Unpublish datachannels, datachannels ").concat(e.map((e=>"".concat(e.id," ")))," "));const t=await this._publishMutex.lock();try{const n=await this._p2pChannel.unpublishDataChannel(e);n&&await this._gateway.unpublishDataChannel(n),FL.info("[".concat(this._clientId,"] Unpublish dataChannel success, dataChannel ids: ").concat(e.map((e=>"".concat(e.id)))))}catch(e){throw FL.error("[".concat(this._clientId,"] unpublish dataChannel error"),e.toString()),e}finally{t&&t()}}async subscribe(e,t,n){if(!(e instanceof qte)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new hk(JN.INVALID_REMOTE_USER,"user is not in the channel");e=t}return"datachannel"===t?this._subscribeDataChannel(e,n):this._subscribe(e,t)}async presubscribe(e,t){if(qN(t,"mediaType",["audio","video"]),this.store.useP2P)throw new hk(JN.INVALID_OPERATION,"can't presub at p2p mode");if(!this._joinInfo)throw new hk(JN.INVALID_OPERATION,"can't presub when not join");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new hk(JN.INVALID_OPERATION,"can't presub in ".concat(this.connectionState," state"));const n=t===nB.AUDIO,i=t===nB.VIDEO,r=await this._subscribeMutex.lock();try{const o=await this._gateway.presubscribe(e,t,!0),s=o.ssrcId,a=o.ortc,c=o.rtxSsrcId,d=o.cname,l=o.uint_id;if(null==s)throw new hk(JN.UNEXPECTED_RESPONSE,"no ssrc id");let u=this._users.find((t=>t.uid===e));u||(u=new qte(e,l||e),u._is_pre_created=!0,this._users.push(u)),d&&(u._cname=d),u._uintid||(u._uintid=l||e),n&&(u._audioSSRC=s,u._audio_pre_subscribed=!0,a&&(u._audioOrtc=a)),i&&(u._videoSSRC=s,u._video_pre_subscribed=!0,a&&(u._videoOrtc=a),null!=c&&(u._rtxSsrcId=c)),FL.info("[".concat(this._clientId,"] presub succeed ssrc: ").concat(s)),await this._p2pChannel.subscribe(u,t,s,c,a);const h=n?u._audioTrack:u._videoTrack;if(!h)throw new hk(JN.UNEXPECTED_ERROR,"can not find remote track in user");return n&&(u._trust_audio_stream_added_state_=!0,u._audio_added_=!0),i&&(u._trust_video_stream_added_state_=!0,u._video_added_=!0),h}catch(t){throw FL.error("[".concat(this._clientId,"] presub user ").concat(e," error"),t),t}finally{r()}}async _subscribeDataChannel(e,t){var n;if(QN(t,"channelId",0,65535,!0),!this._joinInfo)throw new hk(JN.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new hk(JN.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));const i=this._users.find((t=>t===e));if(!i)throw FL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),new hk(JN.INVALID_REMOTE_USER,"user is not in the channel");if(!e.hasAudio&&!e.hasVideo&&0===e._dataChannels.length)throw FL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),new hk(JN.INVALID_REMOTE_USER,"user is not published");const r=null===(n=e._dataChannels)||void 0===n?void 0:n.find((e=>e.id===t));if(!r)throw FL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, remote datachannel is not published")),new hk(JN.REMOTE_USER_IS_NOT_PUBLISHED);const o=await this._subscribeMutex.lock();FL.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: datachannel"));try{const t=await this._p2pChannel.subscribeDataChannel(e,[r]);if(t&&Vi(t).call(t,r.id))try{var s;if("number"!=typeof r._originDataChannelId)throw FL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, cannot get RTCDatachannel")),new hk(JN.CREATE_DATACHANNEL_ERROR);const t={id:r.id,datachannelId:r._originDataChannelId,ordered:r.ordered,maxRetransmits:r.maxRetransmits,metadata:null!==(s=r.metadata)&&void 0!==s?s:""};await this._gateway.subscribeDataChannel(e.uid,t,!0),await r._waitTillOpen()}catch(t){if((null==t?void 0:t.code)!==JN.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(e,[r]),t;await this._p2pChannel.unsubscribeDataChannel(e,[r]),this._p2pChannel.setPendingRemoteDataChannel(e,r.id)}return FL.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: datachannel")),r}finally{o()}}async _p2pSubscribe(e,t,n){if(qN(t,"mediaType",["audio","video"]),!this._joinInfo)throw new hk(JN.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new hk(JN.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const i=this._users.find((t=>t===e));if(!i){const t=new hk(JN.INVALID_REMOTE_USER,"user is not in the channel");throw FL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t}if(!e.hasAudio&&!e.hasVideo){const t=new hk(JN.INVALID_REMOTE_USER,"user is not published");throw FL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!n&&("audio"===t&&!e.hasAudio||"video"===t&&!e.hasVideo)){const n=new hk(JN.REMOTE_USER_IS_NOT_PUBLISHED);throw FL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),n}const r=await this._subscribeMutex.lock();FL.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const n="audio"===t?e._audioSSRC:e._videoSSRC,i="audio"===t?e._audioMid:e._videoMid;this.store.subscribe(e.uid,t,Date.now()),this.store.useP2P&&await this._p2pChannel.subscribe(e,t,n,i)}catch(e){throw e}FL.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),void 0!==this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{FL.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const n="audio"===t?e._audioTrack:e._videoTrack;if(!n)throw new hk(JN.UNEXPECTED_ERROR,"can not find remote track in user object");return n}catch(t){throw FL.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{r()}}async _subscribe(e,t,n){if(this.store.useP2P)return this._p2pSubscribe(e,t);if(qN(t,"mediaType",["audio","video"]),!this._joinInfo)throw new hk(JN.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new hk(JN.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const i=this._users.find((t=>t===e));if(!i){const t=new hk(JN.INVALID_REMOTE_USER,"user is not in the channel");throw FL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t}if(!e.hasAudio&&!e.hasVideo){const t=new hk(JN.INVALID_REMOTE_USER,"user is not published");throw FL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!(n||("audio"!==t||e.hasAudio&&void 0!==e._audioSSRC)&&("video"!==t||e.hasVideo&&void 0!==e._videoSSRC))){const n=new hk(JN.REMOTE_USER_IS_NOT_PUBLISHED);throw FL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),n}let r="audio"===t?e._audioSSRC:e._videoSSRC,o="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,a={stream_type:"audio"===t?nB.AUDIO:nB.VIDEO,ssrcId:r};"video"===t&&this.store.firstVideoFrameDecoded(e.uid,{subscribeStart:Date.now()});const c=await this._subscribeMutex.lock();FL.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const n="audio"===t?e._audioSSRC:e._videoSSRC;void 0!==n&&n!==r&&(r=n,o="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,a={stream_type:"audio"===t?nB.AUDIO:nB.VIDEO,ssrcId:r}),Hte.markSubscribeStart(this.store.clientId,r),this.store.subscribe(e.uid,t,Date.now()),await this._p2pChannel.subscribe(e,t,r,s,o);try{this._p2pChannel.isPreSubScribe(r)||await this._gateway.subscribe(e.uid,a,!0)}catch(n){if((null==n?void 0:n.code)!==JN.WS_ABORT)throw await this._p2pChannel.unsubscribe(e,t),n;await this._p2pChannel.unsubscribe(e,t,!0),this._p2pChannel.setPendingRemoteMedia(e,t)}this.store.subscribe(e.uid,t,void 0,Date.now()),this._p2pChannel.reportSubscribeEvent(!0,null,e,t)}catch(n){throw this._p2pChannel.reportSubscribeEvent(!1,null==n?void 0:n.code,e,t),n}FL.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),void 0!==this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{FL.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const n="audio"===t?e._audioTrack:e._videoTrack;if(!n)throw new hk(JN.UNEXPECTED_ERROR,"can not find remote track in user object");return"video"===t&&(this.store.firstVideoFrameDecoded(e.uid,{subscribeEnd:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(e)),n}catch(t){throw FL.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{c()}}async massSubscribe(e){if(tD(e,"subscribeList"),!this._joinInfo)throw new hk(JN.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new hk(JN.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const t=Date.now(),n=new Map,i=await this._subscribeMutex.lock();FL.info("[".concat(this._clientId,"]start massSubscribe user ").concat(e.map((e=>{let t=e.user,n=e.mediaType;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(n)})).join("; ")));const r=(e=[...e]).map((e=>({user:e.user,mediaType:e.mediaType}))),o=await this._p2pChannel.globalLock();try{var s;for(let t=e.length-1;t>=0;t--){const i=e[t],o=i.user,s=i.mediaType;if(qN(s,"mediaType",["audio","video"]),!o){const e=new hk(JN.INVALID_PARAMS,"user property does not exist in subscribeList item");throw FL.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),e}const a=this._users.find((e=>e===o));if(!a){const n=new hk(JN.INVALID_REMOTE_USER,"user is not in the channel");FL.error("[".concat(this._clientId,"] can not massSubscribe ").concat(o.uid,", this user is not in the channel")),r[t].error=n,e.splice(t,1);continue}if("audio"===s&&(!o.hasAudio||void 0===o._audioSSRC)||"video"===s&&(!o.hasVideo||void 0===o._videoSSRC)){const n=new hk(JN.REMOTE_USER_IS_NOT_PUBLISHED);FL.error("[".concat(this._clientId,"] can not subscribe ").concat(o.uid," with mediaType ").concat(s,", remote user is not published")),r[t].error=n,e.splice(t,1);continue}const c=XF.Video|XF.LowVideo,d=n.get(o);if(d){if("video"===s?d&c:d&XF.Audio){e.splice(t,1),FL.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(o.uid,", mediaType:").concat(s," twice"));continue}n.set(o,d|("video"===s?c:XF.Audio))}else n.set(o,"video"===s?c:XF.Audio)}for(let t=e.length-1;t>=0;t--){const i=e[t],r=i.user,o=i.mediaType,s=XF.Video|XF.LowVideo;if(this._p2pChannel.hasRemoteMedia(r,o)){await this._p2pChannel.unmuteRemoteNoLock(r,o);const i=n.get(r);n.set(r,"video"===o?i^s:i^XF.Audio),e.splice(t,1)}}this.store.massSubscribe(e.map((e=>({userId:e.user.uid,type:e.mediaType}))),t);let a=ar(s=Array.from(n.entries())).call(s,((e,t)=>{let n=Hb(t,2),i=n[0],r=n[1];if(0===r)return e;const o={stream_id:i.uid,stream_type:r};return r&XF.Audio&&(o.audio_ssrc=i._audioSSRC),r&XF.Video&&(o.video_ssrc=i._videoSSRC),e.push(o),e}),[]);try{e.length>0&&await this._p2pChannel.massSubscribeNoLock(e.map((e=>{let t=e.user,n=e.mediaType;return{user:t,mediaType:n,ssrcId:n===nB.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:n===nB.VIDEO?t._rtxSsrcId:void 0}})));const n=new Map;if(a=a.filter((e=>e.video_ssrc&&!this._p2pChannel.isPreSubScribe(e.video_ssrc)||e.audio_ssrc&&!this._p2pChannel.isPreSubScribe(e.audio_ssrc)||!e.video_ssrc&&!e.audio_ssrc)),a.length>0){const e=await this._gateway.subscribeAll(a,!0);((null==e?void 0:e.users)||[]).forEach((e=>{let t=e.stream_id,i=e.video_error_code,r=e.audio_error_code,o=e.error_code;(i||r||o)&&n.set(t,{video_error_code:i,audio_error_code:r,error_code:o})}))}if(Array.from(n.entries()).length>0){const e=[];Array.from(n.entries()).forEach((t=>{let n=Hb(t,2),i=n[0],r=n[1];const o=this.remoteUsers.find((e=>e.uid===i));if(o){let t;r.error_code||r.video_error_code&&r.audio_error_code?t=void 0:r.video_error_code?t=nB.VIDEO:r.audio_error_code&&(t=nB.AUDIO),e.push({user:o,mediaType:t})}})),e.length>0&&await this._p2pChannel.massUnsubscribeNoLock(e)}for(const e of r){const t=n.get(e.user.uid);if(t){const n=t.error_code||"audio"===e.mediaType&&t.audio_error_code||"video"===e.mediaType&&t.video_error_code;if(n){const t=CB(n);FL.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new hk(JN.SUBSCRIBE_FAILED,"code ".concat(n,": ").concat(t.desc))}}e.error||("video"===e.mediaType?e.track=e.user.videoTrack:e.track=e.user.audioTrack)}return this.store.massSubscribe(r.filter((e=>!e.error)).map((e=>({userId:e.user.uid,type:e.mediaType}))),void 0,Date.now()),r.forEach((e=>{var n;uk.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null===(n=e.error)||void 0===n?void 0:n.code)||null,video:e.mediaType===nB.VIDEO,audio:e.mediaType===nB.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===nB.VIDEO?e.user._videoSSRC:e.user._audioSSRC,p2pid:this.store.p2pId,eventElapse:Math.floor(performance.now()-t),preSsrc:this._p2pChannel.isPreSubScribe(e.user._videoSSRC)},!0)})),FL.info("[".concat(this._clientId,"] massSubscribe success ").concat(e.map((e=>{let t=e.user,n=e.mediaType;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(n)})).join("; "))),r}catch(t){throw await this._p2pChannel.massUnsubscribeNoLock(e),t}}finally{o(),i()}}async unsubscribe(e,t,n){if(!(e instanceof qte)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new hk(JN.INVALID_REMOTE_USER,"user is not in the channel");e=t}if(t||this.store.useP2P){if("datachannel"===t)return this._unsubscribeDataChannel(e,n)}else await this._unsubscribeDataChannel(e,n);if(t&&qN(t,"mediaType",["audio","video"]),!this._joinInfo)throw new hk(JN.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");const i=this._users.find((t=>t===e));if(!i){const t=new hk(JN.INVALID_REMOTE_USER,"user is not in the channel");throw FL.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}FL.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: ").concat(t));const r=await this._subscribeMutex.lock();try{if(this.store.useP2P)await this._p2pChannel.unsubscribe(e,t);else{const n=await this._p2pChannel.unsubscribe(e,t);n&&await this._gateway.unsubscribe(n,e.uid),t&&"audio"!==t||(e._audio_pre_subscribed=!1),t&&"video"!==t||(e._video_pre_subscribed=!1),e._is_pre_created&&FD(this._users,e),FL.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t))}}catch(t){if(t.code===JN.DISCONNECT_P2P)return void FL.warning("disconnecting p2p, abort unsubscribe request.");throw FL.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}finally{r()}}async _unsubscribeDataChannel(e,t){if(t&&QN(t,"id",0,65535,!0),!this._joinInfo)throw new hk(JN.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");const n=this._users.find((t=>t===e));if(!n){const t=new hk(JN.INVALID_REMOTE_USER,"user is not in the channel");throw FL.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}let i;if("number"==typeof t){const n=e._dataChannels.find((e=>e.id===t));n&&(i=[n])}else i=e._dataChannels;if(void 0===i){const n=new hk(JN.REMOTE_USER_IS_NOT_PUBLISHED);throw FL.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid," with channelId ").concat(t,", remote datachannel is not published")),n}FL.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(i.map((e=>e.id))));try{const t=await this._p2pChannel.unsubscribeDataChannel(e,i);t&&await this._gateway.unsubscribeDataChannel(t,e.uid),FL.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(t))}catch(t){if(t.code===JN.DISCONNECT_P2P)return void FL.warning("disconnecting p2p, abort unsubscribe request.");throw FL.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}}async massUnsubscribe(e){if(tD(e,"unsubscribeList"),!this._joinInfo)throw new hk(JN.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");FL.info("[".concat(this._clientId,"] start massUnsubscribe ").concat(e.map((e=>{let t=e.user,n=e.mediaType;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(n,";")})).join())),e=[...e];const t=new Map;for(let n=e.length-1;n>=0;n--){const i=e[n],r=i.user,o=i.mediaType;if(!r){const e=new hk(JN.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw FL.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e}qN(o,"mediaType",["video","audio",void 0]);const s=this._users.find((e=>e===r));if(!s){FL.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(r.uid,", user is not in the channel")),e.splice(n,1);continue}const a=XF.Video|XF.LowVideo;if(t.has(r)){const i=t.get(r);let s;switch(o){case"video":s=i&a;break;case"audio":s=i&XF.Audio;break;default:s=i&(XF.Audio|a)}if(s){FL.warning("[".concat(this._clientId,"] repeat massUnsubscribe user:").concat(r.uid,",mediaType:").concat(o," twice.")),e.splice(n,1);continue}o?"audio"===o?t.set(r,i|XF.Audio):"video"===o&&t.set(r,i|a):t.set(r,i|XF.Audio|a)}else o?"audio"===o?t.set(r,XF.Audio):"video"===o&&t.set(r,a):t.set(r,XF.Audio|a)}try{const t=await this._p2pChannel.massUnsubscribe(e);t&&await this._gateway.massUnsubscribe(t),FL.info("[".concat(this._clientId,"] massUnsubscribe success ").concat(e.map((e=>{let t=e.user,n=e.mediaType;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(n,";")})).join()))}catch(e){if(e.code===JN.DISCONNECT_P2P)return void FL.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw FL.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e}}async setLowStreamParameter(e){!function(e){if(!e)throw new zN(JN.INVALID_PARAMS);nD(e.width)||$N(e.width,"streamParameter.width"),nD(e.height)||$N(e.height,"streamParameter.height"),nD(e.framerate)||$N(e.framerate,"streamParameter.framerate"),nD(e.bitrate)||QN(e.bitrate,"streamParameter.bitrate")}(e),(!e.width&&e.height||e.width&&!e.height)&&FL.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),FL.info("[".concat(this._clientId,"] set low stream parameter to"),JSON.stringify(e));const t=this._configDistribute.getLowStreamConfigDistribute();if(t&&t.bitrate&&e.bitrate&&t.bitrate<e.bitrate&&(e.bitrate=t.bitrate),this._lowStreamParameter=e,this._isDualStreamEnabled)return this._p2pChannel.updateVideoStreamParameter(e,sB.LocalVideoLowTrack)}async setDualStreamMode(e,t){qN(e,"mode",[0,1,-1]);try{switch(t&&await this.setLowStreamParameter(t),this._dualStreamMode=e,this._joinInfo?this._gateway.setDualStreamMode(e).catch((e=>{FL.warning("[".concat(this._clientId,"] set dual stream mode failed"),e.toString())})):FL.debug("[".concat(this._clientId,"] haven't joined yet, cache dual stream mode ").concat(e)),e){case vD.AUTO_SIMULCAST_STREAM:FL.info("[".concat(this._clientId,"] set dual stream mode to ").concat(e));break;case vD.DISABLE_SIMULCAST_STREM:return this.disableDualStream();case vD.ENABLE_SIMULCAST_STREAM:return this.enableDualStream()}}catch(e){throw FL.error("[".concat(this._clientId,"] set dual stream mode error"),e.toString()),e}}async enableDualStream(){if(!_k().supportDualStream)throw uk.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),new hk(JN.NOT_SUPPORTED,"Your browser is not support dual stream");if(this._isDualStreamEnabled)throw new hk(JN.INVALID_OPERATION,"Dual stream is already enabled");if(this._p2pChannel.canPublishLowStream())try{await this._publishLowStream()}catch(e){throw uk.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),e}this._isDualStreamEnabled=!0,this._dualStreamMode=vD.ENABLE_SIMULCAST_STREAM,this._joinInfo&&this._gateway.setDualStreamMode(this._dualStreamMode,!0,!0).catch((e=>{FL.debug("[".concat(this._clientId,"] try to inform gateway to set dual stream mode to ").concat(this._dualStreamMode," ,but failed"),e.toString())})),uk.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!0}),FL.info("[".concat(this._clientId,"] enable dual stream"))}async disableDualStream(){if(this._isDualStreamEnabled){if(!this._joinInfo)return this._isDualStreamEnabled=!1,void FL.info("[".concat(this._clientId,"] disable dual stream before join"));if(this._p2pChannel.getLocalMedia(sB.LocalVideoLowTrack))try{const e=await this._p2pChannel.unpublishLowStream();e&&await this._gateway.unpublish(e,this._joinInfo.stringUid||this._joinInfo.uid)}catch(e){throw uk.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!1}),e}this._isDualStreamEnabled=!1,this._dualStreamMode=vD.DISABLE_SIMULCAST_STREM,this._joinInfo&&this._gateway.setDualStreamMode(this._dualStreamMode,!0,!0).catch((e=>{FL.debug("[".concat(this._clientId,"] try to inform gateway to set dual stream mode to ").concat(this._dualStreamMode," ,but failed"),e.toString())})),uk.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!0}),FL.info("[".concat(this._clientId,"] disable dual stream"))}}async setClientRole(e,t){if(function(e){qN(e,"role",["audience","host"])}(e),t&&yD(t),"rtc"===this.mode||"p2p"===this.mode)throw FL.warning("[".concat(this._clientId,"]").concat(this.mode," mode can not use setClientRole")),new hk(JN.INVALID_OPERATION,"".concat(this.mode," mode can not use setClientRole"));if(t&&t.level&&"host"===e)throw new hk(JN.INVALID_OPERATION,"host mode can not set audience latency level");if("audience"===e&&this._p2pChannel.hasLocalMedia())throw new hk(JN.INVALID_OPERATION,"can not set client role to audience when publishing stream");const n=this._config.role;if(this._joinInfo&&(this._joinInfo.role=e),e!==n&&rL("ENABLE_ROLE_SELECT_EDGE")?(this._gateway.updateClientRole(e,t),this._config.role=e,this._gateway.reconnect("recover",ID.REGIONAL_DISTRIBUTION)):(await this._gateway.setClientRole(e,t),this._config.role=e),FL.info("[".concat(this._clientId,"] set client role to ").concat(e,", level: ").concat(t&&t.level)),"audience"===n&&"audience"!==e&&this._pendingRtpCapabilityChange&&this._p2pChannel instanceof sie){const e=this._pendingRtpCapabilityChange.video_codec;this._p2pChannel.updateRemoteRTPCapabilities(e.map((e=>e.toLowerCase())).filter((e=>{var t;return Vi(t=Object.keys(cL)).call(t,e)})))}}async _setClientRoleOptions(e){if("rtc"===this.mode||"p2p"===this.mode)return;if("audience"!==this._config.role||this._p2pChannel.hasLocalMedia())return;let t=!1;try{e&&yD(e),await this._gateway.setClientRole(this._config.role,e),t=!0}catch(e){}finally{FL.info("[".concat(this._clientId,"] set client role options ").concat(t?"succeed":"failed",", options is ").concat(e))}}getRemoteInboundOffset(){var e;const t=null===(e=this._p2pChannel.getStats())||void 0===e?void 0:e.audioSend[0];if(!t||!t.timestamp)return 0;const n=t.timestamp-Date.now();return Math.abs(n)>1e3+t.rttMs+100?this.ntpAlignErrorCount+=1:this.ntpAlignErrorCount=0,this.ntpAlignErrorCount>=3?n:0}getNtpWallTimeInMs(){return"visible"===document.visibilityState&&(this.remoteInboundOffset=this.getRemoteInboundOffset()),this.remoteInboundOffset+Date.now()+this._gateway.ntpOffset}setProxyServer(e,t){if(eD(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new hk(JN.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new hk(JN.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=e,uk.setProxyServer(this._proxyServer),FL.setProxyServer(this._proxyServer),FL.info("[".concat(this._clientId,"] Set proxy server ").concat(t?"by initialize call":""," success."))}setTurnServer(e,t){if(Array.isArray(e)||(e=[e]),!t){if("DISCONNECTED"!==this.connectionState)throw new hk(JN.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new hk(JN.INVALID_OPERATION,"You have already set the proxy")}if(TD(e))return this._turnServer={servers:e,mode:"original-manual"},void FL.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map((e=>e.urls)).join(","),"."));e.forEach((e=>RD(e))),this._turnServer={servers:e,mode:"manual"},FL.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."))}setLicense(e){if("DISCONNECTED"!==this.connectionState){throw new hk(JN.INVALID_OPERATION,"you should set license before join channel")}if(eD(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new hk(JN.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,FL.info("[".concat(this._clientId,"] set license success"),e)}startProxyServer(e){if("DISCONNECTED"!==this.connectionState)throw new hk(JN.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new hk(JN.INVALID_OPERATION,"You have already set the proxy");const t=[3,4,5];let n;switch(void 0===e&&(e=3),e){case 1:case 2:throw new hk(JN.NOT_SUPPORTED,"proxy mode 1/2 has been deprecated and not supported.");case 3:n="proxy3";break;case 4:n="proxy4";break;case 5:n="proxy5";break;default:throw new hk(JN.INVALID_PARAMS,"proxy server mode must be ".concat(t.join("|")))}this._cloudProxyServerMode=n,this.store.cloudProxyServerMode=n,FL.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new hk(JN.INVALID_OPERATION,"Stop proxy server after leave channel");uk.setProxyServer(),FL.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",FL.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode),this._proxyServer=void 0,this._turnServer={mode:"auto",servers:[]}}setLocalAccessPointsV2(e){if(!e.accessPoints)throw new hk(JN.INVALID_PARAMS,"accessPoints is required.");tD(e.accessPoints.serverList,"accessPoints.serverList"),eD(e.accessPoints.domain,"accessPoints.domain");const t=(e,t)=>{QN(e,t,0,65535,!0)};let n=443;if(e.accessPoints.port&&(t(e.accessPoints.port,"accessPoints.port"),n=e.accessPoints.port),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new hk(JN.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");rL("CLOSE_AFB_FOR_LOCAL_AP")&&(iL("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),iL("JOIN_WITH_FALLBACK_MEDIA_PROXY",!1));const i=/^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,r=e.accessPoints.domain,o=e.accessPoints.serverList.map((e=>i.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(r):e)),s=o.map((e=>"".concat(e,":").concat(n)));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,iL("WEBCS_DOMAIN",s),iL("WEBCS_DOMAIN_BACKUP_LIST",s),iL("GATEWAY_DOMAINS",[r]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(tD(e.report.hostname,"report.hostname"),iL("EVENT_REPORT_DOMAIN",e.report.hostname[0]),iL("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])):(iL("EVENT_REPORT_DOMAIN",o[0]),iL("EVENT_REPORT_BACKUP_DOMAIN",o[1]||o[0]));let a=6443;e.report&&e.report.port&&(t(e.report.port,"report.port"),a=e.report.port),iL("STATS_COLLECTOR_PORT",a),e.report?iL("ENABLE_EVENT_REPORT",!0):iL("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(tD(e.log.hostname,"log.hostname"),c=e.log.hostname[0]):c=o[0];let d=6444;e.log&&e.log.port&&(t(e.log.port,"log.port"),d=e.log.port),iL("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let l=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(tD(e.cds.hostname,"cds.hostname"),l=e.cds.hostname):l=o;let u=443;e.cds&&e.cds.port&&(t(e.cds.port,"cds.port"),u=e.cds.port),iL("CDS_AP",l.map((e=>"".concat(e,":").concat(u)))),e.cds?iL("ENABLE_CONFIG_DISTRIBUTE",!0):iL("ENABLE_CONFIG_DISTRIBUTE",!1),FL.info("set local access point v2 success")}setLocalAccessPoints(e,t){if(tD(e,"serverList"),eD(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new hk(JN.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");const n=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;e=e.map((e=>n.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(t):e)),this._useLocalAccessPoint=!0,this._setLocalAPVersion=1,iL("WEBCS_DOMAIN",e),iL("WEBCS_DOMAIN_BACKUP_LIST",e),iL("GATEWAY_DOMAINS",[t]),iL("EVENT_REPORT_DOMAIN",e[0]),iL("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),iL("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),FL.info("[".concat(this._clientId,"] set local access point success"))}async setRemoteDefaultVideoStreamType(e){if(qN(e,"streamType",[0,1,4,5,6,7,8,9]),this._remoteDefaultVideoStreamType=e,this._joinInfo)try{await this._gateway.setDefaultRemoteVideoStreamType(e),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType}catch(e){throw FL.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e}else FL.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(e))}async setRemoteVideoStreamType(e,t){qN(t,"streamType",[0,1,4,5,6,7,8,9]);try{await this._gateway.setRemoteVideoStreamType(e,t),setTimeout((()=>{const t=this._users.find((t=>t.uid===e));t&&t.videoTrack&&t.videoTrack.updateMediaStreamTrackResolution()}),2e3)}catch(e){throw FL.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e}FL.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){qN(t,"fallbackType",[0,1,2,3,4,5,6,7,8]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(e){throw FL.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e}FL.info("[".concat(this._clientId,"] set remote ").concat(e," stream fallback type to ").concat(t)),this._streamFallbackTypeCacheMap.set(e,t)}setEncryptionConfig(e,t,n,i){!function(e){qN(e,"encryptionMode",["aes-128-xts","aes-256-xts","aes-128-ecb","sm4-128-ecb","aes-128-gcm","aes-256-gcm","aes-128-gcm2","aes-256-gcm2","none"])}(e),eD(t,"secret");const r=["aes-128-gcm2","aes-256-gcm2"];if(Vi(r).call(r,e)){if(!n||!(n instanceof Uint8Array&&32===n.length))throw new hk(JN.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(n)throw new hk(JN.INVALID_PARAMS,"current encrypt mode does not need salt");if(i){if(ZN(i,"encryptDataStream"),!Vi(r).call(r,e))throw new hk(JN.INVALID_PARAMS,"current encrypt mode does not support data stream");this._encryptDataStream=!0}new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||FL.warning("The secret is not strong:\n      The secret must contain at least 1 lowercase alphabetical character,\n      The secret must contain at least 1 uppercase alphabetical character,\n      The secret must contain at least 1 numeric character,\n      The secret must contain at least one special character,\n      The secret must be eight characters or longer.\n      "),this._encryptionMode=e,this._encryptionSecret=t,n&&(this._encryptionSalt=XD(n))}async renewToken(e){if(eD(e,"token",1,2047),!this._key||!this._joinInfo)throw new hk(JN.INVALID_OPERATION,"renewToken should not be called before user join");const t=this._key;this._key=e,this._joinInfo&&(this._joinInfo.token=e);const n=await this._renewTokenMutex.lock();try{if(rL("USE_NEW_TOKEN")){FL.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));const t=await Fte(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||mP);FL.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t})}else FL.debug("[".concat(this._clientId,"] start renew token without ticket")),await this._gateway.renewToken({token:e});FL.debug("[".concat(this._clientId,"] renewToken success"))}catch(e){throw this._key=t,this._joinInfo.token=t,FL.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e}finally{n()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?FL.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval((()=>{const e=this._p2pChannel.getAudioLevels();this.safeEmit(bD.VOLUME_INDICATOR,e)}),rL("AUDIO_VOLUME_INDICATION_INTERVAL")||2e3)}getRTCStats(){const e=this._statsCollector.getRTCStats(),t=this._gateway.getInChannelInfo();return e.Duration=Math.round(t.duration/1e3),e}async startLiveStreaming(e,t){if(!t){if("h264"!==this.codec)throw new hk(JN.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new hk(JN.LIVE_STREAMING_INVALID_RAW_STREAM,"can not find stream to raw streaming")}if(this._liveRawStreamingClient&&this._liveRawStreamingClient.hasUrl(e)||this._liveTranscodeStreamingClient&&this._liveTranscodeStreamingClient.hasUrl(e))throw new hk(JN.LIVE_STREAMING_TASK_CONFLICT);const n=t?DF.TRANSCODE:DF.RAW;return this._createLiveStreamingClient(n).startLiveStreamingTask(e,n)}setLiveTranscoding(e){return this._createLiveStreamingClient(DF.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter((t=>t&&t.hasUrl(e)));if(!t.length)throw new hk(JN.INVALID_PARAMS,"can not find live streaming url to stop");await dp.all(t.map((t=>t&&t.stopLiveStreamingTask(e))))}async startChannelMediaRelay(e){Zte(e);const t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e)}async updateChannelMediaRelay(e){Zte(e);const t=this._createChannelMediaRelayClient();await t.updateChannelMediaRelay(e)}async stopChannelMediaRelay(){const e=this._createChannelMediaRelayClient();await e.stopChannelMediaRelay(),this._statsCollector.onStatsChanged&&(this._statsCollector.onStatsChanged=void 0)}sendAudioMetadata(e){this._p2pChannel instanceof sie&&this._p2pChannel.addAudioMetadata(e)}async sendStreamMessage(e){var t;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this._joinInfo)throw new hk(JN.INVALID_OPERATION,"can not send data stream, not joined");if(("string"==typeof e||e instanceof Uint8Array)&&(e={payload:e}),"string"==typeof e.payload){const t=new TextEncoder;e.payload=t.encode(e.payload)}let i=!1;this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&Vi(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)&&(i=!0,e.payload=await async function(e,t,n){var i;const r=ar(i=Array.from(n)).call(i,((e,t)=>e+t),0),o={serverTs:0,seq:pL++,length:n.length,checkSum:r},s=new Uint8Array(aP(r,2)),a=new ArrayBuffer(hL),c=new DataView(a);c.setUint32(0,o.serverTs),c.setUint16(4,o.seq),c.setUint16(6,o.length),c.setUint16(8,o.checkSum);const d=16-n.length%16;n=zD(n,new Uint8Array(d));const l=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:e,tagLength:dL,additionalData:s},t,n);return zD(new Uint8Array(a),new Uint8Array(l))}(this._encryptDataStreamIv,this._encryptDataStreamKey,e.payload));if(new Blob([e.payload]).size>1024)throw new hk(JN.INVALID_PARAMS,i?"encrypted stream message out of range.":"stream message out of range.");return this._gateway.signal.request(bF.DATA_STREAM,{payload:XD(e.payload),syncWithAudio:e.syncWithAudio,sendTs:Date.now()-lie},!n)}sendMetadata(e){if(!this._joinInfo)throw new hk(JN.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new hk(JN.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(bF.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:XD(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(jL),!this._joinInfo)throw new hk(JN.INVALID_OPERATION,"can not send custom report, not joined");await uk.sendCustomReportMessage(this._joinInfo.sid,e)}getLocalAudioStats(){return this._statsCollector.getLocalAudioTrackStats()}getRemoteAudioStats(){return this._statsCollector.getRemoteAudioTrackStats()}getLocalVideoStats(){return this._statsCollector.getLocalVideoTrackStats()}getRemoteVideoStats(){return this._statsCollector.getRemoteVideoTrackStats()}getRemoteNetworkQuality(){const e=this._statsCollector.getRemoteNetworkQualityStats();if(rL("DELETE_NEQ_AFTER_USER_LEAVE")){const t=this._users.map((e=>e.uid+""));Object.keys(e).forEach((n=>{Vi(t).call(t,n)||delete e[n]}))}return e}getNetworkQuality(){return this._statsCollector.getNetworkQuality()}async pickSVCLayer(e,t){qN(t.spatialLayer,"spatialLayer",[0,1,2,3]),qN(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(e){throw FL.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e}}async setRTMConfig(e){const t=e.apRTM,n=void 0!==t&&t,i=e.rtmFlag;if(ZN(n,"apRTM"),QN(i,"rtmFlag",0),this._rtmConfig.apRTM=n,this._rtmConfig.rtmFlag=i,FL.debug("[".concat(this._clientId,"] setRTMconfig ").concat(JSON.stringify(e)," in ").concat(this.connectionState," state")),("CONNECTED"===this.connectionState||"RECONNECTING"===this.connectionState)&&this._joinInfo)return this._joinInfo.apRTM=n,this._joinInfo.rtmFlag=i,this._gateway.setRTM2Flag(i)}_reset(){if(FL.debug("[".concat(this._clientId,"] reset client")),function(e){const t=qx.indexOf(e);-1!==t&&qx.splice(t,1)}(this._clientId),this.store.hasStartJoinChannel=!1,this.store.isABTestSuccess=!1,this.store.autoSubscribe=!1,this._pendingRtpCapabilityChange=void 0,this._axiosCancelSource.cancel(),this._axiosCancelSource=QO.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo&&xie(this._joinInfo),this._rteDetailInterval&&(window.clearInterval(this._rteDetailInterval),this._rteDetailInterval=void 0,this._sessionId&&uk.reportRteDetail(this._sessionId)),this._fallbackServerInfo=void 0,this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId&&uk.removeSid(this._sessionId),this._sessionId=null,this.store.sessionId=null,this.store.resetFirstVideoFrameDecoded(),this._statsCollector.reset(),this._key=void 0,this._appId=void 0,this._uid=void 0,this.store.uid=void 0,this._channelName=void 0,this._encryptionMode="none",this._encryptionSecret=null,this._encryptionSalt=null,this._encryptDataStreamKey=null,this._encryptDataStreamIv=null,this._pendingPublishedUsers=[],this._users.forEach((e=>{e._audioTrack&&e._audioTrack._destroy(),e._videoTrack&&e._videoTrack._destroy(),e._dataChannels&&(e._dataChannels.forEach((e=>e._close())),e._dataChannels.length=0)})),this._users=[],this._audioVolumeIndicationInterval&&(window.clearInterval(this._audioVolumeIndicationInterval),this._audioVolumeIndicationInterval=void 0),"fallback"===this._cloudProxyServerMode&&(this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled"),this._p2pChannel.reset(),this._publishMutex=new _P("client-publish",this._clientId),this._subscribeMutex=new _P("client-subscribe",this._clientId),this._networkQualityInterval&&(window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=void 0),this._liveRawStreamingClient&&(this._liveRawStreamingClient.terminate(),this._liveRawStreamingClient.removeAllListeners(),this._liveRawStreamingClient=void 0),this._liveTranscodeStreamingClient&&(this._liveTranscodeStreamingClient.terminate(),this._liveTranscodeStreamingClient.removeAllListeners(),this._liveTranscodeStreamingClient=void 0),this._channelMediaRelayClient&&(this._channelMediaRelayClient.dispose(),this._channelMediaRelayClient=void 0),this._inspect)try{this._inspect.close(),this._inspect=void 0}catch(e){}if(this._moderation)try{this.setImageModeration(!1)}catch(e){}}_startSession(e,t){var n;const i=e||tP();e?FL.debug("[".concat(this._clientId,"] new Session ").concat(i)):FL.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(i));const r=e?"":this._sessionId||"";this._sessionId=i,this.store.sessionId=i,uk.addSid(i);const o={lts:(new Date).getTime(),mode:this.mode,buildFormat:2,stringUid:(null==t?void 0:t.stringUid)||(null===(n=this._joinInfo)||void 0===n?void 0:n.stringUid),channelProfile:"live"===this.mode?1:0,channelMode:0,isABTestSuccess:Number(this._configDistribute.isSuccess),lsid:r,clientRole:"audience"===this.role?2:1,rteUrl:this.store.rteUrl,rteSid:this.store.rteSid};uk.sessionInit(this._sessionId,_oe({cname:t.channel,appid:t.appId},o)),this._joinInfo&&(this._joinInfo.sid=i),this._gateway.joinInfo&&(this._gateway.joinInfo.sid=i)}async _publishHighStream(e){if(!this._joinInfo||void 0===this._uid)throw new hk(JN.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new hk(JN.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&rL("FORCE_TURN")&&!rL("TURN_ENABLE_TCP")&&!rL("TURN_ENABLE_UDP"))throw new hk(JN.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");FL.debug("[".concat(this._clientId,"] publish high stream"));try{const n=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter);if(this.store.useP2P){const e=(await n.next()).value;if(e){try{await this._gateway.sendExtensionMessage(gB.PUBLISH,e,!0)}catch(e){throw n.throw(e),e}await n.next()}this._p2pChannel.reportPublishEvent(!0,null)}else{const i=(await n.next()).value;if(i){var t;let e;try{e=await this._gateway.publish(this._uid,i,!0)}catch(e){if(e.code!==JN.DISCONNECT_P2P)throw n.throw(e),e}await n.next((null===(t=e)||void 0===t?void 0:t.ortc)||[])}this._p2pChannel.reportPublishEvent(!0,null);for(const t of e)t instanceof BV&&t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig).catch((e=>{FL.debug("[".concat(this._clientId,"] stop setVideoProfile, because websocket is closed"))})),!t.muted&&t.enabled||await this._p2pChannel.muteLocalTrack(t)}}catch(t){if(this._p2pChannel.reportPublishEvent(!1,null==t?void 0:t.code,e),(null==t?void 0:t.code)===JN.WS_ABORT)return;throw t}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new hk(JN.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new hk(JN.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));FL.debug("[".concat(this._clientId,"] publish low stream"));const e=this._configDistribute.getLowStreamConfigDistribute();e&&e.bitrate&&(this._lowStreamParameter||(this._lowStreamParameter={width:160,height:120,framerate:15,bitrate:50}),this._lowStreamParameter&&this._lowStreamParameter.bitrate&&e.bitrate<this._lowStreamParameter.bitrate&&(this._lowStreamParameter.bitrate=e.bitrate));try{const e=await this._p2pChannel.publishLowStream(this._lowStreamParameter),n=(await e.next()).value;if(n){var t;let i;try{i=await this._gateway.publish(this._uid,n,!0)}catch(t){if(t.code!==JN.DISCONNECT_P2P)throw e.throw(t),t}e.next((null===(t=i)||void 0===t?void 0:t.ortc)||[]),this._p2pChannel.reportPublishEvent(!0,null,void 0,!0)}}catch(e){if(this._p2pChannel.reportPublishEvent(!1,null==e?void 0:e.code,void 0,!0),(null==e?void 0:e.code)===JN.WS_ABORT)return;throw e}}_createLiveStreamingClient(e){const t=()=>{if(!this._joinInfo||!this._appId){return new hk(JN.INVALID_OPERATION,"can not create live streaming client, please join channel first").throw()}const e=(t={joinInfo:this._joinInfo,appId:this._appId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig},Kee("LiveStreaming").create(t));var t;return e.onLiveStreamError=(e,t)=>{uk.reportApiInvoke(this._sessionId,{name:ED.ON_LIVE_STREAM_ERROR,options:[e,t],tag:mD.TRACER}).onSuccess(),this.safeEmit(bD.LIVE_STREAMING_ERROR,e,t)},e.onLiveStreamWarning=(e,t)=>{uk.reportApiInvoke(this._sessionId,{name:ED.ON_LIVE_STREAM_WARNING,options:[e,t],tag:mD.TRACER}).onSuccess(),this.safeEmit(bD.LIVE_STREAMING_WARNING,e,t)},e.on(VF.REQUEST_WORKER_MANAGER_LIST,((e,t,n)=>{if(!this._joinInfo)return n(new hk(JN.INVALID_OPERATION,"can not find join info to get worker manager"));(async function(e,t,n,i){const r=rL("UAP_AP").slice(0,rL("AJAX_REQUEST_CONCURRENT")).map((e=>t.proxyServer?"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1?action=uap"):"https://".concat(e,"/api/v1?action=uap")));return await _te(r,e,t,n,i)})(e,this._joinInfo,this._axiosCancelSource.token,mP).then(t).catch(n)})),e};return e===DF.RAW?(this._liveRawStreamingClient=this._liveRawStreamingClient||t(),this._liveRawStreamingClient):(this._liveTranscodeStreamingClient=this._liveTranscodeStreamingClient||t(),this._liveTranscodeStreamingClient)}_createChannelMediaRelayClient(){if(!this._joinInfo){return new hk(JN.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw()}if(!this._channelMediaRelayClient){const t=this.getLocalVideoStats(),n=t.sendResolutionWidth,i=t.sendResolutionHeight,r=(e={joinInfo:this._joinInfo,clientId:this._clientId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig,resolution:{width:n,height:i}},Kee("ChannelMediaRelay").create(e));r.on("state",(e=>{e===GF.RELAY_STATE_FAILURE&&r&&r.dispose(),this.safeEmit(bD.CHANNEL_MEDIA_RELAY_STATE,e)})),r.on("event",(e=>{this.safeEmit(bD.CHANNEL_MEDIA_RELAY_EVENT,e)})),this._channelMediaRelayClient=r,this._statsCollector.onStatsChanged=(e,t)=>{var n;"resolution"===e&&(null===(n=this._channelMediaRelayClient)||void 0===n||n.setVideoProfile(t))}}var e;return this._channelMediaRelayClient}_handleFullDatachannel(e){const t=[],n=[];this._users.forEach((i=>{const r=i._dataChannels;r.forEach((n=>{e.some((e=>e.uid===i._uintid&&e.stream_id===n.id&&e.metadata===n.metadata))||t.push({uid:i._uintid,stream_id:n.id,ordered:n.ordered,max_retrans_times:n.maxRetransmits,metadata:n.metadata})})),e.filter((e=>e.uid===i._uintid)).forEach((e=>{if(!r.some((t=>i._uintid===e.uid&&t.id===e.stream_id&&t.metadata===e.metadata))){const r=t.findIndex((t=>i._uintid===t.uid&&t.stream_id===e.stream_id));-1!==r&&(n.push(e),t.splice(r,1))}}))})),this._handleDataChannelDeleted(t),this._handleDataChannelUpdated(n),this._handleDataChannelAdded(e,!0),FL.debug("[".concat(this._clientId,"] emit full infos, data_channel ids: ").concat(e.map((e=>e.stream_id)))),this.safeEmit(bD.PUBLISHED_USER_LIST,this._pendingPublishedUsers),this._pendingPublishedUsers=[]}_handleDataChannelAdded(e,t){const n=[];Array.isArray(e)&&e.length>0&&(FL.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map((e=>e.stream_id))," added")),e.forEach((e=>{const i=e.uid,r=e.stream_id,o=e.ordered,s=e.max_retrans_times,a=e.metadata,c=this._users.find((e=>e._uintid===i));if(!c)return void FL.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"));FL.debug("[".concat(this._clientId,"] data_channel added with uid ").concat(i)),Vi(n).call(n,c)||n.push(c),c._uintid||(c._uintid=i);const d=-1!==c._dataChannels.findIndex((t=>t.id===e.stream_id));if(d){const t=c._dataChannels.find((t=>t.id===e.stream_id));null==t||t._updateDataChannelConfig(_oe(_oe({},null==t?void 0:t.getConfig()),{},{metadata:e.metadata}))}else{const e={id:r,ordered:!!o,maxRetransmits:s,metadata:a},n=function(e){return Hee(e,!0)}(e);c._dataChannels.push(n),FL.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published datachannel")),t||this.safeEmit(bD.USER_PUBLISHED,c,"datachannel",e)}this._p2pChannel.hasPendingRemoteDataChannel(c,e.stream_id)&&(FL.debug("[".concat(this._clientId,"] resubscribe datachannel id: ").concat(e.stream_id," for user ").concat(c.uid," after reconnect.")),this._subscribeDataChannel(c,e.stream_id).catch((e=>{FL.error("[".concat(this._clientId,"] resubscribe datachannel error"),e.toString())})))})))}_handleDataChannelUpdated(e){Array.isArray(e)&&e.length>0&&(FL.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map((e=>e.stream_id))," updated")),e.forEach((e=>{var t;const n=e.uid,i=e.stream_id,r=e.metadata,o=this._users.find((e=>e._uintid===n));if(!o)return void FL.error("[".concat(this._clientId,"] can not find target user!(on_update_data_channel)"));const s=o._dataChannels.find((e=>e.id===i));FL.debug("[".concat(this._clientId,"] data_channel: ").concat(i," updated with uid ").concat(n,", last metadata: ").concat(null==s||null===(t=s._config)||void 0===t?void 0:t.metadata,", new metadata: ").concat(r)),this.safeEmit(bD.USER_UNPUBLISHED,o,"datachannel",null==s?void 0:s._config),this.safeEmit(bD.USER_PUBLISHED,o,"datachannel",{id:i,ordered:!!e.ordered,maxRetransmits:e.max_retrans_times,metadata:r})})))}_handleDataChannelDeleted(e){Array.isArray(e)&&e.length>0&&(FL.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map((e=>e.stream_id))," deleted")),e.forEach((e=>{const t=e.uid;e.stream_id;const n=this._users.find((e=>e._uintid===t));if(!n)return void FL.error("[".concat(this._clientId,"] can not find target user!(on_delete_data_channel)"));const i=n._dataChannels.find((t=>t.id===e.stream_id));i&&(FL.debug("[".concat(this._clientId,"] data_stream delete with uid ").concat(t)),n._dataChannels=n._dataChannels.filter((e=>e.id!==i.id)),this._p2pChannel.unsubscribeDataChannel(n,[i]).then((e=>{if(e)return this._gateway.unsubscribeDataChannel(e,n.uid)})),FL.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished datachannel , id:").concat(i.id)),this.safeEmit(bD.USER_UNPUBLISHED,n,"datachannel",i._config))})))}_handleUpdateDataChannel(e){const t=e.added,n=e.deleted;this._handleDataChannelDeleted(null!=n?n:[]),this._handleDataChannelAdded(null!=t?t:[])}_getEncodingName(e){var t,n;if(!this._joinResponse)return;const i=null===(t=this._joinResponse.ortc.rtpCapabilities.sendrecv)||void 0===t?void 0:t.videoCodecs;if(!i)return;for(const t of i){var r;if(t.payloadType===e)return null==t||null===(r=t.rtpMap)||void 0===r?void 0:r.encodingName}const o=null===(n=this._joinResponse.ortc.rtpCapabilities.recv)||void 0===n?void 0:n.videoCodecs;if(o)for(const t of o){var s;if(t.payloadType===e)return null==t||null===(s=t.rtpMap)||void 0===s?void 0:s.encodingName}return 0===e?"unknown":void 0}_handleRemoveDataChannels(e){const t=this._users.find((t=>t.uid===e.uid));if(t){if(void 0!==t._dataChannels&&t._dataChannels.length>0){FL.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(e.uid));const n=()=>{FL.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished datachannel")),t._dataChannels.forEach((e=>{this.safeEmit(bD.USER_UNPUBLISHED,t,"datachannel",e._config)}))};this._p2pChannel.unsubscribeDataChannel(t,t._dataChannels).then((e=>{if(e)return this._gateway.unsubscribeDataChannel(e,t.uid)})),n()}}else FL.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"))}_handleGatewayEvents(){this._gateway.on(HF.UPDATE_GATEWAY_CONFIG,(()=>{!function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void FL.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),n=Date.now();Object.keys(t).forEach((e=>{const i=t[e],r=i.value,o=i.type,s=i.expires;s&&s<=n||o||$x()||!Object.prototype.hasOwnProperty.call(QP,e)||(sL[e]=r,nL[e]=r,FL.debug("Update gateway parameters from config distribute",e,r))}))}catch(e){FL.error("Error update config from local cache",e.message)}}()})),this._gateway.on(HF.DISCONNECT_P2P,(async()=>{await this._p2pChannel.disconnectForReconnect()})),this._gateway.on(HF.CONNECTION_STATE_CHANGE,((e,t,n)=>{var i;if(n===SD.FALLBACK)return;const r=()=>{this.safeEmit(bD.CONNECTION_STATE_CHANGE,e,t,n)};if(uk.reportApiInvoke(this._sessionId||(null===(i=this._gateway.joinInfo)||void 0===i?void 0:i.sid)||null,{name:ED.CONNECTION_STATE_CHANGE,options:[e,t,n],tag:mD.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:n})),FL.info("[".concat(this._clientId,"] signal connection state change: ").concat(t," -> ").concat(e)),"DISCONNECTED"===e)return this._reset(),void r();if("RECONNECTING"===e)this._users.forEach((e=>{e._trust_in_room_=!1,e._trust_audio_enabled_state_=!1,e._trust_video_enabled_state_=!1,e._trust_audio_mute_state_=!1,e._trust_video_mute_state_=!1,e._trust_audio_stream_added_state_=!1,e._trust_video_stream_added_state_=!1,e._is_pre_created||(e._audio_pre_subscribed||(e._audioSSRC=void 0,e._audioOrtc=void 0),e._video_pre_subscribed||(e._videoSSRC=void 0,e._videoOrtc=void 0,e._rtxSsrcId=void 0),e._cname=void 0)})),this._userOfflineTimeout&&window.clearTimeout(this._userOfflineTimeout),this._streamRemovedTimeout&&window.clearTimeout(this._streamRemovedTimeout),this._userOfflineTimeout=void 0,this._streamRemovedTimeout=void 0;else if("CONNECTED"===e){var o;this._streamFallbackTypeCacheMap.forEach(((e,t)=>{this._gateway.setStreamFallbackOption(t,e).catch((e=>{FL.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e)}))})),this._remoteStreamTypeCacheMap.forEach(((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch((e=>{FL.warning("[".concat(this._clientId,"] auto set remote stream type failed"),e)}))})),rL("VOS_CONFIGURE")&&Array.isArray(rL("VOS_CONFIGURE"))&&rL("VOS_CONFIGURE").length>0&&(this._gateway.setConfigure(rL("VOS_CONFIGURE")).catch((e=>{FL.debug("[".concat(this._clientId,"] auto set vos config failed"),e)})),FL.debug("[".concat(this._clientId,"] ws connected auto set vos config"))),void 0!==this._remoteDefaultVideoStreamType&&void 0===(null===(o=this._joinInfo)||void 0===o?void 0:o.defaultVideoStream)&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then((()=>{FL.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))})).catch((e=>{FL.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(e))})),this._dualStreamMode&&this._gateway.setDualStreamMode(this._dualStreamMode).catch((e=>{FL.warning("[".concat(this._clientId,"] auto set dual stream mode failed"),e)})),this.store.useP2P||(this._p2pChannel.republish(),this._userOfflineTimeout=window.setTimeout((()=>{if("CONNECTED"!==this.connectionState)return;this._userOfflineTimeout=void 0;this._users.filter((e=>!e._trust_in_room_)).forEach((e=>{FL.debug("[".concat(this._clientId,"] user offline timeout, emit user offline ").concat(e.uid)),this._handleUserOffline({uid:e.uid})}))}),3e3),this._streamRemovedTimeout=window.setTimeout((()=>{"CONNECTED"===this.connectionState&&(this._streamRemovedTimeout=void 0,this._users.forEach((e=>{e._trust_audio_mute_state_||(FL.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,nB.AUDIO,!1)),e._trust_video_mute_state_||(FL.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,nB.VIDEO,!1)),e._trust_audio_enabled_state_||(FL.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(FL.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(FL.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(FL.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(FL.debug("[".concat(this._clientId,"] auto dispatch stream remove ").concat(e.uid)),this._handleRemoveStream({uid:e.uid,uint_id:e._uintid}))})))}),1e3))}r()})),this._gateway.on(HF.REQUEST_NEW_GATEWAY_LIST,(async(e,t)=>{if(!this._joinInfo)return t(new hk(JN.UNEXPECTED_ERROR,"can not recover, no join info"));try{let t;if(this._fallbackServerInfo)t=this._fallbackServerInfo,this._fallbackServerInfo=void 0,this._joinInfo.preload=!1,uk.reportApiInvoke(this._sessionId,{name:ED.VOS_FALLBACK_CN,options:{cur:t.gatewayInfo.gatewayAddrs,prev:this._joinInfo.gatewayAddrs,is_done:!0},tag:mD.TRACER}).onSuccess(),FL.info("[".concat(this._clientId,"] use fallback cn server info"));else{const e=await kie(_oe(_oe({},this._joinInfo),{},{uid:this._joinInfo.uid,stringUid:void 0}));e?(t=e.ap,Fie(e),this._joinInfo.preload=!0):(t=await Nte(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||mP,this.store),this._joinInfo.preload=!1)}this._joinInfo&&(this._joinInfo.apResponse=t.gatewayInfo.res,this._joinInfo.gatewayAddrs=t.gatewayInfo.gatewayAddrs,this._joinInfo.uni_lbs_ip=t.gatewayInfo.uni_lbs_ip,delete this._joinInfo.signalResponse);const n=[];t.gatewayInfo.gatewayAddrs.forEach((e=>{const t=Hb(e.address.split(":"),2),i=t[0],r=t[1];this._joinInfo&&this._joinInfo.proxyServer?n.push({proxy:this._joinInfo.proxyServer,host:i,port:r}):n.push({host:i,port:r})})),e(n)}catch(e){t(e)}})),this._gateway.on(HF.NETWORK_QUALITY,(e=>{"normal"===this._networkQualitySensitivity&&this.safeEmit(bD.NETWORK_QUALITY,e)})),this._gateway.on(HF.STREAM_TYPE_CHANGE,((e,t)=>{this.safeEmit(bD.STREAM_TYPE_CHANGED,e,t);uk.reportApiInvoke(this._sessionId,{name:ED.STREAM_TYPE_CHANGE,options:[e,t],tag:mD.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}))})),this._gateway.isPreSub=()=>"isPreSub"in this._p2pChannel&&this._p2pChannel.isPreSub(),this._gateway.isPreallocation=()=>"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation(),this._gateway.on(HF.IS_P2P_DISCONNECTED,(e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0)})),this._gateway.on(HF.REQUEST_P2P_CONNECTION_PARAMS,(async(e,t,n)=>{try{let n=await this._p2pChannel.getEstablishParams();n&&"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()||(n=await this._p2pChannel.startP2PConnection(e)),t(n)}catch(e){n(e)}})),this._gateway.on(HF.JOIN_RESPONSE,((e,t)=>{if(this.store.useP2P)return;let n;this._joinResponse=e,e.attributes?n=e.attributes.userAttributes.preSubSsrcs:FL.debug("no attributes in joinResponse");const i=gee(e.ortc,t,n);this._p2pChannel.connect(i)})),this._gateway.on(HF.PRE_CONNECT_PC,(async(e,t,n)=>{const i=e.candidates,r=e.fingerprint,o=e.turnServer;if(this._joinInfo&&i.length>0&&!this._p2pChannel.isPlanB){var s,a;const d=this._joinInfo.apResponse,l=d.cert,u=d.cid,h="".concat(u,"_").concat(l),p=e.iceUfrag||h,_=e.icePwd||h;if(!Xee(p,_))return void FL.debug("[".concat(this._clientId,"] ufrag/pwd length is not valid, length: ").concat(p.length," / ").concat(_.length));let E;await this._p2pChannel.getEstablishParams()&&"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()?(this._p2pChannel.updateConnectionConfiguration({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer,isPreallocation:!0}),FL.debug("pre pc before connect ws/dc, use sdp endpoint")):await this._p2pChannel.startP2PConnection({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer,isPreallocation:!0});const m=null===(s=this._joinInfo.signalResponse)||void 0===s||null===(s=s.attributes)||void 0===s||null===(s=s.userAttributes)||void 0===s?void 0:s.preSubSsrcs;Array.isArray(m)&&m.length>0&&(E=See(m));const f=null===(a=this._joinInfo.signalResponse)||void 0===a?void 0:a.rtpCapabilities;try{var c;t(await this._p2pChannel.connect(_oe({iceParameters:{iceUfrag:p,icePwd:_},dtlsParameters:{fingerprints:[{hashFunction:"sha-256",fingerprint:null!==(c=rL("FINGERPRINT"))&&void 0!==c?c:r}]},candidates:i,rtpCapabilities:f||{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},setup:"active",cname:"o/i14u9pJrxRKAsu",preallocation:!0},E?{preSSRCs:E}:{})))}catch(e){e.code&&e.code===JN.EXCHANGE_SDP_FAILED&&(FL.debug("try to pre connect pc, but exchange sdp failed, reset p2p connection",e),await this._p2pChannel.startP2PConnection({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer},!0)),n(e)}}})),this._gateway.on(HF.VOS_FALLBACK,(e=>{"fallback_hls"===e&&this.safeEmit(bD.FALLBACK_TO_HLS,CD.VOSERROR)})),this._gateway.on(HF.RESET_SIGNAL,(()=>{this._p2pChannel instanceof sie&&this._p2pChannel.fallbackConnection(),this._handleGatewaySignalEvents()})),this._gateway.on(HF.DATACHANNEL_FAILBACK,(()=>{uk.reportApiInvoke(this._sessionId,{name:ED.DATACHANNEL_FAILBACK,options:{},tag:mD.TRACER}).onSuccess(),this._joinGateway()}))}_handleGatewaySignalEvents(){this._gateway.signal.on(IF.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(IF.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(IF.ON_ADD_AUDIO_STREAM,(e=>this._handleAddAudioOrVideoStream("audio",e.uid,e.ssrcId,e.cname,e.pt,e.uint_id,e.ortc))),this._gateway.signal.on(IF.ON_ADD_VIDEO_STREAM,(e=>this._handleAddAudioOrVideoStream("video",e.uid,e.ssrcId,e.cname,e.pt,e.uint_id,e.ortc,e.rtxSsrcId))),this._gateway.signal.on(IF.ON_REMOTE_DATASTREAM_UPDATE,(e=>{this._handleUpdateDataChannel(e)})),this._gateway.signal.on(IF.ON_REMOTE_FULL_DATASTREAM_INFO,(e=>{var t;this._handleFullDatachannel(null!==(t=e.datastreams)&&void 0!==t?t:[])})),this._gateway.signal.on(IF.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(IF.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(IF.MUTE_AUDIO,(e=>this._handleMuteStream(e.uid,nB.AUDIO,!0))),this._gateway.signal.on(IF.UNMUTE_AUDIO,(e=>this._handleMuteStream(e.uid,nB.AUDIO,!1))),this._gateway.signal.on(IF.MUTE_VIDEO,(e=>this._handleMuteStream(e.uid,nB.VIDEO,!0))),this._gateway.signal.on(IF.UNMUTE_VIDEO,(e=>this._handleMuteStream(e.uid,nB.VIDEO,!1))),this._gateway.signal.on(IF.RECEIVE_METADATA,(e=>{const t=YD(e.metadata);this.safeEmit(bD.RECEIVE_METADATA,e.uid,t)})),this._gateway.signal.on(IF.ON_DATA_STREAM,(async e=>{var t;if(!e)return;let n=YD(e.payload);if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&Vi(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)){if(e.payload.length<hL)throw new hk(JN.UNEXPECTED_RESPONSE,"payload length ".concat(e.payload.length," is less than header length ").concat(hL));const t=await async function(e,t,n){const i=n.subarray(0,hL),r=i.slice(8,hL),o=(r[0]<<8)+r[1],s=(i[6]<<8)+i[7],a=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:e,tagLength:dL,additionalData:new Uint8Array(aP(o,2))},t,n.subarray(hL));return new Uint8Array(a).subarray(0,s)}(this._encryptDataStreamIv,this._encryptDataStreamKey,n);n=t}let i=0;if(e.ordered||e.syncWithAudio){const t=this._p2pChannel.getStats(),n=this.remoteUsers.find((t=>t.uid===e.uid)),r=null==t?void 0:t.audioRecv.find((e=>e.ssrc===(null==n?void 0:n._audioSSRC)));i=null==r?void 0:r.jitterBufferMs}(null==i||Number.isNaN(i))&&(i=0),mie(_oe(_oe({},e),{},{payload:n}),i,{id:this._clientId,onStreamMessage:"function"==typeof this.onStreamMessage?this.onStreamMessage.bind(this):void 0,safeEmit:this.safeEmit.bind(this)})})),this._gateway.signal.on(IF.ON_CRYPT_ERROR,(()=>{HD((()=>{FL.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(bD.CRYPT_ERROR)}),this._sessionId)})),this._gateway.signal.on(IF.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(IF.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{FL.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,SD.TOKEN_EXPIRE),this.safeEmit(bD.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()})),this._gateway.signal.on(IF.ON_STREAM_FALLBACK_UPDATE,(e=>{FL.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.safeEmit(bD.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover")})),this._gateway.signal.on(IF.ENABLE_MULTI_STREAM,(e=>{this._dualStreamMode===vD.AUTO_SIMULCAST_STREAM&&this.enableDualStream().catch((e=>{FL.debug("[".concat(this._clientId,"] set dual stream mode error"),e.toString())}))})),this._gateway.signal.on(IF.ON_PUBLISH_STREAM,(e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),FL.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))))})),this._gateway.signal.on(IF.ENABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!0)})),this._gateway.signal.on(IF.DISABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!1)})),this._gateway.signal.on(yF.REQUEST_TIMEOUT,((e,t)=>{if(this._joinInfo)switch(e){case bF.PUBLISH:{if(!t)return;const e=t.ortc;if(e){var n,i;const r=e.some((e=>e.stream_type===KF.Audio)),o=e.some((e=>e.stream_type!==KF.Audio)),s=e.some((e=>{let t=e.stream_type;return t===KF.Screen||t===KF.ScreenLow}));"offer"===t.state&&uk.publish(this._joinInfo.sid,{eventElapse:Hte.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:JN.TIMEOUT,audio:r,video:o,p2pid:t.p2p_id,publishRequestid:this.store.pubId,screenshare:s,audioName:r?null===(n=e.find((e=>e.stream_type===KF.Audio)))||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId.toString():void 0,videoName:o?null===(i=e.find((e=>e.stream_type!==KF.Audio)))||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId.toString():void 0})}break}case bF.SUBSCRIBE:t&&uk.subscribe(this._joinInfo.sid,{succ:!1,ec:JN.TIMEOUT,audio:t.stream_type===nB.AUDIO,video:t.stream_type===nB.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:Hte.measureFromSubscribeStart(this.store.clientId,t.ssrcId),preSsrc:this._p2pChannel.isPreSubScribe(t.ssrcId)})}})),this._gateway.signal.on(IF.ON_P2P_OK,(e=>{this.uid,this._uid})),this._gateway.signal.on(IF.ON_PUBLISHED_USER_LIST,(e=>{if(null==e||!e.users)return;let t=e.users;rL("BLOCK_LOCAL_CLIENT")&&(t=t.filter((e=>!Qx(e.string_id||e.stream_id,this.channelName)))),this._handleUserList(t)})),this._gateway.signal.on(IF.ON_USER_LIST,(e=>{if(!e||!Array.isArray(e.users)||0===e.users.length)return;let t=e.users;t=rL("BLOCK_LOCAL_CLIENT")?t.filter((e=>!Qx(e.string_id||e.stream_id,this.channelName))):t,this._handleUserList(t)})),this._gateway.signal.on(IF.ON_RTP_CAPABILITY_CHANGE,(e=>{const t=e.video_codec;if(this._p2pChannel instanceof sie){if("audience"===this.role&&rL("UPDATE_RTP_CAP_IN_HOST"))return this._pendingRtpCapabilityChange=e,void FL.debug("[".concat(this._clientId,"] no need to change rtp capability because of audience, params: ").concat(JSON.stringify(e)));this._p2pChannel.updateRemoteRTPCapabilities(t.map((e=>e.toLowerCase())).filter((e=>{var t;return Vi(t=Object.keys(cL)).call(t,e)})))}})),this._gateway.signal.on(yF.VOS_FALLBACK_PROMISE,(async(e,t,n)=>{if("FALLBACKCN"===e&&rL("ENABLE_QUALITY_FALLBACK")){if(!this._joinInfo)return n(new hk(JN.UNEXPECTED_ERROR,"can not recover, no join info"));FL.info("[".concat(this._clientId,"] try fallback to cn, start request new server info"));const r=this._joinInfo.apRequestDetail;try{this._joinInfo.apRequestDetail=e;const i=await Nte(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||mP,this.store);if(rL("QUALITY_FALLBACK_REHEARSAL"))return uk.reportApiInvoke(this._sessionId,{name:ED.VOS_FALLBACK_CN,options:{cur:i.gatewayInfo.gatewayAddrs,prev:this._joinInfo.gatewayAddrs,is_done:!1},tag:mD.TRACER}).onSuccess(),this._joinInfo.apRequestDetail=r,void n();this._fallbackServerInfo=i,t()}catch(e){var i;const t=null==e||null===(i=e.data)||void 0===i?void 0:i.desc;rL("QUALITY_FALLBACK_REHEARSAL")?(uk.reportApiInvoke(this._sessionId,{name:ED.VOS_FALLBACK_CN,options:{cur:"failed, errorReason: "+t||"unknown",prev:this._joinInfo.gatewayAddrs,is_done:!1},tag:mD.TRACER}).onSuccess(),this._joinInfo.apRequestDetail=r):Array.isArray(t)&&Vi(t).call(t,"request downgrade fallback")&&this.safeEmit(bD.FALLBACK_TO_HLS,CD.AP_ERROR),n(e)}}else n()}))}_handleUserList(e){var t=this;if(0===e.length)return;const n=[],i=[],r=[],o=[],s=[],a=[],c=this.getListeners(bD.USER_LIST).length>0,d=this.getListeners(bD.PUBLISHED_USER_LIST).length>0;for(const t of e){let e=this._users.find((e=>e._uintid===t.stream_id));const c=!!e;e?e._trust_in_room_=!0:(e=new qte(t.string_id||t.stream_id,t.stream_id),this._users.push(e),this.store.firstVideoFrameDecoded(e.uid,{userJoinNotify:Date.now()}));const d=XF.Audio&t.stream_type,l=(XF.Video|XF.LowVideo)&t.stream_type,u=0!=(65280&t.stream_type),h=d&&e.hasAudio,p=l&&e.hasVideo;l&&(e._trust_video_stream_added_state_=!0,e._video_added_=!0,e._videoSSRC=t.video_ssrc,e._rtxSsrcId=t.video_rtx),d&&(e._trust_audio_stream_added_state_=!0,e._audio_added_=!0,e._audioSSRC=t.audio_ssrc),(d&&!h||l&&!p||u)&&(i.push(e),d&&!h&&r.push(e),l&&!p&&o.push(e)),c||s.push(e),l&&this._p2pChannel.hasPendingRemoteMedia(e,"video")&&a.push({user:e,mediaType:"video"}),d&&this._p2pChannel.hasPendingRemoteMedia(e,"audio")&&a.push({user:e,mediaType:"audio"}),n.push(e)}a.length>0&&(FL.debug("[".concat(this._clientId,"] RE massSubscribe after reconnect ").concat(a.map((e=>"user: ".concat(e.user.uid,", mediaType: ").concat(e.mediaType))).join("; ")," ")),this.massSubscribe(a).catch((e=>{FL.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString())})));const l=function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];FL.info("[".concat(t._clientId,"] client not emit user-list event case there is no user-list listener...")),e||s.forEach((e=>{FL.debug("[".concat(t._clientId,"] user online"),e._uintid),t.safeEmit(bD.USER_JOINED,e)})),i.length>0&&(r.forEach((e=>{FL.info("[".concat(t._clientId,"] remote user ").concat(e.uid," published audio")),t.safeEmit(bD.USER_PUBLISHED,e,"audio")})),o.forEach((e=>{FL.info("[".concat(t._clientId,"] remote user ").concat(e.uid," published video")),t.safeEmit(bD.USER_PUBLISHED,e,"video")})))};if(rL("ENABLE_USER_LIST"))c?(this.safeEmit(bD.USER_LIST,n),l(!0)):l();else if(d){if(i.length>0){const e=ar(i).call(i,((e,t)=>"".concat(e&&e+", ").concat(t.uid)),"");rL("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=i:(FL.info("[".concat(this._clientId,"] client emit published-user-list, users: ").concat(e)),this.safeEmit(bD.PUBLISHED_USER_LIST,i))}}else l()}_handleP2PEvents(){this._gateway.signal.on(IF.ON_USER_OFFLINE,(()=>{this._p2pChannel.disconnectForReconnect()})),this._gateway.signal.on(gB.PUBLISH,((e,t,n)=>{const i=e.uid;e.forEach((e=>{const r=e.kind,o=e.ssrcs,s=e.mid,a=e.isMuted;this._handleP2PAddAudioOrVideoStream(r,i,o[0].ssrcId,s);const c=this._users.find((e=>e.uid===i));return c&&this.store.useP2P?this._p2pChannel.mockSubscribe(c,r,o[0].ssrcId,s).then((()=>{t()})).catch(n):t(),this._handleMuteStream(i,r,!!a)}))})),this._gateway.signal.on(gB.CALL,(async(e,t,n)=>{if(this.store.useP2P)try{var i;t(await this._p2pChannel.startP2P({turnServer:null===(i=this._joinInfo)||void 0===i?void 0:i.turnServer},e))}catch(e){n(e)}})),this._gateway.signal.on(yF.P2P_CONNECTION,(async e=>{this.store.useP2P&&(await this._p2pChannel).p2pConnect(e)})),this._gateway.signal.on(gB.UNPUBLISH,(async(e,t,n)=>{if(this.store.useP2P){const i=e.unpubMsg,r=e.uid,o=this._users.find((e=>e.uid===r));if(!o)return FL.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(r)),void t();try{i.forEach((async e=>{const t=e.stream_type===KF.Audio?nB.AUDIO:nB.VIDEO;await this._p2pChannel.unsubscribe(o,t),this._handleMuteStream(r,t,!0)})),t()}catch(e){n(e)}}})),this._gateway.signal.on(gB.CONTROL,(async(e,t)=>{switch(e.action){case TB.MUTE_LOCAL_VIDEO:this._handleMuteStream(t,nB.VIDEO,!0);break;case TB.MUTE_LOCAL_AUDIO:this._handleMuteStream(t,nB.AUDIO,!0);break;case TB.UNMUTE_LOCAL_VIDEO:this._handleP2PAddAudioOrVideoStream("video",t),this._handleMuteStream(t,nB.VIDEO,!1);break;case TB.UNMUTE_LOCAL_AUDIO:this._handleP2PAddAudioOrVideoStream("audio",t),this._handleMuteStream(t,nB.AUDIO,!1)}})),this._gateway.signal.on(gB.RESTART_ICE,(async(e,t,n)=>{if(this.store.useP2P)try{const n=e.direction,i=e.iceParameter;if(n!==AF.SEND_ONLY||i){t(await this._p2pChannel.restartICE(n,i))}else this._p2pChannel.handleDisconnect(n),t()}catch(e){n(e)}})),this._gateway.signal.on(gB.CANDIDATE,(e=>{if(this.store.useP2P){const t=e.candidate,n=e.direction;this._p2pChannel.addRemoteCandidate(t,n)}})),this._p2pChannel.on(cB.RequestP2PRestartICE,(async(e,t,n)=>{try{const n=e.direction;t(await this._gateway.sendExtensionMessage(gB.RESTART_ICE,e,n===AF.SEND_ONLY))}catch(e){n(e)}})),this._p2pChannel.on(cB.LocalCandidate,(e=>{this._gateway.sendExtensionMessage(gB.CANDIDATE,JSON.stringify(e),!0)})),this._p2pChannel.on(cB.RequestP2PMuteLocal,(async(e,t,n)=>{try{await this._gateway.sendExtensionMessage(gB.CONTROL,e,!0),t()}catch(e){n(e)}})),this._p2pChannel.on(cB.RequestP2PUnmuteRemote,(async(e,t,n)=>{if(this._joinInfo)try{await this._gateway.unmuteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===JN.DISCONNECT_P2P?t():n(e)}else t()})),this._p2pChannel.on(cB.RequestP2PMuteRemote,(async(e,t,n)=>{if(this._joinInfo)try{await this._gateway.muteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===JN.DISCONNECT_P2P?t():n(e)}else t()})),this._p2pChannel.on(cB.StateChange,((e,t)=>{t===aB.Connected&&this._p2pChannel.republish()}))}_handleP2PChannelEvents(){this._p2pChannel.on(cB.PeerConnectionStateChange,(e=>{const t=this._peerConnectionState;e!==t&&(this.safeEmit(bD.PEERCONNECTION_STATE_CHANGE,e,t),this._peerConnectionState=e)})),this._p2pChannel.on(cB.RequestMuteLocal,(async(e,t,n)=>{if(this._joinInfo)try{await this._gateway.muteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===JN.DISCONNECT_P2P?t():n(e)}else t()})),this._p2pChannel.on(cB.RequestUnmuteLocal,(async(e,t,n)=>{if(this._joinInfo)try{await this._gateway.unmuteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===JN.DISCONNECT_P2P?t():n(e)}else t()})),this._p2pChannel.on(cB.RequestRePublish,((e,t,n)=>{this.publish(e,!1).then(t).catch(n)})),this._p2pChannel.on(cB.RequestRePublishDataChannel,((e,t,n)=>{dp.all(e.map((async e=>{const t=await this._p2pChannel.publishDataChannel([e]);try{t.forEach((e=>{this._uid&&this._gateway.publishDataChannel(this._uid,e,!0)}))}catch(e){if(e.code!==JN.DISCONNECT_P2P)throw e}}))).then(t).catch(n)})),this._p2pChannel.on(cB.RequestReSubscribe,(async(e,t,n)=>{try{for(const t of e){const e=t.user;t.kind===nB.VIDEO?await this.subscribe(e,"video"):await this.subscribe(e,"audio")}t()}catch(e){n(e)}})),this._p2pChannel.on(cB.RequestUpload,((e,t)=>{this._gateway.upload(e,t)})),this._p2pChannel.on(cB.RequestUploadStats,(e=>{this._gateway.uploadWRTCStats(e)})),this._p2pChannel.on(cB.MediaReconnectStart,(e=>{this.safeEmit(bD.MEDIA_RECONNECT_START,e)})),this._p2pChannel.on(cB.MediaReconnectEnd,(e=>{this.safeEmit(bD.MEDIA_RECONNECT_END,e)})),this._p2pChannel.on(cB.NeedSignalRTT,(e=>{e(this._gateway.getSignalRTT())})),this._p2pChannel.on(cB.RequestRestartICE,(async e=>{if(this.store.useP2P)return;const t=await this._p2pChannel.restartICE(e),n=await t.next();if(n.done)return;const i=n.value;let r;try{r=await this._gateway.restartICE({iceParameters:i})}catch(e){return void t.throw(e)}const o=function(e){const t=e.iceParameters;return{iceParameters:{iceUfrag:t.iceUfrag,icePwd:t.icePwd}}}(r).iceParameters;await t.next({remoteIceParameters:o})})),this._p2pChannel.on(cB.RequestReconnect,(async()=>{this._gateway.reconnect()})),this._p2pChannel.on(cB.RequestReconnectPC,(async()=>{var e;const t=await this._p2pChannel.startP2PConnection({turnServer:null===(e=this._joinInfo)||void 0===e?void 0:e.turnServer}),n=t.iceParameters,i=t.dtlsParameters,r=t.rtpCapabilities,o=await this._gateway.reconnectPC({iceParameters:n,dtlsParameters:i,rtpCapabilities:r}),s=gee(o.gatewayEstablishParams,o.gatewayAddress);await this._p2pChannel.connect(s),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()})),this._p2pChannel.on(cB.RequestUnpublishForReconnectPC,(async(e,t,n)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):n()})),this._p2pChannel.on(cB.P2PLost,(()=>{this.safeEmit(bD.P2P_LOST,this.store.uid)})),this._p2pChannel.on(cB.UpdateVideoEncoder,(e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig)})),this._p2pChannel.on(cB.ConnectionTypeChange,(e=>{this.safeEmit(bD.IS_USING_CLOUD_PROXY,e),this._gateway.setUsingProxy(e)})),this._p2pChannel.on(cB.FirstVideoBufferReady,((e,t)=>{this.safeEmit(bD.FIRST_VIDEO_BUFFER_READY,e,t)})),this._p2pChannel.on(cB.FirstVideoPreRender,((e,t)=>{this.safeEmit(bD.FIRST_VIDEO_PRE_RENDER,e,t)})),this._p2pChannel.on(cB.RequestLowStreamParameter,(e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})})),this._p2pChannel.on(cB.QueryClientConnectionState,(e=>{e(this.connectionState)})),this._p2pChannel.on(cB.AudioMetadata,(e=>{this.safeEmit(bD.AUDIO_METADATA,e)})),this._p2pChannel.on(cB.AudioPts,(e=>{this.safeEmit(bD.AUDIO_PTS,Number(e))}))}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){if(!this._joinInfo||"CONNECTED"!==this.connectionState)throw new hk(JN.INVALID_OPERATION,"[".concat(this._clientId,"] can not create content inspect, please join channel first"));if(this._inspect)throw new hk(JN.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));try{const n=(t={config:e},Kee("ContentInspect").create(t));this._inspect=n,this.handleVideoInspectEvents(n);const i=this._joinInfo,r=i.appId,o=i.cname,s=i.sid,a=i.token,c=i.uid,d=i.cid,l=i.vid;await n.init({appId:r,areaCode:"",cname:o,sid:s,token:a,uid:c,cid:d,vid:l?Number(l):0},mP)}catch(e){throw Array.isArray(e)?e[0]:e}var t}handleVideoInspectEvents(e){e.on(uB.CONNECTION_STATE_CHANGE,((t,n)=>{if(this.safeEmit(bD.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,n),n===dB.CONNECTED){if("CONNECTED"!==this.connectionState)return void this.safeEmit(bD.CONTENT_INSPECT_ERROR,new hk(JN.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage()}})),e.on(uB.INSPECT_RESULT,((e,t)=>{var n;if((null==t?void 0:t.code)===JN.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return FL.debug("Stop inspect content because that has left channel"),null==this||null===(n=this._inspect)||void 0===n||n.close(),void(this._inspect=void 0);this.safeEmit(bD.CONTENT_INSPECT_RESULT,e,t)})),e.on(uB.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}async disableContentInspect(){if(!this._inspect)throw new hk(JN.INVALID_OPERATION,"[".concat(this._clientId,"] inspectVideoContent not started"));try{this._inspect.close(),this._inspect=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}async setImageModeration(e,t){if(ZN(e,"enabled"),e){if(!t)throw new hk(JN.INVALID_PARAMS,"config is required");if(vre(t),!this._joinInfo)throw new hk(JN.INVALID_OPERATION,"can not create image moderation, please join channel first");try{if(this._moderation)this._moderation.updateConfig(t);else{const e=(n={config:t},Kee("ImageModeration").create(n));this._moderation=e,this.handleImageModerationEvents(e);const i=this._joinInfo,r=i.appId,o=i.cname,s=i.sid,a=i.token,c=i.uid,d=i.cid,l=i.vid;await e.init({appId:r,areaCode:"",cname:o,sid:s,token:a,uid:c,cid:d,vid:l?Number(l):0},mP)}}catch(e){throw Array.isArray(e)?e[0]:e}}else{var n;if(!this._moderation)throw new hk(JN.INVALID_OPERATION,"[".concat(this._clientId,"] image moderation not started"));try{this._moderation.close(),this._moderation.removeAllListeners(),this._moderation=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}}handleImageModerationEvents(e){e.on(mB.CONNECTION_STATE_CHANGE,((t,n)=>{if(this.safeEmit(bD.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,t,n),t===EB.CONNECTED){if("CONNECTED"!==this.connectionState)throw this.setImageModeration(!1),new hk(JN.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");e.inspectImage()}})),e.on(mB.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}setP2PTransport(e){if(function(e){qN(e,"transport",["default","auto","relay","sd-rtn"])}(e),"p2p"!==this.mode)throw new hk(JN.INVALID_OPERATION,"only p2p mode can set p2pTransport");this.store.p2pTransport=e,FL.info("[".concat(this._clientId,"] set client p2pTransport to ").concat(e))}getJoinChannelServiceRecords(){return FL.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){ZN(e,"enabled"),iL("ENABLE_PUBLISH_AUDIO_FILTER",e),this._joinInfo&&await this._gateway.setPublishAudioFilterEnabled(e)}_setRteInfo(e,t){this.store.rteUrl=e,this.store.rteSid=t}_isPreRender(){return"isPreRender"in this._p2pChannel&&this._p2pChannel.isPreRender()}_handleResetAddStream(e,t){switch(t){case"audio":e._audio_added_=!1,e._trust_audio_stream_added_state_=!0;break;case"video":e._video_added_=!1,e._trust_video_stream_added_state_=!0}}},mF(hoe.prototype,"leave",[bre],Object.getOwnPropertyDescriptor(hoe.prototype,"leave"),hoe.prototype),mF(hoe.prototype,"publish",[Cre],Object.getOwnPropertyDescriptor(hoe.prototype,"publish"),hoe.prototype),mF(hoe.prototype,"unpublish",[Ire],Object.getOwnPropertyDescriptor(hoe.prototype,"unpublish"),hoe.prototype),mF(hoe.prototype,"subscribe",[Are],Object.getOwnPropertyDescriptor(hoe.prototype,"subscribe"),hoe.prototype),mF(hoe.prototype,"presubscribe",[wre],Object.getOwnPropertyDescriptor(hoe.prototype,"presubscribe"),hoe.prototype),mF(hoe.prototype,"massSubscribe",[Ore],Object.getOwnPropertyDescriptor(hoe.prototype,"massSubscribe"),hoe.prototype),mF(hoe.prototype,"unsubscribe",[Nre],Object.getOwnPropertyDescriptor(hoe.prototype,"unsubscribe"),hoe.prototype),mF(hoe.prototype,"massUnsubscribe",[Dre],Object.getOwnPropertyDescriptor(hoe.prototype,"massUnsubscribe"),hoe.prototype),mF(hoe.prototype,"setLowStreamParameter",[Pre],Object.getOwnPropertyDescriptor(hoe.prototype,"setLowStreamParameter"),hoe.prototype),mF(hoe.prototype,"setDualStreamMode",[Lre],Object.getOwnPropertyDescriptor(hoe.prototype,"setDualStreamMode"),hoe.prototype),mF(hoe.prototype,"enableDualStream",[kre],Object.getOwnPropertyDescriptor(hoe.prototype,"enableDualStream"),hoe.prototype),mF(hoe.prototype,"disableDualStream",[Mre],Object.getOwnPropertyDescriptor(hoe.prototype,"disableDualStream"),hoe.prototype),mF(hoe.prototype,"setClientRole",[Ure],Object.getOwnPropertyDescriptor(hoe.prototype,"setClientRole"),hoe.prototype),mF(hoe.prototype,"_setClientRoleOptions",[Vre],Object.getOwnPropertyDescriptor(hoe.prototype,"_setClientRoleOptions"),hoe.prototype),mF(hoe.prototype,"setProxyServer",[xre],Object.getOwnPropertyDescriptor(hoe.prototype,"setProxyServer"),hoe.prototype),mF(hoe.prototype,"setTurnServer",[Fre],Object.getOwnPropertyDescriptor(hoe.prototype,"setTurnServer"),hoe.prototype),mF(hoe.prototype,"setLicense",[Bre],Object.getOwnPropertyDescriptor(hoe.prototype,"setLicense"),hoe.prototype),mF(hoe.prototype,"startProxyServer",[jre],Object.getOwnPropertyDescriptor(hoe.prototype,"startProxyServer"),hoe.prototype),mF(hoe.prototype,"stopProxyServer",[Gre],Object.getOwnPropertyDescriptor(hoe.prototype,"stopProxyServer"),hoe.prototype),mF(hoe.prototype,"setLocalAccessPointsV2",[Wre],Object.getOwnPropertyDescriptor(hoe.prototype,"setLocalAccessPointsV2"),hoe.prototype),mF(hoe.prototype,"setLocalAccessPoints",[Kre],Object.getOwnPropertyDescriptor(hoe.prototype,"setLocalAccessPoints"),hoe.prototype),mF(hoe.prototype,"setRemoteDefaultVideoStreamType",[Hre],Object.getOwnPropertyDescriptor(hoe.prototype,"setRemoteDefaultVideoStreamType"),hoe.prototype),mF(hoe.prototype,"setRemoteVideoStreamType",[Yre],Object.getOwnPropertyDescriptor(hoe.prototype,"setRemoteVideoStreamType"),hoe.prototype),mF(hoe.prototype,"setStreamFallbackOption",[Xre],Object.getOwnPropertyDescriptor(hoe.prototype,"setStreamFallbackOption"),hoe.prototype),mF(hoe.prototype,"setEncryptionConfig",[Jre],Object.getOwnPropertyDescriptor(hoe.prototype,"setEncryptionConfig"),hoe.prototype),mF(hoe.prototype,"renewToken",[zre],Object.getOwnPropertyDescriptor(hoe.prototype,"renewToken"),hoe.prototype),mF(hoe.prototype,"enableAudioVolumeIndicator",[Zre],Object.getOwnPropertyDescriptor(hoe.prototype,"enableAudioVolumeIndicator"),hoe.prototype),mF(hoe.prototype,"startLiveStreaming",[qre],Object.getOwnPropertyDescriptor(hoe.prototype,"startLiveStreaming"),hoe.prototype),mF(hoe.prototype,"setLiveTranscoding",[Qre],Object.getOwnPropertyDescriptor(hoe.prototype,"setLiveTranscoding"),hoe.prototype),mF(hoe.prototype,"stopLiveStreaming",[$re],Object.getOwnPropertyDescriptor(hoe.prototype,"stopLiveStreaming"),hoe.prototype),mF(hoe.prototype,"startChannelMediaRelay",[eoe],Object.getOwnPropertyDescriptor(hoe.prototype,"startChannelMediaRelay"),hoe.prototype),mF(hoe.prototype,"updateChannelMediaRelay",[toe],Object.getOwnPropertyDescriptor(hoe.prototype,"updateChannelMediaRelay"),hoe.prototype),mF(hoe.prototype,"stopChannelMediaRelay",[noe],Object.getOwnPropertyDescriptor(hoe.prototype,"stopChannelMediaRelay"),hoe.prototype),mF(hoe.prototype,"sendCustomReportMessage",[ioe],Object.getOwnPropertyDescriptor(hoe.prototype,"sendCustomReportMessage"),hoe.prototype),mF(hoe.prototype,"pickSVCLayer",[roe],Object.getOwnPropertyDescriptor(hoe.prototype,"pickSVCLayer"),hoe.prototype),mF(hoe.prototype,"setRTMConfig",[ooe],Object.getOwnPropertyDescriptor(hoe.prototype,"setRTMConfig"),hoe.prototype),mF(hoe.prototype,"enableContentInspect",[soe],Object.getOwnPropertyDescriptor(hoe.prototype,"enableContentInspect"),hoe.prototype),mF(hoe.prototype,"disableContentInspect",[aoe],Object.getOwnPropertyDescriptor(hoe.prototype,"disableContentInspect"),hoe.prototype),mF(hoe.prototype,"setImageModeration",[coe],Object.getOwnPropertyDescriptor(hoe.prototype,"setImageModeration"),hoe.prototype),mF(hoe.prototype,"setP2PTransport",[doe],Object.getOwnPropertyDescriptor(hoe.prototype,"setP2PTransport"),hoe.prototype),mF(hoe.prototype,"getJoinChannelServiceRecords",[loe],Object.getOwnPropertyDescriptor(hoe.prototype,"getJoinChannelServiceRecords"),hoe.prototype),mF(hoe.prototype,"setPublishAudioFilterEnabled",[uoe],Object.getOwnPropertyDescriptor(hoe.prototype,"setPublishAudioFilterEnabled"),hoe.prototype),hoe);function moe(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const t=eP(5,"client-"),n=uk.reportApiInvoke(null,{id:t,name:ED.CREATE_CLIENT,options:[e],tag:mD.TRACER});try{var i;!function(e){qN(e.codec,"config.codec",["vp8","vp9","av1","h264","h265"]),qN(e.mode,"config.mode",["rtc","live","p2p"]),void 0!==e.audioCodec&&qN(e.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),void 0!==e.proxyServer&&eD(e.proxyServer,"config.proxyServer",1,1e4),void 0!==e.turnServer&&RD(e.turnServer),void 0!==e.httpRetryConfig&&fD(e.httpRetryConfig),void 0!==e.websocketRetryConfig&&fD(e.websocketRetryConfig)}(e),(wN(16,0,!0)||ON(16,0,!0))&&("vp9"===e.codec&&(e.codec="vp8",FL.debug("browser not support vp9, force use vp8")),iL("UNSUPPORTED_VIDEO_CODEC",["vp9"])),void 0===e.audioCodec&&(e.audioCodec="opus");const r=new Eoe(_oe(_oe({forceWaitGatewayResponse:!0},e),{},{role:Vi(i=["rtc","p2p"]).call(i,e.mode)?"host":e.role||"audience"}),t);return n.onSuccess(),r}catch(e){throw n.onError(e),e}}function foe(){let e=!1;const t=dN();return(t.name===oN.CHROME&&Number(t.version)>=58&&("WebKit"!==aN.engine.name||function(){const e=dN();if(pN()){if(e.os===rN.MAC_OS)return!0;if(e.os===rN.IOS){const e=aN.os.version&&aN.os.version.split(".");if(e&&14===Number(e[0])&&e[1]&&Number(e[1])>=3)return!0;if(e&&Number(e[0])>14)return!0}}return!1}())||t.name===oN.FIREFOX&&Number(t.version)>=56||t.name===oN.OPERA&&Number(t.version)>=45||t.name===oN.SAFARI&&Number(t.version)>=11||"WebKit"===t.name&&(TN()||MN())&&t.osVersion&&Number(t.osVersion.split(".")[0])>=11||UN()||dN().name===oN.QQ)&&(e=!0),e}class goe{constructor(e,t){GA(this,"id",0),GA(this,"element",void 0),GA(this,"peerPair",void 0),GA(this,"context",void 0),GA(this,"audioPlayerElement",void 0),GA(this,"audioTrack",void 0),goe.count+=1,this.id=goe.count,this.element=e,this.context=t}initPeers(){this.peerPair=[new RTCPeerConnection,new RTCPeerConnection],this.peerPair[1].ontrack=e=>{const t=document.createElement("audio");t.srcObject=new MediaStream([e.track]),t.play(),this.audioPlayerElement=t}}async switchSdp(){if(!this.peerPair)return;const e=async(e,t)=>{const n="offer"===t?await e.createOffer():await e.createAnswer();return await e.setLocalDescription(n),"complete"===e.iceGatheringState?e.localDescription:new dp((t=>{e.onicegatheringstatechange=()=>{"complete"===e.iceGatheringState&&t(e.localDescription)}}))},t=async(e,t)=>await e.setRemoteDescription(t);try{const n=await e(this.peerPair[0],"offer");await t(this.peerPair[1],n);const i=await e(this.peerPair[1],"answer");await t(this.peerPair[0],i)}catch(e){throw new hk(JN.LOCAL_AEC_ERROR,e.toString()).print()}}async getTracksFromMediaElement(e){if(this.audioTrack)return this.audioTrack;let t;try{e instanceof HTMLVideoElement&&(e.captureStream?e.captureStream():e.mozCaptureStream()),t=this.context.createMediaStreamDestination();this.context.createMediaElementSource(e).connect(t)}catch(e){throw new hk(JN.LOCAL_AEC_ERROR,e.toString()).print()}if(!t){throw new hk(JN.LOCAL_AEC_ERROR,"no dest node when local aec").print()}const n=t.stream.getAudioTracks()[0];return this.audioTrack=n,n}getElement(){return this.element}async startEchoCancellation(){this.context.resume(),this.peerPair&&this.close(),this.initPeers();const e=this.element,t=await this.getTracksFromMediaElement(e);this.peerPair&&this.peerPair[0].addTrack(t),await this.switchSdp()}close(){FL.debug("close echo cancellation unit, id is",this.id),this.audioPlayerElement&&this.audioPlayerElement.pause(),this.peerPair&&this.peerPair.forEach((e=>{e.close()})),this.peerPair=void 0,this.audioPlayerElement=void 0}}var Soe,Toe;GA(goe,"count",0);const Roe=window.AudioContext||window.webkitAudioContext;const voe=new(Soe=lk({report:uk}),mF((Toe=class{constructor(){GA(this,"units",[]),GA(this,"context",void 0)}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return FL.debug("the system does not need to process local aec"),-1;this.context||(this.context=new Roe);let t=this.units.find((t=>t&&t.getElement()===e));return t||(t=new goe(e,this.context),this.units.push(t)),t.startEchoCancellation(),FL.debug("start processing local audio echo cancellation, id is",t.id),t.id}_doesEnvironmentNeedAEC(){return dN().name!==oN.SAFARI}}).prototype,"processExternalMediaAEC",[Soe],Object.getOwnPropertyDescriptor(Toe.prototype,"processExternalMediaAEC"),Toe.prototype),Toe);function yoe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function boe(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?yoe(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):yoe(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const Coe=window||document;function Ioe(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!Coe)return;const n=Lae._cspEventHandlerPointer;if(n&&t)return void console.error(n,t);const i=e=>{if(!(e&&e.blockedURI&&(Lae.onSecurityPolicyViolation||Lae.getListeners(_B.SECURITY_POLICY_VIOLATION).length>0)))return;const t=e.blockedURI;rL("CSP_DETECTED_HOSTNAME_LIST").some((e=>Vi(t).call(t,e)))&&(Lae.onSecurityPolicyViolation&&"function"==typeof Lae.onSecurityPolicyViolation&&Lae.onSecurityPolicyViolation(e),Lae.getListeners(_B.SECURITY_POLICY_VIOLATION).length>0&&Lae.safeEmit(_B.SECURITY_POLICY_VIOLATION,e))};n&&Coe.removeEventListener("securitypolicyviolation",n),(t||e&&"function"==typeof e||Lae.getListeners(_B.SECURITY_POLICY_VIOLATION).length>0)&&Coe.addEventListener("securitypolicyviolation",i),Lae._cspEventHandlerPointer=i}var Aoe=function(e){return e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE",e}(Aoe||{});class woe{constructor(){GA(this,"_sequence",0),GA(this,"_startTime",Date.now()),GA(this,"isUseOneByte",!0)}get startTime(){const e=Date.now()-this._startTime;return e<Math.pow(2,16)?e:(this._startTime+=Math.pow(2,16),this.startTime)}get sequence(){return this._sequence<Math.pow(2,32)?this._sequence++:(this._sequence-=Math.pow(2,32),this.sequence)}serialize(e){const t={commonPacketHeader:{length:0,reserved:0,extension:0,sequence:this.sequence},commonStreamHeader:this.startTime,extension:void 0,payload:e};if(e.byteLength>128){const n=new Uint8Array(4);n.set([1,0,0,0]);const i={id:0,length:4,data:n.buffer},r={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[i]};t.commonPacketHeader.extension=1,t.extension=r,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength}else t.commonPacketHeader.length=8+t.payload.byteLength;rL("SHOW_DATASTREAM2_LOG")&&FL.debug("send data header: ".concat(JSON.stringify(t.commonPacketHeader)));const n=new ArrayBuffer(t.commonPacketHeader.length),i=new Uint8Array(n),r=new DataView(n);let o=0;if(r.setUint16(o,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),o+=2,r.setUint32(o,t.commonPacketHeader.sequence,!0),o+=4,r.setUint16(o,t.commonStreamHeader,!0),o+=2,t.extension){const e=this.serializeExtension(t.extension);i.set(new Uint8Array(e),o),o+=e.byteLength}if(i.set(new Uint8Array(t.payload),o),o+=t.payload.byteLength,o!==t.commonPacketHeader.length)throw Error("serialize error!");return n}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let n=0;const i=t.getUint16(n,!0);n+=2;const r={length:16383&i,reserved:(16384&i)>>14,extension:(32768&i)>>15,sequence:t.getUint16(n+2,!0)<<16|t.getUint16(n,!0)};let o,s;if(n+=4,rL("SHOW_DATASTREAM2_LOG")&&FL.debug("receive data header: ".concat(JSON.stringify(r))),t.getUint16(n,!0),n+=2,r.extension){s=this.deserializeExtension(e.slice(n)),n+=2+s.length,o=e.slice(n);let t=!1;if(s.datas.length>0){const e=s.datas.find((e=>0===e.id));if(e){t=1==(1&new DataView(e.data).getUint32(0,!0))}}o=t?this.decompress(o):o}else o=e.slice(8);return o}serializeExtension(e){const t=e.profile,n=e.length,i=e.datas,r=new ArrayBuffer(n+2),o=new Uint8Array(r),s=new DataView(r);let a=0;if(s.setUint8(a++,t),s.setUint8(a++,n),i.forEach((e=>{t?(s.setUint8(a++,e.id),s.setUint8(a++,e.length),o.set(new Uint8Array(e.data),a),a+=e.data.byteLength):(s.setUint8(a++,e.id|e.length<<4),o.set(new Uint8Array(e.data),a),a+=e.data.byteLength)})),a!==n+2)throw Error("serialize extension error, is ".concat(a,"!==").concat(n+2));return r}deserializeExtension(e){const t=new DataView(e);let n=0;const i=t.getUint8(n);n++;const r=t.getUint8(n);n++;const o=i===Aoe.TWO_BYTE,s=[],a=new DataView(e,2);let c=0;for(;c<r;){let e=0,t=0,n=new ArrayBuffer(0);o?(e=a.getUint8(c),c++,t=a.getUint8(c),c++):(e=15&a.getUint8(c),t=a.getUint8(c)>>4,c++),t>0&&(n=a.buffer.slice(c+2,c+2+t),c+=n.byteLength),s.push({id:e,length:t,data:n})}if(c!==r)throw Error("parse error");return{profile:i,length:r,datas:s}}decompress(e){return lK(new Uint8Array(e))}compress(e){return cK(new Uint8Array(e))}}const Ooe={name:"DataStream",create:(e,t)=>{const n=t?new cx(e):new dx(e);return n.useDataStream(new woe),n}};class Noe extends hD{constructor(e,t,n){super(),GA(this,"ws",void 0),GA(this,"requestId",1),GA(this,"heartBeatTimer",void 0),GA(this,"joinInfo",void 0),GA(this,"clientId",void 0),GA(this,"onOpen",(()=>{this.emit("open"),this.startHeartBeatCheck()})),GA(this,"onClose",(e=>{this.emit("close"),this.dispose()})),GA(this,"onMessage",(e=>{const t=JSON.parse(e.data);if(!t||"serverResponse"!==t.command||!t.requestId)return t&&"serverStatus"===t.command&&t.serverStatus&&t.serverStatus.command?(this.emit("status",t.serverStatus),void this.emit(t.serverStatus.command,t.serverStatus)):void 0;this.emit("req_".concat(t.requestId),t)})),this.joinInfo=e,this.clientId=t,this.ws=new xB("cross-channel-".concat(this.clientId),n),this.ws.on(wF.RECONNECTING,(()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")})),this.ws.on(wF.CONNECTED,this.onOpen),this.ws.on(wF.ON_MESSAGE,this.onMessage),this.ws.on(wF.CLOSED,this.onClose)}isConnect(){return"connected"===this.ws.state}sendMessage(e){const t=this.requestId++;return e.requestId=t,e.seq=t,this.ws.sendMessage(e),t}waitStatus(e){return new dp(((t,n)=>{const i=window.setTimeout((()=>{n(new hk(JN.TIMEOUT,"wait status timeout, status: ".concat(e)))}),5e3);this.once(e,(r=>{window.clearTimeout(i),r.state&&0!==r.state?n(new hk(JN.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0)})),this.once("dispose",(()=>{window.clearTimeout(i),n(new hk(JN.WS_ABORT))}))}))}async request(e){if("closed"===this.ws.state)throw new hk(JN.WS_DISCONNECT);const t=()=>new dp(((e,t)=>{this.ws.once(wF.CLOSED,(()=>t(new hk(JN.WS_ABORT)))),this.ws.once(wF.CONNECTED,e)}));"connected"!==this.ws.state&&await t();const n=this.sendMessage(e),i=new dp(((e,t)=>{const i=()=>{t(new hk(JN.WS_ABORT))};this.ws.once(wF.RECONNECTING,i),this.ws.once(wF.CLOSED,i),this.once("req_".concat(n),e),$D(3e3).then((()=>{this.removeAllListeners("req_".concat(n)),this.ws.off(wF.RECONNECTING,i),this.ws.off(wF.CLOSED,i),t(new hk(JN.TIMEOUT,"cross channel ws request timeout"))}))})),r=await i;if(!r||200!==r.code)throw new hk(JN.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(r)));return r}async connect(e){this.ws.removeAllListeners(wF.REQUEST_NEW_URLS),this.ws.on(wF.REQUEST_NEW_URLS,(t=>{t(e)})),await this.ws.init(e)}dispose(){this.clearHeartBeatCheck(),this.emit("dispose"),this.removeAllListeners(),this.ws.close()}sendPing(e){const t=this.requestId++;return e.requestId=t,this.ws.sendMessage(e),t}startHeartBeatCheck(){this.heartBeatTimer&&window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=window.setInterval((()=>{this.sendPing({command:"ping",appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sid:this.joinInfo.sid,ts:+new Date,requestId:0})}),3e3)}clearHeartBeatCheck(){window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=void 0}}class Doe extends hD{set state(e){e!==this._state&&(e!==GF.RELAY_STATE_FAILURE&&(this.errorCode=WF.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,t,n,i,r){super(),GA(this,"joinInfo",void 0),GA(this,"sid",void 0),GA(this,"clientId",void 0),GA(this,"cancelToken",QO.CancelToken.source()),GA(this,"workerToken",void 0),GA(this,"requestId",0),GA(this,"signal",void 0),GA(this,"prevChannelMediaConfig",void 0),GA(this,"httpRetryConfig",void 0),GA(this,"_resolution",void 0),GA(this,"_state",GF.RELAY_STATE_IDLE),GA(this,"errorCode",WF.RELAY_OK),GA(this,"onStatus",(e=>{FL.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",jF.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",jF.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=WF.SRC_TOKEN_EXPIRED,this.state=GF.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=WF.DEST_TOKEN_EXPIRED,this.state=GF.RELAY_STATE_FAILURE))})),GA(this,"onReconnect",(async()=>{FL.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",jF.NETWORK_DISCONNECTED),this.state=GF.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch((e=>{this.state!==GF.RELAY_STATE_IDLE&&(FL.error("auto restart channel media relay failed",e.toString()),this.errorCode=WF.SERVER_CONNECTION_LOST,this.state=GF.RELAY_STATE_FAILURE)}))})),this.joinInfo=e,this.clientId=t,this.sid=tP(),this.signal=new Noe(this.joinInfo,this.clientId,n),this.httpRetryConfig=i,this._resolution=r}async startChannelMediaRelay(e){if(this.state!==GF.RELAY_STATE_IDLE)throw new hk(JN.INVALID_OPERATION);this.state=GF.RELAY_STATE_CONNECTING,await this.connect(),FL.debug("[".concat(this.clientId,"] startChannelMediaRelay: connect success"));try{await this.sendStartRelayMessage(e)}catch(e){if(e.data&&e.data.serverResponse&&"SetSourceChannel"===e.data.serverResponse.command)throw new hk(JN.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new hk(JN.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new hk(JN.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==GF.RELAY_STATE_RUNNING)throw new hk(JN.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async setVideoProfile(e){if(this._resolution=e,this.state!==GF.RELAY_STATE_RUNNING)throw new hk(JN.INVALID_OPERATION);const t=this.genMessage(BF.SetVideoProfile);await this.signal.request(t),FL.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"))}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),FL.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=GF.RELAY_STATE_IDLE,this.dispose()}dispose(){FL.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=QO.CancelToken.source(),this.state=GF.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const e=await xte(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",jF.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(e){const t=this.genMessage(BF.SetSdkProfile,e);await this.signal.request(t),FL.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const n=this.genMessage(BF.SetSourceChannel,e);await this.signal.request(n),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",jF.PACKET_JOINED_SRC_CHANNEL),FL.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const i=this.genMessage(BF.SetSourceUserId,e);await this.signal.request(i),FL.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const r=this.genMessage(BF.SetDestChannel,e);await this.signal.request(r),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",jF.PACKET_JOINED_DEST_CHANNEL),FL.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const o=this.genMessage(BF.StartPacketTransfer,e);await this.signal.request(o),this.emit("event",jF.PACKET_SENT_TO_DEST_CHANNEL),this.state=GF.RELAY_STATE_RUNNING,FL.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution)}async sendUpdateMessage(e){const t=this.genMessage(BF.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",jF.PACKET_UPDATE_DEST_CHANNEL),FL.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){const e=this.genMessage(BF.StopPacketTransfer);await this.signal.request(e),FL.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))}genMessage(e,t){const n=[],i=[],r=[];this.requestId+=1;const o={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:JP,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.24.4"===o.sdkVersion&&(o.sdkVersion="0.0.1");let s=null,a=null;switch(e){case BF.SetSdkProfile:return o.clientRequest={command:"SetSdkProfile",type:"multi_channel"},o;case BF.SetSourceChannel:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new hk(JN.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceChannel",uid:"0",channelName:a.channelName,token:a.token||this.joinInfo.appId},o;case BF.SetSourceUserId:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new hk(JN.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceUserId",uid:a.uid+""},o;case BF.SetDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new hk(JN.UNEXPECTED_ERROR,"can not find dest config");return s.forEach((e=>{n.push(e.channelName),i.push(e.uid+""),r.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:"SetDestChannel",channelName:n,uid:i,token:r},o;case BF.StartPacketTransfer:return o.clientRequest={command:"StartPacketTransfer"},o;case BF.Reconnect:return o.clientRequest={command:"Reconnect"},o;case BF.StopPacketTransfer:return o.clientRequest={command:"StopPacketTransfer"},o;case BF.UpdateDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new hk(JN.UNEXPECTED_ERROR,"can not find dest config");return s.forEach((e=>{n.push(e.channelName),i.push(e.uid+""),r.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:"UpdateDestChannel",channelName:n,uid:i,token:r},o;case BF.SetVideoProfile:o.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return o}}const Poe={name:"ChannelMediaRelay",create:function(e){return new Doe(e.joinInfo,e.clientId,e.websocketRetryConfig||mP,e.httpRetryConfig||mP,e.resolution)}};function Loe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function koe(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Loe(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Loe(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class Moe extends hD{constructor(e,t,n,i){super(),GA(this,"spec",void 0),GA(this,"token",void 0),GA(this,"websocket",void 0),GA(this,"pingpongTimer",void 0),GA(this,"reconnectMode","retry"),GA(this,"serviceMode",void 0),GA(this,"reqId",0),GA(this,"commandReqId",0),GA(this,"handleWebSocketOpen",(()=>{this.reconnectMode="retry",this.startPingPong()})),GA(this,"handleWebSocketMessage",(e=>{if(!e.data)return;const t=JSON.parse(e.data);t.requestId?this.emit("@".concat(t.requestId,"-").concat(t.sid),t):(uk.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===DF.TRANSCODE?1:2}),this.emit(UF.PUBLISH_STREAM_STATUS,t))})),this.spec=t,this.token=e,this.serviceMode=i,this.websocket=new xB("live-streaming",n),this.websocket.on(wF.CONNECTED,this.handleWebSocketOpen),this.websocket.on(wF.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(wF.REQUEST_NEW_URLS,((e,t)=>{OD(this,UF.REQUEST_NEW_ADDRESS).then(e).catch(t)})),this.websocket.on(wF.RECONNECTING,(()=>{this.websocket.reconnectMode=this.reconnectMode}))}init(e){return this.websocket.init(e)}async request(e,t,n,i){this.reqId+=1,"request"===e&&(this.commandReqId+=1);const r=this.commandReqId,o=this.reqId;if(!o||!this.websocket)throw new hk(JN.UNEXPECTED_ERROR);const s=koe({command:e,sdkVersion:"4.24.4"===JP?"0.0.1":JP,seq:o,requestId:o,allocate:n,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},t);if("closed"===this.websocket.state)throw new hk(JN.WS_DISCONNECT);const a=()=>new dp(((e,t)=>{this.websocket.once(wF.CLOSED,(()=>t(new hk(JN.WS_ABORT)))),this.websocket.once(wF.CONNECTED,e)}));"connected"!==this.websocket.state&&await a(),s.clientRequest&&(s.clientRequest.workerToken=this.token);const c=new dp(((e,t)=>{const n=()=>{t(new hk(JN.WS_ABORT))};this.websocket.once(wF.RECONNECTING,n),this.websocket.once(wF.CLOSED,n),this.once("@".concat(o,"-").concat(this.spec.sid),(t=>{e(t)}))}));i&&uk.workerEvent(this.spec.sid,koe(koe({},i),{},{requestId:r,actionType:"request",payload:JSON.stringify(t.clientRequest),serverCode:0,code:0}));const d=Date.now();this.websocket.sendMessage(s);let l=null;try{l=await c}catch(i){if("closed"===this.websocket.state)throw i;return await a(),await this.request(e,t,n)}return i&&uk.workerEvent(this.spec.sid,koe(koe({},i),{},{requestId:r,actionType:"response",payload:JSON.stringify(l.serverResponse),serverCode:l.code,success:200===l.code,responseTime:Date.now()-d})),200!==l.code&&this.handleResponseError(l),l}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext")}close(){const e="4.24.4"===JP?"0.0.1":JP;this.reqId+=1,"connected"===this.websocket.state?(this.websocket.sendMessage({command:"request",appId:this.spec.appId,cname:this.spec.cname,uid:this.spec.uid.toString(),sdkVersion:e,sid:this.spec.sid,seq:this.reqId,ts:Math.floor(Date.now()/1e3),requestId:this.reqId,clientRequest:{command:"DestroyWorker"}}),this.websocket.close(!1,!0)):this.websocket.close(!1),this.pingpongTimer&&(window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0)}handleResponseError(e){switch(e.code){case xF.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void FL.warning("live stream response already exists stream");case xF.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case xF.LIVE_STREAM_RESPONSE_BAD_STREAM:case xF.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new hk(JN.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case xF.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"===e.serverResponse.command)return;throw new hk(JN.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case xF.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new hk(JN.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case xF.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new hk(JN.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(UF.WARNING,t,e.serverResponse.url)}case xF.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new hk(JN.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(UF.WARNING,t,e.serverResponse.url)}case xF.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new hk(JN.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case xF.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new hk(JN.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case xF.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new hk(JN.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(UF.WARNING,t,e.serverResponse.url)}case xF.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new hk(JN.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case xF.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new hk(JN.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case xF.LIVE_STREAM_RESPONSE_WORKER_LOST:case xF.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command)return;throw new hk(JN.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case xF.ERROR_FAIL_SEND_MESSAGE:if("UnpublishStream"===e.serverResponse.command)return;if("UpdateTranscoding"===e.serverResponse.command||"ControlStream"===e.serverResponse.command)return new hk(JN.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new hk(JN.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case xF.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case xF.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case xF.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case xF.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new hk(JN.LIVE_STREAMING_CDN_ERROR,"",{code:e.code}).throw()}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval((()=>{"connected"===this.websocket.state&&this.request("ping",{}).catch(nP)}),6e3)}}function Uoe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Voe(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Uoe(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Uoe(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class xoe extends hD{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mP,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:mP;super(),GA(this,"onLiveStreamWarning",void 0),GA(this,"onLiveStreamError",void 0),GA(this,"spec",void 0),GA(this,"retryTimeout",1e4),GA(this,"connection",void 0),GA(this,"httpRetryConfig",void 0),GA(this,"wsRetryConfig",void 0),GA(this,"streamingTasks",new Map),GA(this,"isStartingStreamingTask",!1),GA(this,"taskMutex",new _P("live-streaming")),GA(this,"cancelToken",QO.CancelToken.source()),GA(this,"transcodingConfig",void 0),GA(this,"uapResponse",void 0),GA(this,"lastTaskId",1),GA(this,"statusError",new Map),this.spec=e,this.httpRetryConfig=n,this.wsRetryConfig=t}async setTranscodingConfig(e){const t=Voe(Voe({},MF),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(FL.debug("[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ").concat(t.videoCodecProfile," -> 100")),t.videoCodecProfile=100),t.transcodingUsers||(t.transcodingUsers=t.userConfigs),t.transcodingUsers&&(t.transcodingUsers=t.transcodingUsers.map((e=>Voe(Voe(Voe({},PF),e),{},{zOrder:e.zOrder?e.zOrder+1:1})))),function(e){nD(e.width)||QN(e.width,"config.width",0,1e4),nD(e.height)||QN(e.height,"config.height",0,1e4),nD(e.videoBitrate)||QN(e.videoBitrate,"config.videoBitrate",1,1e6),nD(e.videoFrameRate)||QN(e.videoFrameRate,"config.videoFrameRate"),nD(e.lowLatency)||ZN(e.lowLatency,"config.lowLatency"),nD(e.audioSampleRate)||qN(e.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),nD(e.audioBitrate)||QN(e.audioBitrate,"config.audioBitrate",1,128),nD(e.audioChannels)||qN(e.audioChannels,"config.audioChannels",[1,2,3,4,5]),nD(e.videoGop)||QN(e.videoGop,"config.videoGop"),nD(e.videoCodecProfile)||qN(e.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),nD(e.userCount)||QN(e.userCount,"config.userCount",0,17),nD(e.backgroundColor)||QN(e.backgroundColor,"config.backgroundColor",0,16777215),nD(e.userConfigExtraInfo)||eD(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!nD(e.transcodingUsers)&&(tD(e.transcodingUsers,"config.transcodingUsers"),e.transcodingUsers.forEach(((e,t)=>{NF(e.uid),nD(e.x)||QN(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),nD(e.y)||QN(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),nD(e.width)||QN(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),nD(e.height)||QN(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),nD(e.zOrder)||QN(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),nD(e.alpha)||QN(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1)}))),nD(e.watermark)||kF(e.watermark,"watermark"),nD(e.backgroundImage)||kF(e.backgroundImage,"backgroundImage"),e.images&&!nD(e.images)&&(tD(e.images,"config.images"),e.images.forEach(((e,t)=>{kF(e,"images[".concat(t,"]"))})))}(t);const n=[];t.images&&n.push(...t.images.map((e=>Voe(Voe(Voe({},LF),e),{},{zOrder:255})))),t.backgroundImage&&(n.push(Voe(Voe(Voe({},LF),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(n.push(Voe(Voe(Voe({},LF),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=n,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map((e=>Voe({},e))),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const i=(t.userConfigs||[]).map((e=>"number"==typeof e.uid?dp.resolve(e.uid):Lte(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig)));if((await dp.all(i)).forEach(((e,n)=>{t.userConfigs&&t.userConfigs[n]&&(t.userConfigs[n].uid=e)})),this.transcodingConfig=t,this.connection)try{var r;const e=await this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:Array.from(gp(r=this.streamingTasks).call(r)).map((e=>e.taskId)).join("#")});FL.debug("[".concat(this.spec.clientId,"] update live transcoding config success, code: ").concat(e.code,", config:"),JSON.stringify(this.transcodingConfig))}catch(e){if(!e.data||!e.data.retry)throw e;e.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach((t=>{FL.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then((()=>{FL.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"))})).catch((e=>{FL.error("[".concat(this.spec.clientId,"] live streaming republish failed"),t.url,e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}))}))}}async startLiveStreamingTask(e,t,n){if(!this.transcodingConfig&&t===DF.TRANSCODE)throw new hk(JN.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");const i={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};FL.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(e,", mode: ").concat(t));const r=await this.taskMutex.lock();if(!this.connection&&n)return void r();if(this.streamingTasks.get(e)&&!n)return r(),new hk(JN.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t))}catch(e){throw r(),e}switch(t){case DF.TRANSCODE:i.transcodingConfig=Voe({},this.transcodingConfig);case DF.RAW:}this.uapResponse&&this.uapResponse.vid&&(i.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const o=this.lastTaskId++;try{const s=new dp(((t,i)=>{$D(this.retryTimeout).then((()=>{if(n)return i(n);const t=this.statusError.get(e);return t?(this.statusError.delete(e),i(t)):void 0}))})),a=await dp.race([this.connection.request("request",{clientRequest:i},!0,{url:e,command:"PublishStream",workerType:t===DF.TRANSCODE?1:2,requestByUser:!n,tid:o.toString()}),s]);this.isStartingStreamingTask=!1,FL.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(a.code)),this.streamingTasks.set(e,{clientRequest:i,mode:t,url:e,taskId:o}),r()}catch(i){if(r(),this.isStartingStreamingTask=!1,!i.data||!i.data.retry||n)throw i;return i.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(e,t,i)):await this.startLiveStreamingTask(e,t,i)}}stopLiveStreamingTask(e){return new dp(((t,n)=>{const i=this.streamingTasks.get(e);if(!i||!this.connection)return new hk(JN.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const r=i.mode;i.abortTask=()=>{FL.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),t()},this.connection.request("request",{clientRequest:{command:"UnpublishStream",url:i.url}},!1,{url:e,command:"UnPublishStream",workerType:r===DF.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then((n=>{FL.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(n.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&(this.connection&&this.connection.close(),this.connection=void 0),t()})).catch(n)}))}resetAllTask(){var e;const t=Array.from(gp(e=this.streamingTasks).call(e));this.terminate();for(const e of t)this.startLiveStreamingTask(e.url,e.mode).catch((t=>{this.onLiveStreamError&&this.onLiveStreamError(e.url,t)}))}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.statusError=new Map,this.cancelToken=QO.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(e){if(this.connection)throw new hk(JN.UNEXPECTED_ERROR,"live streaming connection has already connected");const t=await OD(this,VF.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new Moe(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(UF.WARNING,((e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e))),this.connection.on(UF.PUBLISH_STREAM_STATUS,(e=>this.handlePublishStreamServer(e))),this.connection.on(UF.REQUEST_NEW_ADDRESS,((t,n)=>{if(!this.connection)return n(new hk(JN.UNEXPECTED_ERROR,"can not get new live streaming address list"));OD(this,VF.REQUEST_WORKER_MANAGER_LIST,e).then((e=>{this.uapResponse=e,t(e.addressList)})).catch(n)})),await this.connection.init(t.addressList),this.connection}handlePublishStreamServer(e){const t=e.serverStatus&&e.serverStatus.url||"empty_url",n=this.streamingTasks.get(t),i=e.reason;switch(e.code){case xF.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case xF.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case xF.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case xF.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const i=new hk(JN.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(n)return FL.error(i.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,i);if(!this.isStartingStreamingTask)return;this.statusError.set(t,i)}case xF.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new hk(JN.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,i);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)}case xF.LIVE_STREAM_RESPONSE_WORKER_LOST:case xF.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var r;if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(gp(r=this.streamingTasks).call(r));for(const n of t)n.abortTask?n.abortTask():(FL.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",n.url),this.startLiveStreamingTask(n.url,n.mode,new hk(JN.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then((()=>{FL.debug("[".concat(this.spec.clientId,"] republish live stream success"),n.url)})).catch((e=>{FL.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(n.url,e)})));return}}}hasUrl(e){return this.streamingTasks.has(e)}}const Foe={name:"LiveStreaming",create:function(e){return new xoe(e.joinInfo,e.websocketRetryConfig||mP,e.httpRetryConfig||mP)}};function Boe(e){let t=qoe();return function(e,t){let n=e.appId;void 0!==n&&(use(t,10),rse(t,n));let i=e.cid;void 0!==i&&(use(t,16),use(t,i));let r=e.cname;void 0!==r&&(use(t,26),rse(t,r));let o=e.deviceId;void 0!==o&&(use(t,34),rse(t,o));let s=e.elapse;void 0!==s&&(use(t,40),hse(t,s));let a=e.fileSize;void 0!==a&&(use(t,48),hse(t,zoe(a)));let c=e.height;void 0!==c&&(use(t,56),hse(t,zoe(c)));let d=e.jpg;void 0!==d&&(use(t,66),use(t,d.length),function(e,t){let n=tse(e,t.length);e.bytes.set(t,n)}(t,d));let l=e.networkType;void 0!==l&&(use(t,72),hse(t,zoe(l)));let u=e.osType;void 0!==u&&(use(t,80),hse(t,zoe(u)));let h=e.requestId;void 0!==h&&(use(t,90),rse(t,h));let p=e.sdkVersion;void 0!==p&&(use(t,98),rse(t,p));let _=e.sequence;void 0!==_&&(use(t,104),hse(t,zoe(_)));let E=e.sid;void 0!==E&&(use(t,114),rse(t,E));let m=e.timestamp;void 0!==m&&(use(t,120),hse(t,m));let f=e.uid;void 0!==f&&(use(t,128),use(t,f));let g=e.vid;void 0!==g&&(use(t,136),use(t,g));let S=e.width;void 0!==S&&(use(t,144),hse(t,zoe(S)));let T=e.service;void 0!==T&&(use(t,152),use(t,T));let R=e.callbackData;void 0!==R&&(use(t,162),rse(t,R));let v=e.jpgEncryption;void 0!==v&&(use(t,168),use(t,v));let y=e.requestType;void 0!==y&&(use(t,176),use(t,y));let b=e.scorePorn;void 0!==b&&(use(t,185),dse(t,b));let C=e.scoreSexy;void 0!==C&&(use(t,193),dse(t,C));let I=e.scoreNeutral;void 0!==I&&(use(t,201),dse(t,I));let A=e.scene;void 0!==A&&(use(t,208),use(t,A));let w=e.ossFilePrefix;void 0!==w&&(use(t,218),rse(t,w));let O=e.serviceVendor;if(void 0!==O)for(let e of O){use(t,226);let n=qoe();Woe(e,n),use(t,n.limit),ose(t,n),Qoe(n)}}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function joe(e){return function(e){let t={};e:for(;!ese(e);){let n=lse(e);switch(n>>>3){case 0:break e;case 1:t.code=lse(e);break;case 2:t.msg=ise(e,lse(e));break;case 3:{let n=Koe(e);t.data=Goe(e),e.limit=n;break}default:Hoe(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function Goe(e){let t={};e:for(;!ese(e);){let n=lse(e);switch(n>>>3){case 0:break e;case 1:t.requestId=ise(e,lse(e));break;case 2:t.requestType=lse(e)>>>0;break;case 3:t.scorePorn=cse(e);break;case 4:t.scoreSexy=cse(e);break;case 5:t.scoreNeutral=cse(e);break;case 6:t.requestScene=lse(e)>>>0;break;case 7:t.scene=lse(e)>>>0;break;default:Hoe(e,7&n)}}return t}function Woe(e,t){let n=e.service;void 0!==n&&(use(t,8),use(t,n));let i=e.vendor;void 0!==i&&(use(t,16),use(t,i));let r=e.token;void 0!==r&&(use(t,26),rse(t,r));let o=e.callbackUrl;void 0!==o&&(use(t,34),rse(t,o))}function Koe(e){let t=lse(e),n=e.limit;return e.limit=e.offset+t,n}function Hoe(e,t){switch(t){case 0:for(;128&sse(e););break;case 2:$oe(e,lse(e));break;case 5:$oe(e,4);break;case 1:$oe(e,8);break;default:throw new Error("Unimplemented type: "+t)}}let Yoe=new Float32Array(1);new Uint8Array(Yoe.buffer);let Xoe=new Float64Array(1),Joe=new Uint8Array(Xoe.buffer);function zoe(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let Zoe=[];function qoe(){const e=Zoe.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function Qoe(e){Zoe.push(e)}function $oe(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function ese(e){return e.offset>=e.limit}function tse(e,t){let n=e.bytes,i=e.offset,r=e.limit,o=i+t;if(o>n.length){let t=new Uint8Array(2*o);t.set(n),e.bytes=t}return e.offset=o,o>r&&(e.limit=o),i}function nse(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function ise(e,t){let n=nse(e,t),i=String.fromCharCode,r=e.bytes,o="�",s="";for(let e=0;e<t;e++){let a,c,d,l,u=r[e+n];0==(128&u)?s+=i(u):192==(224&u)?e+1>=t?s+=o:(a=r[e+n+1],128!=(192&a)?s+=o:(l=(31&u)<<6|63&a,l<128?s+=o:(s+=i(l),e++))):224==(240&u)?e+2>=t?s+=o:(a=r[e+n+1],c=r[e+n+2],32896!=(49344&(a|c<<8))?s+=o:(l=(15&u)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?s+=o:(s+=i(l),e+=2))):240==(248&u)?e+3>=t?s+=o:(a=r[e+n+1],c=r[e+n+2],d=r[e+n+3],8421504!=(12632256&(a|c<<8|d<<16))?s+=o:(l=(7&u)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?s+=o:(l-=65536,s+=i(55296+(l>>10),56320+(1023&l)),e+=3))):s+=o}return s}function rse(e,t){let n=t.length,i=0;for(let e=0;e<n;e++){let r=t.charCodeAt(e);r>=55296&&r<=56319&&e+1<n&&(r=(r<<10)+t.charCodeAt(++e)-56613888),i+=r<128?1:r<2048?2:r<65536?3:4}use(e,i);let r=tse(e,i),o=e.bytes;for(let e=0;e<n;e++){let i=t.charCodeAt(e);i>=55296&&i<=56319&&e+1<n&&(i=(i<<10)+t.charCodeAt(++e)-56613888),i<128?o[r++]=i:(i<2048?o[r++]=i>>6&31|192:(i<65536?o[r++]=i>>12&15|224:(o[r++]=i>>18&7|240,o[r++]=i>>12&63|128),o[r++]=i>>6&63|128),o[r++]=63&i|128)}}function ose(e,t){let n=tse(e,t.limit),i=e.bytes,r=t.bytes;for(let e=0,o=t.limit;e<o;e++)i[e+n]=r[e]}function sse(e){return e.bytes[nse(e,1)]}function ase(e,t){let n=tse(e,1);e.bytes[n]=t}function cse(e){let t=nse(e,8),n=e.bytes;return Joe[0]=n[t++],Joe[1]=n[t++],Joe[2]=n[t++],Joe[3]=n[t++],Joe[4]=n[t++],Joe[5]=n[t++],Joe[6]=n[t++],Joe[7]=n[t++],Xoe[0]}function dse(e,t){let n=tse(e,8),i=e.bytes;Xoe[0]=t,i[n++]=Joe[0],i[n++]=Joe[1],i[n++]=Joe[2],i[n++]=Joe[3],i[n++]=Joe[4],i[n++]=Joe[5],i[n++]=Joe[6],i[n++]=Joe[7]}function lse(e){let t,n=0,i=0;do{t=sse(e),n<32&&(i|=(127&t)<<n),n+=7}while(128&t);return i}function use(e,t){for(t>>>=0;t>=128;)ase(e,127&t|128),t>>>=7;ase(e,t)}function hse(e,t){let n=t.low>>>0,i=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,o=0===r?0===i?n<16384?n<128?1:2:n<1<<21?3:4:i<16384?i<128?5:6:i<1<<21?7:8:r<128?9:10,s=tse(e,o),a=e.bytes;switch(o){case 10:a[s+9]=r>>>7&1;case 9:a[s+8]=9!==o?128|r:127&r;case 8:a[s+7]=8!==o?i>>>21|128:i>>>21&127;case 7:a[s+6]=7!==o?i>>>14|128:i>>>14&127;case 6:a[s+5]=6!==o?i>>>7|128:i>>>7&127;case 5:a[s+4]=5!==o?128|i:127&i;case 4:a[s+3]=4!==o?n>>>21|128:n>>>21&127;case 3:a[s+2]=3!==o?n>>>14|128:n>>>14&127;case 2:a[s+1]=2!==o?n>>>7|128:n>>>7&127;case 1:a[s]=1!==o?128|n:127&n}}function pse(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}const _se=new Map([["moderation",1],["supervise",2]]);class Ese extends hD{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(uB.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){var t;this._inspectMode=ar(t=e.map((e=>_se.get(e)||0))).call(t,((e,t)=>e+t)),this._inspectType=e}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this.qualityTimer&&(window.clearTimeout(this.qualityTimer),this.qualityTimer=null),this._quality>=1||(this.qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this.qualityRatio}),6e4))}constructor(e){super(),GA(this,"name","AgoraRTCVideoContentInspect"),GA(this,"_connectionState",dB.CONNECTING),GA(this,"_innerConnectionState",void 0),GA(this,"sequence",0),GA(this,"inspectStartTime",void 0),GA(this,"workerManagerConnection",void 0),GA(this,"workerConnection",void 0),GA(this,"workerMessageLengthLimit",void 0),GA(this,"inspectIntervalMinimum",void 0),GA(this,"qualityRatio",void 0),GA(this,"_connectInfo",void 0),GA(this,"_cancelTokenSource",QO.CancelToken.source()),GA(this,"_retryConfig",void 0),GA(this,"wmSequence",0),GA(this,"inspectInterval",void 0),GA(this,"inspectTimer",null),GA(this,"ossFilePrefix",void 0),GA(this,"extraInfo",void 0),GA(this,"_inspectType",void 0),GA(this,"_inspectMode",void 0),GA(this,"_quality",1),GA(this,"qualityTimer",null),GA(this,"_inspectId",void 0),GA(this,"_needWorkUrlOnly",!1),GA(this,"inspectImage",(()=>{if(this.connectionState!==dB.CONNECTED)throw new hk(JN.OPERATION_ABORTED,"content inspect service connection status is ".concat(this.connectionState));this.inspectTimer&&(window.clearInterval(this.inspectTimer),this.inspectTimer=null),this.inspectTimer=window.setInterval((()=>{this.connectionState===dB.CONNECTED?this.requestToInspectImage():FL.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)}),this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage()})),this._inspectId=eP(5,"inspect-"),this.workerMessageLengthLimit=rL("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=rL("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=rL("VIDEO_INSPECT_QUALITY_RATIO"),this.inspectInterval=e.interval,this.ossFilePrefix=e.ossFilePrefix,this.extraInfo=e.extraInfo,this.inspectType=e.inspectType,this.inspectStartTime=Number(Date.now()),this.workerManagerConnection=new xB("worker-manager-"+this._inspectId,mP),this.on(uB.STATE_CHANGE,((e,t)=>{this._innerConnectionState=e,FL.debug("[".concat(this._inspectId,"] Inspect operation :").concat(lB[e]," ").concat(t||""))})),this.handleWorkerManagerEvents(),this.workerConnection=new xB("worker-"+this._inspectId,mP),this.handleWorkerEvents()}async init(e,t){this.emit(uB.STATE_CHANGE,lB.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new dp(((i,r)=>{this.on(uB.CONNECTION_STATE_CHANGE,((e,t)=>{t===dB.CONNECTED&&i()})),this.requestAP(e,n,t).then((e=>{this.connectWorkerManager(e)})).catch((e=>{r(e)}))}))}async requestAP(e,t,n){const i=rL("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),r=await function(e,t,n,i){let r=t.appId,o=t.areaCode,s=t.cname,a=t.sid,c=t.token,d=t.uid;Cte++;const l="image_moderation_api",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:o,cname:s,command:"allocateEdge",requestId:Cte,seq:Cte,sid:a,token:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return gP((async()=>{h=Date.now();const e=await tte(_,{data:u,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-h,0!==e.code){const t=new hk(JN.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:p});throw FL.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new hk(JN.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw FL.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new hk(JN.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:p});throw FL.error(e.toString()),e}const i=rL("VIDEO_INSPECT_WORKER_MANAGER_WSS");if(i)return{addressList:[i],workerToken:t.workerToken,vid:t.vid,responseTime:p};const r=rL("VIDEO_INSPECT_WORKER_MANAGER_HOST"),o=rL("VIDEO_INSPECT_WORKER_MANAGER_PORT"),s=t.servers.map((e=>{let t=e.address,n=e.wss;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(r,":").concat(o||n)})).filter((e=>!!e));return{addressList:s,workerToken:t.workerToken,vid:t.vid,responseTime:p}}),((t,n)=>(uk.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:p,serverIp:e[n%e.length]}),!1)),((t,n)=>(uk.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[n%e.length]}),!!(t.code!==JN.OPERATION_ABORTED&&t.code!==JN.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(n+1)%e.length],!0))),i)}(i,e,t,n);this.emit(uB.STATE_CHANGE,lB.AP_CONNECTED);const o=r.addressList;return this.wmSequence++,o}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(uB.STATE_CHANGE,lB.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(wF.CONNECTED,(async()=>{this.emit(uB.STATE_CHANGE,lB.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.24.4",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:"join"}},!0)})),this.workerManagerConnection.on(wF.CLOSED,(()=>{this._innerConnectionState<lB.GET_WORKER_MANAGER_RESPONSE&&FL.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))})),this.workerManagerConnection.on(wF.FAILED,(()=>{this._innerConnectionState<lB.GET_WORKER_MANAGER_RESPONSE&&FL.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"))})),this.workerManagerConnection.on(wF.RECONNECTING,(()=>{this._innerConnectionState<lB.GET_WORKER_MANAGER_RESPONSE&&FL.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))})),this.workerManagerConnection.on(wF.ON_MESSAGE,(async e=>{this.emit(uB.STATE_CHANGE,lB.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const n=JSON.parse(e.data);if(200!==n.code)throw FL.error("[".concat(this._inspectId,"] Unexpected code ").concat(n.code," from worker manager")),new hk(JN.UNEXPECTED_RESPONSE,"response code of worker is unexpected",n);if(!(n.serverResponse&&n.serverResponse.portWss&&t))throw FL.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(n))),new hk(JN.UNEXPECTED_RESPONSE,"response content of worker is unexpected",n);{const e=rL("VIDEO_INSPECT_WORKER_PORT")||n.serverResponse.portWss,i=t.replace(/:\d+\/?$/,":".concat(e));this.emit(uB.STATE_CHANGE,lB.CONNECT_WORKER,i),this._needWorkUrlOnly?this.emit(uB.REQUEST_NEW_WORKER_URL,i):await this.connectWorker(i)}})),this.workerManagerConnection.on(wF.WILL_RECONNECT,((e,t,n)=>{n(e)})),this.workerManagerConnection.on(wF.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}handleWorkerEvents(){this.workerConnection.on(wF.CONNECTED,(async()=>{this.emit(uB.STATE_CHANGE,lB.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=dB.CONNECTED})),this.workerConnection.on(wF.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const n=joe(new Uint8Array(e.data));if(rL("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&FL.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(n)),200===n.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&"supervise"===this.inspectType[0])return void this.emit(uB.INSPECT_RESULT,void 0,void 0);if(n.data&&n.data.scorePorn&&n.data.scoreSexy&&n.data.scoreNeutral){var t;const e={porn:n.data.scorePorn,sexy:n.data.scoreSexy,neutral:n.data.scoreNeutral},i=ar(t=Object.keys(e)).call(t,((t,n)=>e[t]>e[n]?t:n),"porn"),r=Object.keys(e).find((e=>e===i));this.emit(uB.INSPECT_RESULT,r)}else this.emit(uB.INSPECT_RESULT,void 0,new hk(JN.UNEXPECTED_RESPONSE,n.code+"","There is an unexpected data on message"))}else this.emit(uB.INSPECT_RESULT,void 0,new hk(JN.UNEXPECTED_RESPONSE,n.code+"",n.msg))}else FL.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(uB.INSPECT_RESULT,void 0,new hk(JN.UNEXPECTED_RESPONSE,"invalid worker message type"))})),this.workerConnection.on(wF.CLOSED,(()=>{this.connectionState=dB.CLOSED})),this.workerConnection.on(wF.FAILED,(()=>{this.connectionState=dB.CLOSED})),this.workerConnection.on(wF.RECONNECTING,(()=>{this.connectionState=this.connectionState===dB.CONNECTED?dB.RECONNECTING:dB.CONNECTING})),this.workerConnection.on(wF.WILL_RECONNECT,((e,t,n)=>{"recover"===e&&n(e),n("tryNext")})),this.workerConnection.on(wF.REQUEST_NEW_URLS,((e,t)=>{this.workerManagerConnection.close(),this.once(uB.REQUEST_NEW_WORKER_URL,(t=>{e([t])})),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then((e=>{this.connectWorkerManager(e,!0)})).catch((e=>{t(e)}))}))}async requestToInspectImage(){this.sequence++;const e=DD(this,uB.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void this.emit(uB.INSPECT_RESULT,void 0,new hk(JN.INVALID_OPERATION,"Only the track being played can be inspected"));const n=await this.generateRequestData(e,t);this.workerConnection.sendMessage(n,!0,!0)}else this.emit(uB.INSPECT_RESULT,void 0,new hk(JN.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(e,t){let n=t.appId,i=t.cname,r=t.cid,o=t.vid,s=t.sid,a=t.uid;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await iU(d,n,i),u=this.sequence+"-"+r+"-"+a+"-"+c+"-"+eP(12,""),h={appId:n,cid:r,cname:i,deviceId:"",elapse:(p=Number(c-this.inspectStartTime),{low:p|=0,high:p>>31,unsigned:p>=0}),fileSize:l.byteLength,jpgEncryption:2,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:"4.24.4",sequence:this.sequence,sid:s,timestamp:Sre(c),uid:a,vid:o,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};var p;void 0===this.extraInfo&&delete h.callbackData,void 0===this.ossFilePrefix&&delete h.ossFilePrefix;const _=Boe(h);if(_.byteLength<this.workerMessageLengthLimit){if(rL("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){const e=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?pse(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):pse(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},h);delete e.jpg,FL.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(e))}return _}{const t=this.quality*this.qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:n,cname:i,cid:r,vid:o,sid:s,uid:a})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=QO.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=dB.CLOSED,this.emit(uB.STATE_CHANGE,lB.CLOSED)}}const mse={name:"ContentInspect",create:function(e){let t=e.config;return function(e){if(!e)throw new hk(JN.INVALID_PARAMS,"inspectConfig is necessary.");if(!e.inspectType||!Array.isArray(e.inspectType))throw new hk(JN.INVALID_PARAMS,"inspectConfig.inspectType is necessary and is an instance of Array.");{const t=[...new Set(e.inspectType)];t.forEach((e=>{var t;if(!Vi(t=["supervise","moderation"]).call(t,e))throw new hk(JN.INVALID_PARAMS,"".concat(e," is not a valid inspect type."))})),e.inspectType=t}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new hk(JN.INVALID_PARAMS,"inspectConfig.extraInfo length cannot exceed 1024 bytes")}(t),new Ese(t)}};var fse=n($.Object.getOwnPropertySymbols),gse=Nn,Sse=zn.indexOf,Tse=Xi,Rse=b([].indexOf),vse=!!Rse&&1/Rse([1],1,-0)<0;gse({target:"Array",proto:!0,forced:vse||!Tse("indexOf")},{indexOf:function(e){var t=arguments.length>1?arguments[1]:void 0;return vse?Rse(this,e,t)||0:Sse(this,e,t)}});var yse=ii("Array","indexOf"),bse=l,Cse=yse,Ise=Array.prototype,Ase=function(e){var t=e.indexOf;return e===Ise||bse(Ise,e)&&t===Ise.indexOf?Cse:t},wse=n(Ase);function Ose(e,t){if(null==e)return{};var n,i,r=function(e,t){if(null==e)return{};var n={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==wse(t).call(t,i))continue;n[i]=e[i]}return n}(e,t);if(fse){var o=fse(e);for(i=0;i<o.length;i++)n=o[i],-1===wse(t).call(t,n)&&{}.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}let Nse=class{get localCapabilities(){return GD(this._localCapabilities)}get rtpCapabilities(){return GD(this._rtpCapabilities)}get candidates(){return GD(this._candidates)}get iceParameters(){return GD(this._iceParameters)}get dtlsParameters(){return GD(this._dtlsParameters)}constructor(e){GA(this,"sessionDesc",void 0),GA(this,"_localCapabilities",void 0),GA(this,"_rtpCapabilities",void 0),GA(this,"_candidates",void 0),GA(this,"_iceParameters",void 0),GA(this,"_dtlsParameters",void 0),GA(this,"setup",void 0),GA(this,"currentMidIndex",void 0),GA(this,"cname","o/i14u9pJrxRKAsu"),GA(this,"firefoxSsrcMidMap",new Map);const t=e=GD(e),n=t.remoteIceParameters,i=t.remoteDtlsParameters,r=t.candidates,o=t.remoteRTPCapabilities,s=t.localCapabilities,a=t.direction,c=t.setup,d=t.videoCodec,l=t.audioCodec;let u;this.setup=c,u=a===AF.RECEIVE_ONLY?EL("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=extmap-allow-mixed\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n"):EL("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=extmap-allow-mixed\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=recvonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=recvonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n"),this._rtpCapabilities=o,this._candidates=r,this._iceParameters=n,this._dtlsParameters=i,this._localCapabilities=s;const h=a===AF.RECEIVE_ONLY?this.rtpCapabilities.send:this.rtpCapabilities.recv,p=a===AF.RECEIVE_ONLY?this._localCapabilities.recv:this._localCapabilities.send,_=a===AF.RECEIVE_ONLY?o.send.videoCodecs:kee(nB.VIDEO,h,p,d),E=a===AF.RECEIVE_ONLY?o.send.audioCodecs:kee(nB.AUDIO,h,p,l);for(const e of u.mediaDescriptions)e.attributes.iceUfrag=n.iceUfrag,e.attributes.icePwd=n.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=r,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType&&(e.media.fmts=_.map((e=>e.payloadType.toString(10))),e.attributes.payloads=_,e.attributes.extmaps=h.videoExtensions),"audio"===e.media.mediaType&&(e.media.fmts=E.map((e=>e.payloadType.toString(10))),e.attributes.payloads=E,e.attributes.extmaps=h.audioExtensions,Lee(e));this.sessionDesc=u,this.currentMidIndex=u.mediaDescriptions.length-1}toString(){return mL(this.sessionDesc)}hasMid(e){return Array.isArray(e)?e.every((e=>this.hasMid(e))):this.sessionDesc.mediaDescriptions.some((t=>t.attributes.mid===e))}send(e,t,n,i,r){n=n.replace(/ /g,"-");const o=Ree(t,this.cname,rL("SYNC_GROUP")?n:void 0),s=o.ssrcs,a=o.ssrcGroups,c=this.findPreloadMediaDesc(s);if(c){if(SN()&&this.firefoxSsrcMidMap.set(s[0].ssrcId,c.attributes.mid),r&&(r.twcc||r.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(c);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(c,r),{mid:c.attributes.mid,needExchangeSDP:!0}}return{mid:c.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,s,i);let n;return-1===t?(n=this.createOrRecycleSendMedia(e,s,a,"sendonly",i,r),this.updateBundleMids()):(n=GD(this.sessionDesc.mediaDescriptions[t]),n.attributes.direction="sendonly",n.attributes.ssrcs=s,n.attributes.ssrcGroups=a,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(n,r)),SN()&&this.firefoxSsrcMidMap.set(s[0].ssrcId,n.attributes.mid),{needExchangeSDP:!0,mid:n.attributes.mid}}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach((e=>{e.attributes.ssrcs=[]})),this.updateBundleMids()}receive(e,t,n){const i=[];return e.forEach((e=>{const r=e._mediaStreamTrack.kind,o=this.findAvailableRecvMediaIndex(r);let s,a=!1;-1===o?(a=!0,s=this.createOrRecycleRecvMedia(e,[],"recvonly",t,n),this.updateBundleMids()):(s=GD(this.sessionDesc.mediaDescriptions[o]),s.attributes.direction="recvonly"),i.push({mid:s.attributes.mid,needCreateTransceiver:a})})),i}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach((e=>{e.media.port="0",e.attributes.direction="inactive"})),this.updateBundleMids()}addRemoteCandidate(e){const t=new RTCIceCandidate(e),n=t.foundation,i=t.protocol,r=t.address,o=t.port,s=t.type,a=t.relatedAddress,c=t.relatedPort,d=t.priority,l={foundation:null!=n?n:"",componentId:"1",transport:null!=i?i:"",priority:d?d+"":"",connectionAddress:null!=r?r:"",port:o?o+"":"",type:s?s+"":"",relAddr:null!=a?a:"",relPort:c?c+"":"",extension:{}};this.candidates.some((e=>e.priority===l.priority&&e.connectionAddress===l.connectionAddress&&e.port===l.port))||(this._candidates.push(l),this.sessionDesc.mediaDescriptions.forEach((e=>{e.attributes.candidates=this.candidates})))}clearRemoteCandidate(){this._candidates=[],this.sessionDesc.mediaDescriptions[0].attributes.candidates=this._candidates}createOrRecycleRecvMedia(e,t,n,i,r){const o=e._mediaStreamTrack.kind,s=this.rtpCapabilities.recv,a=kee(o,s,this.localCapabilities.send,o===nB.AUDIO?r:i),c=o===nB.VIDEO?s.videoExtensions:s.audioExtensions,d="".concat(++this.currentMidIndex);let l={media:{mediaType:o,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};l=this.mungRecvMediaDsec(l,e);const u=this.findFirstClosedMedia(o);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Vi(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="inactive"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Vi(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="recvonly"}))}findAvailableMediaIndex(e,t,n){return this.sessionDesc.mediaDescriptions.findIndex((i=>{const r=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(SN()){if(r){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||"0"!==i.attributes.mid&&"1"!==i.attributes.mid)||!(!e||e!==i.attributes.mid)}return!1}return r&&i.attributes.mid===n}))}findAvailableRecvMediaIndex(e){return this.sessionDesc.mediaDescriptions.findIndex((t=>{const n=t.media.mediaType===e&&"0"!==t.media.port&&("recvonly"===t.attributes.direction||"sendrecv"===t.attributes.direction);return"0"!==t.attributes.mid&&"1"!==t.attributes.mid&&n}))}predictReceivingMids(e){const t=[];for(let n=0;n<e;n++)t.push((this.currentMidIndex+n+1).toString(10));return t}restartICE(e){e=GD(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}createOrRecycleSendMedia(e,t,n,i,r,o){const s=this.rtpCapabilities.send,a=e===nB.VIDEO?s.videoCodecs:s.audioCodecs,c=e===nB.VIDEO?s.videoExtensions:s.audioExtensions;SN()&&(r="".concat(++this.currentMidIndex));let d={media:{mediaType:e,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:n,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:r}};d=this.mungSendMediaDesc(d,o);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}mungRecvMediaDsec(e,t,n){const i=GD(e);return yee(i),vee(i,t),bee(i,t),Cee(i),Iee(i,n,this.localCapabilities.send),i}mungSendMediaDesc(e,t){const n=GD(e);return Iee(n,t,this.localCapabilities.recv),Lee(n),n}updateRecvMedia(e,t){const n=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==n){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],t);this.sessionDesc.mediaDescriptions[n]=e}}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>"0"!==e.media.port)).map((e=>e.attributes.mid))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var n;return(null===(n=t.attributes)||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId)===e[0].ssrcId}))}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>SN()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}};const Dse=["sdp"];var Pse;function Lse(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function kse(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Lse(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Lse(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let Mse=(Pse=class e extends eB{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!==(e=null===(t=this.peerConnection.getReceivers()[0])||void 0===t||null===(t=t.transport)||void 0===t?void 0:t.state)&&void 0!==e?e:null}get localCodecs(){return[]}set isInRestartIce(e){this._isInRestartIce=e}get isInRestartIce(){return this._isInRestartIce}constructor(t,n,i){super(t,n),GA(this,"direction",void 0),GA(this,"name",void 0),GA(this,"store",void 0),GA(this,"spec",void 0),GA(this,"peerConnection",void 0),GA(this,"initialOffer",void 0),GA(this,"transport",void 0),GA(this,"statsFilter",void 0),GA(this,"localCandidateCount",0),GA(this,"_isInRestartIce",!1),GA(this,"mutex",void 0),GA(this,"onLocalCandidate",void 0),GA(this,"remoteSDP",void 0),GA(this,"pendingCandidates",[]),GA(this,"localCapabilities",void 0),GA(this,"isReady",!1),GA(this,"restartCnt",0),GA(this,"curTurnServerIndex",0),this.store=n,this.spec=t,this.mutex=new _P("P2PConnection-mutex",n.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t,n.p2pTransport),{optional:[{googDscp:!0}]}),this.direction=null!=i?i:AF.SEND_ONLY,this.name=this.direction===AF.SEND_ONLY?"sendP2PConnection":"recvP2PConnection",this.statsFilter=HP(this.peerConnection,rL("STATS_UPDATE_INTERVAL"),void 0,SN()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1}async establish(e){try{const t=await Oee();if(this.localCapabilities=Pee(t),e){const t=e.sdp,n=Ose(e,Dse),i=function(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=Eee(arguments.length>2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},"sendonly"),n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Dee(t,e,"videoExtensions",n,i,r),Dee(t,e,"videoCodecs",n,i,r),Dee(t,e,"audioExtensions",n,i,r),Dee(t,e,"audioCodecs",n,i,r),rL("RAISE_H264_BASELINE_PRIORITY")){const e=r.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"===e.fmtp.parameters["profile-level-id"]));if(-1!==e){const t=r.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()));if(t<e){FL.debug("raising H264 baseline profile priority");const n=r.videoCodecs[e];r.videoCodecs.splice(e,1),r.videoCodecs.splice(t,0,n)}-1!==t&&rL("FILTER_SEND_H264_BASELINE")&&(n.videoCodecs=n.videoCodecs.filter((e=>!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"]))))}}return{send:n,recv:i,sendrecv:r}}({},{},t);this.remoteSDP=new Nse({remoteIceParameters:n.iceParameters,remoteDtlsParameters:n.dtlsParameters,candidates:[],remoteRTPCapabilities:i,localCapabilities:this.localCapabilities,direction:this.direction,setup:"actpass",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()}),this.isReady=!0;const r=await this.peerConnection.createAnswer();if(!r.sdp)throw new Error("Cannot get answer sdp when trying to establish PeerConnection.");const o=mee(r.sdp);await this.peerConnection.setLocalDescription(r);const s=await Nee({},{},r.sdp);this.localCapabilities=Pee(s);const a=this.peerConnection.getTransceivers()[0];return null!=a&&a.receiver&&a.receiver.transport&&this.tryBindTransportEvents(a.receiver.transport),kse(kse({},o),{},{sdp:r.sdp})}{this.peerConnection.addTransceiver("video",{direction:"sendonly"}),this.peerConnection.addTransceiver("audio",{direction:"sendonly"});const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=mee(e.sdp);return this.initialOffer=e,kse(kse({},t),{},{sdp:e.sdp})}}catch(e){throw new zN(JN.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");await this.peerConnection.setLocalDescription(this.initialOffer);const t=e.sdp,n=e.iceParameters,i=e.dtlsParameters,r=await Nee({},{},t);this.remoteSDP=new Nse({remoteIceParameters:n,remoteDtlsParameters:i,candidates:[],remoteRTPCapabilities:r,localCapabilities:this.localCapabilities,direction:this.direction,setup:"active",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()});const o=this.peerConnection.getTransceivers()[0];null!=o&&o.sender&&o.sender.transport&&this.tryBindTransportEvents(o.sender.transport)}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async addRemoteCandidate(e){try{e&&this.pendingCandidates.push(e),this.peerConnection.remoteDescription&&this.isReady&&(this.pendingCandidates.forEach((e=>{this.peerConnection.addIceCandidate(e)})),this.pendingCandidates=[])}catch(e){throw new zN(JN.ADD_CANDIDATE_FAILED,"P2PConnection.addRemoteCandidate failed; ".concat(e.toString()))}}send(e,t,n){var i=this;return mO((function*(){const r=yield gO(i.mutex.lock("From P2PConnection.send"));try{if(!i.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=[],s=i.remoteSDP.receive(e,t,n);e.forEach(((e,t)=>{if(s[t].needCreateTransceiver){const t=i.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});o.push(t),e._updateRtpTransceiver(t)}else{const n=i.peerConnection.getTransceivers().find((e=>e.mid===s[t].mid));if(!n)throw new Error("cannot find transceiver when sendPeerconnection send, mid is ".concat(s[t].mid));o.push(n),e._updateRtpTransceiver(n)}})),SN()&&!0===rL("SIMULCAST")&&(yield gO(i.applySimulcastForFirefox(o,e)));const a=s.map((e=>e.mid)),c=yield gO(i.peerConnection.createOffer()),d=i.mungSendOfferSDP(c.sdp,e,a),l=EL(d),u=a.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return fee(t,rL("USE_PUB_RTX"))})),h=o.map(((e,t)=>{const n=a[t];return{localSSRC:u[t],id:n}}));yield gO(i.peerConnection.setLocalDescription({type:"offer",sdp:d}));try{yield h}catch(e){const t=i.remoteSDP.toString();throw yield gO(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield gO(i.peerConnection.setRemoteDescription({type:"answer",sdp:t})),yield gO(i.stopSending(a,!0)),e}yield gO(i.applySimulcastEncodings(o,e)),yield gO(i.applySendEncodings(o,e));const p=i.remoteSDP.toString(),_=i.logSDPExchange(d,"offer","local","send");return null==_||_(p),yield gO(i.setRemoteDescription({type:"answer",sdp:p})),o.map(((e,t)=>{const n=a[t];return{localSSRC:u[t],id:n}}))}catch(e){throw e instanceof zN?e:new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{r()}}))()}async stopSending(e,t){const n=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length (".concat(t.length,") doesn't match mids' length (").concat(e.length,") when trying to call P2PConnection.stopSending."));t.map((e=>{var t;e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==r||r(o),await this.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{n&&n()}}async receive(e,t,n,i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const r=this.remoteSDP.send(e,t,n,i),o=r.mid;if(r.needExchangeSDP){const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer(),r=this.mungReceiveAnswerSDP(i.sdp,o,e);null==n||n(r||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:r}),FL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else FL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));const s=this.peerConnection.getTransceivers().find((e=>e.mid===o));if(!s||null===s.mid)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:s.receiver.track,mid:s.mid,transceiver:s}}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async mockReceive(e,t,n,i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const r=this.remoteSDP.send(e,t,n,i),o=r.mid;if(r.needExchangeSDP){const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer(),r=this.mungReceiveAnswerSDP(i.sdp,o,e);null==n||n(r||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:r}),FL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else FL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."))}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async restartICE(t){try{if(this.store.p2pTransport===ZP.Auto&&(this.store.p2pTransport=ZP.SdRtn,_k().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport))),this.restartCnt>3&&(this.restartCnt=0,_k().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport,++this.curTurnServerIndex))),!t){this.restartCnt++,this.isReady=!1;const e=await this.peerConnection.createOffer({iceRestart:!0});if(!e.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const t=mee(e.sdp).iceParameters;return this.store.descriptionStart(),this.direction===AF.SEND_ONLY&&await this.peerConnection.setLocalDescription(e),t}if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");if(this.remoteSDP.restartICE(t),this.store.descriptionStart(),this.direction===AF.RECEIVE_ONLY){this.restartCnt++,await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()});const e=await this.peerConnection.createAnswer();if(!e.sdp)throw new Error("Cannot get answer sdp when trying to iceRestart.");const t=mee(e.sdp).iceParameters;return await this.peerConnection.setLocalDescription(e),t}await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()}),this.isReady=!0}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}close(){var e;this.peerConnection.close(),this.peerConnection.onicecandidate=null,null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.transport=void 0,this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const n=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(n.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(i,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const n=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===n.length&&(this.isVP8Simulcast(t)?SN()||await this.applySimulcastEncodings(n,[t]):await this.applySendEncodings(n,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const n=this.peerConnection.getTransceivers().find((e=>e.mid===t));n&&await n.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport.getSelectedCandidatePair(),n=t.local,i=t.remote;return{local:kse(kse({},OP),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port}),remote:kse(kse({},OP),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e,t;Vi(e=["connected","completed"]).call(e,this.peerConnection.iceConnectionState)&&(this.isReady=!1),null===(t=this.onICEConnectionStateChange)||void 0===t||t.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.restartCnt=0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.startICECandidate()}startICECandidate(){this.peerConnection.onicecandidate||(this.localCandidateCount=0,this.peerConnection.onicecandidate=e=>{if(e.candidate){var t;if(e.candidate.candidate)null===(t=this.onLocalCandidate)||void 0===t||t.call(this,e.candidate.toJSON());this.localCandidateCount+=1}else FL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount)})}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const r={iceServers:[]};var o;t.iceServers?r.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(TD(t.turnServer.servers)?r.iceServers=t.turnServer.servers:(r.iceServers&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers,n,i)),rL("USE_TURN_SERVER_OF_GATEWAY")&&r.iceServers&&t.turnServer.serversFromGateway&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway,n,i)),Vi(o=[ZP.Relay,ZP.SdRtn]).call(o,n)&&(r.iceTransportPolicy="relay"),rL("FORCE_TURN_TCP")?r.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(r.iceTransportPolicy="relay")}))));return rL("ENABLE_ENCODED_TRANSFORM")&&_k().supportWebRTCEncodedTransform&&(r.encodedInsertableStreams=!0),FL.debug("P2PConnection p2pTransport is ".concat(n)),r}static turnServerConfigToIceServers(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const i=[],r=e.filter((e=>e.tcpport));FL.debug("P2PConnection turnServers is ".concat(r,", current index is ").concat(n));const o=r.length>n?r[n]:r[0];switch(t){case ZP.SdRtn:const t=e.filter((e=>{var t;return Vi(t=e.username).call(t,"glb:")&&e.turnServerURL==e.turnServerURL})),r=t.length>n?t[n]:t[0];r&&(i.push({username:r.username,credential:r.password,credentialType:"password",urls:"turn:".concat(X7(r.turnServerURL),":").concat(r.tcpport,"?transport=udp")}),i.push({username:r.username,credential:r.password,credentialType:"password",urls:"turns:".concat(X7(r.turnServerURL),":").concat(r.tcpport,"?transport=tcp")}));break;case ZP.Relay:o&&(i.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=udp")}),i.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(X7(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}));break;default:o&&(i.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=udp")}),i.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(X7(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}),i.push({username:o.username,credential:o.password,credentialType:"password",urls:"stun:".concat(o.turnServerURL,":").concat(o.tcpport)}))}return i}tryBindTransportEvents(e){if(e){this.transport=e,e.onstatechange=()=>{var t;null!=e&&e.state&&(null===(t=this.onDTLSTransportStateChange)||void 0===t||t.call(this,e.state))},e.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const t=e.iceTransport;t&&(t.onstatechange=()=>{const t=null==e?void 0:e.iceTransport.state;var n;t&&(null===(n=this.onICETransportStateChange)||void 0===n||n.call(this,t))},t.getSelectedCandidatePair&&(t.onselectedcandidatepairchange=()=>{if(t.getSelectedCandidatePair()){const e=t.getSelectedCandidatePair()||{},n=e.local,i=e.remote;if(n&&i){const e=n.address+":"+n.port,t=i.address+":"+i.port;FL.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(iee(e)),", remote ").concat(JSON.stringify(iee(t))))}}}))}}tryUnbindTransportEvents(){this.transport&&(this.transport.onstatechange=null,this.transport.onerror=null,this.transport.iceTransport&&(this.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var n;if(!t){t=this.peerConnection.getSenders().find((t=>t.track===e._mediaStreamTrack))}if(!t)return FL.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return FL.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!_k().supportSetRtpSenderParameters)return FL.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const i={},r={};switch(e._optimizationMode){case"motion":i.degradationPreference="maintain-framerate";break;case"detail":i.degradationPreference="maintain-resolution";break;default:i.degradationPreference="balanced"}if(e._encoderConfig){var o;const t=e._encoderConfig,n=t.bitrateMax,i=t.frameRate,s=t.scaleResolutionDownBy;n&&(r.maxBitrate=1e3*n),Vi(o=e._hints).call(o,jk.LOW_STREAM)&&(i&&(r.maxFramerate=Z7(i)),s&&s>=1&&(r.scaleResolutionDownBy=s))}if(rL("DSCP_TYPE")&&FN()){var s;const e=rL("DSCP_TYPE");Vi(s=["very-low","low","medium","high"]).call(s,e)&&(r.networkPriority=e)}const a=t.getParameters(),c=null===(n=a.encodings)||void 0===n?void 0:n[0];SN()&&!c&&(i.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,i),FL.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),await t.setParameters(a)}async applySendEncodings(e,t){try{if(!_k().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let n=0;n<e.length;n++){const i=e[n],r=t[n];r instanceof BV&&!this.isVP8Simulcast(r)&&await this.updateRtpSenderEncodings(r,i.sender)}}catch(e){FL.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,n){const i=EL(e);return t.forEach(((e,t)=>{const r=n[t],o=i.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(vee(o,e),Aee(o,e,this.store.codec))})),mL(i)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,n)=>{var i;null===(i=this.onFirstVideoDecoded)||void 0===i||i.call(this,e,t,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedLocalCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a<e.length;a++){var n,i,r,o,s;const c=e[a],d=t[a];if(d instanceof BV&&!Vi(n=d._hints).call(n,jk.LOW_STREAM)&&null!==(i=d._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(r=d._encoderConfig)||void 0===r?void 0:r.bitrateMax)>200&&null!==(o=d._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(s=d._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const n=c.sender.getParameters();await c.sender.setParameters(Object.assign(n,e))}}}async applySimulcastEncodings(e,t){if(!SN()&&e.length===t.length)for(let n=0;n<e.length;n++){const i=t[n];if(i instanceof BV&&this.isVP8Simulcast(i)){const t=e[n],r={},o={high:1e3*(i._encoderConfig.bitrateMax-50),medium:5e4};r.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:o.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:o.medium,scaleResolutionDownBy:4}];const s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,r))}}}isVP8Simulcast(e){var t,n,i,r,o;return!!(e instanceof BV&&rL("SIMULCAST")&&"vp8"===this.store.codec&&!Vi(t=e._hints).call(t,jk.LOW_STREAM)&&null!==(n=e._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(i=e._encoderConfig)||void 0===i?void 0:i.bitrateMax)>200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(o=e._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,n,i){if(rL("SDP_LOGGING"))return FL.upload("[".concat(this.store.clientId,"] exchanging ").concat(n," ").concat(t," SDP during P2PConnection.").concat(i,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===n?"remote":"local",i)}:void 0}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==i||i(r),await this.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((async e=>{e.direction="sendonly"}));const n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==i||i(r),await this.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}async getRemoteSSRC(e,t){var n;if(t=null!=t?t:null===(n=this.currentRemoteDescription)||void 0===n?void 0:n.sdp){var i;const n=null===(i=EL(t).mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===i?void 0:i.attributes.ssrcs;return null==n?void 0:n[0].ssrcId}}async setRemoteDescription(e){var t;await this.peerConnection.setRemoteDescription(e),Vi(t=["connected","completed"]).call(t,this.peerConnection.iceConnectionState)||(this.isReady=!0,this.addRemoteCandidate())}mungReceiveAnswerSDP(e,t,n){const i=EL(e),r=i.mediaDescriptions.find((e=>e.attributes.mid===t));return r&&n===nB.AUDIO&&"audio"===r.media.mediaType&&Lee(r),mL(i)}},mF(Pse.prototype,"establish",[Use],Object.getOwnPropertyDescriptor(Pse.prototype,"establish"),Pse.prototype),mF(Pse.prototype,"connect",[Use],Object.getOwnPropertyDescriptor(Pse.prototype,"connect"),Pse.prototype),mF(Pse.prototype,"receive",[Use],Object.getOwnPropertyDescriptor(Pse.prototype,"receive"),Pse.prototype),mF(Pse.prototype,"mockReceive",[Use],Object.getOwnPropertyDescriptor(Pse.prototype,"mockReceive"),Pse.prototype),mF(Pse.prototype,"stopReceiving",[Use],Object.getOwnPropertyDescriptor(Pse.prototype,"stopReceiving"),Pse.prototype),mF(Pse.prototype,"restartICE",[Use],Object.getOwnPropertyDescriptor(Pse.prototype,"restartICE"),Pse.prototype),mF(Pse.prototype,"close",[Use],Object.getOwnPropertyDescriptor(Pse.prototype,"close"),Pse.prototype),mF(Pse.prototype,"updateEncoderConfig",[Use],Object.getOwnPropertyDescriptor(Pse.prototype,"updateEncoderConfig"),Pse.prototype),mF(Pse.prototype,"updateSendParameters",[Use],Object.getOwnPropertyDescriptor(Pse.prototype,"updateSendParameters"),Pse.prototype),mF(Pse.prototype,"replaceTrack",[Use],Object.getOwnPropertyDescriptor(Pse.prototype,"replaceTrack"),Pse.prototype),mF(Pse.prototype,"muteLocal",[Use],Object.getOwnPropertyDescriptor(Pse.prototype,"muteLocal"),Pse.prototype),mF(Pse.prototype,"unmuteLocal",[Use],Object.getOwnPropertyDescriptor(Pse.prototype,"unmuteLocal"),Pse.prototype),Pse);function Use(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=await e.lock("From P2PConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await i.apply(this,o)}finally{n()}},n}let Vse=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({});var xse,Fse,Bse,jse,Gse,Wse,Kse,Hse,Yse,Xse,Jse,zse;function Zse(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function qse(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Zse(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Zse(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let Qse=(xse=$se(Vse.SEND_ONLY),Fse=$se(Vse.SEND_ONLY),Bse=$se(),jse=$se(Vse.RECEIVE_ONLY),Gse=$se(Vse.RECEIVE_ONLY),Wse=$se(Vse.RECEIVE_ONLY),Kse=$se(Vse.RECEIVE_ONLY),Hse=$se(Vse.RECEIVE_ONLY),Yse=$se(Vse.RECEIVE_ONLY),Xse=$se(),Jse=$se(Vse.RECEIVE_ONLY),zse=class extends hD{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(cB.StateChange,t,this._state)}constructor(e,t){super(),GA(this,"isPlanB",!1),GA(this,"store",void 0),GA(this,"statsUploader",void 0),GA(this,"sendConnection",void 0),GA(this,"recvConnection",void 0),GA(this,"localTrackMap",new Map),GA(this,"remoteUserMap",new Map),GA(this,"localDataChannels",[]),GA(this,"pendingLocalTracks",[]),GA(this,"pendingRemoteTracks",[]),GA(this,"statsCollector",void 0),GA(this,"dtlsFailedCount",0),GA(this,"sendMutex",void 0),GA(this,"recvMutex",void 0),GA(this,"_state",aB.Disconnected),GA(this,"_restartStates",["disconnected","failed"]),GA(this,"reconnectInterval",void 0),GA(this,"uploadUnplinkStarted",!1),GA(this,"uploadDownlinkStarted",!1),GA(this,"uplinkStateUploadInterval",void 0),GA(this,"downlinkStatsUploadInterval",void 0),GA(this,"handleMuteLocalTrack",(async(e,t,n)=>{const i=await this.sendMutex.lock("Locking from P2PChannel2.handleMuteLocalTrack");try{if(!this.sendConnection||this.state!==aB.Connected)return void n(new zN(JN.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established."));const s=this.filterTobeMutedTracks(e);if(0===s.length)return void t();const a=s.find((e=>"videoLowTrack"===e[0]));if(a){a[1].track._originMediaStreamTrack.stop()}await this.sendConnection.muteLocal(s.map((e=>Hb(e,2)[1].id)));let c=!1;var r,o;if("video"===e.trackMediaType)c=!(null===(r=this.localTrackMap.get(sB.LocalAudioTrack))||void 0===r||!r.track._muted);else c=void 0===(null===(o=this.localTrackMap.get(sB.LocalVideoTrack))||void 0===o?void 0:o.id);const d=this.createMuteMessage(s);await ND(this,cB.RequestMuteLocal,d);const l="video"===e.trackMediaType?TB.MUTE_LOCAL_VIDEO:TB.MUTE_LOCAL_AUDIO;await ND(this,cB.RequestP2PMuteLocal,{action:l,message:d,isMuteAll:c}),t()}catch(e){n(e)}finally{i()}})),GA(this,"handleUnmuteLocalTrack",(async(e,t,n)=>{const i=await this.sendMutex.lock("Locking from P2PChannel2.handleUnmuteLocalTrack");try{if(!this.sendConnection||this.state!==aB.Connected)return void n(new zN(JN.INVALID_OPERATION,"Cannot call P2PChannel2.handleUnmuteLocalTrack before sendConnection established."));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();await this.sendConnection.unmuteLocal(r.map((e=>Hb(e,2)[1].id)));const o=this.createUnmuteMessage(r),s="video"===e.trackMediaType?TB.UNMUTE_LOCAL_VIDEO:TB.UNMUTE_LOCAL_AUDIO;await ND(this,cB.RequestP2PMuteLocal,{action:s,message:o}),t()}catch(e){n(e)}finally{i()}})),GA(this,"handleUpdateVideoEncoder",(async(e,t,n,i)=>{let r;"boolean"==typeof i&&i||(r=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoEncoder"));try{const n=this.localTrackMap.get(sB.LocalVideoTrack);if(!this.sendConnection||!n||n.track!==e||this.state!==aB.Connected)return void t();const i=n.id,s=n.track;i&&(await this.sendConnection.updateSendParameters(i,s),await this.sendConnection.updateEncoderConfig(i,s),this.emit(cB.UpdateVideoEncoder,s)),t()}catch(e){n(e)}finally{var o;null===(o=r)||void 0===o||o()}})),GA(this,"handleUpdateVideoSendParameters",(async(e,t,n)=>{const i=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoSendParameters");try{const n=this.localTrackMap.get(sB.LocalVideoTrack);if(!this.sendConnection||!n||n.track!==e||this.state!==aB.Connected)return void t();const r=n.id,o=n.track;r&&await this.sendConnection.updateSendParameters(r,o),t()}catch(e){n(e)}finally{i()}})),GA(this,"handleReplaceTrack",(async(e,t,n,i)=>{let r;FL.debug("[".concat(this.store.clientId,"] P2PChannel2 handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof i&&i||(r=await this.sendMutex.lock("From P2PChannel2.handleReplaceTrack"));try{var o;const n=Array.from(this.localTrackMap.entries()).find((t=>{let n=Hb(t,2)[1].track;return e===n}));if(!this.sendConnection||!n||void 0===n[1].id||this.state!==aB.Connected)return void t();if(await(null===(o=this.sendConnection)||void 0===o?void 0:o.replaceTrack(e,n[1].id)),n[0]===sB.LocalVideoTrack&&_k().supportDualStreamEncoding){const t=this.localTrackMap.get(sB.LocalVideoLowTrack);if(t){const n=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=n,t.track._originMediaStreamTrack=n,await new dp(((e,n)=>{this.handleReplaceTrack(t.track,e,n,!0)}))}}t()}catch(e){n(e)}finally{var s;null===(s=r)||void 0===s||s()}})),GA(this,"handleGetLocalVideoStats",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),GA(this,"handleGetLocalAudioStats",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),GA(this,"handleGetRemoteVideoStats",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),GA(this,"handleGetRemoteAudioStats",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new Xne(e),this.bindStatsUploaderEvents(),this.sendMutex=new _P("P2PChannel2-send-mutex",e.clientId),this.recvMutex=new _P("P2PChannel2-recv-mutex",e.clientId),this.reconnectInterval=window.setInterval((()=>{[this.sendConnection,this.recvConnection].forEach((e=>{e&&("disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction))}))}),rL("ICE_RESTART_INTERVAL"))}async startP2PConnection(e,t){throw new zN(JN.NOT_SUPPORTED,"p2p mode does not support startP2PConnection.")}async connect(e){throw new zN(JN.NOT_SUPPORTED,"p2p mode does not support connect.")}async startP2P(e,t){let n;try{if(t){this.recvConnection&&(FL.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset recvConnection.")),this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection)),n=await this.recvMutex.lock("From P2PChannel.startP2P"),this.recvConnection=new Mse(e,this.store,AF.RECEIVE_ONLY),this.bindConnectionEvents(this.recvConnection);const i=await this.recvConnection.establish(t);return{iceParameters:i.iceParameters,dtlsParameters:i.dtlsParameters,sdp:i.sdp}}{this.state=aB.New,this.sendConnection&&(FL.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset sendConnection.")),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection)),n=await this.sendMutex.lock("From P2PChannel.startP2P"),this.sendConnection=new Mse(e,this.store),this.store.peerConnectionStart(),this.bindConnectionEvents(this.sendConnection);const t=await this.sendConnection.establish();return{iceParameters:t.iceParameters,dtlsParameters:t.dtlsParameters,sdp:t.sdp}}}finally{n&&n()}}async p2pConnect(e){if(!this.sendConnection)throw new zN(JN.UNEXPECTED_ERROR,"Cannot P2PChannel2.p2pConnect before P2PChannel2.startP2PConnection .");this.store.peerConnectionStart(),await this.sendConnection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=aB.Connected}async addRemoteCandidate(e,t){if(t===AF.RECEIVE_ONLY){if(!this.sendConnection)throw new zN(JN.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.sendConnection.addRemoteCandidate(e)}else{if(!this.recvConnection)throw new zN(JN.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.recvConnection.addRemoteCandidate(e)}}publish(e,t,n){var i=this;return mO((function*(){const r=yield gO(i.sendMutex.lock("From P2PChannel.publish"));try{if(!i.sendConnection||i.state!==aB.Connected){i.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===i.pendingLocalTracks.indexOf(e)));return void(i.pendingLocalTracks=i.pendingLocalTracks.concat(t))}i.store.pubId=i.store.pubId+1,Hte.markPublishStart(i.store.clientId,i.store.pubId);const o=i.filterTobePublishedTracks(e,t,n);if(0===o.length)return void(yield gO(i.tryToUnmuteAudio(e)));o.forEach((e=>{let t=e.track,n=e.type;const r=Date.now();i.store.publish(t.getTrackId(),n===sB.LocalAudioTrack?"audio":"video",r)})),i.bindLocalTrackEvents(o);const s=yield gO(i.sendConnection.send(o.map((e=>e.track)),i.store.codec,i.store.audioCodec)),a=(yield gO(s.next())).value,c=i.createGatewayPublishMessage(o,a);try{yield c}catch(e){throw s.throw(e),(null==e?void 0:e.code)===JN.WS_ABORT&&o.forEach((e=>{let t=e.track;-1===i.pendingLocalTracks.indexOf(t)&&i.pendingLocalTracks.push(t)})),i.unbindLocalTrackEvents(o),e}yield gO(s.next()),o.forEach((e=>{let t=e.type;i.statsCollector.addLocalStats(t)})),i.statsUploader.startUploadOutboundStats(),i.assignLocalTracks(o,a),o.forEach((e=>{let t=e.track,n=e.type;const r=Date.now();i.store.publish(t.getTrackId(),n===sB.LocalAudioTrack?"audio":"video",void 0,r)})),i.startUploadUplinkState()}finally{r()}}))()}async unpublish(e){if(!this.sendConnection||this.state!==aB.Connected)return void(0===e.length?this.pendingLocalTracks.length=0:this.pendingLocalTracks=this.pendingLocalTracks.filter((t=>!Vi(e).call(e,t))));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const n=t.find((e=>"videoLowTrack"===e[0]));if(n){n[1].track.close()}const i=this.createGatewayUnpublishMessage(t);if(await this.sendConnection.stopSending(t.map((e=>Hb(e,2)[1].id))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let t=Hb(e,2);return{type:t[0],track:t[1].track}}))),t.forEach((e=>{let t=Hb(e,1)[0];this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&(this.statsUploader.stopUploadOutboundStats(),this.stopUploadUplinkState()),this.sendConnection&&this.state===aB.Connected){if(n){n[1].track.close()}return i}e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}))}startUploadUplinkState(){if(this.uploadUnplinkStarted)return;this.uploadUnplinkStarted=!0,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval);const e=()=>{const e=[],t=[];Array.from(this.localTrackMap.entries()).forEach((n=>{let i=Hb(n,2),r=i[0],o=i[1],s=o.track,a=o.ssrcs;const c={stream_type:Sne(s,r),ssrcs:a};s._muted||!s._enabled?e.push(c):t.push(c)})),e.length>0&&e.forEach((e=>{ND(this,cB.RequestMuteLocal,[e])})),t.length>0&&t.forEach((e=>{ND(this,cB.RequestUnmuteLocal,[e])}))};e(),this.uplinkStateUploadInterval=window.setInterval((()=>{e()}),3e3)}stopUploadUplinkState(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval))}publishLowStream(e){return mO((function*(){throw new zN(JN.NOT_SUPPORTED,"p2p mode does not support publishLowStream.")}))()}async republish(){this.pendingLocalTracks.length>0&&(FL.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await OD(this,cB.RequestRePublish,this.pendingLocalTracks),this.emit(cB.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[])}async unpublishLowStream(){throw new zN(JN.NOT_SUPPORTED,"p2p mode does not support unpublishLowStream.")}async subscribe(e,t,n,i){var r;if(!this.recvConnection)throw new zN(JN.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");if(null!==(r=this.remoteUserMap.get(e))&&void 0!==r&&r.has(t))return;const o=await this.recvConnection.receive(t,[{ssrcId:n}],String(e.uid),i),s=o.track,a=o.mid,c=o.transceiver;t===nB.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new ox(s,e.uid,e._uintid,this.store),FL.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoSSRC=n,e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new rx(s,e.uid,e._uintid,this.store),FL.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack));const d=this.remoteUserMap.get(e);d?d.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats(),this.startUploadDownlinkState();const l=this.pendingRemoteTracks.findIndex((n=>{let i=n.user,r=n.kind;return i.uid===e.uid&&t===r}));-1!==l&&(this.pendingRemoteTracks.splice(l,1),this.emit(cB.MediaReconnectEnd,e.uid))}async mockSubscribe(e,t,n,i){if(!this.recvConnection)throw new zN(JN.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");await this.recvConnection.mockReceive(t,[{ssrcId:n}],String(e.uid),i)}async unsubscribe(e,t,n){const i=this.pendingRemoteTracks.filter((n=>{let i=n.user,r=n.kind;return void 0!==t?i.uid===e.uid&&t===r:i.uid===e.uid}));if(i.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.recvConnection||n||i.forEach((t=>{let n=t.kind;var i;if(n===nB.AUDIO)null===(i=e._audioTrack)||void 0===i||i._destroy(),e._audioTrack=void 0;else if(n===nB.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.recvConnection)return;const r=this.filterTobeUnSubscribedTracks(e,t);0!==r.length&&(await this.recvConnection.stopReceiving(r.map((e=>Hb(e,2)[1].id))),this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&(this.statsUploader.stopUploadInboundStats(),this.stopUploadDownlinkState()),r.forEach((e=>{let t=Hb(e,2),i=t[0],r=t[1].kind;var o,s;r===nB.VIDEO&&i._videoSSRC&&(null===(o=this.recvConnection)||void 0===o||o.setStatsRemoteVideoIsReady(i._videoSSRC,!1));if(r===nB.VIDEO)this.unbindRemoteTrackEvents(i._videoTrack),n||(null===(s=i._videoTrack)||void 0===s||s._destroy(),i._videoTrack=void 0);else if(r===nB.AUDIO){var a;if(this.unbindRemoteTrackEvents(i._audioTrack),!n)null===(a=i._audioTrack)||void 0===a||a._destroy(),i._audioTrack=void 0}})),r.forEach((e=>{let t=Hb(e,2)[1].kind;ND(this,cB.RequestP2PMuteRemote,t)})))}startUploadDownlinkState(){if(this.uploadDownlinkStarted)return;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);const e=()=>Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=Hb(e,2)[1];[nB.VIDEO,nB.AUDIO].forEach((e=>{t.has(e)?ND(this,cB.RequestP2PUnmuteRemote,e):ND(this,cB.RequestP2PMuteRemote,e)}))}));e(),this.downlinkStatsUploadInterval=window.setInterval((()=>{e()}),3e3)}stopUploadDownlinkState(){this.uploadDownlinkStarted&&(this.uploadDownlinkStarted=!1,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval))}getAllDataChannels(){return this.localDataChannels}async massSubscribe(e){throw new zN(JN.NOT_SUPPORTED,"p2p mode does not support massSubscribe.")}async massSubscribeNoLock(e){throw new zN(JN.NOT_SUPPORTED,"p2p mode does not support massSubscribeNoLock.")}async massUnsubscribe(e){throw new zN(JN.NOT_SUPPORTED,"p2p mode does not support massUnsubscribe.")}async massUnsubscribeNoLock(e){throw new zN(JN.NOT_SUPPORTED,"p2p mode does not support massUnsubscribeNoLock.")}async muteRemote(e,t){if(!this.recvConnection)return;const n=this.remoteUserMap.get(e);if(!n)return void FL.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid,"."));if(!n.get(t))return void FL.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const i=t===nB.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==i&&this.recvConnection.setStatsRemoteVideoIsReady(i,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.recvConnection)return;const n=this.remoteUserMap.get(e);if(!n)return void FL.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid,"."));n.get(t)||FL.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."))}getAllTracks(e){const t=this.localTrackMap.get(sB.LocalAudioTrack);if((null==t?void 0:t.track)instanceof zU){const n=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>Hb(e,1)[0]!==sB.LocalAudioTrack)).filter((t=>{let n=Hb(t,1)[0];return!(e&&n===sB.LocalVideoLowTrack)})).map((e=>Hb(e,2)[1].track)).concat(n.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let n=Hb(t,1)[0];return!(e&&n===sB.LocalVideoLowTrack)})).map((e=>Hb(e,2)[1].track))}reportPublishEvent(e,t,n,i,r){if(e){const n=this.localTrackMap.get(sB.LocalAudioTrack),o=i?this.localTrackMap.get(sB.LocalVideoLowTrack):this.localTrackMap.get(sB.LocalVideoTrack);uk.publish(this.store.sessionId,{eventElapse:Hte.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==n?void 0:n.track.getTrackLabel(),videoName:null==o?void 0:o.track.getTrackLabel(),screenshare:-1!==(null==o?void 0:o.track._hints.indexOf(jk.SCREEN_TRACK)),audio:!!n,video:!!o,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var o;n||(n=[]);const s=n.find((e=>e instanceof YU)),a=i?null===(o=this.localTrackMap.get(sB.LocalVideoTrack))||void 0===o?void 0:o.track:n.find((e=>e instanceof BV));uk.publish(this.store.sessionId,{eventElapse:Hte.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==s?void 0:s.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(jk.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,n,i){const r=i===nB.VIDEO?n._videoSSRC:n._audioSSRC;r&&uk.subscribe(this.store.sessionId,{succ:e,ec:t,video:i===nB.VIDEO,audio:i===nB.AUDIO,peerid:n.uid,subscribeRequestid:i===nB.VIDEO?n._videoSSRC:n._audioSSRC,p2pid:this.store.p2pId,eventElapse:Hte.measureFromSubscribeStart(this.store.clientId,r)})}reset(){FL.debug("[".concat(this.store.clientId,"] P2PChannel2.reset")),this.sendMutex=new _P("P2PChannel2-send-mutex",this.store.clientId),this.sendMutex=new _P("P2PChannel2-recv-mutex",this.store.clientId),this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(sB.LocalAudioTrack);if((null==e?void 0:e.track)instanceof zU){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach((e=>{t.removeAudioTrack(e)}))}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.reconnectInterval&&(window.clearInterval(this.reconnectInterval),this.reconnectInterval=void 0),this.state=aB.Disconnected}getStats(e){var t,n;return e?null===(n=this.recvConnection)||void 0===n?void 0:n.getStats():null===(t=this.sendConnection)||void 0===t?void 0:t.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.recvConnection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(sB.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(sB.LocalVideoTrack);if(e)return{width:e.track.videoWidth||0,height:e.track.videoHeight||0}}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof BV||t&&t.track instanceof YU?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const n=this.remoteUserMap.get(e);return!!n&&(!t||n.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const n=this.remoteUserMap.get(e);return!!n&&(!t||n.has(t))}getRemoteMedia(e){var t;const n=Array.from(CL(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return n?{audioTrack:n.audioTrack,audioSSRC:n._audioSSRC,videoTrack:n.videoTrack,videoSSRC:n._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let t=Hb(e,1)[0];return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(sB.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=n_(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.sendConnection&&this.recvConnection&&(FL.debug("[".concat(this.store.clientId,"] P2PChannel2.disconnectForReconnect closing P2PConnection")),this.state=aB.Reconnecting,rL("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=Hb(e,1)[0];var n;t._videoTrack&&t._videoTrack._player&&(null===(n=t._videoTrack._player.getVideoElement())||void 0===n||n.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0,this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0,0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{var t;let n=Hb(e,2),i=n[0],r=n[1].track;switch(i){case sB.LocalVideoTrack:Vi(t=r._hints).call(t,jk.LOW_STREAM)?r.close():this.pendingLocalTracks.push(r);break;case sB.LocalAudioTrack:r instanceof zU?this.pendingLocalTracks=this.pendingLocalTracks.concat(r.trackList):this.pendingLocalTracks.push(r);case sB.LocalVideoLowTrack:}})),this.emit(cB.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=Hb(e,2),n=t[0],i=t[1];Array.from(CL(i).call(i)).forEach((e=>{this.setPendingRemoteMedia(n,e)})),this.emit(cB.MediaReconnectStart,n.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),FL.debug("[".concat(this.store.clientId,"] P2PChannel2 disconnected, waiting to reconnect.")))}hasPendingRemoteMedia(e,t){for(const n of this.pendingRemoteTracks){const i=n.user,r=n.kind;if((e instanceof qte?e.uid:e)===i.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}async restartICE(e,t){let n,i;if(e===AF.SEND_ONLY){if(!this.sendConnection)throw new zN(JN.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established.");n=await this.sendMutex.lock("From P2PChannel.restartICE"),i=this.sendConnection}else{if(!this.recvConnection)throw new zN(JN.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before recvConnection established.");n=await this.recvMutex.lock("From P2PChannel.restartICE"),i=this.recvConnection}try{if(t){const e=await i.restartICE(t);return i.isInRestartIce=!1,e}{const e=await i.restartICE();if(e){const t=await OD(this,cB.RequestP2PRestartICE,{direction:AF.RECEIVE_ONLY,iceParameter:e});await i.restartICE(t),i.isInRestartIce=!1}}}finally{n()}}getUplinkNetworkQuality(){if(!this.sendConnection)return 0;const e=this.sendConnection.getStats(),t=this.localTrackMap.get(sB.LocalVideoTrack),n=this.localTrackMap.get(sB.LocalAudioTrack),i=e.videoSend.find((e=>{var n;return e.ssrc===(null==t||null===(n=t.ssrcs)||void 0===n?void 0:n[0].ssrcId)})),r=e.audioSend.find((e=>{var t;return e.ssrc===(null==n||null===(t=n.ssrcs)||void 0===t?void 0:t[0].ssrcId)}));if(!i||!r)return 1;const o=DD(this,cB.NeedSignalRTT),s=i?i.rttMs:void 0,a=r?r.rttMs:void 0,c=s&&a?(s+a)/2:s||a,d=(c&&o?(c+o)/2:c||o)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(jk.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,n=e.bitrate.actualEncoded;if(t&&n){const e=(1e3*t-n)/(1e3*t);return zx[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u]}}return u}getDownlinkNetworkQuality(){if(!this.recvConnection)return 0;const e=this.recvConnection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((n=>{let i=Hb(n,1)[0];const r=i._audioSSRC,o=i._videoSSRC,s=e.audioRecv.find((e=>e.ssrc===r)),a=e.videoRecv.find((e=>e.ssrc===o));if(!s&&!a)return void(t+=1);const c=DD(this,cB.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=s?s.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new dp(((t,n)=>{this.handleMuteLocalTrack(e,t,n)}))}filterTobePublishedTracks(e,t,n){const i=[],r=_k(),o=this.getAllTracks();e=BD(e=e.filter((e=>-1===o.indexOf(e))));let s=!1,a=!1;for(const o of e){if(o instanceof BV&&(this.localTrackMap.has(sB.LocalVideoTrack)||s?new zN(JN.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(i.push({track:o,type:sB.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(o,n);i.push({track:e,type:sB.LocalVideoLowTrack})}if(o instanceof YU){const e=this.localTrackMap.get(sB.LocalAudioTrack);if(e){if(!(e.track instanceof zU))throw new zN(JN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(o._bypassWebAudio)throw new zN(JN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(o),this.bindLocalAudioTrackEvents(o,!0)}else if(a){const e=i.find((e=>e.type===sB.LocalAudioTrack));if(!(e.track instanceof zU))throw new zN(JN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(o._bypassWebAudio)throw new zN(JN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(o)}else{if(!r.webAudioMediaStreamDest||o instanceof zU||o._bypassWebAudio)i.push({track:o,type:sB.LocalAudioTrack});else{const e=new zU;e.addAudioTrack(o),i.push({track:e,type:sB.LocalAudioTrack})}a=!0}}}return i}filterTobeUnpublishedTracks(e){const t=[],n=this.getAllTracks();e=BD(e=e.filter((e=>-1!==n.indexOf(e))));for(const n of e){if(n instanceof YU){const e=this.localTrackMap.get(sB.LocalAudioTrack);if(!e)continue;e.track instanceof zU?(e.track.removeAudioTrack(n),this.unbindLocalAudioTrackEvents(n),0===e.track.trackList.length&&(t.push([sB.LocalAudioTrack,e]),e.track.close())):t.push([sB.LocalAudioTrack,e])}if(n instanceof BV){const e=this.localTrackMap.get(sB.LocalVideoTrack);if(!e)continue;t.push([sB.LocalVideoTrack,e]);const n=this.localTrackMap.get(sB.LocalVideoLowTrack);n&&t.push([sB.LocalVideoLowTrack,n])}}return t}bindLocalTrackEvents(e){e.forEach((e=>{let t=e.track;switch(e.type){case sB.LocalVideoTrack:t.addListener(Bk.GET_STATS,this.handleGetLocalVideoStats),t.addListener(Bk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(Bk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(Bk.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(Bk.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(Bk.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(Bk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(Bk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case sB.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case sB.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof zU?e.trackList.forEach((e=>{e.addListener(Bk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(Bk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(Bk.GET_STATS,this.handleGetLocalAudioStats),e.addListener(Bk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(Bk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(Bk.GET_STATS,this.handleGetLocalAudioStats),e.addListener(Bk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(Bk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(Bk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(Bk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(Bk.NEED_REPLACE_TRACK,this.handleReplaceTrack))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let t=Hb(e,2),n=t[0];return{track:t[1].track,type:n}}))),e.forEach((e=>{let t=e.track;switch(e.type){case sB.LocalVideoTrack:t.off(Bk.GET_STATS,this.handleGetLocalVideoStats),t.off(Bk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(Bk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(Bk.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(Bk.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(Bk.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(Bk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(Bk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case sB.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case sB.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof zU?e.trackList.forEach((e=>{e.off(Bk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(Bk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(Bk.GET_STATS,this.handleGetLocalAudioStats),e.off(Bk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(Bk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(Bk.GET_STATS,this.handleGetLocalAudioStats),e.off(Bk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(Bk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(Bk.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(Bk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(Bk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof rx&&t.addListener(Bk.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof ox&&t.addListener(Bk.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(Bk.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=Hb(e,2),n=t[0],i=t[1];i.has(nB.AUDIO)&&this.unbindRemoteTrackEvents(n._audioTrack),i.has(nB.VIDEO)&&this.unbindRemoteTrackEvents(n._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,n)=>{var i;let r,o=e.track,s=e.type;switch(s){case sB.LocalAudioTrack:r=KF.Audio;break;case sB.LocalVideoTrack:r=Vi(i=o._hints).call(i,jk.SCREEN_TRACK)?KF.Screen:KF.High;break;case sB.LocalVideoLowTrack:r=KF.Low}return{kind:s===sB.LocalAudioTrack?nB.AUDIO:nB.VIDEO,stream_type:r,mid:t[n].id,ssrcs:t[n].localSSRC,isMuted:o.muted||!o.enabled}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let n,i=Hb(e,2),r=i[0],o=i[1],s=o.track,a=o.ssrcs,c=o.id;switch(r){case sB.LocalVideoTrack:n=Vi(t=s._hints).call(t,jk.SCREEN_TRACK)?KF.Screen:KF.High;break;case sB.LocalAudioTrack:n=KF.Audio;break;case sB.LocalVideoLowTrack:n=KF.Low}return{stream_type:n,ssrcs:a,mid:c}}))}assignLocalTracks(e,t){e.forEach(((e,n)=>{let i=e.track,r=e.type;this.localTrackMap.set(r,{track:i,id:t[n].id,ssrcs:t[n].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let t=Hb(e,1)[0];this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{var n;FL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: ").concat(e.name,".onConnectionStateChange(").concat(t,")")),this.emit(cB.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t&&(e.isInRestartIce=!1),Vi(n=this._restartStates).call(n,t)&&!e.isInRestartIce&&("disconnected"===t&&await $D(800),"disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction))},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),FL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),uk.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:mD.TRACER}).onSuccess(),this.emit(cB.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{FL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{FL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{FL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t;const n=Array.from(CL(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));var i;n&&(this.store.subscribe(n.uid,"audio",void 0,void 0,void 0,Date.now()),null===(i=n.audioTrack)||void 0===i||i.emit(Xk.FIRST_FRAME_DECODED),uk.firstRemoteFrame(this.store.sessionId,HL.FIRST_AUDIO_DECODE,YL.FIRST_AUDIO_DECODE,{peer:n._uintid,subscribeElapse:Hte.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const n=Array.from(CL(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));n&&uk.firstRemoteFrame(this.store.sessionId,HL.FIRST_AUDIO_RECEIVED,YL.FIRST_AUDIO_RECEIVED,{peer:n._uintid,subscribeElapse:Hte.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,n)=>{this.reportVideoFirstFrameDecoded(e,t,n)},e.onFirstVideoReceived=e=>{var t;const n=Array.from(CL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));n&&uk.firstRemoteFrame(this.store.sessionId,HL.FIRST_VIDEO_RECEIVED,YL.FIRST_VIDEO_RECEIVED,{peer:n._uintid,subscribeElapse:Hte.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(e,t)=>{const n="relay"===e.candidateType,i="relay"===t.candidateType;"unknown"!==t.candidateType&&n===i||this.emit(cB.ConnectionTypeChange,n),FL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(nee(t))," -> ").concat(JSON.stringify(nee(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{FL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(nee(t))," -> ").concat(JSON.stringify(nee(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.onLocalCandidate=t=>{this.emit(cB.LocalCandidate,{candidate:t,direction:e.direction})}}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.onLocalCandidate=void 0}async handleDisconnect(e){const t=e===AF.SEND_ONLY?this.sendConnection:this.recvConnection;t&&!t.isInRestartIce&&(t.isInRestartIce=!0,FL.debug("[".concat(this.store.clientId,"] [P2PChannel-").concat(t.name,"] start use restartICE")),e===AF.SEND_ONLY?this.restartICE(e):OD(this,cB.RequestP2PRestartICE,{direction:AF.SEND_ONLY}))}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const n=this.localTrackMap.get(sB.LocalAudioTrack);if(e instanceof YU&&(null==n?void 0:n.track)instanceof zU)return n.track.isActive||t.push([sB.LocalAudioTrack,n]),t;const i=Array.from(this.localTrackMap.entries()).find((t=>{let n=Hb(t,2)[1].track;return e===n}));if(i&&(t.push(i),i[0]===sB.LocalVideoTrack)){const e=this.localTrackMap.get(sB.LocalVideoLowTrack);e&&t.push([sB.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],n=this.localTrackMap.get(sB.LocalAudioTrack);if(e instanceof YU&&(null==n?void 0:n.track)instanceof zU)return n.track.isActive&&t.push([sB.LocalAudioTrack,n]),t;const i=Array.from(this.localTrackMap.entries()).find((t=>{let n=Hb(t,2)[1].track;return e===n}));if(i)if(i[0]===sB.LocalVideoTrack){t.push(i);const e=this.localTrackMap.get(sB.LocalVideoLowTrack);e&&t.push([sB.LocalVideoLowTrack,e])}else t.push(i);return t}createMuteMessage(e){return e.map((e=>{var t;let n,i=Hb(e,2),r=i[0],o=i[1],s=o.track,a=o.ssrcs,c=o.id;switch(r){case sB.LocalAudioTrack:n=KF.Audio;break;case sB.LocalVideoTrack:n=Vi(t=s._hints).call(t,jk.SCREEN_TRACK)?KF.Screen:KF.High;break;case sB.LocalVideoLowTrack:n=KF.Low}return{stream_type:n,ssrcs:a,mid:c}}))}createUnmuteMessage(e){return e.map((e=>{var t;let n,i=Hb(e,2),r=i[0],o=i[1],s=o.track,a=o.ssrcs,c=o.id;switch(r){case sB.LocalAudioTrack:n=KF.Audio;break;case sB.LocalVideoTrack:n=Vi(t=s._hints).call(t,jk.SCREEN_TRACK)?KF.Screen:KF.High;break;case sB.LocalVideoLowTrack:n=KF.Low}return{stream_type:n,ssrcs:a,mid:c}}))}filterTobeUnSubscribedTracks(e,t){const n=[],i=this.remoteUserMap.get(e);if(!i)return n;if(t){const r=i.get(t);if(!r)return n;n.push([e,{kind:t,id:r}])}else Array.from(i.entries()).forEach((t=>{let i=Hb(t,2),r=i[0],o=i[1];n.push([e,{kind:r,id:o}])}));return n}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let n=Hb(e,2),i=n[0],r=n[1],o=r.kind;switch(r.id,o){case nB.VIDEO:return void(i._videoSSRC&&t.push({stream_type:nB.VIDEO,ssrcId:i._videoSSRC}));case nB.AUDIO:return void(i._audioSSRC&&t.push({stream_type:nB.AUDIO,ssrcId:i._audioSSRC}))}})),t}withdrawRemoteTracks(e){e.forEach((e=>{let t=Hb(e,2),n=t[0],i=t[1].kind;const r=this.remoteUserMap.get(n);r&&(r.delete(i),0===Array.from(r.entries()).length&&this.remoteUserMap.delete(n))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(sB.LocalVideoTrack),n=this.localTrackMap.get(sB.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new dp(((e,n)=>{this.handleUpdateVideoEncoder(t.track,e,n,!0)}))),n&&e.low_stream_uplink&&(await n.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new dp(((e,t)=>{this.handleUpdateVideoEncoder(n.track,e,t,!0)})))}isP2PDisconnected(){if(this.sendConnection&&this.recvConnection){const e=this.sendConnection.peerConnectionState,t=this.recvConnection.peerConnectionState;return"connected"!==e&&"connected"!==t}return!0}async tryToUnmuteAudio(e){for(let t=0;t<e.length;t++)if(e[t]instanceof YU){const n=this.filterTobeUnmutedTracks(e[t]);if(0===n.length)continue;const i=this.createUnmuteMessage(n);return void await ND(this,cB.RequestUnmuteLocal,i)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=e=>this.getStats(e),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()).filter((e=>!!Hb(e,2)[1].ssrcs)),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null===(t=this.recvConnection)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(cB.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(cB.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks()}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await $D(fP(this.dtlsFailedCount,mP)),this.emit(cB.RequestReconnect)}async reconnectP2P(){}canPublishLowStream(){return this.localTrackMap.has(sB.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof BV))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof BV)).length>1)throw new zN(JN.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof YU)).length>1&&(e.some((e=>e instanceof YU&&e._bypassWebAudio))||!_k().webAudioMediaStreamDest))throw new zN(JN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const t of e){if(t instanceof BV&&this.pendingLocalTracks.some((e=>e instanceof BV)))throw new zN(JN.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof YU&&this.pendingLocalTracks.some((e=>e instanceof YU))&&(!_k().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof YU&&e._bypassWebAudio))))throw new zN(JN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){const n=!rL("DISABLE_DUAL_STREAM_USE_ENCODING")&&_k().supportDualStreamEncoding,i=qse(qse({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=n?e._mediaStreamTrack.clone():Dne(e,i);const o=eP(8,"track-low-"),s=new BV(r,qse(qse({},n&&{scaleResolutionDownBy:tee(i,e)}),{},{frameRate:i.framerate,bitrateMax:i.bitrate,bitrateMin:i.bitrate}),void 0,void 0,o);return s.on(Hk.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,Gk.LOW_STREAM)})),s._hints.push(jk.LOW_STREAM),e.addListener(Bk.NEED_CLOSE,(()=>{s.close()})),s}async globalLock(){return this.recvMutex.lock("From P2PChannel2.globalLock")}reportVideoFirstFrameDecoded(e,t,n,i){var r;const o=Array.from(CL(r=this.remoteUserMap).call(r)).find((t=>t._videoSSRC===e));if(o){i||this.store.subscribe(o.uid,"video",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,s=r.subscribe.find((e=>e.userId===o.uid&&"video"===e.type));uk.firstRemoteVideoDecode(this.store.sessionId,HL.FIRST_VIDEO_DECODE,YL.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:n,subscribeElapse:Hte.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==s?void 0:s.subscribeEnd)||0,subscriberStart:(null==s?void 0:s.subscribeStart)||0,videoAddNotify:(null==s?void 0:s.streamAdded)||0,state:i?1:0})}}async remoteMediaSsrcChanged(e,t,n){if(!this.recvConnection)return!1;const i=this.remoteUserMap.get(e);if(!i)return!1;const r=i.get(t);if(!r)return!1;const o=await this.recvConnection.getRemoteSSRC(r);return void 0!==o&&o!==n}isPreSubScribe(e){return!1}async publishDataChannel(e){throw new zN(JN.NOT_SUPPORTED)}async unpublishDataChannel(e){throw new zN(JN.NOT_SUPPORTED)}async subscribeDataChannel(e,t){throw new zN(JN.NOT_SUPPORTED)}async unsubscribeDataChannel(e,t){throw new zN(JN.NOT_SUPPORTED)}hasPendingRemoteDataChannel(e,t){throw new zN(JN.NOT_SUPPORTED)}setPendingRemoteDataChannel(e,t){throw new zN(JN.NOT_SUPPORTED)}async preConnect(e){throw new zN(JN.NOT_SUPPORTED)}getEstablishParams(){throw new zN(JN.NOT_SUPPORTED)}async reSubscribe(e){throw new zN(JN.NOT_SUPPORTED)}reportVideoFirstFrameRender(e){}async updateVideoStreamParameter(e,t){throw new zN(JN.NOT_SUPPORTED)}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let t=Hb(e,2),n=t[0],i=t[1].track;n===sB.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,Gk.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}},mF(zse.prototype,"p2pConnect",[xse],Object.getOwnPropertyDescriptor(zse.prototype,"p2pConnect"),zse.prototype),mF(zse.prototype,"unpublish",[Fse],Object.getOwnPropertyDescriptor(zse.prototype,"unpublish"),zse.prototype),mF(zse.prototype,"unpublishLowStream",[Bse],Object.getOwnPropertyDescriptor(zse.prototype,"unpublishLowStream"),zse.prototype),mF(zse.prototype,"subscribe",[jse],Object.getOwnPropertyDescriptor(zse.prototype,"subscribe"),zse.prototype),mF(zse.prototype,"mockSubscribe",[Gse],Object.getOwnPropertyDescriptor(zse.prototype,"mockSubscribe"),zse.prototype),mF(zse.prototype,"unsubscribe",[Wse],Object.getOwnPropertyDescriptor(zse.prototype,"unsubscribe"),zse.prototype),mF(zse.prototype,"muteRemote",[Kse],Object.getOwnPropertyDescriptor(zse.prototype,"muteRemote"),zse.prototype),mF(zse.prototype,"unmuteRemote",[Hse],Object.getOwnPropertyDescriptor(zse.prototype,"unmuteRemote"),zse.prototype),mF(zse.prototype,"hasRemoteMediaWithLock",[Yse],Object.getOwnPropertyDescriptor(zse.prototype,"hasRemoteMediaWithLock"),zse.prototype),mF(zse.prototype,"disconnectForReconnect",[Xse],Object.getOwnPropertyDescriptor(zse.prototype,"disconnectForReconnect"),zse.prototype),mF(zse.prototype,"remoteMediaSsrcChanged",[Jse],Object.getOwnPropertyDescriptor(zse.prototype,"remoteMediaSsrcChanged"),zse.prototype),zse);function $se(e){return function(t,n,i){const r=t[n];if("function"!=typeof r)throw new Error("Cannot use mutex on object property.");return i.value=async function(){for(var t=arguments.length,i=new Array(t),o=0;o<t;o++)i[o]=arguments[o];switch(e){case Vse.SEND_ONLY:{const e=await this.sendMutex.lock("From P2PChannel2.".concat(n));try{return await r.apply(this,i)}finally{e()}}case Vse.RECEIVE_ONLY:{const e=await this.recvMutex.lock("From P2PChannel2.".concat(n));try{return await r.apply(this,i)}finally{e()}}default:{const e=await this.sendMutex.lock("From P2PChannel2.".concat(n)),t=await this.recvMutex.lock("From P2PChannel2.".concat(n));try{return await r.apply(this,i)}finally{e(),t()}}}},i}}class eae extends hD{constructor(e,t){super(),GA(this,"signal",void 0),GA(this,"token",void 0),GA(this,"tokenTimeout",void 0),GA(this,"tokenInterval",void 0),GA(this,"_sequence",0),GA(this,"userMap",new Map),GA(this,"encoder",new TextEncoder),this.signal=e,this.token=t;const n=()=>{this.signal.connectionState===vF.CONNECTED&&this.check(),0===this.userMap.size?this.tokenInterval=window.setTimeout(n,1e3):this.tokenInterval=window.setTimeout(n,3*rL("P2P_TOKEN_INTERVAL"))};n()}async send(e,t,n,i,r){var o;if(0===this.userMap.size)return;const s=Array.from(gp(o=this.userMap).call(o))[0].token;"string"!=typeof t&&(t=JSON.stringify(t)),i=null!=i?i:eP(6,""),r=null!=r?r:this._sequence++;const a={_id:i,_type:e,_seq:r,_message:t,token:"".concat(this.token,"_").concat(s)};rL("SHOW_P2P_LOG")&&FL.debug("send message",a,"noNeedResponse : ".concat(n));this.splitMessage(JSON.stringify(a)).forEach((e=>{this.signal.request(bF.DATA_STREAM,{payload:XD(this.encoder.encode(e))})}));const c=new dp(((t,r)=>{const o=window.setTimeout((()=>{this.off("res-@".concat(i,"_ack"),s),this.off("res-@".concat(i),d),this.off(SB.ABORT,c),FL.debug("[external-signal] request timeout, type: ".concat(e,", requestId: ").concat(i)),0===this.userMap.size?r(new zN(JN.INVALID_REMOTE_USER)):r(new zN(JN.TIMEOUT))}),rL("EXTERNAL_SIGNAL_REQUEST_TIMEOUT")),s=()=>{o&&window.clearTimeout(o),this.off(SB.ABORT,c),n&&t()},c=()=>{o&&window.clearTimeout(o),this.off("res-@".concat(i,"_ack"),s),this.off("res-@".concat(i),d),r(new zN(JN.EXTERNAL_SIGNAL_ABORT,"type: ".concat(e,", requestId: ").concat(i)))};this.once(SB.ABORT,c),this.once("res-@".concat(i,"_ack"),s);const d=(n,a)=>{l=!0,o&&window.clearTimeout(o),this.off("res-@".concat(i,"_ack"),s),this.off(SB.ABORT,c),"success"===n?t(a):r(new zN(JN.P2P_MESSAGE_FAILED,"request ".concat(e," failed, requestId: ").concat(i)))};let l=!1;n||(this.once("res-@".concat(i),d),$D(rL("SIGNAL_REQUEST_TIMEOUT")).then((()=>{l||FL.warning("external_signal request timeout, type: ".concat(e,", requestId: ").concat(i,", ").concat(a))})))}));try{return await c}catch(o){if(o.code===JN.TIMEOUT)return await this.send(e,t,n,i,r);throw o}}onMessage(e){var t;const n=e._uid;let i,r=this.userMap.get(n);if(r)i=r.splitMessageMap;else{if(this.userMap.size>0||!("_type"in e)||e._type!==gB.CHECK)return;const t=e.token;i=new Map,r={uid:n,isStart:!0,token:t,splitMessageMap:i,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map},this.userMap.set(n,r),this.signal.emit(IF.ON_USER_ONLINE,{uid:n}),this.handleUserOnline()}if("id"in e&&"total"in e){var o;const t=e,r=t.id,s=t.total,a=null!==(o=i.get(r))&&void 0!==o?o:[];if(a.push(e),i.has(r)||i.set(r,a),a.length!==s)return;{const t=n_(a).call(a,((e,t)=>e.index-t.index)).map((e=>e.payload)).join("");i.delete(r),(e=JSON.parse(t))._uid=n}}const s=e,a=s._type,c=s.token;if(Vi(t=[gB.ACK,gB.CHECK]).call(t,a))return a===gB.CHECK&&this.handleCheckToken(r,c),void this.receiveMessage(e);c==="".concat(r.token,"_").concat(this.token)?this.handleReceivedMessage(e):FL.debug('Receive unexpected message", '.concat(c,", cur_token: ").concat(r.token,"_").concat(this.token),e)}check(){const e={_id:eP(6,""),token:this.token,_type:gB.CHECK};rL("SHOW_P2P_LOG")&&FL.debug("send message",e),this.signal.request(bF.DATA_STREAM,{payload:XD(this.encoder.encode(JSON.stringify(e)))})}ack(e){const t={_id:e,_type:gB.ACK,token:this.token};rL("SHOW_P2P_LOG")&&FL.debug("send message",t),this.signal.request(bF.DATA_STREAM,{payload:XD(this.encoder.encode(JSON.stringify(t)))})}response(e,t,n){this.send(gB.RESPONSE,JSON.stringify({success:!n,message:t}),!0,e)}handleReceivedMessage(e){const t=()=>{this.userMap.forEach((e=>{const t=e.receivedMessagesMap,n=e.nextExpectedSequenceNumber;for(;t.has(n);){const i=t.get(n);t.delete(n),this.receiveMessage(i),e.nextExpectedSequenceNumber++}}))};if(!e)return void t();const n=e,i=n._uid,r=n._seq,o=this.userMap.get(i),s=o.receivedMessagesMap,a=o.isStart,c=o.nextExpectedSequenceNumber;if(r<c)return this.ack(e._id),void FL.debug("[external-signal] receive old message, seq: ".concat(r,", ").concat(e._message));s.set(r,e),a&&r===c&&(this.receiveMessage(e),s.delete(c),o.nextExpectedSequenceNumber++,t())}receiveMessage(e){const t=e._id,n=e._type,i=e._message,r=e._uid;if(rL("SHOW_P2P_LOG")&&FL.debug("receive message",e),t){let o;switch(e._type!==gB.ACK&&(i&&(o=JSON.parse(i)),this.ack(e._id)),e._type){case gB.CANDIDATE:case gB.CONTROL:this.signal.emit(n,o,r);break;case gB.PUBLISH:case gB.UNPUBLISH:case gB.RESTART_ICE:case gB.CALL:o.uid=r,OD(this.signal,n,o).then((t=>{this.response(e._id,t)})).catch((()=>{this.response(e._id,void 0,!0)}));break;case gB.ACK:this.getListeners("res-@".concat(t,"_ack")).length>0&&this.emit("res-@".concat(t,"_ack"));break;case gB.RESPONSE:{const e=o,n=e.success,i=e.message;this.emit("res-@".concat(t),n?"success":"failed",i);break}}}}splitMessage(e){if(e.length<eae.MAX_MESSAGE_SIZE)return[e];const t=[],n=JSON.parse(e).remoteToken,i=eP(6,"");let r=0,o=800;const s=Math.ceil(e.length/o);for(;e.length>0;){r++;const a={id:i,index:r,total:s,payload:e.slice(0,o),token:"".concat(this.token,"_").concat(n)};JSON.stringify(a).length>eae.MAX_MESSAGE_SIZE?o-=50:(t.push(a),e=e.slice(o))}return t.map((e=>JSON.stringify(e)))}handleCheckToken(e,t){return e.token!==t?(FL.debug("token changed, from ".concat(e.token," to ").concat(t)),this.reset(e.uid,t),!1):(this.tokenTimeout&&(window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0),this.tokenTimeout=window.setTimeout((()=>{FL.debug("token timeout, ".concat(t)),this.reset(e.uid)}),rL("MAX_P2P_TIMEOUT")),!0)}async handleUserOnline(){const e=await OD(this.signal,gB.CALL,void 0),t=await this.send(gB.CALL,e);this.signal.emit(yF.P2P_CONNECTION,t,!0)}async reset(e,t){const n=this.userMap.get(e);n&&(this.emit(SB.ABORT),this.signal.emit(IF.ON_USER_OFFLINE,{uid:n.uid,reason:RB.P2P_TOKEN_CHANGED}),this._sequence=0,this.userMap.clear(),t||(FL.debug("change local token from ".concat(t," to ").concat(t)),this.token=eP(6,"")))}clear(){this._sequence=0,this.userMap.clear(),this.tokenInterval&&window.clearTimeout(this.tokenInterval),this.tokenInterval=void 0,this.tokenTimeout&&window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0,this.emit(SB.ABORT)}}GA(eae,"MAX_SIZE",1),GA(eae,"MAX_MESSAGE_SIZE",1024);class tae extends hD{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===vF.CONNECTED?this.emit(yF.WS_CONNECTED):e===vF.RECONNECTING?this.emit(yF.WS_RECONNECTING,this._websocketReconnectReason):e===vF.CLOSED&&this.emit(yF.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),GA(this,"__name__","P2PSignal"),GA(this,"_disconnectedReason",void 0),GA(this,"_websocketReconnectReason",void 0),GA(this,"_connectionState",vF.CLOSED),GA(this,"reconnectToken",void 0),GA(this,"p2pToken",void 0),GA(this,"websocket",void 0),GA(this,"openConnectionTime",void 0),GA(this,"clientId",void 0),GA(this,"lastMsgTime",Date.now()),GA(this,"uploadCache",[]),GA(this,"uploadCacheInterval",void 0),GA(this,"rttRolling",new TP(5)),GA(this,"pingpongTimer",void 0),GA(this,"pingpongTimeoutCount",0),GA(this,"joinResponse",void 0),GA(this,"multiIpOption",void 0),GA(this,"initError",void 0),GA(this,"spec",void 0),GA(this,"store",void 0),GA(this,"_external_signal",void 0),GA(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(yF.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")){switch(t._type){case IF.ON_DATA_STREAM:return void this.handleDataStream(t._message);case IF.MUTE_AUDIO:case IF.MUTE_VIDEO:case IF.ON_P2P_LOST:case IF.ON_USER_ONLINE:return;case IF.ON_USER_OFFLINE:const e=t._message.uid;return FL.debug("[".concat(this.clientId,"] user-offline uid: ").concat(e)),void this._external_signal.reset(e)}if(this.emit(t._type,t._message),t._type===IF.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===IF.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(SD.UID_BANNED);break;case 15:this.close(SD.IP_BANNED);break;case 16:this.close(SD.CHANNEL_BANNED)}if(t._type===IF.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case RF.ERR_LICENSE_MISSING:this.close(SD.LICENSE_MISSING);break;case RF.ERR_LICENSE_EXPIRED:this.close(SD.LICENSE_EXPIRED);break;case RF.ERR_LICENSE_MINUTES_EXCEEDED:this.close(SD.LICENSE_MINUTES_EXCEEDED);break;case RF.ERR_LICENSE_PERIOD_INVALID:this.close(SD.LICENSE_PERIOD_INVALID);break;case RF.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(SD.LICENSE_MULTIPLE_SDK_SERVICE);break;case RF.ERR_LICENSE_ILLEGAL:this.close(SD.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new VB("gateway-".concat(this.clientId),this.spec.retryConfig,!0,rL("JOIN_GATEWAY_USE_DUAL_DOMAIN"),rL("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===vF.CONNECTED&&this.reconnect("retry",ID.OFFLINE)})),this.p2pToken=eP(6,""),this._external_signal=new eae(this,this.p2pToken)}async request(e,t,n,i){const r=eP(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new dp(((e,t)=>{if(this.connectionState===vF.CONNECTED)return e();const n=()=>{this.off(yF.WS_CLOSED,i),e()},i=()=>{this.off(yF.WS_CONNECTED,n),t(new zN(JN.WS_ABORT))};this.once(yF.WS_CONNECTED,n),this.once(yF.WS_CLOSED,i)}));if(this.connectionState!==vF.CONNECTING&&this.connectionState!==vF.RECONNECTING||e===bF.JOIN||e===bF.REJOIN||await a(),this.websocket.sendMessage(o,!0),i)return;const c=new dp(((n,i)=>{let o=!1;const a=(i,r)=>{o=!0,n({isSuccess:"success"===i,message:r||{}}),this.off(yF.WS_CLOSED,c),this.off(yF.WS_RECONNECTING,c),this.emit(yF.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{i(new zN(JN.WS_ABORT,"type: ".concat(e))),this.off(yF.WS_CLOSED,c),this.off(yF.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(yF.WS_CLOSED,c),this.once(yF.WS_RECONNECTING,c),$D(rL("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(FL.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(yF.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(i){if(this.connectionState===vF.CLOSED||e===bF.LEAVE)throw new zN(JN.WS_ABORT);return!this.spec.forceWaitGatewayResponse||n?i.throw():e===bF.JOIN||e===bF.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=CB(l),h=new zN(JN.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:u.desc});return"success"===u.action?d.message:(FL.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===RF.ERR_TOO_MANY_BROADCASTERS?e===bF.JOIN||e===bF.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===RF.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,FL.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",ID.MULTI_IP)):this.reconnect(u.action,ID.SERVER_ERROR),e===bF.JOIN||e===bF.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new dp((n=>{const i=r=>{(!t||t(r))&&(this.off(e,i),n(r))};this.on(e,i)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void FL.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(CF.WRTC_STATS,t)}upload(e,t){const n={_type:e,_message:t};try{this.websocket.sendMessage(n)}catch(e){const t=rL("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(n),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==vF.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),rL("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const n={_type:e,_message:t};this.websocket.sendMessage(n)}async sendExtensionMessage(e,t,n){return await this._external_signal.send(e,t,n)}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new dp(((t,n)=>{this.once(yF.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(yF.WS_CLOSED,(()=>n(this.initError||new zN(JN.WS_ABORT)))),this.connectionState=vF.CONNECTING,this.websocket.init(e).catch(n)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._external_signal.clear(),this._disconnectedReason=e||SD.LEAVE,this.connectionState=vF.CLOSED,FL.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),this.p2pToken=eP(6,""),this._external_signal.clear(),this._external_signal=new eae(this,this.p2pToken)}async join(){if(!this.joinResponse){this.emit(yF.ABORT_P2P_EXECUTION);const e=await OD(this,yF.REQUEST_JOIN_INFO),t=await this.request(bF.JOIN,e);if(!t)return this.emit(yF.REPORT_JOIN_GATEWAY,JN.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(yF.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=vF.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}async downgradeCodec(e){return!1}handleDataStream(e){try{var t;const n=YD(e.payload),i=(new TextDecoder).decode(n),r=JSON.parse(i);"total"in r&&"id"in r||Vi(t=Object.values(gB)).call(t,r._type)?(r._uid=e.uid,this._external_signal.onMessage(r)):this.emit(IF.ON_DATA_STREAM,e)}catch(t){this.emit(IF.ON_DATA_STREAM,e)}}handleNotification(e){FL.debug("[".concat(this.clientId,"] receive notification: "),e);const t=CB(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?e.code===RF.ERR_REPEAT_JOIN_CHANNEL&&rL("IGNORE_UID_CHECK")?void this.close(SD.UID_CONFLICT):("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(SD.UID_BANNED),void this.close()):void this.reconnect(t.action,ID.SERVER_ERROR);FL.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=rL("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(FL.warning("[".concat(this.clientId,"] PINGPONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>rL("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",ID.TIMEOUT):this.request(bF.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),rL("REPORT_STATS")&&this.send(bF.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWebsocketEvents(){this.websocket.on(wF.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(yF.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(wF.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(wF.CLOSED,(()=>{this.connectionState=vF.CLOSED})),this.websocket.on(wF.FAILED,(()=>{this._disconnectedReason=SD.NETWORK_ERROR,this.connectionState=vF.CLOSED})),this.websocket.on(wF.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===vF.CONNECTED?this.connectionState=vF.RECONNECTING:this.connectionState=vF.CONNECTING})),this.websocket.on(wF.WILL_RECONNECT,((e,t,n)=>{"retry"!==e?(FL.debug("".concat(this.clientId," websocket will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0):FL.debug("".concat(this.clientId," reconnect mode is retry, no need to renew session")),n(e)})),this.websocket.on(wF.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.join().catch((e=>{if(this.emit(yF.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof zN&&e.code===JN.UNEXPECTED_RESPONSE&&e.data.code===RF.ERR_NO_AUTHORIZED)return FL.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",ID.SERVER_ERROR);FL.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",ID.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(wF.REQUEST_NEW_URLS,((e,t)=>{OD(this,yF.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(wF.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(IF.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}))}}const nae={name:"P2PChannel",create:function(e){let t=e.store,n=e.statsCollector;return new Qse(t,n)},createSubmodule:function(e){let t=e.store,n=e.spec;return new tae(n,t)}};function iae(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function rae(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?iae(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):iae(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class oae{constructor(e){GA(this,"sessionDesc",void 0),GA(this,"localCapabilities",void 0),GA(this,"rtpCapabilities",void 0),GA(this,"candidates",void 0),GA(this,"_originCandidates",void 0),GA(this,"iceParameters",void 0),GA(this,"dtlsParameters",void 0),GA(this,"setup",void 0),GA(this,"currentMidIndex",void 0),GA(this,"cname",void 0);const t=e=GD(e),n=t.iceParameters,i=t.dtlsParameters,r=t.candidates,o=t.rtpCapabilities,s=t.setup,a=t.localCapabilities,c=t.sdkCodec,d=t.cname,l=EL("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE audio video\na=msid-semantic: WMS\na=ice-lite\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:audio\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:video\n");this.rtpCapabilities=o,this.candidates=r,this._originCandidates=GD(r),this.iceParameters=n,this.dtlsParameters=i,this.setup=s,this.localCapabilities=a,this.cname=d;for(let e=0;e<l.mediaDescriptions.length;e++){const t=l.mediaDescriptions[e];if(t.attributes.iceUfrag=n.iceUfrag,t.attributes.icePwd=n.icePwd,t.attributes.fingerprints=i.fingerprints,t.attributes.candidates=r,t.attributes.setup=s,"video"===t.media.mediaType){t.media.fmts=o.videoCodecs.map((e=>e.payloadType.toString(10)));const e=o.videoCodecs.filter((e=>{var t,n;return null===(t=e.rtpMap)||void 0===t?void 0:Vi(n=t.encodingName.toLowerCase()).call(n,c)})),n=o.videoCodecs.filter((t=>!Vi(e).call(e,t)));t.attributes.payloads=[...e,...n],t.attributes.extmaps=o.videoExtensions}"audio"===t.media.mediaType&&(t.media.fmts=o.audioCodecs.map((e=>e.payloadType.toString(10))),t.attributes.payloads=o.audioCodecs,t.attributes.extmaps=o.audioExtensions),l.mediaDescriptions[e]=this.mungMediaDesc(t)}this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1}toString(){return mL(this.sessionDesc)}send(e,t,n){const i=Ree(t,this.cname),r=i.ssrcs,o=i.ssrcGroups,s=this.sessionDesc.mediaDescriptions.find((t=>e===nB.VIDEO?"video"===t.media.mediaType:"audio"===t.media.mediaType)),a=r[0].attributes.label,c=r[0].attributes.mslabel;return s.attributes.ssrcs=s.attributes.ssrcs.concat(r),s.attributes.ssrcGroups=s.attributes.ssrcGroups.concat(o),{id:a,mslabel:c}}batchSend(e){return e.map((e=>{let t=e.kind,n=e.ssrcMsg;return this.send(t,n,void 0)}))}stopSending(e){this.sessionDesc.mediaDescriptions.forEach((t=>{const n=[],i=[],r=[];t.attributes.ssrcs.forEach((t=>{Vi(e).call(e,t.attributes.label||"")?r.push(t):n.push(t)})),t.attributes.ssrcGroups.forEach((e=>{var t;Vi(t=r.map((e=>e.ssrcId))).call(t,e.ssrcIds[0])||i.push(e)})),t.attributes.ssrcs=n,t.attributes.ssrcGroups=i}))}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}receive(e,t,n){e.forEach(((e,t)=>{const n=e._mediaStreamTrack,i=this.sessionDesc.mediaDescriptions.findIndex((e=>e.attributes.mid===n.kind)),r=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],e);this.sessionDesc.mediaDescriptions[i]=r}))}stopReceiving(e){}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),n=[];if(t.forEach((e=>{n.push(rae(rae({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case iB.TCP_RELAY:this.candidates=n;break;case iB.UDP_TCP_RELAY:case iB.RELAY:this.candidates=[...t,...n];break;default:this.candidates=t}for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){e=GD(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let n=0;n<e;n++)t.push((this.currentMidIndex+n+1).toString(10));return t}mungRecvMediaDsec(e,t){const n=GD(e);return vee(n,t),bee(n,t),n}updateRecvMedia(e,t){const n=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==n){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],t);this.sessionDesc.mediaDescriptions[n]=e}}bumpMid(e){this.currentMidIndex+=e}updateTrackLabel(e,t,n){const i=this.sessionDesc.mediaDescriptions.find((t=>e===nB.VIDEO?"video"===t.attributes.mid:"audio"===t.attributes.mid));if(i){const e=i.attributes.ssrcs.find((e=>e.attributes.label===t));var r;if(e)e.attributes.label=n,null===(r=e.attributes.msid)||void 0===r||r.replace(t,n)}}mungMediaDesc(e){const t=GD(e);return yee(t),function(e){const t=e.attributes.extmaps.find((e=>hee(e.extensionName)));t&&e.attributes.extmaps.splice(e.attributes.extmaps.indexOf(t),1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"transport-cc"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}(t),t}getSSRC(e){for(const t of this.sessionDesc.mediaDescriptions)for(const n of t.attributes.ssrcs)if(n.attributes.label===e)return[n]}}var sae;function aae(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function cae(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?aae(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):aae(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let dae=(sae=class e extends tB{get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Vi(t=Object.keys(cL)).call(t,e)})))]}constructor(t,n){super(t,n),GA(this,"store",void 0),GA(this,"peerConnection",void 0),GA(this,"remoteSDP",void 0),GA(this,"initialOffer",void 0),GA(this,"statsFilter",void 0),GA(this,"useRTX",!1),GA(this,"localCapabilities",void 0),GA(this,"localCandidateCount",0),GA(this,"allCandidatesReceived",!1),GA(this,"establishPromise",void 0),GA(this,"mutex",void 0),this.store=n,this.mutex=new _P("P2PConnection-mutex",n.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=HP(this.peerConnection,rL("STATS_UPDATE_INTERVAL"),void 0,SN()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(){try{const e=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=mee(e.sdp),n=Eee(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:rL("FILTER_VIDEO_FEC"),filterAudioFec:rL("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=n,this.initialOffer=e,cae(cae({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:n},offerSDP:e.sdp})}catch(e){throw new zN(JN.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async updateRemoteConnect(){}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new oae(cae(cae({},e),{},{rtpCapabilities:e.rtpCapabilities.send,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec}));const t=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t})}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async updateRemoteRTPCapabilities(e,t){throw new zN(JN.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}getPreMedia(e){}send(e,t){var n=this;return mO((function*(){const i=yield gO(n.mutex.lock());try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const r=e.map((e=>n.peerConnection.addTrack(e._mediaStreamTrack))),o=yield gO(n.peerConnection.createOffer()),s=EL(o.sdp),a=e.map((e=>{const t=e._mediaStreamTrack,i=s.mediaDescriptions.find((e=>e.attributes.mid===t.kind));if(!i)throw new Error("Cannot extract ssrc from mediaDescription.");return function(e,t,n){const i=e.attributes.ssrcs.filter((e=>e.attributes.label===t)),r=e.attributes.ssrcGroups;if(0===i.length)throw new Error("Cannot extract ssrc from plan-b SDP.");if(r&&i.length>1){const e=r.find((e=>-1!==e.ssrcIds.indexOf(i[0].ssrcId)));return e?[{ssrcId:e.ssrcIds[0],rtx:n?e.ssrcIds[1]:void 0}]:[{ssrcId:i[0].ssrcId}]}return[{ssrcId:i[0].ssrcId}]}(i,t.id,n.useRTX)}));let c;try{c=yield a}catch(e){throw r.forEach((e=>{EN()&&e.replaceTrack(null),n.peerConnection.removeTrack(e)})),e}const d=n.mungSendOfferSDP(o.sdp,e);n.remoteSDP.receive(e,t,c);const l=n.remoteSDP.toString();return yield gO(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield gO(n.applySendEncodings(r,e)),yield gO(n.peerConnection.setRemoteDescription({type:"answer",sdp:l})),e.map(((e,t)=>{const n=e._mediaStreamTrack.id;return{localSSRC:a[t],id:n}}))}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{i()}}))()}async stopSending(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getSenders().filter((t=>{var n;return-1!==e.indexOf((null===(n=t.track)||void 0===n?void 0:n.id)||"")}));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map((e=>{EN()&&e.replaceTrack(null),this.peerConnection.removeTrack(e)}));const n=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}}async receive(e,t,n,i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const n=this.remoteSDP.send(e,t,i),r=n.id,o=n.mslabel,s=new dp(((t,n)=>{const i=setTimeout((()=>{n(new Error("Cannot receive track, id: ".concat(r)))}),1e4),s=n=>{const a=dN();if(("Safari"===a.name&&11===Number(a.version)||TN())&&n.track.id!==r&&n.streams[0].id===o){var c;const o=n.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(e,r,n.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(i),void t(o)}if(n.track.id===r)return this.peerConnection.removeEventListener("track",s),clearTimeout(i),void t(n.track)};this.peerConnection.addEventListener("track",s)})),a=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:a});const c=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(c);return{track:await s,id:r}}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(n)}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){}async unmuteRemote(e){}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter((t=>{var n;return-1!==e.indexOf((null===(n=t.track)||void 0===n?void 0:n.id)||"")}));if(t.length!==e.length)throw new Error("sender' length doesn't match mids' length.");t.map((e=>{if(EN()&&e.track)e.track.enabled=!1;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!1)),e.setParameters(t)}}))}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter((t=>{var n;return-1!==e.indexOf((null===(n=t.track)||void 0===n?void 0:n.id)||"")}));if(t.length!==e.length)throw new Error("Senders' length doesn't match mids' length.");t.map((async e=>{if(EN()&&e.track)e.track.enabled=!0;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!0)),await e.setParameters(t)}}));const n=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(n);const i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return mO((function*(){const n=yield gO(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const i=_k().supportPCSetConfiguration;if(e===iB.RELAY&&!i)return;if(i){const n=t.peerConnection.getConfiguration(),i=e===iB.RELAY?"relay":"all";n.iceTransportPolicy!==i&&(FL.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(n.iceTransportPolicy,"] to [").concat(i,"]")),n.iceTransportPolicy=i,t.peerConnection.setConfiguration(n))}e!==iB.RELAY&&t.remoteSDP.updateCandidates(e);const r=yield gO(t.peerConnection.createOffer({iceRestart:!0}));if(!r.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const o=mee(r.sdp),s=(yield o.iceParameters).remoteIceParameters;t.remoteSDP.restartICE(s);const a=t.remoteSDP.toString();yield gO(t.peerConnection.setLocalDescription(r)),yield gO(t.peerConnection.setRemoteDescription({type:"answer",sdp:a}))}catch(e){FL.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{n()}}))()}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const e=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(e.sdp,[t]);this.remoteSDP.updateRecvMedia(t._mediaStreamTrack.kind,t);const i=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),await this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const n=this.peerConnection.getSenders().filter((t=>{var n;return(null===(n=t.track)||void 0===n?void 0:n.id)===e}));1===n.length&&await this.applySendEncodings(n,[t])}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const n=this.peerConnection.getSenders().find((e=>{var n;return(null===(n=e.track)||void 0===n?void 0:n.id)===t}));n&&await n.replaceTrack(e._mediaStreamTrack)}createDataChannels(e,t){throw new zN(JN.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}stopDataChannels(e){throw new zN(JN.NOT_SUPPORTED,"Planb mode does not support stopDataChannels.")}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,FL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,FL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),rL("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const n={iceServers:[],sdpSemantics:"plan-b"};return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(TD(t.turnServer.servers)?n.iceServers=t.turnServer.servers:(n.iceServers&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),rL("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(n.iceTransportPolicy="relay")})))),n}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}async updateRtpSenderEncodings(e,t){var n;if(!t){t=this.peerConnection.getSenders().find((t=>{var n;return(null===(n=t.track)||void 0===n?void 0:n.id)===e._mediaStreamTrack.id}))}if(!t)return FL.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(!_k().supportSetRtpSenderParameters)return FL.warn("Browser not support set rtp-sender parameters");const i={},r={};if(e instanceof BV)switch(e._optimizationMode){case"motion":i.degradationPreference="maintain-framerate";break;case"detail":i.degradationPreference="maintain-resolution";break;default:i.degradationPreference="balanced"}if(rL("DSCP_TYPE")&&FN()){var o;const e=rL("DSCP_TYPE");Vi(o=["very-low","low","medium","high"]).call(o,e)&&(r.networkPriority=e)}const s=t.getParameters(),a=null===(n=s.encodings)||void 0===n?void 0:n[0];a&&Object.assign(a,r),Object.assign(s,i),FL.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(s.encodings))),await t.setParameters(s)}async applySendEncodings(e,t){try{if(!_k().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let n=0;n<e.length;n++){const i=e[n],r=t[n];i&&r&&await this.updateRtpSenderEncodings(r,i)}}catch(e){FL.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t){const n=EL(e);return t.forEach(((e,t)=>{const i=e._mediaStreamTrack,r=n.mediaDescriptions.find((e=>e.attributes.mid===i.kind));r&&vee(r,e)})),mL(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,n)=>{var i;null===(i=this.onFirstVideoDecoded)||void 0===i||i.call(this,e,t,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedLocalCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n||n.call(this,e,t)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e).map(((t,n)=>{let i=t.id,r=t.mslabel;const o=e[n].kind;return new dp(((e,t)=>{const n=setTimeout((()=>{t(new Error("Cannot receive track, id: ".concat(i)))}),1e4),s=t=>{const a=dN();if("Safari"===a.name&&11===Number(a.version)&&t.track.id!==i&&t.streams[0].id===r){var c;const r=t.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(o,i,t.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(n),void e({track:r,id:i})}if(t.track.id===i)return this.peerConnection.removeEventListener("track",s),clearTimeout(n),void e({track:t.track,id:i})};this.peerConnection.addEventListener("track",s)}))})),n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const i=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(i),await dp.all(t)}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(t){if(_k().supportPCSetConfiguration){const n=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(n)}}},mF(sae.prototype,"connect",[lae],Object.getOwnPropertyDescriptor(sae.prototype,"connect"),sae.prototype),mF(sae.prototype,"stopSending",[lae],Object.getOwnPropertyDescriptor(sae.prototype,"stopSending"),sae.prototype),mF(sae.prototype,"receive",[lae],Object.getOwnPropertyDescriptor(sae.prototype,"receive"),sae.prototype),mF(sae.prototype,"stopReceiving",[lae],Object.getOwnPropertyDescriptor(sae.prototype,"stopReceiving"),sae.prototype),mF(sae.prototype,"muteRemote",[lae],Object.getOwnPropertyDescriptor(sae.prototype,"muteRemote"),sae.prototype),mF(sae.prototype,"unmuteRemote",[lae],Object.getOwnPropertyDescriptor(sae.prototype,"unmuteRemote"),sae.prototype),mF(sae.prototype,"muteLocal",[lae],Object.getOwnPropertyDescriptor(sae.prototype,"muteLocal"),sae.prototype),mF(sae.prototype,"unmuteLocal",[lae],Object.getOwnPropertyDescriptor(sae.prototype,"unmuteLocal"),sae.prototype),mF(sae.prototype,"close",[lae],Object.getOwnPropertyDescriptor(sae.prototype,"close"),sae.prototype),mF(sae.prototype,"updateEncoderConfig",[lae],Object.getOwnPropertyDescriptor(sae.prototype,"updateEncoderConfig"),sae.prototype),mF(sae.prototype,"updateSendParameters",[lae],Object.getOwnPropertyDescriptor(sae.prototype,"updateSendParameters"),sae.prototype),mF(sae.prototype,"replaceTrack",[lae],Object.getOwnPropertyDescriptor(sae.prototype,"replaceTrack"),sae.prototype),mF(sae.prototype,"getRemoteSSRC",[lae],Object.getOwnPropertyDescriptor(sae.prototype,"getRemoteSSRC"),sae.prototype),sae);function lae(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=await e.lock("Locking from P2PConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await i.apply(this,o)}finally{n()}},n}const uae={name:"PlanBConnection",create:function(e){let t=e.store,n=e.spec;return new dae(n,t)}},hae={interceptLocalAudioFrame:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!_k().supportWebRTCEncodedTransform)return void FL.warning("browser not support audio encoded transform");if(gx.has(e))return;if(!e.track)return;const n={track:e.track};if(_N()){if(!e.createEncodedStreams)return void FL.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(e){return void FL.error("create audio-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(r,o){n.controller||(n.controller=o),e.track&&e.track.id!==n.track.id&&(FL.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i));const s=t.metadata&&t.metadata();s?function(e,t){const n=t.chunk,i=t.controller,r=mx.METADATA;n.data=function(e,t,n){const i=n.byteLength,r=i+_x+Ex,o=hx+px+r,s=new ArrayBuffer(e.byteLength+o),a=new DataView(s);a.setUint8(0,ux),a.setUint16(1,r),a.setUint8(3,t),a.setUint16(4,i);for(let e=0;e<i;e++)a.setUint8(6+e,n[e]);const c=new Uint8Array(a.buffer);return c.set(new Uint8Array(e),o),c.buffer}(n.data,r,e),i.enqueue(n)}(s,{sender:e,chunk:r,controller:o}):o.enqueue(r)}});r.readable.pipeThrough(o).pipeTo(r.writable)}else if(EN()){if("undefined"==typeof RTCRtpScriptTransform)return void FL.warning("browser not support RTCRtpScriptTransform");const r=lx(),o=new MessageChannel;await new dp((e=>r.onmessage=t=>{"registered"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(r,{name:"audio-metadata-tx",port:o.port2},[o.port2]);e.transform=s,await new dp((e=>r.onmessage=t=>{"started"===t.data&&e(void 0)})),o.port1.onmessage=r=>{var s;if(r.data.transformed&&e.track&&(null===(s=e.track)||void 0===s?void 0:s.id)!==n.track.id)FL.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i);else if(r.data.getMetadata){const e=t.metadata&&t.metadata();e&&o.port1.postMessage({metadata:e})}},n.worker=r}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",i)}const t=gx.get(e);if(t){gx.delete(e);try{var n,r;null===(n=t.controller)||void 0===n||n.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){FL.warning(e&&e.message)}}}gx.set(e,n),e.track.addEventListener("ended",i)},interceptRemoteAudioFrame:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!_k().supportWebRTCEncodedTransform)return void FL.warning("browser not support audio encoded transform");if(Fx.has(e))return;const n={track:e.track,onMetadata:t.onMetadata,onPts:t.onPts};if(_N()&&!TN()){if(!e.createEncodedStreams)return void FL.warning("browser not support createEncodedStreams() API");yN(oN.CHROME,87,116)||(t.enableTopn=!1);let r=null;try{r=e.createEncodedStreams()}catch(e){return void FL.error("create audio-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(r,o){n.controller||(n.controller=o),e.track&&e.track.id!==n.track.id&&(FL.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i)),t.enableTopn?function(e,t,n){var i;const r=fx(new DataView(t.data));if(!r)return n.enqueue(t);const o=e.track.id;Bx.set(o,e.track);const s=null===(i=r.tlv.find((e=>e.tag===mx.AUDIO_LEVEL)))||void 0===i?void 0:i.value;let a=0;"number"==typeof s&&(a=127-s);const c=function(e,t){let n=Ox.get(e);if(n||(n=function(e){const t=new Ix;return Ox.set(e,t),Nx||(Nx=new wx(rL("TOPN_SILENCE_THRESHOLD")||500),Nx.on("ActiveSpeakerChanged",(e=>{null!=e&&(Dx=e)}))),Nx.addSpeakers([t]),t}(e)),Ox.size<=Px)return{selected:!0,speaker:n};if(!Nx)throw new Error("no active speaker detector");return Nx.levelChanged(n.id,t),Lx=Nx.loudest.map((e=>e.id)),Dx&&!Vi(Lx).call(Lx,Dx)&&Lx.length>=Px&&Lx.pop(),{selected:Vi(Lx).call(Lx,n.id)||n.id===Dx,speaker:n}}(e,Math.round(Math.pow(10,a/60)-1)),d=c.selected,l=c.speaker,u=function(e,t,n){const i=kx.get(e)||new Vx(e,t);return i.score=n,kx.set(e,i),function(e){if(Mx.set(e,!0),!Ux)return void(Ux=Date.now());const t=Date.now();t-Ux>1e3&&(Mx.get(e)?Mx.set(e,!1):(xx(e),Mx.delete(e)),Ux=t)}(e),i}(o,e.track,l.energyScore);u.addSample(d),u.active&&(t.data=r.frame.buffer,n.enqueue(t))}(e,r,o):t.enableMetadata||t.enablePts?function(e,t,n,i){const r=new DataView(e.data),o=r.getUint8(0);let s;if(0!=(128&o)&&71!==o){const t=function(e){if(e.byteLength<=0)return[];const t=[];let n=0;for(;n<e.byteLength;){const i=(128&e.getUint8(n))>>7,r=127&e.getUint8(n);if(!(i&&n+4<=e.byteLength)){n++;break}{const i=e.getUint32(n,!1),o=(16776192&i)>>10,s=1023&i;t.push({pt:r,ts_offset:o,length:s,data:new Uint8Array}),n+=4}}let i=e.byteLength-n;for(const r of t){if(r.length>i)return console.warn("Broken red payload"),[];r.length>0&&(r.data=new Uint8Array(e.buffer,e.byteOffset+n,r.length),n+=r.length,i-=r.length)}if(i>0){const r={pt:t.length>0?t[t.length-1].pt:0,ts_offset:0,length:i,data:new Uint8Array(e.buffer,e.byteOffset+n,i)};t.push(r)}return t}(r);if(t.length>0){const n=function(e){let t=0;for(let n=0;n<e.length;n++)t+=n<e.length-1?4:1,t+=e[n].length;const n=new Uint8Array(t);let i=0;for(let t=0;t<e.length;t++)if(t<e.length-1){const r=(2147483648|(127&e[t].pt)<<24|(262143&e[t].ts_offset)<<10|1023&e[t].length)>>>0;n[i++]=r>>24&255,n[i++]=r>>16&255,n[i++]=r>>8&255,n[i++]=255&r}else n[i++]=127&e[t].pt;for(const t of e)n.set(t.data,i),i+=t.length;return n}(t.map((e=>{const t=new Uint8Array(e.length);t.set(e.data);const n=fx(new DataView(t.buffer));return null!=n&&n.frame&&(e.data=null==n?void 0:n.frame),s=n,e})));e.data=n.buffer}}else s=fx(r),s&&(e.data=s.frame.buffer);if(t.enqueue(e),!s)return;const a=s.tlv.find((e=>e.tag===mx.METADATA));a&&n&&a.value instanceof Uint8Array&&n(a.value);const c=s.tlv.find((e=>e.tag===mx.AUDIO_64_BIT_PTS));c&&i&&c.value instanceof Uint8Array&&8==c.value.length&&i(new DataView(c.value.buffer).getBigUint64(0,!0))}(r,o,t.onMetadata,t.onPts):o.enqueue(r)}});r.readable.pipeThrough(o).pipeTo(r.writable)}else{if("undefined"==typeof RTCRtpScriptTransform)return void FL.warning("browser not support RTCRtpScriptTransform");const t=lx(),r=new MessageChannel;await new dp((e=>t.onmessage=t=>{"registered"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(t,{name:"audio-metadata-rx",port:r.port2},[r.port2]);e.transform=o,await new dp((e=>t.onmessage=t=>{"started"===t.data&&e(void 0)})),r.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==n.track.id?(FL.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i)):t.data.metadata&&n.onMetadata?n.onMetadata(t.data.metadata):t.data.pts&&n.onPts&&n.onPts(t.data.pts)},n.worker=t}function i(){e.track.removeEventListener("ended",i),function(e){const t=Fx.get(e);if(t){!function(e){const t=Ox.get(e);t&&(Ox.delete(e),Nx&&(Nx.removeSpeakers([t]),0===Ox.size&&(Nx.destroy(),Nx=null)))}(e),xx(e.track.id),Fx.delete(e);try{var n,i;null===(n=t.controller)||void 0===n||n.terminate(),null===(i=t.worker)||void 0===i||i.terminate()}catch(e){FL.warning(e&&e.message)}}}(e)}Fx.set(e,n),e.track.addEventListener("ended",i)},interceptLocalVideoFrame:async function(e,t){if(!_k().supportWebRTCEncodedTransform)return void FL.warning("browser not support video encoded transform");if(Yx.has(e))return;if(!e.track)return;const n={track:e.track};if(_N()){if(!e.createEncodedStreams)return void FL.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(e){return void FL.error("create video-encoded-streams error",e&&e.message)}const o=[];t.on("sei-to-send",(e=>{o.push(e)}));const s=new TransformStream({transform(t,r){n.controller||(n.controller=r),e.track&&e.track.id!==n.track.id&&(FL.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i));const s=Hx(new Uint8Array(t.data)),a=o.shift();if(a){const e=function(e,t,n){switch(n){case jx:return function(e,t){const n=Kx(t),i=n.length,r=Math.floor(i/255),o=i%255,s=new Uint8Array(6+r+1+i+e.byteLength);s[0]=0,s[1]=0,s[2]=0,s[3]=1,s[4]=6,s[5]=101;let a=0;for(;a<r;)s[6+a]=255,a++;return s[6+a]=o,a++,s.set(n,6+a),s.set(new Uint8Array(e),6+a+i),s.buffer}(e,t);case Gx:return function(e,t){const n=Kx(t),i=n.length,r=Math.floor(i/255),o=i%255,s=new Uint8Array(7+r+1+i+1+e.byteLength);s[0]=0,s[1]=0,s[2]=0,s[3]=1,s[4]=78,s[5]=1,s[6]=101;let a=0;for(;a<r;)s[7+a]=255,a++;return s[7+a]=o,a++,s.set(n,7+a),a+=i,s[7+a]=128,a++,s.set(new Uint8Array(e),7+a),s.buffer}(e,t);default:return null}}(t.data,a,s);e&&(t.data=e)}r.enqueue(t)}});r.readable.pipeThrough(s).pipeTo(r.writable)}else{if(!EN())return;{if("undefined"==typeof RTCRtpScriptTransform)return void FL.warning("browser not support RTCRtpScriptTransform");const r=lx(),o=new MessageChannel;await new dp((e=>r.onmessage=t=>{"registered"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(r,{name:"sei-tx",port:o.port2},[o.port2]);e.transform=s,await new dp((e=>r.onmessage=t=>{"started"===t.data&&e(void 0)})),t.on("sei-to-send",(e=>{o.port1.postMessage({sei:e})})),o.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==n.track.id&&(FL.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i))},n.worker=r}}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",i)}const t=Yx.get(e);if(t){Yx.delete(e);try{var n,r;null===(n=t.controller)||void 0===n||n.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){FL.warning(e&&e.message)}}}Yx.set(e,n),e.track.addEventListener("ended",i)},interceptRemoteVideoFrame:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!_k().supportWebRTCEncodedTransform)return void FL.warning("browser not support video encoded transform");if(!e.track)return;if(Xx.has(e)){const n=Xx.get(e);return void(n&&(n.onSei=t.onSei))}const n={track:e.track,onSei:t.onSei};if(_N()){if(!e.createEncodedStreams)return void FL.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(e){return void FL.error("create video-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(r,o){if(n.controller||(n.controller=o),!n.firstFrameInfo){var s;const e=r.getMetadata()||{};n.firstFrameInfo=pM({type:r.type,rtpTimestamp:r.timestamp,payloadType:e.payloadType||0,ssrc:e.synchronizationSource||0,length:r.data.byteLength},"mimeType"in e?{mimeType:e.mimeType}:{}),null===(s=t.onFirstFrame)||void 0===s||s.call(t,n.firstFrameInfo)}e.track&&e.track.id!==n.track.id&&(FL.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i));const a=function(e,t){switch(t){case jx:return function(e){const t=new DataView(e.data);let n=0;for(;n+4<e.data.byteLength;){if(0===t.getUint8(n+0)&&0===t.getUint8(n+1)&&0===t.getUint8(n+2)&&1===t.getUint8(n+3)&&6===t.getUint8(n+4)){let i=n+6,r=0,o=0;for(;255===(o=t.getUint8(i++));)r+=255;r+=o;const s=Wx(e.data,i,r);return new Uint8Array(s)}n++}return null}(e);case Gx:return function(e){const t=new DataView(e.data);let n=0;for(;n+5<e.data.byteLength;){if(0===t.getUint8(n+0)&&0===t.getUint8(n+1)&&0===t.getUint8(n+2)&&1===t.getUint8(n+3)&&78===t.getUint8(n+4)&&1===t.getUint8(n+5)&&101===t.getUint8(n+6)){let i=n+7,r=0,o=0;for(;255===(o=t.getUint8(i++));)r+=255;r+=o;const s=Wx(e.data,i,r);return new Uint8Array(s)}n++}return null}(e);default:return null}}(r,Hx(new Uint8Array(r.data)));a&&n.onSei&&n.onSei(a),o.enqueue(r)}});r.readable.pipeThrough(o).pipeTo(r.writable)}else if(EN()){if("undefined"==typeof RTCRtpScriptTransform)return void FL.warning("browser not support RTCRtpScriptTransform");const r=lx(),o=new MessageChannel;await new dp((e=>r.onmessage=t=>{"registered"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(r,{name:"sei-rx",port:o.port2},[o.port2]);e.transform=s,await new dp((e=>r.onmessage=t=>{"started"===t.data&&e(void 0)})),o.port1.onmessage=r=>{var o;if(r.data.transformed&&e.track&&(null===(o=e.track)||void 0===o?void 0:o.id)!==n.track.id)FL.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i);else if(r.data.sei&&n.onSei)n.onSei(r.data.sei);else if(r.data.firstFrameInfo&&t.onFirstFrame){var s;null===(s=t.onFirstFrame)||void 0===s||s.call(t,r.data.firstFrameInfo)}},n.worker=r}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",i)}!function(e){const t=Xx.get(e);if(t){Xx.delete(e);try{var n,i;null===(n=t.controller)||void 0===n||n.terminate(),null===(i=t.worker)||void 0===i||i.terminate()}catch(e){FL.warning(e&&e.message)}}}(e)}Xx.set(e,n),e.track.addEventListener("ended",i)}},pae={name:"InterceptFrame",create:()=>hae};var _ae;function Eae(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function mae(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Eae(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Eae(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let fae=(_ae=class e extends tB{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!==(e=null===(t=this.peerConnection.getReceivers()[0])||void 0===t||null===(t=t.transport)||void 0===t?void 0:t.state)&&void 0!==e?e:null}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.send.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Vi(t=Object.keys(cL)).call(t,e)})))]}constructor(e,t,n){super(e,t),GA(this,"id",eP(5,"connection-")),GA(this,"store",void 0),GA(this,"peerConnection",void 0),GA(this,"forceTurn",!1),GA(this,"remoteSDP",void 0),GA(this,"initialOffer",void 0),GA(this,"transportEventReceiver",void 0),GA(this,"statsFilter",void 0),GA(this,"extension",{useXR:rL("USE_XR")}),GA(this,"localCapabilities",void 0),GA(this,"remoteCodecs",void 0),GA(this,"localCandidateCount",0),GA(this,"allCandidatesReceived",!1),GA(this,"isPreallocation",!1),GA(this,"preMediaMap",new Map),GA(this,"dataStreamChannelMap",new Map),GA(this,"establishPromise",void 0),GA(this,"recoveredDataChannelIds",[]),GA(this,"currentDataChannelId",1),GA(this,"supportAV1RtpSpec",!1),GA(this,"mutex",void 0),GA(this,"qualityLimitationReason",VP.NONE),GA(this,"isFirstConnected",!1),this.store=t,this.forceTurn=Cne(e),this.mutex=new _P("NVConnectionExtension-mutex",t.clientId),this.peerConnection=n,this.isFirstConnected=!1,this.statsFilter=HP(this.peerConnection,rL("STATS_UPDATE_INTERVAL"),void 0,SN()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,e.isPreallocation&&(this.isPreallocation=!0),this.establishPromise=this.establish()}getPreMedia(e){return this.preMediaMap.get(e)}isPreSub(){return this.preMediaMap.size>0}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void FL.debug("[NVConnectionExtension] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);const n=this.remoteSDP.toString();null==t||t(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}else FL.debug("[NVConnectionExtension] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const t=await this.peerConnection.createOffer();if(!t.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const n=mee(t.sdp),i=await Oee({filterRTX:!rL("USE_PUB_RTX")&&!rL("USE_SUB_RTX"),filterVideoFec:rL("FILTER_VIDEO_FEC"),filterAudioFec:rL("FILTER_AUDIO_FEC"),filterVideoCodec:rL("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:rL("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:rL("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=Pee(i),this.initialOffer=t,rL("ENABLE_SVC")&&"av1"==this.store.codec){const t=await wee();var e;if(t)this.supportAV1RtpSpec=!0,null===(e=i.send)||void 0===e||e.videoExtensions.push(t)}let r;return t.sdp&&Bee(t.sdp)&&(r=GD(i),aee(r)),mae(mae({},n),{},{rtpCapabilities:r||i,offerSDP:t.sdp})}catch(e){throw new zN(JN.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish NVConnectionExtension without initial offer.");if(this.initialOffer.sdp&&Bee(this.initialOffer.sdp)&&cee(e.rtpCapabilities,this.localCapabilities),this.remoteSDP=new rne(mae(mae({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!rL("ENABLE_PRE_SUB_WITH_PRE_PC")||!rL("PRE_USE_LOCAL_CODECS"))&&gk(this.store),!0),e.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec),fk()){var t;const e=(null===(t=this.store.preSubOptions)||void 0===t?void 0:t.length)||0,n=rL("PRE_SUB_NUM")||1,i=e>n?e:n,r=this.remoteSDP.preloadRemoteMedia(i),o=r.mids,s=r.preSSRCs,a=Vee(this.initialOffer.sdp,this.extension),c=this.logSDPExchange(a||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:a}),null==c||c(a),new Array(i).fill(0).forEach((()=>{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})}));const d=await this.peerConnection.createOffer(),l=this.logSDPExchange(d.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(d);const u=this.remoteSDP.toString();null==l||l(u),await this.peerConnection.setRemoteDescription({type:"answer",sdp:u}),FL.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media with icc/dtls, add preload ssrcs ").concat(s)),this.presetMedia(o,s);const h=this.peerConnection.getTransceivers()[0];null!=h&&h.receiver&&this.tryBindTransportEvents(h.receiver)}else{const t=this.remoteSDP.toString(),i=Vee(this.initialOffer.sdp,this.extension),r=this.logSDPExchange(i||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==r||r(t),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t});const o=this.peerConnection.getTransceivers()[0];if(null!=o&&o.receiver&&this.tryBindTransportEvents(o.receiver),gk(this.store))if(e.preallocation&&rL("ENABLE_PRE_SUB_WITH_PRE_PC")){var n;const e=(null===(n=this.store.preSubOptions)||void 0===n?void 0:n.length)||0,t=rL("PRE_SUB_NUM")||1,i=e>t?e:t,r=this.remoteSDP.preloadRemoteMedia(i),o=r.mids,s=r.preSSRCs;await Uee(this.peerConnection,this.remoteSDP,this.extension),FL.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(s)),this.presetMedia(o,s)}else{const t=e.preSSRCs,n=void 0===t?[]:t,i=n.map((e=>e.ssrcMsg[0].ssrcId));if(0===n.length)return;const r=this.remoteSDP.batchSend(n.map((e=>Object.assign({},e)))).mids;await Uee(this.peerConnection,this.remoteSDP,this.extension),FL.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(i)),this.presetMedia(r,i)}}}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.connect failed; ".concat(e.toString()))}}presetMedia(e,t){e.forEach(((e,n)=>{this.peerConnection.getTransceivers().forEach((i=>{if(null!=i.mid&&e===i.mid&&i.receiver.track){const r=i.receiver.track;let o;"video"===r.kind&&rL("ENABLE_PRE_RENDER")&&(o=new tV({trackId:"track-".concat(r.kind,"-unknown-").concat(this.store.clientId,"_").concat(eP(5,""))},!0),o.updateVideoTrack(r),o.onFirstVideoFrameRender=()=>{var e;const i=this.preMediaMap.get(t[n]);i&&(i.firstVideoRender=Date.now()),null===(e=this.onFirstVideoRender)||void 0===e||e.call(this,t[n])},o.onVideoBufferReady=()=>{var e;null===(e=this.onFirstVideoBufferReady)||void 0===e||e.call(this,t[n])},o.play(this.store.sessionId||void 0)),this.preMediaMap.set(t[n],{mid:e,track:r,player:o,transceiver:i})}})),this.store.peerReceiver()}))}checkDtlsParameters(e){return!!this.remoteSDP&&(e.length>0&&this.remoteSDP.updateRemoteDtlsParameters(e))}checkIceParameters(e){if(!this.remoteSDP)return!1;return this.remoteSDP.restartICE(e)}async updateRemoteConnect(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.updateRemoteConnect before remote SDP created");let t=!1;const n=e.rtpCapabilities;if(t=Hb(this.remoteSDP.updateRemoteRTPCapabilities(n),2)[1],Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);t=t||e}const i=e.preSSRCs,r=void 0===i?[]:i,o=r.map((e=>e.ssrcMsg[0].ssrcId));if(!this.remoteSDP.checkPreloadSsrcs(o)){const e=[],t=[];if(Array.from(this.preMediaMap.entries()).every((n=>{let i=Hb(n,2),r=i[0],o=i[1],s=o.mid,a=o.player;o.track;return e.push(s),t.push(r),this.preMediaMap.delete(r),a&&a.destroy(),!0})),e.length>0&&(this.remoteSDP.stopSending(e),await Uee(this.peerConnection,this.remoteSDP,this.extension),FL.warn("[NVConnectionExtension.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(t)),uk.reportApiInvoke(this.store.sessionId,{name:ED.PRELOAD_MEDIA_FAILED,options:[r,t],tag:mD.TRACER}).onSuccess()),r.length>0){const e=this.remoteSDP.batchSend(r.map((e=>Object.assign({},e)))).mids;await Uee(this.peerConnection,this.remoteSDP,this.extension),FL.debug("[NVConnectionExtension.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(o)),this.presetMedia(e,o)}}t?(await Uee(this.peerConnection,this.remoteSDP,this.extension),FL.debug("[NVConnectionExtension] updateRemoteConnect by exchanging SDP.")):FL.debug("[NVConnectionExtension] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,n){var i=this;return mO((function*(){const r=yield gO(i.mutex.lock("From NVConnectionExtension.send"));try{if(!i.remoteSDP)throw new Error("Cannot call NVConnectionExtension.send before remote SDP created");const o=[],s=oee();e.forEach((e=>{const t=i.peerConnection.addTransceiver(e._mediaStreamTrack,mae({direction:"sendonly"},"video"===e.trackMediaType&&i.supportAV1RtpSpec&&s?{sendEncodings:[{scalabilityMode:s}]}:{}));o.push(t),e._updateRtpTransceiver(t)})),SN()&&!0===rL("SIMULCAST")&&(yield gO(i.applySimulcastForFirefox(o,e)));const a=yield gO(i.peerConnection.createOffer()),c=i.remoteSDP.predictReceivingMids(e.length),d=i.mungSendOfferSDP(a.sdp,e,c),l=EL(d),u=c.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return fee(t,rL("USE_PUB_RTX"))}));let h;try{h=yield u}catch(r){h=[],i.remoteSDP.receive(e,t,n,h);const o=i.remoteSDP.toString();throw yield gO(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield gO(i.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield gO(i.stopSending(c,!0)),r}i.remoteSDP.receive(e,t,n,h);const p=i.remoteSDP.toString(),_=i.logSDPExchange(d,"offer","local","send");return yield gO(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield gO(i.applySimulcastEncodings(o,e)),yield gO(i.applySendEncodings(o,e)),null==_||_(p),yield gO(i.peerConnection.setRemoteDescription({type:"answer",sdp:p})),o.map(((e,t)=>{const n=c[t];return{localSSRC:u[t],id:n,transceiver:e}}))}catch(e){throw e instanceof zN?e:new zN(JN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.send failed; ".concat(e.toString()))}finally{r()}}))()}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.createDataChannels before remote SDP created");let n=this.dataStreamChannelMap.get(e);if(n&&"open"===n.readyState)FL.debug("[NVConnectionExtension] Channels are already available and can be reused directly.");else{const t=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if("number"!=typeof t)throw new Error("create DataChannel error, because cannot get dc id");n=this.peerConnection.createDataChannel("datastream-channel",{id:t,negotiated:!0,ordered:!1,maxRetransmits:rL("DATASTREAM_MAX_RETRANSMITS")}),n.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,n)}t.forEach((e=>{e._updateOriginDataChannel(n)}));const i=this.remoteSDP.sendDataChannel();if(i.needExchangeSDP){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),FL.debug("[NVConnectionExtension] createDataChannels by exchanging SDP.")}else FL.debug("[NVConnectionExtension] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof zN?e:new zN(JN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.createDataChannels failed; ".concat(e.toString()))}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return t&&(t.id&&this.recoveredDataChannelIds.push(t.id),t.close()),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof zN?e:new zN(JN.DATACHANNEL_FAILED,"NVConnectionExtension.stopDataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){const n=t?void 0:await this.mutex.lock("From NVConnectionExtension.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call NVConnectionExtension.stopSending.");t.map((e=>{var t;gne(this.id+e.mid,this),e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==r||r(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.stopSending failed; ".concat(e.toString()))}finally{n&&n()}}async receive(e,t,n,i){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.receive ".concat(e," before remoteSDP created."));const r=this.remoteSDP.send(e,t,n,i),o=r.mid;r.needExchangeSDP&&(await Uee(this.peerConnection,this.remoteSDP,this.extension),FL.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] receive ").concat(e," by exchanging SDP.")));const s=this.peerConnection.getTransceivers().find((e=>e.mid===o));if(!s)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:s.receiver.track,id:o,transceiver:s}}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e),n=t.mids;return t.needExchangeSDP&&(await Uee(this.peerConnection,this.remoteSDP,this.extension),FL.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] batchReceive by exchanging SDP."))),n.map((e=>{const t=this.peerConnection.getTransceivers().find((t=>t.mid===e));if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:t.receiver.track,id:e,transceiver:t}}))}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.stopReceiving before remote SDP created.");e.forEach((e=>{Array.from(this.preMediaMap.entries()).some((t=>{let n=Hb(t,2),i=n[0],r=n[1],o=r.mid,s=r.player;if(o===e)return this.preMediaMap.delete(i),s&&s.destroy(),!0}))})),this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"NVConnectionExtension stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==i||i(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((async(e,t)=>{e.direction="sendonly"}));const n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.unmuteRemote(e),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(e,this.remoteCodecs,this.store.codec);const r=this.remoteSDP.toString();null==i||i(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return mO((function*(){const n=yield gO(t.mutex.lock("From NVConnectionExtension.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const i=_k().supportPCSetConfiguration,r=rL("FORCE_TURN_TCP")||t.forceTurn;if(e===iB.RELAY&&!i)return;if(i&&!r){const n=e===iB.RELAY?"relay":"all",i=t.peerConnection.getConfiguration();i.iceTransportPolicy!==n&&(FL.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}t.remoteSDP.updateCandidates(e);const o=yield gO(t.peerConnection.createOffer({iceRestart:!0}));if(!o.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const s=mee(o.sdp),a=(yield s.iceParameters).remoteIceParameters;t.remoteSDP.restartICE(a);const c=t.remoteSDP.toString(),d=t.logSDPExchange(o.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield gO(t.peerConnection.setLocalDescription(o)),null==d||d(c),yield gO(t.peerConnection.setRemoteDescription({type:"answer",sdp:c}))}catch(e){FL.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{n()}}))()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const e=await this.mutex.lock("From NVConnectionExtension.extendCandidate");try{this.remoteSDP.updateCandidates(iB.TCP_RELAY),await Uee(this.peerConnection,this.remoteSDP,this.extension)}catch(e){FL.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e;this.peerConnection.getTransceivers().forEach((e=>{gne(this.id+e.mid,this)})),this.preMediaMap.forEach((e=>{let t=e.player;t&&t.destroy()})),this.preMediaMap.clear(),this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1}getStats(){return mae(mae({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason})}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.updateEncoderConfig before remote SDP created.");const n=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(n.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(i,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new zN(JN.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const n=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===n.length&&(this.isVP8Simulcast(t)?SN()||await this.applySimulcastEncodings(n,[t]):await this.applySendEncodings(n,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const n=this.peerConnection.getTransceivers().find((e=>e.mid===t));n&&await n.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport.getSelectedCandidatePair(),n=t.local,i=t.remote;return{local:mae(mae({},OP),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port}),remote:mae(mae({},OP),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.isFirstConnected=!0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidateerror=e=>{if(e&&(e.errorCode||e.errorText)){var t;const n="code: ".concat(e.errorCode,", message: ").concat(e.errorText),i=e.port?"local: ".concat(e.port):"",r=iee(e.url||"");FL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: NVConnectionExtension.onICECandidateError(").concat(n,"), url: ").concat(r||"",", host_candidate:").concat(i)),null===(t=this.onICECandidateError)||void 0===t||t.call(this,n)}},this.peerConnection.onicegatheringstatechange=e=>{e&&e.target&&"iceGatheringState"in e.target&&FL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] RTCPeerConnection.onicegatheringstatechange(").concat(e.target.iceGatheringState,")"))},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,FL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,FL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),rL("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const n={iceServers:[]},i=t.cloudProxyServer||"disabled";return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&(TD(t.turnServer.servers)?n.iceServers=t.turnServer.servers:rL("NEW_TURN_MODE")&&n.iceServers&&"disabled"===i?(rL("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&n.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):n.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),rL("NEW_FORCE_TURN")&&(n.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(n.iceServers&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),rL("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),rL("FORCE_TURN_TCP")?n.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(n.iceTransportPolicy="relay")})))),rL("ENABLE_ENCODED_TRANSFORM")&&_k().supportWebRTCEncodedTransform&&(n.encodedInsertableStreams=!0),n}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(X7(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!rL("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}static newTurnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{const n=rL("NEW_TURN_MODE");1===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}):2===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}):3===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(X7(e.turnServerURL),":443?transport=tcp")}):4===n&&(t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(X7(e.turnServerURL),":443?transport=tcp")}))})),t}tryBindTransportEvents(e){const t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,t.state))},t.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const n=t.iceTransport;n&&(n.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var n;e&&(null===(n=this.onICETransportStateChange)||void 0===n||n.call(this,e))},n.getSelectedCandidatePair&&(n.onselectedcandidatepairchange=()=>{if(n.getSelectedCandidatePair()){const e=n.getSelectedCandidatePair()||{},t=e.local,i=e.remote;if(t&&i){const e=t.address+":"+t.port,n=i.address+":"+i.port;FL.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(iee(e)),", remote ").concat(JSON.stringify(iee(n))))}}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var n,i;if(!t){const n=this.peerConnection.getSenders();t=n.find((t=>t.track===e._mediaStreamTrack))}if(!t)return FL.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return FL.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!_k().supportSetRtpSenderParameters)return FL.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const r={},o={};switch(e._optimizationMode){case"motion":r.degradationPreference="maintain-framerate";break;case"detail":r.degradationPreference="maintain-resolution";break;case"balanced":r.degradationPreference="balanced"}const s=ree(this.peerConnection,e._mediaStreamTrack),a=nU(e);if(Ene(e)&&s&&t&&a&&this.getLocalVideoStats&&Vi(n=["vp8","vp9"]).call(n,this.store.codec)){var c;const n=r.degradationPreference||(Vi(c=e._hints).call(c,jk.CUSTOM_TRACK)?rL("CUSTOM_ADAPTATION_DEFAULT_MODE"):"maintain-framerate");fne(this.id+s.mid,a,this,n,(e=>{t&&this.updateAdaptation(t,e)}),this.getLocalVideoStats.bind(this))}if(e._encoderConfig){var d;const t=e._encoderConfig,n=t.bitrateMax,i=t.frameRate,r=t.scaleResolutionDownBy;n&&(o.maxBitrate=1e3*n),(Vi(d=e._hints).call(d,jk.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(o.maxFramerate=Z7(i)),r&&r>=1&&(o.scaleResolutionDownBy=r))}const l=rL("ENCODER_CONFIG_LIMIT").maxFramerate;if(l&&"number"==typeof l&&(o.maxFramerate=o.maxFramerate?Math.min(o.maxFramerate,l):l),rL("DSCP_TYPE")&&FN()){var u;const e=rL("DSCP_TYPE");Vi(u=["very-low","low","medium","high"]).call(u,e)&&(o.networkPriority=e)}const h=t.getParameters(),p=null===(i=h.encodings)||void 0===i?void 0:i[0];SN()&&!p&&(r.encodings=[o]),p&&Object.assign(p,o),Object.assign(h,r),FL.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(h.encodings))),await t.setParameters(h),await Fee(this.store.codec,t,rL("SVC_MODE"))}async updateAdaptation(e,t){var n,i;if(!e)return FL.debug("[updateAdaptation] no rtpSender found");if(!_k().supportSetRtpSenderParameters)return FL.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const r={},o=t.bitrateMax,s=t.frameRate,a=t.scaleResolutionDownBy;o&&(r.maxBitrate=1e3*o),s&&(r.maxFramerate=Z7(s)),a&&a>=1&&Vi(n=["vp8","vp9"]).call(n,this.store.codec)&&(r.scaleResolutionDownBy=a);const c=e.getParameters(),d=null===(i=c.encodings)||void 0===i?void 0:i[0];d&&Object.assign(d,r),Object.assign(c,{});try{await e.setParameters(c),FL.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(c.encodings)))}catch(t){!("transport"in e)||e.transport&&"connected"===e.transport.state?"connected"!==this.peerConnectionState?FL.debug("[updateAdaptation] peerConnection not connected}"):FL.debug("[updateAdaptation] updateRtpSenderEncodings failed",t):FL.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(e,t){try{if(!_k().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let n=0;n<e.length;n++){const i=e[n],r=t[n];r instanceof BV&&!this.isVP8Simulcast(r)&&await this.updateRtpSenderEncodings(r,i.sender)}}catch(e){FL.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,n){const i=EL(e);return t.forEach(((e,t)=>{const r=n[t],o=i.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(vee(o,e),Aee(o,e,this.store.codec))})),mL(i)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,n)=>{var i;null===(i=this.onFirstVideoDecoded)||void 0===i||i.call(this,e,t,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedLocalCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a<e.length;a++){var n,i,r,o,s;const c=e[a],d=t[a];if(d instanceof BV&&!Vi(n=d._hints).call(n,jk.LOW_STREAM)&&null!==(i=d._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(r=d._encoderConfig)||void 0===r?void 0:r.bitrateMax)>200&&null!==(o=d._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(s=d._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const n=c.sender.getParameters();await c.sender.setParameters(Object.assign(n,e))}}}async applySimulcastEncodings(e,t){if(!SN()&&e.length===t.length)for(let n=0;n<e.length;n++){const i=t[n];if(i instanceof BV&&this.isVP8Simulcast(i)){const t=e[n],r={},o={high:1e3*(i._encoderConfig.bitrateMax-50),medium:5e4};r.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:o.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:o.medium,scaleResolutionDownBy:4}];const s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,r))}}}isVP8Simulcast(e){var t,n,i,r,o;return!!(e instanceof BV&&rL("SIMULCAST")&&"vp8"===this.store.codec&&!Vi(t=e._hints).call(t,jk.LOW_STREAM)&&null!==(n=e._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(i=e._encoderConfig)||void 0===i?void 0:i.bitrateMax)>200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(o=e._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,n,i){if(rL("SDP_LOGGING"))return FL.upload("[".concat(this.store.clientId,"] exchanging ").concat(n," ").concat(t," SDP during NVConnectionExtension.").concat(i,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===n?"remote":"local",i)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return t&&0!==t.length?t[0].ssrcId:void 0}setConfiguration(t){if(_k().supportPCSetConfiguration){const n=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(n)}t.isPreallocation&&(this.isPreallocation=!0)}},mF(_ae.prototype,"updateRemoteRTPCapabilities",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"updateRemoteRTPCapabilities"),_ae.prototype),mF(_ae.prototype,"connect",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"connect"),_ae.prototype),mF(_ae.prototype,"updateRemoteConnect",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"updateRemoteConnect"),_ae.prototype),mF(_ae.prototype,"createDataChannels",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"createDataChannels"),_ae.prototype),mF(_ae.prototype,"receive",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"receive"),_ae.prototype),mF(_ae.prototype,"batchReceive",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"batchReceive"),_ae.prototype),mF(_ae.prototype,"stopReceiving",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"stopReceiving"),_ae.prototype),mF(_ae.prototype,"muteRemote",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"muteRemote"),_ae.prototype),mF(_ae.prototype,"unmuteRemote",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"unmuteRemote"),_ae.prototype),mF(_ae.prototype,"muteLocal",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"muteLocal"),_ae.prototype),mF(_ae.prototype,"unmuteLocal",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"unmuteLocal"),_ae.prototype),mF(_ae.prototype,"close",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"close"),_ae.prototype),mF(_ae.prototype,"updateEncoderConfig",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"updateEncoderConfig"),_ae.prototype),mF(_ae.prototype,"updateSendParameters",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"updateSendParameters"),_ae.prototype),mF(_ae.prototype,"replaceTrack",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"replaceTrack"),_ae.prototype),mF(_ae.prototype,"updateAdaptation",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"updateAdaptation"),_ae.prototype),mF(_ae.prototype,"getRemoteSSRC",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"getRemoteSSRC"),_ae.prototype),_ae);function gae(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=await e.lock("From NVConnectionExtension.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await i.apply(this,o)}finally{n()}},n}var Sae;function Tae(e){var t,n,i,r=2;for("undefined"!=typeof Symbol&&(n=TO,i=Symbol.iterator);r--;){if(n&&null!=(t=e[n]))return t.call(e);if(i&&null!=(t=e[i]))return new Rae(t.call(e));n="@@asyncIterator",i="@@iterator"}throw new TypeError("Object is not async iterable")}function Rae(e){function t(e){if(Object(e)!==e)return dp.reject(new TypeError(e+" is not an object."));var t=e.done;return dp.resolve(e.value).then((function(e){return{value:e,done:t}}))}return Rae=function(e){this.s=e,this.n=e.next},Rae.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return void 0===n?dp.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return void 0===n?dp.reject(e):t(n.apply(this.s,arguments))}},new Rae(e)}let vae=(Sae=class e extends tB{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get localCodecs(){return this._p2pConnection.localCodecs}constructor(t,n){super(t,n),GA(this,"name","DataChannelConnection"),GA(this,"store",void 0),GA(this,"peerConnection",void 0),GA(this,"cname",void 0),GA(this,"mutex",new _P("DataChannelConnection-mutex")),GA(this,"dataChannel",void 0),GA(this,"_p2pConnection",void 0),GA(this,"establishPromise",void 0),GA(this,"_nvMedia",void 0),this.store=n,this.store.dcId=this.store.dcId+1,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.dataChannel=this.peerConnection.createDataChannel("agora-signal",{ordered:!1,maxPacketLifeTime:50}),this.dataChannel.binaryType="arraybuffer",this._p2pConnection=new fae(t,n,this.peerConnection),this.bindPCEvents(),this.establishPromise=this._p2pConnection.establishPromise}getPreMedia(e){var t;return null===(t=this._p2pConnection)||void 0===t?void 0:t.getPreMedia(e)}isPreSub(){var e,t;return null!==(e=null===(t=this._p2pConnection)||void 0===t?void 0:t.isPreSub())&&void 0!==e&&e}async establish(){return await this._p2pConnection.establish()}getP2PConnectionParams(){return this._p2pConnection.establishPromise}updateRtpSenderEncodings(e){return this._p2pConnection.updateRtpSenderEncodings(e)}async connect(e){return this.cname=e.cname,await this._p2pConnection.connect(e),await new dp(((t,n)=>{const i=setTimeout((()=>{this.closeSignal(),n(new hk(JN.DATACHANNEL_CONNECTION_TIMEOUT,"Datachannel connection timed out, candidates: ".concat(JSON.stringify(e.candidates))))}),rL("DC_CONNECTION_TIMEOUT"));this.dataChannel.onopen=()=>{if("open"===this.dataChannel.readyState)return clearTimeout(i),void t()},this.dataChannel.onerror=e=>{this.closeSignal(),n(e)},this.dataChannel.addEventListener("close",(()=>{n(new hk(JN.DATACHANNEL_CONNECTION_TIMEOUT))}))})),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)}}checkDtlsParameters(e){return this._p2pConnection.checkDtlsParameters(e)}checkIceParameters(e){return this._p2pConnection.checkIceParameters(e)}async updateRemoteRTPCapabilities(e,t){return this._p2pConnection.updateRemoteRTPCapabilities(e,t)}send(e,t,n){var i=this;return mO((function*(){const r=yield gO(i.mutex.lock("From DataChannelConnection.send"));try{return yield*SO(Tae(i._p2pConnection.send(e,t,n)))}finally{r()}}))()}async stopSending(e,t){return this._p2pConnection.stopSending(e,t)}async createDataChannels(e,t){return this._p2pConnection.createDataChannels(e,t)}async stopDataChannels(e){return this._p2pConnection.stopDataChannels(e)}async receive(e,t,n,i){return this._nvMedia?(FL.debug("[DataChannelConnection] receive ".concat(e," by DataChannel.")),await this._nvMedia.reveiveByRTCMedia(e,t,this.cname)):(FL.debug("[DataChannelConnection] receive ".concat(e," by WebRTC.")),await this._p2pConnection.receive(e,t,n,i))}async batchReceive(e){return[...await this._p2pConnection.batchReceive(e)]}async stopReceiving(e){return await this._p2pConnection.stopReceiving(e)}async muteRemote(e){return await this._p2pConnection.muteRemote(e)}async unmuteRemote(e){return await this._p2pConnection.unmuteRemote(e)}async muteLocal(e){return await this._p2pConnection.muteLocal(e)}async unmuteLocal(e){return await this._p2pConnection.unmuteLocal(e)}restartICE(e){var t=this;return mO((function*(){return yield*SO(Tae(t._p2pConnection.restartICE(e)))}))()}close(){var e;null===(e=this._nvMedia)||void 0===e||e.close(),this._p2pConnection.close(),this.unbindConnectionEvents(this._p2pConnection)}getStats(){return this._p2pConnection.getStats()}getRemoteVideoIsReady(e){return this._p2pConnection.getRemoteVideoIsReady(e)}updateRemoteConnect(e){var t;return null===(t=this._nvMedia)||void 0===t||t.setRemoteRtpCapabilities(e),this._p2pConnection.updateRemoteConnect(e)}async updateEncoderConfig(e,t){return await this._p2pConnection.updateEncoderConfig(e,t)}async updateSendParameters(e,t){return await this._p2pConnection.updateSendParameters(e,t)}setStatsRemoteVideoIsReady(e,t){this._p2pConnection.setStatsRemoteVideoIsReady(e,t)}async replaceTrack(e,t){return await this._p2pConnection.replaceTrack(e,t)}async getRemoteSSRC(e){return this._p2pConnection.getRemoteSSRC(e)}logSDPExchange(e,t,n,i){if(rL("SDP_LOGGING"))return FL.upload("exchanging ".concat(n," ").concat(t," SDP during DataChannelConnection.").concat(i,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===n?"remote":"local",i)}:void 0}static resolvePCConfiguration(t){const n={iceServers:[]};return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(TD(t.turnServer.servers)?n.iceServers=t.turnServer.servers:(n.iceServers&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),rL("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),rL("FORCE_TURN_TCP")?n.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(n.iceTransportPolicy="relay")})))),rL("ENABLE_ENCODED_TRANSFORM")&&_k().supportWebRTCEncodedTransform&&(n.encodedInsertableStreams=!0),n}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(X7(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!rL("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}bindPCEvents(){this._p2pConnection.onICEConnectionStateChange=e=>{var t;return null===(t=this.onICEConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onConnectionStateChange=e=>{var t;return null===(t=this.onConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportStateChange=e=>{var t;return null===(t=this.onDTLSTransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportError=e=>{var t;return null===(t=this.onDTLSTransportError)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onICETransportStateChange=e=>{var t;return null===(t=this.onICETransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioReceived=e=>{var t;return null===(t=this.onFirstAudioReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoReceived=e=>{var t;return null===(t=this.onFirstVideoReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioDecoded=e=>{var t;return null===(t=this.onFirstAudioDecoded)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoRender=e=>{var t;return null===(t=this.onFirstVideoRender)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoBufferReady=e=>{var t;return null===(t=this.onFirstVideoBufferReady)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoDecoded=(e,t,n)=>{var i;return null===(i=this.onFirstVideoDecoded)||void 0===i?void 0:i.call(this,e,t,n)},this._p2pConnection.onFirstVideoDecodedTimeout=e=>{var t;return null===(t=this.onFirstVideoDecodedTimeout)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onSelectedLocalCandidateChanged=(e,t)=>{var n;return null===(n=this.onSelectedLocalCandidateChanged)||void 0===n?void 0:n.call(this,e,t)},this._p2pConnection.onSelectedRemoteCandidateChanged=(e,t)=>{var n;return null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n?void 0:n.call(this,e,t)}}closeSignal(){this.dataChannel.close(),this.peerConnection.close()}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0}setConfiguration(e){this._p2pConnection.setConfiguration(e)}},mF(Sae.prototype,"connect",[yae],Object.getOwnPropertyDescriptor(Sae.prototype,"connect"),Sae.prototype),mF(Sae.prototype,"updateRemoteRTPCapabilities",[yae],Object.getOwnPropertyDescriptor(Sae.prototype,"updateRemoteRTPCapabilities"),Sae.prototype),mF(Sae.prototype,"createDataChannels",[yae],Object.getOwnPropertyDescriptor(Sae.prototype,"createDataChannels"),Sae.prototype),mF(Sae.prototype,"receive",[yae],Object.getOwnPropertyDescriptor(Sae.prototype,"receive"),Sae.prototype),mF(Sae.prototype,"stopReceiving",[yae],Object.getOwnPropertyDescriptor(Sae.prototype,"stopReceiving"),Sae.prototype),mF(Sae.prototype,"muteRemote",[yae],Object.getOwnPropertyDescriptor(Sae.prototype,"muteRemote"),Sae.prototype),mF(Sae.prototype,"unmuteRemote",[yae],Object.getOwnPropertyDescriptor(Sae.prototype,"unmuteRemote"),Sae.prototype),mF(Sae.prototype,"muteLocal",[yae],Object.getOwnPropertyDescriptor(Sae.prototype,"muteLocal"),Sae.prototype),mF(Sae.prototype,"unmuteLocal",[yae],Object.getOwnPropertyDescriptor(Sae.prototype,"unmuteLocal"),Sae.prototype),mF(Sae.prototype,"close",[yae],Object.getOwnPropertyDescriptor(Sae.prototype,"close"),Sae.prototype),mF(Sae.prototype,"updateEncoderConfig",[yae],Object.getOwnPropertyDescriptor(Sae.prototype,"updateEncoderConfig"),Sae.prototype),mF(Sae.prototype,"updateSendParameters",[yae],Object.getOwnPropertyDescriptor(Sae.prototype,"updateSendParameters"),Sae.prototype),mF(Sae.prototype,"replaceTrack",[yae],Object.getOwnPropertyDescriptor(Sae.prototype,"replaceTrack"),Sae.prototype),mF(Sae.prototype,"getRemoteSSRC",[yae],Object.getOwnPropertyDescriptor(Sae.prototype,"getRemoteSSRC"),Sae.prototype),Sae);function yae(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=await e.lock("From DataChannelConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await i.apply(this,o)}finally{n()}},n}function bae(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}class Cae extends hD{get url(){return this._url?this._url:null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;Vi(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(pB.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(pB.CONNECTED):"closed"===this._state?this.emit(pB.CLOSED):"failed"===this._state&&this.emit(pB.FAILED))}constructor(e,t,n,i){super(),GA(this,"connectionID",0),GA(this,"currentURLIndex",0),GA(this,"reconnectReason",void 0),GA(this,"_reconnectMode","tryNext"),GA(this,"_initMutex",void 0),GA(this,"_name",void 0),GA(this,"_state","closed"),GA(this,"_reconnectInterrupter",void 0),GA(this,"_url",void 0),GA(this,"_retryConfig",void 0),GA(this,"_reconnectCount",0),GA(this,"_forceCloseTimeout",5e3),GA(this,"_onlineReconnectListener",void 0),GA(this,"_closeEstablishingTransmitter",(()=>{})),GA(this,"_store",void 0),GA(this,"_joinChannelServiceRecordIndex",void 0),GA(this,"_transmitter",void 0),GA(this,"_useCompress",void 0),GA(this,"_inflateLength",0),GA(this,"_deflateLength",0),this._store=i,this._name=e,this._retryConfig=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?bae(Object(n),!0).forEach((function(t){GA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):bae(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},t),this._useCompress=n}resetReconnectCount(e){FL.debug("".concat(this._name," reset reconnect count, reason: ").concat(e)),this._reconnectCount=0}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this._reconnectInterrupter&&this._reconnectInterrupter(),this._transmitter){this._transmitter.onclose=null,this._transmitter.onopen=null,this._transmitter.onmessage=null;const e=this._transmitter;t?setTimeout((()=>e.close()),500):e.close(),this._transmitter=void 0}this.state=e?"failed":"closed",this._closeEstablishingTransmitter&&this._closeEstablishingTransmitter()}reconnect(e,t){if(!this._transmitter)return void FL.warning("[".concat(this._name,"] can not reconnect, no websocket"));var n;(void 0!==e&&(this.reconnectMode=e),FL.debug("[".concat(this._name,"] reconnect is triggered initiative")),"number"==typeof this._joinChannelServiceRecordIndex)&&(null===(n=this._store)||void 0===n||n.recordJoinChannelService({status:"error",errors:[new Error(t)]},this._joinChannelServiceRecordIndex));const i=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),i&&i.bind(this._transmitter)({code:9999,reason:t})}getInflateData(){const e=this._inflateLength,t=this._deflateLength;return this.clearInflateData(),{inflateLength:e,deflateLength:t}}setInflateData(e){this._deflateLength=this._deflateLength+e.originLength,this._inflateLength=this._inflateLength+e.compressedLength}clearInflateData(){this._inflateLength=0,this._deflateLength=0}}let Iae=function(e){return e[e.Default=0]="Default",e[e.Ack=1]="Ack",e}({});class Aae{constructor(e,t,n){GA(this,"version",1),GA(this,"initialRTO",void 0),GA(this,"maxBatchAckCount",void 0),GA(this,"maxRTO",void 0),GA(this,"initialRTT",void 0),GA(this,"ID",void 0),GA(this,"rtt",void 0),GA(this,"packetNumber",1),GA(this,"rtoRatioMap",new Map),GA(this,"timeoutMap",new Map),GA(this,"unorderedPacketQueue",[]),GA(this,"batchAckPacketQueue",[]),GA(this,"lastOrderedPacketNumber",0),GA(this,"batchAckTimer",void 0),GA(this,"sendImpl",void 0),GA(this,"receiveImpl",void 0),this.sendImpl=e,this.receiveImpl=t,this.ID=eP(7,"transmitter-"),this.initialRTO=void 0!==(null==n?void 0:n.initialRTO)?n.initialRTO:rL("TRANSMITTER_INITIAL_RTO"),this.initialRTT=void 0!==(null==n?void 0:n.initialRTT)?n.initialRTT:rL("TRANSMITTER_INITIAL_RTT"),this.rtt=void 0!==(null==n?void 0:n.initialRTT)?n.initialRTT:rL("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=void 0!==(null==n?void 0:n.maxBatchAckCount)?n.maxBatchAckCount:rL("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=void 0!==(null==n?void 0:n.maxRTO)?n.maxRTO:rL("TRANSMITTER_MAX_RTO")}packetize(e,t){return{type:Iae.Default,version:this.version,packetNumber:t,payload:e}}serialize(e){switch(e.type){case Iae.Default:{let t;if("string"==typeof e.payload){t=(new TextEncoder).encode(e.payload)}else t=e.payload;const n=new ArrayBuffer(t.length+15),i=new DataView(n);i.setUint16(0,e.version),i.setUint8(2,e.type),i.setUint32(3,e.packetNumber),oD(i,7,BigInt(e.sendTs));return new Uint8Array(i.buffer).set(t,15),n}case Iae.Ack:{const t=new ArrayBuffer(16),n=new DataView(t);return n.setUint16(0,e.version),n.setUint8(2,e.type),n.setUint32(3,e.maxAckPacketNumber),n.setUint8(7,e.shift),oD(n,8,BigInt(e.ackSendTs)),t}}}deserialize(e){const t=new DataView(e),n=t.getUint16(0),i=t.getUint8(2);switch(i){case Iae.Default:{const r=t.getUint32(3),o=rD(t,7),s=e.slice(15),a=new Uint8Array(s);return{version:n,type:i,packetNumber:r,sendTs:Number(o),payload:a}}case Iae.Ack:{const e=t.getUint32(3),r=t.getUint8(7),o=rD(t,8);return{version:n,type:i,maxAckPacketNumber:e,shift:r,ackSendTs:Number(o)}}default:throw FL.error("[".concat(this.ID,"] Unrecognized packet type ").concat(i)),new Error("Unrecognized packet type ".concat(i))}}sendMessage(e){rL("DC_DEBUG_LOG")&&"string"==typeof e&&FL.debug("[".concat(this.ID,"] sending message packet"),JSON.parse(e));const t=this.packetize(e,this.packetNumber);this.packetNumber=4294967295===this.packetNumber?1:this.packetNumber+1;const n=this.calculateRTO(t),i=window.setTimeout((()=>{this.resendMessage(t)}),n);this.timeoutMap.set(t.packetNumber,i),this.sendPacket(t)}onData(e){const t=this.deserialize(e);t.type===Iae.Default?this.ack(t):t.type===Iae.Ack&&(this.updateRTT(t,Math.round(performance.now())),this.clearRTO(t))}close(){this.rtt=this.initialRTT,this.packetNumber=1,Array.from(this.timeoutMap.entries()).forEach((e=>{let t=Hb(e,2);t[0];let n=t[1];window.clearTimeout(n)})),this.timeoutMap=new Map,this.rtoRatioMap=new Map,this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,void 0!==this.batchAckTimer&&window.clearTimeout(this.batchAckTimer)}resendMessage(e){const t=this.calculateRTO(e),n=window.setTimeout((()=>{rL("DC_DEBUG_LOG")&&"string"==typeof e.payload&&FL.debug("[".concat(this.ID,"] resending message packet"),JSON.parse(e.payload),"timeout: ".concat(t)),this.resendMessage(e)}),t);this.timeoutMap.set(e.packetNumber,n),this.sendPacket(e)}calculateRTO(e){const t=this.rtoRatioMap.get(e.packetNumber);if(void 0===t)return this.rtoRatioMap.set(e.packetNumber,1),this.initialRTO;{const n=9*this.rtt/8*t;return this.rtoRatioMap.set(e.packetNumber,t+1),n>this.maxRTO?this.maxRTO:n}}updateRTT(e,t){const n=e.ackSendTs;this.rtt=this.rtt*(7/8)+(t-n-this.rtt)/8}ack(e){if(e.packetNumber===this.lastOrderedPacketNumber+1)for(this.batchAckPacketQueue.length>=this.maxBatchAckCount&&this.batchAck(),this.batchAckTimer?this.batchAckPacketQueue.push(e):(this.batchAckPacketQueue.push(e),this.batchAckTimer=window.setTimeout((()=>{this.batchAck()}),this.rtt/8)),this.lastOrderedPacketNumber+=1,this.receiveImpl(e.payload);;){const e=this.unorderedPacketQueue[0];if(!e){this.unorderedPacketQueue.shift();break}this.batchAckTimer&&this.batchAck(),this.receiveImpl(e.payload),this.unorderedPacketQueue.shift(),this.lastOrderedPacketNumber+=1}else if(e.packetNumber<=this.lastOrderedPacketNumber){const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:Iae.Ack,version:this.version};rL("DC_DEBUG_LOG")&&FL.debug("[".concat(this.ID,"] sending ack packet"),t,"packetNumber: ".concat(e.packetNumber)),this.sendPacket(t)}else if(e.packetNumber>this.lastOrderedPacketNumber){this.unorderedPacketQueue[e.packetNumber-this.lastOrderedPacketNumber-2]=e;const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:Iae.Ack,version:this.version};rL("DC_DEBUG_LOG")&&FL.debug("[".concat(this.ID,"] sending ack packet"),t,"packetNumber: ".concat(e.packetNumber)),this.sendPacket(t)}}batchAck(){window.clearTimeout(this.batchAckTimer),this.batchAckTimer=void 0;const e={ackSendTs:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].sendTs,maxAckPacketNumber:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].packetNumber,shift:this.batchAckPacketQueue.length-1,type:Iae.Ack,version:this.version};rL("DC_DEBUG_LOG")&&FL.debug("[".concat(this.ID,"] sending batch ack packet"),e,"shift: ".concat(this.batchAckPacketQueue.length-1)),this.sendPacket(e),this.batchAckPacketQueue=[]}sendPacket(e){e.type===Iae.Default&&(e.sendTs=Math.round(performance.now()));const t=this.serialize(e);this.sendImpl(t)}clearRTO(e){for(let t=e.maxAckPacketNumber-e.shift;t<=e.maxAckPacketNumber;t++){const e=this.timeoutMap.get(t);void 0!==e&&window.clearTimeout(e),this.timeoutMap.delete(t),this.rtoRatioMap.delete(t)}}}class wae extends Cae{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3?arguments[3]:void 0),GA(this,"_initMutex",void 0),GA(this,"_reconnectInterrupter",void 0),GA(this,"_url",void 0),GA(this,"_transmitter",void 0),GA(this,"_addresses",void 0),GA(this,"_reliableTransmission",void 0),GA(this,"_textEncoder",void 0),GA(this,"_textDecoder",void 0),this._textEncoder=new TextEncoder,this._textDecoder=new TextDecoder,this._initMutex=new _P("datachannel");const n=t.timeout,i=t.timeoutFactor,r=Math.max(300,Math.floor(3*n/5)),o=Math.max(1.2,Math.floor(8*i)/10);AD.ONLINE&&(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=o),LD.on(wD.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===AD.ONLINE?(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=o):(this._retryConfig.timeout=n,this._retryConfig.timeoutFactor=i))}))}getConnection(){if(this._reliableTransmission)return this._reliableTransmission}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;this._forceCloseTimeout=t;const n=(t,n)=>{this._addresses=e,this.currentURLIndex=this._addresses.findIndex((e=>e.fingerprint||rL("FINGERPRINT")));const i=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(i).then(t).catch(n),this.once(pB.CLOSED,(()=>n(new hk(JN.WS_DISCONNECT)))),this.once(pB.CONNECTED,(()=>t()))};return this._initMutex.lock().then((e=>new dp(((e,t)=>{n(e,t)})).then((()=>{e()})).catch((()=>{e()}))))}async sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this._transmitter||!this._reliableTransmission)throw new hk(JN.WS_ABORT,"datachannel is not ready");try{t||(e=JSON.stringify(e));const n=this._textEncoder.encode(e),i=dK(n,{raw:!0});this._reliableTransmission.sendMessage(i)}catch(e){throw new hk(JN.WS_ERR,"send datachannel signal message error"+e.toString())}}unbindDcCloseEventListener(){this._transmitter&&(this._transmitter.onclose=null)}sendMessageWithJSON(e){const t=JSON.stringify(e);return{compressed:t,compressedLength:t.length,origin:e}}sendMessageWithUint8Array(e){return{compressed:e,compressedLength:e.byteLength,origin:e}}createTransmitterConnection(e){return this.connectionID+=1,this._joinChannelServiceRecordIndex=void 0,this._url="dc://".concat(e.ip,":").concat(e.port),new dp(((t,n)=>{var i;const r=()=>{FL.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="recover",this.state="connected",this.resetReconnectCount("opened"),t()},o=async e=>{var i;if(null===(i=this._closeEstablishingTransmitter)||void 0===i||i.call(this),FL.debug("[".concat(this._name,"] datachannel close ").concat(this._url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this._reconnectCount<this._retryConfig.maxRetryCount){"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const i=DD(this,pB.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,r=await this.reconnectWithAction(i);if("closed"===this.state)return void FL.debug("[".concat(this.connectionID,"] dc is closed, no need to reconnect"));if(!r)return n(new hk(JN.WS_DISCONNECT,"datachannel reconnect failed: ".concat(e.code))),void this.close(!0);t()}else n(new hk(JN.WS_DISCONNECT,"datachannel close: ".concat(e.code))),this.close()},s=async e=>{try{var t;null===(t=this._reliableTransmission)||void 0===t||t.onData(e.data)}catch(e){console.log(e)}};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),FL.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(e)));const a=null===(i=this._store)||void 0===i?void 0:i.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),c=Date.now();OD(this,pB.TO_CONNECT_DATACHANNEL).then((e=>{var t,n;if(!e)throw new Error("transmissonInfo not exist yet");const i=e.transmitter,d=e.close;this._transmitter=i,null===(t=this._store)||void 0===t||t.signalChannelOpen();const l=Date.now()-c;FL.debug("[choose dc] dc open cost ".concat(l,"ms"));this._reliableTransmission=new Aae((e=>{var t;this._transmitter&&"open"===this._transmitter.readyState&&(null===(t=this._transmitter)||void 0===t||t.send(e))}),(e=>{if("string"==typeof e)this.emit(pB.ON_MESSAGE,e);else{const t=uK(e,{raw:!0}).buffer,n=this._textDecoder.decode(t);this.emit(pB.ON_MESSAGE,n)}})),this._closeEstablishingTransmitter=()=>{var e;null===(e=this._reliableTransmission)||void 0===e||e.close(),this._reliableTransmission=void 0,d()},r&&r(),i.onclose=o,i.onmessage=s,null===(n=this._store)||void 0===n||n.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this._joinChannelServiceRecordIndex=a})).catch((e=>{var t;if(null===(t=this._store)||void 0===t||t.recordJoinChannelService({endTs:Date.now(),status:e instanceof hk&&e.code===JN.WS_ABORT?"aborted":"error",errors:[e]},a),"closed"!==this.state){if(e instanceof hk&&e.code===JN.WS_ERR){const t=new hk(JN.WS_ERR,"init datachannel failed! Error: ".concat(e.toString()));return FL.error("[".concat(this._name,"]").concat(t)),void n(t)}o&&o(e)}else n(new hk(JN.WS_DISCONNECT,"datachannel is closed: ".concat(e.toString())))}))}))}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this._reconnectCount>=this._retryConfig.maxRetryCount)return!1;if(!this._addresses)return!1;if("closed"===this.state)return!1;this._onlineReconnectListener||LD.networkState!==AD.OFFLINE||(this._onlineReconnectListener=LD.onlineWaiter&&LD.onlineWaiter.then((()=>{this._onlineReconnectListener=void 0})));let n=!0;if(this._reconnectInterrupter=()=>{n=!1},t){const t=fP(this._reconnectCount,this._retryConfig);FL.debug("[".concat(this._name,"] wait ").concat(t,"ms to reconnect datachannel, mode: ").concat(e)),await dp.race([$D(t),this._onlineReconnectListener||new dp((()=>{}))])}if("closed"===this.state||!n)return!1;this._reconnectCount+=1;const i=async(e,t)=>{this.emit(pB.RECONNECT_CREATE_CONNECTION,t),await this.createTransmitterConnection(e)};try{if("retry"===e){const t=this._addresses[this.currentURLIndex];await i(t,e)}else if("tryNext"===e){this.currentURLIndex+=1;for(let e=this.currentURLIndex;e<this._addresses.length;e++){if(this._addresses[e].fingerprint||rL("FINGERPRINT")){this.currentURLIndex=e;break}this.currentURLIndex+=1}if(this.currentURLIndex>=this._addresses.length)return FL.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);FL.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));const t=this._addresses[this.currentURLIndex];await i(t,e)}else"recover"===e&&(FL.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(pB.FAILBACK));return!0}catch(n){var r,o;return FL.error("[".concat(this._name,"] reconnect failed"),n.toString()),null!=n&&null!==(r=n.data)&&void 0!==r&&r.desc&&Array.isArray(n.data.desc)&&n.data.desc.length&&Vi(o=n.data.desc).call(o,"dynamic key expired")?(this.emit(pB.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(e,t)}}}class Oae extends hD{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===vF.CONNECTED?this.emit(yF.WS_CONNECTED):e===vF.RECONNECTING?this.emit(yF.WS_RECONNECTING,this._websocketReconnectReason):e===vF.CLOSED&&this.emit(yF.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket?this.websocket.url:null}get rtt(){return this.rttRolling.mean()}processPendingNotifications(){0!==this.pendingNotifications.length&&(FL.debug("[".concat(this.clientId,"] processing ").concat(this.pendingNotifications.length," pending notifications")),this.pendingNotifications.forEach((e=>{let t=e.type,n=e.message;this.emit(t,n),t===IF.ON_NOTIFICATION&&this.handleNotification(n),t===IF.ON_USER_BANNED&&this.handleUserBanned(n)})),this.pendingNotifications=[])}handleUserBanned(e){switch(e.error_code){case 14:this.close(SD.UID_BANNED);break;case 15:this.close(SD.IP_BANNED);break;case 16:this.close(SD.CHANNEL_BANNED)}}constructor(e,t){super(),GA(this,"__name__","DataChannelSignal"),GA(this,"_disconnectedReason",void 0),GA(this,"_websocketReconnectReason",void 0),GA(this,"_connectionState",vF.CLOSED),GA(this,"reconnectToken",void 0),GA(this,"websocket",void 0),GA(this,"openConnectionTime",void 0),GA(this,"clientId",void 0),GA(this,"lastMsgTime",Date.now()),GA(this,"uploadCache",[]),GA(this,"uploadCacheInterval",void 0),GA(this,"rttRolling",new TP(5)),GA(this,"pingpongTimer",void 0),GA(this,"inflateDataTimer",void 0),GA(this,"pingpongTimeoutCount",0),GA(this,"ortc",void 0),GA(this,"joinResponse",void 0),GA(this,"multiIpOption",void 0),GA(this,"initError",void 0),GA(this,"spec",void 0),GA(this,"store",void 0),GA(this,"isJoining",!1),GA(this,"pendingNotifications",[]),GA(this,"onWebsocketMessage",(e=>{if(e instanceof ArrayBuffer)return void this.emit(yF.ON_BINARY_DATA,e);const t=JSON.parse(e);if(rL("DC_DEBUG_LOG")&&FL.debug("[datachannel-signal] received packet",t),this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else Object.prototype.hasOwnProperty.call(t,"_type")&&(this.isJoining?t._type===IF.ON_NOTIFICATION||t._type===IF.ON_USER_BANNED?(this.emit(t._type,t._message),t._type===IF.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===IF.ON_USER_BANNED&&this.handleUserBanned(t._message)):(this.pendingNotifications.push({type:t._type,message:t._message}),FL.debug("[".concat(this.clientId,"] cached notification during join: ").concat(t._type))):(this.emit(t._type,t._message),t._type===IF.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===IF.ON_USER_BANNED&&this.handleUserBanned(t._message)))})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new wae("gateway-".concat(this.clientId),this.spec.retryConfig,!0,t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===vF.CONNECTED&&this.reconnect("retry",hB.OFFLINE)}))}async request(e,t,n,i){const r=eP(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new dp(((t,n)=>{if(this.connectionState===vF.CONNECTED)return t();const i=()=>{this.off(yF.WS_CLOSED,r),t()},r=()=>{this.off(yF.WS_CONNECTED,i),n(new hk(JN.WS_ABORT))};this.once(yF.WS_CONNECTED,i),this.once(yF.WS_CLOSED,r),e!==bF.PUBLISH&&e!==bF.SUBSCRIBE&&e!==bF.UNSUBSCRIBE&&e!==bF.UNPUBLISH&&e!==bF.CONTROL&&e!==bF.RESTART_ICE||this.once(yF.DISCONNECT_P2P,(()=>{n(new hk(JN.DISCONNECT_P2P))})),e!==bF.PUBLISH&&e!==bF.RESTART_ICE||this.once(yF.ABORT_P2P_EXECUTION,(()=>{n(new hk(JN.DISCONNECT_P2P))}))}));if(this.connectionState!==vF.CONNECTING&&this.connectionState!==vF.RECONNECTING||e===bF.JOIN||e===bF.REJOIN||await a(),e===bF.LEAVE&&(this.websocket.unbindDcCloseEventListener(),i=!0),rL("DC_DEBUG_LOG")&&FL.debug("[datachannel-signal] sendMessage",o),await this.websocket.sendMessage(o,!0,!1),i)return;const c=new dp(((n,i)=>{let o=!1;const a=(i,r)=>{o=!0,n({isSuccess:"success"===i,message:r||{}}),this.off(yF.WS_CLOSED,c),this.off(yF.WS_RECONNECTING,c),this.emit(yF.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{i(new hk(JN.WS_ABORT,"type: ".concat(e))),this.off(yF.WS_CLOSED,c),this.off(yF.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(yF.WS_CLOSED,c),this.once(yF.WS_RECONNECTING,c),$D(rL("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(FL.warning("dc request timeout, type: ".concat(e)),this.emit(yF.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(i){if(this.connectionState===vF.CLOSED||e===bF.LEAVE)throw new hk(JN.WS_ABORT);return!this.spec.forceWaitGatewayResponse||n?i.throw():e===bF.JOIN||e===bF.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=CB(l),h=new hk(JN.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return"success"===u.action?d.message:(FL.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===RF.ERR_TOO_MANY_BROADCASTERS?e===bF.JOIN||e===bF.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===RF.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,FL.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",hB.MULTI_IP)):this.reconnect(u.action,hB.SERVER_ERROR),e===bF.JOIN||e===bF.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new dp((n=>{const i=r=>{(!t||t(r))&&(this.off(e,i),n(r))};this.on(e,i)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void FL.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(CF.WRTC_STATS,t)}upload(e,t){const n={_type:e,_message:t};try{this.websocket.sendMessage(n)}catch(e){const t=rL("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(n),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==vF.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),rL("UPLOAD_CACHE_INTERVAL")||2e3))}}async send(e,t){const n={_type:e,_message:t};await this.websocket.sendMessage(n)}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new dp(((t,n)=>{this.once(yF.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(yF.WS_CLOSED,(()=>n(this.initError||new hk(JN.WS_ABORT)))),this.connectionState=vF.CONNECTING,this.websocket.init(e).catch(n),this.websocket.once(pB.FAILBACK,(()=>{n(new hk(JN.INIT_DATACHANNEL_TIMEOUT))})),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval((()=>{this.handleInflateData()}),2e4),setTimeout((()=>{void 0===this.openConnectionTime&&(FL.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),n(new hk(JN.INIT_DATACHANNEL_TIMEOUT)))}),rL("DC_JOIN_WITH_FAILBACK"))}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.inflateDataTimer&&(this.handleInflateData(),window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this.isJoining=!1,this.pendingNotifications=[],this._disconnectedReason=e||SD.LEAVE,this.connectionState=vF.CLOSED,FL.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),e===SD.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new wae("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents())}async join(){if(this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),rL("DC_PINGPONG_INTERVAL")),!this.joinResponse){this.emit(yF.ABORT_P2P_EXECUTION),this.store.signalConnected();const e=await OD(this,yF.REQUEST_JOIN_INFO);this.store.joinReq();let t=await OD(this,yF.REQUEST_JOIN_INFO_WITH_PRE_JOIN_RESPONSE);if(this.isJoining=!0,this.pendingNotifications=[],t){FL.debug("join response from pre join response");const n=await this.request(bF.JOIN,e);n&&"ortc"in n&&(t=n)}else FL.debug("join response from request join_v3"),t=await this.request(bF.JOIN,e);if(this.store.joinRep(),this.ortc=null==e?void 0:e.ortc,!t)return this.emit(yF.REPORT_JOIN_GATEWAY,JN.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(yF.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=vF.CONNECTED,this.isJoining=!1,this.processPendingNotifications(),!0}async rejoin(){if(!this.reconnectToken)throw new hk(JN.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=PD(this,yF.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(bF.REJOIN,e);return!!t&&(this.connectionState=vF.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),rL("DC_PINGPONG_INTERVAL")),t.peers&&t.peers.forEach((e=>{this.emit(IF.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(IF.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(IF.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(IF.MUTE_AUDIO,{uid:e.uid}):this.emit(IF.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(IF.MUTE_VIDEO,{uid:e.uid}):this.emit(IF.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(IF.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(IF.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(IF.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(IF.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(IF.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})})),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}async downgradeCodec(e){if(!this.ortc)return!1;const t={downgrade_codec:e,ortc:this.ortc};return!!await this.request(bF.DOWNGRADE_CODEC,t)}handleNotification(e){FL.debug("[".concat(this.clientId,"] receive notification: "),e);const t=CB(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(SD.UID_BANNED),void this.close()):void this.reconnect(t.action,hB.SERVER_ERROR);FL.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1,rL("DC_DEBUG_LOG")&&console.debug("[datachannel-signal] pingpongTimeoutCount: ".concat(this.pingpongTimeoutCount));const e=rL("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(FL.warning("[datachannel-signal] PINGPONG Timeout. Last Socket Message: ".concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>rL("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("recover",hB.FALLBACK):this.request(bF.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),rL("REPORT_STATS")&&this.send(bF.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleInflateData(){const e=this.websocket.getInflateData(),t=e.inflateLength,n=e.deflateLength;0!==t&&0!==n&&this.upload(CF.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:n,ws_inflate_length:t})}handleWebsocketEvents(){this.websocket.on(pB.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(yF.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(pB.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(pB.CLOSED,(()=>{this.connectionState=vF.CLOSED})),this.websocket.on(pB.FAILED,(()=>{this._disconnectedReason=SD.NETWORK_ERROR,this.connectionState=vF.CLOSED})),this.websocket.on(pB.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===vF.CONNECTED?this.connectionState=vF.RECONNECTING:this.connectionState=vF.CONNECTING})),this.websocket.on(pB.WILL_RECONNECT,((e,t)=>{if(PD(this,yF.IS_P2P_DISCONNECTED)&&"retry"===e)return FL.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(yF.NEED_RENEW_SESSION),this.emit(yF.DISCONNECT_P2P),t("tryNext");"retry"!==e&&(FL.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(yF.NEED_RENEW_SESSION),this.emit(yF.DISCONNECT_P2P)),t(e)})),this.websocket.on(pB.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{FL.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",hB.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(yF.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof hk&&e.code===JN.UNEXPECTED_RESPONSE&&e.data.code===RF.ERR_NO_AUTHORIZED)return FL.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",hB.SERVER_ERROR);FL.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",hB.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(pB.REQUEST_NEW_URLS,((e,t)=>{OD(this,yF.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(pB.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(IF.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(pB.TO_CONNECT_DATACHANNEL,((e,t)=>{OD(this,yF.PRE_CONNECT_PC).then(e).catch(t)})),this.websocket.on(pB.FAILBACK,(()=>{void 0!==this.openConnectionTime&&this.emit(yF.DATACHANNEL_FAILBACK)}))}}const Nae={name:"DataChannelConnection",create:function(e){let t=e.store,n=e.spec;return new vae(n,t)}};const Dae={name:"DataChannelSignal",create:function(e){let t=e.store,n=e.spec;return new Oae(n,t)}};XP(),iL("PROCESS_ID","process-".concat(eP(8,""),"-").concat(eP(4,""),"-").concat(eP(4,""),"-").concat(eP(4,""),"-").concat(eP(12,""))),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void FL.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),n=Date.now();FL.debug("Loading global parameters from cache",t),Object.keys(t).forEach((e=>{if(Object.prototype.hasOwnProperty.call(nL,e)){const i=t[e],r=i.value,o=i.expires;if(o&&o<=n)return;sL[e]=r,nL[e]=r}}))}catch(t){FL.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(sL.AREAS)&&sL.AREAS.length>0&&lte(sL.AREAS,!0);const Pae=(e,t,n)=>{FL.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),iL(e,t,n)};Wee(Poe,!1),Wee(Foe,!1),Wee(yre,!1),Wee(mse,!1),Wee(Ooe,!1),Wee(nae,!1),Wee(uae,!1),Wee(pae,!1),Wee(Nae,!1),Wee(Dae,!1);const Lae=function(e){const t=new hD,n=e,i={getListeners:t.getListeners.bind(t),on:(e,n)=>(function(e,t){e===_B.SECURITY_POLICY_VIOLATION&&Ioe(t,!0)}(e,n),t.on.bind(t)(e,n)),addListener:t.addListener.bind(t),once:t.once.bind(t),off:t.off.bind(t),removeAllListeners:t.removeAllListeners.bind(t),emit:t.emit.bind(t),safeEmit:t.safeEmit.bind(t)};return boe(boe({},n),i)}({__TRACK_LIST__:xk,VERSION:JP,BUILD:eL,ESM_BUNDLER:!1,ESM:!0,UMD:!1,DEV:!1,setParameter:Pae,getParameter:rL,getSupportedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;const n=await async function(e){let t;return _k().supportUnifiedPlan?(e.addTransceiver("video",{direction:"recvonly"}),e.addTransceiver("audio",{direction:"recvonly"}),t=(await e.createOffer()).sdp):t=(await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0})).sdp,t}(t);if(!n)return e;t.close(),t=null,e=function(e){const t={video:[],audio:[]};return e.match(/ VP8/i)&&t.video.push("VP8"),e.match(/ VP9/i)&&t.video.push("VP9"),e.match(/ AV1/i)&&t.video.push("AV1"),e.match(/ H264/i)&&t.video.push("H264"),e.match(/ H265/i)&&t.video.push("H265"),e.match(/ opus/i)&&t.audio.push("OPUS"),e.match(/ PCMU/i)&&t.audio.push("PCMU"),e.match(/ PCMA/i)&&t.audio.push("PCMA"),e.match(/ G722/i)&&t.audio.push("G722"),t}(n)}catch(e){throw new hk(JN.CREATE_OFFER_FAILED,e.toString&&e.toString()).print()}return e},checkSystemRequirements:function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];const t=uk.reportApiInvoke(null,{name:ED.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:mD.TRACER}),n=function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=!1;try{const n=window.RTCPeerConnection,i=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,r=window.WebSocket;t=!(!n||!r),e&&!i&&(t=!1),t&&BN()&&vN(75)&&(new n).close()}catch(e){FL.error("check system requirement failed: ",e),t=!1}return t}(e),i=foe();FL.debug("checkSystemRequirements, api:",n,"browser",i);const r=n&&i;return t.onSuccess(r),rL("IGNORE_RTC_DEVICE_CHECK")?n:r},getDevices:function(e){return xM.enumerateDevices(!0,!0,e)},getMicrophones:function(e){return xM.getRecordingDevices(e)},getCameras:function(e){return xM.getCamerasDevices(e)},getElectronScreenSources:NM,getPlaybackDevices:function(e){return xM.getSpeakers(e)},createClient:moe,createCameraVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=rL("CAMERA_CAPTURE_CONFIG"),n=eP(8,"track-cam-"),i=uk.reportApiInvoke(null,{id:n,tag:mD.TRACER,name:ED.CREATE_CAM_VIDEO_TRACK,options:[pM({},e),t]});t&&(e.encoderConfig=t);const r=$M(e);let o=null;FL.info("start create camera video track with config",JSON.stringify(e),"trackId",n);try{o=(await kM({video:r},n)).getVideoTracks()[0]||null}catch(e){throw i.onError(e),e}if(!o){const e=new zN(JN.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(FL)}if(e.optimizationMode&&WV(n,o,e,Lk(e.encoderConfig)),rL("USE_STANDARD_BITRATE_DEFAULT")){const t=Lk(e.encoderConfig);e.encoderConfig=t,delete t.bitrateMax,delete t.bitrateMin}const s=new jV(o,e,r,e.scalabiltyMode?Mk(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n);return i.onSuccess(s.getTrackId()),FL.info("create camera video success, trackId:",n),s},createCustomVideoTrack:function(e){const t=eP(8,"track-cus-"),n=uk.reportApiInvoke(null,{id:t,tag:mD.TRACER,name:ED.CREATE_CUSTOM_VIDEO_TRACK,options:[e]});rL("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin);const i=new BV(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?Mk(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,t,[jk.CUSTOM_TRACK]);return n.onSuccess(i.getTrackId()),FL.info("create custom video track success with config",e,"trackId",i.getTrackId()),i},createScreenVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"disable";const n="object"==typeof t?function(e){const t=eU(e);return yk()&&e.suppressLocalAudioPlayback&&(t.suppressLocalAudioPlayback=e.suppressLocalAudioPlayback),bk()&&e.restrictOwnAudio&&(t.restrictOwnAudio=!0),t}(t):void 0;n&&(t="auto");const i=eP(8,"track-scr-v-"),r=uk.reportApiInvoke(null,{id:i,tag:mD.TRACER,name:ED.CREATE_SCREEN_VIDEO_TRACK,options:[pM({},e),t]});e.encoderConfig?"string"==typeof e.encoderConfig||e.encoderConfig.width&&e.encoderConfig.height||(e.encoderConfig.width={max:1920},e.encoderConfig.height={max:1080}):e.encoderConfig="1080p_2";const o=function(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&_N()&&(t.extensionId=e.extensionId);const n=e.displaySurface,i=e.selfBrowserSurface,r=e.surfaceSwitching,o=e.systemAudio,s=e.preferCurrentTab,a=e.windowAudio,c=e.monitorTypeSurfaces;(RN(107)||bN(107)||NN(93))&&(n&&(qN(n,"displaySurface",["browser","window","monitor"]),t.displaySurface=n),i?(qN(i,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=i):t.selfBrowserSurface="include",r&&(qN(r,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=r)),(RN(105)||bN(105)||NN(91))&&o&&(qN(o,"systemAudio",["exclude","include"]),t.systemAudio=o),(RN(94)||bN(94)||NN(80))&&s&&(t.preferCurrentTab=!0),(RN(141)||bN(141)||NN(125))&&a&&(qN(a,"windowAudio",["exclude","system"]),t.windowAudio=a),(RN(119)||bN(119)||NN(105))&&c&&(qN(c,"monitorTypeSurfaces",["exclude","include"]),t.monitorTypeSurfaces=c),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const d=e.encoderConfig?kk(e.encoderConfig):null;return t.mandatory={chromeMediaSource:"desktop",maxWidth:d?d.width:void 0,maxHeight:d?d.height:void 0},d&&(d.frameRate&&("number"==typeof d.frameRate?(t.mandatory.maxFrameRate=d.frameRate,t.mandatory.minFrameRate=d.frameRate):(t.mandatory.maxFrameRate=d.frameRate.max||d.frameRate.ideal||d.frameRate.exact||void 0,t.mandatory.minFrameRate=d.frameRate.min||d.frameRate.ideal||d.frameRate.exact||void 0),t.frameRate=d.frameRate),d.width&&(t.width=d.width),d.height&&(t.height=d.height)),t}(e);let s=null,a=null;const c=_k();if(!c.supportShareAudio&&"enable"===t){const e=new zN(JN.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return r.onError(e),e.throw(FL)}FL.info("start create screen video track with config",e,"withAudio",t,"trackId",i);const d=c.supportShareAudio&&"disable"!==t;try{const e=await kM({screen:o,screenAudio:d?n||!0:void 0},i);s=e.getVideoTracks()[0]||null,a=e.getAudioTracks()[0]||null}catch(e){throw r.onError(e),e}if(!s){const e=new zN(JN.UNEXPECTED_ERROR,"can not find track in media stream");return r.onError(e),e.throw(FL)}if(!a&&"enable"===t){s&&s.stop();const e=new zN(JN.SHARE_AUDIO_NOT_ALLOWED);return r.onError(e),e.throw(FL)}e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode&&(WV(i,s,e,e.encoderConfig&&kk(e.encoderConfig)||void 0),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax));const l=new BV(s,e.encoderConfig?kk(e.encoderConfig):{},e.scalabiltyMode?Mk(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,i,[jk.SCREEN_TRACK]);if(!a)return r.onSuccess(l.getTrackId()),FL.info("create screen video track success","video:",l.getTrackId()),l;const u=new YU(a,void 0,eP(8,"track-scr-a-"),!1);return r.onSuccess([l.getTrackId(),u.getTrackId()]),FL.info("create screen video track success","video:",l.getTrackId(),"audio:",u.getTrackId()),[l,u]},createMicrophoneAndCameraTracks:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=rL("CAMERA_CAPTURE_CONFIG"),i=eP(8,"track-mic-"),r=eP(8,"track-cam-"),o=uk.reportApiInvoke(null,{id:"".concat(i,"-").concat(r),tag:mD.TRACER,name:ED.CREATE_MIC_AND_CAM_TRACKS,options:[e,t,n]});n&&(t.encoderConfig=n);const s=$M(t),a=tU(e);let c=null,d=null;FL.info("start create camera video track(".concat(r,") and microphone audio track(").concat(i,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{const e=await kM({audio:a,video:s},"".concat(i,"-").concat(r));c=e.getAudioTracks()[0],d=e.getVideoTracks()[0]}catch(e){throw o.onError(e),e}if(!c||!d){const e=new zN(JN.UNEXPECTED_ERROR,"can not find tracks in media stream");return o.onError(e),e.throw(FL)}if(t.optimizationMode&&WV(r,d,t,Lk(t.encoderConfig)),rL("USE_STANDARD_BITRATE_DEFAULT")){const e=Lk(t.encoderConfig);t.encoderConfig=e,delete e.bitrateMax,delete e.bitrateMin}const l=new XU(c,e,a,i),u=new jV(d,t,s,t.scalabiltyMode?Mk(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,r);return o.onSuccess([l.getTrackId(),u.getTrackId()]),FL.info("create camera video track(".concat(r,") and microphone audio track(").concat(i,") success")),[l,u]},createMicrophoneAudioTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=eP(8,"track-mic-"),n=uk.reportApiInvoke(null,{id:t,tag:mD.TRACER,name:ED.CREATE_MIC_AUDIO_TRACK,options:[e]}),i=tU(e);let r=null;FL.info("start create microphone audio track with config",JSON.stringify(e),"trackId",t);try{r=(await kM({audio:i},t)).getAudioTracks()[0]||null}catch(e){throw n.onError(e),e}if(!r){const e=new zN(JN.UNEXPECTED_ERROR,"can not find track in media stream");return n.onError(e),e.throw(FL)}const o=new XU(r,e,i,t);return n.onSuccess(o.getTrackId()),FL.info("create microphone audio track success, trackId:",t),o},createCustomAudioTrack:GV,createBufferSourceAudioTrack:async function(e){var t;const n=e.cacheOnlineFile,i=e.encoderConfig;let r=e.source;const o={source:r instanceof AudioBuffer?"AudioBuffer":r instanceof File?null!==(t=File.name)&&void 0!==t?t:"File":r,cacheOnlineFile:n,encoderConfig:i},s=eP(8,"track-buf-"),a=uk.reportApiInvoke(null,{id:s,tag:mD.TRACER,name:ED.CREATE_BUFFER_AUDIO_TRACK,options:[o]});if(rL("DISABLE_WEBAUDIO"))throw new zN(JN.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");FL.info("start create buffer source audio track with config",JSON.stringify(o),"trackId",s);const c=r;if(!(r instanceof AudioBuffer))try{r=await async function(e,t){let n=null;if("string"==typeof e){const t=qU.get(e);if(t)return FL.debug("use cached audio resource: ",e),t;try{n=(await gP((()=>QO.get(e,{responseType:"arraybuffer"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new zN(JN.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{const t=new dp(((t,n)=>{const i=new FileReader;i.onload=e=>{e.target?t(e.target.result):n(new zN(JN.READ_LOCAL_AUDIO_FILE_ERROR))},i.onerror=()=>{n(new zN(JN.READ_LOCAL_AUDIO_FILE_ERROR))},i.readAsArrayBuffer(e)}));n=await t}const i=await function(e){const t=RM();return new dp(((n,i)=>{t.decodeAudioData(e,(e=>{n(e)}),(e=>{i(new zN(JN.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}(n);return"string"==typeof e&&t&&qU.set(e,i),i}(r,n)}catch(e){return a.onError(e),e.throw(FL)}const d=new ZU(r),l=new JU(c,d,i?Vk(i):{},s);return FL.info("create buffer source audio track success, trackId:",s),a.onSuccess(l.getTrackId()),l},setAppType:function(e){if(FL.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw FL.debug("Invalid appType"),new hk(JN.INVALID_PARAMS,"invalid app type",e);iL("APP_TYPE",Math.floor(e))},setLogLevel:function(e){FL.setLogLevel(e)},enableLogUpload:function(){rL("USE_NEW_LOG")?iL("UPLOAD_LOG",!0):FL.enableLogUpload()},disableLogUpload:function(){rL("USE_NEW_LOG")?iL("UPLOAD_LOG",!1):FL.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new zte},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=uk.reportApiInvoke(null,{tag:mD.TRACER,name:ED.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof YU||e instanceof ox)){const e=new hk(JN.INVALID_TRACK,"the parameter is not a audio track");return n.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const i=e instanceof YU?e.getTrackLabel():"remote_track",r=e.getVolumeLevel();let o=r,s=r;const a=Date.now();return new dp((r=>{const c=setInterval((()=>{const d=e.getVolumeLevel();o=d>o?d:o,s=d<s?d:s;const l=o-s>1e-4,u=Date.now()-a;if(l||u>t){clearInterval(c);const t=l,s={duration:u,deviceLabel:i,maxVolumeLevel:o,result:t};FL.info("[track-".concat(e.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(s))),n.onSuccess(s),r(t)}}),200)}))},checkVideoTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=uk.reportApiInvoke(null,{tag:mD.TRACER,name:ED.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof BV||e instanceof rx)){const e=new hk(JN.INVALID_TRACK,"the parameter is not a video track");return n.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const i=e instanceof BV?e.getTrackLabel():"remote_track",r=e.getMediaStreamTrack(!0),o=document.createElement("video");o.style.width="1px",o.style.height="1px",o.setAttribute("muted",""),o.muted=!0,o.setAttribute("playsinline",""),o.controls=!1,(EN()||pN())&&(o.style.opacity="0.01",o.style.position="fixed",o.style.left="0",o.style.top="0",document.body.appendChild(o)),o.srcObject=new MediaStream([r]),o.play();const s=document.createElement("canvas");s.width=160,s.height=120;let a=0,c=0;try{const e=Date.now();a=await function(e,t,n,i){let r,o=0,s=null;return new dp(((a,c)=>{function d(){o>i&&r&&(r(),a(o));const t=n.getContext("2d");if(!t){const e=new hk(JN.UNEXPECTED_ERROR,"can not get canvas 2d context.");return FL.error(e.toString()),void c(e)}t.drawImage(e,0,0,160,120);const d=t.getImageData(0,0,n.width,n.height),l=Math.floor(d.data.length/3);if(s){for(let e=0;e<l;e+=3)if(d.data[e]!==s[e])return o+=1,void(s=d.data);s=d.data}else s=d.data}setTimeout((()=>{r&&(r(),a(o))}),t),r=bM((()=>{d()}),30)}))}(o,t,s,4),c=Date.now()-e}catch(e){throw n.onError(e),e}fie===oN.SAFARI&&(o.pause(),o.remove()),o.srcObject=null;const d=a>4,l={duration:c,changedPicNum:a,deviceLabel:i,result:d};return FL.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(l))),n.onSuccess(l),d},setArea:lte,audioElementPlayCenter:KM,resumeAudioContext:function(){return KM.autoResumeAfterInterruption(!0)},processExternalMediaAEC:function(e){voe.processExternalMediaAEC(e)},registerExtensions:function(e){const t=rL("PLUGIN_INFO")||[];e.forEach((e=>{"name"in e&&!Vi(t).call(t,e.name)&&t.push(e.name);const n=e;n.__registered__=!0,n.logger.hookLog=FL.extLog,n.reporter.hookApiInvoke=uk.extApiInvoke,n.parameters&&Object.keys(n.parameters).forEach((e=>{n.parameters[e]=rL(e)}))})),Pae("PLUGIN_INFO",t)},ChannelMediaRelayError:WF,ChannelMediaRelayEvent:jF,ChannelMediaRelayState:GF,RemoteStreamFallbackType:Kk,RemoteStreamType:Wk,ConnectionDisconnectedReason:SD,AudienceLatencyLevelType:gD,AREAS:JF,preload:async function(e,t,n,i){return Lie(e,t,n,i)},startLastmileProbeTest:async function(e,t,n,i){let r={state:"unavailable"};await Lie(e,t,n,i);const o=await kie({appId:e,cname:t,token:n||e,uid:i,cloudProxyServer:"disabled"});if(!o)return r;await Uie(o);const s=moe({mode:"rtc",codec:"vp8"});let a;try{a=await s.join(e,t,n,i,{networkQualityProbe:!0})}catch(e){return r}const c=new Pie,d=c.createMuteAudioTrack(),l=await GV({mediaStreamTrack:d});await s.publish([l]);const u=Hb(await new dp(((e,t)=>{const n=setTimeout((()=>{clearTimeout(n),e([!0,null,"audio"])}),5e3);s.on("user-published",(async(t,i)=>{t.uid===a&&(clearTimeout(n),e([!1,t,i]))}))})),3),h=u[0],p=u[1],_=u[2];if(h||!p)return await s.unpublish([l]),await s.leave(),l.close(),c.close(),r;await s.subscribe(p,_),await new dp(((e,t)=>{const n=setTimeout((()=>{clearTimeout(n),e(null)}),5e3)}));const E=s.getRTCStats(),m=s.getLocalAudioStats(),f=E.RTT,g=m.sendJitterMs,S=m.currentPacketLossRate;return r={state:"complete",rtt:f,packetLossRate:S,jitter:g,networkQuality:((e,t,n)=>{let i=1;if(n>0){let e=Math.log(100*n)/Math.log(2)+1;e=Math.min(5,Math.max(0,e)),i=1-e/5}let r=1;if(e>0){let t=Math.log(e/40)/Math.log(2)+1;t=Math.min(5,Math.max(0,t)),r=1-t/5}let o=1;if(t>0){let e=Math.log(t/10)/Math.log(2.5)+1;e=Math.min(5,Math.max(0,e)),o=1-e/5}const s=.5*i+.3*r+.2*o;let a=0;return a=s>=.8?1:s>=.6?2:s>=.4?3:s>=.2?4:5,a})(f,g,S)},await s.unsubscribe(p),await s.unpublish([l]),await s.leave(),l.close(),c.close(),await Uie(o),r}});Object.defineProperties(Lae,{onAudioAutoplayFailed:{get:()=>BM.onAudioAutoplayFailed,set:e=>{BM.onAudioAutoplayFailed=e}},onAutoplayFailed:{get:()=>BM.onAutoplayFailed,set:e=>{BM.onAutoplayFailed=e}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>Lae._onSecurityPolicyViolation,set(e){Lae._onSecurityPolicyViolation=e,Ioe(e)}},__CLIENT_LIST__:{get:()=>rL("SHOW_GLOBAL_CLIENT_LIST")?Zx:[]}}),xM.on(rM.CAMERA_DEVICE_CHANGED,(e=>{FL.info("camera device changed",JSON.stringify(e)),Lae.onCameraChanged&&Lae.onCameraChanged(e),Lae.safeEmit(_B.CAMERA_CHANGED,e)})),xM.on(rM.RECORDING_DEVICE_CHANGED,(e=>{FL.info("microphone device changed",JSON.stringify(e)),Lae.onMicrophoneChanged&&Lae.onMicrophoneChanged(e),Lae.safeEmit(_B.MICROPHONE_CHANGED,e)})),xM.on(rM.PLAYOUT_DEVICE_CHANGED,(e=>{FL.debug("playout device changed",JSON.stringify(e)),Lae.onPlaybackDeviceChanged&&Lae.onPlaybackDeviceChanged(e),Lae.safeEmit(_B.PLAYBACK_DEVICE_CHANGED,e)})),KM.onAutoplayFailed=()=>{FL.info("detect audio element autoplay failed"),BM.onAudioAutoplayFailed&&BM.onAudioAutoplayFailed()},TM.on("autoplay-failed",(()=>{FL.info("detect webaudio autoplay failed"),BM.onAudioAutoplayFailed&&BM.onAudioAutoplayFailed(),Lae.safeEmit(_B.AUTOPLAY_FAILED)})),TM.on(Ck.STATE_CHANGE,((e,t)=>{FL.info("audio context state changed: ".concat(t," => ").concat(e)),Lae.onAudioContextStateChanged&&Lae.onAudioContextStateChanged(e,t),Lae.safeEmit(_B.AUDIO_CONTEXT_STATE_CHANGED,e,t)})),LD.on(wD.NETWORK_STATE_CHANGE,((e,t)=>{FL.info("[network-indicator] network state changed, ".concat(t," => ").concat(e))})),window&&(window.__ARTC__=Lae);export{Lae as default};
