aliyun-rtc-sdk 6.11.5 → 6.11.6-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aliyun-rtc-sdk.js +13 -13
- package/dist/types/index.d.ts +45 -1
- package/package.json +2 -1
package/dist/aliyun-rtc-sdk.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);r=e.reduce(function(i,s){var a=s.split(": ");return i[a[0]]=a[1],i},{})}catch(i){r={}}return r},getQuerys:function(t){if(!t)return"";var r={},e=[],i="",s="";try{var a=[];if(t.indexOf("?")>=0&&(a=t.substring(t.indexOf("?")+1,t.length).split("&")),a.length>0)for(var n in a)i=(e=a[n].split("="))[0],s=e[1],r[i]=s}catch(o){r={}}return r},getURL:function(t){if(!t)return null;var r={},e=t.length,i=t.indexOf("://");if(i<0)return null;r.protocol=t.substring(0,i+1);var s=t.indexOf("#"),a=t.indexOf("?");s<0&&(s=e),a<0&&(a=s),r.search=t.substring(a,s).substring(0,1e3);var n=t.substring(i+3,a),o=n.indexOf("/");return o<0&&(o=n.length),r.domain=n.substring(0,o).split(":")[0],r.path=n.substring(o,n.length).substring(0,1e3),r},getResType:function(t,r){if(["script","img","other"].indexOf(t)>-1)return t;if(["video"].indexOf(t)>-1)return"media";if(["document","iframe"].indexOf(t)>-1)return"doc";var e=r?this.getURL(r):null,i=e&&e.path?e.path.lastIndexOf("."):-1,s=(i>0?e.path.substr(i+1):"").toLowerCase();if(s){if(["eot","woff","woff2","ttf"].indexOf(s)>-1)return"font";if(s==="css")return"css";if(s==="js")return"script"}return["fetch","xmlhttprequest","beacon"].indexOf(t)>-1?"api":"others"},areInOrder:function(){for(var t=1;t<arguments.length;t+=1)if(arguments[t-1]>arguments[t])return!1;return!0},getFetchSnapshot:function(t,r,e){var i,s;try{var a=(t&&typeof t[0]!="string"?t[0].url:t[0])||"",n=(t&&typeof t[0]!="string"?t[0]:t[1])||{},o=n.method.toUpperCase()==="POST"?n.body:this.getQuerys(a);i={originApi:a,method:n.method||"unknown",params:o,response:r||"",reqHeaders:this.parseFetchHeaders(n.headers||null),resHeaders:this.parseFetchHeaders(e)},s=JSON&&JSON.stringify(i)||"{}"}catch(c){s="{}"}return s},getXhrSnapshot:function(t,r,e){if(!t||!r||!e)return{};var i,s;try{var a="";e.responseType===""||e.responseType==="text"?a=e.responseText:e.responseType==="document"&&(a=e.responseXML),i={originApi:t,method:r,params:this.getQuerys(t),response:a,reqHeaders:{},resHeaders:this.parseXhrHeaders(typeof e.getAllResponseHeaders=="function"&&e.getAllResponseHeaders()||"")},s=JSON&&JSON.stringify(i)||"{}"}catch(n){s="{}"}return s},isRobot:function(){var t=["nuhk","googlebot/","googlebot-image","yammybot","openbot","slurp","msnbot","ask jeeves/teoma","ia_archiver","baiduspider","bingbot/","adsbot"];if(!navigator||typeof navigator.userAgent!="string")return!1;try{for(var r=navigator.userAgent.toLowerCase(),e=0;e<t.length;e++){var i=t[e];if(r.lastIndexOf(i)>=0)return!0}}catch(s){this.warn("[arms] useragent parse error")}return!1},isFunction:function(t){return typeof t=="function"},isPlainObject:function(t){return Object.prototype.toString.call(t)==="[object Object]"},isString:function(t){return Object.prototype.toString.call(t)==="[object String]"},isArray:function(t){return Object.prototype.toString.call(t)==="[object Array]"},joinRegExp:function(t){for(var r,e=[],i=0,s=t.length;i<s;i++)r=t[i],this.isString(r)?e.push(r.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")):r&&r.source&&e.push(r.source);return new RegExp(e.join("|"),"i")},reWriteMethod:function(t,r,e){if(t!==null){var i=t[r];t[r]=e(i)}},checkSDKError:function(t,r){return!t&&!r?!1:new RegExp(this.selfErrKey,"i").test(t)?!0:!!this.ignoreByRule(r,[/retcode.alicdn.com\/retcode\/bl.js/,/g.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/laz-g-cdn.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/local.taobao.com:8880\/build\/bl/])},sdkError:function(t){return{msg:t,message:this.selfErrKey}},dealParam:function(t,r,e){var i={};try{i=this.isPlainObject(t)?this.ext({key:t.key||"default",val:t.val||t.value||e},t,{begin:Date.now()}):{key:t||"default",val:r||e,begin:Date.now()}}catch(s){this.warn("[retcode] baseLog error: "+s)}return i}},ye=ba,Cr={exports:{}},Mr={exports:{}},Nr=ye,va=function(t,r,e){typeof t=="object"&&(t=Nr.serialize(t));var i=r+t+(e?"&post_res=":"");window&&window.navigator&&typeof window.navigator.sendBeacon=="function"?window.navigator.sendBeacon(i,e||"&post_res="):Nr.warn("[arms] navigator.sendBeacon not surported")},H=ye,ya=va,Lr="aokcdqn3ly@e629dabd48a9933",Or=function(t,r){var e;if(r.t==="error"&&(e=t.requestQueue[0])&&e.t==="error"&&r.msg===e.msg)return r.times=e.times+1,void(t.requestQueue[0]=r);if(r.t==="behavior"){var i=t.requestQueue&&t.requestQueue.length;if(i>0&&t.requestQueue[i-1].t==="behavior"){var s=r.behavior||[];t.requestQueue[i-1].behavior.concat(s)}else t.requestQueue.push(r)}else t.requestQueue.unshift(r);return t.onReady(function(){t.requestTimmer=H.delay(function(){t.clear()},t.requestQueue[0]&&t.requestQueue[0].t==="error"?3e3:-1)}),!0},Ot=function(t){return this.ver="1.8.36-beta.12",this._conf=H.ext({},Ot.dftCon),this.sampleCache={},this.requestQueue=[],this.selfQueue=[],this.sdkFlag=!0,this.hash=H.seq(),this.resetPageview(),this.setConfig(t),this.rip=H.getRandIP(),this.record=999,this["EagleEye-TraceID"]=this.getTraceId()["EagleEye-TraceID"],this._common={},this};Ot.dftCon={sample:1,pvSample:1,tag:"",imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",region:null,ignore:{ignoreUrls:[],ignoreApis:[],ignoreErrors:[/^Script error\.?$/],ignoreResErrors:[],ignoreResources:[/\/(bl|wl)(.debug)?.js$/]},release:void 0,environment:"prod",beforeReport:null,parseTraceId:null},Ot.prototype={constructor:Ot,onReady:function(t){return t()},getPage:function(){var t=this._conf.page;return H.safetyCall(t,[],t+"")},setPage:function(){},setConfig:function(t){t&&typeof t=="object"&&(H.verifyConfig(t),t=this.setImgUrl(t),this._conf=H.ext({},this._conf,t))},setImgUrl:function(t){var r=t.region,e=t.imgUrl;if(r){var i=H.regionMap[r];return t.imgUrl=i||H.defaultImgUrl,t}return e&&(t.imgUrl=e),t},checkImgUrl:function(){return!0},sendRequest:function(){},sendBeacon:function(t,r,e){ya(t,r||this.getConfig("imgUrl"),e)},postData:function(){},commonInfo:function(){return{}},setCommonInfo:function(t){t&&typeof t=="object"&&(this._common=H.ext({},this._common,t))},resetPageview:function(){this.pageview=H.uu(),this.sBegin=Date.now()},getUsername:function(){if(this.username)return this.username;var t=this._conf,r=t&&t.setUsername;if(typeof r=="function")try{var e=r();typeof e=="string"&&(e=e.substr(0,40),this.username=e)}catch(i){H.warn("[arms] setUsername fail",i)}return this.username},getTraceId:function(){var t=this.rip,r=Date.now(),e=H.getSortNum(this.record),i=t+r+e+H.getRandNum(this._conf.pid);return this["EagleEye-TraceID"]=i,this.record=e,{"EagleEye-TraceID":i}},getUberTraceId:function(t){var r=this.rip,e=Date.now(),i=H.getSortNum(this.record),s=H.getRandNum(this._conf.pid),a=r+e+i+H.getNum(2)+s,n=a.substring(0,16);return t=t?"1":"0",a[0]==="0"&&(a[0]="1"),a[16]==="0"&&(a[16]="1"),{"uber-trace-id":a+":"+n+":0:"+t,traceId:a}},getB3TraceId:function(t){var r=this.rip,e=Date.now(),i=H.getSortNum(this.record),s=H.getRandNum(this._conf.pid),a=r+e+i+H.getNum(2)+s,n=a.substring(0,16);return t=t?"1":"0",a[0]==="0"&&(a[0]="1"),a[16]==="0"&&(a[16]="1"),{b3:a+"-"+n+"-"+t+"-0","X-B3-TraceId":a,"X-B3-ParentSpanId":"0","X-B3-SpanId":n,"X-B3-Sampled":t}},getPageviewId:function(){return{"EagleEye-SessionID":this.pageview}},getConfig:function(t){return t?this._conf[t]:H.ext({},this._conf)},sampling:function(t){return t===1||(typeof this.sampleCache[t]=="boolean"?this.sampleCache[t]:(this.sampleCache[t]=H.pick(t),this.sampleCache[t]))},clear:function(t){var r;clearTimeout(this.requestTimmer),this.requestTimmer=null;for(var e=this._conf&&typeof this._conf.sendRequest=="function";r=this.requestQueue.pop();)if(r.t==="res")this.postData(r,"res");else if(r.t==="error")this.postData(r,"err");else if(r.t==="api")this.postData(r,"apiSnapshot");else if(r.t==="behavior")this.postData(r,"behavior");else if(r.t==="health"&&!e&&window&&window.navigator&&typeof window.navigator.sendBeacon=="function")this.sendBeacon(r);else if(r.t==="resource"&&!e&&window&&window.navigator&&typeof window.navigator.sendBeacon=="function"){var i=JSON.stringify({resource:r.resource});delete r.resource,this.sendBeacon(r,null,i)}else r.t==="resource"?this.postData(r,"resource"):this.sendRequest(r);return t&&this.clearSelf(),this},clearSelf:function(){var t;for(clearTimeout(this.Timmer),this.Timmer=null;t=this.selfQueue.pop();)this.postData(t,"err");return this},_lg:function(t,r,e,i){var s=this,a=s._conf,n=s.getPage(),o=a.ignore||{},c=o.ignoreErrors,h=o.ignoreResErrors,f=o.ignoreUrls,p=o.ignoreApis;if(s._isRobot||H.ignoreByRule(n,f)||H.ignoreByRule(H.decode(n),f)||t==="error"&&(H.ignoreByRule(r.msg,c)||H.ignoreByRule(H.decode(r.msg),c))||t==="resourceError"&&(H.ignoreByRule(r.src,h)||H.ignoreByRule(H.decode(r.src),h))||t==="api"&&(H.ignoreByRule(r.api,p)||H.ignoreByRule(H.decode(r.api),p))||!s.checkImgUrl(a.imgUrl)||!r||a.disabled||!a.pid||i===0)return s;var u=r.dl;if(delete r.dl,r=H.ext({t,times:1,page:n,tag:a.tag||"",release:a.release||"",environment:a.environment,begin:Date.now(),c1:a.c1,c2:a.c2,c3:a.c3},r,s.commonInfo(),s._common,{pid:a.pid,_v:s.ver,pv_id:s.pageview,username:s.getUsername(),sampling:e||1,dl:u,z:H.seq()}),H.T(a.beforeReport)==="Function")try{if(!(r=a.beforeReport(r)))return s}catch(g){return s}return i===1?Or(s,r):e&&!s.sampling(e)?s:Or(s,r)},_self:function(t,r,e){var i=this,s=i._conf;if(t!=="error"||!i.checkImgUrl(s.imgUrl)||!r||s.disabled||!s.pid||!Lr||e&&!i.sampling(e))return i;r=H.ext({t,times:1,page:H.selfErrPage,tag:s.pid,begin:Date.now()},r,{pid:Lr,_v:i.ver,sampling:e||1,z:H.seq()});var a=i.selfQueue[0];if(a){a.times++;try{a.err&&r.err&&a.err.msg_raw&&r.err.msg_raw&&a.err.msg_raw.split("&").indexOf(r.err.msg_raw)<0&&a.err.msg_raw.length<1e3&&(a.err.msg_raw+="&"+r.err.msg_raw)}catch(n){}}else i.selfQueue.unshift(r),i.onReady(function(){i.sdkFlag&&(i.sdkFlag=!1,i.Timmer=H.delay(function(){i.clearSelf()},1e4))})},custom:function(t,r){if(!t||typeof t!="object")return this;var e=!1,i={begin:Date.now()};return H.each(t,function(s,a){return!(e=a&&a.length<=20)&&H.warn("[retcode] invalid key: "+a),i["x-"+a]=s,e}),e?this._lg("custom",i,r||1):this}},Mr.exports=Ot;var wa=Mr.exports,$=ye,dt=wa,_a=["api","success","time","code","msg","trace","traceId","begin","pv_id","sid","seq","domain","flag","apiSnapshot","tag","c1","c2","c3"],Oi=function(t){var r=(t.key||"default").split("::");return r.length>1?$.ext(t,{group:r[0],key:r[1]}):$.ext(t,{group:"default_group",key:r[0]})},pt=function(t){dt.call(this,t);var r;try{r=typeof performance=="object"?performance.timing.fetchStart:Date.now()}catch(e){r=Date.now()}return this._startTime=r,this};pt.prototype=$.createObject(dt.prototype),$.ext(dt.dftCon,{startTime:null}),$.ext(pt.prototype,{constructor:pt,_super:dt,sum:function(t,r,e){try{var i=$.dealParam(t,r,1);return this._lg("sum",Oi(i),e)}catch(s){$.warn("[retcode] can not get parseStatData: "+s)}},avg:function(t,r,e){try{var i=$.dealParam(t,r,0);return this._lg("avg",Oi(i),e)}catch(s){$.warn("[retcode] can not get parseStatData: "+s)}},percent:function(t,r,e,i){try{return this._lg("percent",Oi({key:t,subkey:r,val:e||0,begin:Date.now()}),i)}catch(s){$.warn("[retcode] can not get parseStatData: "+s)}},msg:function(t,r){if(t&&!(t.length>180))return this.custom({msg:t},r)},error:function(t,r){if(!t)return $.warn("[retcode] invalid param e: "+t),this;arguments.length===1?(typeof t=="string"&&(t={message:t},r={}),typeof t=="object"&&(r=t=t.error||t)):(typeof t=="string"&&(t={message:t}),typeof r!="object"&&(r={}));var e=t.name||"CustomError",i=t.message||"",s=t.stack||"";r=r||{};var a=typeof location=="object"&&typeof location.href=="string"&&location.href.substring(0,500)||"";if($.checkSDKError(i,r.filename)){var n=/^Script error\.?$/,o=t.msg||t.message;if($.ignoreByRule(o,n)||$.ignoreByRule($.decode(o),n))return this;var c={msg:$.selfErrKey,err:{msg_raw:$.encode(t.msg||t.message)}};return this._self("error",c,1)}for(var h={begin:Date.now(),cate:e,msg:i&&i.substring(0,1e3),stack:s&&s.substring(0,1e3),file:$.removeUrlSearch(r.filename||""),line:r.lineno||"",col:r.colno||"",err:{msg_raw:$.encode(i),stack_raw:$.encode(s)},dl:a},f=["tag","c1","c2","c3"],p=0;p<f.length;p++){var u=f[p];r[u]&&(h[u]=r[u])}var g=(this.getConfig("ignore")||{}).ignoreErrors;return $.ignoreByRule(h.msg,g)||$.ignoreByRule($.decode(h.msg),g)?this:(this.beforeSend&&this.beforeSend("error",h),this._lg("error",h,1))},behavior:function(t){if(t){var r=typeof t=="object"&&t.behavior?t:{behavior:t};return this.beforeSend&&this.beforeSend("behavior",r),this._lg("behavior",r,1)}},api:function(t,r,e,i,s,a,n,o,c,h,f,p,u,g,m,d){if(!t)return $.warn("[retcode] api is null"),this;if(t=typeof t=="string"?{api:t,success:r,time:e,code:i,msg:s,begin:a,traceId:n,pv_id:o,apiSnapshot:c,domain:h,flag:p,tag:u,c1:g,c2:m,c3:d}:$.sub(t,_a),!$.checkAPI(t.api,!0))return this;t.code=t.code||"";var S=t.msg||"";if(S=typeof S=="string"?S.substring(0,1e3):S,t.msg=S,t.success=t.success?1:0,t.time=+t.time,t.begin=t.begin,t.traceId=t.traceId||"",t.pv_id=t.pv_id||"",t.domain=t.domain||"",t.flag=t.flag,t.dl=typeof location=="object"&&typeof location.href=="string"&&location.href.substring(0,500)||"",t.apiSnapshot&&(typeof t.apiSnapshot=="object"&&(t.apiSnapshot=JSON.stringify(t.apiSnapshot)),typeof t.apiSnapshot!="string"&&delete t.apiSnapshot,t.apiSnapshot.length>2e3&&(t.apiSnapshot=t.apiSnapshot.substring(0,2e3))),f&&(t.traceOrigin=f),!t.api||isNaN(t.time))return $.warn("[retcode] invalid time or api"),this;var b=(this.getConfig("ignore")||{}).ignoreApis;return $.ignoreByRule(t.api,b)||$.ignoreByRule($.decode(t.api),b)?this:t.time<0?this:(this.beforeSend&&this.beforeSend("api",t),this._lg("api",t,t.success&&this.getConfig("sample"),t.flag))},speed:function(t,r,e){var i=this,s=this.getConfig("startTime")||this._startTime;return/^s(\d|1[0])$/.test(t)?(r=typeof r!="number"?Date.now()-s:r>=s?r-s:r,i.speedCache=i.speedCache||{},i.speedCache[t]=r,i.speedCache.begin=s,clearTimeout(i.speedTimmer),i.speedTimmer=setTimeout(function(){e||(i.speedCache.page=i.getPage(!0)),i._lg("speed",i.speedCache),i.speedCache=null},5e3),i):($.warn("[retcode] invalid point: "+t),i)},performance:function(t){if(t&&typeof t=="object"&&!this.hasSendPerf){var r={},e={},i=this.getConfig("autoSendPerf");if(t.autoSend&&i)return e=$.ext(this.perfData||{},t),this.hasSendPerf=!0,this._lg("perf",e,this.getConfig("sample"));if(t.autoSend&&!i)return delete t.autoSend,this.perfData?(e=$.ext(this.perfData||{},t),this.hasSendPerf=!0,this._lg("perf",e,this.getConfig("sample"))):void(this.perfData=t);for(var s in t)(/^t([1-9]|1[0])$/.test(s)||s==="ctti"||s==="cfpt")&&(r[s]=t[s]);if(t.autoSend===!0||!i&&(i||this.perfData))return t.autoSend!==!0&&i===!1&&this.perfData?(r=$.ext(this.perfData||{},r),this.hasSendPerf=!0,this._lg("perf",r,this.getConfig("sample"))):void 0;this.perfData=$.ext(this.perfData||{},r)}},resource:function(t,r){if(!t||!$.isPlainObject(t))return $.warn("[arms] invalid param data: "+t),this;var e=Object.keys(t),i=["begin","dom","load","res","dl"],s=!1;for(var a in i)if(e.indexOf(i[a])<0){s=!0;break}if(s)return $.warn("[arms] lack param data: "+t),this;var n={begin:t.begin||Date.now(),dom:t.dom||"",load:t.load||"",res:$.isArray(t.res)?JSON.stringify(t.res):JSON.stringify([]),dl:t.dl||""};return this._lg("res",n,r)},event:function(t,r){if(typeof t=="object"&&t&&t.key){var e={},i=["key","success","time","c1","c2","c3"];for(var s in t)i.indexOf(s)>-1&&(e[s]=t[s]);e.success=t.success===!1?0:1,this._lg("event",e,r)}}}),pt._super=dt,pt._root=dt,dt.Reporter=pt,Cr.exports=pt;var Ra=Cr.exports,Vr={exports:{}},Dr=ye,It=typeof window=="object"?window:{},Ia="catch",Vt=It.__oFetch_||It.fetch;Vt=typeof Vt=="function"?Vt:void 0,Vr.exports=function(t,r){var e=-1;typeof t=="object"&&(e=t.z,t=Dr.serialize(t));var i=r+t;if(Vt)return Vt(i,{method:"HEAD",mode:"no-cors"})[Ia](Dr.noop);if(It.document&&It.document.createElement){var s="__request_hold_"+e,a=It[s]=new Image;a.onload=a.onerror=function(){It[s]=void 0},a.src=i,a=null}};var Ea=Vr.exports,xr={exports:{}},Aa=ye,Ur=typeof window=="object"?window:{},ri=Ur.__oXMLHttpRequest_||Ur.XMLHttpRequest;ri=typeof ri=="function"?ri:void 0,xr.exports=function(t,r){try{var e=new ri;e.open("POST",r,!0),e.setRequestHeader("Content-Type","text/plain"),e.send(JSON.stringify(t))}catch(i){Aa.warn(`[retcode] Failed to log, exception is :
|
|
3
|
-
`+i)}};var Ta=xr.exports,Vi,Br;function Pa(){if(Br)return Vi;Br=1;var t=ye;return Vi=function(r,e){var i=[],s=null,a=e&&e.location&&e.location.href,n=void 0,o=null,c=function(u,g,m){if(u!==null){var d=u[g];u[g]=m(d)}},h=function(u){var g,m,d,S,b,w=[];if(!u||typeof u.tagName!="string")return"";if(w.push(u.tagName.toLowerCase()),typeof u.id=="string"&&w.push("#".concat(u.id)),typeof(g=u.className)=="string")for(m=g.split(/\s+/),b=0;b<m.length;b++)w.push(".".concat(m[b]));var _=["type","name","title","alt","data-arms-attr"];for(b=0;b<_.length;b++)d=_[b],typeof(S=u.getAttribute(d))=="string"&&w.push("[".concat(d,'="').concat(S,'"]'));return w.join("")},f=function(u,g){return function(m){if(m&&m!==o){o=m;var d;try{d=m.target}catch(b){d="<unknown>"}if(d.length!==0){var S={type:"ui.".concat(u),data:{message:function(b){if(!b||b.nodeType!==1)return"";for(var w=b||null,_=[],R=0,x=0,z=3,j="";w&&R++<5&&!((j=h(w))==="html"||R>1&&x+_.length*z+j.length>=80);)_.push(j),x+=j.length,w=w.parentNode;return _.reverse().join(" > ")}(d)},timestamp:Date.now()};u==="click"?s&&s.addBehavior(S):u==="keypress"&&(n||s&&s.addBehavior(S),clearTimeout(n),n=setTimeout(function(){n=void 0},100))}}}},p=function(){if(function(){var d=e&&e.chrome,S=d&&d.app&&d.app.runtime,b="history"in e&&!!e.history.pushState&&!!e.history.replaceState;return!S&&b}()){var u=function(d,S){var b={type:"navigation",data:{from:d,to:S}};s&&s.addBehavior(b),a=S},g=e.onpopstate;e.onpopstate=function(){for(var d=arguments.length,S=new Array(d),b=0;b<d;b++)S[b]=arguments[b];var w=e.location.href;if(u(a,w),g)return g.apply(this,S)};var m=function(d){return function(){for(var S=arguments.length,b=new Array(S),w=0;w<S;w++)b[w]=arguments[w];var _=b.length>2?b[2]:void 0;return _&&u(a,String(_)),d.apply(this,b)}};c(e.history,"pushState",m),c(e.history,"replaceState",m)}};t.ext(r.prototype,{addBehavior:function(u){if(this.getConfig("behavior")&&u&&typeof u=="object"){var g={},m=u.data||{};if(u.type)g=m;else{if(typeof m.name!="string"||typeof m.message!="string")return;g.name=m.name.substr(0,20),g.message=m.message.substr(0,200)}g.message&&(g.message=t.encode(g.message));var d={type:u.type||"custom",data:g||{},timestamp:u.timestamp||Date.now(),page:u.page||e&&e.location&&e.location.pathname};return i.push(d),i=i.slice(-100)}},getBehavior:function(){return i||[]},setBehavior:function(u){return u&&(i=u),i},reportBehavior:function(u){var g=this;g.getConfig("behavior")&&(g.sendBhTimer&&(clearTimeout(g.sendBhTimer),g.sendBhTimer=void 0),g.sendBhTimer=setTimeout(function(){i&&i.length>0&&(g.behavior(i),i=[],g.sendBhTimer=void 0,u&&typeof u=="function"&&u())},0))},initBehavior:function(){if(!this.hasInitBehavior&&!s){try{(function(){if(document&&document.referrer&&document.location){var g=document.referrer,m=document.location.href;if(g!==""){var d={type:"navigation",data:{from:g,to:m}};a=m,s&&s.addBehavior(d)}}})(),e&&e.document&&e.document.addEventListener&&(e.document.addEventListener("click",f("click"),!1),e.document.addEventListener("keypress",f("keypress"),!1)),p();var u=this.getConfig("enableConsole");u&&function(g){if(e&&e.console){var m=["debug","info","warn","log","error","assert"];t.isArray(g)&&(m=g);for(var d=0;d<m.length;d++){var S=m[d];S&&t.isString(S)&&e.console[S]&&typeof e.console[S]=="function"&&c(e.console,S,function(b){var w=S;return function(){for(var _=arguments.length,R=new Array(_),x=0;x<_;x++)R[x]=arguments[x];var z={type:"console",data:{level:w,message:R}};if(s&&s.addBehavior(z),w==="error")for(var j=0;j<R.length;j++){var O=R[j];O&&O.message&&O.stack&&s&&s.errorHandler(new ErrorEvent("error",{error:O,message:O.message}))}b&&Function.prototype.apply.call(b,e.console,R)}})}}}(u)}catch(g){t.warn("[arms] error in initBehavior",g)}s=this,this.hasInitBehavior=!0}return this}})},Vi}var Hr={},Fr;function Di(){return Fr||(Fr=1,Hr.TIMING_KEYS=["startTime","fetchStart","domainLookupStart","domainLookupEnd","connectStart","connectEnd","requestStart","responseStart","responseEnd","","domInteractive","","domContentLoadedEventEnd","","loadEventStart","","msFirstPaint","secureConnectionStart","redirectStart","redirectEnd"]),Hr}var xi,jr;function ka(){if(jr)return xi;jr=1;var t=ye,r=Di(),e=r.TIMING_KEYS;return xi=function(){var i=t.win||{},s=i.performance;if(!s||typeof s!="object"||typeof s.getEntriesByType!="function")return null;var a={},n=s.timing||{},o=s.getEntriesByType("resource")||[];if(a.begin=n[e[1]]||Date.now(),typeof i.PerformanceNavigationTiming=="function"){var c=s.getEntriesByType("navigation")[0];c&&(n=c)}return t.each({dom:[10,8],load:[14,1]},function(h,f){var p=n[e[h[1]]],u=n[e[h[0]]];if(p>0&&u>0){var g=Math.round(u-p);g>=0&&g<6e5&&(a[f]=g)}}),a.res=JSON.stringify(o),a},xi}var Ui,$r;function Ca(){if($r)return Ui;$r=1;var t=ye,r=Di(),e=r.TIMING_KEYS;return Ui=function(){var i=t.win||{},s=i.performance;if(!s||typeof s!="object")return null;var a={},n=s.timing||{},o=Date.now(),c=1;if(typeof i.PerformanceNavigationTiming=="function"){var h=s.getEntriesByType("navigation")[0];h&&(n=h,c=2)}t.each({dns:[3,2],tcp:[5,4],ssl:[5,17],ttfb:[7,6],trans:[8,7],dom:[10,8],res:[14,12],firstbyte:[7,2],fpt:[8,1],tti:[10,1],ready:[12,1],load:[14,1]},function(m,d){var S=n[e[m[1]]],b=n[e[m[0]]];if(c===2||S>0&&b>0){var w=Math.round(b-S);w>=0&&w<6e5&&(a[d]=w)}});var f=i.navigator.connection,p=s.navigation||{};a.ct=f?f.effectiveType||f.type:"";var u=f&&(f.downlink||f.downlinkMax||f.bandwidth)||null;if((u=u>999?999:u)&&(a.bandwidth=u),a.navtype=p.type===1?"Reload":"Other",c===1&&n[e[16]]>0&&n[e[1]]>0){var g=n[e[16]]-n[e[1]];g>=0&&g<36e5&&(a.fpt=g)}return c===1&&n[e[1]]>0?a.begin=n[e[1]]:c===2&&a.load>0?a.begin=o-a.load:a.begin=o,a},Ui}var Wr,Kr;function Ma(){return Kr||(Kr=1,Wr=function(t,r,e){var i=ye,s=ka(),a=Ca(),n=null,o=e.documentElement,c=r.innerWidth||o.clientWidth||e.body.clientWidth,h=r.innerHeight||o.clientHeight||e.body.clientHeight,f=r.navigator.connection,p={sr:screen.width+"x"+screen.height,vp:c+"x"+h,ct:f?f.effectiveType||f.type:""},u={},g=function(d,S,b,w,_){if(S===void 0){var R,x;if(!u[d]){R=new RegExp(d+"=([^;]+)");try{x=R.exec(e.cookie)}catch(j){return i.warn("[retcode] can not get cookie:",j),null}x&&(u[d]=x[1])}return u[d]}var z=d+"="+S;z+="; path=/",b&&(z+="; max-age="+b);try{return e.cookie=z,!!e.cookie}catch(j){return i.warn("[retcode] can not set cookie: ",j),!1}},m=function(d){var S=d._conf.uid||g("_nk_")||g("_bl_uid");return!S&&(S=i.uu(),!g("_bl_uid",S,15552e3))?null:S};return i.ext(t.prototype,{activeErrHandler:function(d){return n&&!d?this:(n=this,this)},errorHandler:function(d){if(!d)return this;var S=d.type;if(S==="error"){var b=d.target||d.srcElement;!b||!b.tagName||d.message||d.filename||d.lineno||d.colno?this.error(d.error||{message:d.message},d):this.resourceErrorHandler(d)}else S==="unhandledrejection"&&i.T(d.reason,"Error")&&i.checkAutoError(d.reason)&&this.error(d.reason);try{this.getConfig("behavior")&&this.reportBehavior&&this.reportBehavior()}catch(w){}return this},resourceErrorHandler:function(d){var S=this,b=d.target||d.srcElement;try{var w=S.getSrc(b),_=typeof b.tagName=="string"?b.tagName.toLowerCase():"",R=S.getXPath(b,5),x=i.getURL(w),z={src:w&&w.substring(0,1e3),node_name:_,xpath:R,res_type:i.getResType(_,w),res_name:x.path,domain:x.domain};return S._conf.enableResource&&S.fixResourceStatus&&d.timeStamp&&S.fixResourceStatus({src:w,node_name:_,res_type:i.getResType(_,w),timeStamp:d.timeStamp,domain:x.domain}),S._lg("resourceError",z),S}catch(j){return i.warn("[ARMS] resourceErrorHandler error :",j),S}},getSrc:function(d){var S=d.src||d.href;try{if(!S){var b=(typeof d.tagName=="string"?d.tagName.toLowerCase():"")==="object",w=d.getAttribute("classid")&&d.getAttribute("classid").toLowerCase()==="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"||d.getAttribute("type")==="application/x-shockwave-flash";b&&w&&(S=d.getAttribute("data")||d.getAttribute("codebase")),S||(S=d.outerHTML||d.innerHTML)}}catch(_){S=""}return S},getXPath:function(d,S){var b=d.id?"#"+d.id:"",w=typeof d.className=="string"?"."+d.className.split(" ").join("."):"",_=(typeof d.tagName=="string"?d.tagName.toLowerCase():"")+b+w;return d.parentNode&&d.parentNode.tagName&&S-1!=0?this.getXPath(d.parentNode,S-1)+" > "+_:_},sendPerformance:function(d){var S=this;S.onReady(function(){var b=a();b&&b.load&&b.load>0&&(b.page=S.getPage(!0),d&&(b=i.ext(b,d)),b.autoSend=!0,S.performance(b))})},sendResources:function(d){var S=this;S.onReady(function(){var b=s();b&&b.load&&b.load>0&&(b.load&&b.load<=2e3||b.load&&b.load<=8e3&&Math.random()>.05||(b.page=S.getPage(!0),b.dl=location.href,d&&(b=i.ext(b,d)),S._lg("res",b,S.getConfig("sample"))))})},sendPV:function(){var d=this;d.onReady(function(){var S=function(b){var w=m(b),_=r.devicePixelRatio||1;return{uid:w,dt:e.title,dl:location.href,dr:e.referrer,dpr:_.toFixed(2),de:(e.characterSet||e.defaultCharset||"").toLowerCase(),ul:o.lang,begin:Date.now()}}(d);S&&S.uid&&d._lg("pv",S,d.getConfig("pvSample"))})},commonInfo:function(){return p.uid=m(this),p.sid=function(d){if(d.session)return d.session;var S;try{if(typeof window=="object"&&typeof sessionStorage=="object"&&typeof sessionStorage.getItem=="function")return typeof(S=sessionStorage.getItem("_bl_sid"))=="string"?(d.session=S,S):(S=i.uu(),d.session=S,typeof sessionStorage.setItem=="function"&&sessionStorage.setItem("_bl_sid",S),S)}catch(b){i.warn("[ARMS] getSid error :",b)}return d.session=S=i.uu(),S}(this),p},handleUnload:function(d){var S=Date.now();if(S-this._lastUnload<200)return this;this._lastUnload=S,this.sendHealth(d),this.speedCache&&(this._lg("speed",this.speedCache),this.speedCache=null,clearTimeout(this.speedTimmer)),this._conf&&this._conf.enableResource&&this.resourceComboReport(),this.clear(!0)},bindHashChange:function(d){var S=this;if(!d^S.hashChangeHandler)return S;d?(S.hackHistoryState(),S.hashChangeHandler=function(b){var w=S._conf.parseHash(location.hash);w&&S.setPage(w,b!==!1)},S.stateChangeHandler=function(b){var w=S._conf.parseHash(b.detail);w&&S.setPage(w)},i.on(r,"hashchange",S.hashChangeHandler),i.on(r,"historystatechange",S.stateChangeHandler),S.hashChangeHandler(!1)):(i.off(r,"hashchange",S.hashChangeHandler),i.off(r,"historystatechange",S.stateChangeHandler),S.hashChangeHandler=null,S.stateChangeHandler=null)},initHandler:function(){var d=this;if(d.hasInitHandler)return d;var S=d._conf;return i.on(r,"beforeunload",function(){d.handleUnload(0)}),d.bindHashChange(S.enableSPA),d.activeErrHandler(!1),d.hasInitHandler=!0,d}}),i.on(r,"error",function(d){n&&n.errorHandler(d)},!1,!0).on(r,"unhandledrejection",function(d){n&&n.errorHandler(d)}),t}),Wr}var Bi,qr;function Na(){if(qr)return Bi;qr=1;var t=ye,r=500;return Bi=function(e,i,s){function a(p,u,g){var m=0,d=p.tagName;if(d!=="SCRIPT"&&d!=="STYLE"&&d!=="META"&&d!=="HEAD"){var S=p.children?p.children.length:0;if(S>0)for(var b=p.children,w=S-1;w>=0;w--)m+=a(b[w],u+1,m>0);if(m<=0&&!g&&!(p.getBoundingClientRect&&p.getBoundingClientRect().top<o))return 0;m+=1+.5*u}return m}function n(p){for(var u=1;u<p.length;u++)if(p[u].score<p[u-1].score)return p.splice(u,1),n(p);return p}var o=i.innerHeight||0,c=[],h=null,f=0;t.ext(e.prototype,{initFmpObserver:function(p){var u=this;if(!u._conf||!u._conf.useFmp)return null;if(!i.MutationObserver)return t.warn("[retcode] first meaningful paint can not be retrieved"),u.sendPerformance(),null;t.on(i,"beforeunload",function(){u.endObserving(0,!0)});var g=i.MutationObserver;return(h=new g(function(){(function(m){var d=Date.now()-m,S=s.querySelector("body");if(S){var b=0;b+=a(S,1,!1),c.push({score:b,t:d})}else c.push({score:0,t:d})})(u._startTime)})).observe(document,{childList:!0,subtree:!0}),f=1,u.onReady(function(){u.endObserving(p)}),h},endObserving:function(p,u){var g=this;if(h&&f)if(g.fmpTimmer&&(clearTimeout(g.fmpTimmer),g.fmpTimmer=null),u||!function(b,w){var _=Date.now()-b;return!(_>w||_-(c&&c.length&&c[c.length-1].t||0)>2*r)}(g._startTime,p)){h.disconnect(),f=0,c=n(c);for(var m=null,d=1;d<c.length;d++)if(c[d].t>=c[d-1].t){var S=c[d].score-c[d-1].score;(!m||m.rate<=S)&&(m={t:c[d].t,rate:S})}m&&m.t>0&&m.t<36e5?g.sendPerformance({fmp:m.t}):g.sendPerformance()}else g.fmpTimmer=t.delay(function(){g.endObserving(p)},r)}})},Bi}var Jr,Gr;function La(){return Gr||(Gr=1,Jr=function(t,r){var e=ye,i=null,s=e.getCurDomain(),a=function(f,p,u,g,m,d,S,b,w,_,R,x,z){var j=e.J(m)||null,O=e.safetyCall(p,[j,g],null);if(!O)return!1;var ie=O.code||d,Ae=!("success"in O)||O.success;f.api(u,Ae,S,ie,O.msg,b,w,_,Ae?{}:R,s,x,z)},n="fetch",o="__oFetch_",c="__oXMLHttpRequest_",h="XMLHttpRequest";return e.ext(t.prototype,{removeHook:function(f,p){return i&&(p||this===i)?(r[o]&&(r[n]=r[o],delete r[o]),r[c]&&(r[h]=r[c],delete r[c]),i=null,this):this},addHook:function(f){return!f&&i?this:(i||(function(){if(typeof r[n]=="function"){var p=r[n];r[o]=p,r[n]=function(u,g){var m=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),d=i;if(!d||!d.api||g&&(g.method==="HEAD"||g.mode==="no-cors"))return p.apply(r,m);g||(g={});var S=Date.now(),b=d._conf,w=e.duration(),_=(u&&typeof u!="string"?u.url:u)||"",R=_;_=e.cutUrlSearch(_);var x=(b.ignore||{}).ignoreApis,z=b.parseTraceId;if(!e.checkAPI(_,!0)||e.ignoreByRule(_,x))return p.apply(r,m);_=e.filterByRule(_,R,b.ignoreApiPath?b.ignoreApiPath:b.apiHelper);var j=b.enableLinkTrace,O="",ie="",Ae=d.getConfig("pid"),ut=null,pe=d.getConfig("sample"),ge=d.getConfig("linkType"),Re=1;if(pe&&!d.sampling(pe)&&(Re=0),j){var qe="";try{qe=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(Z){qe=""}var Ze=e.checkSameOrigin(R,qe);if(d.getConfig("enableApiCors")||Ze)if(u&&typeof u!="string")try{if(m[0].headers&&typeof m[0].headers.get=="function"&&typeof m[0].headers.append=="function")switch(ge){case"arms":var et=m[0].headers.get("EagleEye-TraceID"),Ve=m[0].headers.get("EagleEye-SessionID"),Me=m[0].headers.get("EagleEye-pAppName");et?O=et:(O=d.getTraceId()["EagleEye-TraceID"],m[0].headers.append("EagleEye-TraceID",O)),Ve?ie=Ve:(ie=d.getPageviewId()["EagleEye-SessionID"],m[0].headers.append("EagleEye-SessionID",ie)),Me||m[0].headers.append("EagleEye-pAppName",Ae);break;case"b3":var He=m[0].headers.get("X-B3-TraceId");if(He)O=He;else{var Te=d.getB3TraceId(Re);m[0].headers.append("X-B3-TraceId",Te["X-B3-TraceId"]),m[0].headers.append("X-B3-ParentSpanId",Te["X-B3-ParentSpanId"]),m[0].headers.append("X-B3-SpanId",Te["X-B3-SpanId"]),m[0].headers.append("X-B3-Sampled",Te["X-B3-Sampled"]),m[0].headers.append("X-Request-ID",e.guid()),O=Te["X-B3-TraceId"]}ie=d.pageview;break;case"tracing":default:var be=m[0].headers.get("uber-trace-id");be?O=be.split(":")[0]:(be=d.getUberTraceId(Re),m[0].headers.append("uber-trace-id",be["uber-trace-id"]),O=be.traceId),ie=d.pageview}}catch(Z){e.warn(`[retcode] fetch failed to set header, exception is :
|
|
4
|
-
`+Z)}else switch(g.headers=g.headers?g.headers:{},ge){case"arms":g.headers["EagleEye-TraceID"]?O=g.headers["EagleEye-TraceID"]:(O=d.getTraceId()["EagleEye-TraceID"],g.headers["EagleEye-TraceID"]=O),g.headers["EagleEye-SessionID"]?ie=g.headers["EagleEye-SessionID"]:(ie=d.getPageviewId()["EagleEye-SessionID"],g.headers["EagleEye-SessionID"]=ie),g.headers["EagleEye-pAppName"]||(g.headers["EagleEye-pAppName"]=Ae);break;case"b3":if(g.headers["X-B3-TraceId"])O=g.headers["X-B3-TraceId"];else{var ve=d.getB3TraceId(Re);g.headers["X-B3-TraceId"]=ve["X-B3-TraceId"],g.headers["X-B3-ParentSpanId"]=ve["X-B3-ParentSpanId"],g.headers["X-B3-SpanId"]=ve["X-B3-SpanId"],g.headers["X-B3-Sampled"]=ve["X-B3-Sampled"],g.headers["X-Request-ID"]=e.guid(),O=ve["X-B3-TraceId"]}ie=d.getPageviewId()["EagleEye-SessionID"];break;case"tracing":default:if(g.headers["uber-trace-id"])O=g.headers["uber-trace-id"].split(":")[0];else{var Je=d.getUberTraceId(Re);g.headers["uber-trace-id"]=Je["uber-trace-id"],O=Je.traceId}ie=d.getPageviewId()["EagleEye-SessionID"]}}return p.apply(r,m).then(function(Z){if(!d||!d.api)return Z;try{if(!Z||typeof Z.clone!="function")return Z;var fe=Z.clone(),Ge=fe.headers;if(Ge&&typeof Ge.get=="function"){var Yt=Ge.get("content-type");if(Yt&&!/(text)|(json)/.test(Yt))return Z;if(!O){var Mt=e.parseFetchHeaders(Ge);typeof Mt=="object"&&Mt["eagleeye-traceid"]&&(O=Mt["eagleeye-traceid"],ut="response")}}var Qt=w();return fe.text().then(function(_t){if(!O&&e.isFunction(z)){var ht=z(fe,_t);ht&&e.isString(ht)&&(O=ht)}var Zt=e.getFetchSnapshot(m,_t,Ge);fe.ok?a(d,b.parseResponse,_,R,_t,fe.status||200,Qt,S,O,ie,Zt,ut,Re):(d.api(_,!1,Qt,fe.status||404,fe.statusText,S,O,ie,Zt,s,ut,Re),b.enableResource&&i.fixResourceStatus&&i.fixResourceStatus({src:fe.url,res_type:"api"}))}),Z}catch(_t){return e.warn("[ARMS] fetch response error :",_t),Z}}).catch(function(Z){if(!d||!d.api)throw Z;var fe=w();throw d.api(_,!1,fe,Z.name||"Error",Z.message,S,O,ie,{},s),b.enableResource&&i.fixResourceStatus&&i.fixResourceStatus({src:R,res_type:"api"}),Z})},r[n].toString=e.createFakeToString(n)}}(),function(){if(typeof r[h]=="function"){var p,u=r[h];r[c]=u;var g=function(m){var d=new u(m),S=i;if(!S||!S.api||!d.addEventListener)return d;var b,w,_,R,x=d.send,z=d.open,j=d.setRequestHeader,O=S._conf,ie=(O.ignore||{}).ignoreApis,Ae=O.parseTraceId,ut=S.getConfig("enableLinkTrace"),pe="",ge="",Re="",qe=null,Ze=S.getConfig("sample"),et=S.getConfig("linkType"),Ve=1;return Ze&&!S.sampling(Ze)&&(Ve=0),d.open=function(Me,He){p=Me;var Te=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);z.apply(d,Te),R=He||"",_=e.cutUrlSearch(R);var be=!e.checkAPI(_,!0)||e.ignoreByRule(_,ie);if(_=_?e.filterByRule(_,R,O.ignoreApiPath?O.ignoreApiPath:O.apiHelper):"",!be&&ut){var ve="";try{ve=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(Ge){ve=""}var Je=e.checkSameOrigin(R,ve);if((S.getConfig("enableApiCors")||Je)&&j&&typeof j=="function")switch(et){case"arms":pe=S.getTraceId()["EagleEye-TraceID"],j.apply(d,["EagleEye-TraceID",pe]),ge=S.getPageviewId()["EagleEye-SessionID"],j.apply(d,["EagleEye-SessionID",ge]),Re=S.getConfig("pid"),j.apply(d,["EagleEye-pAppName",Re]);break;case"b3":var Z=S.getB3TraceId(Ve);j.apply(d,["X-B3-TraceId",Z["X-B3-TraceId"]]),j.apply(d,["X-B3-ParentSpanId",Z["X-B3-ParentSpanId"]]),j.apply(d,["X-B3-SpanId",Z["X-B3-SpanId"]]),j.apply(d,["X-B3-Sampled",Z["X-B3-Sampled"]]),j.apply(d,["X-Request-ID",e.guid()]),pe=Z["X-B3-TraceId"],ge=S.getPageviewId()["EagleEye-SessionID"];break;case"tracing":default:var fe=S.getUberTraceId(Ve);j.apply(d,["uber-trace-id",fe["uber-trace-id"]]),pe=fe.traceId,ge=S.getPageviewId()["EagleEye-SessionID"]}}},d.send=function(){b=Date.now(),w=e.duration();var Me=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);x.apply(d,Me)},e.on(d,"readystatechange",function(){if(_&&d.readyState===4){var Me=w(),He=e.getXhrSnapshot(R,p,d);if(!pe){var Te=e.parseXhrHeaders(typeof d.getAllResponseHeaders=="function"&&d.getAllResponseHeaders()||"");typeof Te=="object"&&Te["eagleeye-traceid"]&&(pe=Te["eagleeye-traceid"],qe="response")}if(!pe&&e.isFunction(Ae)){var be=Ae(d);be&&e.isString(be)&&(pe=be)}if(d.status>=200&&d.status<=299){var ve=d.status||200;if(typeof d.getResponseHeader=="function"){var Je=d.getResponseHeader("Content-Type");if(Je&&!/(text)|(json)/.test(Je))return}d.responseType&&d.responseType!=="text"?S.api(_,!0,Me,ve,"",b,pe,ge,{},s,qe,Ve):a(S,O.parseResponse,_,R,d.responseText,ve,Me,b,pe,ge,He,qe,Ve)}else S.api(_,!1,Me,d.status||"FAILED",d.statusText,b,pe,ge,He,s,qe,Ve),O.enableResource&&i.fixResourceStatus&&i.fixResourceStatus({src:d.responseURL||R,res_type:"api"})}}),d};g.prototype=u.prototype,e.each(Object.keys(u),function(m){g[m]=u[m]}),r[h]=g,r[h].toString=e.createFakeToString(h)}}()),i=this,this)},initHook:function(){return this.hasInitHook?this:(this.getConfig("disableHook")||this.addHook(),this.hasInitHook=!0,this)}}),t}),Jr}var zr,Xr;function Oa(){return Xr||(Xr=1,zr=function(t,r){var e=ye,i=r.history||{},s=r.document,a=function(o,c){var h;r.CustomEvent?h=new CustomEvent(o,{detail:c}):((h=s.createEvent("HTMLEvents")).initEvent(o,!1,!0),h.detail=c),r.dispatchEvent(h)},n=function(o){var c=i[o];typeof c=="function"&&(i[o]=function(h,f,p){var u=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),g=location.href,m=c.apply(i,u);if(!p||typeof p!="string"||p===g)return m;try{var d=g.split("#"),S=p.split("#"),b=e.cutUrlSearch(d[0]),w=e.cutUrlSearch(S[0]),_=d[1]&&d[1].replace(/^\/?(.*)/,"$1"),R=S[1]&&S[1].replace(/^\/?(.*)/,"$1");_!==R?a("historystatechange",R):b!==w&&a("historystatechange",w)}catch(x){e.warn("[retcode] error in "+o+": "+x)}return m},i[o].toString=e.createFakeToString(o))};e.ext(t.prototype,{hackHistoryState:function(){return this.hasHackedHistoryState?this:(n("pushState"),n("replaceState"),this.hasHackedHistoryState=!0,this)}})}),zr}var Hi,Yr;function Va(){if(Yr)return Hi;Yr=1;var t=ye,r=Di(),e=r.TIMING_KEYS;return Hi=function(i,s){function a(c,h,f){if(c instanceof s.PerformanceResourceTiming&&c.initiatorType){var p=t.getResType(c.initiatorType,c.name),u=h.resourceTypes||[],g=(h.ignore||{}).ignoreResources;if(p&&u.includes(p)&&!t.ignoreByRule(c.name,g)&&!t.ignoreByRule(t.decode(c.name),g)){var m=c[e[0]],d=c[e[1]],S=c[e[2]],b=c[e[3]],w=c[e[4]],_=c[e[5]],R=c[e[6]],x=c[e[7]],z=c[e[8]],j=c[e[18]],O=c[e[19]];if(!f.has(c)&&(!t.areInOrder(m,d,S,b,w,_,R,x,z)||m>x))return;if(j<m&&(j=m),O<m&&(O=d),t.areInOrder(m,j,O,d))return{domain:t.getURL(c.name).domain,res_type:p,src_type:t.getSrcType(c.name,h.cdnHostList),success:1,size:Math.round(c.decodedBodySize),duration:Math.round(c.duration),timeStamp:c.responseEnd,timing:c}}}}var n="_resource-"+Date.now(),o="_resource_error-"+Date.now();t.ext(i.prototype,{initResource:function(){var c=this,h=s.performance,f=s.PerformanceObserver;if(c[o]||(c[o]=new WeakMap),!h||!f||typeof h!="object"||typeof h.getEntriesByType!="function")return null;var p=h.getEntriesByType("resource")||[];return setTimeout(function(){c.setResource(p)},10),new f(function(u){setTimeout(function(){c.setResource(u.getEntries())},10)}).observe({entryTypes:["resource"]}),this.onReady(function(){setTimeout(c.resourceComboReport.bind(c),5e3)}),c},setResource:function(c){var h=this._conf,f=this[o];if(t.isArray(c)&&c.length){this[n]||(this[n]={});for(var p=this[n],u=0,g=c.length;u<g;u+=1){var m=c[u];if(t.checkAPI(m.name,!1)){var d=a(m,h,f);if(d){var S=d.res_type+"-"+d.domain;S in p||(p[S]=[]),p[S].push(d)}}}return this}},fixResourceStatus:function(c){var h=s.performance;if(!h||typeof h.getEntriesByName!="function")return null;var f=this[o];if(!c.src||!t.checkAPI(c.src,!1))return this;var p=c.timeStamp||h.now(),u=h.getEntriesByName(c.src,"resource");return t.each(u,function(g){f.has(g)||p-g.responseEnd<100&&f.set(g,{success:0})}),this},resourceComboReport:function(){var c=this[n]||{},h=this._conf.resourceSlow||2e3,f=this[o];this[n]={};var p=Object.keys(c);if(p.length!==0){var u=[];t.each(p,function(S){var b=c[S],w={domain:"",res_type:"",src_type:"",size:0,duration:0,count:0,err_count:0,err_duration:0,slow_count:0,slow_duration:0,timings:[]};t.each(b,function(_){var R=_.timing||{},x=f.get(_.timing),z=x?x.success:1,j=_.duration>h?1:0;w.domain=_.domain,w.res_type=_.res_type,w.src_type=_.src_type,w.count+=1,w.duration+=_.duration,w.size+=_.size,z||(w.err_count+=1,w.err_duration+=_.duration),j&&(w.slow_count+=1,w.slow_duration+=_.duration);try{var O=JSON.parse(JSON.stringify(R));O.success=z,O.resourceSlow=h,O.isSlow=j,w.timings.push(O)}catch(ie){}}),w.count&&(w.size=Math.round(w.size/w.count),w.duration=Math.round(w.duration/w.count)),w.slow_count&&(w.slow_duration=Math.round(w.slow_duration/w.slow_count)),w.err_count&&(w.err_duration=Math.round(w.err_duration/w.err_count)),w.timings.length>20&&(w.timings.sort(function(_,R){return R.duration-_.duration}),w.timings.length=20),w.timings=encodeURIComponent(JSON.stringify(w.timings)),u.push(w)});var g={_combo:1,resource:JSON.stringify(u)},m=s.navigator.connection;g.ct=m?m.effectiveType||m.type:"";var d=m&&(m.downlink||m.downlinkMax||m.bandwidth)||null;(d=d>999?999:d)&&(g.bandwidth=d),this._lg("resource",g,this.getConfig("sample"))}}})},Hi}var ne=ye,gt=Ra,Da=Ea,xa=Ta,Ye=ne.win,Fi=Ye.document,Ua=/^(error|api|speed|sum|avg|percent|custom|msg|setPage|setConfig|behavior|performance)$/,Pe=function(t){var r=this;return gt.call(r,t),r._initialPage=t.page&&ne.safetyCall(t.page,[],t.page+"")||null,r._isRobot=ne.isRobot(),r._health={errcount:0,apisucc:0,apifail:0},r.beforeSend=function(e,i){e==="error"?r._health.errcount++:e==="api"&&r._health[i.success?"apisucc":"apifail"]++},t.enableInstanceAutoSend!==!1&&(r.initHandler(),r.initHook(),r.initFmpObserver(1e4),r._conf&&r._conf.behavior&&typeof r.initBehavior=="function"&&r.initBehavior(),r._conf&&r._conf.enableResource&&typeof r.initResource=="function"&&r.initResource()),Object.defineProperty&&Ye.addEventListener&&Object.defineProperty(r,"pipe",{set:r.sendPipe}),r};Pe.prototype=ne.createObject(gt.prototype),ne.ext(gt._root.dftCon,{uid:null,setUsername:null,ignoreUrlPath:null,ignoreApiPath:null,urlHelper:[{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},/\/$/],resourceHelper:[],apiHelper:{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},ignoreUrlCase:!0,imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",cdnHostList:[],resourceTypes:["css","script","img","font"],resourceSlow:2e3,disableHook:!1,autoSendPv:!0,autoSendPerf:!0,enableSPA:!1,enableLinkTrace:!1,linkType:"arms",enableApiCors:!1,sendResource:!0,behavior:!0,enableConsole:!1,parseHash:function(t){return(t?ne.cutUrlSearch(t.replace(/^#\/?/,"")):"")||"[index]"},parseResponse:function(t){if(!t||typeof t!="object")return{};var r=t.code,e=t.msg||t.message||t.subMsg||t.errorMsg||t.ret||t.errorResponse||"";return typeof e=="object"&&(r=r||e.code,e=e.msg||e.message||e.info||e.ret||JSON.stringify(e)),{msg:e,code:r,success:!0}}}),ne.ext(Pe.prototype,{constructor:Pe,_super:gt,onReady:function(t){var r=this;if(r.hasReady)return t();Fi.readyState==="complete"?(r.hasReady=!0,t()):ne.on(Ye,"load",function(){r.hasReady=!0,t()},!0)},getPage:function(t){var r=this._conf,e=r.page,i=location,s=i.host+i.pathname;return e&&!t?ne.safetyCall(e,[],e+""):this._initialPage||ne.filterByRule(r.ignoreUrlCase?s.toLowerCase():s,i.href,r.ignoreUrlPath?r.ignoreUrlPath:r.urlHelper)},setPage:function(t,r){var e=this,i=e.prevPage;if(r!==!1){if(!t||t===i)return e;e.prevPage=t,clearTimeout(e.sendPVTimmer),e.handleUnload(1),e.resetPageview(),e.sendPVTimmer=setTimeout(function(){e.sendPV()},10)}else e.prevPage=t;return e._conf.page=t,e},setConfig:function(t,r){if(t&&typeof t=="object"){ne.verifyConfig(t),t=this.setImgUrl(t);var e=this._conf;if(this._conf=ne.ext({},e,t),!r){var i="disableHook";i in t&&e[i]!==t[i]&&(t[i]?this.removeHook():this.addHook()),(i="enableSPA")in t&&e[i]!==t[i]&&this.bindHashChange(t[i])}}},sendRequest:function(t){Da(t,this.getConfig("imgUrl"))},postData:function(t,r){var e={};e[r]=t[r],delete t[r];var i="";typeof t=="object"&&(i=ne.serialize(t)),xa(e,this.getConfig("imgUrl")+i+"&post_res=")},sendPipe:function(t){var r=this;if(!t||!t.length)return r;try{if(ne.T(t[0])==="Array")return ne.each(t,function(i){return r.sendPipe(i)});if(ne.T(t)!=="Array")return r;var e=t.shift();if(!Ua.test(e))return r;r[e].apply(r,t)}catch(i){return ne.warn("[retcode] error in sendPipe",i),r}},sendHealth:function(){var t=ne.ext({},this._health);t.healthy=t.errcount>0?0:1,t.begin=Date.now();var r=t.begin-this.sBegin;t.stay=r,this._lg("health",t,1),this._health={errcount:0,apisucc:0,apifail:0}},createInstance:function(t){t=ne.ext({pid:this._conf.pid},t);var r=this.__proto__.constructor(t);return t.page&&r.sendPV(),r}}),Pa()(Pe,Ye),Ma()(Pe,Ye,Fi),Na()(Pe,Ye,Fi),La()(Pe,Ye),Oa()(Pe,Ye),Va()(Pe,Ye),Pe._super=gt,Pe._root=gt._root,gt.Browser=Pe,kr.exports=Pe;var Ba=kr.exports;function Qr(t,r){var e=De[ft]=new Et(t);e.sendPipe(r);var i=e._conf;return i.autoSendPv!==!1&&e.sendPV(),i&&i.useFmp||e.sendPerformance(),i&&i.sendResource&&e.sendResources(),De[ji]=!0,e}function Ha(){if(De[ji])return De[ft];var t={},r=[];return ft in De&&(t=De[ft].config||{},r=De[ft].pipe||[]),Qr(t,r)}var De=window,Et=De.BrowserLogger=Ba,ft=ye.key,ji="__hasInitBlSdk";Et.singleton=function(t,r){return De[ji]?De[ft]:Qr(t,r)},Et.createExtraInstance=function(t){t&&typeof t=="object"&&t.enableInstanceAutoSend!==!0&&(t.enableInstanceAutoSend=!1);var r=new Et(t),e=r._conf;return e.enableInstanceAutoSend&&(e.autoSendPv!==!1&&r.sendPV(),e&&e.useFmp||r.sendPerformance(),e&&e.sendResource&&r.sendResources()),r};var Fa=typeof window=="object"&&!!window.navigator;Fa&&De[ft]&&(Et.bl=Ha()),Rt.exports=Et;var ja=Rt.exports;const $a=Xe(ja);function Wa(t){const r=[],e=Object.getOwnPropertyDescriptors(Object.getPrototypeOf(t));for(const s of Object.keys(e))e[s].get&&r.push(s);const i={MediaboxWrapperObjectGetter(s,a){if(typeof a=="string"&&r.indexOf(a)>-1)return $e(s[a]);const n={MediaboxWrapperObjectMethod(...o){return $e(s[a](...o))}};return typeof s[a]=="function"?n.MediaboxWrapperObjectMethod:$e(s[a])},MediaboxWrapperObjectSetter(s,a,n){return s[a]=$e(n),!0}};return new Proxy(t,{get:i.MediaboxWrapperObjectGetter,set:i.MediaboxWrapperObjectSetter})}function Ka(t){const r={MediaboxWrapperFunctionApply(e,i,s){const a=e.apply(i,s);return $e(a)},MediaboxWrapperFunctionGet(e,i){const s=Object.getOwnPropertyDescriptor(e,i);if(s&&!s.writable&&!s.configurable)return e[i];const a={MediaboxWrapperFunctionGet(...n){const o=e[i](...n);return $e(o)}};return typeof e[i]=="function"?a.MediaboxWrapperFunctionGet:$e(e[i])},MediaboxWrapperClassConstructor(e,i){const s=new e(...i);return $e(s)}};return new Proxy(t,{apply:r.MediaboxWrapperFunctionApply,get:r.MediaboxWrapperFunctionGet,construct:r.MediaboxWrapperClassConstructor})}function qa(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date)&&!(t instanceof RegExp)&&!(t instanceof Function)}function $e(t){return typeof t=="function"?Ka(t):t instanceof Promise?t.then($e).catch(r=>(r.stack.indexOf("MediaboxWrapper")>-1&&setTimeout(()=>{throw r},0),Promise.reject(r))):qa(t)?Wa(t):t}const Ja="https://arms-retcode-sg.aliyuncs.com/r.png?",Ga="https://arms-retcode.aliyuncs.com/r.png?",za="https://retcode-us-west-1.arms.aliyuncs.com/r.png?",Xa={cn:Ga,sg:Ja,usw:za};class $i{constructor(r){je(this,"armsLogger"),je(this,"isReady",!1),je(this,"isDestroyed",!1),je(this,"options"),je(this,"queue",[]),je(this,"helper",{MediaboxWrapperQueue(a){return new Error(a)},MediaboxWrapperInitiative(a){return new Error(a)}}),this.options=r;const{region:e="cn",env:i="prod"}=r,s=a=>{var n;if(this.isDestroyed)return!1;if(a.c1=(n=this.options.cid)!=null?n:window.location.host,a.c2=$i.version,this.options.customData&&(a.c3=new URLSearchParams(this.options.customData).toString()),a.t==="error"){if(a.file.indexOf("g.alicdn.com/apsara-media-")>-1||a.file.indexOf("g.alicdn.com/thor-server")>-1||a.stack.indexOf("MediaboxWrapper")>-1){let o=a;return this.options.beforeSend&&(o=this.options.beforeSend(a)),this.isReady?o:(o&&this.queue.push(o),!1)}return!1}return a};this.armsLogger=$a.singleton({pid:"e1iftji1w7@7ec1cef2cc88733",tag:r.businessName,release:`${r.businessName}_${r.version}`,imgUrl:Xa[e],behavior:!0,sample:1,disableHook:!0,environment:i,beforeReport:s})}static get version(){return"0.6.0"}wrap(r){return this.options.disabled?r:$e(r)}updateOptions(r){this.options=q(q({},this.options),r)}setReady(){this.isReady=!0,this.queue.length&&this.queue.forEach(r=>{this.armsLogger.error(this.helper.MediaboxWrapperQueue(r.msg),{filename:r.file,lineno:r.line,colno:r.col})})}report(r,e){this.armsLogger.error(this.helper.MediaboxWrapperInitiative(r),e)}destroy(){this.isDestroyed=!0}}var J=(t=>(t.PullStreamStats="remoteStat",t.RtsSubscribeExceeds="rtsSubscribeExceeds",t.UserJoined="userJoined",t.UserLeft="userLeft",t.Bye="bye",t.MuteAudio="muteAudio",t.UnmuteAudio="unmuteAudio",t.MuteVideo="muteVideo",t.UnmuteVideo="unmuteVideo",t.MuteScreen="muteScreen",t.UnmuteScreen="unmuteScreen",t.Error="error",t))(J||{}),we=(t=>(t.Local="local-device-status-change",t.Remote="remote-device-status-change",t))(we||{}),k=(t=>(t.Audio="sophon_audio",t.VideoLarge="sophon_video_camera_large",t.VideoSmall="sophon_video_camera_small",t.Screen="sophon_video_screen_share",t))(k||{}),Wi=(t=>(t.Audio="rts audio",t.VideoLarge="rts video",t))(Wi||{}),At=(t=>(t[t.Camera=0]="Camera",t[t.Screen=1]="Screen",t[t.Image=2]="Image",t))(At||{}),si=(t=>(t[t.Microphone=0]="Microphone",t[t.Screen=1]="Screen",t[t.Mixed=2]="Mixed",t))(si||{}),ai=(t=>(t.prod="rs.rtn.aliyuncs.com",t.pre="prs.rtn.aliyuncs.com",t))(ai||{});const Dt="6.11.5",Zr="web";class it{static getVersionNumber(){let r=Dt.split("."),e="";return r.forEach(i=>{i.length===1?e+="0"+i:e+=i}),parseInt(e)}static queryingParam(r){let e=[];if(r)for(let i in r)e.push(i+"="+r[i]);return e.join("&")}static getQueryParams(r){const i=window.location.search.substring(1).split("&");for(let s=0;s<i.length;s++){const a=i[s].split("=");if(decodeURIComponent(a[0])===r)return decodeURIComponent(a[1])}}static createCallid(){return D.Guid.create(8)+"-"+D.Guid.create(4)+"-4"+D.Guid.create(3)+"-"+D.Guid.create(4)}static checkSubOptionsValid(r){if(r){const{audio:e,video:i,screen:s}=r;if(e===!1&&i===!1&&s===!1)return!1}return!0}static isNetworkAvailable(){return v(this,null,function*(){const r=ai.prod,{onLine:e}=navigator;if(!e)return!1;try{return yield fetch(`https://${r}/roomserver/v1/ws/version`),!0}catch(i){return!1}})}}var Ki=(t=>(t[t.DEBUG=0]="DEBUG",t[t.INFO=1]="INFO",t[t.API=2]="API",t[t.WARNING=3]="WARNING",t[t.ERROR=4]="ERROR",t[t.NONE=5]="NONE",t))(Ki||{});class Ne{constructor(r,e,i){l(this,"logLevel");l(this,"outputToConsole");l(this,"maxLogLength");l(this,"maxlogCache");l(this,"uri");l(this,"requestTimeout");l(this,"delay");l(this,"rate");l(this,"hugeBatchCount");l(this,"checkInterval");l(this,"flushModecheckInterval");l(this,"recordOverheadLength");l(this,"httpRequest");l(this,"traceId");l(this,"traceIdPostfix");l(this,"flushMode");l(this,"outputToServer");l(this,"batchCount");l(this,"msgCounter");l(this,"lastRequestTime");l(this,"enable");l(this,"retx");l(this,"lastProfilingTime");l(this,"bytesOut");l(this,"dropped");l(this,"networkdropped");l(this,"lastLogTime",0);l(this,"logArray");l(this,"onTimer",()=>{if(!this.enable)return;this.processCachedLogs();let r=Date.now(),e=r-this.lastLogTime>1e4;if(r-this.lastProfilingTime>=5e3&&!e){let s=this.getProfiling();this.logInternal("[logger] profiling result: "+Ne.toString(s))}let i=this.flushMode?this.flushModecheckInterval:this.checkInterval;e&&(i=this.checkInterval),setTimeout(this.onTimer,i)});this.logLevel=3,this.maxLogLength=12e3,this.requestTimeout=5e3,this.delay=2e3,this.rate=3,this.maxlogCache=1e3,this.hugeBatchCount=100,this.outputToConsole=!0,this.outputToServer=!1,this.checkInterval=1e3,this.flushModecheckInterval=200,this.recordOverheadLength=120,this.flushMode=!1,this.batchCount=0,this.retx=[],this.lastProfilingTime=Date.now(),this.bytesOut=0,this.dropped=0,this.networkdropped=0,window&&window.location&&window.location.protocol&&window.location.protocol==="http:"?this.uri="http://"+e+"."+r+"/logstores/"+i+"/track":this.uri="https://"+e+"."+r+"/logstores/"+i+"/track",this.httpRequest=null,this.msgCounter=0,this.traceIdPostfix=D.LocalStorage.uuid+"-"+Date.now(),this.traceId="",this.logArray=[],this.enable=!0,this.lastRequestTime=0,this.onTimer()}static toString(r){let e;if(r instanceof Error)e=r.message;else if(typeof r=="string")e=r;else try{e=JSON.stringify(r)}catch(i){e="undefined"}return e}changeConfig(r){r.enable!==void 0&&(this.enable=r.enable,this.enable||this.clear()),r.logLevel!==void 0&&r.logLevel>=0&&r.logLevel<=5&&(this.logLevel=r.logLevel),r.logToConsole!==void 0&&(this.outputToConsole=r.logToConsole),r.logToServer!==void 0&&(this.outputToServer=r.logToServer),r.maxLogLength!==void 0&&r.maxLogLength>10&&(this.maxLogLength=r.maxLogLength),r.maxlogCache!==void 0&&r.maxlogCache>10&&r.maxlogCache<2e4&&(this.maxlogCache=r.maxlogCache),r.requestTimeout!==void 0&&r.requestTimeout>100&&r.requestTimeout<1e5&&(this.requestTimeout=r.requestTimeout),r.delay!==void 0&&r.delay>0&&r.delay<1e5&&(this.delay=r.delay),r.rate!==void 0&&r.rate>0&&r.rate<1e4&&(this.rate=r.rate)}getProfiling(){let r={enable:this.enable,flush:this.flushMode,cache:this.logArray.length,drop:this.dropped,dropNw:this.networkdropped,kbps:0},e=Date.now();return e-this.lastProfilingTime>500?(r.kbps=Math.round(this.bytesOut*8/(e-this.lastProfilingTime)),this.lastProfilingTime=e,this.bytesOut=0):r.kbps=-1,r}clear(){this.retx=[],this.logArray=[]}setFlushMode(r){this.enable&&(this.flushMode=r,this.flushMode&&this.processCachedLogs())}setTraceID(r){r&&(r.length>64&&(r=r.substring(0,64)),this.traceId=r)}d(...r){if(!this.enable||this.logLevel>0)return;let e=this.getCurrentTime();this.outputToConsole&&console.debug(e,...r);let i=Ne.paramArrayToString(r);this.addLog(0,i,!1,e)}i(...r){if(!this.enable||this.logLevel>1)return;let e=this.getCurrentTime();this.outputToConsole&&console.log(e,...r);let i=Ne.paramArrayToString(r);this.addLog(1,i,!1,e)}w(...r){if(!this.enable||this.logLevel>3)return;let e=this.getCurrentTime();this.outputToConsole&&console.warn(e,...r);let i=Ne.paramArrayToString(r);this.addLog(3,i,!1,e)}e(...r){if(!this.enable||this.logLevel>4)return;let e=this.getCurrentTime();this.outputToConsole&&console.error(e,...r);let i=Ne.paramArrayToString(r);i="<error> "+i,this.addLog(4,i,!1,e)}ev(...r){if(!this.enable||this.logLevel>2)return;let e=this.getCurrentTime();this.outputToConsole&&console.log(e,...r);let i=Ne.paramArrayToString(r);this.addLog(2,i,!1,e)}a(...r){if(!this.enable||this.logLevel>2)return;let e=this.getCurrentTime();if(this.outputToConsole){if(r.length>2){const s=`${r[1]}`;s.startsWith("__g__")&&console.group(`${s.substring(5)}_${r[2]}`)}console.log(e,...r)}let i=Ne.paramArrayToString(r);this.addLog(2,i,!1,e)}ar(...r){if(!this.enable||this.logLevel>2)return;let e=this.getCurrentTime();this.outputToConsole&&(console.log(e,...r),r.length>2&&`${r[1]}`.startsWith("__g__")&&console.groupEnd());let i=Ne.paramArrayToString(r);this.addLog(2,i,!1,e)}ae(...r){if(!this.enable||this.logLevel>4)return;let e=this.getCurrentTime();this.outputToConsole&&(console.error(e,...r),this.logLevel>2&&r.length>2&&console.groupEnd());let i=Ne.paramArrayToString(r);i="<error> "+i,this.addLog(4,i,!1,e)}logInternal(r){if(!this.enable||this.logLevel>3)return;let e=this.getCurrentTime();this.addLog(2,r,!0,e)}addLog(r,e,i,s){e=s+" "+e,e.length>this.maxLogLength&&(e=e.substring(0,this.maxLogLength));let a=Date.now();i||(this.lastLogTime=a);let n={tm:a.toString(),level:r.toString(),msg:e,count:this.msgCounter.toString(),trace:this.traceId+"-"+this.traceIdPostfix};this.logArray.push(n),this.msgCounter++,this.logArray.length>this.maxlogCache&&this.saveMemory(this.maxlogCache-5)}saveMemory(r){let e=0,i=0;for(;this.logArray.length>r&&e<=4;){for(;i<this.logArray.length;)if(parseInt(this.logArray[i].level)===e){if(this.logArray.splice(i,1),this.dropped++,this.logArray.length<=r)break}else i++;i===this.logArray.length&&(i=0,e++)}}processCachedLogs(){if(!this.outputToServer||this.logArray.length===0&&this.retx.length===0||this.isHttpRequesting()||!this.flushMode&&Date.now()-this.lastRequestTime<this.delay)return;if(this.retx&&this.retx.length>0){let o=this.retx[0].tries?parseInt(this.retx[0].tries)+1:1;if(this.flushMode||this.retx.length<this.hugeBatchCount||o<4){let c=o.toString();for(let h=0;h<this.retx.length;h++)this.retx[h].tries=c;this.batchSend(this.retx);return}else this.retx=[],this.dropped+=this.retx.length,this.networkdropped+=this.retx.length}if(this.logArray.length===0)return;let r=this.flushMode?1.5*1024*1024:this.delay*this.rate,e=0,i=0,s=this.recordOverheadLength;for(let o=0;o<this.logArray.length&&(i+=this.logArray[o].msg.length+s,!(i>r));o++)e=o+1;e===0&&(e=1);let a=this.logArray.splice(0,e);this.batchCount++;let n=this.batchCount.toString();for(let o=0;o<a.length;o++)a[o].batch=n,a[o].tries="0";this.retx=a,this.batchSend(a)}createHttpRequest(){this.httpRequest||window.XMLHttpRequest&&(this.httpRequest=new XMLHttpRequest)}isHttpRequesting(){return this.httpRequest!==null}batchSend(r){if(this.isHttpRequesting())return;this.lastRequestTime=Date.now();let e=this.uri,i=JSON.stringify(r);i='{"__logs__":'+i+"}",this.createHttpRequest(),this.isHttpRequesting()&&(this.bytesOut+=i.length,this.httpRequest.open("POST",e,!0),this.httpRequest.timeout=this.requestTimeout,this.httpRequest.setRequestHeader("x-log-apiversion","0.6.0"),this.httpRequest.setRequestHeader("x-log-bodyrawsize",i.length),this.httpRequest.onload=()=>{this.httpRequest.status!==200&&console.log("Error: failed to post log ",this.httpRequest),this.retx=[],this.lastRequestTime=Date.now(),this.httpRequest=null},this.httpRequest.onerror=()=>{console.log("Error: post log failed"),this.lastRequestTime=Date.now(),this.httpRequest=null},this.httpRequest.onabort=()=>{console.log("Error: post log aborted"),this.lastRequestTime=Date.now(),this.httpRequest=null},this.httpRequest.send(i))}getCurrentTime(){let r=new Date;return("00"+r.getHours()).slice(-2)+":"+("00"+r.getMinutes()).slice(-2)+":"+("00"+r.getSeconds()).slice(-2)+"."+("000"+r.getMilliseconds()).slice(-3)}static paramArrayToString(r){let e="";for(let i=0;i<r.length;i++){e!==""&&(e+=",");let s=Ne.toString(r[i]);e+=s}return e}}class E{static getLogger(){return this.logger||(this.logger=new Ne("cn-shanghai.log.aliyuncs.com","alirtc","client_h5")),this.logger}static setLogLevel(r){this.getLogger().changeConfig({logLevel:r})}static config(r){this.getLogger().changeConfig(r)}static setTraceID(r){this.getLogger().setTraceID(r)}static setFlushMode(r){this.getLogger().setFlushMode(r)}static interface(...r){this.getLogger().a("[API]",...r)}static interfaceResult(r,e,i,...s){i?this.getLogger().ar("[ARE]",r,e,...s):this.getLogger().ae("[ARE]",r,e,...s)}static event(...r){this.getLogger().ev("[EVT]",...r)}static debug(...r){this.getLogger().d("[DBG]",...r)}static info(...r){this.getLogger().i("[INF]",...r)}static warn(...r){this.getLogger().w("[WARN]",...r)}static error(...r){this.getLogger().e("[ERR]",...r)}}l(E,"logger");const Ya=t=>v(this,null,function*(){const r=new V.AliRTS.SupportUtil;let e={support:!1,detail:{isWebRTCSupported:r.checkMediaDevices()&&r.checkWebRtcSupport(),isH264DecodeSupported:!1,isH264EncodeSupported:!1,isScreenShareSupported:!1,isSendMediaExtensionMsgSupported:!1,isBrowserSupported:r.checkBrowser({errorCode:0,message:""})}};if(e.support=e.detail.isWebRTCSupported&&e.detail.isBrowserSupported,r.checkWebRtcSupport()&&t!=="sendonly"){const i=yield r.checkH264Decode();e.detail.isH264DecodeSupported=i,e.support=e.support&&i}if(r.checkWebRtcSupport()&&t!=="recvonly"){const i=yield r.checkH264Encode();e.detail.isH264EncodeSupported=i,e.support=e.support&&i}return e.detail.isScreenShareSupported=r.checkWebRtcSupport()&&r.checkScreenCapture()&&!V.AliRTS.SystenUtil.isAndroid&&!V.AliRTS.SystenUtil.isIos,e.detail.isSendMediaExtensionMsgSupported=r.checkWebRtcSupport()&&r.checkEncodedTransformSupport(),e});var ce=(t=>(t[t.AliRtcSdkStreamTypeCapture=0]="AliRtcSdkStreamTypeCapture",t[t.AliRtcSdkStreamTypeScreen=1]="AliRtcSdkStreamTypeScreen",t))(ce||{}),es=(t=>(t[t.PRE_PROCESSOR=0]="PRE_PROCESSOR",t[t.POST_PROCESSOR=1]="POST_PROCESSOR",t))(es||{}),ni=(t=>(t[t.AUDIO=0]="AUDIO",t[t.VIDEO=1]="VIDEO",t[t.BOTH=2]="BOTH",t))(ni||{});class Tt extends Q{constructor(e,i=ce.AliRtcSdkStreamTypeCapture,s=1){super();l(this,"name");l(this,"options");l(this,"type",0);l(this,"streamType");l(this,"trackType");l(this,"zIndex",1);l(this,"_isEnable",!0);l(this,"lastInputAudioTrack");l(this,"lastOutputAudioTrack");l(this,"lastInputVideoTrack");l(this,"lastOutputVideoTrack");this.name=e,this.streamType=i,this.trackType=s,this.options=this.initOptions}get initOptions(){return{}}getOptions(){return this.options}init(){return v(this,null,function*(){})}enable(){this._isEnable||(this._isEnable=!0,this.init(),this.emit("enabled"))}disable(){this._isEnable&&(this._isEnable=!1,this.clear(),this.emit("disabled"))}get isEnable(){return this._isEnable}audioUpdated(e){var i,s;return((i=this.lastInputAudioTrack)==null?void 0:i.id)!==((s=e.currentAudioTrack)==null?void 0:s.id)}videoUpdated(e){var i,s;return((i=this.lastInputVideoTrack)==null?void 0:i.id)!==((s=e.currentVideoTrack)==null?void 0:s.id)}execute(e,i){return v(this,null,function*(){const s=this.shouldUpdate(e,i);this.lastInputAudioTrack=e.currentAudioTrack,this.lastInputVideoTrack=e.currentVideoTrack,s?yield this.process(e,i):(this.lastOutputAudioTrack&&(this.trackType===2||this.trackType===0)&&this.lastOutputAudioTrack&&e.updateAudioTrack(this.lastOutputAudioTrack),this.lastOutputVideoTrack&&(this.trackType===2||this.trackType===1)&&this.lastOutputVideoTrack&&e.updateVideoTrack(this.lastOutputVideoTrack)),this.lastOutputAudioTrack=e.currentAudioTrack,this.lastOutputVideoTrack=e.currentVideoTrack})}clear(e){this.lastInputAudioTrack=void 0,this.lastInputVideoTrack=void 0,this.lastOutputAudioTrack=void 0,this.lastOutputVideoTrack=void 0}}var xt=(t=>(t[t.LiveTranscodingSingle=0]="LiveTranscodingSingle",t[t.LiveTranscodingMix=1]="LiveTranscodingMix",t))(xt||{}),qi=(t=>(t[t.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",t[t.LiveTranscodingAudio=1]="LiveTranscodingAudio",t[t.LiveTranscodingVideo=2]="LiveTranscodingVideo",t))(qi||{}),Pt=(t=>(t[t.LiveTranscodingCamera=0]="LiveTranscodingCamera",t[t.LiveTranscodingShareScreen=1]="LiveTranscodingShareScreen",t))(Pt||{});const Ut={0:"camera",1:"shareScreen"};var Ji=(t=>(t[t.LiveTranscoding_Profile_1IN_1080P=0]="LiveTranscoding_Profile_1IN_1080P",t[t.LiveTranscoding_Profile_1IN_720P=1]="LiveTranscoding_Profile_1IN_720P",t[t.LiveTranscoding_Profile_1IN_360P=2]="LiveTranscoding_Profile_1IN_360P",t[t.LiveTranscoding_Profile_2IN_1080P=3]="LiveTranscoding_Profile_2IN_1080P",t[t.LiveTranscoding_Profile_2IN_720P=4]="LiveTranscoding_Profile_2IN_720P",t[t.LiveTranscoding_Profile_2IN_360P=5]="LiveTranscoding_Profile_2IN_360P",t[t.LiveTranscoding_Profile_4IN_1080P=6]="LiveTranscoding_Profile_4IN_1080P",t[t.LiveTranscoding_Profile_4IN_720P=7]="LiveTranscoding_Profile_4IN_720P",t[t.LiveTranscoding_Profile_4IN_360P=8]="LiveTranscoding_Profile_4IN_360P",t[t.LiveTranscoding_Profile_9IN_1080P=9]="LiveTranscoding_Profile_9IN_1080P",t[t.LiveTranscoding_Profile_9IN_720P=10]="LiveTranscoding_Profile_9IN_720P",t[t.LiveTranscoding_Profile_9IN_360P=11]="LiveTranscoding_Profile_9IN_360P",t[t.LiveTranscoding_Profile_12IN_1080P=12]="LiveTranscoding_Profile_12IN_1080P",t[t.LiveTranscoding_Profile_12IN_720P=13]="LiveTranscoding_Profile_12IN_720P",t[t.LiveTranscoding_Profile_12IN_360P=14]="LiveTranscoding_Profile_12IN_360P",t[t.LiveTranscoding_Profile_16IN_1080P=15]="LiveTranscoding_Profile_16IN_1080P",t[t.LiveTranscoding_Profile_16IN_720P=16]="LiveTranscoding_Profile_16IN_720P",t[t.LiveTranscoding_Profile_16IN_360P=17]="LiveTranscoding_Profile_16IN_360P",t[t.LiveTranscoding_Profile_Mixed=9999]="LiveTranscoding_Profile_Mixed",t))(Ji||{});const Qa={0:"1IN_1080P",1:"1IN_720P",2:"1IN_360P",3:"2IN_1080P",4:"2IN_720P",5:"2IN_360P",6:"4IN_1080P",7:"4IN_720P",8:"4IN_360P",9:"9IN_1080P",10:"9IN_720P",11:"9IN_360P",12:"12IN_1080P",13:"12IN_720P",14:"12IN_360P",15:"16IN_1080P",16:"16IN_720P",17:"16IN_360P",9999:"Mixed_Audio"};var oi=(t=>(t[t.LiveTranscoding_HZ_48000=48e3]="LiveTranscoding_HZ_48000",t[t.LiveTranscoding_HZ_44100=44100]="LiveTranscoding_HZ_44100",t[t.LiveTranscoding_HZ_32000=32e3]="LiveTranscoding_HZ_32000",t[t.LiveTranscoding_HZ_16000=16e3]="LiveTranscoding_HZ_16000",t[t.LiveTranscoding_HZ_8000=8e3]="LiveTranscoding_HZ_8000",t))(oi||{}),Bt=(t=>(t[t.LiveTranscodingNoBody=0]="LiveTranscodingNoBody",t[t.LiveTranscodingBody=1]="LiveTranscodingBody",t))(Bt||{}),Ht=(t=>(t[t.NOTO_SERIF_CJKSC_REGULAR=0]="NOTO_SERIF_CJKSC_REGULAR",t[t.ALIBABA_PUHUITI_REGULAR=1]="ALIBABA_PUHUITI_REGULAR",t[t.ALIBABA_PUHUITI_BOLD=2]="ALIBABA_PUHUITI_BOLD",t[t.ALIBABA_PUHUITI_Heavy=3]="ALIBABA_PUHUITI_Heavy",t[t.ALIBABA_PUHUITI_LIGHT=4]="ALIBABA_PUHUITI_LIGHT",t[t.ALIBABA_PUHUITI_MEDIUM=5]="ALIBABA_PUHUITI_MEDIUM",t))(Ht||{}),Gi=(t=>(t[t.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",t[t.LiveTranscodingCrop=1]="LiveTranscodingCrop",t[t.LiveTranscodingFill=2]="LiveTranscodingFill",t))(Gi||{}),ci=(t=>(t[t.LiveTranscodingNormal=0]="LiveTranscodingNormal",t[t.LiveTranscodingVirtualBackground=1]="LiveTranscodingVirtualBackground",t))(ci||{}),zi=(t=>(t[t.LiveTranscodingState_IDLE=0]="LiveTranscodingState_IDLE",t[t.LiveTranscodingState_CONNNECT=1]="LiveTranscodingState_CONNNECT",t[t.LiveTranscodingState_RUNNING=2]="LiveTranscodingState_RUNNING",t[t.LiveTranscodingState_RECOVERING=3]="LiveTranscodingState_RECOVERING",t[t.LiveTranscodingState_FAILURE=4]="LiveTranscodingState_FAILURE",t[t.LiveTranscodingState_END=5]="LiveTranscodingState_END",t))(zi||{}),We=(t=>(t[t.LiveTranscodingErrorPublishOk=0]="LiveTranscodingErrorPublishOk",t[t.LiveTranscodingErrorStreamNotFound=17825793]="LiveTranscodingErrorStreamNotFound",t[t.LiveTranscodingErrorStreamAlreadyExist=17825794]="LiveTranscodingErrorStreamAlreadyExist",t[t.LiveTranscodingErrorInvalidParam=17825795]="LiveTranscodingErrorInvalidParam",t[t.LiveTranscodingErrorInternalError=17825796]="LiveTranscodingErrorInternalError",t[t.LiveTranscodingErrorRtmpServerError=17825797]="LiveTranscodingErrorRtmpServerError",t[t.LiveTranscodingErrorRtmpStreamUrlError=17825798]="LiveTranscodingErrorRtmpStreamUrlError",t[t.LiveTranscodingErrorPublishTimeout=17825799]="LiveTranscodingErrorPublishTimeout",t[t.LiveTranscodingErrorNotAuthorized=17825800]="LiveTranscodingErrorNotAuthorized",t))(We||{}),Xi=(t=>(t[t.TrascodingPublishTaskStatusStart=0]="TrascodingPublishTaskStatusStart",t[t.TrascodingPublishTaskStatusUpdate=1]="TrascodingPublishTaskStatusUpdate",t[t.TrascodingPublishTaskStatusStop=2]="TrascodingPublishTaskStatusStop",t))(Xi||{}),Ie=(t=>(t[t.MPU_TASK_TRANSACTION_START=0]="MPU_TASK_TRANSACTION_START",t[t.MPU_TASK_TRANSACTION_UPDATE=1]="MPU_TASK_TRANSACTION_UPDATE",t[t.MPU_TASK_TRANSACTION_STOP=2]="MPU_TASK_TRANSACTION_STOP",t[t.MPU_TASK_TRANSACTION_LIST=3]="MPU_TASK_TRANSACTION_LIST",t[t.MPU_TASK_TRANSACTION_POLLING=4]="MPU_TASK_TRANSACTION_POLLING",t[t.MPU_TASK_TRANSACTION_ACKNOWLEDGE=5]="MPU_TASK_TRANSACTION_ACKNOWLEDGE",t[t.MPU_TASK_TRANSACTION_END=6]="MPU_TASK_TRANSACTION_END",t))(Ie||{});const Za={0:"/libra/v1/sdk/start-task",1:"/libra/v1/sdk/update-task",2:"/libra/v1/sdk/stop-task",3:"/libra/v1/sdk/list-task",4:"/libra/v1/sdk/polling",5:"/libra/v1/sdk/acknowledge",6:"/"};class Yi{constructor(r,e,i,s,a,n,o,c){l(this,"videoWidth");l(this,"videoHeight");l(this,"videoFramerate",20);l(this,"videoBitrate",2e3);l(this,"videoGop",30);l(this,"audioSamplerate",oi.LiveTranscoding_HZ_44100);l(this,"audioBitrate",500);l(this,"audioChannels",1);this.videoWidth=r,this.videoHeight=e,i&&(this.videoFramerate=i),s&&(this.videoBitrate=s),a&&(this.videoGop=a),n&&(this.audioSamplerate=n),o&&(this.audioBitrate=o),c&&(this.audioChannels=c)}}const Qi=t=>((t&16711680)>>16)+(t&65280)+((t&255)<<16),Le=(t=0,r)=>{if(r==0)return 0;let e=t/r;return e<0&&(e=0),e>1&&(e=1),e};class ui{constructor(r,e,i){l(this,"mixMode",xt.LiveTranscodingSingle);l(this,"singleParam");l(this,"mixParam");r&&(this.mixMode=r),e&&(this.singleParam=e),i&&(this.mixParam=i)}toJson(r,e,i,s,a){const n={appid:e.appId,channelid:e.channelId};if(r===Ie.MPU_TASK_TRANSACTION_POLLING||r===Ie.MPU_TASK_TRANSACTION_LIST||r===Ie.MPU_TASK_TRANSACTION_ACKNOWLEDGE)return r===Ie.MPU_TASK_TRANSACTION_ACKNOWLEDGE&&(n.messageid=a),n;if(n.taskid=i,r!==Ie.MPU_TASK_TRANSACTION_STOP){if(n.mixmode=this.mixMode,s&&(n.streamurl=s),this.mixMode===xt.LiveTranscodingSingle){const o=this.singleParam;if(o){n.streamtype=o.streamType,o.sourceType===Pt.LiveTranscodingShareScreen?n.sourcetype=Ut[o.sourceType]:n.sourcetype=Ut[Pt.LiveTranscodingCamera];const c=[];o.userId&&c.push(o.userId),n.subspecusers=c}}else if(r===Ie.MPU_TASK_TRANSACTION_START||r===Ie.MPU_TASK_TRANSACTION_UPDATE){const o=this.mixParam;if(o){o.taskProfile&&(n.taskprofile=Qa[o.taskProfile]);const c=o.encodeParam||new Yi(1280,720);let h=c.videoWidth,f=c.videoHeight;const p={};Object.keys(c).forEach(g=>{const m=c[g];m>0&&(p[g.toLowerCase()]=m)}),p.lowbitratehighquality=0,n.encodeparam=p,n.backgrounds=o.backgrounds.map(g=>g.toJson(h,f)),n.watermarks=o.watermarks.map(g=>g.toJson(h,f)),n.clockwidgets=o.clockWidgets.map(g=>g.toJson(h,f));const u=o.users.map(g=>g.userId);n.subspecusers=[...new Set(u)],n.layouts=[{audiomixcount:o.users.length,panes:o.users.map((g,m)=>g.toJson(m,h,f,o.mediaProcessMode))}],n.layoutids=["0"],n.cropmode=o.cropMode,n.backgroundcolor=Qi(o.backgroundColor),n.taskmode=o.mediaProcessMode}}}return n}}var rt=(t=>(t.pre="pre",t.prod="prod",t))(rt||{}),Qe=(t=>(t.AliRtcSdkCommunication="communication",t.AliRtcSdkInteractiveLive="interactive_live",t.AliRtcSdkInteractiveWithLowLatencyLive="cdn_live",t))(Qe||{}),st=(t=>(t.AliRtcSdkInteractive="interactive",t.AliRtcSdkLive="live",t))(st||{}),Ke=(t=>(t[t.AliEngineLocalDeviceTypeUnknown=0]="AliEngineLocalDeviceTypeUnknown",t[t.AliEngineLocalDeviceTypeMic=1]="AliEngineLocalDeviceTypeMic",t[t.AliEngineLocalDeviceTypeSpeaker=2]="AliEngineLocalDeviceTypeSpeaker",t[t.AliEngineLocalDeviceTypeAudioDevice=3]="AliEngineLocalDeviceTypeAudioDevice",t[t.AliEngineLocalDeviceTypeCamera=4]="AliEngineLocalDeviceTypeCamera",t[t.AliEngineLocalDeviceTypeDisplay=5]="AliEngineLocalDeviceTypeDisplay",t[t.AliEngineLocalDeviceTypeVideoDevice=6]="AliEngineLocalDeviceTypeVideoDevice",t))(Ke||{}),re=(t=>(t[t.AliEngineLocalDeviceExceptionTypeUnknown=0]="AliEngineLocalDeviceExceptionTypeUnknown",t[t.AliEngineLocalDeviceExceptionTypeMicOpenFail=1]="AliEngineLocalDeviceExceptionTypeMicOpenFail",t[t.AliEngineLocalDeviceExceptionTypeMicInterrupt=2]="AliEngineLocalDeviceExceptionTypeMicInterrupt",t[t.AliEngineLocalDeviceExceptionTypeMicAuthFail=3]="AliEngineLocalDeviceExceptionTypeMicAuthFail",t[t.AliEngineLocalDeviceExceptionTypeMicNotAvailable=4]="AliEngineLocalDeviceExceptionTypeMicNotAvailable",t[t.AliEngineLocalDeviceExceptionTypeSpeakerOpenFail=5]="AliEngineLocalDeviceExceptionTypeSpeakerOpenFail",t[t.AliEngineLocalDeviceExceptionTypeSpeakerInterrupt=6]="AliEngineLocalDeviceExceptionTypeSpeakerInterrupt",t[t.AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable=7]="AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable",t[t.AliEngineLocalDeviceExceptionTypeAudioDeviceException=8]="AliEngineLocalDeviceExceptionTypeAudioDeviceException",t[t.AliEngineLocalDeviceExceptionTypeCameraOpenFail=9]="AliEngineLocalDeviceExceptionTypeCameraOpenFail",t[t.AliEngineLocalDeviceExceptionTypeCameraInterrupt=10]="AliEngineLocalDeviceExceptionTypeCameraInterrupt",t[t.AliEngineLocalDeviceExceptionTypeCameraAuthFail=11]="AliEngineLocalDeviceExceptionTypeCameraAuthFail",t[t.AliEngineLocalDeviceExceptionTypeDisplayException=12]="AliEngineLocalDeviceExceptionTypeDisplayException",t[t.AliEngineLocalDeviceExceptionTypeVideoDeviceException=13]="AliEngineLocalDeviceExceptionTypeVideoDeviceException",t))(re||{}),G=(t=>(t[t.AliRtcConnectionStatusInit=0]="AliRtcConnectionStatusInit",t[t.AliRtcConnectionStatusDisconnected=1]="AliRtcConnectionStatusDisconnected",t[t.AliRtcConnectionStatusConnecting=2]="AliRtcConnectionStatusConnecting",t[t.AliRtcConnectionStatusConnected=3]="AliRtcConnectionStatusConnected",t[t.AliRtcConnectionStatusReconnecting=4]="AliRtcConnectionStatusReconnecting",t[t.AliRtcConnectionStatusFailed=5]="AliRtcConnectionStatusFailed",t))(G||{}),mt=(t=>(t[t.AliRtcConnectionChangedDummyReason=0]="AliRtcConnectionChangedDummyReason",t[t.AliRtcConnectionMediaPathChanged=1]="AliRtcConnectionMediaPathChanged",t[t.AliRtcConnectionSignalingHeartbeatTimeout=2]="AliRtcConnectionSignalingHeartbeatTimeout",t[t.AliRtcConnectionSignalingHeartbeatAlive=3]="AliRtcConnectionSignalingHeartbeatAlive",t[t.AliRtcConnectionSignalingHttpDnsResolved=4]="AliRtcConnectionSignalingHttpDnsResolved",t[t.AliRtcConnectionSignalingHttpDnsFailure=5]="AliRtcConnectionSignalingHttpDnsFailure",t[t.AliRtcConnectionSignalingGslbFailure=6]="AliRtcConnectionSignalingGslbFailure",t[t.AliRtcConnectionSignalingGslbSuccess=7]="AliRtcConnectionSignalingGslbSuccess",t[t.AliRtcConnectionSignalingJoinRoomFailure=8]="AliRtcConnectionSignalingJoinRoomFailure",t[t.AliRtcConnectionSignalingJoinRoomSuccess=9]="AliRtcConnectionSignalingJoinRoomSuccess",t[t.AliRtcConnectionSignalingLeaveRoom=10]="AliRtcConnectionSignalingLeaveRoom",t[t.AliRtcConnectionSignalingConnecting=11]="AliRtcConnectionSignalingConnecting",t[t.AliRtcConnectionChangedNetworkInterrupted=12]="AliRtcConnectionChangedNetworkInterrupted",t))(mt||{}),Zi=(t=>(t[t.AliRtcUserOfflineQuit=0]="AliRtcUserOfflineQuit",t[t.AliRtcUserOfflineDropped=1]="AliRtcUserOfflineDropped",t[t.AliRtcUserOfflineBecomeAudience=2]="AliRtcUserOfflineBecomeAudience",t))(Zi||{}),kt=(t=>(t[t.AliRtcAudioTrackNo=0]="AliRtcAudioTrackNo",t[t.AliRtcAudioTrackMic=1]="AliRtcAudioTrackMic",t[t.AliRtcAudioTrackDual=2]="AliRtcAudioTrackDual",t))(kt||{}),W=(t=>(t[t.AliRtcVideoTrackNo=0]="AliRtcVideoTrackNo",t[t.AliRtcVideoTrackCamera=1]="AliRtcVideoTrackCamera",t[t.AliRtcVideoTrackScreen=2]="AliRtcVideoTrackScreen",t[t.AliRtcVideoTrackBoth=3]="AliRtcVideoTrackBoth",t))(W||{}),B=(t=>(t[t.AliRtcStatePublishIdle=0]="AliRtcStatePublishIdle",t[t.AliRtcStateNoPublish=1]="AliRtcStateNoPublish",t[t.AliRtcStatePublishing=2]="AliRtcStatePublishing",t[t.AliRtcStatePublished=3]="AliRtcStatePublished",t))(B||{}),te=(t=>(t[t.AliRtcStateSubscribeIdle=0]="AliRtcStateSubscribeIdle",t[t.AliRtcStateNoSubscribe=1]="AliRtcStateNoSubscribe",t[t.AliRtcStateSubscribing=2]="AliRtcStateSubscribing",t[t.AliRtcStateSubscribed=3]="AliRtcStateSubscribed",t))(te||{}),he=(t=>(t[t.AliRtcVideoStreamTypeNone=0]="AliRtcVideoStreamTypeNone",t[t.AliRtcVideoStreamTypeHigh=1]="AliRtcVideoStreamTypeHigh",t[t.AliRtcVideoStreamTypeLow=2]="AliRtcVideoStreamTypeLow",t))(he||{}),Ft=(t=>(t[t.CAMERA_INVALID=-1]="CAMERA_INVALID",t[t.CAMERA_REAR=0]="CAMERA_REAR",t[t.CAMERA_FRONT=1]="CAMERA_FRONT",t))(Ft||{});const ts=10,is=5e3,Ti=class Ti extends Q{constructor(e){super();l(this,"ws");l(this,"socketStatus",0);l(this,"wsUrl","");l(this,"lastConnectStartTime",0);l(this,"maxConnectRetryCount",ts);l(this,"connectRetryCount",0);l(this,"gotErr",!1);l(this,"closedByInvoke",!0);l(this,"isReconnecting",!1);l(this,"networkAvailableChecked",!0);this.maxConnectRetryCount=e!=null?e:ts,this.onOpen=this.onOpen.bind(this),this.onMessage=this.onMessage.bind(this),this.onError=this.onError.bind(this),this.onClose=this.onClose.bind(this)}get connectUrl(){return this.wsUrl}get connectStatus(){return this.socketStatus}start(e){this.wsUrl=e,this.initWebSocket()}send(e){return this.ws&&this.socketStatus===2?(this.ws.send(JSON.stringify(e)),!0):!1}close(){this.closedByInvoke=!0,this.uninitWebscoket()}reconnect(){this.emit("onReconnectStart"),this.isReconnecting=!0,this.initWebSocket()}onOpen(e){this.socketStatus=2,this.connectRetryCount=0,this.networkAvailableChecked=!1,this.closedByInvoke=!1,this.gotErr=!1,this.isReconnecting=!1,this.emit("onOpen",e)}onMessage(e){this.emit("onMessage",e)}onError(e){this.isReconnecting&&this.emit("onReconnectFail",e),this.emit("onError",e),this.isReconnecting=!1,this.gotErr=!0}onClose(e){return v(this,null,function*(){const i=this.socketStatus;if(E.info(Ti.logName,`onClose, status: ${i}, retryCount: ${this.connectRetryCount}`),i!==0||this.connectRetryCount)if(yield it.isNetworkAvailable()){if(!this.networkAvailableChecked&&!this.closedByInvoke&&!this.gotErr){this.reconnect();return}this.networkAvailableChecked=!0,this.emit("onAuthInvalid")}else{if(this.connectRetryCount||this.emit("onNetworkError"),this.closedByInvoke)return;this.connectRetryCount+=1,this.connectRetryCount>this.maxConnectRetryCount?this.emit("onConnectFail"):Date.now()-this.lastConnectStartTime>=is?this.reconnect():window.setTimeout(()=>{this.reconnect()},is)}this.socketStatus=0,this.emit("onClose",e)})}initWebSocket(){this.uninitWebscoket(),this.socketStatus=1,this.lastConnectStartTime=Date.now(),this.ws=new WebSocket(this.wsUrl),this.ws.addEventListener("open",this.onOpen),this.ws.addEventListener("message",this.onMessage),this.ws.addEventListener("error",this.onError),this.ws.addEventListener("close",this.onClose)}uninitWebscoket(){this.ws&&(this.ws.removeEventListener("open",this.onOpen),this.ws.removeEventListener("message",this.onMessage),this.ws.removeEventListener("error",this.onError),this.ws.removeEventListener("close",this.onClose),this.ws.close(),this.ws=void 0,this.socketStatus=0)}};l(Ti,"logName","Socket");let er=Ti;var ue=(t=>(t.KEEPALIVE="keepalive",t.JOINCHANNEL="joinchannel",t.NOTIFYJOIN="notifyjoin",t.NOTIFYSTATUS="notifystatus",t.STATUSREPORT="statusreport",t.LEAVECHANNEL="leavechannel",t.NOTIFYLEAVE="notifyleave",t.NOTIFYPUBLISH="notifypublish",t.BYE="bye",t.RECONNECT="reconnect",t.PUBLISH="publish",t.REFRESHURL="refreshurl",t.UNSUBSCRIBE="unsubscribe",t.ROLEUPDATE="roleupdate",t))(ue||{});class en{constructor(r,e){l(this,"authInfo");l(this,"userName");l(this,"seqIndex",0);this.authInfo=r,this.userName=e}get roleAuth(){if(this.authInfo.role){const{timestamp:r,nonce:e,token:i,role:s}=this.authInfo;return{timestamp:r,nonce:e,token:i,tokenrole:s}}}refreshAuthInfo(r){this.authInfo=r}getSeqIndex(){return this.seqIndex}createKeepAlivePackage(){return this.createBaseSendPackage("keepalive")}createJoinPackage(){let r=this.createBaseSendPackage("joinchannel");return r.header.displayName=this.userName,r.header.clientversion=it.getVersionNumber().toString(),r.header.platform=Zr,this.roleAuth&&(r.data.auth=this.roleAuth),r}crateLeavePackage(){return this.createBaseSendPackage("leavechannel")}createStatusPackage(r){let e=this.createBaseSendPackage("statusreport");return e.header.displayName=this.userName,e.data.status=r,e}createPublishPackage(){let r=this.createBaseSendPackage("publish");return r.data.users=[{}],this.roleAuth&&(r.data.auth=this.roleAuth),r}createRoleUpdatePackage(){let r=this.createBaseSendPackage("roleupdate");return r.header.displayName=this.userName,r}createReconnectPackage(r){let e=this.createBaseSendPackage("reconnect");return e.header.displayName=this.userName,e.header.clientversion=it.getVersionNumber().toString(),e.header.platform=Zr,e.data=q(q({},e.data),r!=null?r:{}),this.roleAuth&&(e.data.auth=this.roleAuth),e}createRefreshUrlPackage(){let r=this.createBaseSendPackage("refreshurl");return r.header.displayName=this.userName,r}createResponsePackage(r,e){return{version:1,code:200,tid:r,msgtype:e}}createBaseSendPackage(r){var i;return++this.seqIndex,{version:1,msgtype:r,tid:D.Guid.create(32),header:{appid:this.authInfo.appId,channelid:this.authInfo.channelId,sessionid:(i=this.authInfo.callid)!=null?i:"",userid:this.authInfo.userId},data:{seq:this.seqIndex}}}}var N=(t=>(t[t.ERR_JOIN_ALREADY_JOINED=16843521]="ERR_JOIN_ALREADY_JOINED",t[t.ERR_JOIN_BAD_APPID=33620481]="ERR_JOIN_BAD_APPID",t[t.ERR_JOIN_INVALID_APPID=33620482]="ERR_JOIN_INVALID_APPID",t[t.ERR_JOIN_BAD_CHANNEL=33620484]="ERR_JOIN_BAD_CHANNEL",t[t.ERR_JOIN_INVALID_CHANNEL=33620483]="ERR_JOIN_INVALID_CHANNEL",t[t.ERR_JOIN_BAD_TOKEN=33620485]="ERR_JOIN_BAD_TOKEN",t[t.ERR_JOIN_TIMEOUT=16908804]="ERR_JOIN_TIMEOUT",t[t.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD=16974081]="ERR_JOIN_ERR_JOIN_BAD_PARAMBAD",t[t.ERR_JOIN_CHANNEL_FAILED=16974338]="ERR_JOIN_CHANNEL_FAILED",t[t.ERR_LOG_ALREADY_INIT=16974085]="ERR_LOG_ALREADY_INIT",t[t.ERR_LOG_ROOT_PATH_ERROR=16974086]="ERR_LOG_ROOT_PATH_ERROR",t[t.ERR_MIC_OPEN_FAIL=17040388]="ERR_MIC_OPEN_FAIL",t[t.ERR_SPEAKER_OPEN_FAIL=17040389]="ERR_SPEAKER_OPEN_FAIL",t[t.ERR_MIC_INTERRUPT=17040390]="ERR_MIC_INTERRUPT",t[t.ERR_SPEAKER_INTERRUPT=17040391]="ERR_SPEAKER_INTERRUPT",t[t.ERR_MIC_AUTH_FAIL=17040392]="ERR_MIC_AUTH_FAIL",t[t.ERR_MIC_NOT_AVAILABLE=17040393]="ERR_MIC_NOT_AVAILABLE",t[t.ERR_SPEAKER_NO_AVAILABLE=17040400]="ERR_SPEAKER_NO_AVAILABLE",t[t.ERR_CAMERA_OPEN_FAIL=17039620]="ERR_CAMERA_OPEN_FAIL",t[t.ERR_CAMERA_INTERRUPT=17039622]="ERR_CAMERA_INTERRUPT",t[t.ERR_VIDEO_DISPLAY_OPEN_FAIL=17039873]="ERR_VIDEO_DISPLAY_OPEN_FAIL",t[t.ERR_VIDEO_DISPLAY_INTERRUPT=1064992]="ERR_VIDEO_DISPLAY_INTERRUPT",t[t.ERR_ICE_CONNECTION_CONNECT_FAIL=17105409]="ERR_ICE_CONNECTION_CONNECT_FAIL",t[t.ERR_ICE_CONNECTION_RECONNECT_FAI=17105410]="ERR_ICE_CONNECTION_RECONNECT_FAI",t[t.ERR_ICE_CONNECTION_MOBILITY_FAIL=17105411]="ERR_ICE_CONNECTION_MOBILITY_FAIL",t[t.ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT=16908812]="ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT",t[t.ERR_LATENCY_LIVE_COMMUNICATION_FAILED=17235971]="ERR_LATENCY_LIVE_COMMUNICATION_FAILED",t[t.ERR_LATENCY_LIVE_MEIDASETTING_FAILED=17235972]="ERR_LATENCY_LIVE_MEIDASETTING_FAILED",t[t.ERR_LATENCY_LIVE_NONE_BROADCASTER=17235973]="ERR_LATENCY_LIVE_NONE_BROADCASTER",t[t.ERR_LATENCY_LIVE_NEED_RESTART=17235974]="ERR_LATENCY_LIVE_NEED_RESTART",t[t.ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER=17235975]="ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER",t[t.ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE=17235976]="ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE",t[t.ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION=17235977]="ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION",t[t.ERR_SDK_PUBLISH_INVAILD=16974597]="ERR_SDK_PUBLISH_INVAILD",t[t.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL=16843782]="ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL",t[t.ERR_SDK_PUBLISH_AUDIO_STRAM_FAILED=16843856]="ERR_SDK_PUBLISH_AUDIO_STRAM_FAILED",t[t.ERR_SDK_PUBLISH_VIDEO_STRAM_FAILED=16843857]="ERR_SDK_PUBLISH_VIDEO_STRAM_FAILED",t[t.ERR_SDK_PUBLISH_DUAL_STRAM_FAILED=16843858]="ERR_SDK_PUBLISH_DUAL_STRAM_FAILED",t[t.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED=16843859]="ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED",t[t.ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR=16843860]="ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR",t[t.ERR_SDK_SUBSCRIBE_INVAILD=16974852]="ERR_SDK_SUBSCRIBE_INVAILD",t[t.ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL=16844112]="ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL",t[t.ERR_SDK_SUBSCRIBE_AUDIO_STRAM_FAILED=16844113]="ERR_SDK_SUBSCRIBE_AUDIO_STRAM_FAILED",t[t.ERR_SDK_SUBSCRIBE_VIDEO_STRAM_FAILED=16844114]="ERR_SDK_SUBSCRIBE_VIDEO_STRAM_FAILED",t[t.ERR_SDK_SUBSCRIBE_DUAL_STRAM_FAILED=16844115]="ERR_SDK_SUBSCRIBE_DUAL_STRAM_FAILED",t[t.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED=16844116]="ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED",t[t.ERR_SDK_INVALID_STATE=16974340]="ERR_SDK_INVALID_STATE",t[t.ERR_INVALID_ARGUMENTS=16974083]="ERR_INVALID_ARGUMENTS",t[t.ERR_SESSION_REMOVED=33620229]="ERR_SESSION_REMOVED",t[t.ERR_SDK_UPDATE_ROLE_CHANNEL=16908801]="ERR_SDK_UPDATE_ROLE_CHANNEL",t[t.ERR_INNER=-1]="ERR_INNER",t[t.ERR_SDK_MPU_TASK_PUBLISH_OK=0]="ERR_SDK_MPU_TASK_PUBLISH_OK",t[t.ERR_SDK_MPU_TASK_STREAM_NOT_FOUND=17825793]="ERR_SDK_MPU_TASK_STREAM_NOT_FOUND",t[t.ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST=17825794]="ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST",t[t.ERR_SDK_MPU_TASK_INVALID_PARAM=17825795]="ERR_SDK_MPU_TASK_INVALID_PARAM",t[t.ERR_SDK_MPU_TASK_INTERNAL_ERROR=17825796]="ERR_SDK_MPU_TASK_INTERNAL_ERROR",t[t.ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR=17825797]="ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR",t[t.ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR=17825798]="ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR",t[t.ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT=17825799]="ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT",t[t.ERR_SDK_MPU_TASK_NOT_AUTHORIZED=17825800]="ERR_SDK_MPU_TASK_NOT_AUTHORIZED",t[t.ERR_SDK_CHANNEL_RELAY_STATE_ERROR=18874369]="ERR_SDK_CHANNEL_RELAY_STATE_ERROR",t[t.ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW=18874370]="ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW",t[t.ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED=18874371]="ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED",t[t.ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID=18874372]="ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID",t[t.ERR_SDK_CHANNEL_RELAY_ROLE_ERROR=18874373]="ERR_SDK_CHANNEL_RELAY_ROLE_ERROR",t[t.ERR_SDK_CHANNEL_RELAY_INVALID_PARAM=18874374]="ERR_SDK_CHANNEL_RELAY_INVALID_PARAM",t[t.ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR=18874375]="ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR",t))(N||{});class C extends Error{constructor(e,i,s){super(i);l(this,"_code");l(this,"_extra");this._code=e,this._extra=s}static fromError(e,i=-1,s=""){return new C(i,e.message||e.reason||s||"error",e.extraInfo)}get code(){return this._code}set code(e){this._code=e}get reason(){return this.message}get extra(){return this._extra}}const tn=3e4;class rn extends Q{constructor(e,i,s,a,n){super();l(this,"authInfo");l(this,"userName");l(this,"channelProfile");l(this,"clientRole");l(this,"wsClient");l(this,"packageCreater");l(this,"keepAliveTimer",0);l(this,"packageCache",new Map);l(this,"isFirstConnect",!0);l(this,"aliveChecker",0);l(this,"reconnectData");this.authInfo=e,this.userName=i,this.packageCreater=new en(e,i),this.channelProfile=s,this.clientRole=a,this.wsClient=new er(n),this.wsClient.on("onOpen",this.onOpen.bind(this)),this.wsClient.on("onMessage",this.onMessage.bind(this)),this.wsClient.on("onError",this.onError.bind(this)),this.wsClient.on("onClose",this.onClose.bind(this)),this.wsClient.on("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.on("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.on("onNetworkError",this.onNetworkError.bind(this)),this.wsClient.on("onReconnectStart",this.onReconnectStart.bind(this)),this.wsClient.on("onReconnectFail",this.onReconnectFail.bind(this))}start(e){this.wsClient.start(e)}startKeepAlive(){this.keepAliveTimer===0&&(this.keepAliveTimer=window.setInterval(()=>{let e=this.packageCreater.createKeepAlivePackage();this.sendPackage(e)},5e3)),this.checkAlive()}stopKeepAlive(){this.keepAliveTimer!==0&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=0),this.aliveChecker&&(window.clearTimeout(this.aliveChecker),this.aliveChecker=0)}sendPkgCache(){this.packageCache.forEach(e=>{this.wsClient.send(e)})}leave(){let e=this.packageCreater.crateLeavePackage();this.sendPackage(e)}reportStatus(e){let i=this.packageCreater.createStatusPackage(e);this.sendPackage(i)}publish(e){let i=this.packageCreater.createPublishPackage();i.data.users=[],e.subscribe.signal=this.wsClient.connectUrl;const{tracks:s,resume:a}=e;s.forEach(n=>{const{codec:o,ssrc:c}=n;n.userdata=JSON.stringify({codec:o}),n.ssrc=`${c}`,a&&(n.attr={reason:"reconnect"})}),i.data.users.push(e),this.sendPackage(i)}roleUpdate(e){let i=this.packageCreater.createRoleUpdatePackage();i.data.clientrole=e,this.sendPackage(i)}refreshUrl(e){const i=this.packageCreater.createRefreshUrlPackage();i.data=q(Lt(q({},i.data),{sessionid:i.header.sessionid}),e),this.sendPackage(i)}refreshAuthInfo(e){this.authInfo=e,this.packageCreater.refreshAuthInfo(e)}close(){E.info("[roomsigcenter] close"),this.stopKeepAlive(),this.wsClient.off("onOpen",this.onOpen.bind(this)),this.wsClient.off("onMessage",this.onMessage.bind(this)),this.wsClient.off("onError",this.onError.bind(this)),this.wsClient.off("onClose",this.onClose.bind(this)),this.wsClient.off("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.off("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.off("onReconnectStart"),this.wsClient.off("onReconnectFail"),this.wsClient.close()}sendPackage(e){[ue.KEEPALIVE,ue.RECONNECT,ue.JOINCHANNEL].includes(e.msgtype)||this.packageCache.set(e.tid,e),this.wsClient.send(e)}updateReconnectData(e){this.reconnectData=e}onOpen(){if(E.info("[roomsigcenter] onOpen"),this.isFirstConnect){let e=this.packageCreater.createJoinPackage();e.data.configure={channelprofile:this.channelProfile},(this.channelProfile===Qe.AliRtcSdkInteractiveLive||this.channelProfile===Qe.AliRtcSdkInteractiveWithLowLatencyLive)&&(e.data.configure.clientrole=this.clientRole),this.sendPackage(e)}else{this.stopKeepAlive();const e=this.packageCreater.createReconnectPackage(this.reconnectData);this.sendPackage(e)}}onMessage(e){try{let i=JSON.parse(e.data);this.packageCache.delete(i.tid),this.onRecvMessage(i)}catch(i){E.error("[roomsigcenter] onMessage err",i,e)}}onError(e){E.error("[roomsigcenter] onError",e),this.isFirstConnect&&this.onConnectFail()}onConnectFail(){E.error("[roomsigcenter] onConnectFail");const e=new C(N.ERR_INNER,"Signaling connect failed.");this.isFirstConnect?this.emit("onJoinChannelResult",e):this.emit("onConnectFail",e)}onAuthInvalid(){E.error("[roomsigcenter] onAuthInvalid"),this.isFirstConnect&&this.emit("onAuthInvalid")}onNetworkError(){E.error("[roomsigcenter] onNetworkError");const e=new C(N.ERR_INNER,"Network error, signaling connect failed.");this.emit("onNetworkError",e)}onClose(e){E.info("[roomsigcenter] onClose",e),this.stopKeepAlive()}onKeepAliveRsp(){this.emit("onKeepAliveRsp"),this.checkAlive()}onReconnectStart(){this.emit("onReconnectStart")}onReconnectFail(){this.emit("onReconnectFail",new C(N.ERR_INNER,"signaling reconnect failed."))}checkAlive(){window.clearTimeout(this.aliveChecker),this.aliveChecker=window.setTimeout(()=>{E.info("[roomsigcenter] not alive, reconnect"),this.stopKeepAlive(),this.emit("onReconnectStart"),this.wsClient.reconnect()},tn)}onRecvMessage(e){switch(e.msgtype!==ue.KEEPALIVE&&E.info("[roomsigcenter] recv msg "+e.msgtype),e.msgtype){case ue.JOINCHANNEL:this.onJoinResult(e);break;case ue.KEEPALIVE:this.onKeepAliveRsp();break;case ue.PUBLISH:this.onPublishResult(e);break;case ue.NOTIFYJOIN:this.onNotifyJoin(e);break;case ue.NOTIFYSTATUS:this.onNotifyStatus(e);break;case ue.LEAVECHANNEL:this.onLeaveResult(e);break;case ue.NOTIFYLEAVE:this.onNotifyLeave(e);break;case ue.NOTIFYPUBLISH:this.onNotifyPublish(e);break;case ue.STATUSREPORT:this.onStatusReport(e);break;case ue.BYE:this.onBye(e);break;case ue.ROLEUPDATE:this.onRoleUpdateResult(e);break;case ue.REFRESHURL:this.onRefreshUrlResult(e);break;case ue.RECONNECT:this.onReconnectResult(e);break}}onJoinResult(e){this.isFirstConnect=!1,this.emit("onJoinChannelResult",e)}onLeaveResult(e){this.emit("onLeaveResult",e.code,e.tid)}onPublishResult(e){this.emit("onPublishResult",e.code,e.tid,e.description)}onRoleUpdateResult(e){this.emit("onRoleUpdateResult",e.code,e.tid,e.description)}onRefreshUrlResult(e){this.emit("onRefreshUrlResult",e)}onReconnectResult(e){if(e.code===200)this.sendPkgCache(),this.startKeepAlive(),this.emit("onReconnectSuccess",e.data.users);else{const i=new C(N.ERR_INNER,`reconnect failed, code: ${e.code};description: ${e.description}`);e.code===403&&(i.code=403),this.emit("onReconnectFail",i),this.close()}}onNotifyJoin(e){let i=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(i),e&&e.data&&e.data.users&&this.emit("onNotifyJoin",e.data.users)}onNotifyStatus(e){let i=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(i),e.data&&e.data.status&&e.data.status.length&&this.emit("onNotifyStatus",e.data.status)}onNotifyLeave(e){let i=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(i),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyLeave",e.data.users)}onNotifyPublish(e){let i=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(i),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyPublish",e.data.users)}onStatusReport(e){this.emit("onStatusReport",e.code,e.tid,e.description)}onBye(e){this.stopKeepAlive(),this.emit("onBye",e.reason,e.description)}}const y=(t,r)=>(e,i,s)=>{const a=s.value;return s.value=function(...n){var p;const o=`[${((p=e.constructor)==null?void 0:p.logName)||""}]`,c=Date.now();let h=[];t&&(h=t(n)),E.interface(o,i,...h);const f=a.apply(this,n);return Promise.resolve(f).then(u=>u).catch(u=>u).then(u=>{let g="";const m=u instanceof Error;!r&&!m||(m?g=u:r&&(u===void 0?g="":g=r(u)),E.interfaceResult(o,i,!m,`${Date.now()-c}ms`,g))}),f},s},I=t=>t;var sn=Object.defineProperty,an=Object.getOwnPropertyDescriptor,tr=(t,r,e,i)=>{for(var s=i>1?void 0:i?an(r,e):r,a=t.length-1,n;a>=0;a--)(n=t[a])&&(s=(i?n(r,e,s):n(s))||s);return i&&s&&sn(r,e,s),s};const hi=(Ee=class extends Q{constructor(e,i,s=rt.prod){super();l(this,"messageCenter");l(this,"authInfo");l(this,"userName");l(this,"channelProfile");l(this,"clientRole");l(this,"reconnectData");l(this,"roomServerUri","");this.channelProfile=e,this.clientRole=i,this.reconnectData={role:{channelprofile:e,clientrole:i}};const a=s===rt.pre?ai.pre:ai.prod;this.roomServerUri=`wss://${a}/roomserver/v1/ws`}updateReconnectData(e){var i;this.reconnectData=e,(i=this.messageCenter)==null||i.updateReconnectData(this.reconnectData)}reset(){E.info("[roomsig] reset"),this.messageCenter&&(this.messageCenter.close(),this.messageCenter=void 0),this.authInfo=void 0}join(e,i,s){return v(this,null,function*(){return new Promise((a,n)=>{E.setTraceID(e.channelId+"-"+e.callid),this.authInfo=e,this.userName=i,this.messageCenter=new rn(e,i,this.channelProfile,this.clientRole,s),this.initMessageCenter(),this.messageCenter.once("onJoinChannelResult",c=>{var h,f;if(E.info("join result: ",c),c.code==200){(h=this.messageCenter)==null||h.sendPkgCache(),(f=this.messageCenter)==null||f.startKeepAlive();let p=c.data;p.tid=c.tid,p.users=c.data.users,p.timestamp=c.timestamp,a(p)}else this.reset(),n(this.handleSignalError(c.code,c.reason,N.ERR_JOIN_CHANNEL_FAILED))}),this.messageCenter.once("onAuthInvalid",()=>{this.reset(),n(new C(N.ERR_JOIN_BAD_TOKEN,"join failed because authentication failed"))}),E.info(`[${Ee.logName}]`,"start ws connecting roomserver and auto join when connected");const o={appid:this.authInfo.appId,callid:this.authInfo.callid,channelid:this.authInfo.channelId,userid:this.authInfo.userId,nonce:this.authInfo.nonce||"",timestamp:this.authInfo.timestamp,token:this.authInfo.token,authtype:"app",tid:D.Guid.create(32)};e.role&&(o.tokenrole=e.role),this.messageCenter.start(this.roomServerUri+"?"+it.queryingParam(o))})})}leave(){return E.info("[roomsig] leave .."),new Promise((e,i)=>{this.messageCenter?(this.messageCenter.on("onLeaveResult",(s,a)=>{E.info(`[${Ee.logName}]`,"recv leave response "+s),s===200?(this.updateReconnectData(),this.reset(),e({tid:a})):i(this.handleSignalError(s,"leave error"))}),E.info(`[${Ee.logName}]`,"send leave request"),this.messageCenter.leave()):(E.info(`[${Ee.logName}]`,"no message center, ok to leave"),e({tid:""}))})}publish(e){return new Promise((i,s)=>{var a;this.messageCenter?(this.messageCenter.once("onPublishResult",(n,o,c)=>{E.info(`[${Ee.logName}]`,"recv pubish response "+n),n===200?(this.updateReconnectData(Lt(q({},this.reconnectData),{publish:{users:[e]}})),i({tid:o})):s(this.handleSignalError(n,`publish error, ${c}`))}),this.authInfo&&(e.sessionid=(a=this.authInfo.callid)!=null?a:""),e.callid=D.Guid.create(32),E.info(`[${Ee.logName}]`,"assign callid "+e.callid+" and send publish request"),this.messageCenter.publish(e)):s(this.handleSignalError(-1,"publish error, no message center"))})}roleUpdate(e){return new Promise((i,s)=>{if(!this.messageCenter){s(this.handleSignalError(-1,"role update error, no message center"));return}this.messageCenter.on("onRoleUpdateResult",(a,n,o)=>{var c,h;E.info(`[${Ee.logName}]`,"recv role update response "+a),a===200?((h=(c=this.reconnectData)==null?void 0:c.role)!=null&&h.clientrole&&(this.reconnectData.role.clientrole=e,this.updateReconnectData(this.reconnectData)),i({tid:n})):s(this.handleSignalError(a,`role update error, ${o}`))}),this.messageCenter.roleUpdate(e)})}setChannelProfile(e){this.channelProfile=e}refreshUrl(e){return E.info(`[${Ee.logName}]`,"refreshUrl .."),new Promise((i,s)=>{if(!this.messageCenter){s(this.handleSignalError(-1,"refresh url error, no message center"));return}this.messageCenter.on("onRefreshUrlResult",a=>{const{code:n,description:o,data:c={}}=a||{};E.info("recv refresh url response "+n),n===200?i(c):s(this.handleSignalError(n,`refresh url error, ${o}`))}),E.info("send refresh url request"),this.messageCenter.refreshUrl(e)})}reportStatus(e){return E.info(`[${Ee.logName}]`,"reportStatus "+e),new Promise((i,s)=>{this.messageCenter?(this.messageCenter.once("onStatusReport",(a,n)=>{a===200?i():s(new C(a,n))}),this.messageCenter.reportStatus(e)):s(new C(-1,"No messageCenter"))})}handleSignalError(e,i,s=N.ERR_INNER){const a=`signal error: code - ${e}; description - ${i}`;return new C(s,a)}refreshAuthInfo(e){return v(this,null,function*(){var i;this.authInfo&&(this.authInfo=e,(i=this.messageCenter)==null||i.refreshAuthInfo(this.authInfo))})}initMessageCenter(){var e,i,s,a,n,o,c,h,f,p,u,g;(e=this.messageCenter)==null||e.on("onKeepAliveRsp",()=>{this.emit("onKeepAliveRsp")}),(i=this.messageCenter)==null||i.on("onNotifyJoin",m=>{this.emit("onNotifyJoin",m)}),(s=this.messageCenter)==null||s.on("onNotifyStatus",m=>{this.emit("onNotifyStatus",m)}),(a=this.messageCenter)==null||a.on("onNotifyLeave",m=>{this.emit("onNotifyLeave",m)}),(n=this.messageCenter)==null||n.on("onNotifyPublish",m=>{this.emit("onNotifyPublish",m)}),(o=this.messageCenter)==null||o.on("onBye",(m,d)=>{this.emit("onBye",m,d)}),(c=this.messageCenter)==null||c.on("onReconnectStart",()=>{this.emit("onReconnectStart")}),(h=this.messageCenter)==null||h.on("onReconnectSuccess",m=>{this.emit("onReconnectSuccess",m)}),(f=this.messageCenter)==null||f.on("onReconnectFail",m=>{this.emit("onReconnectFail",m)}),(p=this.messageCenter)==null||p.on("onConnectFail",m=>{this.emit("onConnectFail",m),this.reset()}),(u=this.messageCenter)==null||u.on("onNetworkError",m=>{this.emit("onNetworkError",m)}),(g=this.messageCenter)==null||g.on("onAuthInvalid",()=>{this.emit("onAuthInvalid")})}},l(Ee,"logName","RoomServerSignaling"),Ee);tr([y()],hi.prototype,"join",1),tr([y()],hi.prototype,"publish",1),tr([y()],hi.prototype,"roleUpdate",1);let nn=hi;class on extends Q{constructor(e,i,s=rt.prod){super();l(this,"signaling");l(this,"authInfo");l(this,"userName");l(this,"channelProfile");l(this,"clientRole");l(this,"env",rt.prod);l(this,"maxConnectRetryCount");this.channelProfile=e,this.clientRole=i,this.env=s}reset(){var e;E.info("[signalingmanager] reset"),(e=this.signaling)==null||e.reset(),this.signaling=void 0,this.authInfo=void 0}join(e,i=e.userId,s){return this.maxConnectRetryCount=s,this.userName=i,new Promise((a,n)=>{this.signaling?n(new C(N.ERR_JOIN_ALREADY_JOINED,"already joined")):(E.info("[signalingmanager] create signaling"),this.signaling=new nn(this.channelProfile,this.clientRole,this.env),this.initSignaling(),this.signaling.join(e,i,s).then(o=>{this.authInfo=e,a(o)}).catch(o=>{this.reset(),n(o)}))})}retryJoin(){const e=this.authInfo;this.reset(),e&&this.join(e,this.userName,this.maxConnectRetryCount)}leave(){return new Promise((e,i)=>{this.signaling?this.signaling.leave().then(s=>{this.reset(),e(s)}).catch(s=>{i(s)}):e({tid:""})})}publish(e){return new Promise((i,s)=>{var a;this.signaling&&this.authInfo?(e.userid=this.authInfo.userId,e.displayname=(a=this.userName)!=null?a:this.authInfo.userId,this.signaling.publish(e).then(n=>{i(n)}).catch(n=>{s(n)})):s(new C(N.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL,"no signaling"))})}reportStatus(e){return new Promise((i,s)=>{this.signaling?this.signaling.reportStatus(e).then(()=>{i()}).catch(a=>{s(a)}):s(new C(-1,"no signaling"))})}setClientRole(e){return v(this,null,function*(){if(!this.signaling){this.clientRole=e;return}return yield this.signaling.roleUpdate(e)})}setChannelProfile(e){this.signaling?this.signaling.setChannelProfile(e):this.channelProfile=e}refreshUrl(e){return this.signaling?this.signaling.refreshUrl(e):Promise.reject(new C(N.ERR_SDK_INVALID_STATE,"should join first"))}refreshAuthInfo(e){return v(this,null,function*(){var i;try{this.authInfo&&(this.authInfo=q(q({},this.authInfo),e),(i=this.signaling)==null||i.refreshAuthInfo(this.authInfo))}catch(s){throw s}})}initSignaling(){var e,i,s,a,n,o,c,h,f,p,u,g,m;(e=this.signaling)==null||e.on("onKeepAliveRsp",this.onKeepAliveRsp.bind(this)),(i=this.signaling)==null||i.on("onNotifyJoin",this.onNotifyJoin.bind(this)),(s=this.signaling)==null||s.on("onNotifyStatus",this.onNotifyStatus.bind(this)),(a=this.signaling)==null||a.on("onNotifyLeave",this.onNotifyLeave.bind(this)),(n=this.signaling)==null||n.on("onNotifyPublish",this.onNotifyPublish.bind(this)),(o=this.signaling)==null||o.on("onBye",this.onBye.bind(this)),(c=this.signaling)==null||c.on("onReconnectStart",this.onReconnectStart.bind(this)),(h=this.signaling)==null||h.on("onReconnectSuccess",this.onReconnectSuccess.bind(this)),(f=this.signaling)==null||f.on("onReconnectFail",this.onReconnectFail.bind(this)),(p=this.signaling)==null||p.on("onConnectFail",this.onConnectFail.bind(this)),(u=this.signaling)==null||u.on("onNetworkError",this.onNetworkError.bind(this)),(g=this.signaling)==null||g.on("onAuthInvalid",this.onAuthInvalid.bind(this)),(m=this.signaling)==null||m.on("onError",this.onError.bind(this))}onKeepAliveRsp(){this.emit("onKeepAliveRsp")}onNotifyJoin(e){this.emit("onNotifyJoin",e)}onNotifyStatus(e){this.emit("onNotifyStatus",e)}onNotifyLeave(e){this.emit("onNotifyLeave",e)}onNotifyPublish(e){this.emit("onNotifyPublish",e)}onBye(e,i){this.emit("onBye",e,i)}onConnectFail(e){this.reset(),this.emit("onConnectFail",e)}onNetworkError(e){this.emit("onNetworkError",e)}onAuthInvalid(e){}onReconnectStart(){this.emit("onReconnectStart")}onReconnectSuccess(e){this.emit("onReconnectSuccess",e)}onReconnectFail(e){this.emit("onReconnectFail",e)}onError(e){this.emit("onError",e)}}const wt=class wt{static getInstance(){return wt.instance||(wt.instance=new AudioContext),wt.instance.resume(),wt.instance}};l(wt,"instance");let ir=wt;function cn(t,r,e,i,s){let a=i,n=0,o;const c=t.createAnalyser();c.fftSize=256;const h=new Uint8Array(c.frequencyBinCount);r.connect(c),c.connect(e);const f=()=>{o&&window.clearInterval(o)},p=()=>{o=window.setInterval(()=>{c.getByteFrequencyData(h);let u=Math.round(h.reduce((g,m)=>g+m)/h.length);u=Math.min(100,u),n=u,s&&s(u)},a)};return p(),{updateInterval:u=>{f(),a=u,p()},getLevel:()=>n,dispose:()=>{f(),r.disconnect(),c.disconnect()}}}class un extends Q{constructor(){super();l(this,"audioContext");l(this,"stream");l(this,"sourceNode");l(this,"analyser");this.audioContext=ir.getInstance(),this.stream=new MediaStream}getLevel(){return this.analyser?this.analyser.getLevel():0}start(e,i=1e3){this.sourceNode&&this.stop(),this.stream.addTrack(e),this.sourceNode=this.audioContext.createMediaStreamSource(this.stream);const s=this.audioContext.createMediaStreamDestination();this.analyser=cn(this.audioContext,this.sourceNode,s,i,a=>{this.emit("audioLevel",a)})}stop(){this.analyser&&this.analyser.dispose(),this.analyser=void 0,this.sourceNode=void 0,this.stream.getAudioTracks().forEach(e=>{this.stream.removeTrack(e)})}dispose(){this.stop()}}class rs extends Q{constructor(e,i,s,a){super();l(this,"uid");l(this,"name");l(this,"rtsManager");l(this,"callid","");l(this,"audioLevelMonitor");l(this,"audioVolumeIndicationInterval",0);this.uid=e,this.name=i,this.rtsManager=s,this.audioVolumeIndicationInterval=a,this.audioLevelMonitor=new un}get userId(){return this.uid}get displayname(){return this.name}setUserInfo(e,i){this.uid=e,this.name=i}refreshUserInfo(e){this.uid=e}getAudioLevel(){return this.audioLevelMonitor.getLevel()}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval=e}clear(){this.audioLevelMonitor.dispose()}}class ss{static getCurrentStatus(r){let e=0;r.micOpen&&(e+=1),r.micInterrupted&&(e+=2),r.cameraOpen&&(e+=4),r.screenShare&&(e+=128),r.audioDisable&&(e+=8),r.videoDisable&&(e+=16),r.screenDisable&&(e+=256);let i=e.toString(16);for(;i.length<16;)i="0"+i;return i}static parseStatus(r){let e=parseInt(r,16);return{micOpen:!!(e&1),micInterrupted:!!(e&2),cameraOpen:!!(e&4),screenShare:!!(e&128),audioDisable:!!(e&8),videoDisable:!!(e&16),screenDisable:!!(e&256),backgroundMode:!!(e&32),accompanyPlaying:!!(e&64)}}}const as="customVideoProfile",ns="customScreenProfile",jt={width:1280,height:720,frameRate:30,maxBitrate:2e3},$t={width:1920,height:1080,frameRate:30,maxBitrate:2600},hn={1e4:re.AliEngineLocalDeviceExceptionTypeUnknown,2e4:re.AliEngineLocalDeviceExceptionTypeUnknown,10001:re.AliEngineLocalDeviceExceptionTypeMicNotAvailable,10002:re.AliEngineLocalDeviceExceptionTypeMicAuthFail,10003:re.AliEngineLocalDeviceExceptionTypeMicOpenFail,10005:re.AliEngineLocalDeviceExceptionTypeCameraAuthFail,10004:re.AliEngineLocalDeviceExceptionTypeVideoDeviceException,10006:re.AliEngineLocalDeviceExceptionTypeCameraOpenFail,10010:re.AliEngineLocalDeviceExceptionTypeDisplayException,10011:re.AliEngineLocalDeviceExceptionTypeDisplayException,10012:re.AliEngineLocalDeviceExceptionTypeDisplayException,10013:re.AliEngineLocalDeviceExceptionTypeDisplayException,10014:re.AliEngineLocalDeviceExceptionTypeDisplayException,10019:re.AliEngineLocalDeviceExceptionTypeDisplayException},ln=t=>t.getAudioTracks()[0];function os(t){var r;if(((r=t==null?void 0:t.nodeName)==null?void 0:r.toLowerCase())==="video")return t.setAttribute("playsinline",""),t;if(typeof t=="string"){let e=document.getElementById(t);if(e){if(e.nodeName.toLocaleLowerCase()==="video")return e.setAttribute("playsinline",""),e;throw new C(N.ERR_INVALID_ARGUMENTS,"element should be HtmlVideoElement")}else throw new C(N.ERR_INVALID_ARGUMENTS,"element not founded")}else throw new C(N.ERR_INVALID_ARGUMENTS,"element id should be string")}function rr(t){var e;const r=[];if(Array.isArray(t))t.forEach(i=>{try{r.push(os(i))}catch(s){}});else if(typeof t=="string"||((e=t==null?void 0:t.nodeName)==null?void 0:e.toLowerCase())==="video")try{r.push(os(t))}catch(i){}return r}function at(t){return new Promise(r=>setTimeout(r,t))}const cs=(t,r)=>{const e=()=>(t.muted=!0,Promise.race([at(500),t._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{let i;return t.srcObject!==r?(t.load(),t.srcObject=r,i=t.play(),t._playPromise=i):i=Promise.resolve(),i}));return new Promise(i=>{if(D.BrowserUtil.isMicroMessenger){const s=window.top!==window.self,a=window.WeixinJSBridge||window.top.WeixinJSBridge;a?a.invoke("getNetworkType",{},()=>{i(e())}):(s?window.top.document:document).addEventListener("WeixinJSBridgeReady",()=>{a.invoke("getNetworkType",{},()=>{i(e())})}),setTimeout(()=>{i(e())},1e3)}else i(e())})},nt=t=>{Promise.race([at(100),t._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{t.srcObject=null,t._playPromise=void 0})};var dn=Object.defineProperty,pn=Object.getOwnPropertyDescriptor,oe=(t,r,e,i)=>{for(var s=i>1?void 0:i?pn(r,e):r,a=t.length-1,n;a>=0;a--)(n=t[a])&&(s=(i?n(r,e,s):n(s))||s);return i&&s&&dn(r,e,s),s};class li extends Q{constructor(){super();l(this,"state");l(this,"time");this.state=B.AliRtcStatePublishIdle,this.time=Date.now()}setState(e){const i=this.state,s=this.time;this.state=e,this.time=Date.now(),this.emit("change",i,e,Math.floor((this.time-s)/1e3))}}const se=(ct=class extends rs{constructor(e){const{rtsManager:i,localStreamManager:s,reporter:a,webTrackingClient:n,signalingManager:o,audioVolumeIndicationInterval:c}=e;super("","",i,c);l(this,"url","");l(this,"_isPublishing",!1);l(this,"publishPromise",Promise.resolve(""));l(this,"previewElements",[]);l(this,"screenPreviewElements",[]);l(this,"streamManager");l(this,"streamTracks");l(this,"publishId",D.Guid.create(16));l(this,"signalingManager");l(this,"traceId","");l(this,"monitorTimerId");l(this,"reporter");l(this,"webTrackingClient");l(this,"audioPubState");l(this,"videoPubState");l(this,"videoSmallPubState");l(this,"screenPubState");l(this,"onTrackEnd",e=>{this.emit(e)});this.streamManager=s,this.signalingManager=o,this.reporter=a,this.webTrackingClient=n,this.streamManager.on("trackended",h=>{this.onTrackEnd(h)}),this.streamManager.on("publishupdate",()=>{this.publishUpdate()}),this.audioPubState=new li,this.audioPubState.on("change",(h,f,p)=>{this.emit("audioPublishStateChanged",h,f,p)}),this.videoPubState=new li,this.videoPubState.on("change",(h,f,p)=>{this.emit("videoPublishStateChanged",h,f,p)}),this.videoSmallPubState=new li,this.videoSmallPubState.on("change",(h,f,p)=>{this.emit("dualStreamPublishStateChanged",h,f,p)}),this.screenPubState=new li,this.screenPubState.on("change",(h,f,p)=>{this.emit("screenPublishStateChanged",h,f,p)})}get joined(){return!!this.uid}get isPublishing(){return this._isPublishing}get publishStreams(){return this.streamManager.publishStreams}get cameraTrack(){return this.streamManager.cameraStreamInfo.originVideoTrack}get screenTrack(){return this.streamManager.screenStreamInfo.originVideoTrack}get audioTrack(){return this.streamManager.cameraStreamInfo.originAudioTrack}get hasCamera(){return!!this.streamManager.cameraStreamInfo.originVideoTrack}get hasMicrophone(){return!!this.streamManager.cameraStreamInfo.originAudioTrack}get hasScreenShare(){return!!this.streamManager.screenStreamInfo.originVideoTrack}get hasCameraTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:i,type:s,msid:a})=>s==="video"&&i&&a===k.VideoLarge))}get hasCameraDualTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:i,type:s,msid:a})=>s==="video"&&i&&a===k.VideoSmall))}get hasScreenTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:i,type:s,msid:a})=>s==="video"&&i&&a===k.Screen))}get hasAudioTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:i,type:s,msid:a})=>s==="audio"&&i&&a===k.Audio))}get cameraDirection(){var e,i;return(i=(e=this.streamManager.cameraStreamInfo)==null?void 0:e.cameraVideoConstraints)==null?void 0:i.facingMode}get audioCaptureDisabled(){return this.streamManager.audioCaptureDisabled}get cameraCaptureDisabled(){return this.streamManager.cameraCaptureDisabled}get publishLocalVideoStreamEnabled(){return this.streamManager.publishLocalVideoStreamEnabled}get publishLocalAudioStreamEnabled(){return this.streamManager.publishLocalAudioStreamEnabled}get publishLocalScreenStreamEnabled(){return this.streamManager.publishLocalScreenStreamEnabled}setPublishLocalAudioStreamEnabled(e){this.streamManager.publishLocalAudioStreamEnabled=e}setPublishLocalVideoStreamEnabled(e){this.streamManager.publishLocalVideoStreamEnabled=e}setPublishLocalScreenStreamEnabled(e){this.streamManager.publishLocalScreenStreamEnabled=e}initInfo(e,i){var s;this.setUserInfo(e.userId,e.userId),this.url=i,this.callid=(s=e.callid)!=null?s:"",this.updatePubId()}setVideoProfile(e,i){return v(this,null,function*(){yield this.streamManager.setVideoProfile(e,i)})}setVideoContentHint(e){this.streamManager.setVideoContentHint(e)}setScreenContentHint(e){this.streamManager.setScreenContentHint(e)}setAudioProfile(e){return v(this,null,function*(){yield this.streamManager.setAudioProfile(e)})}setScreenProfile(e,i){return v(this,null,function*(){yield this.streamManager.setScreenProfile(e,i)})}setCameraDirection(e){if(e===Ft.CAMERA_FRONT)this.streamManager.setCameraVideoConstraints({facingMode:"user"});else if(e===Ft.CAMERA_REAR)this.streamManager.setCameraVideoConstraints({facingMode:"environment"});else throw new C(N.ERR_CAMERA_OPEN_FAIL,`camera direction set to ${e} failed`)}setCameraDeviceId(e){this.streamManager.setCameraVideoConstraints({deviceId:e})}muteLocalCamera(e){this.streamManager.setCameraMuted(e)}muteLocalMic(e){this.streamManager.setAudioMuted(e)}muteLocalScreen(e){this.streamManager.setScreenMuted(e)}setMicrophoneDeviceId(e){this.streamManager.setMicAudioConstraints({deviceId:e})}updatePubId(){this.publishId=D.Guid.create(16)}clearPublishState(){this.streamTracks=void 0}clear(){return v(this,null,function*(){Pr(ct.prototype,this,"clear").call(this),this._isPublishing&&(yield this.unPublish()),this.stopPreview(),this.resetPreviewElements(),this.resetSecondayPreviewElements(),this.clearStream(),this.stopStreamMonitor(),this.streamManager.cameraCaptureDisabled=!1})}resetElement(e){this.previewElements.includes(e)&&(nt(e),this.previewElements.splice(this.previewElements.indexOf(e),1)),this.screenPreviewElements.includes(e)&&(nt(e),this.screenPreviewElements.splice(this.screenPreviewElements.indexOf(e),1))}setPreviewElement(e){const{videoElement:i,screen:s}=e;s?this.screenPreviewElements.includes(i)||this.screenPreviewElements.push(i):this.previewElements.includes(i)||this.previewElements.push(i)}setViewConfig(e,i){if(!e){i===W.AliRtcVideoTrackCamera?this.stopPreview({primary:!0,screen:!1}):this.stopPreview({primary:!1,screen:!0});return}if(![W.AliRtcVideoTrackCamera,W.AliRtcVideoTrackScreen].includes(i))throw new C(N.ERR_INVALID_ARGUMENTS,"set view config invalid track",{track:i});e.forEach(s=>{this.setPreviewElement({videoElement:s,screen:i===W.AliRtcVideoTrackScreen})})}startCameraCapture(e){return v(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,yield this.createLocalStream(e)})}stopCameraCapture(){return v(this,null,function*(){this.streamManager.cameraCaptureDisabled=!0,yield this.stopLocalStream({video:!0})})}stopAudioCapture(){return v(this,null,function*(){this.streamManager.audioCaptureDisabled=!0,yield this.stopLocalStream({audio:!0})})}preview(e){return v(this,null,function*(){const{videoElement:i,screen:s}=e!=null?e:{};try{let a=s?this.streamManager.screenStreamInfo.previewStream:this.streamManager.cameraStreamInfo.previewStream;if(!i)throw new C(N.ERR_INVALID_ARGUMENTS,"no video element found",{videoElement:i});if(!a){E.info(`[${ct.logName}]`,"preview no stream founded");return}return cs(i,a.mediaStream),this.setPreviewElement(e),a.mediaStream}catch(a){const n=N.ERR_INNER;throw C.fromError(a,n,"preview failed")}})}previewAll(e){return v(this,null,function*(){const{primary:i=!0,screen:s=!0}=e!=null?e:{};if(i&&this.previewElements.length)for(let a=0;a<this.previewElements.length;a++){const n=this.previewElements[a];yield this.preview({videoElement:n})}if(s&&this.screenPreviewElements.length)for(let a=0;a<this.screenPreviewElements.length;a++){const n=this.screenPreviewElements[a];yield this.preview({videoElement:n,screen:!0})}})}stopPreview(e){const{videoElement:i,primary:s=!0,screen:a=!0}=e||{};if(!i)s&&(this.previewElements.forEach(n=>{nt(n)}),this.previewElements=[]),a&&(this.screenPreviewElements.forEach(n=>{nt(n)}),this.screenPreviewElements=[]);else{const n=this.previewElements.findIndex(o=>o===i);if(n>=0)this.previewElements.splice(n,1),nt(i);else{const o=this.screenPreviewElements.findIndex(c=>c===i);o>=0&&(this.screenPreviewElements.splice(o,1),nt(i))}}}resumePublish(){return v(this,null,function*(){this._isPublishing=!1,yield this.startPublish(!0)})}createLocalStream(e){return v(this,null,function*(){try{const i=yield this.streamManager.createLocalStream(e);return i!=null&&i.audioTrack&&this.audioVolumeIndicationInterval>0&&this.audioLevelMonitor.start(i.audioTrack,this.audioVolumeIndicationInterval),e.video?this.previewAll({primary:!0}):e.screen&&this.previewAll({screen:!0}),i}catch(i){const s=hn[i.errorCode];throw s&&(e.audio?this.emit("localDeviceException",Ke.AliEngineLocalDeviceTypeMic,s,""):e.video?this.emit("localDeviceException",Ke.AliEngineLocalDeviceTypeCamera,s,""):e.screen?this.emit("localDeviceException",Ke.AliEngineLocalDeviceTypeDisplay,s,""):this.emit("localDeviceException",Ke.AliEngineLocalDeviceTypeUnknown,s,"")),i}})}stopLocalStream(e){return v(this,null,function*(){e.audio&&this.audioLevelMonitor.stop(),yield this.streamManager.stopLocalStream(e)})}compareAndPublish(e,i,s){return v(this,null,function*(){var n,o;if(!e&&!i)return;if(e&&!i){const c={};return s===k.Audio?c.audio=!0:s===k.VideoLarge||s===k.VideoSmall?(c.video=!0,c.vMsid=s):s===k.Screen&&(c.screen=!0),yield this.publishDeleteTracks(c)}const a={};if(i!=null&&i.hasVideo&&(a.isScreen=s===k.Screen,a.vMsid=s),i!=null&&i.hasAudio&&(a.aMsid=s),!e&&i)return yield this.publishAdd(i,a,!1);if(e&&i){const c=e.trackId,h=((n=i.videoTrack)==null?void 0:n.id)||((o=i.audioTrack)==null?void 0:o.id);if(c!==h)return yield this.publishReplace(i,a)}})}startPublish(e=!1){return v(this,null,function*(){if(!this.joined)return;const i=yield this.streamManager.publishStreams,{audio:s,video:a,videoSmall:n,screen:o}=i;try{const c=new Date().getTime();s&&this.audioPubState.setState(B.AliRtcStatePublishing),a&&this.videoPubState.setState(B.AliRtcStatePublishing),n&&this.videoSmallPubState.setState(B.AliRtcStatePublishing),o&&this.screenPubState.setState(B.AliRtcStatePublishing),this.publishPromise=this.rtsManager.publish(this.url,e);const h=yield this.publishPromise;this._isPublishing=!0,this.streamTracks=this.rtsManager.publishingTracks,this.traceId=h;const f={userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:e,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callid,tracks:this.streamTracks,traceId:h};yield this.syncPublishToRoomServer(f,i,c),s&&this.audioPubState.setState(B.AliRtcStatePublished),a&&this.videoPubState.setState(B.AliRtcStatePublished),n&&this.videoSmallPubState.setState(B.AliRtcStatePublished),o&&this.screenPubState.setState(B.AliRtcStatePublished)}catch(c){throw s&&this.audioPubState.setState(B.AliRtcStateNoPublish),a&&this.videoPubState.setState(B.AliRtcStateNoPublish),n&&this.videoSmallPubState.setState(B.AliRtcStateNoPublish),o&&this.screenPubState.setState(B.AliRtcStateNoPublish),c}})}publishUpdate(){return v(this,null,function*(){var a,n,o,c;if(!this._isPublishing)return;yield this.publishPromise;const e=yield this.streamManager.publishStreams;let i;const s=new Date().getTime();try{const h=(a=this.streamTracks)==null?void 0:a.find(({ssrc:b,type:w,msid:_})=>w==="audio"&&b&&_===k.Audio),f=yield this.compareAndPublish(h,e.audio,k.Audio);f&&(i=f);const p=(n=this.streamTracks)==null?void 0:n.find(({ssrc:b,type:w,msid:_})=>w==="video"&&b&&_===k.VideoLarge),u=yield this.compareAndPublish(p,e.video,k.VideoLarge);u&&(i=u);const g=(o=this.streamTracks)==null?void 0:o.find(({ssrc:b,type:w,msid:_})=>w==="video"&&b&&_===k.VideoSmall),m=yield this.compareAndPublish(g,e.videoSmall,k.VideoSmall);m&&(i=m);const d=(c=this.streamTracks)==null?void 0:c.find(({ssrc:b,type:w,msid:_})=>w==="video"&&b&&_===k.Screen),S=yield this.compareAndPublish(d,e.screen,k.Screen);if(S&&(i=S),!i)return;yield this.syncPublishToRoomServer(i,e,s)}catch(h){const{code:f}=h!=null?h:{},p=this.url;throw f===403&&p&&(yield this.refreshPushStreamUrl(),i=yield this.publishUpdate()),h}return i})}syncPublishToRoomServer(e,i,s){return v(this,null,function*(){var p;if(!e)throw new C(N.ERR_INNER,"sync publish to room server failed because no publishInfo");const a=yield this.signalingManager.publish(e);e.signaltid=a.tid;const n=new Date().getTime()-s,o=!!i.video,c=!1,h=!!i.screen,f=!!i.audio;this.reporter.reportPublish(this.callid||"",o,c,h,f,0,a.tid,n),this.webTrackingClient.reportPush(this.callid||"",o,c,h,f,0,a.tid,n,s,e.traceid||"",this.traceId,(p=this.url)!=null?p:"")})}refreshPushStreamUrl(){return v(this,null,function*(){const e=new C(N.ERR_INNER,"refresh push stream url error"),i=this.url;if(!i)throw e;const s=yield this.signalingManager.refreshUrl({pushstreamurl:i});if(!(s!=null&&s.pushstreamurl))throw e;this.url=s==null?void 0:s.pushstreamurl})}publishAdd(e,i,s=!1,a=0){return v(this,null,function*(){const n=(i==null?void 0:i.aMsid)===k.Audio,o=(i==null?void 0:i.vMsid)===k.VideoLarge,c=(i==null?void 0:i.vMsid)===k.VideoSmall,h=(i==null?void 0:i.vMsid)===k.Screen;n&&this.audioPubState.setState(B.AliRtcStatePublishing),o&&this.videoPubState.setState(B.AliRtcStatePublishing),c&&this.videoSmallPubState.setState(B.AliRtcStatePublishing),h&&this.screenPubState.setState(B.AliRtcStatePublishing);try{const f=yield this.rtsManager.publishAdd(this.url,e,i,!1,0,!0);n&&this.audioPubState.setState(B.AliRtcStatePublished),o&&this.videoPubState.setState(B.AliRtcStatePublished),c&&this.videoSmallPubState.setState(B.AliRtcStatePublished),h&&this.screenPubState.setState(B.AliRtcStatePublished),this.streamTracks=this.rtsManager.publishingTracks;const p={userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:s,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callid,tracks:this.streamTracks,traceid:f};return this.reportSelfDeviceStatus(),p}catch(f){let p=N.ERR_SDK_PUBLISH_INVAILD;if(n&&(this.audioPubState.setState(B.AliRtcStateNoPublish),p=N.ERR_SDK_PUBLISH_AUDIO_STRAM_FAILED),o&&(this.videoPubState.setState(B.AliRtcStateNoPublish),p=N.ERR_SDK_PUBLISH_VIDEO_STRAM_FAILED),c&&(this.videoSmallPubState.setState(B.AliRtcStateNoPublish),p=N.ERR_SDK_PUBLISH_DUAL_STRAM_FAILED),h&&(this.screenPubState.setState(B.AliRtcStateNoPublish),p=N.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED),f.errorCode===15006&&a<3)return this.publishAdd(e,i,s,a+1);throw C.fromError(f,p,"publish add failed")}})}publishReplace(e,i){return v(this,null,function*(){try{yield this.rtsManager.publishReplace(this.url,e,i),this.traceId="",this.streamTracks=this.rtsManager.publishingTracks;const s={userid:this.userId,sessionid:"",pubid:this.publishId,displayname:this.name,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callid,tracks:this.streamTracks};return this.reportSelfDeviceStatus(),s}catch(s){throw C.fromError(s,N.ERR_INNER,`publish replace failed, vMsid: ${i==null?void 0:i.vMsid} aMsid: ${i==null?void 0:i.aMsid}`)}})}publishDeleteTracks(e){return v(this,null,function*(){const i={userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callid,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{return yield this.rtsManager.publishDelete(this.url,e),this.streamTracks=this.rtsManager.publishingTracks,e.audio&&this.audioPubState.setState(B.AliRtcStateNoPublish),e.video&&(e.vMsid===k.VideoSmall?this.videoSmallPubState.setState(B.AliRtcStateNoPublish):this.videoPubState.setState(B.AliRtcStateNoPublish)),e.screen&&this.screenPubState.setState(B.AliRtcStateNoPublish),this.traceId="",i.tracks=this.streamTracks,this.reportSelfDeviceStatus(),i}catch(s){throw C.fromError(s,N.ERR_INNER,"publish delete tracks failed")}})}publishStop(){return v(this,null,function*(){if(!this._isPublishing)throw new C(N.ERR_INNER,"publish stop failed, previous localStream is required for publishing stopping");E.info(`[${ct.logName}]`,"publishStop",{url:this.url});const e=new Date().getTime();try{const i=this.hasAudioTrackInMS,s=this.hasCameraTrackInMS,a=this.hasCameraDualTrackInMS,n=this.hasScreenTrackInMS;yield this.rtsManager.publishStop(this.url),i&&this.audioPubState.setState(B.AliRtcStateNoPublish),s&&this.videoPubState.setState(B.AliRtcStateNoPublish),a&&this.videoSmallPubState.setState(B.AliRtcStateNoPublish),n&&this.screenPubState.setState(B.AliRtcStateNoPublish),this.traceId="",this.streamTracks=[];const o={userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callid,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};return this.syncPublishToRoomServer(o,{},e),o}catch(i){throw C.fromError(i,N.ERR_INNER,"publish stop failed")}})}unPublish(){return v(this,null,function*(){const e=new Date().getTime();let i={userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callid,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{if(this._isPublishing){const s=this.hasAudioTrackInMS,a=this.hasCameraTrackInMS,n=this.hasCameraDualTrackInMS,o=this.hasScreenTrackInMS;yield this.rtsManager.unpublish(),s&&this.audioPubState.setState(B.AliRtcStateNoPublish),a&&this.videoPubState.setState(B.AliRtcStateNoPublish),n&&this.videoSmallPubState.setState(B.AliRtcStateNoPublish),o&&this.screenPubState.setState(B.AliRtcStateNoPublish),this._isPublishing=!1,this.traceId="",this.clearStream()}return this.reporter.reportUnpublish(this.callid||"",e,0,""),i}catch(s){throw C.fromError(s,N.ERR_INNER,"unpublish failed")}})}reportSelfDeviceStatus(){this.emit(we.Local,this.getDeviceStatus())}getDeviceStatus(){var i,s,a,n;let e={micOpen:!1,micInterrupted:!1,cameraOpen:!1,screenShare:!1,audioDisable:!0,videoDisable:!0,screenDisable:!0,backgroundMode:!1,accompanyPlaying:!1};return e.cameraOpen=this.hasCamera,e.micOpen=this.hasMicrophone,e.screenShare=this.hasScreenShare,e.audioDisable=!((i=this.streamManager.cameraStreamInfo.originAudioTrack)!=null&&i.enabled),e.videoDisable=!((s=this.streamManager.cameraStreamInfo.originVideoTrack)!=null&&s.enabled),e.screenDisable=!this.hasScreenShare||!((n=(a=this.streamManager.screenStreamInfo)==null?void 0:a.originVideoTrack)!=null&&n.enabled),ss.getCurrentStatus(e)}resetPreviewElements(){this.previewElements=[]}resetSecondayPreviewElements(){this.screenPreviewElements=[]}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0)}clearStream(){this.streamManager.stop(),this.audioPubState.setState(B.AliRtcStatePublishIdle),this.videoPubState.setState(B.AliRtcStatePublishIdle),this.videoSmallPubState.setState(B.AliRtcStatePublishIdle),this.screenPubState.setState(B.AliRtcStatePublishIdle)}getCurrentCameraDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originVideoTrack)==null?void 0:e.getSettings().deviceId}getCurrentMicDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originAudioTrack)==null?void 0:e.getSettings().deviceId}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.streamManager.cameraStreamInfo.originAudioTrack&&this.audioLevelMonitor.start(this.streamManager.cameraStreamInfo.originAudioTrack,e),this.audioVolumeIndicationInterval=e)}sendSEI(e,i,s){return v(this,null,function*(){if(!this.url)return;let a=0;return!i||i<1?a=1:a=i-1,this.rtsManager.sendSEI(this.url,e,a,s)})}getStats(){return v(this,null,function*(){const e=[];if(this.hasAudioTrackInMS){const s=yield this.rtsManager.getPublishAudioStats(this.url);s&&e.push({stats:s,track:kt.AliRtcAudioTrackMic})}const i=[];if(this.hasCameraTrackInMS){const s=yield this.rtsManager.getPublishVideoStats(this.url,k.VideoLarge);s&&i.push({track:W.AliRtcVideoTrackCamera,streamType:he.AliRtcVideoStreamTypeHigh,stats:s})}if(this.hasCameraDualTrackInMS){const s=yield this.rtsManager.getPublishVideoStats(this.url,k.VideoSmall);s&&i.push({track:W.AliRtcVideoTrackCamera,streamType:he.AliRtcVideoStreamTypeLow,stats:s})}if(this.hasScreenTrackInMS){const s=yield this.rtsManager.getPublishVideoStats(this.url,k.Screen);s&&i.push({track:W.AliRtcVideoTrackScreen,stats:s})}return{audio:e,video:i}})}},l(ct,"logName","LocalUser"),ct);oe([y()],se.prototype,"clearPublishState",1),oe([y()],se.prototype,"clear",1),oe([y()],se.prototype,"setViewConfig",1),oe([y()],se.prototype,"startCameraCapture",1),oe([y()],se.prototype,"stopCameraCapture",1),oe([y()],se.prototype,"stopAudioCapture",1),oe([y()],se.prototype,"stopPreview",1),oe([y()],se.prototype,"resumePublish",1),oe([y()],se.prototype,"createLocalStream",1),oe([y()],se.prototype,"stopLocalStream",1),oe([y(I)],se.prototype,"startPublish",1),oe([y(([t])=>[t])],se.prototype,"syncPublishToRoomServer",1),oe([y()],se.prototype,"refreshPushStreamUrl",1),oe([y(([t,r,e])=>[JSON.stringify(e)])],se.prototype,"publishAdd",1),oe([y(([t,r])=>[JSON.stringify(r)])],se.prototype,"publishReplace",1),oe([y(I)],se.prototype,"publishDeleteTracks",1),oe([y()],se.prototype,"publishStop",1),oe([y()],se.prototype,"unPublish",1),oe([y(([t,r,e])=>[t.length,r,e])],se.prototype,"sendSEI",1);let us=se;var St=(t=>(t.OPUS="opus",t.H264="H264",t.UNKONWN="",t))(St||{}),bt=(t=>(t.VideoTrackEnded="videoTrackEnded",t.AudioTrackEnded="audioTrackEnded",t.ScreenTrackEnded="screenTrackEnded",t))(bt||{});const gn=t=>{const r=new MediaStream;return r.addTrack(t),r},hs=t=>v(this,null,function*(){return yield V.AliRTS.createStream({custom:!0,mediaStream:t})}),Wt=t=>v(this,null,function*(){const r=gn(t);return yield hs(r)}),fn=t=>{const{audio:r,video:e,screen:i}=t;if(e&&i)throw new C(N.ERR_INNER,"create stream error, cannot create video && screen together");return!(!e&&!r&&!i)},mn=t=>t===k.Audio||t===Wi.Audio,Sn=t=>t===k.VideoLarge||t===Wi.VideoLarge,bn=t=>t===k.VideoSmall,vn=t=>t===k.Screen;var yn=Object.defineProperty,wn=Object.getOwnPropertyDescriptor,_n=(t,r,e,i)=>{for(var s=i>1?void 0:i?wn(r,e):r,a=t.length-1,n;a>=0;a--)(n=t[a])&&(s=(i?n(r,e,s):n(s))||s);return i&&s&&yn(r,e,s),s};class di extends Q{constructor(){super();l(this,"audioInfo",{subscribed:!1,ssrc:"",msid:"",pt:0,red:0,codec:St.UNKONWN});l(this,"videoLargeInfo",{subscribed:!1,ssrc:"",msid:"",pt:0,red:0,codec:St.UNKONWN});l(this,"videoSmallInfo",{subscribed:!1,ssrc:"",msid:"",pt:0,red:0,codec:St.UNKONWN});l(this,"screenInfo",{subscribed:!1,ssrc:"",msid:"",pt:0,red:0,codec:St.UNKONWN});l(this,"audioVolume",1);l(this,"audioMuted",!1);l(this,"userStatus")}getAudioInfo(){return this.audioInfo}getVideoSmallInfo(){return this.videoSmallInfo}getVideoLargeInfo(){return this.videoLargeInfo}getScreenInfo(){return this.screenInfo}get hasAudio(){return this.audioInfo.ssrc!==""}get hasVideo(){return this.videoLargeInfo.ssrc!==""||this.videoSmallInfo.ssrc!==""}get hasVideoLarge(){return this.videoLargeInfo.ssrc!==""}get hasVideoSmall(){return this.videoSmallInfo.ssrc!==""}get hasScreen(){return this.screenInfo.ssrc!==""}get isAudioSubscribing(){return!!this.audioInfo.subscribed}get isVideoSubscribing(){return!!this.videoLargeInfo.subscribed||!!this.videoSmallInfo.subscribed}get isVideoLargeSubscribing(){return!!this.videoLargeInfo.subscribed}get isVideoSmallSubscribing(){return!!this.videoSmallInfo.subscribed}get isScreenSubscribing(){return!!this.screenInfo.subscribed}get audioCodec(){return this.audioInfo.codec}get videoCodec(){return this.hasVideoLarge?this.videoLargeInfo.codec:this.hasVideoSmall?this.videoSmallInfo.codec:this.hasScreen?this.screenInfo.codec:St.UNKONWN}get audioTrackInfo(){return this.hasAudio?kt.AliRtcAudioTrackMic:kt.AliRtcAudioTrackNo}get videoTrackInfo(){return this.hasVideo&&this.hasScreen?W.AliRtcVideoTrackBoth:this.hasVideo?W.AliRtcVideoTrackCamera:this.hasScreen?W.AliRtcVideoTrackScreen:W.AliRtcVideoTrackNo}updateTracks(e){let i="",s="",a="",n="";return e?(e.forEach(o=>{var f;let c=St.UNKONWN;const h=((f=o==null?void 0:o.attr)==null?void 0:f.reason)==="reconnect";if(o.userdata){const{codec:p}=JSON.parse(o.userdata);p&&(c=p)}mn(o.msid)?(i=o.ssrc,this.audioInfo.msid=o.msid,this.audioInfo.codec=c,h&&(this.audioInfo.subscribed=!1)):bn(o.msid)?(a=o.ssrc,this.videoSmallInfo.msid=o.msid,this.videoSmallInfo.codec=c,h&&(this.videoSmallInfo.subscribed=!1)):Sn(o.msid)?(s=o.ssrc,this.videoLargeInfo.msid=o.msid,this.videoLargeInfo.codec=c,h&&(this.videoLargeInfo.subscribed=!1)):vn(o.msid)&&(n=o.ssrc,this.screenInfo.msid=o.msid,this.screenInfo.codec=c,h&&(this.screenInfo.subscribed=!1))}),this.updateRemoteTrackSsrc(i,s,a,n)):this.updateRemoteTrackSsrc(i,s,a,n),{}}updateRemoteTrackSsrc(e,i,s,a){this.audioInfo.ssrc=e,this.videoSmallInfo.ssrc=s,this.videoLargeInfo.ssrc=i,this.screenInfo.ssrc=a}updateRemoteTrackSubState(e){return e.video!==void 0&&((e.vMsid===this.videoSmallInfo.msid||!e.vMsid)&&(this.videoSmallInfo.subscribed=e.video),(e.vMsid===this.videoLargeInfo.msid||!e.vMsid)&&(this.videoLargeInfo.subscribed=e.video)),e.screen!==void 0&&(this.screenInfo.subscribed=e.screen),e.audio!==void 0&&(this.audioInfo.subscribed=e.audio),{audioInfo:this.audioInfo,videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo,screenInfo:this.screenInfo}}updateRemoteUserDeviceStatus(e){let i=ss.parseStatus(e);const{audioDisable:s,videoDisable:a,screenDisable:n}=i;return this.userStatus?(this.userStatus.audioDisable!=s&&(this.userStatus.audioDisable=s,this.emit(we.Remote,s?J.MuteAudio:J.UnmuteAudio)),this.userStatus.videoDisable!=a&&(this.userStatus.videoDisable=a,this.emit(we.Remote,a?J.MuteVideo:J.UnmuteVideo)),this.userStatus.screenDisable!=n&&(this.userStatus.screenDisable=n,this.emit(we.Remote,n?J.MuteScreen:J.UnmuteScreen))):(this.userStatus=i,this.emit(we.Remote,s?J.MuteAudio:J.UnmuteAudio),this.emit(we.Remote,a?J.MuteVideo:J.UnmuteVideo),this.emit(we.Remote,n?J.MuteScreen:J.UnmuteScreen)),!1}}l(di,"logName","RemoteStreamInfo"),_n([y()],di.prototype,"updateRemoteTrackSubState",1);class ls{constructor(r){l(this,"remoteUser");this.remoteUser=r}get userId(){return this.remoteUser.userId}get displayName(){return this.remoteUser.displayname}get isMuteAudioPlaying(){return this.remoteUser.getAudioMuted()}get hasAudio(){return this.remoteUser.hasAudioTrack}get hasCamera(){return this.remoteUser.hasVideoTrack}get hasCameraLarge(){return this.remoteUser.hasVideoLargeTrack}get hasCameraSmall(){return this.remoteUser.hasVideoSmallTrack}get hasScreenShare(){return this.remoteUser.hasScreenTrack}get isAudioSubscribing(){return this.remoteUser.isAudioSubscribing}get isVideoSubscribing(){return this.remoteUser.isVideoSubscribing}get isVideoLargeSubscribing(){return this.remoteUser.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.remoteUser.isVideoSmallSubscribing}get isScreenSubscribing(){return this.remoteUser.isScreenSubscribing}}var Rn=Object.defineProperty,In=Object.getOwnPropertyDescriptor,le=(t,r,e,i)=>{for(var s=i>1?void 0:i?In(r,e):r,a=t.length-1,n;a>=0;a--)(n=t[a])&&(s=(i?n(r,e,s):n(s))||s);return i&&s&&Rn(r,e,s),s};class Kt extends Q{constructor(){super();l(this,"state");l(this,"time");l(this,"_enabled");this.state=te.AliRtcStateSubscribeIdle,this.time=Date.now(),this._enabled=!0}setState(e){if(this.state===e)return;const i=this.state,s=this.time;this.state=e,this.time=Date.now(),this.emit("change",i,e,Math.floor((this.time-s)/1e3))}get currentState(){return this.state}getEnabled(){return this._enabled}setEnabled(e){this._enabled=e}}const Pi=class Pi extends rs{constructor(e){var u;const{userId:i,displayName:s,rtsManager:a,usersViewMap:n,reporter:o,webTrackingClient:c,signalingManager:h,localUserId:f,audioVolumeIndicationInterval:p}=e;super(i,s,a,p);l(this,"remoteCallid","");l(this,"remoteUserInfo");l(this,"localUserId");l(this,"lastPubId","");l(this,"stream");l(this,"screenStream");l(this,"viewMap");l(this,"audioTrack");l(this,"audioElement");l(this,"subscribed",!1);l(this,"mediaStream");l(this,"secondaryMediaStream");l(this,"prevSubConfig");l(this,"signalingManager");l(this,"reporter");l(this,"webTrackingClient");l(this,"wantSubAudio",!1);l(this,"wantSubVideo",!1);l(this,"wantSubScreen",!1);l(this,"defaultVideoStreamType",he.AliRtcVideoStreamTypeHigh);l(this,"audioMuted",!1);l(this,"audioSubState");l(this,"videoSubState");l(this,"videoLargeSubState",new Kt);l(this,"videoSmallSubState",new Kt);l(this,"screenSubState");l(this,"streamInfo");l(this,"streamUrl","");this.streamInfo=new di,this.remoteUserInfo=new ls(this),this.streamInfo.on(we.Remote,g=>{this.emit(we.Remote,g,this.userId)}),this.signalingManager=h,this.viewMap=(u=n[i])!=null?u:{cameraViews:[],screenViews:[]},n[i]=this.viewMap,this.reporter=o,this.webTrackingClient=c,this.localUserId=f,this.audioSubState=new Kt,this.audioSubState.on("change",(g,m,d)=>{this.emit("audioSubscribeStateChanged",this.uid,g,m,d)}),this.videoSubState=new Kt,this.videoSubState.on("change",(g,m,d)=>{this.emit("videoSubscribeStateChanged",this.uid,g,m,d)}),this.screenSubState=new Kt,this.screenSubState.on("change",(g,m,d)=>{this.emit("screenSubscribeStateChanged",this.uid,g,m,d)})}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e}setRemoteDefaultVideoStreamType(e){e!==this.defaultVideoStreamType&&(this.defaultVideoStreamType=e,this.updateSubscribe())}setAudioMuted(e){this.audioMuted=e,this.toggleAudio(!e)}getAudioMuted(){return this.audioMuted}get hasAudioTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasAudio)}get hasVideoTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideo)}get hasVideoLargeTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideoLarge)}get hasVideoSmallTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideoSmall)}get hasScreenTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasScreen)}get isAudioSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isAudioSubscribing)}get isVideoSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isVideoSubscribing)}get isVideoLargeSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isVideoLargeSubscribing)}get isVideoSmallSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isVideoSmallSubscribing)}get isScreenSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isScreenSubscribing)}get audioEnabled(){var e,i;return!!((i=(e=this.stream)==null?void 0:e.audioTrack)!=null&&i.enabled)}get videoEnabled(){var e,i;return!!((i=(e=this.stream)==null?void 0:e.videoTrack)!=null&&i.enabled)}get screenEnabled(){var e,i;return!!((i=(e=this.screenStream)==null?void 0:e.videoTrack)!=null&&i.enabled)}get getAudioTrack(){return this.audioTrack}get getCameraStream(){return this.stream}get getScreenStream(){return this.screenStream}setViewConfig(e,i){if(i!==W.AliRtcVideoTrackScreen&&i!==W.AliRtcVideoTrackCamera)throw new C(N.ERR_INVALID_ARGUMENTS,"track is not AliRtcVideoTrackScreen or AliRtcVideoTrackCamera");e?rr(e).forEach(a=>{a.setAttribute("playsinline",""),D.BrowserUtil.isMicroMessenger&&(a.setAttribute("x5-video-player-type","h5-page"),a.setAttribute("x5-playsinline",""),D.SystemUtil.isAndroid||D.SystemUtil.isIos&&a.setAttribute("x-webkit-airplay","allow")),i===W.AliRtcVideoTrackScreen?this.viewMap.screenViews.push(a):this.viewMap.cameraViews.push(a),this.play(a,i===W.AliRtcVideoTrackScreen)}):(this.stopPlayAll(i===W.AliRtcVideoTrackScreen),i===W.AliRtcVideoTrackScreen?this.viewMap.screenViews=[]:this.viewMap.cameraViews=[])}clear(e=!0){return v(this,null,function*(){var i;e&&this.doStopSubscribe(this.streamUrl),Pr(Pi.prototype,this,"clear").call(this),this.clearStream(),this.clearScreenStream(),(i=this.streamInfo)==null||i.removeAllListeners(we.Remote)})}updateRemoteUserDeviceStatus(e){var i;(i=this.streamInfo)==null||i.updateRemoteUserDeviceStatus(e)}updateRemoteTracks(e,i,s,a){return v(this,null,function*(){var o;return this.remoteCallid=e,this.streamUrl=i!=null?i:"",this.callid=e!=null?e:"",this.streamInfo||(this.streamInfo=new di),(o=this.streamInfo)==null?void 0:o.updateTracks(a)})}subscribe(e){return v(this,null,function*(){var h;e?this.reporter.reportSubscribeInvoked(this.userId,e.video,!1,e.screen,e.audio):this.reporter.reportSubscribeInvoked(this.userId);let i=e;if(!i){const{hasAudio:f,hasVideo:p,hasScreen:u}=(h=this.streamInfo)!=null?h:{};i={audio:this.wantSubAudio&&f,video:this.wantSubVideo&&p,screen:this.wantSubScreen&&u}}const{screen:s,audio:a,video:n,vMsid:o}=i,c=[];(n||a)&&c.push({audio:a,video:n,vMsid:o}),s&&c.push({screen:s}),c.length!==0&&(yield Promise.all(c.map(f=>this.subscribeProxy(f))))})}subscribeProxy(e){return v(this,null,function*(){var n,o;let i=new Date().getTime(),s="",a="";try{e.audio&&this.audioSubState.setState(te.AliRtcStateSubscribing),e.video&&(this.videoSubState.currentState===te.AliRtcStateSubscribeIdle||this.videoSubState.currentState===te.AliRtcStateNoSubscribe)&&this.videoSubState.setState(te.AliRtcStateSubscribing),e.screen&&this.screenSubState.setState(te.AliRtcStateSubscribing);const c=yield this.rtsManager.subscribe({remoteUser:this,options:e});this.streamInfo.updateRemoteTrackSubState(e),s=c;const{stream:h}=c;if(e.audio){const p=h.audioTrack;p&&(this.audioTrack=p,(n=h.mediaStream)==null||n.removeTrack(p),this.playAudio(),this.audioVolumeIndicationInterval&&this.audioLevelMonitor.start(p,this.audioVolumeIndicationInterval)),this.audioSubState.setState(te.AliRtcStateSubscribed),this.audioSubState.getEnabled()||this.toggleAudio(!1)}e.video&&(e.vMsid===k.VideoSmall?this.videoSmallSubState.setState(te.AliRtcStateSubscribed):this.videoLargeSubState.setState(te.AliRtcStateSubscribed),this.videoSubState.setState(te.AliRtcStateSubscribed),this.videoSubState.getEnabled()||this.toggleVideo(!1),this.updateStream(h,this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing)),e.screen&&(this.screenSubState.setState(te.AliRtcStateSubscribed),this.videoSubState.getEnabled()||this.toggleScreen(!1),this.updateScreenStream(h));const f=new Date().getTime()-i;this.webTrackingClient.reportPull(c.callid,c.remoteCallid,c.isVideoLargeSubscribing,c.isVideoSmallSubscribing,c.isScreenSubscribing,c.isAudioSubscribing,0,f,a,s,this.streamUrl,i)}catch(c){const h=new Date().getTime()-i;this.webTrackingClient.reportPull("","",!1,!1,!1,!1,c.code,h,a,s,(o=this.streamUrl)!=null?o:"",i),c&&(c.message=`user(${this.uid}) subscribe error, ${(c==null?void 0:c.message)||""}`);let f=N.ERR_INNER;e.audio&&(f=N.ERR_SDK_SUBSCRIBE_AUDIO_STRAM_FAILED),e.video&&(e.vMsid===k.VideoSmall?f=N.ERR_SDK_SUBSCRIBE_DUAL_STRAM_FAILED:f=N.ERR_SDK_SUBSCRIBE_VIDEO_STRAM_FAILED),e.screen&&(f=N.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED);const p=C.fromError(c,f);throw this.emit("remoteSubscribeError",p),p}})}subscribeDeleteTracks(e){return v(this,null,function*(){const{audio:i,video:s,screen:a,vMsid:n}=e,o=[];(i||s)&&o.push({audio:i,video:s,vMsid:n}),a&&o.push({screen:a}),o.length!==0&&(yield Promise.all(o.map(c=>this.subscribeDeleteProxy(c))))})}subscribeDeleteProxy(e){return v(this,null,function*(){try{const i=yield this.rtsManager.subscibeDelete({remoteUser:this,options:e}),{stream:s}=i!=null?i:{},a={};e.audio===!0&&(a.audio=!1,this.audioSubState.setState(te.AliRtcStateNoSubscribe)),e.video===!0&&(a.video=!1,e.vMsid===k.VideoSmall?(this.videoSmallSubState.setState(te.AliRtcStateNoSubscribe),(this.videoLargeSubState.currentState===te.AliRtcStateNoSubscribe||this.videoLargeSubState.currentState===te.AliRtcStateSubscribeIdle)&&this.videoSubState.setState(te.AliRtcStateNoSubscribe)):(this.videoLargeSubState.setState(te.AliRtcStateNoSubscribe),(this.videoSmallSubState.currentState===te.AliRtcStateNoSubscribe||this.videoSmallSubState.currentState===te.AliRtcStateSubscribeIdle)&&this.videoSubState.setState(te.AliRtcStateNoSubscribe))),e.screen===!0&&(a.screen=!1,this.screenSubState.setState(te.AliRtcStateNoSubscribe));const{callid:n,remoteCallid:o}=this,c={callid:n,remoteCallid:o,remoteStream:s};return e.audio&&(this.audioLevelMonitor.stop(),this.stopPlayAudio(),this.audioTrack=void 0),this.streamInfo.updateRemoteTrackSubState({audio:e.audio===!0?!1:void 0,video:e.video===!0?!1:void 0,screen:e.screen===!0?!1:void 0,vMsid:e.vMsid}),c}catch(i){throw C.fromError(i,N.ERR_INNER,"subscribe delete failed")}})}restore(){this.clearStream(),this.clearScreenStream(),this.audioTrack=void 0,this.streamInfo.updateRemoteTrackSubState({audio:!1,video:!1,screen:!1})}resumeAudio(){return v(this,null,function*(){var e;return(e=this.audioElement)==null?void 0:e.play()})}resumeVideo(e){return v(this,null,function*(){if(!e||e===W.AliRtcVideoTrackCamera||e===W.AliRtcVideoTrackBoth)return this.playAll();if(!e||e===W.AliRtcVideoTrackScreen||e===W.AliRtcVideoTrackBoth)return this.playAll(!0)})}resumePlay(){this.playAudio(),this.playAll(),this.playAll(!0)}stopSubscribe(e){return v(this,null,function*(){var p,u,g,m,d,S,b;const{isAudioSubscribing:i=!1,isVideoSubscribing:s=!1,isScreenSubscribing:a=!1}=this,n=i&&!((p=e==null?void 0:e.audio)==null||p),o=s&&!((u=e==null?void 0:e.video)==null||u),c=!1,h=a&&!((g=e==null?void 0:e.screen)==null||g);e?this.reporter.reportSubscribeInvoked(this.userId,o,c,h,n):this.reporter.reportUnsubscribeInvoked(this.userId);let f=new Date().getTime();try{let w;e?w=yield this.subscribeDeleteTracks(e):w=yield this.doStopSubscribe(this.streamUrl),e?this.reporter.reportSubscribe((m=w==null?void 0:w.callid)!=null?m:"",this.userId,o,c,h,n,0,"",new Date().getTime()-f,(d=this.localUserId)!=null?d:""):this.reporter.reportUnsubscribe((S=w==null?void 0:w.callid)!=null?S:"",this.userId,new Date().getTime()-f,0,"")}catch(w){throw e?this.reporter.reportSubscribe("",this.userId,o,c,h,n,w.code,"",new Date().getTime()-f,(b=this.localUserId)!=null?b:""):this.reporter.reportUnsubscribe("",this.userId,new Date().getTime()-f,0,""),w}})}doStopSubscribe(e){return v(this,null,function*(){var a,n,o,c;const{callid:i,remoteCallid:s}=this;if((this.isAudioSubscribing||this.isVideoSubscribing||this.isScreenSubscribing)&&e)try{return yield this.rtsManager.subscibeStop(e),this.restore(),{callid:i,remoteCallid:s,remoteStream:this.stream}}catch(h){if(((c=(o=(n=(a=h==null?void 0:h.extraInfo)==null?void 0:a.parsedData)==null?void 0:n.streams)==null?void 0:o[0])==null?void 0:c.res_code)!==404)throw C.fromError(h,N.ERR_INNER,"subscribe stop failed")}})}updateStream(e,i=!1){return v(this,null,function*(){this.stream&&this.stream.videoTrack&&e.mediaStream&&i&&(yield new Promise(s=>{let a,n;if(e.mediaStream){n=document.createElement("video");const o=()=>{E.event(`uid: ${this.userId} new mediaStream canplay`),n&&n.removeEventListener("canplaythrough",o,!1),n=void 0,clearTimeout(a),s(!0)};n.addEventListener("canplaythrough",o,!1),(n._playPromise||Promise.resolve()).then(()=>{n&&e.mediaStream&&(n.srcObject=e.mediaStream)})}else s(!0);a=window.setTimeout(()=>{E.event(`uid: ${this.userId} new mediaStream timeout`),n=void 0,s(!0)},3e3)}),this.updateSubscribe()),this.stream=e,this.playAll(),!this.subscribed&&e&&(this.subscribed=!0),e.hasAudio&&this.isAudioSubscribing&&e.enableAudio(),e.hasVideo&&this.isVideoSubscribing&&e.enableVideo()})}updateScreenStream(e){this.screenStream=e,this.playAll(!0),!this.subscribed&&e&&(this.subscribed=!0),e.hasVideo&&this.isScreenSubscribing&&e.enableVideo()}clearStream(){var e;(e=this.stream)==null||e.stop(),this.stream=void 0}clearScreenStream(){var e;(e=this.screenStream)==null||e.stop(),this.screenStream=void 0}updateSubscribe(){var s,a,n,o,c,h,f,p;const e={},i={};return this.wantSubAudio&&!this.isAudioSubscribing&&((s=this.streamInfo)!=null&&s.hasAudio)?e.audio=!0:(!this.wantSubAudio||!((a=this.streamInfo)!=null&&a.hasAudio))&&this.isAudioSubscribing&&(i.audio=!0),this.wantSubVideo&&((n=this.streamInfo)!=null&&n.hasVideo)?(this.defaultVideoStreamType===he.AliRtcVideoStreamTypeLow&&!this.isVideoSmallSubscribing&&((o=this.streamInfo)!=null&&o.hasVideoSmall)?(e.video=!0,e.vMsid=k.VideoSmall):!this.isVideoLargeSubscribing&&((c=this.streamInfo)!=null&&c.hasVideoLarge)&&!(this.defaultVideoStreamType===he.AliRtcVideoStreamTypeLow&&this.isVideoSmallSubscribing)&&(e.video=!0,e.vMsid=k.VideoLarge),this.defaultVideoStreamType===he.AliRtcVideoStreamTypeLow&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall?(i.video=!0,i.vMsid=k.VideoLarge):this.defaultVideoStreamType===he.AliRtcVideoStreamTypeHigh&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&(i.video=!0,i.vMsid=k.VideoSmall)):(!this.wantSubVideo||!((h=this.streamInfo)!=null&&h.hasVideo))&&this.isVideoSubscribing&&(i.video=!0,i.vMsid=this.streamInfo.isVideoSmallSubscribing?k.VideoSmall:k.VideoLarge),this.wantSubScreen&&!this.isScreenSubscribing&&((f=this.streamInfo)!=null&&f.hasScreen)?e.screen=!0:(!this.wantSubScreen||!((p=this.streamInfo)!=null&&p.hasScreen))&&this.isScreenSubscribing&&(i.screen=!0),(e.audio||e.video||e.screen)&&this.subscribe(e),i.audio&&i.video&&i.screen?this.stopSubscribe():(i.audio||i.video||i.screen)&&this.subscribeDeleteTracks(i),{addOption:e,deleteOption:i}}handleAutoPlayFailed(){this.emit("remoteAudioAutoPlayFail",this.uid);const e=()=>{this.resumeAudio().then(()=>{document.removeEventListener("click",e,!1),document.removeEventListener("touchstart",e,!1)})};document.addEventListener("click",e,!1),document.addEventListener("touchstart",e,!1)}handleVideoPlayFailded(e,i){this.emit("remoteVideoAutoPlayFail",this.uid,i);const s=()=>{var n;const a=(n=i===W.AliRtcVideoTrackScreen?this.screenStream:this.stream)==null?void 0:n.mediaStream;e.srcObject===a&&this.play(e,i===W.AliRtcVideoTrackScreen),document.removeEventListener("click",s,!1),document.removeEventListener("touchstart",s,!1)};document.addEventListener("click",s,!1),document.addEventListener("touchstart",s,!1)}playAudio(){return v(this,null,function*(){var i,s;if(!this.audioTrack)return;if(this.toggleAudio(!this.audioMuted),this.audioElement||(this.audioElement=document.createElement("audio")),((s=(i=this.audioElement.srcObject)==null?void 0:i.getAudioTracks())==null?void 0:s[0])!==this.audioTrack){let a=this.audioElement.srcObject;a?a.getAudioTracks().forEach(n=>{a.removeTrack(n)}):(a=new MediaStream,this.audioElement.srcObject=a),a.addTrack(this.audioTrack)}this.audioElement.play().catch(()=>{this.handleAutoPlayFailed()});const e=this.audioElement;this.audioElement.addEventListener("playing",function a(){e.removeEventListener("playing",a),D.SystemUtil.isIos&&parseInt(D.SystemUtil.systemVersion)<=14&&(e.muted||(e.pause(),e.play()))})})}stopPlayAudio(){this.audioElement&&(this.audioElement.pause(),this.audioElement.srcObject=null)}playAll(e=!1){e?(this.viewMap.screenViews||[]).forEach(i=>{this.play(i,e)}):(this.viewMap.cameraViews||[]).forEach(i=>{this.play(i,e)})}play(e,i=!1){const s=i?this.screenStream:this.stream;!e||!s||!s.mediaStream||cs(e,s.mediaStream).catch(a=>{a.code===20||a.name==="AbortError"||this.handleVideoPlayFailded(e,i?W.AliRtcVideoTrackScreen:W.AliRtcVideoTrackCamera)})}stopPlayAll(e=!1){e?this.viewMap.screenViews.forEach(i=>{nt(i)}):this.viewMap.cameraViews.forEach(i=>{nt(i)})}toggleAudio(e=!0){this.audioSubState.setEnabled(e),this.audioTrack&&(this.audioTrack.enabled=e)}toggleVideo(e=!0){this.videoSubState.setEnabled(e),this.stream&&(e?this.stream.enableVideo():this.stream.disableVideo())}toggleScreen(e=!0){this.screenSubState.setEnabled(e),this.screenStream&&(e?this.screenStream.enableVideo():this.screenStream.disableVideo())}getStats(){return v(this,null,function*(){var s,a;const e=[];if(this.isAudioSubscribing){const n=yield this.rtsManager.getSubscribeAudioStats(this.streamUrl);n&&e.push({uid:this.uid,track:kt.AliRtcAudioTrackMic,stats:n})}const i=[];if((s=this.streamInfo)!=null&&s.isVideoLargeSubscribing){const n=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,k.VideoLarge);n&&i.push({uid:this.uid,track:W.AliRtcVideoTrackCamera,streamType:he.AliRtcVideoStreamTypeHigh,stats:n})}if((a=this.streamInfo)!=null&&a.isVideoSmallSubscribing){const n=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,k.VideoSmall);n&&i.push({uid:this.uid,track:W.AliRtcVideoTrackCamera,streamType:he.AliRtcVideoStreamTypeLow,stats:n})}if(this.isScreenSubscribing){const n=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,k.Screen);n&&i.push({uid:this.uid,track:W.AliRtcVideoTrackScreen,stats:n})}return{audio:e,video:i}})}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.audioTrack&&this.audioLevelMonitor.start(this.audioTrack,e),this.audioVolumeIndicationInterval=e)}};l(Pi,"logName","RemoteUser");let ae=Pi;le([y()],ae.prototype,"clear",1),le([y()],ae.prototype,"updateRemoteUserDeviceStatus",1),le([y()],ae.prototype,"updateRemoteTracks",1),le([y(I)],ae.prototype,"subscribe",1),le([y()],ae.prototype,"subscribeProxy",1),le([y(I)],ae.prototype,"subscribeDeleteProxy",1),le([y()],ae.prototype,"restore",1),le([y(I)],ae.prototype,"stopSubscribe",1),le([y(I)],ae.prototype,"doStopSubscribe",1),le([y()],ae.prototype,"clearStream",1),le([y()],ae.prototype,"clearScreenStream",1),le([y()],ae.prototype,"updateSubscribe",1),le([y()],ae.prototype,"playAudio",1),le([y()],ae.prototype,"stopPlayAudio",1),le([y(I)],ae.prototype,"playAll",1),le([y()],ae.prototype,"play",1),le([y()],ae.prototype,"stopPlayAll",1);var ot=(t=>(t[t.AliRtcPluginErrorCodeSuccess=0]="AliRtcPluginErrorCodeSuccess",t[t.AliRtcPluginErrorCodeFailed=-1]="AliRtcPluginErrorCodeFailed",t[t.AliRtcPluginErrorNoFindPlugin=-2]="AliRtcPluginErrorNoFindPlugin",t[t.AliRtcPluginErrorParameterError=-3]="AliRtcPluginErrorParameterError",t[t.AliRtcPluginErrorLoadError=-4]="AliRtcPluginErrorLoadError",t[t.AliRtcPluginErrorCreateError=-5]="AliRtcPluginErrorCreateError",t[t.AliRtcPluginErrorInitError=-6]="AliRtcPluginErrorInitError",t[t.AliRtcPluginErrorInitTokenError=-7]="AliRtcPluginErrorInitTokenError",t))(ot||{});class En extends Q{constructor(){super(...arguments);l(this,"plugins",new Map)}add(e,i){if(this.plugins.has(e.name))throw new C(ot.AliRtcPluginErrorCreateError,`Plugin ${e.name} already exists`);this.plugins.set(e.name,e),i&&e.setOptions(i),this.emit("added",e),e.on("enabled",()=>this.emit("added",e)),e.on("disabled",()=>this.emit("removed",e)),e.on("updated",()=>this.emit("updated",e))}remove(e){const i=this.plugins.get(e);if(!i)throw new C(ot.AliRtcPluginErrorNoFindPlugin,`Plugin ${e} not founded`);this.plugins.delete(e),i.removeAllListeners(),this.emit("removed",i)}get(e){return this.plugins.get(e)}has(e){return!!this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}}var An=Object.defineProperty,Tn=Object.getOwnPropertyDescriptor,_e=(t,r,e,i)=>{for(var s=i>1?void 0:i?Tn(r,e):r,a=t.length-1,n;a>=0;a--)(n=t[a])&&(s=(i?n(r,e,s):n(s))||s);return i&&s&&An(r,e,s),s};const pi=([t])=>{const{remoteUser:r,options:e}=t;return[`user(${r.userId})`,e]},me=(Ce=class extends Q{constructor(e){super();l(this,"rts");l(this,"encodedInsertableStreams",!0);l(this,"audioRedEnabled",!1);l(this,"localStreamManager");l(this,"connecting",!1);l(this,"connected",!1);l(this,"connectionResolve");l(this,"connectingPromise");l(this,"dcResolve");l(this,"dcConnectingPromise");l(this,"_publishingTracks",[]);this.rts=V.AliRTS.createClient(),this.localStreamManager=e,this.rts.on("connectStatusChange",i=>{var s,a,n,o;if(E.event(`[${Ce.logName}]`,"rts connectStatusChange to:",i.status),i.status===V.EConnectStatus.CONNECT_STATUS_DISCONNECTED)this.emit("disconnected"),this.setConnected(!1);else if(i.status===V.EConnectStatus.CONNECT_STATUS_RECONNECTING)this.emit("reconnecting"),this.setConnected(!1);else if(i.status===V.EConnectStatus.CONNECT_STATUS_CONNECTED){this.setConnected(!0);const c=(o=(n=(a=(s=this.rts.commonController)==null?void 0:s.peerCore)==null?void 0:a.getSignal())==null?void 0:n.getDatachannelCore())==null?void 0:o.readyState;E.event(Ce.logName,"dcReadyState:",c),c==="open"&&this.dcResolve&&this.dcResolve(!0),this.emit("connected")}}),this.rts.on("datachannelStatusChange",i=>{E.event(`[${Ce.logName}]`,"rts datachannelStatusChange to:",i.status),i.status===V.EDatachannelStatus.DATACHANNEL_STATUS_OPEN?this.dcResolve&&this.dcResolve(!0):i.status===V.EDatachannelStatus.DATACHANNEL_STATUS_CLOSE&&(this.dcConnectingPromise=new Promise(s=>{this.dcResolve=s}),console.warn("DC DisConnected"))}),this.rts.on("receivedSEI",i=>{this.emit("seimessage",i.url,i.sei.payloadType,i.sei.data)})}setEncodedInsertableStreams(e){this.encodedInsertableStreams=e}setAudioRedEnabled(e){var i;if(e!==this.audioRedEnabled){try{const a=[...((i=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:i.codecs)||[]];if(a.length>0){if(e){const n=a.findIndex(c=>c.mimeType==="audio/red"),o=a.findIndex(c=>c.mimeType==="audio/opus");if(n>-1&&o>-1&&n>o){const c=a[o];a[o]=a[n],a[n]=c}}this.rts.setSenderCodecPreferences({audio:a}),this.rts.setReceiverCodecPreferences({audio:a})}}catch(s){}this.audioRedEnabled=e}}destroy(){this.rts.unpublish()}startConnect(){this.connecting=!0,this.connectingPromise=new Promise(e=>{this.connectionResolve=e}),this.dcConnectingPromise=new Promise(e=>{this.dcResolve=e})}setConnected(e){var i;this.connected=e,this.connecting=!1,(i=this.connectionResolve)==null||i.call(this,!0),e||(this.dcConnectingPromise=new Promise(s=>{this.dcResolve=s}))}get isConnecting(){return this.connecting}get isConnected(){return this.connected}get publishingTracks(){return this._publishingTracks}getPubMsid(e,i){const{aMsid:s,vMsid:a}=i!=null?i:{},n={};return e.hasAudio&&(n.aMsid=[s!=null?s:k.Audio]),e.hasScreen&&(n.vMsid=[k.Screen]),e.hasVideo&&(n.vMsid=[a!=null?a:i!=null&&i.isScreen?k.Screen:k.VideoLarge]),n}updatePublishingTracks(e){e&&(this._publishingTracks=e.map(({msid:i,from:s,ssrc:a,codec:n,type:o,trackId:c})=>({msid:i,from:s,type:o,ssrc:`${a}`,codec:n!=null?n:"",trackId:c})))}httpPublish(e,i=!1){return v(this,null,function*(){const{publishStream:s,videoSmallStream:a,screenStream:n,vMsid:o}=yield this.localStreamManager.createHTTPPublishStream();if(!s)return"";const c=this.getPubMsid(s,{vMsid:o});c.retryTimes=0,this.encodedInsertableStreams&&(c.encodedInsertableStreams=!0);let h=!s.hasVideo,f=o;try{this.startConnect();const p=yield this.rts.publish(e,s,c);return this.setConnected(!0),this._publishingTracks=this.rts.getPublishTrackInfoList(),a&&(yield this.publishAdd(e,a,{vMsid:k.VideoSmall},i),h=!1,f=k.VideoSmall),n&&(yield this.publishAdd(e,n,{vMsid:k.Screen},i),h=!1,f=k.Screen),yield this.waitPublishSender(e,h,f),p}catch(p){throw this.setConnected(!1),p}})}waitPublishSender(e,i=!1,s){return v(this,null,function*(){const a=(n,o)=>{let c=0;const h=()=>(i?this.rts.getPublishAudioStats(e,s):this.rts.getPublishVideoStats(e,s)).then(p=>!(p.bytesSent>0)&&c<n?(c++,new Promise(g=>setTimeout(()=>g(h()),o))):Promise.resolve());return h()};return Promise.race([at(1e3),a(5,100)]).catch(()=>{})})}checkSubscribeStats(e,i){return v(this,null,function*(){const s=(a,n)=>{let o=0;const c=()=>{const h=this.rts.getSubscribeVideoStats(e,i);return this.rts.getSubscribeAudioStats(e).then(p=>{var u;E.event(`[${Ce.logName}]`,"AudioLevel",((u=p.audioLevel)!=null?u:0).toFixed(2))}),h.then(p=>(E.event(`[${Ce.logName}]`,"VideoFramesDecoded",p.framesDecoded),!(p.framesDecoded>0)&&o<a?(o++,new Promise(g=>setTimeout(()=>g(c()),n))):Promise.resolve()))};return c()};return Promise.race([at(1200),s(10,100)]).catch(()=>{})})}getPublishVideoStats(e,i){return v(this,null,function*(){return yield this.rts.getPublishVideoStats(e,i)})}getPublishAudioStats(e,i){return v(this,null,function*(){return yield this.rts.getPublishAudioStats(e,i)})}publishAdd(e,i,s,a=!1,n=0,o=!1){return v(this,null,function*(){try{yield this.dcConnectingPromise;const c=yield this.rts.publishAdd([q({url:e,stream:i,updateSourceStream:!1},this.getPubMsid(i,s))]);if(c){const[h]=c;return this.updatePublishingTracks(h.trackInfoList),o&&(yield this.waitPublishSender(e,!i.hasVideo,i.hasVideo?s==null?void 0:s.vMsid:s==null?void 0:s.aMsid)),h.traceId||""}}catch(c){if(c.errorCode===15006&&n<3)return yield this.publishAdd(e,i,s,a,n+1);throw c}return""})}publishDelete(e,i){return v(this,null,function*(){var f,p,u,g,m,d,S,b;yield this.dcConnectingPromise;const s=(p=(f=this.publishingTracks)==null?void 0:f.find(({msid:w})=>w===k.Audio))==null?void 0:p.msid,a=(g=(u=this.publishingTracks)==null?void 0:u.find(({msid:w})=>w===k.VideoLarge))==null?void 0:g.msid,n=(d=(m=this.publishingTracks)==null?void 0:m.find(({msid:w})=>w===k.Screen))==null?void 0:d.msid,o=[];i.screen&&n?o.push(n):i.video&&o.push(i.vMsid||a);const c=[];i.audio&&s&&c.push(s),E.event(Ce.logName,"publishDelete",{streamUrl:e,aMsid:c,vMsid:o});const[h]=(yield this.rts.publishDeleteTracks([{url:e,aMsid:c,vMsid:o}]))||[];return E.event(Ce.logName,"publishDelete",{result:h}),h&&this.updatePublishingTracks(h.trackInfoList),((b=(S=h==null?void 0:h.trackInfoList)==null?void 0:S[0])==null?void 0:b.trackId)||""})}publishReplace(e,i,s){return v(this,null,function*(){var h,f;yield this.dcConnectingPromise;const{vMsid:a,aMsid:n}=s!=null?s:{},o=yield this.rts.publishReplaceTracks([{url:e,stream:i,updateSourceStream:!1,vMsid:a,aMsid:n}]),[c]=o;return this.updatePublishingTracks(c.trackInfoList),((f=(h=c==null?void 0:c.trackInfoList)==null?void 0:h[0])==null?void 0:f.trackId)||""})}publishStop(e){return v(this,null,function*(){return yield this.rts.publishStop([{url:e}]),this._publishingTracks=[],""})}unpublish(){return v(this,null,function*(){yield this.rts.unpublish(),this.connecting=!1,this.connected=!1})}getSubConfig(e,i){let s=i!=null?i:{};i||(s={audio:!0,video:!0,screen:!0});const a={};return s.audio&&(a.aMsid=[(e==null?void 0:e.getAudioInfo().msid)||k.Audio]),s.video?s.vMsid?a.vMsid=[s.vMsid]:e!=null&&e.hasVideoLarge?a.vMsid=[(e==null?void 0:e.getVideoLargeInfo().msid)||k.VideoLarge]:e!=null&&e.hasVideoSmall?a.vMsid=[(e==null?void 0:e.getVideoSmallInfo().msid)||k.VideoSmall]:a.vMsid=[k.VideoLarge]:s.screen&&e!=null&&e.hasScreen&&(a.vMsid=[(e==null?void 0:e.getScreenInfo().msid)||k.Screen]),a}httpSubscribe(e){return v(this,null,function*(){const{remoteUser:i,options:s}=e;let a=i.streamUrl;s.video||s.screen?s!=null&&s.audio||(a+="@subaudio=no"):a+="@subvideo=no";const n=this.getSubConfig(i.streamInfo,s);n.retryTimes=0,this.encodedInsertableStreams&&(n.encodedInsertableStreams=!0);try{this.startConnect();const o=yield this.rts.subscribe(a,n);return this.setConnected(!0),{traceId:o.traceId,stream:o}}catch(o){throw this.setConnected(!1),o}})}subscribeAdd(e){return v(this,null,function*(){var n,o,c,h,f;yield this.dcConnectingPromise;const{remoteUser:i,options:s}=e,a=Lt(q({url:i.streamUrl,subAudio:!!s.audio,subVideo:!!(s.screen||s.video)},this.getSubConfig(i.streamInfo,s)),{targetStream:s.screen?i.getScreenStream:i.getCameraStream});try{const p=yield this.rts.subscribeAdd([a]);return a.subVideo&&this.checkSubscribeStats(i.streamUrl,(n=a.vMsid)==null?void 0:n[0]).then(()=>{var u;E.info(Ce.logName,"checkSubscribeStats",{streamUrl:i.streamUrl,msid:(u=a.vMsid)==null?void 0:u[0]})}),p[0]}catch(p){if(((f=(h=(c=(o=p==null?void 0:p.extraInfo)==null?void 0:o.parsedData)==null?void 0:c.streams)==null?void 0:h[0])==null?void 0:f.res_code)===508)return this.emit("subscribeexceeds"),null;throw C.fromError(p)}return null})}subscibeDelete(e){return v(this,null,function*(){var n,o,c,h;yield this.dcConnectingPromise;const{remoteUser:i,options:s}=e,a=Lt(q({url:i.streamUrl,subAudio:!!s.audio,subVideo:!!(s.screen||s.video)},this.getSubConfig(i.streamInfo,s)),{targetStream:s.screen?i.getScreenStream:i.getCameraStream});try{return(yield this.rts.subscribeDeleteTracks([a]))[0]}catch(f){if(((h=(c=(o=(n=f==null?void 0:f.extraInfo)==null?void 0:n.parsedData)==null?void 0:o.streams)==null?void 0:c[0])==null?void 0:h.res_code)===404)return;throw f}})}subscibeStop(e){return v(this,null,function*(){var i,s,a,n;try{yield this.rts.subscribeStop([{url:e}])}catch(o){if(((n=(a=(s=(i=o==null?void 0:o.extraInfo)==null?void 0:i.parsedData)==null?void 0:s.streams)==null?void 0:a[0])==null?void 0:n.res_code)===404)return;throw o}})}publish(e,i=!1){return v(this,null,function*(){let s="";if(this.connecting&&(yield this.connectingPromise),this.connected){yield this.dcConnectingPromise;let a=!1,n;const{audio:o,video:c,videoSmall:h,screen:f}=this.localStreamManager.publishStreams;o&&(s=yield this.publishAdd(e,o,{aMsid:k.Audio},i),a=!0,n=k.Audio,yield at(100)),c&&(s=yield this.publishAdd(e,c,{vMsid:k.VideoLarge},i),a=!1,n=k.VideoLarge,yield at(100)),h&&(s=yield this.publishAdd(e,h,{vMsid:k.VideoSmall},i),a=!1,n=k.VideoSmall,yield at(100)),f&&(s=yield this.publishAdd(e,f,{isScreen:!0,vMsid:k.Screen},i),a=!1,n=k.Screen),n&&(yield this.waitPublishSender(e,a,n))}else s=yield this.httpPublish(e,i);return s})}subscribe(e){return v(this,null,function*(){const{options:i}=e;if(i.video&&i.screen)throw new C(N.ERR_INNER,"subscribe error, video and screen cannot be subscribed at the same time");this.connecting&&(yield this.connectingPromise);let s;return this.connected?(yield this.dcConnectingPromise,s=yield this.subscribeAdd(e)):s=yield this.httpSubscribe(e),s})}getSubscribeVideoStats(e,i){return v(this,null,function*(){return yield this.rts.getSubscribeVideoStats(e,i)})}getSubscribeAudioStats(e,i){return v(this,null,function*(){return yield this.rts.getSubscribeAudioStats(e,i)})}sendSEI(e,i,s,a){return v(this,null,function*(){return this.rts.sendSEI({url:e,vMsid:k.VideoLarge,data:i,repeatCount:s,payloadType:a})})}},l(Ce,"logName","RtsManager"),Ce);_e([y()],me.prototype,"updatePublishingTracks",1),_e([y(I,I)],me.prototype,"httpPublish",1),_e([y(I,I)],me.prototype,"waitPublishSender",1),_e([y(([t,r,e])=>[t,JSON.stringify(e)],I)],me.prototype,"publishAdd",1),_e([y(I,I)],me.prototype,"publishDelete",1),_e([y(([t,r,e])=>[t,JSON.stringify(e)])],me.prototype,"publishReplace",1),_e([y(I)],me.prototype,"publishStop",1),_e([y()],me.prototype,"unpublish",1),_e([y(pi,({traceId:t})=>t)],me.prototype,"httpSubscribe",1),_e([y(pi,({traceId:t})=>t)],me.prototype,"subscribeAdd",1),_e([y(pi)],me.prototype,"subscibeDelete",1),_e([y(I)],me.prototype,"subscibeStop",1),_e([y(I)],me.prototype,"publish",1),_e([y(pi)],me.prototype,"subscribe",1),_e([y()],me.prototype,"sendSEI",1);let Pn=me;class sr{constructor(){l(this,"profile");l(this,"profileMap",new Map);l(this,"audioProfile");l(this,"contentHint")}updateProfile(r,e){e&&this.profileMap.set(r,e),this.profile=r}get videoProfile(){return this.profile}updateAudioProfile(r){this.audioProfile=r}setContentHint(r,e){e&&(this.contentHint=e),this.contentHint&&r&&(r.contentHint=this.contentHint)}setVideoProfile(r,e,i=!1){return v(this,null,function*(){if(!this.profile)return;const s=this.profileMap.get(this.profile)||(e==null?void 0:e.VideoProfileMap.get(this.profile));if(s){if(!i&&r&&r.applyConstraints)try{yield r.applyConstraints(s)}catch(a){}e&&(e==null||e.VideoProfileMap.set(this.profile,s),yield e.setVideoProfile(this.profile))}})}}class ar extends Q{constructor(e){super();l(this,"type");l(this,"originVideoTrack");l(this,"videoSource");l(this,"_videoMuted",!1);l(this,"originAudioTrack");l(this,"audioSource");l(this,"_audioMuted",!1);l(this,"_targetVideoTrack");l(this,"_targetDualVideoTrack");l(this,"_targetAudioTrack");l(this,"_publishVideoStream");l(this,"_publishDualVideoStream");l(this,"_publishAudioStream");l(this,"_previewStream");l(this,"plugins",[]);l(this,"_profileManager");l(this,"cameraVideoConstraints");l(this,"micAudioConstraints");l(this,"onVideoTrackEnded",()=>{this.emit("videotrackended")});l(this,"onAudioTrackEnded",()=>{this.emit("audiotrackended")});this.type=e}get profileManager(){return this._profileManager}get audioProfile(){var e;return(e=this.profileManager)==null?void 0:e.audioProfile}updateSource(e,i,s){return v(this,null,function*(){var o,c,h,f,p,u;const{videoTrack:a,audioTrack:n}=e;a&&((o=this.originVideoTrack)==null||o.removeEventListener("ended",this.onVideoTrackEnded)),n&&((c=this.originAudioTrack)==null||c.removeEventListener("ended",this.onAudioTrackEnded)),this.type===ce.AliRtcSdkStreamTypeScreen?this.stop():(a&&((h=this.originVideoTrack)==null||h.stop()),n&&((f=this.originAudioTrack)==null||f.stop())),a&&(this.originVideoTrack=a,(p=this.originVideoTrack)==null||p.addEventListener("ended",this.onVideoTrackEnded),this.videoSource=i||At.Camera,this.updateVideoTrack(a)),n&&(this.originAudioTrack=n,(u=this.originAudioTrack)==null||u.addEventListener("ended",this.onAudioTrackEnded),this.audioSource=s||si.Microphone,this.updateAudioTrack(n))})}get currentProfile(){var e;return(e=this.profileManager)==null?void 0:e.profile}get currentVideoTrack(){return this._targetVideoTrack}get currentDualVideoTrack(){return this._targetDualVideoTrack}get publishVideoStream(){return this._publishVideoStream}get publishDualVideoStream(){return this._publishDualVideoStream}get currentAudioTrack(){return this._targetAudioTrack}get publishAudioStream(){return this._publishAudioStream}get previewStream(){return this._previewStream}updateVideoTrack(e,i=!1){return v(this,null,function*(){(this._targetVideoTrack!==e||i)&&(this._targetVideoTrack=e)})}updateDualVideoTrack(e,i=!1){return v(this,null,function*(){(this._targetDualVideoTrack!==e||i)&&(this._targetDualVideoTrack=e)})}updateAudioTrack(e,i=!1){return v(this,null,function*(){(this._targetAudioTrack!==e||i)&&(this._targetAudioTrack=e)})}setAudioMuted(e){var i,s;this._audioMuted=e,e?(i=this.publishAudioStream)==null||i.disableAudio():(s=this.publishAudioStream)==null||s.enableAudio()}get isAudioMuted(){return this._audioMuted}setVideoMuted(e){var i,s;this._videoMuted=e,e?(i=this.publishVideoStream)==null||i.disableVideo():(s=this.publishVideoStream)==null||s.enableVideo()}get isVideoMuted(){return this._videoMuted}process(e){return v(this,null,function*(){var i,s,a,n,o,c,h,f,p,u,g,m;this._targetAudioTrack=this.originAudioTrack,this._targetVideoTrack=this.originVideoTrack;for(const d of this.plugins)try{yield d.execute(this,e)}catch(S){console.error(`error in plugin-${d.name}, error: ${S}`)}this._targetVideoTrack?((s=(i=this._publishVideoStream)==null?void 0:i.videoTrack)==null?void 0:s.id)!==this._targetVideoTrack.id&&(this._publishVideoStream=yield Wt(this._targetVideoTrack),this.setVideoMuted(this._videoMuted),(a=this.profileManager)==null||a.setVideoProfile(this.originVideoTrack,this._publishVideoStream,!0),(n=this.profileManager)==null||n.setContentHint(this._targetVideoTrack),this.previewStream?(o=this.previewStream)==null||o.mergeStream(this._publishVideoStream):this._previewStream=yield Wt(this._targetVideoTrack)):(this._publishVideoStream=void 0,(c=this.previewStream)==null||c.deleteTracks({video:!0})),this._targetDualVideoTrack?((f=(h=this._publishDualVideoStream)==null?void 0:h.videoTrack)==null?void 0:f.id)!==this._targetDualVideoTrack.id&&(this._publishDualVideoStream=yield Wt(this._targetDualVideoTrack),this._videoMuted?this._publishDualVideoStream.disableVideo():this._publishDualVideoStream.enableVideo()):this._publishDualVideoStream=void 0,this._targetAudioTrack?((u=(p=this._publishAudioStream)==null?void 0:p.audioTrack)==null?void 0:u.id)!==this._targetAudioTrack.id&&(this._publishAudioStream=yield Wt(this._targetAudioTrack),this.setAudioMuted(this._audioMuted),this.previewStream?(g=this.previewStream)==null||g.mergeStream(this._publishAudioStream):this._previewStream=yield Wt(this._targetAudioTrack)):(this._publishAudioStream=void 0,(m=this.previewStream)==null||m.deleteTracks({audio:!0}))})}stopVideo(){var e,i;this.originVideoTrack&&((e=this.originVideoTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(i=this.originVideoTrack)==null||i.stop(),this.originVideoTrack=void 0),this.updateVideoTrack(void 0)}stopAudio(){var e,i;this.originAudioTrack&&((e=this.originAudioTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(i=this.originAudioTrack)==null||i.stop(),this.originAudioTrack=void 0),this.updateAudioTrack(void 0)}stop(){this.stopVideo(),this.stopAudio()}updateVideoProfile(e,i){return v(this,null,function*(){this._profileManager||(this._profileManager=new sr),e&&this._profileManager.updateProfile(e,i),yield this._profileManager.setVideoProfile(this.originVideoTrack,this._publishVideoStream,this.type===ce.AliRtcSdkStreamTypeScreen)})}get videoProfile(){var e;return(e=this.profileManager)==null?void 0:e.videoProfile}setVideoContentHint(e){this._profileManager||(this._profileManager=new sr),this._profileManager.setContentHint(this.currentVideoTrack,e)}updateAudioProfile(e){return v(this,null,function*(){this._profileManager||(this._profileManager=new sr),this._profileManager.updateAudioProfile(e)})}cloneVideoProfile(e){return v(this,null,function*(){var i;yield(i=this.profileManager)==null?void 0:i.setVideoProfile(void 0,e)})}addPlugin(e){const i=this.plugins.findIndex(s=>s.zIndex>e.zIndex);i>-1?this.plugins.splice(i,0,e):this.plugins.push(e)}removePlugin(e){const i=this.plugins.indexOf(e);return i>-1?(e.clear(this),this.plugins.splice(i,1),!0):!1}}var kn=Object.defineProperty,Cn=Object.getOwnPropertyDescriptor,xe=(t,r,e,i)=>{for(var s=i>1?void 0:i?Cn(r,e):r,a=t.length-1,n;a>=0;a--)(n=t[a])&&(s=(i?n(r,e,s):n(s))||s);return i&&s&&kn(r,e,s),s};const Oe=(Ct=class extends Q{constructor(e){super();l(this,"pluginManager");l(this,"publishingCameraVideoStream");l(this,"publishingScreenVideoStream");l(this,"cameraStreamInfo",new ar(ce.AliRtcSdkStreamTypeCapture));l(this,"screenStreamInfo",new ar(ce.AliRtcSdkStreamTypeScreen));l(this,"streamInfos",[this.cameraStreamInfo,this.screenStreamInfo]);l(this,"_audioCaptureDisabled",!1);l(this,"_cameraCaptureDisabled",!1);l(this,"_publishLocalAudioStreamEnabled",!0);l(this,"_publishLocalVideoStreamEnabled",!0);l(this,"_publishLocalScreenStreamEnabled",!0);this.screenStreamInfo.setVideoContentHint("motion"),this.pluginManager=e;const i=s=>v(this,null,function*(){if(E.info(`[${Ct.logName}]`,"plugin added",s.name),!s.isSupported("6.11.5")){console.warn(`${s.name} is not supported!!!`),s.emit("unsupported");return}try{yield s.init()}catch(a){s.emit("error",C.fromError(a,ot.AliRtcPluginErrorInitError))}s.streamType===ce.AliRtcSdkStreamTypeCapture&&(this.cameraStreamInfo.addPlugin(s),yield this.cameraStreamInfo.process(this.streamInfos)),s.streamType===ce.AliRtcSdkStreamTypeScreen&&(this.screenStreamInfo.addPlugin(s),yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")});this.cameraStreamInfo.updateVideoProfile(as,jt),this.cameraStreamInfo.on("videotrackended",()=>v(this,null,function*(){yield this.stopLocalStream({video:!0}),this.emit("trackended",bt.VideoTrackEnded)})),this.cameraStreamInfo.on("audiotrackended",()=>v(this,null,function*(){yield this.stopLocalStream({audio:!0}),this.emit("trackended",bt.AudioTrackEnded)})),this.screenStreamInfo.updateVideoProfile(ns,$t),this.screenStreamInfo.on("videotrackended",()=>v(this,null,function*(){yield this.stopLocalStream({screen:!0}),this.emit("trackended",bt.ScreenTrackEnded)})),this.pluginManager.on("added",i),this.pluginManager.on("removed",s=>v(this,null,function*(){this.cameraStreamInfo.removePlugin(s)&&(yield this.cameraStreamInfo.process(this.streamInfos)),this.screenStreamInfo.removePlugin(s)&&(yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("updated",()=>v(this,null,function*(){yield this.updateStreams()}))}get hasCamera(){return!!this.cameraStreamInfo.originVideoTrack}get audioCaptureDisabled(){return this._audioCaptureDisabled}set audioCaptureDisabled(e){this._audioCaptureDisabled=e}get cameraCaptureDisabled(){return this._cameraCaptureDisabled}setAudioMuted(e){this.cameraStreamInfo.setAudioMuted(e)}get isAudioMuted(){return this.cameraStreamInfo.isAudioMuted}setCameraMuted(e){this.cameraStreamInfo.setVideoMuted(e)}get isCameraMuted(){return this.cameraStreamInfo.isVideoMuted}setScreenMuted(e){this.screenStreamInfo.setVideoMuted(e)}get isScreenMuted(){return this.screenStreamInfo.isVideoMuted}set cameraCaptureDisabled(e){this._cameraCaptureDisabled=e}get publishLocalAudioStreamEnabled(){return this._publishLocalAudioStreamEnabled}set publishLocalAudioStreamEnabled(e){this._publishLocalAudioStreamEnabled=e}get publishLocalVideoStreamEnabled(){return this._publishLocalVideoStreamEnabled}set publishLocalVideoStreamEnabled(e){this._publishLocalVideoStreamEnabled=e}get publishLocalScreenStreamEnabled(){return this._publishLocalScreenStreamEnabled}set publishLocalScreenStreamEnabled(e){this._publishLocalScreenStreamEnabled=e}updateStreams(){return v(this,null,function*(){yield this.cameraStreamInfo.process(this.streamInfos),yield this.screenStreamInfo.process(this.streamInfos),this.emit("publishupdate")})}setAvailableCameraDeviceId(){return v(this,null,function*(){var e,i,s,a;if((e=this.cameraStreamInfo.cameraVideoConstraints)!=null&&e.deviceId){let n=(i=this.cameraStreamInfo.cameraVideoConstraints)==null?void 0:i.deviceId;const o=yield V.AliRTS.getCameraList();o.find(c=>c.deviceId===n)||(n=(a=(s=o.find(c=>!!c.deviceId))==null?void 0:s.deviceId)!=null?a:""),this.cameraStreamInfo.cameraVideoConstraints.deviceId=n}})}setAvailableMicrophoneDeviceId(){return v(this,null,function*(){var e,i,s,a;if((e=this.cameraStreamInfo.micAudioConstraints)!=null&&e.deviceId){let n=(i=this.cameraStreamInfo.micAudioConstraints)==null?void 0:i.deviceId;const o=yield V.AliRTS.getMicList();o.find(c=>c.deviceId===n)||(n=(a=(s=o.find(c=>!!c.deviceId))==null?void 0:s.deviceId)!=null?a:""),this.cameraStreamInfo.micAudioConstraints.deviceId=n}})}createLocalStream(e){return v(this,null,function*(){const{screen:i,mediaStream:s,videoProfile:a,screenProfile:n}=e;let{video:o,audio:c}=e;const h=fn(e);let f;if(h){if(s||(o===!0&&this.cameraStreamInfo.cameraVideoConstraints?(yield this.setAvailableCameraDeviceId(),o=q({},this.cameraStreamInfo.cameraVideoConstraints)):typeof o=="object"&&(yield this.setAvailableCameraDeviceId(),o=q(q({},o),this.cameraStreamInfo.cameraVideoConstraints)),c===void 0&&this.audioCaptureDisabled?c=!1:c&&(c===!0&&this.cameraStreamInfo.micAudioConstraints?(yield this.setAvailableMicrophoneDeviceId(),c=q({},this.cameraStreamInfo.micAudioConstraints)):typeof c=="object"&&(yield this.setAvailableMicrophoneDeviceId(),c=q(q({},c),this.cameraStreamInfo.micAudioConstraints)),this._audioCaptureDisabled=!1)),f=yield V.AliRTS.createStream({audio:c,video:o,screen:i,custom:!!s,mediaStream:s,skipProfile:!0}),i)yield this.screenStreamInfo.updateSource(f,At.Screen,si.Screen),yield this.setScreenProfile(n),this.setScreenContentHint(),this.publishingScreenVideoStream=void 0;else if(yield this.cameraStreamInfo.updateSource(f,At.Camera,si.Microphone),f.hasVideo&&(yield this.setVideoProfile(a),this.setVideoContentHint(),this.publishingCameraVideoStream=void 0),f.hasAudio&&typeof c=="boolean"){const p=this.cameraStreamInfo.audioProfile;p&&(yield f.setAudioProfile(p))}}return V.AliRTS.SystenUtil.isIos&&V.AliRTS.SystenUtil.compareVersion("15.1")&&!V.AliRTS.SystenUtil.compareVersion("15.2")&&(yield at(1e3)),yield this.updateStreams(),f})}stopLocalStream(e){return v(this,null,function*(){const{screen:i,video:s,audio:a}=e!=null?e:{};let n=!1;s&&this.cameraStreamInfo.originVideoTrack&&(n=!0,this.cameraStreamInfo.stopVideo(),this.publishingCameraVideoStream=void 0),a&&this.cameraStreamInfo.originAudioTrack&&(n=!0,this.cameraStreamInfo.stopAudio()),i&&this.screenStreamInfo.originVideoTrack&&(n=!0,this.screenStreamInfo.stop(),this.publishingScreenVideoStream=void 0),n&&(yield this.updateStreams())})}get publishStreams(){const{publishLocalVideoStreamEnabled:e,publishLocalAudioStreamEnabled:i,publishLocalScreenStreamEnabled:s}=this;return{video:e?this.cameraStreamInfo.publishVideoStream:void 0,videoSmall:e?this.cameraStreamInfo.publishDualVideoStream:void 0,audio:i?this.cameraStreamInfo.publishAudioStream:void 0,screen:s?this.screenStreamInfo.publishVideoStream:void 0}}createHTTPPublishStream(){return v(this,null,function*(){var c,h,f,p;let e,i=!1,s,a,n;const o=yield this.publishStreams;try{if(!o.audio&&!o.video&&!o.videoSmall&&!o.screen)throw new C(N.ERR_SDK_PUBLISH_INVAILD,"no tracks founded");const u=new MediaStream;(c=o.audio)!=null&&c.audioTrack&&u.addTrack(o.audio.audioTrack),(h=o.video)!=null&&h.videoTrack?(u.addTrack(o.video.videoTrack),a=o.videoSmall,n=o.screen):(f=o.screen)!=null&&f.videoTrack&&(s=k.Screen,u.addTrack((p=o.screen)==null?void 0:p.videoTrack),i=!0),e=yield hs(u),i?(this.screenStreamInfo.cloneVideoProfile(e),this.publishingScreenVideoStream=e):(this.cameraStreamInfo.cloneVideoProfile(e),this.publishingCameraVideoStream=e)}catch(u){}return{publishStream:e,videoSmallStream:a,screenStream:n,vMsid:s}})}stop(){this.cameraStreamInfo.stop(),this.screenStreamInfo.stop()}setVideoProfile(e,i){return v(this,null,function*(){yield this.cameraStreamInfo.updateVideoProfile(e,i),this.publishingCameraVideoStream&&this.cameraStreamInfo.cloneVideoProfile(this.publishingCameraVideoStream)})}setVideoContentHint(e){this.cameraStreamInfo.setVideoContentHint(e)}setAudioProfile(e){return v(this,null,function*(){var i;yield this.cameraStreamInfo.updateAudioProfile(e),yield(i=this.publishingCameraVideoStream)==null?void 0:i.setAudioProfile(e)})}setScreenProfile(e,i){return v(this,null,function*(){yield this.screenStreamInfo.updateVideoProfile(e,i),this.publishingScreenVideoStream&&this.screenStreamInfo.cloneVideoProfile(this.publishingScreenVideoStream)})}setScreenContentHint(e){this.screenStreamInfo.setVideoContentHint(e)}setCameraVideoConstraints(e){var i;this.cameraStreamInfo.cameraVideoConstraints=q(q({},(i=this.cameraStreamInfo.cameraVideoConstraints)!=null?i:{}),e)}setMicAudioConstraints(e){var i;this.cameraStreamInfo.micAudioConstraints=q(q({},(i=this.cameraStreamInfo.micAudioConstraints)!=null?i:{}),e)}},l(Ct,"logName","LocalStreamManager"),Ct);xe([y(([t])=>{const{audio:r,video:e,screen:i,custom:s,skipProfile:a,videoProfile:n,screenProfile:o}=t;return[{audio:r,video:e,screen:i,custom:s,skipProfile:a,videoProfile:n,screenProfile:o}]})],Oe.prototype,"createLocalStream",1),xe([y(I)],Oe.prototype,"stopLocalStream",1),xe([y()],Oe.prototype,"createHTTPPublishStream",1),xe([y()],Oe.prototype,"stop",1),xe([y(I)],Oe.prototype,"setVideoProfile",1),xe([y(I)],Oe.prototype,"setVideoContentHint",1),xe([y(I)],Oe.prototype,"setAudioProfile",1),xe([y(I)],Oe.prototype,"setScreenProfile",1),xe([y(I)],Oe.prototype,"setScreenContentHint",1),xe([y(I)],Oe.prototype,"setCameraVideoConstraints",1),xe([y(I)],Oe.prototype,"setMicAudioConstraints",1);let Mn=Oe;var Nn=Object.defineProperty,Ln=Object.getOwnPropertyDescriptor,Ue=(t,r,e,i)=>{for(var s=i>1?void 0:i?Ln(r,e):r,a=t.length-1,n;a>=0;a--)(n=t[a])&&(s=(i?n(r,e,s):n(s))||s);return i&&s&&Nn(r,e,s),s};class ke extends Q{constructor(e){super();l(this,"self");l(this,"userMap",{});l(this,"usersViewMap",{});l(this,"rtsManager");l(this,"localStreamManager");l(this,"authInfo");l(this,"signalingManager");l(this,"pluginManager");l(this,"reporter");l(this,"webTrackingClient");l(this,"statsMonitorId");l(this,"autoSubAudio",!0);l(this,"autoSubVideo",!0);l(this,"autoSubScreen",!0);l(this,"wantSubAudio",!0);l(this,"wantSubVideo",!0);l(this,"wantSubScreen",!0);l(this,"defaultStreamType",he.AliRtcVideoStreamTypeHigh);l(this,"audioMuted",!1);l(this,"audioVolumeIndicationInterval",0);l(this,"indicationTimer",0);const{signalingManager:i,reporter:s,webTrackingClient:a}=e;this.signalingManager=i,this.addSignalingManagerListener(),this.reporter=s,this.webTrackingClient=a,this.pluginManager=new En,this.localStreamManager=new Mn(this.pluginManager),this.rtsManager=new Pn(this.localStreamManager),this.self=new us({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,reporter:this.reporter,webTrackingClient:this.webTrackingClient,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval})}addSignalingManagerListener(){this.signalingManager.on("onNotifyPublish",e=>{E.event("[Signaling] Notify Publish ",e),e.forEach(i=>{this.onRemotePublishStateChange(i)})})}isAutoSubAudio(){return this.autoSubAudio}setAutoSubAudio(e){this.autoSubAudio=e}isAutoSubVideo(){return this.autoSubVideo}setAutoSubVideo(e){this.autoSubVideo=e}isAutoSubScreen(){return this.autoSubScreen}setAutoSubScreen(e){this.autoSubScreen=e}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e,this.remoteUsers.forEach(i=>{i.setWantSubAudio(e),i.updateSubscribe()})}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e,this.remoteUsers.forEach(i=>{i.setWantSubVideo(e),i.updateSubscribe()})}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e,this.remoteUsers.forEach(i=>{i.setWantSubScreen(e),i.updateSubscribe()})}setRemoteDefaultVideoStreamType(e){this.defaultStreamType=e,this.remoteUsers.forEach(i=>{i.setRemoteDefaultVideoStreamType(e)})}setRemoteUserVideoStreamType(e,i){var s;(s=this.getRemoteUser(e))==null||s.setRemoteDefaultVideoStreamType(i)}setAudioMuted(e){this.audioMuted=e,this.remoteUsers.forEach(i=>{i.setAudioMuted(e)})}setLocalViewConfig(e,i){var a;if(!e)return(a=this.publisher)==null?void 0:a.setViewConfig(null,i);const s=rr(e);s.length!==0&&s.forEach(n=>{var o,c;(o=this.publisher)==null||o.resetElement(n),Object.values(this.usersViewMap).forEach(({cameraViews:h=[],screenViews:f=[]})=>{h.includes(n)&&h.splice(h.indexOf(n),1),f.includes(n)&&f.splice(f.indexOf(n),1)}),(c=this.publisher)==null||c.setViewConfig(s,i)})}setRemoteViewConfig(e,i,s){var n,o;if(!i)return(n=this.userMap[e])==null?void 0:n.setViewConfig(null,s);const a=rr(i);a.length!==0&&(a.forEach(c=>{var h;(h=this.publisher)==null||h.resetElement(c),Object.values(this.usersViewMap).forEach(({cameraViews:f=[],screenViews:p=[]})=>{f.includes(c)&&f.splice(f.indexOf(c),1),p.includes(c)&&p.splice(p.indexOf(c),1)})}),(o=this.userMap[e])==null||o.setViewConfig(a,s))}get channel(){var e;return(e=this.authInfo)==null?void 0:e.channelId}get userId(){var e;return(e=this.authInfo)==null?void 0:e.userId}get remoteUsers(){return Object.values(this.userMap)}get publisher(){return this.self}get isSubscribing(){var e;return((e=this.remoteUsers)!=null?e:[]).some(i=>{var c;const{isAudioSubscribing:s,isVideoLargeSubscribing:a,isVideoSmallSubscribing:n,isScreenSubscribing:o}=(c=i.streamInfo)!=null?c:{};return s||a||n||o})}onRemotePublishStateChange(e){var u;const{userid:i,callid:s,subscribe:a,pubid:n="",tracks:o}=e,c=(u=a==null?void 0:a.pullstreamurl)!=null?u:"";let h=this.getRemoteUser(i);if(!h)return;const f=h.streamInfo.audioTrackInfo,p=h.streamInfo.videoTrackInfo;h.updateRemoteTracks(s,c,n,o),h.updateSubscribe(),(f!==h.streamInfo.audioTrackInfo||p!==h.streamInfo.videoTrackInfo)&&this.emit("remoteTrackAvailableChange",i,h.streamInfo.audioTrackInfo,h.streamInfo.videoTrackInfo)}init(e,i){var s;this.authInfo=e,this.self||(this.self=new us({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,reporter:this.reporter,webTrackingClient:this.webTrackingClient,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval})),this.self.enableAudioVolumeIndication(this.audioVolumeIndicationInterval),(s=this.self)==null||s.initInfo(e,i.pushstreamurl),i.users.forEach(a=>{const n=a.userid;if(n){const o=this.addUser(n,a.displayname),{callid:c,subscribe:h,tracks:f}=a;o.updateRemoteTracks(c,(h==null?void 0:h.pullstreamurl)||"","",f),this.emit("remoteTrackAvailableChange",n,o.streamInfo.audioTrackInfo,o.streamInfo.videoTrackInfo)}}),this.startStatsMonitor()}clear(){return v(this,null,function*(){var e;this.stopStatsMonitor();for(let i in this.userMap)this.userMap[i]&&(yield this.userMap[i].clear(),delete this.userMap[i]);yield(e=this.self)==null?void 0:e.clear(),this.authInfo=void 0})}startStatsMonitor(){this.statsMonitorId=window.setInterval(()=>v(this,null,function*(){if(this.publisher){const{audio:s,video:a}=yield this.publisher.getStats();s&&s.length>0&&this.emit("rtcLocalAudioStats",s),a&&a.length>0&&this.emit("rtcLocalVideoStats",a)}const e=[],i=[];for(const s of this.remoteUsers){const{audio:a,video:n}=yield s.getStats();a&&a.forEach(o=>{e.push(o)}),n&&n.forEach(o=>{i.push(o)})}e.length>0&&this.emit("rtcRemoteAudioStats",e),i.length>0&&this.emit("rtcRemoteVideoStats",i)}),2e3)}stopStatsMonitor(){this.statsMonitorId&&clearInterval(this.statsMonitorId)}getUser(e,i){return this.addUser(e,i),this.userMap[e]}addUser(e,i){return this.userMap[e]||(this.userMap[e]=this.executeAddUser(e,i)),this.userMap[e]}executeAddUser(e,i){var a;const s=new ae({userId:e,displayName:i,rtsManager:this.rtsManager,signalingManager:this.signalingManager,usersViewMap:this.usersViewMap,reporter:this.reporter,webTrackingClient:this.webTrackingClient,localUserId:(a=this.userId)!=null?a:"",audioVolumeIndicationInterval:this.audioVolumeIndicationInterval});return s.on(we.Remote,this.onRemoteDeviceStatusChange.bind(this)),s.on(J.PullStreamStats,this.onRemoteStatReport.bind(this)),s.on(J.RtsSubscribeExceeds,this.onSubscribeExceeds.bind(this)),s.on("audioSubscribeStateChanged",(n,o,c,h)=>{this.emit("audioSubscribeStateChanged",n,o,c,h,this.channel||"")}),s.on("videoSubscribeStateChanged",(n,o,c,h)=>{this.emit("videoSubscribeStateChanged",n,o,c,h,this.channel||"")}),s.on("screenSubscribeStateChanged",(n,o,c,h)=>{this.emit("screenSubscribeStateChanged",n,o,c,h,this.channel||"")}),s.on("remoteAudioAutoPlayFail",n=>{this.emit("remoteAudioAutoPlayFail",n)}),s.on("remoteVideoAutoPlayFail",(n,o)=>{this.emit("remoteVideoAutoPlayFail",n,o)}),s.on("remoteSubscribeError",n=>{this.emit("remoteSubscribeError",n)}),s.setWantSubAudio(this.autoSubAudio&&this.wantSubAudio),s.setWantSubVideo(this.autoSubVideo&&this.wantSubVideo),s.setWantSubScreen(this.autoSubScreen&&this.wantSubScreen),s.setRemoteDefaultVideoStreamType(this.defaultStreamType),s.setAudioMuted(this.audioMuted),(this.autoSubAudio||this.autoSubVideo||this.autoSubScreen)&&s.updateSubscribe(),s}onRemoteDeviceStatusChange(e,i){e===J.MuteAudio?this.emit("userAudioMuted",i,!0):e===J.UnmuteAudio?this.emit("userAudioMuted",i,!1):e===J.MuteVideo?this.emit("userVideoMuted",i,!0):e===J.UnmuteVideo?this.emit("userVideoMuted",i,!1):e===J.MuteScreen?this.emit("userScreenMuted",i,!0):e===J.UnmuteScreen&&this.emit("userScreenMuted",i,!1)}onRemoteStatReport(e,i,s){this.emit(J.PullStreamStats,e,i,s)}onSubscribeExceeds(e,i){this.emit(J.RtsSubscribeExceeds,e,i)}removeLeftUser(e){return v(this,null,function*(){e.userid&&this.userMap[e.userid]&&(yield this.userMap[e.userid].clear(!1),delete this.userMap[e.userid])})}updateUsers(e){const i=[],s=[],a={};e.forEach(c=>{c.userid&&(this.userMap[c.userid]?(s.push(c),a[c.userid]=this.userMap[c.userid]):(i.push(c),a[c.userid]=this.executeAddUser(c.userid,c.displayname)))});const n=Object.keys(this.userMap),o=[];return n.forEach(c=>{a[c]||o.push({userid:c,reason:"",leavecode:Zi.AliRtcUserOfflineQuit})}),this.userMap=a,{joinList:i,leaveList:o,presentList:s}}getRemoteUser(e){return this.userMap[e]}updateRemoteUserDeviceStatus(e){e&&e.userid&&this.userMap[e.userid]&&this.userMap[e.userid].updateRemoteUserDeviceStatus(e.status)}updateAudioWant(e,i){const s=this.userMap[e];if(!s)throw new C(N.ERR_INNER,`no remote user(${e}) founded`);s.setWantSubAudio(i),i?s.updateSubscribe():s.stopSubscribe({audio:!0})}updateVideoWant(e,i){const s=this.userMap[e];if(!s)throw new C(N.ERR_INNER,`no remote user(${e}) founded`);s.setWantSubVideo(i),i?s.updateSubscribe():s.stopSubscribe({video:!0})}updateScreenWant(e,i){const s=this.userMap[e];if(!s)throw new C(N.ERR_INNER,`no remote user(${e}) founded`);s.setWantSubScreen(i),i?s.updateSubscribe():s.stopSubscribe({screen:!0})}stopIndication(){this.indicationTimer&&window.clearInterval(this.indicationTimer)}startIndication(e){this.stopIndication(),this.indicationTimer=window.setInterval(()=>{var s;const i=this.remoteUsers.map(a=>({userId:a.userId,volume:a.getAudioLevel()||0}));i.unshift({userId:"",volume:((s=this.self)==null?void 0:s.getAudioLevel())||0}),this.emit("audioVolume",i)},e)}enableAudioVolumeIndication(e){var i;this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.stopIndication(),e>0&&this.startIndication(e),this.audioVolumeIndicationInterval=e,this.remoteUsers.forEach(s=>{s.enableAudioVolumeIndication(e)}),(i=this.self)==null||i.enableAudioVolumeIndication(e))}refreshAuthInfo(e){var i;this.authInfo&&(this.authInfo=q(q({},this.authInfo),e)),e.userId&&((i=this.self)==null||i.refreshUserInfo(e.userId))}setEnableMediaExtensionMsg(e){this.rtsManager.setEncodedInsertableStreams(e)}setAudioRedEnabled(e){this.rtsManager.setAudioRedEnabled(e)}}l(ke,"logName","UserManager"),Ue([y()],ke.prototype,"init",1),Ue([y()],ke.prototype,"clear",1),Ue([y(I)],ke.prototype,"addUser",1),Ue([y()],ke.prototype,"removeLeftUser",1),Ue([y()],ke.prototype,"updateUsers",1),Ue([y(I)],ke.prototype,"updateAudioWant",1),Ue([y(I)],ke.prototype,"updateVideoWant",1),Ue([y(I)],ke.prototype,"updateScreenWant",1),Ue([y()],ke.prototype,"stopIndication",1),Ue([y()],ke.prototype,"startIndication",1),Ue([y()],ke.prototype,"enableAudioVolumeIndication",1);const nr=t=>v(this,null,function*(){const r=new Uint8Array(160).fill(170),e=new TextEncoder().encode(t),i=yield window.crypto.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-1"}},!1,["sign"]),s=yield window.crypto.subtle.sign("HMAC",i,e);return Array.from(new Uint8Array(s)).map(a=>a.toString(16).padStart(2,"0")).join("")});class On{constructor(){l(this,"authInfo")}doRequest(r,e){var h;const i=this.authInfo;if(!i)return Promise.reject(We.LiveTranscodingErrorInvalidParam);const s="https://gw.rtn.aliyuncs.com",a=Za[r],n={appid:i.appId,userid:i.userId,channelid:i.channelId,timestamp:i.timestamp,token:i.token,nonce:i.nonce?i.nonce:"",requestid:it.createCallid(),tokensid:!1,session:(h=i.callid)!=null?h:it.createCallid()},o=Object.keys(n).map(f=>`${f}=${encodeURIComponent(n[f])}`).join("&"),c=`${s}${a}?${o}`;return fetch(c,{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:e}).then(f=>f.status!==200?Promise.reject(new C(N.ERR_INNER,`transcoding request failed, status: ${f.status}`)):f)}setAuthInfo(r){this.authInfo=r}clear(){this.authInfo=void 0}startPublishLiveStream(r,e){return v(this,null,function*(){if(!this.authInfo)return Promise.reject(We.LiveTranscodingErrorInvalidParam);const i=yield nr(r.split("?")[0]),s=Ie.MPU_TASK_TRANSACTION_UPDATE,a=e.toJson(s,this.authInfo,i,r);return this.doRequest(s,JSON.stringify(a))})}startPublishLiveStreamWithTaskId(r,e){return v(this,null,function*(){if(!this.authInfo)return Promise.reject(We.LiveTranscodingErrorInvalidParam);const i=Ie.MPU_TASK_TRANSACTION_UPDATE,s=e.toJson(i,this.authInfo,r);return this.doRequest(i,JSON.stringify(s))})}updatePublishLiveStream(r,e){return v(this,null,function*(){if(!this.authInfo)return Promise.reject(We.LiveTranscodingErrorInvalidParam);const i=yield nr(r.split("?")[0]),s=Ie.MPU_TASK_TRANSACTION_UPDATE,a=e.toJson(s,this.authInfo,i,r);return this.doRequest(s,JSON.stringify(a))})}updatePublishLiveStreamWithTaskId(r,e){return v(this,null,function*(){if(!this.authInfo)return Promise.reject(We.LiveTranscodingErrorInvalidParam);const i=Ie.MPU_TASK_TRANSACTION_UPDATE,s=e.toJson(i,this.authInfo,r);return this.doRequest(i,JSON.stringify(s))})}stopPublishLiveStream(r){return v(this,null,function*(){if(!this.authInfo)return Promise.reject(We.LiveTranscodingErrorInvalidParam);const e=yield nr(r.split("?")[0]),i=Ie.MPU_TASK_TRANSACTION_STOP,s=new ui().toJson(i,this.authInfo,e,r);return this.doRequest(i,JSON.stringify(s))})}stopPublishLiveStreamWithTaskId(r){if(!this.authInfo)return Promise.reject(We.LiveTranscodingErrorInvalidParam);const e=Ie.MPU_TASK_TRANSACTION_STOP,i=new ui().toJson(e,this.authInfo,r);return this.doRequest(e,JSON.stringify(i))}refreshAuthInfo(r){this.authInfo&&this.setAuthInfo(q(q({},this.authInfo),r))}}var ds=(t,r,e)=>{if(!r.has(t))throw TypeError("Cannot "+e)},gi=(t,r,e)=>(ds(t,r,"read from private field"),e?e.call(t):r.get(t)),or=(t,r,e)=>{if(r.has(t))throw TypeError("Cannot add the same private member more than once");r instanceof WeakSet?r.add(t):r.set(t,e)},cr=(t,r,e,i)=>(ds(t,r,"write to private field"),i?i.call(t,e):r.set(t,e),e),Vn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},M={},vt={};const Dn="SLS_CLIENT";var ps=(t=>(t.ERROR="error",t.LOG="log",t.LOCATION="pv",t.API="api",t.RESOURCE="res",t.RESOURCE_ERROR="res_err",t.PERF="perf",t.CONSOLE_LOG="console",t))(ps||{}),gs=(t=>(t.LOG_SEND="LOG_SEND",t.BROWSER_SEND="BROWSER_SEND",t.BASE_TRANSFORM="BASE_TRANSFORM",t.BROWSER_BASE_TRANSFORM="BROWSER_BASE_TRANSFORM",t.BROWSER_FETCH="BROWSER_FETCH",t.BROWSER_XHR="BROWSER_XHR",t.BROWSER_LOCATION="BROWSER_LOCATION",t.BROWSER_RUNTIME_ERROR="BROWSER_RUNTIME_ERROR",t.BROWSER_CUSTOM_ERROR="BROWSER_CUSTOM_ERROR",t.BROWSER_RESOURCE_ERROR="BROWSER_RESOURCE_ERROR",t.BROWSER_CONSOLE="BROWSER_CONSOLE",t.BROWSER_PERF="BROWSER_PERF",t.BROWSER_RESOURSE="BROWSER_RESOURSE",t.MINI_SEND="MINI_SEND",t.MINI_REQUEST="MINI_REQUEST",t.MINI_BASE_TRANSFORM="MINI_BASE_TRANSFORM",t.MINI_ROUTE="MINI_ROUTE",t))(gs||{});const xn={BROWSER_SEND:-1,MINI_SEND:-2,BASE_TRANSFORM:100,BROWSER_BASE_TRANSFORM:100*2,MINI_BASE_TRANSFORM:100*2+1,BROWSER_PERF:100*3+1,BROWSER_FETCH:100*4,BROWSER_XHR:100*4+1,MINI_REQUEST:100*4+2,BROWSER_RUNTIME_ERROR:100*5},Un="sls-trace-uid";var fs=(t=>(t.OK="OK",t.ERROR="ERROR",t.UNSET="UNSET",t))(fs||{});vt.InternalPlugin=gs,vt.InternalPluginPriority=xn,vt.OTStatusCode=fs,vt.SLS_CLIENT_NAME=Dn,vt.SLS_TRACE_UID_KEY=Un,vt.WebEventType=ps;var Be=vt;function ur(t,r,e){Object.defineProperty(t,r,{writable:!0,enumerable:!0,configurable:!0,value:e})}function Bn(t,r,e,i){i?i(()=>{ur(t,r,e)}):ur(t,r,e)}class Hn{constructor(r){this.onFirstSubscribe=r,this.observers=[]}subscribe(r){return!this.observers.length&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe()||void 0),this.observers.push(r),{unsubscribe:()=>{this.observers=this.observers.filter(e=>r!==e),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(r){this.observers.forEach(e=>e(r))}}function qt(t,r,e){try{return t.apply(r,e)}catch(i){return}}function Fn(t){return function(){return qt(t,this,arguments)}}let jn=!1;function $n(){return jn}function ms(...t){}var Wn=Object.defineProperty,Kn=Object.defineProperties,qn=Object.getOwnPropertyDescriptors,Ss=Object.getOwnPropertySymbols,Jn=Object.prototype.hasOwnProperty,Gn=Object.prototype.propertyIsEnumerable,bs=(t,r,e)=>r in t?Wn(t,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[r]=e,zn=(t,r)=>{for(var e in r||(r={}))Jn.call(r,e)&&bs(t,e,r[e]);if(Ss)for(var e of Ss(r))Gn.call(r,e)&&bs(t,e,r[e]);return t},Xn=(t,r)=>Kn(t,qn(r));const vs=1e3,ys=60*vs,ws=60*ys,_s=24*ws,Rs=365*_s,Yn=1024,Is="0.1.0";function Qn(){}function Es(t){return typeof t=="number"}function Zn(t){return Object.prototype.toString.call(t)==="[object String]"}function eo(t){return Object.prototype.toString.call(t)==="[object Error]"}function As(t,r){return+t.toFixed(r)}function to(t,r){return t.indexOf(r)!==-1}function io(t,r){return t==null?r:!!t}function fi(t){return t?(parseInt(t,10)^Math.random()*16>>parseInt(t,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,fi)}function Ts(t=20){var r,e;const i=new Array(t),s=Date.now().toString(36).split("");for(;t-- >0;)e=(r=36*Math.random()|0).toString(36),i[t]=r%3?e:e.toUpperCase();for(var a=0;a<8;a++)i.splice(3*a+2,0,s[a]);return i.join("")}function ro(t){return t!==0&&Math.random()<=t}function mi(t,r){return(...e)=>{try{return t(...e)}catch(i){console.error(r,i)}}}function Ps(t){return"https://"+t.project+"."+t.host+"/logstores/"+t.logstore+"/track"}function so(t,r){return r?t.includes(Ps(r)):t.includes("/track?APIVersion=0.6.0")}const ks=/^(?:([^:\/?#]+):\/\/)?((?:([^\/?#@]*)@)?([^\/?#:]*)(?:\:(\d*))?)?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n)*))?/i;function ao(t){try{return decodeURIComponent(t)}catch(r){return unescape(t)}}function no(t){return typeof t=="string"&&ks.test(t)}function oo(t){var r=ao(t||"").match(ks);if(r==null)return null;var e=(r[3]||"").split(":"),i=e.length?(r[2]||"").replace(/(.*\@)/,""):r[2];return{uri:r[0],protocol:r[1],host:i,hostname:r[4],port:r[5],auth:r[3],user:e[0],password:e[1],path:r[6],search:r[7],hash:r[8]}}function co(t,r,e,i){const s={url:t,method:r,status_code:e};return i==null?s:Xn(zn({},s),{host:i.host,scheme:i.protocol})}function uo(t,r,...e){return r==null||!Array.isArray(r)?!1:r.some(i=>{if(typeof i=="function")try{return i(t,...e)}catch(s){return console.error("user function callback threw an error:",s),!1}return typeof i=="string"?t.includes(i):Object.prototype.toString.call(i)==="[object RegExp]"?i.test(t):!1})}function ho(t,r,e){return t===!1?!1:t===!0||t==="error"&&!e?!0:typeof t=="function"?mi(t,"call shouldTrackBody failed")(r):!1}function lo(t){return{relative:t,timeStamp:Cs(t)}}function Cs(t){const r=Date.now()-performance.now();return r>Jt()?Math.round(r+t):Ns(t)}function po(){return Math.round(Date.now()-(Jt()+performance.now()))}function go(t){return Es(t)?As(t*1e6,0):t}function hr(){return Date.now()}function Ms(){return performance.now()}function fo(){return{relative:Ms(),timeStamp:hr()}}function mo(){return{relative:0,timeStamp:Jt()}}function So(t,r){return r-t}function bo(t){return t-Jt()}function Ns(t){return Math.round(Jt()+t)}function vo(t){return t<Rs}let Si;function Jt(){return Si===void 0&&(Si=performance.timing.navigationStart),Si}function yo(){Si=void 0}const yt="?";function Gt(t,r){let e;const i=r===void 0?0:+r;try{if(e=_o(t),e)return e}catch(s){}try{if(e=wo(t),e)return e}catch(s){}try{if(e=Ro(t),e)return e}catch(s){}try{if(e=Ls(t,i+1),e)return e}catch(s){}return{message:Se(t,"message"),name:Se(t,"name"),stack:[]}}function wo(t){const r=Se(t,"stack");if(!r)return;const e=/^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,i=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,s=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;let a;const n=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,o=/\((\S*)(?::(\d+))(?::(\d+))\)/,c=r.split(`
|
|
5
|
-
`),
|
|
6
|
-
`),
|
|
7
|
-
`);if(e.length<4)return;const
|
|
8
|
-
at ${i}${s} @ ${e.url}${a}${n}`}),encodeURIComponent(r)}function Mo(t,r,e,i=!0){var s;if(!t||t.message===void 0&&!(r instanceof Error))return{message:`${e} ${JSON.stringify(r)}`,stacktrace:"",type:t&&t.name,id:fi()};t!=null&&t.stack&&i&&(t.stack=Ds(t.stack));const a=(s=t==null?void 0:t.stack)==null?void 0:s[0];return{message:encodeURIComponent(t.message||"Empty message"),stacktrace:dr(t),type:t.name,col:a?a.column:void 0,line:a?a.line:void 0,file:encodeURIComponent(a&&a.url?a.url:""),id:fi()}}function No(){const t=new Error;let r;return qt(()=>{const e=Gt(t);e!=null&&e.stack&&(e.stack=Ds(e.stack)),r=dr(e)}),r}const Lo=8,Oo=16,pr="b3",gr="traceparent",fr="uber-trace-id",bi=Array(32);function xs(t){for(let r=0;r<t*2;r++)bi[r]=Math.floor(Math.random()*16)+48,bi[r]>=58&&(bi[r]+=39);return String.fromCharCode.apply(null,bi.slice(0,t*2))}function Us(){return xs(Oo)}function mr(){return xs(Lo)}function vi(t,r){return`${t}-${r}-1`}function yi(t,r){return`00-${t}-${r}-01`}function wi(t,r){return`${t}:${r}:0:1`}const _i={b3:{name:pr,getter:vi},traceparent:{name:gr,getter:yi},uber:{name:fr,getter:wi}};function Vo(t,r,e,i){var s;const a=i!=null?i:{};a.headers=(s=a.headers)!=null?s:{},a.headers[pr]=vi(t,r),a.headers[gr]=yi(t,r),a.headers[fr]=wi(t,r);try{if(e)for(const[n,o]of Object.entries(e))_i[o]&&(a.headers[n]=_i[o].getter(t,r))}catch(n){}return a}function Do(t,r,e,i){t.setRequestHeader(pr,vi(r,e)),t.setRequestHeader(gr,yi(r,e)),t.setRequestHeader(fr,wi(r,e));try{if(i)for(const[s,a]of Object.entries(i))_i[a]&&t.setRequestHeader(s,_i[a].getter(r,e))}catch(s){}}function zt(t,r,e){t!=null&&Object.keys(t).map(i=>{e==null||e==""?r[i]=t[i]:r[`${e}.${i}`]=t[i]})}var xo=Object.defineProperty,Uo=Object.defineProperties,Bo=Object.getOwnPropertyDescriptors,Bs=Object.getOwnPropertySymbols,Ho=Object.prototype.hasOwnProperty,Fo=Object.prototype.propertyIsEnumerable,Hs=(t,r,e)=>r in t?xo(t,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[r]=e,jo=(t,r)=>{for(var e in r||(r={}))Ho.call(r,e)&&Hs(t,e,r[e]);if(Bs)for(var e of Bs(r))Fo.call(r,e)&&Hs(t,e,r[e]);return t},$o=(t,r)=>Uo(t,Bo(r));function Wo(){return{name:Be.InternalPlugin.BASE_TRANSFORM,run:function(){this.subscribe("*",(t,r)=>{const{otBase:e,extra:i}=t;e.attribute=$o(jo({},e.attribute),{sid:this.session.getSessionId(),pid:this.session.getPageId(),uid:this.options.uid,service:this.options.service}),this.options.nickname&&(e.attribute.nickname=this.options.nickname),zt(this.options.custom,e.attribute,"custom"),zt({env:this.options.env,version:this.options.version},e.attribute),zt({sdk_version:Is,workspace:this.options.workspace},e.resource);const s={otBase:e,extra:i};ms(Be.InternalPlugin.BASE_TRANSFORM,s),r(s)},Be.InternalPluginPriority[Be.InternalPlugin.BASE_TRANSFORM])}}}function Ko(){return{name:Be.InternalPlugin.LOG_SEND,run:function(){}}}function Fs(t,r,e){if(r<0)return;const i=a=>{Fs(t,r-1,a)},s=t[r];mi(()=>{s.callback.call(void 0,e,i)},"plugin notify run error")()}class qo{constructor(r){this.subscribeMap={},this.allNotifiers=[],this.allNotifiers=r}subscribeOne(r,e,i,s){var a;const n=(a=this.subscribeMap[e])!=null?a:[];this.subscribeMap[e]=n,n.push({name:r,priority:s,callback:i}),n.sort((o,c)=>o.priority-c.priority)}notify(r,e){var i;const s=(i=this.subscribeMap[r])!=null?i:[];Fs(s,s.length-1,e)}subscribe(r,e,i,s){if(e==="*")for(let a=0;a<this.allNotifiers.length;a++){const n=this.allNotifiers[a];this.subscribeOne(r,n,i,s)}else this.subscribeOne(r,e,i,s)}getSubscribeMap(){return this.subscribeMap}}function Jo(){const t=Us();let r=mr();return{getSessionId:()=>t,getPageId:()=>r,refreshPageId:()=>{r=mr()}}}var Go=Object.defineProperty,zo=Object.defineProperties,Xo=Object.getOwnPropertyDescriptors,js=Object.getOwnPropertySymbols,Yo=Object.prototype.hasOwnProperty,Qo=Object.prototype.propertyIsEnumerable,$s=(t,r,e)=>r in t?Go(t,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[r]=e,Zo=(t,r)=>{for(var e in r||(r={}))Yo.call(r,e)&&$s(t,e,r[e]);if(js)for(var e of js(r))Qo.call(r,e)&&$s(t,e,r[e]);return t},ec=(t,r)=>zo(t,Xo(r));const tc=["uid","nickname","env","service","version","custom"];class ic{constructor(r){this.isInit=!1,this.pendingPlugins=[],this.pluginMap={},this.session=Jo();var e,i;this.options=r,this.use(Ko()),this.use(Wo()),this.options.env=(e=r.env)!=null?e:"prod",this.options.version=(i=r.version)!=null?i:"-"}initPlugin(r){if(r==null||typeof r!="object"){console.error("plugin is not a object");return}if(r.name==null||r.name===""){console.error("plugin name is required.");return}if(this.pluginMap[r.name]){console.error(`plugin name: ${r.name} is conflict`);return}if(typeof r.run!="function"){console.error("plugin.run is not a function");return}const e=ec(Zo({},this.context),{subscribe:(i,s,a)=>{this.sub.subscribe(r.name,i,s,a)},notify:i=>{this.sub.notify(r.name,i)}});mi(()=>r.run.call(e),`plugin ${r.name} init failed`)()}addLog(r){if(this.isInit){const e={t:Be.WebEventType.LOG};zt(r,e,Be.WebEventType.LOG);const i={start:hr()*1e3,attribute:e,resource:{}};this.sub.notify(Be.InternalPlugin.LOG_SEND,{otBase:i,extra:{}})}else console.error("log should call after start")}setOptions(r){this.isInit?tc.forEach(e=>{r[e]!==this.options[e]&&r[e]!=null&&r[e]!=""&&(this.options[e]=r[e],e==="uid"&&typeof this.setLocalStorage=="function"&&this.setLocalStorage(Be.SLS_TRACE_UID_KEY,r[e]))}):console.error("setOptions should call after start")}start(){if(!this.isInit){this.isInit=!0;let r=this.options.uid;(r==null||r==="")&&(typeof this.getLocalStorage=="function"&&(r=this.getLocalStorage(Be.SLS_TRACE_UID_KEY)),(r==null||r==="")&&(r=Ts())),this.options.uid=r,typeof this.setLocalStorage=="function"&&this.setLocalStorage(Be.SLS_TRACE_UID_KEY,r);const e=this.pendingPlugins.map(i=>i==null?void 0:i.name).filter(i=>i!=null);this.sub=new qo(e),this.context={options:this.options,session:this.session};for(const i of this.pendingPlugins)this.initPlugin(i)}}use(r){this.isInit?console.error(`plugin: ${r==null?void 0:r.name} use should run before start`):this.pendingPlugins.push(r)}}var rc=Object.defineProperty,Ws=Object.getOwnPropertySymbols,sc=Object.prototype.hasOwnProperty,ac=Object.prototype.propertyIsEnumerable,Ks=(t,r,e)=>r in t?rc(t,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[r]=e,nc=(t,r)=>{for(var e in r||(r={}))sc.call(r,e)&&Ks(t,e,r[e]);if(Ws)for(var e of Ws(r))ac.call(r,e)&&Ks(t,e,r[e]);return t};function oc(t,r){var e;const i={current:void 0},s=[];let a={};return typeof r=="function"&&(a=(e=r(i))!=null?e:{}),nc({init:n=>{if(i.current!=null)return;i.current=t(n);const o=i.current;s.forEach(c=>{o.use(c)}),o.start()},use:n=>{s.push(n)},addLog:n=>{i.current.addLog(n)},onReady(n){n()},setOptions:n=>{i.current.setOptions(n)}},a)}class cc{constructor(){this.dep=new Map}subscribe(r,e){const i=this.dep.get(r);if(i){this.dep.set(r,i.concat(e));return}this.dep.set(r,[e])}notify(r,e){const i=this.dep.get(r);!r||!i||i.forEach(s=>{try{s(e)}catch(a){console.error(a)}})}}M.ONE_DAY=_s,M.ONE_HOUR=ws,M.ONE_KILO_BYTE=Yn,M.ONE_MINUTE=ys,M.ONE_SECOND=vs,M.ONE_YEAR=Rs,M.Observable=Hn,M.SDK_VERSION=Is,M.SLSClient=ic,M.Subscribe=cc,M.assembleOTAttribute=zt,M.buildHttpInfo=co,M.callMonitored=qt,M.catchUserErrors=mi,M.clocksNow=fo,M.clocksOrigin=mo,M.computeStackTrace=Gt,M.createHandlingStack=No,M.currentDrift=po,M.debugLog=ms,M.defineGlobal=Bn,M.defineGlobalValue=ur,M.elapsed=So,M.formatErrorMessage=Vs,M.formatUnknownError=Mo,M.genUid=Ts,M.generateSpanId=mr,M.generateTraceId=Us,M.generateUUID=fi,M.getB3Header=vi,M.getConsoleLogStatus=$n,M.getCorrectedTimeStamp=Cs,M.getJaegerTraceHeaderr=wi,M.getRelativeTime=bo,M.getTimeStamp=Ns,M.getTrackUrl=Ps,M.getW3CTraceHeader=yi,M.includes=to,M.instrumentMethod=Os,M.instrumentMethodAndCallOriginal=lr,M.isError=eo,M.isInternalUrl=so,M.isNumber=Es,M.isString=Zn,M.isURL=no,M.looksLikeRelativeTime=vo,M.makeWebPublicApi=oc,M.matchCondition=uo,M.matchSample=ro,M.matchWithDefault=io,M.monitor=Fn,M.noop=Qn,M.parseUri=oo,M.patchHeaderOnRequest=Vo,M.patchHeaderOnXhr=Do,M.relativeNow=Ms,M.relativeToClocks=lo,M.resetNavigationStart=yo,M.round=As,M.shouldTrackBody=ho,M.startUnhandledErrorCollection=Po,M.timeStampNow=hr,M.toServerDuration=go,M.toStackTraceString=dr;var uc=class{constructor(t){this.timer=null,this.time=10,this.count=10,this.arr=[];var r,e;this.time=(r=t.time)!=null?r:10,this.count=(e=t.count)!=null?e:10,this.url="https://"+t.project+"."+t.host+"/logstores/"+t.logstore+"/track",this.opt=t,t.installUnloadHook&&typeof t.installUnloadHook=="function"&&t.installUnloadHook(()=>{this.sendImmediateInner()})}assemblePayload(t=this.arr){const r={__logs__:t};return this.opt.tags&&(r.__tags__=this.opt.tags),this.opt.topic&&(r.__topic__=this.opt.topic),this.opt.source&&(r.__source__=this.opt.source),JSON.stringify(r)}platformSend(){if(this.opt.sendPayload&&typeof this.opt.sendPayload=="function"){const t=this.assemblePayload();this.opt.sendPayload(this.url,t)}}transString(t){let r={};for(let e in t)typeof t[e]=="object"?r[e]=JSON.stringify(t[e]):r[e]=String(t[e]);return r}sendImmediateInner(){this.arr&&this.arr.length>0&&(this.platformSend(),this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.arr=[])}sendInner(){if(this.timer)this.arr.length>=this.count&&(clearTimeout(this.timer),this.timer=null,this.sendImmediateInner());else{const t=this;this.arr.length>=this.count||this.time<=0?this.sendImmediateInner():this.timer=setTimeout(function(){t.sendImmediateInner()},this.time*1e3)}}send(t){const r=this.transString(t);this.arr.push(r),this.sendInner()}sendImmediate(t){const r=this.transString(t);this.arr.push(r),this.sendImmediateInner()}sendBatchLogs(t){const r=t.map(e=>this.transString(e));this.arr.push(...r),this.sendInner()}sendBatchLogsImmediate(t){const r=t.map(e=>this.transString(e));this.arr.push(...r),this.sendImmediateInner()}},hc=M,lc=uc;function dc(t,r){return navigator&&navigator.sendBeacon?navigator.sendBeacon(`${t}?APIVersion=0.6.0`,r):!1}function pc(t,r){const e=new window.XMLHttpRequest;e.open("POST",t,!0),e.setRequestHeader("x-log-apiversion","0.6.0"),e.setRequestHeader("x-log-bodyrawsize",r.length.toString());const i=new Blob([r],{type:"application/x-protobuf"});e.send(i)}function gc(t,r){try{dc(t,r)||pc(t,r)}catch(e){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
|
|
9
|
-
`+e),console.error("Failed log data:",t))}}class qs extends lc{constructor(r){const e=Object.assign({},r,{installUnloadHook:i=>{window.addEventListener("beforeunload",()=>{i()})},sendPayload:(i,s)=>{gc(i,s)}});super(e)}}hc.defineGlobal(window,"SLS_Tracker",qs);var fc=qs,Ri={},mc={get exports(){return Ri},set exports(t){Ri=t}};(function(t,r){(function(e,i){var s="1.0.35",a="",n="?",o="function",c="undefined",h="object",f="string",p="major",u="model",g="name",m="type",d="vendor",S="version",b="architecture",w="console",_="mobile",R="tablet",x="smarttv",z="wearable",j="embedded",O=350,ie="Amazon",Ae="Apple",ut="ASUS",pe="BlackBerry",ge="Browser",Re="Chrome",qe="Edge",Ze="Firefox",et="Google",Ve="Huawei",Me="LG",He="Microsoft",Te="Motorola",be="Opera",ve="Samsung",Je="Sharp",Z="Sony",fe="Xiaomi",Ge="Zebra",Yt="Facebook",Mt="Chromium OS",Qt="Mac OS",_t=function(K,Y){var F={};for(var ee in K)Y[ee]&&Y[ee].length%2===0?F[ee]=Y[ee].concat(K[ee]):F[ee]=K[ee];return F},ht=function(K){for(var Y={},F=0;F<K.length;F++)Y[K[F].toUpperCase()]=K[F];return Y},Zt=function(K,Y){return typeof K===f?ei(Y).indexOf(ei(K))!==-1:!1},ei=function(K){return K.toLowerCase()},Jc=function(K){return typeof K===f?K.replace(/[^\d\.]/g,a).split(".")[0]:i},Ir=function(K,Y){if(typeof K===f)return K=K.replace(/^\s\s*/,a),typeof Y===c?K:K.substring(0,O)},ti=function(K,Y){for(var F=0,ee,lt,ze,X,U,tt;F<Y.length&&!U;){var Ar=Y[F],da=Y[F+1];for(ee=lt=0;ee<Ar.length&&!U&&Ar[ee];)if(U=Ar[ee++].exec(K),U)for(ze=0;ze<da.length;ze++)tt=U[++lt],X=da[ze],typeof X===h&&X.length>0?X.length===2?typeof X[1]==o?this[X[0]]=X[1].call(this,tt):this[X[0]]=X[1]:X.length===3?typeof X[1]===o&&!(X[1].exec&&X[1].test)?this[X[0]]=tt?X[1].call(this,tt,X[2]):i:this[X[0]]=tt?tt.replace(X[1],X[2]):i:X.length===4&&(this[X[0]]=tt?X[3].call(this,tt.replace(X[1],X[2])):i):this[X]=tt||i;F+=2}},Er=function(K,Y){for(var F in Y)if(typeof Y[F]===h&&Y[F].length>0){for(var ee=0;ee<Y[F].length;ee++)if(Zt(Y[F][ee],K))return F===n?i:F}else if(Zt(Y[F],K))return F===n?i:F;return K},Gc={"1.0":"/8","1.2":"/1","1.3":"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"},ha={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"},la={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[S,[g,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[S,[g,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[g,S],[/opios[\/ ]+([\w\.]+)/i],[S,[g,be+" Mini"]],[/\bopr\/([\w\.]+)/i],[S,[g,be]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[g,S],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[S,[g,"UC"+ge]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[S,[g,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[S,[g,"WeChat"]],[/konqueror\/([\w\.]+)/i],[S,[g,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[S,[g,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[S,[g,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[g,/(.+)/,"$1 Secure "+ge],S],[/\bfocus\/([\w\.]+)/i],[S,[g,Ze+" Focus"]],[/\bopt\/([\w\.]+)/i],[S,[g,be+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[S,[g,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[S,[g,"Dolphin"]],[/coast\/([\w\.]+)/i],[S,[g,be+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[S,[g,"MIUI "+ge]],[/fxios\/([-\w\.]+)/i],[S,[g,Ze]],[/\bqihu|(qi?ho?o?|360)browser/i],[[g,"360 "+ge]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[g,/(.+)/,"$1 "+ge],S],[/(comodo_dragon)\/([\w\.]+)/i],[[g,/_/g," "],S],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[g,S],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[g],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[g,Yt],S],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[g,S],[/\bgsa\/([\w\.]+) .*safari\//i],[S,[g,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[S,[g,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[S,[g,Re+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[g,Re+" WebView"],S],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[S,[g,"Android "+ge]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[g,S],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[S,[g,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[S,g],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[g,[S,Er,Gc]],[/(webkit|khtml)\/([\w\.]+)/i],[g,S],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[g,"Netscape"],S],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[S,[g,Ze+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[g,S],[/(cobalt)\/([\w\.]+)/i],[g,[S,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[b,"amd64"]],[/(ia32(?=;))/i],[[b,ei]],[/((?:i[346]|x)86)[;\)]/i],[[b,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[b,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[b,"armhf"]],[/windows (ce|mobile); ppc;/i],[[b,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[b,/ower/,a,ei]],[/(sun4\w)[;\)]/i],[[b,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[b,ei]]],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],[u,[d,ve],[m,R]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[u,[d,ve],[m,_]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[u,[d,Ae],[m,_]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[u,[d,Ae],[m,R]],[/(macintosh);/i],[u,[d,Ae]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[u,[d,Je],[m,_]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[u,[d,Ve],[m,R]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[u,[d,Ve],[m,_]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[u,/_/g," "],[d,fe],[m,_]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[u,/_/g," "],[d,fe],[m,R]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[u,[d,"OPPO"],[m,_]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[u,[d,"Vivo"],[m,_]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[u,[d,"Realme"],[m,_]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[u,[d,Te],[m,_]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[u,[d,Te],[m,R]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[u,[d,Me],[m,R]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[u,[d,Me],[m,_]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[u,[d,"Lenovo"],[m,R]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[u,/_/g," "],[d,"Nokia"],[m,_]],[/(pixel c)\b/i],[u,[d,et],[m,R]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[u,[d,et],[m,_]],[/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],[u,[d,Z],[m,_]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[u,"Xperia Tablet"],[d,Z],[m,R]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[u,[d,"OnePlus"],[m,_]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[u,[d,ie],[m,R]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[u,/(.+)/g,"Fire Phone $1"],[d,ie],[m,_]],[/(playbook);[-\w\),; ]+(rim)/i],[u,d,[m,R]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[u,[d,pe],[m,_]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[u,[d,ut],[m,R]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[u,[d,ut],[m,_]],[/(nexus 9)/i],[u,[d,"HTC"],[m,R]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[d,[u,/_/g," "],[m,_]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[u,[d,"Acer"],[m,R]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[u,[d,"Meizu"],[m,_]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[d,u,[m,_]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[d,u,[m,R]],[/(surface duo)/i],[u,[d,He],[m,R]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[u,[d,"Fairphone"],[m,_]],[/(u304aa)/i],[u,[d,"AT&T"],[m,_]],[/\bsie-(\w*)/i],[u,[d,"Siemens"],[m,_]],[/\b(rct\w+) b/i],[u,[d,"RCA"],[m,R]],[/\b(venue[\d ]{2,7}) b/i],[u,[d,"Dell"],[m,R]],[/\b(q(?:mv|ta)\w+) b/i],[u,[d,"Verizon"],[m,R]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[u,[d,"Barnes & Noble"],[m,R]],[/\b(tm\d{3}\w+) b/i],[u,[d,"NuVision"],[m,R]],[/\b(k88) b/i],[u,[d,"ZTE"],[m,R]],[/\b(nx\d{3}j) b/i],[u,[d,"ZTE"],[m,_]],[/\b(gen\d{3}) b.+49h/i],[u,[d,"Swiss"],[m,_]],[/\b(zur\d{3}) b/i],[u,[d,"Swiss"],[m,R]],[/\b((zeki)?tb.*\b) b/i],[u,[d,"Zeki"],[m,R]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[d,"Dragon Touch"],u,[m,R]],[/\b(ns-?\w{0,9}) b/i],[u,[d,"Insignia"],[m,R]],[/\b((nxa|next)-?\w{0,9}) b/i],[u,[d,"NextBook"],[m,R]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[d,"Voice"],u,[m,_]],[/\b(lvtel\-)?(v1[12]) b/i],[[d,"LvTel"],u,[m,_]],[/\b(ph-1) /i],[u,[d,"Essential"],[m,_]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[u,[d,"Envizen"],[m,R]],[/\b(trio[-\w\. ]+) b/i],[u,[d,"MachSpeed"],[m,R]],[/\btu_(1491) b/i],[u,[d,"Rotor"],[m,R]],[/(shield[\w ]+) b/i],[u,[d,"Nvidia"],[m,R]],[/(sprint) (\w+)/i],[d,u,[m,_]],[/(kin\.[onetw]{3})/i],[[u,/\./g," "],[d,He],[m,_]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[u,[d,Ge],[m,R]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[u,[d,Ge],[m,_]],[/smart-tv.+(samsung)/i],[d,[m,x]],[/hbbtv.+maple;(\d+)/i],[[u,/^/,"SmartTV"],[d,ve],[m,x]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[d,Me],[m,x]],[/(apple) ?tv/i],[d,[u,Ae+" TV"],[m,x]],[/crkey/i],[[u,Re+"cast"],[d,et],[m,x]],[/droid.+aft(\w)( bui|\))/i],[u,[d,ie],[m,x]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[u,[d,Je],[m,x]],[/(bravia[\w ]+)( bui|\))/i],[u,[d,Z],[m,x]],[/(mitv-\w{5}) bui/i],[u,[d,fe],[m,x]],[/Hbbtv.*(technisat) (.*);/i],[d,u,[m,x]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[d,Ir],[u,Ir],[m,x]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[m,x]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[d,u,[m,w]],[/droid.+; (shield) bui/i],[u,[d,"Nvidia"],[m,w]],[/(playstation [345portablevi]+)/i],[u,[d,Z],[m,w]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[u,[d,He],[m,w]],[/((pebble))app/i],[d,u,[m,z]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[u,[d,Ae],[m,z]],[/droid.+; (glass) \d/i],[u,[d,et],[m,z]],[/droid.+; (wt63?0{2,3})\)/i],[u,[d,Ge],[m,z]],[/(quest( 2| pro)?)/i],[u,[d,Yt],[m,z]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[d,[m,j]],[/(aeobc)\b/i],[u,[d,ie],[m,j]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[u,[m,_]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[u,[m,R]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[m,R]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[m,_]],[/(android[-\w\. ]{0,9});.+buil/i],[u,[d,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[S,[g,qe+"HTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[S,[g,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[g,S],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[S,g]],os:[[/microsoft (windows) (vista|xp)/i],[g,S],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[g,[S,Er,ha]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[g,"Windows"],[S,Er,ha]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/ios;fbsv\/([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[S,/_/g,"."],[g,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[g,Qt],[S,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[S,g],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[g,S],[/\(bb(10);/i],[S,[g,pe]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[S,[g,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[S,[g,Ze+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[S,[g,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[S,[g,"watchOS"]],[/crkey\/([\d\.]+)/i],[S,[g,Re+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[g,Mt],S],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[g,S],[/(sunos) ?([\w\.\d]*)/i],[[g,"Solaris"],S],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[g,S]]},Fe=function(K,Y){if(typeof K===h&&(Y=K,K=i),!(this instanceof Fe))return new Fe(K,Y).getResult();var F=typeof e!==c&&e.navigator?e.navigator:i,ee=K||(F&&F.userAgent?F.userAgent:a),lt=F&&F.userAgentData?F.userAgentData:i,ze=Y?_t(la,Y):la,X=F&&F.userAgent==ee;return this.getBrowser=function(){var U={};return U[g]=i,U[S]=i,ti.call(U,ee,ze.browser),U[p]=Jc(U[S]),X&&F&&F.brave&&typeof F.brave.isBrave==o&&(U[g]="Brave"),U},this.getCPU=function(){var U={};return U[b]=i,ti.call(U,ee,ze.cpu),U},this.getDevice=function(){var U={};return U[d]=i,U[u]=i,U[m]=i,ti.call(U,ee,ze.device),X&&!U[m]&<&<.mobile&&(U[m]=_),X&&U[u]=="Macintosh"&&F&&typeof F.standalone!==c&&F.maxTouchPoints&&F.maxTouchPoints>2&&(U[u]="iPad",U[m]=R),U},this.getEngine=function(){var U={};return U[g]=i,U[S]=i,ti.call(U,ee,ze.engine),U},this.getOS=function(){var U={};return U[g]=i,U[S]=i,ti.call(U,ee,ze.os),X&&!U[g]&<&<.platform!="Unknown"&&(U[g]=lt.platform.replace(/chrome os/i,Mt).replace(/macos/i,Qt)),U},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 ee},this.setUA=function(U){return ee=typeof U===f&&U.length>O?Ir(U,O):U,this},this.setUA(ee),this};Fe.VERSION=s,Fe.BROWSER=ht([g,S,p]),Fe.CPU=ht([b]),Fe.DEVICE=ht([u,d,m,w,_,x,R,z,j]),Fe.ENGINE=Fe.OS=ht([g,S]),t.exports&&(r=t.exports=Fe),r.UAParser=Fe;var Nt=typeof e!==c&&(e.jQuery||e.Zepto);if(Nt&&!Nt.ua){var ki=new Fe;Nt.ua=ki.getResult(),Nt.ua.get=function(){return ki.getUA()},Nt.ua.set=function(K){ki.setUA(K);var Y=ki.getResult();for(var F in Y)Nt.ua[F]=Y[F]}}})(typeof window=="object"?window:Vn)})(mc,Ri);let Ii;const Sc=new Uint8Array(16);function bc(){if(!Ii&&(Ii=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Ii))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ii(Sc)}const de=[];for(let t=0;t<256;++t)de.push((t+256).toString(16).slice(1));function vc(t,r=0){return(de[t[r+0]]+de[t[r+1]]+de[t[r+2]]+de[t[r+3]]+"-"+de[t[r+4]]+de[t[r+5]]+"-"+de[t[r+6]]+de[t[r+7]]+"-"+de[t[r+8]]+de[t[r+9]]+"-"+de[t[r+10]]+de[t[r+11]]+de[t[r+12]]+de[t[r+13]]+de[t[r+14]]+de[t[r+15]]).toLowerCase()}const yc=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Js={randomUUID:yc};function wc(t,r,e){if(Js.randomUUID&&!r&&!t)return Js.randomUUID();t=t||{};const i=t.random||(t.rng||bc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,r){e=e||0;for(let s=0;s<16;++s)r[e+s]=i[s];return r}return vc(i)}var Sr={},_c={get exports(){return Sr},set exports(t){Sr=t}},br={},Rc={get exports(){return br},set exports(t){br=t}};(function(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r={rotl:function(e,i){return e<<i|e>>>32-i},rotr:function(e,i){return e<<32-i|e>>>i},endian:function(e){if(e.constructor==Number)return r.rotl(e,8)&16711935|r.rotl(e,24)&4278255360;for(var i=0;i<e.length;i++)e[i]=r.endian(e[i]);return e},randomBytes:function(e){for(var i=[];e>0;e--)i.push(Math.floor(Math.random()*256));return i},bytesToWords:function(e){for(var i=[],s=0,a=0;s<e.length;s++,a+=8)i[a>>>5]|=e[s]<<24-a%32;return i},wordsToBytes:function(e){for(var i=[],s=0;s<e.length*32;s+=8)i.push(e[s>>>5]>>>24-s%32&255);return i},bytesToHex:function(e){for(var i=[],s=0;s<e.length;s++)i.push((e[s]>>>4).toString(16)),i.push((e[s]&15).toString(16));return i.join("")},hexToBytes:function(e){for(var i=[],s=0;s<e.length;s+=2)i.push(parseInt(e.substr(s,2),16));return i},bytesToBase64:function(e){for(var i=[],s=0;s<e.length;s+=3)for(var a=e[s]<<16|e[s+1]<<8|e[s+2],n=0;n<4;n++)s*8+n*6<=e.length*8?i.push(t.charAt(a>>>6*(3-n)&63)):i.push("=");return i.join("")},base64ToBytes:function(e){e=e.replace(/[^A-Z0-9+\/]/ig,"");for(var i=[],s=0,a=0;s<e.length;a=++s%4)a!=0&&i.push((t.indexOf(e.charAt(s-1))&Math.pow(2,-2*a+8)-1)<<a*2|t.indexOf(e.charAt(s))>>>6-a*2);return i}};Rc.exports=r})();var vr={utf8:{stringToBytes:function(t){return vr.bin.stringToBytes(unescape(encodeURIComponent(t)))},bytesToString:function(t){return decodeURIComponent(escape(vr.bin.bytesToString(t)))}},bin:{stringToBytes:function(t){for(var r=[],e=0;e<t.length;e++)r.push(t.charCodeAt(e)&255);return r},bytesToString:function(t){for(var r=[],e=0;e<t.length;e++)r.push(String.fromCharCode(t[e]));return r.join("")}}},Gs=vr;/*!
|
|
1
|
+
var Rc=Object.defineProperty,Ic=Object.defineProperties;var Ec=Object.getOwnPropertyDescriptors;var mi=Object.getOwnPropertySymbols,Ac=Object.getPrototypeOf,Zs=Object.prototype.hasOwnProperty,ea=Object.prototype.propertyIsEnumerable,Tc=Reflect.get;var mr=(P,D,x)=>D in P?Rc(P,D,{enumerable:!0,configurable:!0,writable:!0,value:x}):P[D]=x,W=(P,D)=>{for(var x in D||(D={}))Zs.call(D,x)&&mr(P,x,D[x]);if(mi)for(var x of mi(D))ea.call(D,x)&&mr(P,x,D[x]);return P},_t=(P,D)=>Ic(P,Ec(D));var ta=(P,D)=>{var x={};for(var X in P)Zs.call(P,X)&&D.indexOf(X)<0&&(x[X]=P[X]);if(P!=null&&mi)for(var X of mi(P))D.indexOf(X)<0&&ea.call(P,X)&&(x[X]=P[X]);return x};var p=(P,D,x)=>(mr(P,typeof D!="symbol"?D+"":D,x),x);var Sr=(P,D,x)=>Tc(Ac(P),x,D);var v=(P,D,x)=>new Promise((X,$t)=>{var Si=Le=>{try{Be(x.next(Le))}catch(ot){$t(ot)}},bi=Le=>{try{Be(x.throw(Le))}catch(ot){$t(ot)}},Be=Le=>Le.done?X(Le.value):Promise.resolve(Le.value).then(Si,bi);Be((x=x.apply(P,D)).next())});(function(P,D){typeof exports=="object"&&typeof module!="undefined"?D(exports,require("aliyun-rts-sdk"),require("useragent-util"),require("eventemitter3"),require("browser-log-reporter")):typeof define=="function"&&define.amd?define(["exports","aliyun-rts-sdk","useragent-util","eventemitter3","browser-log-reporter"],D):(P=typeof globalThis!="undefined"?globalThis:P||self,D(P.AliRtcEngine={},P.AliyunRts,P.UserAgentUtil,P.EventEmitter,P.BrowserLogReporter))})(this,function(P,D,x,X,$t){var _e,rt,Te,vt,L,zs;"use strict";var Si=Object.defineProperty,bi=(i,a,e)=>a in i?Si(i,a,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[a]=e,Be=(i,a,e)=>(bi(i,typeof a!="symbol"?a+"":a,e),e),Le={exports:{}},ot={exports:{}},vi,br;function Se(){if(br)return vi;br=1,Date.now=Date.now||function(){return new Date().getTime()};var i=Date.now(),a=function(){},e=function(){var r=typeof console=="object"?console.warn:a;try{var s={warn:r};s.warn.call(s)}catch(n){return a}return r},t={noop:a,warn:e(),key:"__bl",selfErrKey:"ARMS_SDK_ERROR",selfErrPage:"ARMSSDK",win:typeof window=="object"&&window.document?window:void 0,regionMap:{cn:"https://arms-retcode.aliyuncs.com/r.png?",sg:"https://arms-retcode-sg.aliyuncs.com/r.png?",sg_2:"https://retcode-sg-lazada.arms.aliyuncs.com/r.png?",daily:"http://arms-retcode-daily.alibaba.net/r.png?",daily_2:"https://arms-retcode-daily.alibaba.net/r.png?",daily_3:"http://arms-retcode-daily.aliyun.test/r.png?",us:"https://retcode-us-west-1.arms.aliyuncs.com/r.png?",tw:"https://arms-retcode.orientalgame.com.tw/r.png?",tw_sg:"https://arms-retcode-sg.orientalgame.com.tw/r.png?",hz_finance:"https://arms-retcode-hz-finance.aliyuncs.com/r.png?"},defaultImgUrl:"https://arms-retcode.aliyuncs.com/r.png?",createObject:function(r){if(Object.create)return Object.create(r);var s=function(){};return s.prototype=r,new s},each:function(r,s){var n=0,o=r.length;if(this.T(r,"Array"))for(;n<o&&s.call(r[n],r[n],n)!==!1;n++);else for(n in r)if(s.call(r[n],r[n],n)===!1)break;return r},safetyCall:function(r,s,n){if(typeof r!="function")return n;try{return r.apply(this,s)}catch(o){return n}},T:function(r,s){var n=Object.prototype.toString.call(r).substring(8).replace("]","");return s?n===s:n},duration:function(){var r=Date;try{performance&&this.T(performance.now,"Function")&&(r=performance)}catch(n){r=Date}var s=r.now();return function(){return Math.round(r.now()-s)}},filterByRule:function(){var r=[].slice.call(arguments),s=r.length;if(s<2)return r[0];var n=r[s-1],o=r[0];if(!o)return"";if(!n)return o;var c=this,u=c.T(n),h=r.slice(0,s-1);return u==="Function"?c.safetyCall(n,h,o):u==="Array"?(this.each(n,function(l){h[0]=o=c.filterByRule.apply(c,[].concat(h,l))}),o):u==="Object"?o.replace(n.rule,n.target||""):o.replace(n,"")},ignoreByRule:function(r,s){if(!r||!s)return!1;if((this.isString(s)||s.source||this.T(s)==="Function")&&(s=[s]),!this.isArray(s))return this.warn("[arms] invalid rules of ignore config, (list of) String/RegExp/Funcitons are available"),!1;for(var n,o=[],c=0,u=s.length;c<u;c++)if(n=s[c],this.isString(n))o.push(n.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1"));else if(n&&n.source)o.push(n.source);else if(n&&this.T(n)==="Function"&&this.safetyCall(n,[r],!1)===!0)return!0;var h=new RegExp(o.join("|"),"i");return!!(o.length&&h.test&&h.test(r))},J:function(r){if(!r||typeof r!="string")return r;var s=null;try{s=JSON.parse(r)}catch(n){}return s},pick:function(r){return r===1||Math.ceil(Math.random()*r)===1},verifyConfig:function(r){if("sample"in r){var s=r.sample,n=s;s&&/^\d+(\.\d+)?%$/.test(s)&&(n=parseInt(100/parseFloat(s))),0<n&&1>n&&(n=parseInt(1/n)),n>=1&&n<=100?r.sample=n:delete r.sample}return r},on:function(r,s,n,o,c){return r.addEventListener?(c=c||!1,r.addEventListener(s,function u(h){o&&r.removeEventListener(s,u,c),n.call(this,h)},c)):r.attachEvent&&r.attachEvent("on"+s,function u(h){o&&r.detachEvent("on"+s,u),n.call(this,h)}),this},off:function(r,s,n){return n?(r.removeEventListener?r.removeEventListener(s,n):r.detachEvent&&r.detachEvent(s,n),this):this},delay:function(r,s){return s===-1?(r(),null):setTimeout(r,s||0)},ext:function(r){for(var s=1,n=arguments.length;s<n;s++){var o=arguments[s];for(var c in o)Object.prototype.hasOwnProperty.call(o,c)&&(r[c]=o[c])}return r},sub:function(r,s){var n={};return this.each(r,function(o,c){s.indexOf(c)!==-1&&(n[c]=o)}),n},uu:function(){for(var r,s,n=20,o=new Array(n),c=Date.now().toString(36).split("");n-- >0;)s=(r=36*Math.random()|0).toString(36),o[n]=r%3?s:s.toUpperCase();for(var u=0;u<8;u++)o.splice(3*u+2,0,c[u]);return o.join("")},guid:function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){var s=16*Math.random()|0;return(r==="x"?s:3&s|8).toString(16)})},seq:function(){return(i++).toString(36)},decode:function(r){try{r=decodeURIComponent(r)}catch(s){}return r},encode:function(r,s){try{r=s?encodeURIComponent(r).replace(/\(/g,"%28").replace(/\)/g,"%29"):encodeURIComponent(r)}catch(n){}return r},serialize:function(r){r=r||{};var s=[];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&r[n]!==void 0&&s.push(n+"="+this.encode(r[n],n==="msg"));return s.join("&")},checkAPI:function(r,s){if(!r||typeof r!="string")return!1;var n=/arms-retcode[\w-]*\.aliyuncs/.test(r);return!n&&s&&(n=/(alicdn\.com)|(mmstat\.com)/.test(r)),!n},checkAutoError:function(r){return!(!r||!r.message)&&!/failed[\w\s]+fetch/i.test(r.message)},cutUrlSearch:function(r){return r&&typeof r=="string"?r.replace(/^(https?:)?\/\//,"").replace(/\?.*$/,""):""},removeUrlSearch:function(r){return r&&typeof r=="string"?r.replace(/\?.*$/,""):""},createFakeToString:function(r){return function(){return r+"() { [native code] }"}},checkSameOrigin:function(r,s){if(!s||!r)return!1;var n="//"+s.split("/")[2];return r===s||r.slice(0,s.length+1)===s+"/"||r===n||r.slice(0,n.length+1)===n+"/"||!/^(\/\/|http:|https:).*/.test(r)},getRandIP:function(){for(var r=[],s=0;s<4;s++){var n=Math.floor(256*Math.random());r[s]=(n>15?"":"0")+n.toString(16)}return r.join("").replace(/^0/,"1")},getSortNum:function(r){return r?(r+=1)>=1e3&&r<=9999?r:r<1e3?r+1e3:r%1e4+1e3:1e3},getRandNum:function(r){return r&&typeof r=="string"?r.length<5?this.getNum(5):r.substring(r.length-5):this.getNum(5)},getNum:function(r){for(var s=[],n=0;n<r;n++){var o=Math.floor(16*Math.random());s[n]=o.toString(16)}return s.join("")},getCurDomain:function(){return location&&location.hostname||""},getSrcType:function(r,s){var n=location&&location.host||"";if(!n)return"";var o=new URL(r).host;if(o===n)return"self";for(var c=0;c<s.length;c+=1)if(o.includes(s[c]))return"cdn";return"others"},parseFetchHeaders:function(r){if(!r)return{};var s={};try{if(typeof r.keys=="function")for(var n=r.keys(),o=n.next();!o.done;){var c=o.value;s[c]=r.get(c),o=n.next()}else s=r}catch(u){s={}}return s},parseXhrHeaders:function(r){if(!r&&typeof r!="string")return{};var s={};try{var n=r.split(`\r
|
|
2
|
+
`);s=n.reduce(function(o,c){var u=c.split(": ");return o[u[0]]=u[1],o},{})}catch(o){s={}}return s},getQuerys:function(r){if(!r)return"";var s={},n=[],o="",c="";try{var u=[];if(r.indexOf("?")>=0&&(u=r.substring(r.indexOf("?")+1,r.length).split("&")),u.length>0)for(var h in u)o=(n=u[h].split("="))[0],c=n[1],s[o]=c}catch(l){s={}}return s},getURL:function(r){if(!r)return null;var s={},n=r.length,o=r.indexOf("://");if(o<0)return null;s.protocol=r.substring(0,o+1);var c=r.indexOf("#"),u=r.indexOf("?");c<0&&(c=n),u<0&&(u=c),s.search=r.substring(u,c).substring(0,1e3);var h=r.substring(o+3,u),l=h.indexOf("/");return l<0&&(l=h.length),s.domain=h.substring(0,l).split(":")[0],s.path=h.substring(l,h.length).substring(0,1e3),s},getResType:function(r,s){if(["script","img","other"].indexOf(r)>-1)return r;if(["video"].indexOf(r)>-1)return"media";if(["document","iframe"].indexOf(r)>-1)return"doc";var n=s?this.getURL(s):null,o=n&&n.path?n.path.lastIndexOf("."):-1,c=(o>0?n.path.substr(o+1):"").toLowerCase();if(c){if(["eot","woff","woff2","ttf"].indexOf(c)>-1)return"font";if(c==="css")return"css";if(c==="js")return"script"}return["fetch","xmlhttprequest","beacon"].indexOf(r)>-1?"api":"others"},areInOrder:function(){for(var r=1;r<arguments.length;r+=1)if(arguments[r-1]>arguments[r])return!1;return!0},getFetchSnapshot:function(r,s,n){var o,c;try{var u=(r&&typeof r[0]!="string"?r[0].url:r[0])||"",h=(r&&typeof r[0]!="string"?r[0]:r[1])||{},l=h.method.toUpperCase()==="POST"?h.body:this.getQuerys(u);o={originApi:u,method:h.method||"unknown",params:l,response:s||"",reqHeaders:this.parseFetchHeaders(h.headers||null),resHeaders:this.parseFetchHeaders(n)},c=JSON&&JSON.stringify(o)||"{}"}catch(d){c="{}"}return c},getXhrSnapshot:function(r,s,n){if(!r||!s||!n)return{};var o,c;try{var u="";n.responseType===""||n.responseType==="text"?u=n.responseText:n.responseType==="document"&&(u=n.responseXML),o={originApi:r,method:s,params:this.getQuerys(r),response:u,reqHeaders:{},resHeaders:this.parseXhrHeaders(typeof n.getAllResponseHeaders=="function"&&n.getAllResponseHeaders()||"")},c=JSON&&JSON.stringify(o)||"{}"}catch(h){c="{}"}return c},isRobot:function(){var r=["nuhk","googlebot/","googlebot-image","yammybot","openbot","slurp","msnbot","ask jeeves/teoma","ia_archiver","baiduspider","bingbot/","adsbot"];if(!navigator||typeof navigator.userAgent!="string")return!1;try{for(var s=navigator.userAgent.toLowerCase(),n=0;n<r.length;n++){var o=r[n];if(s.lastIndexOf(o)>=0)return!0}}catch(c){this.warn("[arms] useragent parse error")}return!1},isFunction:function(r){return typeof r=="function"},isPlainObject:function(r){return Object.prototype.toString.call(r)==="[object Object]"},isString:function(r){return Object.prototype.toString.call(r)==="[object String]"},isArray:function(r){return Object.prototype.toString.call(r)==="[object Array]"},joinRegExp:function(r){for(var s,n=[],o=0,c=r.length;o<c;o++)s=r[o],this.isString(s)?n.push(s.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")):s&&s.source&&n.push(s.source);return new RegExp(n.join("|"),"i")},reWriteMethod:function(r,s,n){if(r!==null){var o=r[s];r[s]=n(o)}},checkSDKError:function(r,s){return!r&&!s?!1:new RegExp(this.selfErrKey,"i").test(r)?!0:!!this.ignoreByRule(s,[/retcode.alicdn.com\/retcode\/bl.js/,/g.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/laz-g-cdn.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/local.taobao.com:8880\/build\/bl/])},sdkError:function(r){return{msg:r,message:this.selfErrKey}},dealParam:function(r,s,n){var o={};try{o=this.isPlainObject(r)?this.ext({key:r.key||"default",val:r.val||r.value||n},r,{begin:Date.now()}):{key:r||"default",val:s||n,begin:Date.now()}}catch(c){this.warn("[retcode] baseLog error: "+c)}return o}};return vi=t,vi}var yi={exports:{}},wi={exports:{}},_i,vr;function ia(){if(vr)return _i;vr=1;var i=Se();return _i=function(a,e,t){typeof a=="object"&&(a=i.serialize(a));var r=e+a+(t?"&post_res=":"");window&&window.navigator&&typeof window.navigator.sendBeacon=="function"?window.navigator.sendBeacon(r,t||"&post_res="):i.warn("[arms] navigator.sendBeacon not surported")},_i}var yr;function ra(){if(yr)return wi.exports;yr=1;var i=Se(),a=ia(),e="aokcdqn3ly@e629dabd48a9933",t=function(s,n){var o;if(n.t==="error"&&(o=s.requestQueue[0])&&o.t==="error"&&n.msg===o.msg)return n.times=o.times+1,void(s.requestQueue[0]=n);if(n.t==="behavior"){var c=s.requestQueue&&s.requestQueue.length;if(c>0&&s.requestQueue[c-1].t==="behavior"){var u=n.behavior||[];s.requestQueue[c-1].behavior.concat(u)}else s.requestQueue.push(n)}else s.requestQueue.unshift(n);return s.onReady(function(){s.requestTimmer=i.delay(function(){s.clear()},s.requestQueue[0]&&s.requestQueue[0].t==="error"?3e3:-1)}),!0},r=function(s){return this.ver="1.8.36-beta.12",this._conf=i.ext({},r.dftCon),this.sampleCache={},this.requestQueue=[],this.selfQueue=[],this.sdkFlag=!0,this.hash=i.seq(),this.resetPageview(),this.setConfig(s),this.rip=i.getRandIP(),this.record=999,this["EagleEye-TraceID"]=this.getTraceId()["EagleEye-TraceID"],this._common={},this};return r.dftCon={sample:1,pvSample:1,tag:"",imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",region:null,ignore:{ignoreUrls:[],ignoreApis:[],ignoreErrors:[/^Script error\.?$/],ignoreResErrors:[],ignoreResources:[/\/(bl|wl)(.debug)?.js$/]},release:void 0,environment:"prod",beforeReport:null,parseTraceId:null},r.prototype={constructor:r,onReady:function(s){return s()},getPage:function(){var s=this._conf.page;return i.safetyCall(s,[],s+"")},setPage:function(){},setConfig:function(s){s&&typeof s=="object"&&(i.verifyConfig(s),s=this.setImgUrl(s),this._conf=i.ext({},this._conf,s))},setImgUrl:function(s){var n=s.region,o=s.imgUrl;if(n){var c=i.regionMap[n];return s.imgUrl=c||i.defaultImgUrl,s}return o&&(s.imgUrl=o),s},checkImgUrl:function(){return!0},sendRequest:function(){},sendBeacon:function(s,n,o){a(s,n||this.getConfig("imgUrl"),o)},postData:function(){},commonInfo:function(){return{}},setCommonInfo:function(s){s&&typeof s=="object"&&(this._common=i.ext({},this._common,s))},resetPageview:function(){this.pageview=i.uu(),this.sBegin=Date.now()},getUsername:function(){if(this.username)return this.username;var s=this._conf,n=s&&s.setUsername;if(typeof n=="function")try{var o=n();typeof o=="string"&&(o=o.substr(0,40),this.username=o)}catch(c){i.warn("[arms] setUsername fail",c)}return this.username},getTraceId:function(){var s=this.rip,n=Date.now(),o=i.getSortNum(this.record),c=s+n+o+i.getRandNum(this._conf.pid);return this["EagleEye-TraceID"]=c,this.record=o,{"EagleEye-TraceID":c}},getUberTraceId:function(s){var n=this.rip,o=Date.now(),c=i.getSortNum(this.record),u=i.getRandNum(this._conf.pid),h=n+o+c+i.getNum(2)+u,l=h.substring(0,16);return s=s?"1":"0",h[0]==="0"&&(h[0]="1"),h[16]==="0"&&(h[16]="1"),{"uber-trace-id":h+":"+l+":0:"+s,traceId:h}},getB3TraceId:function(s){var n=this.rip,o=Date.now(),c=i.getSortNum(this.record),u=i.getRandNum(this._conf.pid),h=n+o+c+i.getNum(2)+u,l=h.substring(0,16);return s=s?"1":"0",h[0]==="0"&&(h[0]="1"),h[16]==="0"&&(h[16]="1"),{b3:h+"-"+l+"-"+s+"-0","X-B3-TraceId":h,"X-B3-ParentSpanId":"0","X-B3-SpanId":l,"X-B3-Sampled":s}},getPageviewId:function(){return{"EagleEye-SessionID":this.pageview}},getConfig:function(s){return s?this._conf[s]:i.ext({},this._conf)},sampling:function(s){return s===1||(typeof this.sampleCache[s]=="boolean"?this.sampleCache[s]:(this.sampleCache[s]=i.pick(s),this.sampleCache[s]))},clear:function(s){var n;clearTimeout(this.requestTimmer),this.requestTimmer=null;for(var o=this._conf&&typeof this._conf.sendRequest=="function";n=this.requestQueue.pop();)if(n.t==="res")this.postData(n,"res");else if(n.t==="error")this.postData(n,"err");else if(n.t==="api")this.postData(n,"apiSnapshot");else if(n.t==="behavior")this.postData(n,"behavior");else if(n.t==="health"&&!o&&window&&window.navigator&&typeof window.navigator.sendBeacon=="function")this.sendBeacon(n);else if(n.t==="resource"&&!o&&window&&window.navigator&&typeof window.navigator.sendBeacon=="function"){var c=JSON.stringify({resource:n.resource});delete n.resource,this.sendBeacon(n,null,c)}else n.t==="resource"?this.postData(n,"resource"):this.sendRequest(n);return s&&this.clearSelf(),this},clearSelf:function(){var s;for(clearTimeout(this.Timmer),this.Timmer=null;s=this.selfQueue.pop();)this.postData(s,"err");return this},_lg:function(s,n,o,c){var u=this,h=u._conf,l=u.getPage(),d=h.ignore||{},f=d.ignoreErrors,m=d.ignoreResErrors,g=d.ignoreUrls,S=d.ignoreApis;if(u._isRobot||i.ignoreByRule(l,g)||i.ignoreByRule(i.decode(l),g)||s==="error"&&(i.ignoreByRule(n.msg,f)||i.ignoreByRule(i.decode(n.msg),f))||s==="resourceError"&&(i.ignoreByRule(n.src,m)||i.ignoreByRule(i.decode(n.src),m))||s==="api"&&(i.ignoreByRule(n.api,S)||i.ignoreByRule(i.decode(n.api),S))||!u.checkImgUrl(h.imgUrl)||!n||h.disabled||!h.pid||c===0)return u;var b=n.dl;if(delete n.dl,n=i.ext({t:s,times:1,page:l,tag:h.tag||"",release:h.release||"",environment:h.environment,begin:Date.now(),c1:h.c1,c2:h.c2,c3:h.c3},n,u.commonInfo(),u._common,{pid:h.pid,_v:u.ver,pv_id:u.pageview,username:u.getUsername(),sampling:o||1,dl:b,z:i.seq()}),i.T(h.beforeReport)==="Function")try{if(!(n=h.beforeReport(n)))return u}catch(w){return u}return c===1?t(u,n):o&&!u.sampling(o)?u:t(u,n)},_self:function(s,n,o){var c=this,u=c._conf;if(s!=="error"||!c.checkImgUrl(u.imgUrl)||!n||u.disabled||!u.pid||!e||o&&!c.sampling(o))return c;n=i.ext({t:s,times:1,page:i.selfErrPage,tag:u.pid,begin:Date.now()},n,{pid:e,_v:c.ver,sampling:o||1,z:i.seq()});var h=c.selfQueue[0];if(h){h.times++;try{h.err&&n.err&&h.err.msg_raw&&n.err.msg_raw&&h.err.msg_raw.split("&").indexOf(n.err.msg_raw)<0&&h.err.msg_raw.length<1e3&&(h.err.msg_raw+="&"+n.err.msg_raw)}catch(l){}}else c.selfQueue.unshift(n),c.onReady(function(){c.sdkFlag&&(c.sdkFlag=!1,c.Timmer=i.delay(function(){c.clearSelf()},1e4))})},custom:function(s,n){if(!s||typeof s!="object")return this;var o=!1,c={begin:Date.now()};return i.each(s,function(u,h){return!(o=h&&h.length<=20)&&i.warn("[retcode] invalid key: "+h),c["x-"+h]=u,o}),o?this._lg("custom",c,n||1):this}},wi.exports=r,wi.exports}var wr;function sa(){if(wr)return yi.exports;wr=1;var i=Se(),a=ra(),e=["api","success","time","code","msg","trace","traceId","begin","pv_id","sid","seq","domain","flag","apiSnapshot","tag","c1","c2","c3"],t=function(s){var n=(s.key||"default").split("::");return n.length>1?i.ext(s,{group:n[0],key:n[1]}):i.ext(s,{group:"default_group",key:n[0]})},r=function(s){a.call(this,s);var n;try{n=typeof performance=="object"?performance.timing.fetchStart:Date.now()}catch(o){n=Date.now()}return this._startTime=n,this};return r.prototype=i.createObject(a.prototype),i.ext(a.dftCon,{startTime:null}),i.ext(r.prototype,{constructor:r,_super:a,sum:function(s,n,o){try{var c=i.dealParam(s,n,1);return this._lg("sum",t(c),o)}catch(u){i.warn("[retcode] can not get parseStatData: "+u)}},avg:function(s,n,o){try{var c=i.dealParam(s,n,0);return this._lg("avg",t(c),o)}catch(u){i.warn("[retcode] can not get parseStatData: "+u)}},percent:function(s,n,o,c){try{return this._lg("percent",t({key:s,subkey:n,val:o||0,begin:Date.now()}),c)}catch(u){i.warn("[retcode] can not get parseStatData: "+u)}},msg:function(s,n){if(s&&!(s.length>180))return this.custom({msg:s},n)},error:function(s,n){if(!s)return i.warn("[retcode] invalid param e: "+s),this;arguments.length===1?(typeof s=="string"&&(s={message:s},n={}),typeof s=="object"&&(n=s=s.error||s)):(typeof s=="string"&&(s={message:s}),typeof n!="object"&&(n={}));var o=s.name||"CustomError",c=s.message||"",u=s.stack||"";n=n||{};var h=typeof location=="object"&&typeof location.href=="string"&&location.href.substring(0,500)||"";if(i.checkSDKError(c,n.filename)){var l=/^Script error\.?$/,d=s.msg||s.message;if(i.ignoreByRule(d,l)||i.ignoreByRule(i.decode(d),l))return this;var f={msg:i.selfErrKey,err:{msg_raw:i.encode(s.msg||s.message)}};return this._self("error",f,1)}for(var m={begin:Date.now(),cate:o,msg:c&&c.substring(0,1e3),stack:u&&u.substring(0,1e3),file:i.removeUrlSearch(n.filename||""),line:n.lineno||"",col:n.colno||"",err:{msg_raw:i.encode(c),stack_raw:i.encode(u)},dl:h},g=["tag","c1","c2","c3"],S=0;S<g.length;S++){var b=g[S];n[b]&&(m[b]=n[b])}var w=(this.getConfig("ignore")||{}).ignoreErrors;return i.ignoreByRule(m.msg,w)||i.ignoreByRule(i.decode(m.msg),w)?this:(this.beforeSend&&this.beforeSend("error",m),this._lg("error",m,1))},behavior:function(s){if(s){var n=typeof s=="object"&&s.behavior?s:{behavior:s};return this.beforeSend&&this.beforeSend("behavior",n),this._lg("behavior",n,1)}},api:function(s,n,o,c,u,h,l,d,f,m,g,S,b,w,_,R){if(!s)return i.warn("[retcode] api is null"),this;if(s=typeof s=="string"?{api:s,success:n,time:o,code:c,msg:u,begin:h,traceId:l,pv_id:d,apiSnapshot:f,domain:m,flag:S,tag:b,c1:w,c2:_,c3:R}:i.sub(s,e),!i.checkAPI(s.api,!0))return this;s.code=s.code||"";var V=s.msg||"";if(V=typeof V=="string"?V.substring(0,1e3):V,s.msg=V,s.success=s.success?1:0,s.time=+s.time,s.begin=s.begin,s.traceId=s.traceId||"",s.pv_id=s.pv_id||"",s.domain=s.domain||"",s.flag=s.flag,s.dl=typeof location=="object"&&typeof location.href=="string"&&location.href.substring(0,500)||"",s.apiSnapshot&&(typeof s.apiSnapshot=="object"&&(s.apiSnapshot=JSON.stringify(s.apiSnapshot)),typeof s.apiSnapshot!="string"&&delete s.apiSnapshot,s.apiSnapshot.length>2e3&&(s.apiSnapshot=s.apiSnapshot.substring(0,2e3))),g&&(s.traceOrigin=g),!s.api||isNaN(s.time))return i.warn("[retcode] invalid time or api"),this;var K=(this.getConfig("ignore")||{}).ignoreApis;return i.ignoreByRule(s.api,K)||i.ignoreByRule(i.decode(s.api),K)?this:s.time<0?this:(this.beforeSend&&this.beforeSend("api",s),this._lg("api",s,s.success&&this.getConfig("sample"),s.flag))},speed:function(s,n,o){var c=this,u=this.getConfig("startTime")||this._startTime;return/^s(\d|1[0])$/.test(s)?(n=typeof n!="number"?Date.now()-u:n>=u?n-u:n,c.speedCache=c.speedCache||{},c.speedCache[s]=n,c.speedCache.begin=u,clearTimeout(c.speedTimmer),c.speedTimmer=setTimeout(function(){o||(c.speedCache.page=c.getPage(!0)),c._lg("speed",c.speedCache),c.speedCache=null},5e3),c):(i.warn("[retcode] invalid point: "+s),c)},performance:function(s){if(s&&typeof s=="object"&&!this.hasSendPerf){var n={},o={},c=this.getConfig("autoSendPerf");if(s.autoSend&&c)return o=i.ext(this.perfData||{},s),this.hasSendPerf=!0,this._lg("perf",o,this.getConfig("sample"));if(s.autoSend&&!c)return delete s.autoSend,this.perfData?(o=i.ext(this.perfData||{},s),this.hasSendPerf=!0,this._lg("perf",o,this.getConfig("sample"))):void(this.perfData=s);for(var u in s)(/^t([1-9]|1[0])$/.test(u)||u==="ctti"||u==="cfpt")&&(n[u]=s[u]);if(s.autoSend===!0||!c&&(c||this.perfData))return s.autoSend!==!0&&c===!1&&this.perfData?(n=i.ext(this.perfData||{},n),this.hasSendPerf=!0,this._lg("perf",n,this.getConfig("sample"))):void 0;this.perfData=i.ext(this.perfData||{},n)}},resource:function(s,n){if(!s||!i.isPlainObject(s))return i.warn("[arms] invalid param data: "+s),this;var o=Object.keys(s),c=["begin","dom","load","res","dl"],u=!1;for(var h in c)if(o.indexOf(c[h])<0){u=!0;break}if(u)return i.warn("[arms] lack param data: "+s),this;var l={begin:s.begin||Date.now(),dom:s.dom||"",load:s.load||"",res:i.isArray(s.res)?JSON.stringify(s.res):JSON.stringify([]),dl:s.dl||""};return this._lg("res",l,n)},event:function(s,n){if(typeof s=="object"&&s&&s.key){var o={},c=["key","success","time","c1","c2","c3"];for(var u in s)c.indexOf(u)>-1&&(o[u]=s[u]);o.success=s.success===!1?0:1,this._lg("event",o,n)}}}),r._super=a,r._root=a,a.Reporter=r,yi.exports=r,yi.exports}var Ri={exports:{}},_r;function aa(){if(_r)return Ri.exports;_r=1;var i=Se(),a=typeof window=="object"?window:{},e="catch",t=a.__oFetch_||a.fetch;return t=typeof t=="function"?t:void 0,Ri.exports=function(r,s){var n=-1;typeof r=="object"&&(n=r.z,r=i.serialize(r));var o=s+r;if(t)return t(o,{method:"HEAD",mode:"no-cors"})[e](i.noop);if(a.document&&a.document.createElement){var c="__request_hold_"+n,u=a[c]=new Image;u.onload=u.onerror=function(){a[c]=void 0},u.src=o,u=null}},Ri.exports}var Ii={exports:{}},Rr;function na(){if(Rr)return Ii.exports;Rr=1;var i=Se(),a=typeof window=="object"?window:{},e=a.__oXMLHttpRequest_||a.XMLHttpRequest;return e=typeof e=="function"?e:void 0,Ii.exports=function(t,r){try{var s=new e;s.open("POST",r,!0),s.setRequestHeader("Content-Type","text/plain"),s.send(JSON.stringify(t))}catch(n){i.warn(`[retcode] Failed to log, exception is :
|
|
3
|
+
`+n)}},Ii.exports}var Ei,Ir;function oa(){if(Ir)return Ei;Ir=1;var i=Se();return Ei=function(a,e){var t=[],r=null,s=e&&e.location&&e.location.href,n=void 0,o=null,c=function(d,f,m){if(d!==null){var g=d[f];d[f]=m(g)}},u=function(d){var f,m,g,S,b,w=[];if(!d||typeof d.tagName!="string")return"";if(w.push(d.tagName.toLowerCase()),typeof d.id=="string"&&w.push("#".concat(d.id)),typeof(f=d.className)=="string")for(m=f.split(/\s+/),b=0;b<m.length;b++)w.push(".".concat(m[b]));var _=["type","name","title","alt","data-arms-attr"];for(b=0;b<_.length;b++)g=_[b],typeof(S=d.getAttribute(g))=="string"&&w.push("[".concat(g,'="').concat(S,'"]'));return w.join("")},h=function(d,f){return function(m){if(m&&m!==o){o=m;var g;try{g=m.target}catch(b){g="<unknown>"}if(g.length!==0){var S={type:"ui.".concat(d),data:{message:function(b){if(!b||b.nodeType!==1)return"";for(var w=b||null,_=[],R=0,V=0,K=3,F="";w&&R++<5&&!((F=u(w))==="html"||R>1&&V+_.length*K+F.length>=80);)_.push(F),V+=F.length,w=w.parentNode;return _.reverse().join(" > ")}(g)},timestamp:Date.now()};d==="click"?r&&r.addBehavior(S):d==="keypress"&&(n||r&&r.addBehavior(S),clearTimeout(n),n=setTimeout(function(){n=void 0},100))}}}},l=function(){if(function(){var g=e&&e.chrome,S=g&&g.app&&g.app.runtime,b="history"in e&&!!e.history.pushState&&!!e.history.replaceState;return!S&&b}()){var d=function(g,S){var b={type:"navigation",data:{from:g,to:S}};r&&r.addBehavior(b),s=S},f=e.onpopstate;e.onpopstate=function(){for(var g=arguments.length,S=new Array(g),b=0;b<g;b++)S[b]=arguments[b];var w=e.location.href;if(d(s,w),f)return f.apply(this,S)};var m=function(g){return function(){for(var S=arguments.length,b=new Array(S),w=0;w<S;w++)b[w]=arguments[w];var _=b.length>2?b[2]:void 0;return _&&d(s,String(_)),g.apply(this,b)}};c(e.history,"pushState",m),c(e.history,"replaceState",m)}};i.ext(a.prototype,{addBehavior:function(d){if(this.getConfig("behavior")&&d&&typeof d=="object"){var f={},m=d.data||{};if(d.type)f=m;else{if(typeof m.name!="string"||typeof m.message!="string")return;f.name=m.name.substr(0,20),f.message=m.message.substr(0,200)}f.message&&(f.message=i.encode(f.message));var g={type:d.type||"custom",data:f||{},timestamp:d.timestamp||Date.now(),page:d.page||e&&e.location&&e.location.pathname};return t.push(g),t=t.slice(-100)}},getBehavior:function(){return t||[]},setBehavior:function(d){return d&&(t=d),t},reportBehavior:function(d){var f=this;f.getConfig("behavior")&&(f.sendBhTimer&&(clearTimeout(f.sendBhTimer),f.sendBhTimer=void 0),f.sendBhTimer=setTimeout(function(){t&&t.length>0&&(f.behavior(t),t=[],f.sendBhTimer=void 0,d&&typeof d=="function"&&d())},0))},initBehavior:function(){if(!this.hasInitBehavior&&!r){try{(function(){if(document&&document.referrer&&document.location){var f=document.referrer,m=document.location.href;if(f!==""){var g={type:"navigation",data:{from:f,to:m}};s=m,r&&r.addBehavior(g)}}})(),e&&e.document&&e.document.addEventListener&&(e.document.addEventListener("click",h("click"),!1),e.document.addEventListener("keypress",h("keypress"),!1)),l();var d=this.getConfig("enableConsole");d&&function(f){if(e&&e.console){var m=["debug","info","warn","log","error","assert"];i.isArray(f)&&(m=f);for(var g=0;g<m.length;g++){var S=m[g];S&&i.isString(S)&&e.console[S]&&typeof e.console[S]=="function"&&c(e.console,S,function(b){var w=S;return function(){for(var _=arguments.length,R=new Array(_),V=0;V<_;V++)R[V]=arguments[V];var K={type:"console",data:{level:w,message:R}};if(r&&r.addBehavior(K),w==="error")for(var F=0;F<R.length;F++){var O=R[F];O&&O.message&&O.stack&&r&&r.errorHandler(new ErrorEvent("error",{error:O,message:O.message}))}b&&Function.prototype.apply.call(b,e.console,R)}})}}}(d)}catch(f){i.warn("[arms] error in initBehavior",f)}r=this,this.hasInitBehavior=!0}return this}})},Ei}var Er={},Ar;function Ai(){return Ar||(Ar=1,Er.TIMING_KEYS=["startTime","fetchStart","domainLookupStart","domainLookupEnd","connectStart","connectEnd","requestStart","responseStart","responseEnd","","domInteractive","","domContentLoadedEventEnd","","loadEventStart","","msFirstPaint","secureConnectionStart","redirectStart","redirectEnd"]),Er}var Ti,Tr;function ca(){if(Tr)return Ti;Tr=1;var i=Se(),a=Ai(),e=a.TIMING_KEYS;return Ti=function(){var t=i.win||{},r=t.performance;if(!r||typeof r!="object"||typeof r.getEntriesByType!="function")return null;var s={},n=r.timing||{},o=r.getEntriesByType("resource")||[];if(s.begin=n[e[1]]||Date.now(),typeof t.PerformanceNavigationTiming=="function"){var c=r.getEntriesByType("navigation")[0];c&&(n=c)}return i.each({dom:[10,8],load:[14,1]},function(u,h){var l=n[e[u[1]]],d=n[e[u[0]]];if(l>0&&d>0){var f=Math.round(d-l);f>=0&&f<6e5&&(s[h]=f)}}),s.res=JSON.stringify(o),s},Ti}var Pi,Pr;function ua(){if(Pr)return Pi;Pr=1;var i=Se(),a=Ai(),e=a.TIMING_KEYS;return Pi=function(){var t=i.win||{},r=t.performance;if(!r||typeof r!="object")return null;var s={},n=r.timing||{},o=Date.now(),c=1;if(typeof t.PerformanceNavigationTiming=="function"){var u=r.getEntriesByType("navigation")[0];u&&(n=u,c=2)}i.each({dns:[3,2],tcp:[5,4],ssl:[5,17],ttfb:[7,6],trans:[8,7],dom:[10,8],res:[14,12],firstbyte:[7,2],fpt:[8,1],tti:[10,1],ready:[12,1],load:[14,1]},function(m,g){var S=n[e[m[1]]],b=n[e[m[0]]];if(c===2||S>0&&b>0){var w=Math.round(b-S);w>=0&&w<6e5&&(s[g]=w)}});var h=t.navigator.connection,l=r.navigation||{};s.ct=h?h.effectiveType||h.type:"";var d=h&&(h.downlink||h.downlinkMax||h.bandwidth)||null;if((d=d>999?999:d)&&(s.bandwidth=d),s.navtype=l.type===1?"Reload":"Other",c===1&&n[e[16]]>0&&n[e[1]]>0){var f=n[e[16]]-n[e[1]];f>=0&&f<36e5&&(s.fpt=f)}return c===1&&n[e[1]]>0?s.begin=n[e[1]]:c===2&&s.load>0?s.begin=o-s.load:s.begin=o,s},Pi}var kr,Cr;function ha(){return Cr||(Cr=1,kr=function(i,a,e){var t=Se(),r=ca(),s=ua(),n=null,o=e.documentElement,c=a.innerWidth||o.clientWidth||e.body.clientWidth,u=a.innerHeight||o.clientHeight||e.body.clientHeight,h=a.navigator.connection,l={sr:screen.width+"x"+screen.height,vp:c+"x"+u,ct:h?h.effectiveType||h.type:""},d={},f=function(g,S,b,w,_){if(S===void 0){var R,V;if(!d[g]){R=new RegExp(g+"=([^;]+)");try{V=R.exec(e.cookie)}catch(F){return t.warn("[retcode] can not get cookie:",F),null}V&&(d[g]=V[1])}return d[g]}var K=g+"="+S;K+="; path=/",b&&(K+="; max-age="+b);try{return e.cookie=K,!!e.cookie}catch(F){return t.warn("[retcode] can not set cookie: ",F),!1}},m=function(g){var S=g._conf.uid||f("_nk_")||f("_bl_uid");return!S&&(S=t.uu(),!f("_bl_uid",S,15552e3))?null:S};return t.ext(i.prototype,{activeErrHandler:function(g){return n&&!g?this:(n=this,this)},errorHandler:function(g){if(!g)return this;var S=g.type;if(S==="error"){var b=g.target||g.srcElement;!b||!b.tagName||g.message||g.filename||g.lineno||g.colno?this.error(g.error||{message:g.message},g):this.resourceErrorHandler(g)}else S==="unhandledrejection"&&t.T(g.reason,"Error")&&t.checkAutoError(g.reason)&&this.error(g.reason);try{this.getConfig("behavior")&&this.reportBehavior&&this.reportBehavior()}catch(w){}return this},resourceErrorHandler:function(g){var S=this,b=g.target||g.srcElement;try{var w=S.getSrc(b),_=typeof b.tagName=="string"?b.tagName.toLowerCase():"",R=S.getXPath(b,5),V=t.getURL(w),K={src:w&&w.substring(0,1e3),node_name:_,xpath:R,res_type:t.getResType(_,w),res_name:V.path,domain:V.domain};return S._conf.enableResource&&S.fixResourceStatus&&g.timeStamp&&S.fixResourceStatus({src:w,node_name:_,res_type:t.getResType(_,w),timeStamp:g.timeStamp,domain:V.domain}),S._lg("resourceError",K),S}catch(F){return t.warn("[ARMS] resourceErrorHandler error :",F),S}},getSrc:function(g){var S=g.src||g.href;try{if(!S){var b=(typeof g.tagName=="string"?g.tagName.toLowerCase():"")==="object",w=g.getAttribute("classid")&&g.getAttribute("classid").toLowerCase()==="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"||g.getAttribute("type")==="application/x-shockwave-flash";b&&w&&(S=g.getAttribute("data")||g.getAttribute("codebase")),S||(S=g.outerHTML||g.innerHTML)}}catch(_){S=""}return S},getXPath:function(g,S){var b=g.id?"#"+g.id:"",w=typeof g.className=="string"?"."+g.className.split(" ").join("."):"",_=(typeof g.tagName=="string"?g.tagName.toLowerCase():"")+b+w;return g.parentNode&&g.parentNode.tagName&&S-1!=0?this.getXPath(g.parentNode,S-1)+" > "+_:_},sendPerformance:function(g){var S=this;S.onReady(function(){var b=s();b&&b.load&&b.load>0&&(b.page=S.getPage(!0),g&&(b=t.ext(b,g)),b.autoSend=!0,S.performance(b))})},sendResources:function(g){var S=this;S.onReady(function(){var b=r();b&&b.load&&b.load>0&&(b.load&&b.load<=2e3||b.load&&b.load<=8e3&&Math.random()>.05||(b.page=S.getPage(!0),b.dl=location.href,g&&(b=t.ext(b,g)),S._lg("res",b,S.getConfig("sample"))))})},sendPV:function(){var g=this;g.onReady(function(){var S=function(b){var w=m(b),_=a.devicePixelRatio||1;return{uid:w,dt:e.title,dl:location.href,dr:e.referrer,dpr:_.toFixed(2),de:(e.characterSet||e.defaultCharset||"").toLowerCase(),ul:o.lang,begin:Date.now()}}(g);S&&S.uid&&g._lg("pv",S,g.getConfig("pvSample"))})},commonInfo:function(){return l.uid=m(this),l.sid=function(g){if(g.session)return g.session;var S;try{if(typeof window=="object"&&typeof sessionStorage=="object"&&typeof sessionStorage.getItem=="function")return typeof(S=sessionStorage.getItem("_bl_sid"))=="string"?(g.session=S,S):(S=t.uu(),g.session=S,typeof sessionStorage.setItem=="function"&&sessionStorage.setItem("_bl_sid",S),S)}catch(b){t.warn("[ARMS] getSid error :",b)}return g.session=S=t.uu(),S}(this),l},handleUnload:function(g){var S=Date.now();if(S-this._lastUnload<200)return this;this._lastUnload=S,this.sendHealth(g),this.speedCache&&(this._lg("speed",this.speedCache),this.speedCache=null,clearTimeout(this.speedTimmer)),this._conf&&this._conf.enableResource&&this.resourceComboReport(),this.clear(!0)},bindHashChange:function(g){var S=this;if(!g^S.hashChangeHandler)return S;g?(S.hackHistoryState(),S.hashChangeHandler=function(b){var w=S._conf.parseHash(location.hash);w&&S.setPage(w,b!==!1)},S.stateChangeHandler=function(b){var w=S._conf.parseHash(b.detail);w&&S.setPage(w)},t.on(a,"hashchange",S.hashChangeHandler),t.on(a,"historystatechange",S.stateChangeHandler),S.hashChangeHandler(!1)):(t.off(a,"hashchange",S.hashChangeHandler),t.off(a,"historystatechange",S.stateChangeHandler),S.hashChangeHandler=null,S.stateChangeHandler=null)},initHandler:function(){var g=this;if(g.hasInitHandler)return g;var S=g._conf;return t.on(a,"beforeunload",function(){g.handleUnload(0)}),g.bindHashChange(S.enableSPA),g.activeErrHandler(!1),g.hasInitHandler=!0,g}}),t.on(a,"error",function(g){n&&n.errorHandler(g)},!1,!0).on(a,"unhandledrejection",function(g){n&&n.errorHandler(g)}),i}),kr}var ki,Mr;function la(){if(Mr)return ki;Mr=1;var i=Se(),a=500;return ki=function(e,t,r){function s(l,d,f){var m=0,g=l.tagName;if(g!=="SCRIPT"&&g!=="STYLE"&&g!=="META"&&g!=="HEAD"){var S=l.children?l.children.length:0;if(S>0)for(var b=l.children,w=S-1;w>=0;w--)m+=s(b[w],d+1,m>0);if(m<=0&&!f&&!(l.getBoundingClientRect&&l.getBoundingClientRect().top<o))return 0;m+=1+.5*d}return m}function n(l){for(var d=1;d<l.length;d++)if(l[d].score<l[d-1].score)return l.splice(d,1),n(l);return l}var o=t.innerHeight||0,c=[],u=null,h=0;i.ext(e.prototype,{initFmpObserver:function(l){var d=this;if(!d._conf||!d._conf.useFmp)return null;if(!t.MutationObserver)return i.warn("[retcode] first meaningful paint can not be retrieved"),d.sendPerformance(),null;i.on(t,"beforeunload",function(){d.endObserving(0,!0)});var f=t.MutationObserver;return(u=new f(function(){(function(m){var g=Date.now()-m,S=r.querySelector("body");if(S){var b=0;b+=s(S,1,!1),c.push({score:b,t:g})}else c.push({score:0,t:g})})(d._startTime)})).observe(document,{childList:!0,subtree:!0}),h=1,d.onReady(function(){d.endObserving(l)}),u},endObserving:function(l,d){var f=this;if(u&&h)if(f.fmpTimmer&&(clearTimeout(f.fmpTimmer),f.fmpTimmer=null),d||!function(b,w){var _=Date.now()-b;return!(_>w||_-(c&&c.length&&c[c.length-1].t||0)>2*a)}(f._startTime,l)){u.disconnect(),h=0,c=n(c);for(var m=null,g=1;g<c.length;g++)if(c[g].t>=c[g-1].t){var S=c[g].score-c[g-1].score;(!m||m.rate<=S)&&(m={t:c[g].t,rate:S})}m&&m.t>0&&m.t<36e5?f.sendPerformance({fmp:m.t}):f.sendPerformance()}else f.fmpTimmer=i.delay(function(){f.endObserving(l)},a)}})},ki}var Nr,Lr;function da(){return Lr||(Lr=1,Nr=function(i,a){var e=Se(),t=null,r=e.getCurDomain(),s=function(h,l,d,f,m,g,S,b,w,_,R,V,K){var F=e.J(m)||null,O=e.safetyCall(l,[F,f],null);if(!O)return!1;var ee=O.code||g,Re=!("success"in O)||O.success;h.api(d,Re,S,ee,O.msg,b,w,_,Re?{}:R,r,V,K)},n="fetch",o="__oFetch_",c="__oXMLHttpRequest_",u="XMLHttpRequest";return e.ext(i.prototype,{removeHook:function(h,l){return t&&(l||this===t)?(a[o]&&(a[n]=a[o],delete a[o]),a[c]&&(a[u]=a[c],delete a[c]),t=null,this):this},addHook:function(h){return!h&&t?this:(t||(function(){if(typeof a[n]=="function"){var l=a[n];a[o]=l,a[n]=function(d,f){var m=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),g=t;if(!g||!g.api||f&&(f.method==="HEAD"||f.mode==="no-cors"))return l.apply(a,m);f||(f={});var S=Date.now(),b=g._conf,w=e.duration(),_=(d&&typeof d!="string"?d.url:d)||"",R=_;_=e.cutUrlSearch(_);var V=(b.ignore||{}).ignoreApis,K=b.parseTraceId;if(!e.checkAPI(_,!0)||e.ignoreByRule(_,V))return l.apply(a,m);_=e.filterByRule(_,R,b.ignoreApiPath?b.ignoreApiPath:b.apiHelper);var F=b.enableLinkTrace,O="",ee="",Re=g.getConfig("pid"),st=null,he=g.getConfig("sample"),le=g.getConfig("linkType"),ye=1;if(he&&!g.sampling(he)&&(ye=0),F){var $e="";try{$e=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(Y){$e=""}var Ge=e.checkSameOrigin(R,$e);if(g.getConfig("enableApiCors")||Ge)if(d&&typeof d!="string")try{if(m[0].headers&&typeof m[0].headers.get=="function"&&typeof m[0].headers.append=="function")switch(le){case"arms":var ze=m[0].headers.get("EagleEye-TraceID"),Ne=m[0].headers.get("EagleEye-SessionID"),Pe=m[0].headers.get("EagleEye-pAppName");ze?O=ze:(O=g.getTraceId()["EagleEye-TraceID"],m[0].headers.append("EagleEye-TraceID",O)),Ne?ee=Ne:(ee=g.getPageviewId()["EagleEye-SessionID"],m[0].headers.append("EagleEye-SessionID",ee)),Pe||m[0].headers.append("EagleEye-pAppName",Re);break;case"b3":var xe=m[0].headers.get("X-B3-TraceId");if(xe)O=xe;else{var Ie=g.getB3TraceId(ye);m[0].headers.append("X-B3-TraceId",Ie["X-B3-TraceId"]),m[0].headers.append("X-B3-ParentSpanId",Ie["X-B3-ParentSpanId"]),m[0].headers.append("X-B3-SpanId",Ie["X-B3-SpanId"]),m[0].headers.append("X-B3-Sampled",Ie["X-B3-Sampled"]),m[0].headers.append("X-Request-ID",e.guid()),O=Ie["X-B3-TraceId"]}ee=g.pageview;break;case"tracing":default:var fe=m[0].headers.get("uber-trace-id");fe?O=fe.split(":")[0]:(fe=g.getUberTraceId(ye),m[0].headers.append("uber-trace-id",fe["uber-trace-id"]),O=fe.traceId),ee=g.pageview}}catch(Y){e.warn(`[retcode] fetch failed to set header, exception is :
|
|
4
|
+
`+Y)}else switch(f.headers=f.headers?f.headers:{},le){case"arms":f.headers["EagleEye-TraceID"]?O=f.headers["EagleEye-TraceID"]:(O=g.getTraceId()["EagleEye-TraceID"],f.headers["EagleEye-TraceID"]=O),f.headers["EagleEye-SessionID"]?ee=f.headers["EagleEye-SessionID"]:(ee=g.getPageviewId()["EagleEye-SessionID"],f.headers["EagleEye-SessionID"]=ee),f.headers["EagleEye-pAppName"]||(f.headers["EagleEye-pAppName"]=Re);break;case"b3":if(f.headers["X-B3-TraceId"])O=f.headers["X-B3-TraceId"];else{var me=g.getB3TraceId(ye);f.headers["X-B3-TraceId"]=me["X-B3-TraceId"],f.headers["X-B3-ParentSpanId"]=me["X-B3-ParentSpanId"],f.headers["X-B3-SpanId"]=me["X-B3-SpanId"],f.headers["X-B3-Sampled"]=me["X-B3-Sampled"],f.headers["X-Request-ID"]=e.guid(),O=me["X-B3-TraceId"]}ee=g.getPageviewId()["EagleEye-SessionID"];break;case"tracing":default:if(f.headers["uber-trace-id"])O=f.headers["uber-trace-id"].split(":")[0];else{var We=g.getUberTraceId(ye);f.headers["uber-trace-id"]=We["uber-trace-id"],O=We.traceId}ee=g.getPageviewId()["EagleEye-SessionID"]}}return l.apply(a,m).then(function(Y){if(!g||!g.api)return Y;try{if(!Y||typeof Y.clone!="function")return Y;var de=Y.clone(),Ke=de.headers;if(Ke&&typeof Ke.get=="function"){var Ut=Ke.get("content-type");if(Ut&&!/(text)|(json)/.test(Ut))return Y;if(!O){var yt=e.parseFetchHeaders(Ke);typeof yt=="object"&&yt["eagleeye-traceid"]&&(O=yt["eagleeye-traceid"],st="response")}}var Bt=w();return de.text().then(function(gt){if(!O&&e.isFunction(K)){var at=K(de,gt);at&&e.isString(at)&&(O=at)}var Ht=e.getFetchSnapshot(m,gt,Ke);de.ok?s(g,b.parseResponse,_,R,gt,de.status||200,Bt,S,O,ee,Ht,st,ye):(g.api(_,!1,Bt,de.status||404,de.statusText,S,O,ee,Ht,r,st,ye),b.enableResource&&t.fixResourceStatus&&t.fixResourceStatus({src:de.url,res_type:"api"}))}),Y}catch(gt){return e.warn("[ARMS] fetch response error :",gt),Y}}).catch(function(Y){if(!g||!g.api)throw Y;var de=w();throw g.api(_,!1,de,Y.name||"Error",Y.message,S,O,ee,{},r),b.enableResource&&t.fixResourceStatus&&t.fixResourceStatus({src:R,res_type:"api"}),Y})},a[n].toString=e.createFakeToString(n)}}(),function(){if(typeof a[u]=="function"){var l,d=a[u];a[c]=d;var f=function(m){var g=new d(m),S=t;if(!S||!S.api||!g.addEventListener)return g;var b,w,_,R,V=g.send,K=g.open,F=g.setRequestHeader,O=S._conf,ee=(O.ignore||{}).ignoreApis,Re=O.parseTraceId,st=S.getConfig("enableLinkTrace"),he="",le="",ye="",$e=null,Ge=S.getConfig("sample"),ze=S.getConfig("linkType"),Ne=1;return Ge&&!S.sampling(Ge)&&(Ne=0),g.open=function(Pe,xe){l=Pe;var Ie=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);K.apply(g,Ie),R=xe||"",_=e.cutUrlSearch(R);var fe=!e.checkAPI(_,!0)||e.ignoreByRule(_,ee);if(_=_?e.filterByRule(_,R,O.ignoreApiPath?O.ignoreApiPath:O.apiHelper):"",!fe&&st){var me="";try{me=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(Ke){me=""}var We=e.checkSameOrigin(R,me);if((S.getConfig("enableApiCors")||We)&&F&&typeof F=="function")switch(ze){case"arms":he=S.getTraceId()["EagleEye-TraceID"],F.apply(g,["EagleEye-TraceID",he]),le=S.getPageviewId()["EagleEye-SessionID"],F.apply(g,["EagleEye-SessionID",le]),ye=S.getConfig("pid"),F.apply(g,["EagleEye-pAppName",ye]);break;case"b3":var Y=S.getB3TraceId(Ne);F.apply(g,["X-B3-TraceId",Y["X-B3-TraceId"]]),F.apply(g,["X-B3-ParentSpanId",Y["X-B3-ParentSpanId"]]),F.apply(g,["X-B3-SpanId",Y["X-B3-SpanId"]]),F.apply(g,["X-B3-Sampled",Y["X-B3-Sampled"]]),F.apply(g,["X-Request-ID",e.guid()]),he=Y["X-B3-TraceId"],le=S.getPageviewId()["EagleEye-SessionID"];break;case"tracing":default:var de=S.getUberTraceId(Ne);F.apply(g,["uber-trace-id",de["uber-trace-id"]]),he=de.traceId,le=S.getPageviewId()["EagleEye-SessionID"]}}},g.send=function(){b=Date.now(),w=e.duration();var Pe=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);V.apply(g,Pe)},e.on(g,"readystatechange",function(){if(_&&g.readyState===4){var Pe=w(),xe=e.getXhrSnapshot(R,l,g);if(!he){var Ie=e.parseXhrHeaders(typeof g.getAllResponseHeaders=="function"&&g.getAllResponseHeaders()||"");typeof Ie=="object"&&Ie["eagleeye-traceid"]&&(he=Ie["eagleeye-traceid"],$e="response")}if(!he&&e.isFunction(Re)){var fe=Re(g);fe&&e.isString(fe)&&(he=fe)}if(g.status>=200&&g.status<=299){var me=g.status||200;if(typeof g.getResponseHeader=="function"){var We=g.getResponseHeader("Content-Type");if(We&&!/(text)|(json)/.test(We))return}g.responseType&&g.responseType!=="text"?S.api(_,!0,Pe,me,"",b,he,le,{},r,$e,Ne):s(S,O.parseResponse,_,R,g.responseText,me,Pe,b,he,le,xe,$e,Ne)}else S.api(_,!1,Pe,g.status||"FAILED",g.statusText,b,he,le,xe,r,$e,Ne),O.enableResource&&t.fixResourceStatus&&t.fixResourceStatus({src:g.responseURL||R,res_type:"api"})}}),g};f.prototype=d.prototype,e.each(Object.keys(d),function(m){f[m]=d[m]}),a[u]=f,a[u].toString=e.createFakeToString(u)}}()),t=this,this)},initHook:function(){return this.hasInitHook?this:(this.getConfig("disableHook")||this.addHook(),this.hasInitHook=!0,this)}}),i}),Nr}var Or,Vr;function pa(){return Vr||(Vr=1,Or=function(i,a){var e=Se(),t=a.history||{},r=a.document,s=function(o,c){var u;a.CustomEvent?u=new CustomEvent(o,{detail:c}):((u=r.createEvent("HTMLEvents")).initEvent(o,!1,!0),u.detail=c),a.dispatchEvent(u)},n=function(o){var c=t[o];typeof c=="function"&&(t[o]=function(u,h,l){var d=arguments.length===1?[arguments[0]]:Array.apply(null,arguments),f=location.href,m=c.apply(t,d);if(!l||typeof l!="string"||l===f)return m;try{var g=f.split("#"),S=l.split("#"),b=e.cutUrlSearch(g[0]),w=e.cutUrlSearch(S[0]),_=g[1]&&g[1].replace(/^\/?(.*)/,"$1"),R=S[1]&&S[1].replace(/^\/?(.*)/,"$1");_!==R?s("historystatechange",R):b!==w&&s("historystatechange",w)}catch(V){e.warn("[retcode] error in "+o+": "+V)}return m},t[o].toString=e.createFakeToString(o))};e.ext(i.prototype,{hackHistoryState:function(){return this.hasHackedHistoryState?this:(n("pushState"),n("replaceState"),this.hasHackedHistoryState=!0,this)}})}),Or}var Ci,Dr;function ga(){if(Dr)return Ci;Dr=1;var i=Se(),a=Ai(),e=a.TIMING_KEYS;return Ci=function(t,r){function s(c,u,h){if(c instanceof r.PerformanceResourceTiming&&c.initiatorType){var l=i.getResType(c.initiatorType,c.name),d=u.resourceTypes||[],f=(u.ignore||{}).ignoreResources;if(l&&d.includes(l)&&!i.ignoreByRule(c.name,f)&&!i.ignoreByRule(i.decode(c.name),f)){var m=c[e[0]],g=c[e[1]],S=c[e[2]],b=c[e[3]],w=c[e[4]],_=c[e[5]],R=c[e[6]],V=c[e[7]],K=c[e[8]],F=c[e[18]],O=c[e[19]];if(!h.has(c)&&(!i.areInOrder(m,g,S,b,w,_,R,V,K)||m>V))return;if(F<m&&(F=m),O<m&&(O=g),i.areInOrder(m,F,O,g))return{domain:i.getURL(c.name).domain,res_type:l,src_type:i.getSrcType(c.name,u.cdnHostList),success:1,size:Math.round(c.decodedBodySize),duration:Math.round(c.duration),timeStamp:c.responseEnd,timing:c}}}}var n="_resource-"+Date.now(),o="_resource_error-"+Date.now();i.ext(t.prototype,{initResource:function(){var c=this,u=r.performance,h=r.PerformanceObserver;if(c[o]||(c[o]=new WeakMap),!u||!h||typeof u!="object"||typeof u.getEntriesByType!="function")return null;var l=u.getEntriesByType("resource")||[];return setTimeout(function(){c.setResource(l)},10),new h(function(d){setTimeout(function(){c.setResource(d.getEntries())},10)}).observe({entryTypes:["resource"]}),this.onReady(function(){setTimeout(c.resourceComboReport.bind(c),5e3)}),c},setResource:function(c){var u=this._conf,h=this[o];if(i.isArray(c)&&c.length){this[n]||(this[n]={});for(var l=this[n],d=0,f=c.length;d<f;d+=1){var m=c[d];if(i.checkAPI(m.name,!1)){var g=s(m,u,h);if(g){var S=g.res_type+"-"+g.domain;S in l||(l[S]=[]),l[S].push(g)}}}return this}},fixResourceStatus:function(c){var u=r.performance;if(!u||typeof u.getEntriesByName!="function")return null;var h=this[o];if(!c.src||!i.checkAPI(c.src,!1))return this;var l=c.timeStamp||u.now(),d=u.getEntriesByName(c.src,"resource");return i.each(d,function(f){h.has(f)||l-f.responseEnd<100&&h.set(f,{success:0})}),this},resourceComboReport:function(){var c=this[n]||{},u=this._conf.resourceSlow||2e3,h=this[o];this[n]={};var l=Object.keys(c);if(l.length!==0){var d=[];i.each(l,function(S){var b=c[S],w={domain:"",res_type:"",src_type:"",size:0,duration:0,count:0,err_count:0,err_duration:0,slow_count:0,slow_duration:0,timings:[]};i.each(b,function(_){var R=_.timing||{},V=h.get(_.timing),K=V?V.success:1,F=_.duration>u?1:0;w.domain=_.domain,w.res_type=_.res_type,w.src_type=_.src_type,w.count+=1,w.duration+=_.duration,w.size+=_.size,K||(w.err_count+=1,w.err_duration+=_.duration),F&&(w.slow_count+=1,w.slow_duration+=_.duration);try{var O=JSON.parse(JSON.stringify(R));O.success=K,O.resourceSlow=u,O.isSlow=F,w.timings.push(O)}catch(ee){}}),w.count&&(w.size=Math.round(w.size/w.count),w.duration=Math.round(w.duration/w.count)),w.slow_count&&(w.slow_duration=Math.round(w.slow_duration/w.slow_count)),w.err_count&&(w.err_duration=Math.round(w.err_duration/w.err_count)),w.timings.length>20&&(w.timings.sort(function(_,R){return R.duration-_.duration}),w.timings.length=20),w.timings=encodeURIComponent(JSON.stringify(w.timings)),d.push(w)});var f={_combo:1,resource:JSON.stringify(d)},m=r.navigator.connection;f.ct=m?m.effectiveType||m.type:"";var g=m&&(m.downlink||m.downlinkMax||m.bandwidth)||null;(g=g>999?999:g)&&(f.bandwidth=g),this._lg("resource",f,this.getConfig("sample"))}}})},Ci}var xr;function fa(){if(xr)return ot.exports;xr=1;var i=Se(),a=sa(),e=aa(),t=na(),r=i.win,s=r.document,n=/^(error|api|speed|sum|avg|percent|custom|msg|setPage|setConfig|behavior|performance)$/,o=function(c){var u=this;return a.call(u,c),u._initialPage=c.page&&i.safetyCall(c.page,[],c.page+"")||null,u._isRobot=i.isRobot(),u._health={errcount:0,apisucc:0,apifail:0},u.beforeSend=function(h,l){h==="error"?u._health.errcount++:h==="api"&&u._health[l.success?"apisucc":"apifail"]++},c.enableInstanceAutoSend!==!1&&(u.initHandler(),u.initHook(),u.initFmpObserver(1e4),u._conf&&u._conf.behavior&&typeof u.initBehavior=="function"&&u.initBehavior(),u._conf&&u._conf.enableResource&&typeof u.initResource=="function"&&u.initResource()),Object.defineProperty&&r.addEventListener&&Object.defineProperty(u,"pipe",{set:u.sendPipe}),u};return o.prototype=i.createObject(a.prototype),i.ext(a._root.dftCon,{uid:null,setUsername:null,ignoreUrlPath:null,ignoreApiPath:null,urlHelper:[{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},/\/$/],resourceHelper:[],apiHelper:{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},ignoreUrlCase:!0,imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",cdnHostList:[],resourceTypes:["css","script","img","font"],resourceSlow:2e3,disableHook:!1,autoSendPv:!0,autoSendPerf:!0,enableSPA:!1,enableLinkTrace:!1,linkType:"arms",enableApiCors:!1,sendResource:!0,behavior:!0,enableConsole:!1,parseHash:function(c){return(c?i.cutUrlSearch(c.replace(/^#\/?/,"")):"")||"[index]"},parseResponse:function(c){if(!c||typeof c!="object")return{};var u=c.code,h=c.msg||c.message||c.subMsg||c.errorMsg||c.ret||c.errorResponse||"";return typeof h=="object"&&(u=u||h.code,h=h.msg||h.message||h.info||h.ret||JSON.stringify(h)),{msg:h,code:u,success:!0}}}),i.ext(o.prototype,{constructor:o,_super:a,onReady:function(c){var u=this;if(u.hasReady)return c();s.readyState==="complete"?(u.hasReady=!0,c()):i.on(r,"load",function(){u.hasReady=!0,c()},!0)},getPage:function(c){var u=this._conf,h=u.page,l=location,d=l.host+l.pathname;return h&&!c?i.safetyCall(h,[],h+""):this._initialPage||i.filterByRule(u.ignoreUrlCase?d.toLowerCase():d,l.href,u.ignoreUrlPath?u.ignoreUrlPath:u.urlHelper)},setPage:function(c,u){var h=this,l=h.prevPage;if(u!==!1){if(!c||c===l)return h;h.prevPage=c,clearTimeout(h.sendPVTimmer),h.handleUnload(1),h.resetPageview(),h.sendPVTimmer=setTimeout(function(){h.sendPV()},10)}else h.prevPage=c;return h._conf.page=c,h},setConfig:function(c,u){if(c&&typeof c=="object"){i.verifyConfig(c),c=this.setImgUrl(c);var h=this._conf;if(this._conf=i.ext({},h,c),!u){var l="disableHook";l in c&&h[l]!==c[l]&&(c[l]?this.removeHook():this.addHook()),(l="enableSPA")in c&&h[l]!==c[l]&&this.bindHashChange(c[l])}}},sendRequest:function(c){e(c,this.getConfig("imgUrl"))},postData:function(c,u){var h={};h[u]=c[u],delete c[u];var l="";typeof c=="object"&&(l=i.serialize(c)),t(h,this.getConfig("imgUrl")+l+"&post_res=")},sendPipe:function(c){var u=this;if(!c||!c.length)return u;try{if(i.T(c[0])==="Array")return i.each(c,function(l){return u.sendPipe(l)});if(i.T(c)!=="Array")return u;var h=c.shift();if(!n.test(h))return u;u[h].apply(u,c)}catch(l){return i.warn("[retcode] error in sendPipe",l),u}},sendHealth:function(){var c=i.ext({},this._health);c.healthy=c.errcount>0?0:1,c.begin=Date.now();var u=c.begin-this.sBegin;c.stay=u,this._lg("health",c,1),this._health={errcount:0,apisucc:0,apifail:0}},createInstance:function(c){c=i.ext({pid:this._conf.pid},c);var u=this.__proto__.constructor(c);return c.page&&u.sendPV(),u}}),oa()(o,r),ha()(o,r,s),la()(o,r,s),da()(o,r),pa()(o,r),ga()(o,r),o._super=a,o._root=a._root,a.Browser=o,ot.exports=o,ot.exports}var Ur;function ma(){if(Ur)return Le.exports;Ur=1;function i(o,c){var u=e[r]=new t(o);u.sendPipe(c);var h=u._conf;return h.autoSendPv!==!1&&u.sendPV(),h&&h.useFmp||u.sendPerformance(),h&&h.sendResource&&u.sendResources(),e[s]=!0,u}function a(){if(e[s])return e[r];var o={},c=[];return r in e&&(o=e[r].config||{},c=e[r].pipe||[]),i(o,c)}var e=window,t=e.BrowserLogger=fa(),r=Se().key,s="__hasInitBlSdk";t.singleton=function(o,c){return e[s]?e[r]:i(o,c)},t.createExtraInstance=function(o){o&&typeof o=="object"&&o.enableInstanceAutoSend!==!0&&(o.enableInstanceAutoSend=!1);var c=new t(o),u=c._conf;return u.enableInstanceAutoSend&&(u.autoSendPv!==!1&&c.sendPV(),u&&u.useFmp||c.sendPerformance(),u&&u.sendResource&&c.sendResources()),c};var n=typeof window=="object"&&!!window.navigator;return n&&e[r]&&(t.bl=a()),Le.exports=t,Le.exports}function Sa(){return ma()}var ba={getArmsLogger:Sa};function va(i,a){const e=[],t=typeof Object.getOwnPropertyDescriptors=="function"?Object.getOwnPropertyDescriptors(Object.getPrototypeOf(i)):{};for(const s of Object.keys(t))t[s].get&&e.push(s);const r={MediaboxWrapperObjectGetter(s,n){if(typeof n=="string"&&e.indexOf(n)>-1)return He(s[n],a+1);const o={MediaboxWrapperObjectMethod(...c){return He(s[n](...c),a+1)}};return typeof s[n]=="function"?o.MediaboxWrapperObjectMethod:a>10?s[n]:He(s[n],a+1)},MediaboxWrapperObjectSetter(s,n,o){return s[n]=He(o,a+1),!0}};return new Proxy(i,{get:r.MediaboxWrapperObjectGetter,set:r.MediaboxWrapperObjectSetter})}function ya(i,a){const e={MediaboxWrapperFunctionApply(t,r,s){const n=t.apply(r,s);return He(n,a+1)},MediaboxWrapperFunctionGet(t,r){const s=Object.getOwnPropertyDescriptor(t,r);if(s&&!s.writable&&!s.configurable)return t[r];const n={MediaboxWrapperFunctionGet(...o){const c=t[r](...o);return He(c,a+1)}};return typeof t[r]=="function"?n.MediaboxWrapperFunctionGet:He(t[r],a+1)},MediaboxWrapperClassConstructor(t,r){const s=new t(...r);return He(s,a+1)}};return new Proxy(i,{apply:e.MediaboxWrapperFunctionApply,get:e.MediaboxWrapperFunctionGet,construct:e.MediaboxWrapperClassConstructor})}function wa(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp)&&!(i instanceof Function)}function He(i,a){return typeof i=="function"?ya(i,a+1):i instanceof Promise?i.then(e=>He(e,a+1)).catch(e=>(e instanceof Error&&typeof e.stack=="string"&&e.stack.indexOf("MediaboxWrapper")>-1&&setTimeout(()=>{throw e},0),Promise.reject(e))):wa(i)?va(i,a+1):i}const _a="https://arms-retcode-sg.aliyuncs.com/r.png?",Ra="https://arms-retcode.aliyuncs.com/r.png?",Ia="https://retcode-us-west-1.arms.aliyuncs.com/r.png?",Ea={cn:Ra,sg:_a,usw:Ia};class Mi{constructor(a){Be(this,"armsLogger"),Be(this,"isReady",!1),Be(this,"isDestroyed",!1),Be(this,"options"),Be(this,"queue",[]),Be(this,"helper",{MediaboxWrapperQueue(n){return new Error(n)},MediaboxWrapperInitiative(n){return new Error(n)}}),this.options=a;const{region:e="cn",env:t="prod"}=a,r=n=>{var o;if(this.isDestroyed)return!1;if(n.c1=(o=this.options.cid)!=null?o:window.location.host,n.c2=Mi.version,this.options.customData&&(n.c3=new URLSearchParams(this.options.customData).toString()),n.t==="error"){if(n.file.indexOf("g.alicdn.com/apsara-media-")>-1||n.file.indexOf("g.alicdn.com/thor-server")>-1||n.stack.indexOf("MediaboxWrapper")>-1){let c=n;return this.options.beforeSend&&(c=this.options.beforeSend(n)),this.isReady?c:(c&&this.queue.push(c),!1)}return!1}return n},s=ba.getArmsLogger();this.armsLogger=s.singleton({pid:"e1iftji1w7@7ec1cef2cc88733",tag:a.businessName,release:`${a.businessName}_${a.version}`,imgUrl:Ea[e],behavior:!0,sample:1,disableHook:!0,environment:t,beforeReport:r})}static get version(){return"0.9.0"}wrap(a){return this.options.disabled||typeof Proxy>"u"?a:He(a,0)}updateOptions(a){this.options=W(W({},this.options),a)}setReady(){this.isReady=!0,this.queue.length&&this.queue.forEach(a=>{this.armsLogger.error(this.helper.MediaboxWrapperQueue(a.msg),{filename:a.file,lineno:a.line,colno:a.col})})}report(a,e){this.armsLogger.error(this.helper.MediaboxWrapperInitiative(a),e)}destroy(){this.isDestroyed=!0}}var J=(i=>(i.PullStreamStats="remoteStat",i.RtsSubscribeExceeds="rtsSubscribeExceeds",i.UserJoined="userJoined",i.UserLeft="userLeft",i.Bye="bye",i.MuteAudio="muteAudio",i.UnmuteAudio="unmuteAudio",i.MuteVideo="muteVideo",i.UnmuteVideo="unmuteVideo",i.MuteScreen="muteScreen",i.UnmuteScreen="unmuteScreen",i.Error="error",i))(J||{}),be=(i=>(i.Local="local-device-status-change",i.Remote="remote-device-status-change",i))(be||{}),M=(i=>(i.Audio="sophon_audio",i.VideoLarge="sophon_video_camera_large",i.VideoSmall="sophon_video_camera_small",i.Screen="sophon_video_screen_share",i))(M||{}),Ni=(i=>(i.Audio="rts audio",i.VideoLarge="rts video",i))(Ni||{}),ft=(i=>(i[i.Camera=0]="Camera",i[i.Screen=1]="Screen",i[i.Image=2]="Image",i))(ft||{}),Wt=(i=>(i[i.Microphone=0]="Microphone",i[i.Screen=1]="Screen",i[i.Mixed=2]="Mixed",i))(Wt||{}),Kt=(i=>(i.prod="rs.rtn.aliyuncs.com",i.pre="prs.rtn.aliyuncs.com",i))(Kt||{});const Rt="6.11.6-beta.1",Br="web";class Ye{static getVersionNumber(){let a=Rt.split("."),e="";return a.forEach(t=>{t.length===1?e+="0"+t:e+=t}),parseInt(e)}static queryingParam(a){let e=[];if(a)for(let t in a)e.push(t+"="+a[t]);return e.join("&")}static getQueryParams(a){const t=window.location.search.substring(1).split("&");for(let r=0;r<t.length;r++){const s=t[r].split("=");if(decodeURIComponent(s[0])===a)return decodeURIComponent(s[1])}}static createCallid(){return x.Guid.create(8)+"-"+x.Guid.create(4)+"-4"+x.Guid.create(3)+"-"+x.Guid.create(4)}static checkSubOptionsValid(a){if(a){const{audio:e,video:t,screen:r}=a;if(e===!1&&t===!1&&r===!1)return!1}return!0}static isNetworkAvailable(){return v(this,null,function*(){const a=Kt.prod,{onLine:e}=navigator;if(!e)return!1;try{return yield fetch(`https://${a}/roomserver/v1/ws/version`),!0}catch(t){return!1}})}}var Li=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.API=2]="API",i[i.WARNING=3]="WARNING",i[i.ERROR=4]="ERROR",i[i.NONE=5]="NONE",i))(Li||{});class ke{constructor(a,e,t){p(this,"logLevel");p(this,"outputToConsole");p(this,"maxLogLength");p(this,"maxlogCache");p(this,"uri");p(this,"requestTimeout");p(this,"delay");p(this,"rate");p(this,"hugeBatchCount");p(this,"checkInterval");p(this,"flushModecheckInterval");p(this,"recordOverheadLength");p(this,"httpRequest");p(this,"traceId");p(this,"traceIdPostfix");p(this,"flushMode");p(this,"outputToServer");p(this,"batchCount");p(this,"msgCounter");p(this,"lastRequestTime");p(this,"enable");p(this,"retx");p(this,"lastProfilingTime");p(this,"bytesOut");p(this,"dropped");p(this,"networkdropped");p(this,"lastLogTime",0);p(this,"logArray");p(this,"onTimer",()=>{if(!this.enable)return;this.processCachedLogs();let a=Date.now(),e=a-this.lastLogTime>1e4;if(a-this.lastProfilingTime>=5e3&&!e){let r=this.getProfiling();this.logInternal("[logger] profiling result: "+ke.toString(r))}let t=this.flushMode?this.flushModecheckInterval:this.checkInterval;e&&(t=this.checkInterval),setTimeout(this.onTimer,t)});this.logLevel=3,this.maxLogLength=12e3,this.requestTimeout=5e3,this.delay=2e3,this.rate=3,this.maxlogCache=1e3,this.hugeBatchCount=100,this.outputToConsole=!0,this.outputToServer=!1,this.checkInterval=1e3,this.flushModecheckInterval=200,this.recordOverheadLength=120,this.flushMode=!1,this.batchCount=0,this.retx=[],this.lastProfilingTime=Date.now(),this.bytesOut=0,this.dropped=0,this.networkdropped=0,window&&window.location&&window.location.protocol&&window.location.protocol==="http:"?this.uri="http://"+e+"."+a+"/logstores/"+t+"/track":this.uri="https://"+e+"."+a+"/logstores/"+t+"/track",this.httpRequest=null,this.msgCounter=0,this.traceIdPostfix=x.LocalStorage.uuid+"-"+Date.now(),this.traceId="",this.logArray=[],this.enable=!0,this.lastRequestTime=0,this.onTimer()}static toString(a){let e;if(a instanceof Error)e=a.message;else if(typeof a=="string")e=a;else try{e=JSON.stringify(a)}catch(t){e="undefined"}return e}changeConfig(a){a.enable!==void 0&&(this.enable=a.enable,this.enable||this.clear()),a.logLevel!==void 0&&a.logLevel>=0&&a.logLevel<=5&&(this.logLevel=a.logLevel),a.logToConsole!==void 0&&(this.outputToConsole=a.logToConsole),a.logToServer!==void 0&&(this.outputToServer=a.logToServer),a.maxLogLength!==void 0&&a.maxLogLength>10&&(this.maxLogLength=a.maxLogLength),a.maxlogCache!==void 0&&a.maxlogCache>10&&a.maxlogCache<2e4&&(this.maxlogCache=a.maxlogCache),a.requestTimeout!==void 0&&a.requestTimeout>100&&a.requestTimeout<1e5&&(this.requestTimeout=a.requestTimeout),a.delay!==void 0&&a.delay>0&&a.delay<1e5&&(this.delay=a.delay),a.rate!==void 0&&a.rate>0&&a.rate<1e4&&(this.rate=a.rate)}getProfiling(){let a={enable:this.enable,flush:this.flushMode,cache:this.logArray.length,drop:this.dropped,dropNw:this.networkdropped,kbps:0},e=Date.now();return e-this.lastProfilingTime>500?(a.kbps=Math.round(this.bytesOut*8/(e-this.lastProfilingTime)),this.lastProfilingTime=e,this.bytesOut=0):a.kbps=-1,a}clear(){this.retx=[],this.logArray=[]}setFlushMode(a){this.enable&&(this.flushMode=a,this.flushMode&&this.processCachedLogs())}setTraceID(a){a&&(a.length>64&&(a=a.substring(0,64)),this.traceId=a)}d(...a){if(!this.enable||this.logLevel>0)return;let e=this.getCurrentTime();this.outputToConsole&&console.debug(e,...a);let t=ke.paramArrayToString(a);this.addLog(0,t,!1,e)}i(...a){if(!this.enable||this.logLevel>1)return;let e=this.getCurrentTime();this.outputToConsole&&console.log(e,...a);let t=ke.paramArrayToString(a);this.addLog(1,t,!1,e)}w(...a){if(!this.enable||this.logLevel>3)return;let e=this.getCurrentTime();this.outputToConsole&&console.warn(e,...a);let t=ke.paramArrayToString(a);this.addLog(3,t,!1,e)}e(...a){if(!this.enable||this.logLevel>4)return;let e=this.getCurrentTime();this.outputToConsole&&console.error(e,...a);let t=ke.paramArrayToString(a);t="<error> "+t,this.addLog(4,t,!1,e)}ev(...a){if(!this.enable||this.logLevel>2)return;let e=this.getCurrentTime();this.outputToConsole&&console.log(e,...a);let t=ke.paramArrayToString(a);this.addLog(2,t,!1,e)}a(...a){if(!this.enable||this.logLevel>2)return;let e=this.getCurrentTime();if(this.outputToConsole){if(a.length>2){const r=`${a[1]}`;r.startsWith("__g__")&&console.group(`${r.substring(5)}_${a[2]}`)}console.log(e,...a)}let t=ke.paramArrayToString(a);this.addLog(2,t,!1,e)}ar(...a){if(!this.enable||this.logLevel>2)return;let e=this.getCurrentTime();this.outputToConsole&&(console.log(e,...a),a.length>2&&`${a[1]}`.startsWith("__g__")&&console.groupEnd());let t=ke.paramArrayToString(a);this.addLog(2,t,!1,e)}ae(...a){if(!this.enable||this.logLevel>4)return;let e=this.getCurrentTime();this.outputToConsole&&(console.error(e,...a),this.logLevel>2&&a.length>2&&console.groupEnd());let t=ke.paramArrayToString(a);t="<error> "+t,this.addLog(4,t,!1,e)}logInternal(a){if(!this.enable||this.logLevel>3)return;let e=this.getCurrentTime();this.addLog(2,a,!0,e)}addLog(a,e,t,r){e=r+" "+e,e.length>this.maxLogLength&&(e=e.substring(0,this.maxLogLength));let s=Date.now();t||(this.lastLogTime=s);let n={tm:s.toString(),level:a.toString(),msg:e,count:this.msgCounter.toString(),trace:this.traceId+"-"+this.traceIdPostfix};this.logArray.push(n),this.msgCounter++,this.logArray.length>this.maxlogCache&&this.saveMemory(this.maxlogCache-5)}saveMemory(a){let e=0,t=0;for(;this.logArray.length>a&&e<=4;){for(;t<this.logArray.length;)if(parseInt(this.logArray[t].level)===e){if(this.logArray.splice(t,1),this.dropped++,this.logArray.length<=a)break}else t++;t===this.logArray.length&&(t=0,e++)}}processCachedLogs(){if(!this.outputToServer||this.logArray.length===0&&this.retx.length===0||this.isHttpRequesting()||!this.flushMode&&Date.now()-this.lastRequestTime<this.delay)return;if(this.retx&&this.retx.length>0){let o=this.retx[0].tries?parseInt(this.retx[0].tries)+1:1;if(this.flushMode||this.retx.length<this.hugeBatchCount||o<4){let c=o.toString();for(let u=0;u<this.retx.length;u++)this.retx[u].tries=c;this.batchSend(this.retx);return}else this.retx=[],this.dropped+=this.retx.length,this.networkdropped+=this.retx.length}if(this.logArray.length===0)return;let a=this.flushMode?1.5*1024*1024:this.delay*this.rate,e=0,t=0,r=this.recordOverheadLength;for(let o=0;o<this.logArray.length&&(t+=this.logArray[o].msg.length+r,!(t>a));o++)e=o+1;e===0&&(e=1);let s=this.logArray.splice(0,e);this.batchCount++;let n=this.batchCount.toString();for(let o=0;o<s.length;o++)s[o].batch=n,s[o].tries="0";this.retx=s,this.batchSend(s)}createHttpRequest(){this.httpRequest||window.XMLHttpRequest&&(this.httpRequest=new XMLHttpRequest)}isHttpRequesting(){return this.httpRequest!==null}batchSend(a){if(this.isHttpRequesting())return;this.lastRequestTime=Date.now();let e=this.uri,t=JSON.stringify(a);t='{"__logs__":'+t+"}",this.createHttpRequest(),this.isHttpRequesting()&&(this.bytesOut+=t.length,this.httpRequest.open("POST",e,!0),this.httpRequest.timeout=this.requestTimeout,this.httpRequest.setRequestHeader("x-log-apiversion","0.6.0"),this.httpRequest.setRequestHeader("x-log-bodyrawsize",t.length),this.httpRequest.onload=()=>{this.httpRequest.status!==200&&console.log("Error: failed to post log ",this.httpRequest),this.retx=[],this.lastRequestTime=Date.now(),this.httpRequest=null},this.httpRequest.onerror=()=>{console.log("Error: post log failed"),this.lastRequestTime=Date.now(),this.httpRequest=null},this.httpRequest.onabort=()=>{console.log("Error: post log aborted"),this.lastRequestTime=Date.now(),this.httpRequest=null},this.httpRequest.send(t))}getCurrentTime(){let a=new Date;return("00"+a.getHours()).slice(-2)+":"+("00"+a.getMinutes()).slice(-2)+":"+("00"+a.getSeconds()).slice(-2)+"."+("000"+a.getMilliseconds()).slice(-3)}static paramArrayToString(a){let e="";for(let t=0;t<a.length;t++){e!==""&&(e+=",");let r=ke.toString(a[t]);e+=r}return e}}class A{static getLogger(){return this.logger||(this.logger=new ke("cn-shanghai.log.aliyuncs.com","alirtc","client_h5")),this.logger}static setLogLevel(a){this.getLogger().changeConfig({logLevel:a})}static config(a){this.getLogger().changeConfig(a)}static setTraceID(a){this.getLogger().setTraceID(a)}static setFlushMode(a){this.getLogger().setFlushMode(a)}static interface(...a){this.getLogger().a("[API]",...a)}static interfaceResult(a,e,t,...r){t?this.getLogger().ar("[ARE]",a,e,...r):this.getLogger().ae("[ARE]",a,e,...r)}static event(...a){this.getLogger().ev("[EVT]",...a)}static debug(...a){this.getLogger().d("[DBG]",...a)}static info(...a){this.getLogger().i("[INF]",...a)}static warn(...a){this.getLogger().w("[WARN]",...a)}static error(...a){this.getLogger().e("[ERR]",...a)}}p(A,"logger");const Aa=i=>v(this,null,function*(){const a=new D.AliRTS.SupportUtil;let e={support:!1,detail:{isWebRTCSupported:a.checkMediaDevices()&&a.checkWebRtcSupport(),isH264DecodeSupported:!1,isH264EncodeSupported:!1,isScreenShareSupported:!1,isSendMediaExtensionMsgSupported:!1,isBrowserSupported:a.checkBrowser({errorCode:0,message:""})}};if(e.support=e.detail.isWebRTCSupported&&e.detail.isBrowserSupported,a.checkWebRtcSupport()&&i!=="sendonly"){const t=yield a.checkH264Decode();e.detail.isH264DecodeSupported=t,e.support=e.support&&t}if(a.checkWebRtcSupport()&&i!=="recvonly"){const t=yield a.checkH264Encode();e.detail.isH264EncodeSupported=t,e.support=e.support&&t}return e.detail.isScreenShareSupported=a.checkWebRtcSupport()&&a.checkScreenCapture()&&!D.AliRTS.SystenUtil.isAndroid&&!D.AliRTS.SystenUtil.isIos,e.detail.isSendMediaExtensionMsgSupported=a.checkWebRtcSupport()&&a.checkEncodedTransformSupport(),e});var ae=(i=>(i[i.AliRtcSdkStreamTypeCapture=0]="AliRtcSdkStreamTypeCapture",i[i.AliRtcSdkStreamTypeScreen=1]="AliRtcSdkStreamTypeScreen",i))(ae||{}),Hr=(i=>(i[i.PRE_PROCESSOR=0]="PRE_PROCESSOR",i[i.POST_PROCESSOR=1]="POST_PROCESSOR",i))(Hr||{}),Jt=(i=>(i[i.AUDIO=0]="AUDIO",i[i.VIDEO=1]="VIDEO",i[i.BOTH=2]="BOTH",i))(Jt||{});class mt extends X{constructor(e,t=ae.AliRtcSdkStreamTypeCapture,r=1){super();p(this,"name");p(this,"options");p(this,"type",0);p(this,"streamType");p(this,"trackType");p(this,"zIndex",1);p(this,"_isEnable",!0);p(this,"lastInputAudioTrack");p(this,"lastOutputAudioTrack");p(this,"lastInputVideoTrack");p(this,"lastOutputVideoTrack");this.name=e,this.streamType=t,this.trackType=r,this.options=this.initOptions}get initOptions(){return{}}getOptions(){return this.options}init(){return v(this,null,function*(){})}enable(){this._isEnable||(this._isEnable=!0,this.init(),this.emit("enabled"))}disable(){this._isEnable&&(this._isEnable=!1,this.clear(),this.emit("disabled"))}get isEnable(){return this._isEnable}audioUpdated(e){var t,r;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((r=e.currentAudioTrack)==null?void 0:r.id)}videoUpdated(e){var t,r;return((t=this.lastInputVideoTrack)==null?void 0:t.id)!==((r=e.currentVideoTrack)==null?void 0:r.id)}execute(e,t){return v(this,null,function*(){const r=this.shouldUpdate(e,t);this.lastInputAudioTrack=e.currentAudioTrack,this.lastInputVideoTrack=e.currentVideoTrack,r?yield this.process(e,t):(this.lastOutputAudioTrack&&(this.trackType===2||this.trackType===0)&&this.lastOutputAudioTrack&&e.updateAudioTrack(this.lastOutputAudioTrack),this.lastOutputVideoTrack&&(this.trackType===2||this.trackType===1)&&this.lastOutputVideoTrack&&e.updateVideoTrack(this.lastOutputVideoTrack)),this.lastOutputAudioTrack=e.currentAudioTrack,this.lastOutputVideoTrack=e.currentVideoTrack})}clear(e){this.lastInputAudioTrack=void 0,this.lastInputVideoTrack=void 0,this.lastOutputAudioTrack=void 0,this.lastOutputVideoTrack=void 0}}var It=(i=>(i[i.LiveTranscodingSingle=0]="LiveTranscodingSingle",i[i.LiveTranscodingMix=1]="LiveTranscodingMix",i))(It||{}),Oi=(i=>(i[i.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",i[i.LiveTranscodingAudio=1]="LiveTranscodingAudio",i[i.LiveTranscodingVideo=2]="LiveTranscodingVideo",i))(Oi||{}),St=(i=>(i[i.LiveTranscodingCamera=0]="LiveTranscodingCamera",i[i.LiveTranscodingShareScreen=1]="LiveTranscodingShareScreen",i))(St||{});const Et={0:"camera",1:"shareScreen"};var Vi=(i=>(i[i.LiveTranscoding_Profile_1IN_1080P=0]="LiveTranscoding_Profile_1IN_1080P",i[i.LiveTranscoding_Profile_1IN_720P=1]="LiveTranscoding_Profile_1IN_720P",i[i.LiveTranscoding_Profile_1IN_360P=2]="LiveTranscoding_Profile_1IN_360P",i[i.LiveTranscoding_Profile_2IN_1080P=3]="LiveTranscoding_Profile_2IN_1080P",i[i.LiveTranscoding_Profile_2IN_720P=4]="LiveTranscoding_Profile_2IN_720P",i[i.LiveTranscoding_Profile_2IN_360P=5]="LiveTranscoding_Profile_2IN_360P",i[i.LiveTranscoding_Profile_4IN_1080P=6]="LiveTranscoding_Profile_4IN_1080P",i[i.LiveTranscoding_Profile_4IN_720P=7]="LiveTranscoding_Profile_4IN_720P",i[i.LiveTranscoding_Profile_4IN_360P=8]="LiveTranscoding_Profile_4IN_360P",i[i.LiveTranscoding_Profile_9IN_1080P=9]="LiveTranscoding_Profile_9IN_1080P",i[i.LiveTranscoding_Profile_9IN_720P=10]="LiveTranscoding_Profile_9IN_720P",i[i.LiveTranscoding_Profile_9IN_360P=11]="LiveTranscoding_Profile_9IN_360P",i[i.LiveTranscoding_Profile_12IN_1080P=12]="LiveTranscoding_Profile_12IN_1080P",i[i.LiveTranscoding_Profile_12IN_720P=13]="LiveTranscoding_Profile_12IN_720P",i[i.LiveTranscoding_Profile_12IN_360P=14]="LiveTranscoding_Profile_12IN_360P",i[i.LiveTranscoding_Profile_16IN_1080P=15]="LiveTranscoding_Profile_16IN_1080P",i[i.LiveTranscoding_Profile_16IN_720P=16]="LiveTranscoding_Profile_16IN_720P",i[i.LiveTranscoding_Profile_16IN_360P=17]="LiveTranscoding_Profile_16IN_360P",i[i.LiveTranscoding_Profile_Mixed=9999]="LiveTranscoding_Profile_Mixed",i))(Vi||{});const Ta={0:"1IN_1080P",1:"1IN_720P",2:"1IN_360P",3:"2IN_1080P",4:"2IN_720P",5:"2IN_360P",6:"4IN_1080P",7:"4IN_720P",8:"4IN_360P",9:"9IN_1080P",10:"9IN_720P",11:"9IN_360P",12:"12IN_1080P",13:"12IN_720P",14:"12IN_360P",15:"16IN_1080P",16:"16IN_720P",17:"16IN_360P",9999:"Mixed_Audio"};var qt=(i=>(i[i.LiveTranscoding_HZ_48000=48e3]="LiveTranscoding_HZ_48000",i[i.LiveTranscoding_HZ_44100=44100]="LiveTranscoding_HZ_44100",i[i.LiveTranscoding_HZ_32000=32e3]="LiveTranscoding_HZ_32000",i[i.LiveTranscoding_HZ_16000=16e3]="LiveTranscoding_HZ_16000",i[i.LiveTranscoding_HZ_8000=8e3]="LiveTranscoding_HZ_8000",i))(qt||{}),At=(i=>(i[i.LiveTranscodingNoBody=0]="LiveTranscodingNoBody",i[i.LiveTranscodingBody=1]="LiveTranscodingBody",i))(At||{}),Tt=(i=>(i[i.NOTO_SERIF_CJKSC_REGULAR=0]="NOTO_SERIF_CJKSC_REGULAR",i[i.ALIBABA_PUHUITI_REGULAR=1]="ALIBABA_PUHUITI_REGULAR",i[i.ALIBABA_PUHUITI_BOLD=2]="ALIBABA_PUHUITI_BOLD",i[i.ALIBABA_PUHUITI_Heavy=3]="ALIBABA_PUHUITI_Heavy",i[i.ALIBABA_PUHUITI_LIGHT=4]="ALIBABA_PUHUITI_LIGHT",i[i.ALIBABA_PUHUITI_MEDIUM=5]="ALIBABA_PUHUITI_MEDIUM",i))(Tt||{}),Di=(i=>(i[i.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",i[i.LiveTranscodingCrop=1]="LiveTranscodingCrop",i[i.LiveTranscodingFill=2]="LiveTranscodingFill",i))(Di||{}),Gt=(i=>(i[i.LiveTranscodingNormal=0]="LiveTranscodingNormal",i[i.LiveTranscodingVirtualBackground=1]="LiveTranscodingVirtualBackground",i))(Gt||{}),xi=(i=>(i[i.LiveTranscodingState_IDLE=0]="LiveTranscodingState_IDLE",i[i.LiveTranscodingState_CONNNECT=1]="LiveTranscodingState_CONNNECT",i[i.LiveTranscodingState_RUNNING=2]="LiveTranscodingState_RUNNING",i[i.LiveTranscodingState_RECOVERING=3]="LiveTranscodingState_RECOVERING",i[i.LiveTranscodingState_FAILURE=4]="LiveTranscodingState_FAILURE",i[i.LiveTranscodingState_END=5]="LiveTranscodingState_END",i))(xi||{}),Fe=(i=>(i[i.LiveTranscodingErrorPublishOk=0]="LiveTranscodingErrorPublishOk",i[i.LiveTranscodingErrorStreamNotFound=17825793]="LiveTranscodingErrorStreamNotFound",i[i.LiveTranscodingErrorStreamAlreadyExist=17825794]="LiveTranscodingErrorStreamAlreadyExist",i[i.LiveTranscodingErrorInvalidParam=17825795]="LiveTranscodingErrorInvalidParam",i[i.LiveTranscodingErrorInternalError=17825796]="LiveTranscodingErrorInternalError",i[i.LiveTranscodingErrorRtmpServerError=17825797]="LiveTranscodingErrorRtmpServerError",i[i.LiveTranscodingErrorRtmpStreamUrlError=17825798]="LiveTranscodingErrorRtmpStreamUrlError",i[i.LiveTranscodingErrorPublishTimeout=17825799]="LiveTranscodingErrorPublishTimeout",i[i.LiveTranscodingErrorNotAuthorized=17825800]="LiveTranscodingErrorNotAuthorized",i))(Fe||{}),Ui=(i=>(i[i.TrascodingPublishTaskStatusStart=0]="TrascodingPublishTaskStatusStart",i[i.TrascodingPublishTaskStatusUpdate=1]="TrascodingPublishTaskStatusUpdate",i[i.TrascodingPublishTaskStatusStop=2]="TrascodingPublishTaskStatusStop",i))(Ui||{}),we=(i=>(i[i.MPU_TASK_TRANSACTION_START=0]="MPU_TASK_TRANSACTION_START",i[i.MPU_TASK_TRANSACTION_UPDATE=1]="MPU_TASK_TRANSACTION_UPDATE",i[i.MPU_TASK_TRANSACTION_STOP=2]="MPU_TASK_TRANSACTION_STOP",i[i.MPU_TASK_TRANSACTION_LIST=3]="MPU_TASK_TRANSACTION_LIST",i[i.MPU_TASK_TRANSACTION_POLLING=4]="MPU_TASK_TRANSACTION_POLLING",i[i.MPU_TASK_TRANSACTION_ACKNOWLEDGE=5]="MPU_TASK_TRANSACTION_ACKNOWLEDGE",i[i.MPU_TASK_TRANSACTION_END=6]="MPU_TASK_TRANSACTION_END",i))(we||{});const Pa={0:"/libra/v1/sdk/start-task",1:"/libra/v1/sdk/update-task",2:"/libra/v1/sdk/stop-task",3:"/libra/v1/sdk/list-task",4:"/libra/v1/sdk/polling",5:"/libra/v1/sdk/acknowledge",6:"/"};class Bi{constructor(a,e,t,r,s,n,o,c){p(this,"videoWidth");p(this,"videoHeight");p(this,"videoFramerate",20);p(this,"videoBitrate",2e3);p(this,"videoGop",30);p(this,"audioSamplerate",qt.LiveTranscoding_HZ_44100);p(this,"audioBitrate",500);p(this,"audioChannels",1);this.videoWidth=a,this.videoHeight=e,t&&(this.videoFramerate=t),r&&(this.videoBitrate=r),s&&(this.videoGop=s),n&&(this.audioSamplerate=n),o&&(this.audioBitrate=o),c&&(this.audioChannels=c)}}const Hi=i=>((i&16711680)>>16)+(i&65280)+((i&255)<<16),Ce=(i=0,a)=>{if(a==0)return 0;let e=i/a;return e<0&&(e=0),e>1&&(e=1),e};class zt{constructor(a,e,t){p(this,"mixMode",It.LiveTranscodingSingle);p(this,"singleParam");p(this,"mixParam");a&&(this.mixMode=a),e&&(this.singleParam=e),t&&(this.mixParam=t)}toJson(a,e,t,r,s){const n={appid:e.appId,channelid:e.channelId};if(a===we.MPU_TASK_TRANSACTION_POLLING||a===we.MPU_TASK_TRANSACTION_LIST||a===we.MPU_TASK_TRANSACTION_ACKNOWLEDGE)return a===we.MPU_TASK_TRANSACTION_ACKNOWLEDGE&&(n.messageid=s),n;if(n.taskid=t,a!==we.MPU_TASK_TRANSACTION_STOP){if(n.mixmode=this.mixMode,r&&(n.streamurl=r),this.mixMode===It.LiveTranscodingSingle){const o=this.singleParam;if(o){n.streamtype=o.streamType,o.sourceType===St.LiveTranscodingShareScreen?n.sourcetype=Et[o.sourceType]:n.sourcetype=Et[St.LiveTranscodingCamera];const c=[];o.userId&&c.push(o.userId),n.subspecusers=c}}else if(a===we.MPU_TASK_TRANSACTION_START||a===we.MPU_TASK_TRANSACTION_UPDATE){const o=this.mixParam;if(o){o.taskProfile&&(n.taskprofile=Ta[o.taskProfile]);const c=o.encodeParam||new Bi(1280,720);let u=c.videoWidth,h=c.videoHeight;const l={};Object.keys(c).forEach(f=>{const m=c[f];m>0&&(l[f.toLowerCase()]=m)}),l.lowbitratehighquality=0,n.encodeparam=l,n.backgrounds=o.backgrounds.map(f=>f.toJson(u,h)),n.watermarks=o.watermarks.map(f=>f.toJson(u,h)),n.clockwidgets=o.clockWidgets.map(f=>f.toJson(u,h));const d=o.users.map(f=>f.userId);n.subspecusers=[...new Set(d)],n.layouts=[{audiomixcount:o.users.length,panes:o.users.map((f,m)=>f.toJson(m,u,h,o.mediaProcessMode))}],n.layoutids=["0"],n.cropmode=o.cropMode,n.backgroundcolor=Hi(o.backgroundColor),n.taskmode=o.mediaProcessMode}}}return n}}var Qe=(i=>(i.pre="pre",i.prod="prod",i))(Qe||{}),qe=(i=>(i.AliRtcSdkCommunication="communication",i.AliRtcSdkInteractiveLive="interactive_live",i.AliRtcSdkInteractiveWithLowLatencyLive="cdn_live",i))(qe||{}),Ze=(i=>(i.AliRtcSdkInteractive="interactive",i.AliRtcSdkLive="live",i))(Ze||{}),je=(i=>(i[i.AliEngineLocalDeviceTypeUnknown=0]="AliEngineLocalDeviceTypeUnknown",i[i.AliEngineLocalDeviceTypeMic=1]="AliEngineLocalDeviceTypeMic",i[i.AliEngineLocalDeviceTypeSpeaker=2]="AliEngineLocalDeviceTypeSpeaker",i[i.AliEngineLocalDeviceTypeAudioDevice=3]="AliEngineLocalDeviceTypeAudioDevice",i[i.AliEngineLocalDeviceTypeCamera=4]="AliEngineLocalDeviceTypeCamera",i[i.AliEngineLocalDeviceTypeDisplay=5]="AliEngineLocalDeviceTypeDisplay",i[i.AliEngineLocalDeviceTypeVideoDevice=6]="AliEngineLocalDeviceTypeVideoDevice",i))(je||{}),te=(i=>(i[i.AliEngineLocalDeviceExceptionTypeUnknown=0]="AliEngineLocalDeviceExceptionTypeUnknown",i[i.AliEngineLocalDeviceExceptionTypeMicOpenFail=1]="AliEngineLocalDeviceExceptionTypeMicOpenFail",i[i.AliEngineLocalDeviceExceptionTypeMicInterrupt=2]="AliEngineLocalDeviceExceptionTypeMicInterrupt",i[i.AliEngineLocalDeviceExceptionTypeMicAuthFail=3]="AliEngineLocalDeviceExceptionTypeMicAuthFail",i[i.AliEngineLocalDeviceExceptionTypeMicNotAvailable=4]="AliEngineLocalDeviceExceptionTypeMicNotAvailable",i[i.AliEngineLocalDeviceExceptionTypeSpeakerOpenFail=5]="AliEngineLocalDeviceExceptionTypeSpeakerOpenFail",i[i.AliEngineLocalDeviceExceptionTypeSpeakerInterrupt=6]="AliEngineLocalDeviceExceptionTypeSpeakerInterrupt",i[i.AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable=7]="AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable",i[i.AliEngineLocalDeviceExceptionTypeAudioDeviceException=8]="AliEngineLocalDeviceExceptionTypeAudioDeviceException",i[i.AliEngineLocalDeviceExceptionTypeCameraOpenFail=9]="AliEngineLocalDeviceExceptionTypeCameraOpenFail",i[i.AliEngineLocalDeviceExceptionTypeCameraInterrupt=10]="AliEngineLocalDeviceExceptionTypeCameraInterrupt",i[i.AliEngineLocalDeviceExceptionTypeCameraAuthFail=11]="AliEngineLocalDeviceExceptionTypeCameraAuthFail",i[i.AliEngineLocalDeviceExceptionTypeDisplayException=12]="AliEngineLocalDeviceExceptionTypeDisplayException",i[i.AliEngineLocalDeviceExceptionTypeVideoDeviceException=13]="AliEngineLocalDeviceExceptionTypeVideoDeviceException",i))(te||{}),q=(i=>(i[i.AliRtcConnectionStatusInit=0]="AliRtcConnectionStatusInit",i[i.AliRtcConnectionStatusDisconnected=1]="AliRtcConnectionStatusDisconnected",i[i.AliRtcConnectionStatusConnecting=2]="AliRtcConnectionStatusConnecting",i[i.AliRtcConnectionStatusConnected=3]="AliRtcConnectionStatusConnected",i[i.AliRtcConnectionStatusReconnecting=4]="AliRtcConnectionStatusReconnecting",i[i.AliRtcConnectionStatusFailed=5]="AliRtcConnectionStatusFailed",i))(q||{}),ct=(i=>(i[i.AliRtcConnectionChangedDummyReason=0]="AliRtcConnectionChangedDummyReason",i[i.AliRtcConnectionMediaPathChanged=1]="AliRtcConnectionMediaPathChanged",i[i.AliRtcConnectionSignalingHeartbeatTimeout=2]="AliRtcConnectionSignalingHeartbeatTimeout",i[i.AliRtcConnectionSignalingHeartbeatAlive=3]="AliRtcConnectionSignalingHeartbeatAlive",i[i.AliRtcConnectionSignalingHttpDnsResolved=4]="AliRtcConnectionSignalingHttpDnsResolved",i[i.AliRtcConnectionSignalingHttpDnsFailure=5]="AliRtcConnectionSignalingHttpDnsFailure",i[i.AliRtcConnectionSignalingGslbFailure=6]="AliRtcConnectionSignalingGslbFailure",i[i.AliRtcConnectionSignalingGslbSuccess=7]="AliRtcConnectionSignalingGslbSuccess",i[i.AliRtcConnectionSignalingJoinRoomFailure=8]="AliRtcConnectionSignalingJoinRoomFailure",i[i.AliRtcConnectionSignalingJoinRoomSuccess=9]="AliRtcConnectionSignalingJoinRoomSuccess",i[i.AliRtcConnectionSignalingLeaveRoom=10]="AliRtcConnectionSignalingLeaveRoom",i[i.AliRtcConnectionSignalingConnecting=11]="AliRtcConnectionSignalingConnecting",i[i.AliRtcConnectionChangedNetworkInterrupted=12]="AliRtcConnectionChangedNetworkInterrupted",i))(ct||{}),Fi=(i=>(i[i.AliRtcUserOfflineQuit=0]="AliRtcUserOfflineQuit",i[i.AliRtcUserOfflineDropped=1]="AliRtcUserOfflineDropped",i[i.AliRtcUserOfflineBecomeAudience=2]="AliRtcUserOfflineBecomeAudience",i))(Fi||{}),bt=(i=>(i[i.AliRtcAudioTrackNo=0]="AliRtcAudioTrackNo",i[i.AliRtcAudioTrackMic=1]="AliRtcAudioTrackMic",i[i.AliRtcAudioTrackDual=2]="AliRtcAudioTrackDual",i))(bt||{}),j=(i=>(i[i.AliRtcVideoTrackNo=0]="AliRtcVideoTrackNo",i[i.AliRtcVideoTrackCamera=1]="AliRtcVideoTrackCamera",i[i.AliRtcVideoTrackScreen=2]="AliRtcVideoTrackScreen",i[i.AliRtcVideoTrackBoth=3]="AliRtcVideoTrackBoth",i))(j||{}),B=(i=>(i[i.AliRtcStatePublishIdle=0]="AliRtcStatePublishIdle",i[i.AliRtcStateNoPublish=1]="AliRtcStateNoPublish",i[i.AliRtcStatePublishing=2]="AliRtcStatePublishing",i[i.AliRtcStatePublished=3]="AliRtcStatePublished",i))(B||{}),Z=(i=>(i[i.AliRtcStateSubscribeIdle=0]="AliRtcStateSubscribeIdle",i[i.AliRtcStateNoSubscribe=1]="AliRtcStateNoSubscribe",i[i.AliRtcStateSubscribing=2]="AliRtcStateSubscribing",i[i.AliRtcStateSubscribed=3]="AliRtcStateSubscribed",i))(Z||{}),oe=(i=>(i[i.AliRtcVideoStreamTypeNone=0]="AliRtcVideoStreamTypeNone",i[i.AliRtcVideoStreamTypeHigh=1]="AliRtcVideoStreamTypeHigh",i[i.AliRtcVideoStreamTypeLow=2]="AliRtcVideoStreamTypeLow",i))(oe||{}),Pt=(i=>(i[i.CAMERA_INVALID=-1]="CAMERA_INVALID",i[i.CAMERA_REAR=0]="CAMERA_REAR",i[i.CAMERA_FRONT=1]="CAMERA_FRONT",i))(Pt||{});const Fr=10,jr=5e3,pi=class pi extends X{constructor(e){super();p(this,"ws");p(this,"socketStatus",0);p(this,"wsUrl","");p(this,"lastConnectStartTime",0);p(this,"maxConnectRetryCount",Fr);p(this,"connectRetryCount",0);p(this,"gotErr",!1);p(this,"closedByInvoke",!0);p(this,"isReconnecting",!1);p(this,"networkAvailableChecked",!0);this.maxConnectRetryCount=e!=null?e:Fr,this.onOpen=this.onOpen.bind(this),this.onMessage=this.onMessage.bind(this),this.onError=this.onError.bind(this),this.onClose=this.onClose.bind(this)}get connectUrl(){return this.wsUrl}get connectStatus(){return this.socketStatus}start(e){this.wsUrl=e,this.initWebSocket()}send(e){return this.ws&&this.socketStatus===2?(this.ws.send(JSON.stringify(e)),!0):!1}close(){this.closedByInvoke=!0,this.uninitWebscoket()}reconnect(){this.emit("onReconnectStart"),this.isReconnecting=!0,this.initWebSocket()}onOpen(e){this.socketStatus=2,this.connectRetryCount=0,this.networkAvailableChecked=!1,this.closedByInvoke=!1,this.gotErr=!1,this.isReconnecting=!1,this.emit("onOpen",e)}onMessage(e){this.emit("onMessage",e)}onError(e){this.isReconnecting&&this.emit("onReconnectFail",e),this.emit("onError",e),this.isReconnecting=!1,this.gotErr=!0}onClose(e){return v(this,null,function*(){const t=this.socketStatus;if(A.info(pi.logName,`onClose, status: ${t}, retryCount: ${this.connectRetryCount}`),t!==0||this.connectRetryCount)if(yield Ye.isNetworkAvailable()){if(!this.networkAvailableChecked&&!this.closedByInvoke&&!this.gotErr){this.reconnect();return}this.networkAvailableChecked=!0,this.emit("onAuthInvalid")}else{if(this.connectRetryCount||this.emit("onNetworkError"),this.closedByInvoke)return;this.connectRetryCount+=1,this.connectRetryCount>this.maxConnectRetryCount?this.emit("onConnectFail"):Date.now()-this.lastConnectStartTime>=jr?this.reconnect():window.setTimeout(()=>{this.reconnect()},jr)}this.socketStatus=0,this.emit("onClose",e)})}initWebSocket(){this.uninitWebscoket(),this.socketStatus=1,this.lastConnectStartTime=Date.now(),this.ws=new WebSocket(this.wsUrl),this.ws.addEventListener("open",this.onOpen),this.ws.addEventListener("message",this.onMessage),this.ws.addEventListener("error",this.onError),this.ws.addEventListener("close",this.onClose)}uninitWebscoket(){this.ws&&(this.ws.removeEventListener("open",this.onOpen),this.ws.removeEventListener("message",this.onMessage),this.ws.removeEventListener("error",this.onError),this.ws.removeEventListener("close",this.onClose),this.ws.close(),this.ws=void 0,this.socketStatus=0)}};p(pi,"logName","Socket");let ji=pi;var ne=(i=>(i.KEEPALIVE="keepalive",i.JOINCHANNEL="joinchannel",i.NOTIFYJOIN="notifyjoin",i.NOTIFYSTATUS="notifystatus",i.STATUSREPORT="statusreport",i.LEAVECHANNEL="leavechannel",i.NOTIFYLEAVE="notifyleave",i.NOTIFYPUBLISH="notifypublish",i.BYE="bye",i.RECONNECT="reconnect",i.PUBLISH="publish",i.REFRESHURL="refreshurl",i.UNSUBSCRIBE="unsubscribe",i.ROLEUPDATE="roleupdate",i))(ne||{});class ka{constructor(a,e){p(this,"authInfo");p(this,"userName");p(this,"seqIndex",0);this.authInfo=a,this.userName=e}get roleAuth(){if(this.authInfo.role){const{timestamp:a,nonce:e,token:t,role:r}=this.authInfo;return{timestamp:a,nonce:e,token:t,tokenrole:r}}}refreshAuthInfo(a){this.authInfo=a}getSeqIndex(){return this.seqIndex}createKeepAlivePackage(){return this.createBaseSendPackage("keepalive")}createJoinPackage(){let a=this.createBaseSendPackage("joinchannel");return a.header.displayName=this.userName,a.header.clientversion=Ye.getVersionNumber().toString(),a.header.platform=Br,this.roleAuth&&(a.data.auth=this.roleAuth),a}crateLeavePackage(){return this.createBaseSendPackage("leavechannel")}createStatusPackage(a){let e=this.createBaseSendPackage("statusreport");return e.header.displayName=this.userName,e.data.status=a,e}createPublishPackage(){let a=this.createBaseSendPackage("publish");return a.data.users=[{}],this.roleAuth&&(a.data.auth=this.roleAuth),a}createRoleUpdatePackage(){let a=this.createBaseSendPackage("roleupdate");return a.header.displayName=this.userName,a}createReconnectPackage(a){let e=this.createBaseSendPackage("reconnect");return e.header.displayName=this.userName,e.header.clientversion=Ye.getVersionNumber().toString(),e.header.platform=Br,e.data=W(W({},e.data),a!=null?a:{}),this.roleAuth&&(e.data.auth=this.roleAuth),e}createRefreshUrlPackage(){let a=this.createBaseSendPackage("refreshurl");return a.header.displayName=this.userName,a}createResponsePackage(a,e){return{version:1,code:200,tid:a,msgtype:e}}createBaseSendPackage(a){var t;return++this.seqIndex,{version:1,msgtype:a,tid:x.Guid.create(32),header:{appid:this.authInfo.appId,channelid:this.authInfo.channelId,sessionid:(t=this.authInfo.callid)!=null?t:"",userid:this.authInfo.userId},data:{seq:this.seqIndex}}}}var T=(i=>(i[i.ERR_JOIN_ALREADY_JOINED=16843521]="ERR_JOIN_ALREADY_JOINED",i[i.ERR_JOIN_BAD_APPID=33620481]="ERR_JOIN_BAD_APPID",i[i.ERR_JOIN_INVALID_APPID=33620482]="ERR_JOIN_INVALID_APPID",i[i.ERR_JOIN_BAD_CHANNEL=33620484]="ERR_JOIN_BAD_CHANNEL",i[i.ERR_JOIN_INVALID_CHANNEL=33620483]="ERR_JOIN_INVALID_CHANNEL",i[i.ERR_JOIN_BAD_TOKEN=33620485]="ERR_JOIN_BAD_TOKEN",i[i.ERR_JOIN_TIMEOUT=16908804]="ERR_JOIN_TIMEOUT",i[i.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD=16974081]="ERR_JOIN_ERR_JOIN_BAD_PARAMBAD",i[i.ERR_JOIN_CHANNEL_FAILED=16974338]="ERR_JOIN_CHANNEL_FAILED",i[i.ERR_LOG_ALREADY_INIT=16974085]="ERR_LOG_ALREADY_INIT",i[i.ERR_LOG_ROOT_PATH_ERROR=16974086]="ERR_LOG_ROOT_PATH_ERROR",i[i.ERR_MIC_OPEN_FAIL=17040388]="ERR_MIC_OPEN_FAIL",i[i.ERR_SPEAKER_OPEN_FAIL=17040389]="ERR_SPEAKER_OPEN_FAIL",i[i.ERR_MIC_INTERRUPT=17040390]="ERR_MIC_INTERRUPT",i[i.ERR_SPEAKER_INTERRUPT=17040391]="ERR_SPEAKER_INTERRUPT",i[i.ERR_MIC_AUTH_FAIL=17040392]="ERR_MIC_AUTH_FAIL",i[i.ERR_MIC_NOT_AVAILABLE=17040393]="ERR_MIC_NOT_AVAILABLE",i[i.ERR_SPEAKER_NO_AVAILABLE=17040400]="ERR_SPEAKER_NO_AVAILABLE",i[i.ERR_CAMERA_OPEN_FAIL=17039620]="ERR_CAMERA_OPEN_FAIL",i[i.ERR_CAMERA_INTERRUPT=17039622]="ERR_CAMERA_INTERRUPT",i[i.ERR_VIDEO_DISPLAY_OPEN_FAIL=17039873]="ERR_VIDEO_DISPLAY_OPEN_FAIL",i[i.ERR_VIDEO_DISPLAY_INTERRUPT=1064992]="ERR_VIDEO_DISPLAY_INTERRUPT",i[i.ERR_ICE_CONNECTION_CONNECT_FAIL=17105409]="ERR_ICE_CONNECTION_CONNECT_FAIL",i[i.ERR_ICE_CONNECTION_RECONNECT_FAI=17105410]="ERR_ICE_CONNECTION_RECONNECT_FAI",i[i.ERR_ICE_CONNECTION_MOBILITY_FAIL=17105411]="ERR_ICE_CONNECTION_MOBILITY_FAIL",i[i.ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT=16908812]="ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT",i[i.ERR_LATENCY_LIVE_COMMUNICATION_FAILED=17235971]="ERR_LATENCY_LIVE_COMMUNICATION_FAILED",i[i.ERR_LATENCY_LIVE_MEIDASETTING_FAILED=17235972]="ERR_LATENCY_LIVE_MEIDASETTING_FAILED",i[i.ERR_LATENCY_LIVE_NONE_BROADCASTER=17235973]="ERR_LATENCY_LIVE_NONE_BROADCASTER",i[i.ERR_LATENCY_LIVE_NEED_RESTART=17235974]="ERR_LATENCY_LIVE_NEED_RESTART",i[i.ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER=17235975]="ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER",i[i.ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE=17235976]="ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE",i[i.ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION=17235977]="ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION",i[i.ERR_SDK_PUBLISH_INVAILD=16974597]="ERR_SDK_PUBLISH_INVAILD",i[i.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL=16843782]="ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL",i[i.ERR_SDK_PUBLISH_AUDIO_STRAM_FAILED=16843856]="ERR_SDK_PUBLISH_AUDIO_STRAM_FAILED",i[i.ERR_SDK_PUBLISH_VIDEO_STRAM_FAILED=16843857]="ERR_SDK_PUBLISH_VIDEO_STRAM_FAILED",i[i.ERR_SDK_PUBLISH_DUAL_STRAM_FAILED=16843858]="ERR_SDK_PUBLISH_DUAL_STRAM_FAILED",i[i.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED=16843859]="ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED",i[i.ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR=16843860]="ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR",i[i.ERR_SDK_SUBSCRIBE_INVAILD=16974852]="ERR_SDK_SUBSCRIBE_INVAILD",i[i.ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL=16844112]="ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL",i[i.ERR_SDK_SUBSCRIBE_AUDIO_STRAM_FAILED=16844113]="ERR_SDK_SUBSCRIBE_AUDIO_STRAM_FAILED",i[i.ERR_SDK_SUBSCRIBE_VIDEO_STRAM_FAILED=16844114]="ERR_SDK_SUBSCRIBE_VIDEO_STRAM_FAILED",i[i.ERR_SDK_SUBSCRIBE_DUAL_STRAM_FAILED=16844115]="ERR_SDK_SUBSCRIBE_DUAL_STRAM_FAILED",i[i.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED=16844116]="ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED",i[i.ERR_SDK_INVALID_STATE=16974340]="ERR_SDK_INVALID_STATE",i[i.ERR_INVALID_ARGUMENTS=16974083]="ERR_INVALID_ARGUMENTS",i[i.ERR_SESSION_REMOVED=33620229]="ERR_SESSION_REMOVED",i[i.ERR_SDK_UPDATE_ROLE_CHANNEL=16908801]="ERR_SDK_UPDATE_ROLE_CHANNEL",i[i.ERR_INNER=-1]="ERR_INNER",i[i.ERR_SDK_MPU_TASK_PUBLISH_OK=0]="ERR_SDK_MPU_TASK_PUBLISH_OK",i[i.ERR_SDK_MPU_TASK_STREAM_NOT_FOUND=17825793]="ERR_SDK_MPU_TASK_STREAM_NOT_FOUND",i[i.ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST=17825794]="ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST",i[i.ERR_SDK_MPU_TASK_INVALID_PARAM=17825795]="ERR_SDK_MPU_TASK_INVALID_PARAM",i[i.ERR_SDK_MPU_TASK_INTERNAL_ERROR=17825796]="ERR_SDK_MPU_TASK_INTERNAL_ERROR",i[i.ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR=17825797]="ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR",i[i.ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR=17825798]="ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR",i[i.ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT=17825799]="ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT",i[i.ERR_SDK_MPU_TASK_NOT_AUTHORIZED=17825800]="ERR_SDK_MPU_TASK_NOT_AUTHORIZED",i[i.ERR_SDK_CHANNEL_RELAY_STATE_ERROR=18874369]="ERR_SDK_CHANNEL_RELAY_STATE_ERROR",i[i.ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW=18874370]="ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW",i[i.ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED=18874371]="ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED",i[i.ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID=18874372]="ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID",i[i.ERR_SDK_CHANNEL_RELAY_ROLE_ERROR=18874373]="ERR_SDK_CHANNEL_RELAY_ROLE_ERROR",i[i.ERR_SDK_CHANNEL_RELAY_INVALID_PARAM=18874374]="ERR_SDK_CHANNEL_RELAY_INVALID_PARAM",i[i.ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR=18874375]="ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR",i))(T||{});class E extends Error{constructor(e,t,r){super(t);p(this,"_code");p(this,"_extra");this._code=e,this._extra=r}static fromError(e,t=-1,r=""){return new E(t,e.message||e.reason||r||"error",e.extraInfo)}get code(){return this._code}set code(e){this._code=e}get reason(){return this.message}get extra(){return this._extra}}const Ca=3e4,Ae=class Ae extends X{constructor(e,t,r,s,n){super();p(this,"authInfo");p(this,"userName");p(this,"channelProfile");p(this,"clientRole");p(this,"wsClient");p(this,"packageCreater");p(this,"keepAliveTimer",0);p(this,"packageCache",new Map);p(this,"isFirstConnect",!0);p(this,"aliveChecker",0);p(this,"reconnectData");this.authInfo=e,this.userName=t,this.packageCreater=new ka(e,t),this.channelProfile=r,this.clientRole=s,this.wsClient=new ji(n),this.wsClient.on("onOpen",this.onOpen.bind(this)),this.wsClient.on("onMessage",this.onMessage.bind(this)),this.wsClient.on("onError",this.onError.bind(this)),this.wsClient.on("onClose",this.onClose.bind(this)),this.wsClient.on("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.on("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.on("onNetworkError",this.onNetworkError.bind(this)),this.wsClient.on("onReconnectStart",this.onReconnectStart.bind(this)),this.wsClient.on("onReconnectFail",this.onReconnectFail.bind(this))}start(e){this.wsClient.start(e)}startKeepAlive(){this.keepAliveTimer===0&&(this.keepAliveTimer=window.setInterval(()=>{let e=this.packageCreater.createKeepAlivePackage();this.sendPackage(e)},5e3)),this.checkAlive()}stopKeepAlive(){this.keepAliveTimer!==0&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=0),this.aliveChecker&&(window.clearTimeout(this.aliveChecker),this.aliveChecker=0)}sendPkgCache(){this.packageCache.forEach(e=>{this.wsClient.send(e)})}leave(){let e=this.packageCreater.crateLeavePackage();this.sendPackage(e)}reportStatus(e){let t=this.packageCreater.createStatusPackage(e);this.sendPackage(t)}publish(e){let t=this.packageCreater.createPublishPackage();t.data.users=[],e.subscribe.signal=this.wsClient.connectUrl;const{tracks:r,resume:s}=e;r.forEach(n=>{const{codec:o,ssrc:c}=n;n.userdata=JSON.stringify({codec:o}),n.ssrc=`${c}`,s&&(n.attr={reason:"reconnect"})}),t.data.users.push(e),this.sendPackage(t)}roleUpdate(e){let t=this.packageCreater.createRoleUpdatePackage();t.data.clientrole=e,this.sendPackage(t)}refreshUrl(e){const t=this.packageCreater.createRefreshUrlPackage();t.data=W(_t(W({},t.data),{sessionid:t.header.sessionid}),e),this.sendPackage(t)}refreshAuthInfo(e){this.authInfo=e,this.packageCreater.refreshAuthInfo(e)}close(){A.info(`[${Ae.logName}] close`),this.stopKeepAlive(),this.wsClient.off("onOpen",this.onOpen.bind(this)),this.wsClient.off("onMessage",this.onMessage.bind(this)),this.wsClient.off("onError",this.onError.bind(this)),this.wsClient.off("onClose",this.onClose.bind(this)),this.wsClient.off("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.off("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.off("onReconnectStart"),this.wsClient.off("onReconnectFail"),this.wsClient.close()}sendPackage(e){[ne.KEEPALIVE,ne.RECONNECT,ne.JOINCHANNEL].includes(e.msgtype)||this.packageCache.set(e.tid,e),this.wsClient.send(e)}updateReconnectData(e){this.reconnectData=e}onOpen(){if(A.info(`[${Ae.logName}] onOpen`),this.isFirstConnect){let e=this.packageCreater.createJoinPackage();e.data.configure={channelprofile:this.channelProfile},(this.channelProfile===qe.AliRtcSdkInteractiveLive||this.channelProfile===qe.AliRtcSdkInteractiveWithLowLatencyLive)&&(e.data.configure.clientrole=this.clientRole),this.sendPackage(e)}else{this.stopKeepAlive();const e=this.packageCreater.createReconnectPackage(this.reconnectData);this.sendPackage(e)}}onMessage(e){try{let t=JSON.parse(e.data);this.packageCache.delete(t.tid),this.onRecvMessage(t)}catch(t){A.warn(`[${Ae.logName}] onMessage err`,t,e)}}onError(e){A.warn(`[${Ae.logName}] onError`,e),this.isFirstConnect&&this.onConnectFail()}onConnectFail(){A.warn(`[${Ae.logName}] onConnectFail`);const e=new E(T.ERR_INNER,"Signaling connect failed.");this.isFirstConnect?this.emit("onJoinChannelResult",e):this.emit("onConnectFail",e)}onAuthInvalid(){A.warn(`[${Ae.logName}] onAuthInvalid`),this.isFirstConnect&&this.emit("onAuthInvalid")}onNetworkError(){A.warn(`[${Ae.logName}] onNetworkError`);const e=new E(T.ERR_INNER,"Network error, signaling connect failed.");this.emit("onNetworkError",e)}onClose(e){A.info(`[${Ae.logName}] onClose`,e),this.stopKeepAlive()}onKeepAliveRsp(){this.emit("onKeepAliveRsp"),this.checkAlive()}onReconnectStart(){this.emit("onReconnectStart")}onReconnectFail(){this.emit("onReconnectFail",new E(T.ERR_INNER,"signaling reconnect failed."))}checkAlive(){window.clearTimeout(this.aliveChecker),this.aliveChecker=window.setTimeout(()=>{A.info(`[${Ae.logName}] not alive, reconnect`),this.stopKeepAlive(),this.emit("onReconnectStart"),this.wsClient.reconnect()},Ca)}onRecvMessage(e){switch(e.msgtype!==ne.KEEPALIVE&&A.info(`[${Ae.logName}] recv msg: ${e.msgtype}`),e.msgtype){case ne.JOINCHANNEL:this.onJoinResult(e);break;case ne.KEEPALIVE:this.onKeepAliveRsp();break;case ne.PUBLISH:this.onPublishResult(e);break;case ne.NOTIFYJOIN:this.onNotifyJoin(e);break;case ne.NOTIFYSTATUS:this.onNotifyStatus(e);break;case ne.LEAVECHANNEL:this.onLeaveResult(e);break;case ne.NOTIFYLEAVE:this.onNotifyLeave(e);break;case ne.NOTIFYPUBLISH:this.onNotifyPublish(e);break;case ne.STATUSREPORT:this.onStatusReport(e);break;case ne.BYE:this.onBye(e);break;case ne.ROLEUPDATE:this.onRoleUpdateResult(e);break;case ne.REFRESHURL:this.onRefreshUrlResult(e);break;case ne.RECONNECT:this.onReconnectResult(e);break}}onJoinResult(e){this.isFirstConnect=!1,this.emit("onJoinChannelResult",e)}onLeaveResult(e){this.emit("onLeaveResult",e.code,e.tid)}onPublishResult(e){this.emit("onPublishResult",e.code,e.tid,e.description)}onRoleUpdateResult(e){this.emit("onRoleUpdateResult",e.code,e.tid,e.description)}onRefreshUrlResult(e){this.emit("onRefreshUrlResult",e)}onReconnectResult(e){if(e.code===200)this.sendPkgCache(),this.startKeepAlive(),this.emit("onReconnectSuccess",e.data.users);else{const t=new E(T.ERR_INNER,`reconnect failed, code: ${e.code};description: ${e.description}`);e.code===403&&(t.code=403),this.emit("onReconnectFail",t),this.close()}}onNotifyJoin(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e&&e.data&&e.data.users&&this.emit("onNotifyJoin",e.data.users)}onNotifyStatus(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.status&&e.data.status.length&&this.emit("onNotifyStatus",e.data.status)}onNotifyLeave(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyLeave",e.data.users)}onNotifyPublish(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyPublish",e.data.users)}onStatusReport(e){this.emit("onStatusReport",e.code,e.tid,e.description)}onBye(e){this.stopKeepAlive(),this.emit("onBye",e.reason,e.description)}};p(Ae,"logName","RSMessageCenter");let $i=Ae;const y=(i,a)=>(e,t,r)=>{const s=r.value;return r.value=function(...n){var l;const o=`[${((l=e.constructor)==null?void 0:l.logName)||""}]`,c=Date.now();let u=[];i&&(u=i(n)),A.interface(o,t,...u);const h=s.apply(this,n);return Promise.resolve(h).then(d=>d).catch(d=>d).then(d=>{var S;let f="";const m=d instanceof Error,g=m&&((S=e.constructor)==null?void 0:S.logError);if(!(!a&&!m)){if(g)f=d;else if(m)f=d.message||"";else if(a)d===void 0?f="":f=a(d);else return;A.interfaceResult(o,t,!(m&&g),`${Date.now()-c}ms`,f)}}),h},r},I=i=>i;var Ma=Object.defineProperty,Na=Object.getOwnPropertyDescriptor,Wi=(i,a,e,t)=>{for(var r=t>1?void 0:t?Na(a,e):a,s=i.length-1,n;s>=0;s--)(n=i[s])&&(r=(t?n(a,e,r):n(r))||r);return t&&r&&Ma(a,e,r),r};const Xt=(_e=class extends X{constructor(e,t,r=Qe.prod){super();p(this,"messageCenter");p(this,"authInfo");p(this,"userName");p(this,"channelProfile");p(this,"clientRole");p(this,"reconnectData");p(this,"roomServerUri","");this.channelProfile=e,this.clientRole=t,this.reconnectData={role:{channelprofile:e,clientrole:t}};const s=r===Qe.pre?Kt.pre:Kt.prod;this.roomServerUri=`wss://${s}/roomserver/v1/ws`}updateReconnectData(e){var t;this.reconnectData=e,(t=this.messageCenter)==null||t.updateReconnectData(this.reconnectData)}reset(){A.info("[roomsig] reset"),this.messageCenter&&(this.messageCenter.close(),this.messageCenter=void 0),this.authInfo=void 0}join(e,t,r){return v(this,null,function*(){return new Promise((s,n)=>{A.setTraceID(e.channelId+"-"+e.callid),this.authInfo=e,this.userName=t,this.messageCenter=new $i(e,t,this.channelProfile,this.clientRole,r),this.initMessageCenter(),this.messageCenter.once("onJoinChannelResult",c=>{var u,h;if(A.info("join result: ",c),c.code==200){(u=this.messageCenter)==null||u.sendPkgCache(),(h=this.messageCenter)==null||h.startKeepAlive();let l=c.data;l.tid=c.tid,l.users=c.data.users,l.timestamp=c.timestamp,s(l)}else this.reset(),n(this.handleSignalError(c.code,c.reason,T.ERR_JOIN_CHANNEL_FAILED))}),this.messageCenter.once("onAuthInvalid",()=>{this.reset(),n(new E(T.ERR_JOIN_BAD_TOKEN,"join failed because authentication failed"))}),A.info(`[${_e.logName}]`,"start ws connecting roomserver and auto join when connected");const o={appid:this.authInfo.appId,callid:this.authInfo.callid,channelid:this.authInfo.channelId,userid:this.authInfo.userId,nonce:this.authInfo.nonce||"",timestamp:this.authInfo.timestamp,token:this.authInfo.token,authtype:"app",tid:x.Guid.create(32)};e.role&&(o.tokenrole=e.role),this.messageCenter.start(this.roomServerUri+"?"+Ye.queryingParam(o))})})}leave(){return A.info("[roomsig] leave .."),new Promise((e,t)=>{this.messageCenter?(this.messageCenter.on("onLeaveResult",(r,s)=>{A.info(`[${_e.logName}]`,"recv leave response "+r),r===200?(this.updateReconnectData(),this.reset(),e({tid:s})):t(this.handleSignalError(r,"leave error"))}),A.info(`[${_e.logName}]`,"send leave request"),this.messageCenter.leave()):(A.info(`[${_e.logName}]`,"no message center, ok to leave"),e({tid:""}))})}publish(e){return new Promise((t,r)=>{var s;this.messageCenter?(this.messageCenter.once("onPublishResult",(n,o,c)=>{A.info(`[${_e.logName}]`,"recv pubish response "+n),n===200?(this.updateReconnectData(_t(W({},this.reconnectData),{publish:{users:[e]}})),t({tid:o})):r(this.handleSignalError(n,`publish error, ${c}`))}),this.authInfo&&(e.sessionid=(s=this.authInfo.callid)!=null?s:""),e.callid=x.Guid.create(32),A.info(`[${_e.logName}]`,"assign callid "+e.callid+" and send publish request"),this.messageCenter.publish(e)):r(this.handleSignalError(-1,"publish error, no message center"))})}roleUpdate(e){return new Promise((t,r)=>{if(!this.messageCenter){r(this.handleSignalError(-1,"role update error, no message center"));return}this.messageCenter.on("onRoleUpdateResult",(s,n,o)=>{var c,u;A.info(`[${_e.logName}]`,"recv role update response "+s),s===200?((u=(c=this.reconnectData)==null?void 0:c.role)!=null&&u.clientrole&&(this.reconnectData.role.clientrole=e,this.updateReconnectData(this.reconnectData)),t({tid:n})):r(this.handleSignalError(s,`role update error, ${o}`))}),this.messageCenter.roleUpdate(e)})}setChannelProfile(e){this.channelProfile=e}refreshUrl(e){return A.info(`[${_e.logName}]`,"refreshUrl .."),new Promise((t,r)=>{if(!this.messageCenter){r(this.handleSignalError(-1,"refresh url error, no message center"));return}this.messageCenter.on("onRefreshUrlResult",s=>{const{code:n,description:o,data:c={}}=s||{};A.info("recv refresh url response "+n),n===200?t(c):r(this.handleSignalError(n,`refresh url error, ${o}`))}),A.info("send refresh url request"),this.messageCenter.refreshUrl(e)})}reportStatus(e){return A.info(`[${_e.logName}]`,"reportStatus "+e),new Promise((t,r)=>{this.messageCenter?(this.messageCenter.once("onStatusReport",(s,n)=>{s===200?t():r(new E(s,n))}),this.messageCenter.reportStatus(e)):r(new E(-1,"No messageCenter"))})}handleSignalError(e,t,r=T.ERR_INNER){const s=`signal error: code - ${e}; description - ${t}`;return new E(r,s)}refreshAuthInfo(e){return v(this,null,function*(){var t;this.authInfo&&(this.authInfo=e,(t=this.messageCenter)==null||t.refreshAuthInfo(this.authInfo))})}initMessageCenter(){var e,t,r,s,n,o,c,u,h,l,d,f;(e=this.messageCenter)==null||e.on("onKeepAliveRsp",()=>{this.emit("onKeepAliveRsp")}),(t=this.messageCenter)==null||t.on("onNotifyJoin",m=>{this.emit("onNotifyJoin",m)}),(r=this.messageCenter)==null||r.on("onNotifyStatus",m=>{this.emit("onNotifyStatus",m)}),(s=this.messageCenter)==null||s.on("onNotifyLeave",m=>{this.emit("onNotifyLeave",m)}),(n=this.messageCenter)==null||n.on("onNotifyPublish",m=>{this.emit("onNotifyPublish",m)}),(o=this.messageCenter)==null||o.on("onBye",(m,g)=>{this.emit("onBye",m,g)}),(c=this.messageCenter)==null||c.on("onReconnectStart",()=>{this.emit("onReconnectStart")}),(u=this.messageCenter)==null||u.on("onReconnectSuccess",m=>{this.emit("onReconnectSuccess",m)}),(h=this.messageCenter)==null||h.on("onReconnectFail",m=>{this.emit("onReconnectFail",m)}),(l=this.messageCenter)==null||l.on("onConnectFail",m=>{this.emit("onConnectFail",m),this.reset()}),(d=this.messageCenter)==null||d.on("onNetworkError",m=>{this.emit("onNetworkError",m)}),(f=this.messageCenter)==null||f.on("onAuthInvalid",()=>{this.emit("onAuthInvalid")})}},p(_e,"logName","RoomServerSignaling"),_e);Wi([y()],Xt.prototype,"join",1),Wi([y()],Xt.prototype,"publish",1),Wi([y()],Xt.prototype,"roleUpdate",1);let La=Xt;class Oa extends X{constructor(e,t,r=Qe.prod){super();p(this,"signaling");p(this,"authInfo");p(this,"userName");p(this,"channelProfile");p(this,"clientRole");p(this,"env",Qe.prod);p(this,"maxConnectRetryCount");this.channelProfile=e,this.clientRole=t,this.env=r}reset(){var e;A.info("[signalingmanager] reset"),(e=this.signaling)==null||e.reset(),this.signaling=void 0,this.authInfo=void 0}join(e,t=e.userId,r){return this.maxConnectRetryCount=r,this.userName=t,new Promise((s,n)=>{this.signaling?n(new E(T.ERR_JOIN_ALREADY_JOINED,"already joined")):(A.info("[signalingmanager] create signaling"),this.signaling=new La(this.channelProfile,this.clientRole,this.env),this.initSignaling(),this.signaling.join(e,t,r).then(o=>{this.authInfo=e,s(o)}).catch(o=>{this.reset(),n(o)}))})}retryJoin(){const e=this.authInfo;this.reset(),e&&this.join(e,this.userName,this.maxConnectRetryCount)}leave(){return new Promise((e,t)=>{this.signaling?this.signaling.leave().then(r=>{this.reset(),e(r)}).catch(r=>{t(r)}):e({tid:""})})}publish(e){return new Promise((t,r)=>{var s;this.signaling&&this.authInfo?(e.userid=this.authInfo.userId,e.displayname=(s=this.userName)!=null?s:this.authInfo.userId,this.signaling.publish(e).then(n=>{t(n)}).catch(n=>{r(n)})):r(new E(T.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL,"no signaling"))})}reportStatus(e){return new Promise((t,r)=>{this.signaling?this.signaling.reportStatus(e).then(()=>{t()}).catch(s=>{r(s)}):r(new E(-1,"no signaling"))})}setClientRole(e){return v(this,null,function*(){if(!this.signaling){this.clientRole=e;return}return yield this.signaling.roleUpdate(e)})}setChannelProfile(e){this.signaling?this.signaling.setChannelProfile(e):this.channelProfile=e}refreshUrl(e){return this.signaling?this.signaling.refreshUrl(e):Promise.reject(new E(T.ERR_SDK_INVALID_STATE,"should join first"))}refreshAuthInfo(e){return v(this,null,function*(){var t;try{this.authInfo&&(this.authInfo=W(W({},this.authInfo),e),(t=this.signaling)==null||t.refreshAuthInfo(this.authInfo))}catch(r){throw r}})}initSignaling(){var e,t,r,s,n,o,c,u,h,l,d,f,m;(e=this.signaling)==null||e.on("onKeepAliveRsp",this.onKeepAliveRsp.bind(this)),(t=this.signaling)==null||t.on("onNotifyJoin",this.onNotifyJoin.bind(this)),(r=this.signaling)==null||r.on("onNotifyStatus",this.onNotifyStatus.bind(this)),(s=this.signaling)==null||s.on("onNotifyLeave",this.onNotifyLeave.bind(this)),(n=this.signaling)==null||n.on("onNotifyPublish",this.onNotifyPublish.bind(this)),(o=this.signaling)==null||o.on("onBye",this.onBye.bind(this)),(c=this.signaling)==null||c.on("onReconnectStart",this.onReconnectStart.bind(this)),(u=this.signaling)==null||u.on("onReconnectSuccess",this.onReconnectSuccess.bind(this)),(h=this.signaling)==null||h.on("onReconnectFail",this.onReconnectFail.bind(this)),(l=this.signaling)==null||l.on("onConnectFail",this.onConnectFail.bind(this)),(d=this.signaling)==null||d.on("onNetworkError",this.onNetworkError.bind(this)),(f=this.signaling)==null||f.on("onAuthInvalid",this.onAuthInvalid.bind(this)),(m=this.signaling)==null||m.on("onError",this.onError.bind(this))}onKeepAliveRsp(){this.emit("onKeepAliveRsp")}onNotifyJoin(e){this.emit("onNotifyJoin",e)}onNotifyStatus(e){this.emit("onNotifyStatus",e)}onNotifyLeave(e){this.emit("onNotifyLeave",e)}onNotifyPublish(e){this.emit("onNotifyPublish",e)}onBye(e,t){this.emit("onBye",e,t)}onConnectFail(e){this.reset(),this.emit("onConnectFail",e)}onNetworkError(e){this.emit("onNetworkError",e)}onAuthInvalid(e){}onReconnectStart(){this.emit("onReconnectStart")}onReconnectSuccess(e){this.emit("onReconnectSuccess",e)}onReconnectFail(e){this.emit("onReconnectFail",e)}onError(e){this.emit("onError",e)}}const pt=class pt{static getInstance(){return pt.instance||(pt.instance=new AudioContext),pt.instance.resume(),pt.instance}};p(pt,"instance");let Ki=pt;function Va(i,a,e,t,r){let s=t,n=0,o;const c=i.createAnalyser();c.fftSize=256;const u=new Uint8Array(c.frequencyBinCount);a.connect(c),c.connect(e);const h=()=>{o&&window.clearInterval(o)},l=()=>{o=window.setInterval(()=>{c.getByteFrequencyData(u);let d=Math.round(u.reduce((f,m)=>f+m)/u.length);d=Math.min(100,d),n=d,r&&r(d)},s)};return l(),{updateInterval:d=>{h(),s=d,l()},getLevel:()=>n,dispose:()=>{h(),a.disconnect(),c.disconnect()}}}class Da extends X{constructor(){super();p(this,"audioContext");p(this,"stream");p(this,"sourceNode");p(this,"analyser");this.audioContext=Ki.getInstance(),this.stream=new MediaStream}getLevel(){return this.analyser?this.analyser.getLevel():0}start(e,t=1e3){this.sourceNode&&this.stop(),this.stream.addTrack(e),this.sourceNode=this.audioContext.createMediaStreamSource(this.stream);const r=this.audioContext.createMediaStreamDestination();this.analyser=Va(this.audioContext,this.sourceNode,r,t,s=>{this.emit("audioLevel",s)})}stop(){this.analyser&&this.analyser.dispose(),this.analyser=void 0,this.sourceNode=void 0,this.stream.getAudioTracks().forEach(e=>{this.stream.removeTrack(e)})}dispose(){this.stop()}}class $r extends X{constructor(e,t,r,s){super();p(this,"uid");p(this,"name");p(this,"rtsManager");p(this,"callid","");p(this,"audioLevelMonitor");p(this,"audioVolumeIndicationInterval",0);this.uid=e,this.name=t,this.rtsManager=r,this.audioVolumeIndicationInterval=s,this.audioLevelMonitor=new Da}get userId(){return this.uid}get displayname(){return this.name}setUserInfo(e,t){this.uid=e,this.name=t}refreshUserInfo(e){this.uid=e}getAudioLevel(){return this.audioLevelMonitor.getLevel()}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval=e}clear(){this.audioLevelMonitor.dispose()}}class Wr{static getCurrentStatus(a){let e=0;a.micOpen&&(e+=1),a.micInterrupted&&(e+=2),a.cameraOpen&&(e+=4),a.screenShare&&(e+=128),a.audioDisable&&(e+=8),a.videoDisable&&(e+=16),a.screenDisable&&(e+=256);let t=e.toString(16);for(;t.length<16;)t="0"+t;return t}static parseStatus(a){let e=parseInt(a,16);return{micOpen:!!(e&1),micInterrupted:!!(e&2),cameraOpen:!!(e&4),screenShare:!!(e&128),audioDisable:!!(e&8),videoDisable:!!(e&16),screenDisable:!!(e&256),backgroundMode:!!(e&32),accompanyPlaying:!!(e&64)}}}const Kr="customVideoProfile",Jr="customScreenProfile",kt={width:1280,height:720,frameRate:30,maxBitrate:2e3},Ct={width:1920,height:1080,frameRate:30,maxBitrate:2600},xa={1e4:te.AliEngineLocalDeviceExceptionTypeUnknown,2e4:te.AliEngineLocalDeviceExceptionTypeUnknown,10001:te.AliEngineLocalDeviceExceptionTypeMicNotAvailable,10002:te.AliEngineLocalDeviceExceptionTypeMicAuthFail,10003:te.AliEngineLocalDeviceExceptionTypeMicOpenFail,10005:te.AliEngineLocalDeviceExceptionTypeCameraAuthFail,10004:te.AliEngineLocalDeviceExceptionTypeVideoDeviceException,10006:te.AliEngineLocalDeviceExceptionTypeCameraOpenFail,10010:te.AliEngineLocalDeviceExceptionTypeDisplayException,10011:te.AliEngineLocalDeviceExceptionTypeDisplayException,10012:te.AliEngineLocalDeviceExceptionTypeDisplayException,10013:te.AliEngineLocalDeviceExceptionTypeDisplayException,10014:te.AliEngineLocalDeviceExceptionTypeDisplayException,10019:te.AliEngineLocalDeviceExceptionTypeDisplayException},Ua=i=>i.getAudioTracks()[0];function qr(i){var a;if(((a=i==null?void 0:i.nodeName)==null?void 0:a.toLowerCase())==="video")return i.setAttribute("playsinline",""),i;if(typeof i=="string"){let e=document.getElementById(i);if(e){if(e.nodeName.toLocaleLowerCase()==="video")return e.setAttribute("playsinline",""),e;throw new E(T.ERR_INVALID_ARGUMENTS,"element should be HtmlVideoElement")}else throw new E(T.ERR_INVALID_ARGUMENTS,"element not founded")}else throw new E(T.ERR_INVALID_ARGUMENTS,"element id should be string")}function Ji(i){var e;const a=[];if(Array.isArray(i))i.forEach(t=>{try{a.push(qr(t))}catch(r){}});else if(typeof i=="string"||((e=i==null?void 0:i.nodeName)==null?void 0:e.toLowerCase())==="video")try{a.push(qr(i))}catch(t){}return a}function et(i){return new Promise(a=>setTimeout(a,i))}const Gr=(i,a)=>{const e=()=>(i.muted=!0,Promise.race([et(500),i._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{let t;return i.srcObject!==a?(i.load(),i.srcObject=a,t=i.play(),i._playPromise=t):t=Promise.resolve(),t}));return new Promise(t=>{if(x.BrowserUtil.isMicroMessenger){const r=window.top!==window.self,s=window.WeixinJSBridge||window.top.WeixinJSBridge;s?s.invoke("getNetworkType",{},()=>{t(e())}):(r?window.top.document:document).addEventListener("WeixinJSBridgeReady",()=>{s.invoke("getNetworkType",{},()=>{t(e())})}),setTimeout(()=>{t(e())},1e3)}else t(e())})},tt=i=>{Promise.race([et(100),i._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{i.srcObject=null,i._playPromise=void 0})};var Ba=Object.defineProperty,Ha=Object.getOwnPropertyDescriptor,se=(i,a,e,t)=>{for(var r=t>1?void 0:t?Ha(a,e):a,s=i.length-1,n;s>=0;s--)(n=i[s])&&(r=(t?n(a,e,r):n(r))||r);return t&&r&&Ba(a,e,r),r};class Yt extends X{constructor(){super();p(this,"state");p(this,"time");this.state=B.AliRtcStatePublishIdle,this.time=Date.now()}setState(e){const t=this.state,r=this.time;this.state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-r)/1e3))}}const ie=(rt=class extends $r{constructor(e){const{rtsManager:t,localStreamManager:r,reporter:s,webTrackingClient:n,signalingManager:o,audioVolumeIndicationInterval:c}=e;super("","",t,c);p(this,"url","");p(this,"_isPublishing",!1);p(this,"publishPromise",Promise.resolve(""));p(this,"previewElements",[]);p(this,"screenPreviewElements",[]);p(this,"streamManager");p(this,"streamTracks");p(this,"publishId",x.Guid.create(16));p(this,"signalingManager");p(this,"traceId","");p(this,"monitorTimerId");p(this,"reporter");p(this,"webTrackingClient");p(this,"audioPubState");p(this,"videoPubState");p(this,"videoSmallPubState");p(this,"screenPubState");p(this,"onTrackEnd",e=>{this.emit(e)});this.streamManager=r,this.signalingManager=o,this.reporter=s,this.webTrackingClient=n,this.streamManager.on("trackended",u=>{this.onTrackEnd(u)}),this.streamManager.on("publishupdate",()=>{this.publishUpdate()}),this.audioPubState=new Yt,this.audioPubState.on("change",(u,h,l)=>{this.emit("audioPublishStateChanged",u,h,l)}),this.videoPubState=new Yt,this.videoPubState.on("change",(u,h,l)=>{this.emit("videoPublishStateChanged",u,h,l)}),this.videoSmallPubState=new Yt,this.videoSmallPubState.on("change",(u,h,l)=>{this.emit("dualStreamPublishStateChanged",u,h,l)}),this.screenPubState=new Yt,this.screenPubState.on("change",(u,h,l)=>{this.emit("screenPublishStateChanged",u,h,l)})}get joined(){return!!this.uid}get isPublishing(){return this._isPublishing}get publishStreams(){return this.streamManager.publishStreams}get cameraTrack(){return this.streamManager.cameraStreamInfo.originVideoTrack}get screenTrack(){return this.streamManager.screenStreamInfo.originVideoTrack}get audioTrack(){return this.streamManager.cameraStreamInfo.originAudioTrack}get hasCamera(){return!!this.streamManager.cameraStreamInfo.originVideoTrack}get hasMicrophone(){return!!this.streamManager.cameraStreamInfo.originAudioTrack}get hasScreenShare(){return!!this.streamManager.screenStreamInfo.originVideoTrack}get hasCameraTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:r,msid:s})=>r==="video"&&t&&s===M.VideoLarge))}get hasCameraDualTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:r,msid:s})=>r==="video"&&t&&s===M.VideoSmall))}get hasScreenTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:r,msid:s})=>r==="video"&&t&&s===M.Screen))}get hasAudioTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:r,msid:s})=>r==="audio"&&t&&s===M.Audio))}get cameraDirection(){var e,t;return(t=(e=this.streamManager.cameraStreamInfo)==null?void 0:e.cameraVideoConstraints)==null?void 0:t.facingMode}get audioCaptureDisabled(){return this.streamManager.audioCaptureDisabled}get cameraCaptureDisabled(){return this.streamManager.cameraCaptureDisabled}get publishLocalVideoStreamEnabled(){return this.streamManager.publishLocalVideoStreamEnabled}get publishLocalAudioStreamEnabled(){return this.streamManager.publishLocalAudioStreamEnabled}get publishLocalScreenStreamEnabled(){return this.streamManager.publishLocalScreenStreamEnabled}setPublishLocalAudioStreamEnabled(e){this.streamManager.publishLocalAudioStreamEnabled=e}setPublishLocalVideoStreamEnabled(e){this.streamManager.publishLocalVideoStreamEnabled=e}setPublishLocalScreenStreamEnabled(e){this.streamManager.publishLocalScreenStreamEnabled=e}initInfo(e,t){var r;this.setUserInfo(e.userId,e.userId),this.url=t,this.callid=(r=e.callid)!=null?r:"",this.updatePubId()}setVideoProfile(e,t){return v(this,null,function*(){yield this.streamManager.setVideoProfile(e,t)})}setVideoContentHint(e){this.streamManager.setVideoContentHint(e)}setScreenContentHint(e){this.streamManager.setScreenContentHint(e)}setAudioProfile(e){return v(this,null,function*(){yield this.streamManager.setAudioProfile(e)})}setScreenProfile(e,t){return v(this,null,function*(){yield this.streamManager.setScreenProfile(e,t)})}setCameraDirection(e){if(e===Pt.CAMERA_FRONT)this.streamManager.setCameraVideoConstraints({facingMode:"user"});else if(e===Pt.CAMERA_REAR)this.streamManager.setCameraVideoConstraints({facingMode:"environment"});else throw new E(T.ERR_CAMERA_OPEN_FAIL,`camera direction set to ${e} failed`)}setCameraDeviceId(e){this.streamManager.setCameraVideoConstraints({deviceId:e})}muteLocalCamera(e){this.streamManager.setCameraMuted(e)}muteLocalMic(e){this.streamManager.setAudioMuted(e)}muteLocalScreen(e){this.streamManager.setScreenMuted(e)}setMicrophoneDeviceId(e){this.streamManager.setMicAudioConstraints({deviceId:e})}updatePubId(){this.publishId=x.Guid.create(16)}clearPublishState(){this.streamTracks=void 0}clear(){return v(this,null,function*(){Sr(rt.prototype,this,"clear").call(this),this._isPublishing&&(yield this.unPublish()),this.stopPreview(),this.resetPreviewElements(),this.resetSecondayPreviewElements(),this.clearStream(),this.stopStreamMonitor(),this.streamManager.cameraCaptureDisabled=!1})}resetElement(e){this.previewElements.includes(e)&&(tt(e),this.previewElements.splice(this.previewElements.indexOf(e),1)),this.screenPreviewElements.includes(e)&&(tt(e),this.screenPreviewElements.splice(this.screenPreviewElements.indexOf(e),1))}setPreviewElement(e){const{videoElement:t,screen:r}=e;r?this.screenPreviewElements.includes(t)||this.screenPreviewElements.push(t):this.previewElements.includes(t)||this.previewElements.push(t)}setViewConfig(e,t){if(!e){t===j.AliRtcVideoTrackCamera?this.stopPreview({primary:!0,screen:!1}):this.stopPreview({primary:!1,screen:!0});return}if(![j.AliRtcVideoTrackCamera,j.AliRtcVideoTrackScreen].includes(t))throw new E(T.ERR_INVALID_ARGUMENTS,"set view config invalid track",{track:t});e.forEach(r=>{this.setPreviewElement({videoElement:r,screen:t===j.AliRtcVideoTrackScreen})})}startCameraCapture(e){return v(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,yield this.createLocalStream(e)})}stopCameraCapture(){return v(this,null,function*(){this.streamManager.cameraCaptureDisabled=!0,yield this.stopLocalStream({video:!0})})}stopAudioCapture(){return v(this,null,function*(){this.streamManager.audioCaptureDisabled=!0,yield this.stopLocalStream({audio:!0})})}preview(e){return v(this,null,function*(){const{videoElement:t,screen:r}=e!=null?e:{};try{let s=r?this.streamManager.screenStreamInfo.previewStream:this.streamManager.cameraStreamInfo.previewStream;if(!t)throw new E(T.ERR_INVALID_ARGUMENTS,"no video element found",{videoElement:t});if(!s){A.info(`[${rt.logName}]`,"preview no stream founded");return}return Gr(t,s.mediaStream),this.setPreviewElement(e),s.mediaStream}catch(s){const n=T.ERR_INNER;throw E.fromError(s,n,"preview failed")}})}previewAll(e){return v(this,null,function*(){const{primary:t=!0,screen:r=!0}=e!=null?e:{};if(t&&this.previewElements.length)for(let s=0;s<this.previewElements.length;s++){const n=this.previewElements[s];yield this.preview({videoElement:n})}if(r&&this.screenPreviewElements.length)for(let s=0;s<this.screenPreviewElements.length;s++){const n=this.screenPreviewElements[s];yield this.preview({videoElement:n,screen:!0})}})}stopPreview(e){const{videoElement:t,primary:r=!0,screen:s=!0}=e||{};if(!t)r&&(this.previewElements.forEach(n=>{tt(n)}),this.previewElements=[]),s&&(this.screenPreviewElements.forEach(n=>{tt(n)}),this.screenPreviewElements=[]);else{const n=this.previewElements.findIndex(o=>o===t);if(n>=0)this.previewElements.splice(n,1),tt(t);else{const o=this.screenPreviewElements.findIndex(c=>c===t);o>=0&&(this.screenPreviewElements.splice(o,1),tt(t))}}}resumePublish(){return v(this,null,function*(){this._isPublishing=!1,yield this.startPublish(!0)})}createLocalStream(e){return v(this,null,function*(){try{const t=yield this.streamManager.createLocalStream(e);return t!=null&&t.audioTrack&&this.audioVolumeIndicationInterval>0&&this.audioLevelMonitor.start(t.audioTrack,this.audioVolumeIndicationInterval),e.video?this.previewAll({primary:!0}):e.screen&&this.previewAll({screen:!0}),t}catch(t){const r=xa[t.errorCode];throw r&&(e.audio?this.emit("localDeviceException",je.AliEngineLocalDeviceTypeMic,r,""):e.video?this.emit("localDeviceException",je.AliEngineLocalDeviceTypeCamera,r,""):e.screen?this.emit("localDeviceException",je.AliEngineLocalDeviceTypeDisplay,r,""):this.emit("localDeviceException",je.AliEngineLocalDeviceTypeUnknown,r,"")),t}})}stopLocalStream(e){return v(this,null,function*(){e.audio&&this.audioLevelMonitor.stop(),yield this.streamManager.stopLocalStream(e)})}compareAndPublish(e,t,r){return v(this,null,function*(){var n,o;if(!e&&!t)return;if(e&&!t){const c={};return r===M.Audio?c.audio=!0:r===M.VideoLarge||r===M.VideoSmall?(c.video=!0,c.vMsid=r):r===M.Screen&&(c.screen=!0),yield this.publishDeleteTracks(c)}const s={};if(t!=null&&t.hasVideo&&(s.isScreen=r===M.Screen,s.vMsid=r),t!=null&&t.hasAudio&&(s.aMsid=r),!e&&t)return yield this.publishAdd(t,s,!1);if(e&&t){const c=e.trackId,u=((n=t.videoTrack)==null?void 0:n.id)||((o=t.audioTrack)==null?void 0:o.id);if(c!==u)return yield this.publishReplace(t,s)}})}startPublish(e=!1){return v(this,null,function*(){if(!this.joined)return;const t=yield this.streamManager.publishStreams,{audio:r,video:s,videoSmall:n,screen:o}=t;try{const c=new Date().getTime();r&&this.audioPubState.setState(B.AliRtcStatePublishing),s&&this.videoPubState.setState(B.AliRtcStatePublishing),n&&this.videoSmallPubState.setState(B.AliRtcStatePublishing),o&&this.screenPubState.setState(B.AliRtcStatePublishing),this.publishPromise=this.rtsManager.publish(this.url,e);const u=yield this.publishPromise;this._isPublishing=!0,this.streamTracks=this.rtsManager.publishingTracks,this.traceId=u;const h={userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:e,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callid,tracks:this.streamTracks,traceId:u};yield this.syncPublishToRoomServer(h,t,c),r&&this.audioPubState.setState(B.AliRtcStatePublished),s&&this.videoPubState.setState(B.AliRtcStatePublished),n&&this.videoSmallPubState.setState(B.AliRtcStatePublished),o&&this.screenPubState.setState(B.AliRtcStatePublished)}catch(c){throw r&&this.audioPubState.setState(B.AliRtcStateNoPublish),s&&this.videoPubState.setState(B.AliRtcStateNoPublish),n&&this.videoSmallPubState.setState(B.AliRtcStateNoPublish),o&&this.screenPubState.setState(B.AliRtcStateNoPublish),c}})}publishUpdate(){return v(this,null,function*(){var s,n,o,c;if(!this._isPublishing)return;yield this.publishPromise;const e=yield this.streamManager.publishStreams;let t;const r=new Date().getTime();try{const u=(s=this.streamTracks)==null?void 0:s.find(({ssrc:b,type:w,msid:_})=>w==="audio"&&b&&_===M.Audio),h=yield this.compareAndPublish(u,e.audio,M.Audio);h&&(t=h);const l=(n=this.streamTracks)==null?void 0:n.find(({ssrc:b,type:w,msid:_})=>w==="video"&&b&&_===M.VideoLarge),d=yield this.compareAndPublish(l,e.video,M.VideoLarge);d&&(t=d);const f=(o=this.streamTracks)==null?void 0:o.find(({ssrc:b,type:w,msid:_})=>w==="video"&&b&&_===M.VideoSmall),m=yield this.compareAndPublish(f,e.videoSmall,M.VideoSmall);m&&(t=m);const g=(c=this.streamTracks)==null?void 0:c.find(({ssrc:b,type:w,msid:_})=>w==="video"&&b&&_===M.Screen),S=yield this.compareAndPublish(g,e.screen,M.Screen);if(S&&(t=S),!t)return;yield this.syncPublishToRoomServer(t,e,r)}catch(u){const{code:h}=u!=null?u:{},l=this.url;throw h===403&&l&&(yield this.refreshPushStreamUrl(),t=yield this.publishUpdate()),u}return t})}syncPublishToRoomServer(e,t,r){return v(this,null,function*(){var l;if(!e)throw new E(T.ERR_INNER,"sync publish to room server failed because no publishInfo");const s=yield this.signalingManager.publish(e);e.signaltid=s.tid;const n=new Date().getTime()-r,o=!!t.video,c=!1,u=!!t.screen,h=!!t.audio;this.reporter.reportPublish(this.callid||"",o,c,u,h,0,s.tid,n),this.webTrackingClient.reportPush(this.callid||"",o,c,u,h,0,s.tid,n,r,e.traceid||"",this.traceId,(l=this.url)!=null?l:"")})}refreshPushStreamUrl(){return v(this,null,function*(){const e=new E(T.ERR_INNER,"refresh push stream url error"),t=this.url;if(!t)throw e;const r=yield this.signalingManager.refreshUrl({pushstreamurl:t});if(!(r!=null&&r.pushstreamurl))throw e;this.url=r==null?void 0:r.pushstreamurl})}publishAdd(e,t,r=!1,s=0){return v(this,null,function*(){const n=(t==null?void 0:t.aMsid)===M.Audio,o=(t==null?void 0:t.vMsid)===M.VideoLarge,c=(t==null?void 0:t.vMsid)===M.VideoSmall,u=(t==null?void 0:t.vMsid)===M.Screen;n&&this.audioPubState.setState(B.AliRtcStatePublishing),o&&this.videoPubState.setState(B.AliRtcStatePublishing),c&&this.videoSmallPubState.setState(B.AliRtcStatePublishing),u&&this.screenPubState.setState(B.AliRtcStatePublishing);try{const h=yield this.rtsManager.publishAdd(this.url,e,t,!1,0,!0);n&&this.audioPubState.setState(B.AliRtcStatePublished),o&&this.videoPubState.setState(B.AliRtcStatePublished),c&&this.videoSmallPubState.setState(B.AliRtcStatePublished),u&&this.screenPubState.setState(B.AliRtcStatePublished),this.streamTracks=this.rtsManager.publishingTracks;const l={userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:r,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callid,tracks:this.streamTracks,traceid:h};return this.reportSelfDeviceStatus(),l}catch(h){let l=T.ERR_SDK_PUBLISH_INVAILD;if(n&&(this.audioPubState.setState(B.AliRtcStateNoPublish),l=T.ERR_SDK_PUBLISH_AUDIO_STRAM_FAILED),o&&(this.videoPubState.setState(B.AliRtcStateNoPublish),l=T.ERR_SDK_PUBLISH_VIDEO_STRAM_FAILED),c&&(this.videoSmallPubState.setState(B.AliRtcStateNoPublish),l=T.ERR_SDK_PUBLISH_DUAL_STRAM_FAILED),u&&(this.screenPubState.setState(B.AliRtcStateNoPublish),l=T.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED),h.errorCode===15006&&s<3)return this.publishAdd(e,t,r,s+1);throw E.fromError(h,l,"publish add failed")}})}publishReplace(e,t){return v(this,null,function*(){try{yield this.rtsManager.publishReplace(this.url,e,t),this.traceId="",this.streamTracks=this.rtsManager.publishingTracks;const r={userid:this.userId,sessionid:"",pubid:this.publishId,displayname:this.name,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callid,tracks:this.streamTracks};return this.reportSelfDeviceStatus(),r}catch(r){throw E.fromError(r,T.ERR_INNER,`publish replace failed, vMsid: ${t==null?void 0:t.vMsid} aMsid: ${t==null?void 0:t.aMsid}`)}})}publishDeleteTracks(e){return v(this,null,function*(){const t={userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callid,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{return yield this.rtsManager.publishDelete(this.url,e),this.streamTracks=this.rtsManager.publishingTracks,e.audio&&this.audioPubState.setState(B.AliRtcStateNoPublish),e.video&&(e.vMsid===M.VideoSmall?this.videoSmallPubState.setState(B.AliRtcStateNoPublish):this.videoPubState.setState(B.AliRtcStateNoPublish)),e.screen&&this.screenPubState.setState(B.AliRtcStateNoPublish),this.traceId="",t.tracks=this.streamTracks,this.reportSelfDeviceStatus(),t}catch(r){throw E.fromError(r,T.ERR_INNER,"publish delete tracks failed")}})}publishStop(){return v(this,null,function*(){if(!this._isPublishing)throw new E(T.ERR_INNER,"publish stop failed, previous localStream is required for publishing stopping");A.info(`[${rt.logName}]`,"publishStop",{url:this.url});const e=new Date().getTime();try{const t=this.hasAudioTrackInMS,r=this.hasCameraTrackInMS,s=this.hasCameraDualTrackInMS,n=this.hasScreenTrackInMS;yield this.rtsManager.publishStop(this.url),t&&this.audioPubState.setState(B.AliRtcStateNoPublish),r&&this.videoPubState.setState(B.AliRtcStateNoPublish),s&&this.videoSmallPubState.setState(B.AliRtcStateNoPublish),n&&this.screenPubState.setState(B.AliRtcStateNoPublish),this.traceId="",this.streamTracks=[];const o={userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callid,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};return this.syncPublishToRoomServer(o,{},e),o}catch(t){throw E.fromError(t,T.ERR_INNER,"publish stop failed")}})}unPublish(){return v(this,null,function*(){const e=new Date().getTime();let t={userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callid,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{if(this._isPublishing){const r=this.hasAudioTrackInMS,s=this.hasCameraTrackInMS,n=this.hasCameraDualTrackInMS,o=this.hasScreenTrackInMS;yield this.rtsManager.unpublish(),r&&this.audioPubState.setState(B.AliRtcStateNoPublish),s&&this.videoPubState.setState(B.AliRtcStateNoPublish),n&&this.videoSmallPubState.setState(B.AliRtcStateNoPublish),o&&this.screenPubState.setState(B.AliRtcStateNoPublish),this._isPublishing=!1,this.traceId="",this.clearStream()}return this.reporter.reportUnpublish(this.callid||"",e,0,""),t}catch(r){throw E.fromError(r,T.ERR_INNER,"unpublish failed")}})}reportSelfDeviceStatus(){this.emit(be.Local,this.getDeviceStatus())}getDeviceStatus(){var t,r,s,n;let e={micOpen:!1,micInterrupted:!1,cameraOpen:!1,screenShare:!1,audioDisable:!0,videoDisable:!0,screenDisable:!0,backgroundMode:!1,accompanyPlaying:!1};return e.cameraOpen=this.hasCamera,e.micOpen=this.hasMicrophone,e.screenShare=this.hasScreenShare,e.audioDisable=!((t=this.streamManager.cameraStreamInfo.originAudioTrack)!=null&&t.enabled),e.videoDisable=!((r=this.streamManager.cameraStreamInfo.originVideoTrack)!=null&&r.enabled),e.screenDisable=!this.hasScreenShare||!((n=(s=this.streamManager.screenStreamInfo)==null?void 0:s.originVideoTrack)!=null&&n.enabled),Wr.getCurrentStatus(e)}resetPreviewElements(){this.previewElements=[]}resetSecondayPreviewElements(){this.screenPreviewElements=[]}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0)}clearStream(){this.streamManager.stop(),this.audioPubState.setState(B.AliRtcStatePublishIdle),this.videoPubState.setState(B.AliRtcStatePublishIdle),this.videoSmallPubState.setState(B.AliRtcStatePublishIdle),this.screenPubState.setState(B.AliRtcStatePublishIdle)}getCurrentCameraDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originVideoTrack)==null?void 0:e.getSettings().deviceId}getCurrentMicDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originAudioTrack)==null?void 0:e.getSettings().deviceId}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.streamManager.cameraStreamInfo.originAudioTrack&&this.audioLevelMonitor.start(this.streamManager.cameraStreamInfo.originAudioTrack,e),this.audioVolumeIndicationInterval=e)}sendSEI(e,t,r){return v(this,null,function*(){if(!this.url)return;let s=0;return!t||t<1?s=1:s=t-1,this.rtsManager.sendSEI(this.url,e,s,r)})}getStats(){return v(this,null,function*(){const e=[];if(this.hasAudioTrackInMS){const r=yield this.rtsManager.getPublishAudioStats(this.url);r&&e.push({stats:r,track:bt.AliRtcAudioTrackMic})}const t=[];if(this.hasCameraTrackInMS){const r=yield this.rtsManager.getPublishVideoStats(this.url,M.VideoLarge);r&&t.push({track:j.AliRtcVideoTrackCamera,streamType:oe.AliRtcVideoStreamTypeHigh,stats:r})}if(this.hasCameraDualTrackInMS){const r=yield this.rtsManager.getPublishVideoStats(this.url,M.VideoSmall);r&&t.push({track:j.AliRtcVideoTrackCamera,streamType:oe.AliRtcVideoStreamTypeLow,stats:r})}if(this.hasScreenTrackInMS){const r=yield this.rtsManager.getPublishVideoStats(this.url,M.Screen);r&&t.push({track:j.AliRtcVideoTrackScreen,stats:r})}return{audio:e,video:t}})}},p(rt,"logName","LocalUser"),rt);se([y()],ie.prototype,"clearPublishState",1),se([y()],ie.prototype,"clear",1),se([y()],ie.prototype,"setViewConfig",1),se([y()],ie.prototype,"startCameraCapture",1),se([y()],ie.prototype,"stopCameraCapture",1),se([y()],ie.prototype,"stopAudioCapture",1),se([y()],ie.prototype,"stopPreview",1),se([y()],ie.prototype,"resumePublish",1),se([y()],ie.prototype,"createLocalStream",1),se([y()],ie.prototype,"stopLocalStream",1),se([y(I)],ie.prototype,"startPublish",1),se([y(([i])=>[i])],ie.prototype,"syncPublishToRoomServer",1),se([y()],ie.prototype,"refreshPushStreamUrl",1),se([y(([i,a,e])=>[JSON.stringify(e)])],ie.prototype,"publishAdd",1),se([y(([i,a])=>[JSON.stringify(a)])],ie.prototype,"publishReplace",1),se([y(I)],ie.prototype,"publishDeleteTracks",1),se([y()],ie.prototype,"publishStop",1),se([y()],ie.prototype,"unPublish",1),se([y(([i,a,e])=>[i.length,a,e])],ie.prototype,"sendSEI",1);let zr=ie;var ut=(i=>(i.OPUS="opus",i.H264="H264",i.UNKONWN="",i))(ut||{}),ht=(i=>(i.VideoTrackEnded="videoTrackEnded",i.AudioTrackEnded="audioTrackEnded",i.ScreenTrackEnded="screenTrackEnded",i))(ht||{});const Fa=i=>{const a=new MediaStream;return a.addTrack(i),a},Xr=i=>v(this,null,function*(){return yield D.AliRTS.createStream({custom:!0,mediaStream:i})}),Mt=i=>v(this,null,function*(){const a=Fa(i);return yield Xr(a)}),ja=i=>{const{audio:a,video:e,screen:t}=i;if(e&&t)throw new E(T.ERR_INNER,"create stream error, cannot create video && screen together");return!(!e&&!a&&!t)},$a=i=>i===M.Audio||i===Ni.Audio,Wa=i=>i===M.VideoLarge||i===Ni.VideoLarge,Ka=i=>i===M.VideoSmall,Ja=i=>i===M.Screen;var qa=Object.defineProperty,Ga=Object.getOwnPropertyDescriptor,za=(i,a,e,t)=>{for(var r=t>1?void 0:t?Ga(a,e):a,s=i.length-1,n;s>=0;s--)(n=i[s])&&(r=(t?n(a,e,r):n(r))||r);return t&&r&&qa(a,e,r),r};class Qt extends X{constructor(){super();p(this,"audioInfo",{subscribed:!1,ssrc:"",msid:"",pt:0,red:0,codec:ut.UNKONWN});p(this,"videoLargeInfo",{subscribed:!1,ssrc:"",msid:"",pt:0,red:0,codec:ut.UNKONWN});p(this,"videoSmallInfo",{subscribed:!1,ssrc:"",msid:"",pt:0,red:0,codec:ut.UNKONWN});p(this,"screenInfo",{subscribed:!1,ssrc:"",msid:"",pt:0,red:0,codec:ut.UNKONWN});p(this,"audioVolume",1);p(this,"audioMuted",!1);p(this,"userStatus")}getAudioInfo(){return this.audioInfo}getVideoSmallInfo(){return this.videoSmallInfo}getVideoLargeInfo(){return this.videoLargeInfo}getScreenInfo(){return this.screenInfo}get hasAudio(){return this.audioInfo.ssrc!==""}get hasVideo(){return this.videoLargeInfo.ssrc!==""||this.videoSmallInfo.ssrc!==""}get hasVideoLarge(){return this.videoLargeInfo.ssrc!==""}get hasVideoSmall(){return this.videoSmallInfo.ssrc!==""}get hasScreen(){return this.screenInfo.ssrc!==""}get isAudioSubscribing(){return!!this.audioInfo.subscribed}get isVideoSubscribing(){return!!this.videoLargeInfo.subscribed||!!this.videoSmallInfo.subscribed}get isVideoLargeSubscribing(){return!!this.videoLargeInfo.subscribed}get isVideoSmallSubscribing(){return!!this.videoSmallInfo.subscribed}get isScreenSubscribing(){return!!this.screenInfo.subscribed}get audioCodec(){return this.audioInfo.codec}get videoCodec(){return this.hasVideoLarge?this.videoLargeInfo.codec:this.hasVideoSmall?this.videoSmallInfo.codec:this.hasScreen?this.screenInfo.codec:ut.UNKONWN}get audioTrackInfo(){return this.hasAudio?bt.AliRtcAudioTrackMic:bt.AliRtcAudioTrackNo}get videoTrackInfo(){return this.hasVideo&&this.hasScreen?j.AliRtcVideoTrackBoth:this.hasVideo?j.AliRtcVideoTrackCamera:this.hasScreen?j.AliRtcVideoTrackScreen:j.AliRtcVideoTrackNo}updateTracks(e){let t="",r="",s="",n="";return e?(e.forEach(o=>{var h;let c=ut.UNKONWN;const u=((h=o==null?void 0:o.attr)==null?void 0:h.reason)==="reconnect";if(o.userdata){const{codec:l}=JSON.parse(o.userdata);l&&(c=l)}$a(o.msid)?(t=o.ssrc,this.audioInfo.msid=o.msid,this.audioInfo.codec=c,u&&(this.audioInfo.subscribed=!1)):Ka(o.msid)?(s=o.ssrc,this.videoSmallInfo.msid=o.msid,this.videoSmallInfo.codec=c,u&&(this.videoSmallInfo.subscribed=!1)):Wa(o.msid)?(r=o.ssrc,this.videoLargeInfo.msid=o.msid,this.videoLargeInfo.codec=c,u&&(this.videoLargeInfo.subscribed=!1)):Ja(o.msid)&&(n=o.ssrc,this.screenInfo.msid=o.msid,this.screenInfo.codec=c,u&&(this.screenInfo.subscribed=!1))}),this.updateRemoteTrackSsrc(t,r,s,n)):this.updateRemoteTrackSsrc(t,r,s,n),{}}updateRemoteTrackSsrc(e,t,r,s){this.audioInfo.ssrc=e,this.videoSmallInfo.ssrc=r,this.videoLargeInfo.ssrc=t,this.screenInfo.ssrc=s}updateRemoteTrackSubState(e){return e.video!==void 0&&((e.vMsid===this.videoSmallInfo.msid||!e.vMsid)&&(this.videoSmallInfo.subscribed=e.video),(e.vMsid===this.videoLargeInfo.msid||!e.vMsid)&&(this.videoLargeInfo.subscribed=e.video)),e.screen!==void 0&&(this.screenInfo.subscribed=e.screen),e.audio!==void 0&&(this.audioInfo.subscribed=e.audio),{audioInfo:this.audioInfo,videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo,screenInfo:this.screenInfo}}updateRemoteUserDeviceStatus(e){let t=Wr.parseStatus(e);const{audioDisable:r,videoDisable:s,screenDisable:n}=t;return this.userStatus?(this.userStatus.audioDisable!=r&&(this.userStatus.audioDisable=r,this.emit(be.Remote,r?J.MuteAudio:J.UnmuteAudio)),this.userStatus.videoDisable!=s&&(this.userStatus.videoDisable=s,this.emit(be.Remote,s?J.MuteVideo:J.UnmuteVideo)),this.userStatus.screenDisable!=n&&(this.userStatus.screenDisable=n,this.emit(be.Remote,n?J.MuteScreen:J.UnmuteScreen))):(this.userStatus=t,this.emit(be.Remote,r?J.MuteAudio:J.UnmuteAudio),this.emit(be.Remote,s?J.MuteVideo:J.UnmuteVideo),this.emit(be.Remote,n?J.MuteScreen:J.UnmuteScreen)),!1}}p(Qt,"logName","RemoteStreamInfo"),za([y()],Qt.prototype,"updateRemoteTrackSubState",1);class Yr{constructor(a){p(this,"remoteUser");this.remoteUser=a}get userId(){return this.remoteUser.userId}get displayName(){return this.remoteUser.displayname}get isMuteAudioPlaying(){return this.remoteUser.getAudioMuted()}get hasAudio(){return this.remoteUser.hasAudioTrack}get hasCamera(){return this.remoteUser.hasVideoTrack}get hasCameraLarge(){return this.remoteUser.hasVideoLargeTrack}get hasCameraSmall(){return this.remoteUser.hasVideoSmallTrack}get hasScreenShare(){return this.remoteUser.hasScreenTrack}get isAudioSubscribing(){return this.remoteUser.isAudioSubscribing}get isVideoSubscribing(){return this.remoteUser.isVideoSubscribing}get isVideoLargeSubscribing(){return this.remoteUser.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.remoteUser.isVideoSmallSubscribing}get isScreenSubscribing(){return this.remoteUser.isScreenSubscribing}}var Xa=Object.defineProperty,Ya=Object.getOwnPropertyDescriptor,ce=(i,a,e,t)=>{for(var r=t>1?void 0:t?Ya(a,e):a,s=i.length-1,n;s>=0;s--)(n=i[s])&&(r=(t?n(a,e,r):n(r))||r);return t&&r&&Xa(a,e,r),r};class Nt extends X{constructor(){super();p(this,"state");p(this,"time");p(this,"_enabled");this.state=Z.AliRtcStateSubscribeIdle,this.time=Date.now(),this._enabled=!0}setState(e){if(this.state===e)return;const t=this.state,r=this.time;this.state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-r)/1e3))}get currentState(){return this.state}getEnabled(){return this._enabled}setEnabled(e){this._enabled=e}}const gi=class gi extends $r{constructor(e){var f;const{userId:t,displayName:r,rtsManager:s,usersViewMap:n,reporter:o,webTrackingClient:c,signalingManager:u,localUserId:h,audioVolumeIndicationInterval:l,playoutVolume:d}=e;super(t,r,s,l);p(this,"remoteCallid","");p(this,"remoteUserInfo");p(this,"localUserId");p(this,"lastPubId","");p(this,"stream");p(this,"screenStream");p(this,"viewMap");p(this,"audioTrack");p(this,"audioElement");p(this,"subscribed",!1);p(this,"mediaStream");p(this,"secondaryMediaStream");p(this,"prevSubConfig");p(this,"signalingManager");p(this,"reporter");p(this,"webTrackingClient");p(this,"wantSubAudio",!1);p(this,"wantSubVideo",!1);p(this,"wantSubScreen",!1);p(this,"defaultVideoStreamType",oe.AliRtcVideoStreamTypeHigh);p(this,"audioMuted",!1);p(this,"audioSubState");p(this,"videoSubState");p(this,"videoLargeSubState",new Nt);p(this,"videoSmallSubState",new Nt);p(this,"screenSubState");p(this,"streamInfo");p(this,"streamUrl","");p(this,"playoutVolume",1);this.streamInfo=new Qt,this.remoteUserInfo=new Yr(this),this.streamInfo.on(be.Remote,m=>{this.emit(be.Remote,m,this.userId)}),this.signalingManager=u,this.viewMap=(f=n[t])!=null?f:{cameraViews:[],screenViews:[]},n[t]=this.viewMap,this.reporter=o,this.webTrackingClient=c,this.localUserId=h,this.audioSubState=new Nt,this.audioSubState.on("change",(m,g,S)=>{this.emit("audioSubscribeStateChanged",this.uid,m,g,S)}),this.videoSubState=new Nt,this.videoSubState.on("change",(m,g,S)=>{this.emit("videoSubscribeStateChanged",this.uid,m,g,S)}),this.screenSubState=new Nt,this.screenSubState.on("change",(m,g,S)=>{this.emit("screenSubscribeStateChanged",this.uid,m,g,S)}),this.playoutVolume=d}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e}setRemoteDefaultVideoStreamType(e){e!==this.defaultVideoStreamType&&(this.defaultVideoStreamType=e,this.updateSubscribe())}setAudioMuted(e){this.audioMuted=e,this.toggleAudio(!e)}setPlayoutVolume(e){this.playoutVolume=e,this.audioElement&&(this.audioElement.volume=e)}getAudioMuted(){return this.audioMuted}get hasAudioTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasAudio)}get hasVideoTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideo)}get hasVideoLargeTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideoLarge)}get hasVideoSmallTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideoSmall)}get hasScreenTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasScreen)}get isAudioSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isAudioSubscribing)}get isVideoSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isVideoSubscribing)}get isVideoLargeSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isVideoLargeSubscribing)}get isVideoSmallSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isVideoSmallSubscribing)}get isScreenSubscribing(){var e;return!!((e=this.streamInfo)!=null&&e.isScreenSubscribing)}get audioEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.audioTrack)!=null&&t.enabled)}get videoEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get screenEnabled(){var e,t;return!!((t=(e=this.screenStream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get getAudioTrack(){return this.audioTrack}get getCameraStream(){return this.stream}get getScreenStream(){return this.screenStream}setViewConfig(e,t){if(t!==j.AliRtcVideoTrackScreen&&t!==j.AliRtcVideoTrackCamera)throw new E(T.ERR_INVALID_ARGUMENTS,"track is not AliRtcVideoTrackScreen or AliRtcVideoTrackCamera");e?Ji(e).forEach(s=>{s.setAttribute("playsinline",""),x.BrowserUtil.isMicroMessenger&&(s.setAttribute("x5-video-player-type","h5-page"),s.setAttribute("x5-playsinline",""),x.SystemUtil.isAndroid||x.SystemUtil.isIos&&s.setAttribute("x-webkit-airplay","allow")),t===j.AliRtcVideoTrackScreen?this.viewMap.screenViews.push(s):this.viewMap.cameraViews.push(s),this.play(s,t===j.AliRtcVideoTrackScreen)}):(this.stopPlayAll(t===j.AliRtcVideoTrackScreen),t===j.AliRtcVideoTrackScreen?this.viewMap.screenViews=[]:this.viewMap.cameraViews=[])}clear(e=!0){return v(this,null,function*(){var t;e&&this.doStopSubscribe(this.streamUrl),Sr(gi.prototype,this,"clear").call(this),this.clearStream(),this.clearScreenStream(),(t=this.streamInfo)==null||t.removeAllListeners(be.Remote)})}updateRemoteUserDeviceStatus(e){var t;(t=this.streamInfo)==null||t.updateRemoteUserDeviceStatus(e)}updateRemoteTracks(e,t,r,s){return v(this,null,function*(){var o;return this.remoteCallid=e,this.streamUrl=t!=null?t:"",this.callid=e!=null?e:"",this.streamInfo||(this.streamInfo=new Qt),(o=this.streamInfo)==null?void 0:o.updateTracks(s)})}subscribe(e){return v(this,null,function*(){var u;e?this.reporter.reportSubscribeInvoked(this.userId,e.video,!1,e.screen,e.audio):this.reporter.reportSubscribeInvoked(this.userId);let t=e;if(!t){const{hasAudio:h,hasVideo:l,hasScreen:d}=(u=this.streamInfo)!=null?u:{};t={audio:this.wantSubAudio&&h,video:this.wantSubVideo&&l,screen:this.wantSubScreen&&d}}const{screen:r,audio:s,video:n,vMsid:o}=t,c=[];(n||s)&&c.push({audio:s,video:n,vMsid:o}),r&&c.push({screen:r}),c.length!==0&&(yield Promise.all(c.map(h=>this.subscribeProxy(h))))})}subscribeProxy(e){return v(this,null,function*(){var n,o;let t=new Date().getTime(),r="",s="";try{e.audio&&this.audioSubState.setState(Z.AliRtcStateSubscribing),e.video&&(this.videoSubState.currentState===Z.AliRtcStateSubscribeIdle||this.videoSubState.currentState===Z.AliRtcStateNoSubscribe)&&this.videoSubState.setState(Z.AliRtcStateSubscribing),e.screen&&this.screenSubState.setState(Z.AliRtcStateSubscribing);const c=yield this.rtsManager.subscribe({remoteUser:this,options:e});this.streamInfo.updateRemoteTrackSubState(e),r=c;const{stream:u}=c;if(e.audio){const l=u.audioTrack;l&&(this.audioTrack=l,(n=u.mediaStream)==null||n.removeTrack(l),this.playAudio(),this.audioVolumeIndicationInterval&&this.audioLevelMonitor.start(l,this.audioVolumeIndicationInterval)),this.audioSubState.setState(Z.AliRtcStateSubscribed),this.audioSubState.getEnabled()||this.toggleAudio(!1)}e.video&&(e.vMsid===M.VideoSmall?this.videoSmallSubState.setState(Z.AliRtcStateSubscribed):this.videoLargeSubState.setState(Z.AliRtcStateSubscribed),this.videoSubState.setState(Z.AliRtcStateSubscribed),this.videoSubState.getEnabled()||this.toggleVideo(!1),this.updateStream(u,this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing)),e.screen&&(this.screenSubState.setState(Z.AliRtcStateSubscribed),this.videoSubState.getEnabled()||this.toggleScreen(!1),this.updateScreenStream(u));const h=new Date().getTime()-t;this.webTrackingClient.reportPull(c.callid,c.remoteCallid,c.isVideoLargeSubscribing,c.isVideoSmallSubscribing,c.isScreenSubscribing,c.isAudioSubscribing,0,h,s,r,this.streamUrl,t)}catch(c){const u=new Date().getTime()-t;this.webTrackingClient.reportPull("","",!1,!1,!1,!1,c.code,u,s,r,(o=this.streamUrl)!=null?o:"",t),c&&(c.message=`user(${this.uid}) subscribe error, ${(c==null?void 0:c.message)||""}`);let h=T.ERR_INNER;e.audio&&(h=T.ERR_SDK_SUBSCRIBE_AUDIO_STRAM_FAILED),e.video&&(e.vMsid===M.VideoSmall?h=T.ERR_SDK_SUBSCRIBE_DUAL_STRAM_FAILED:h=T.ERR_SDK_SUBSCRIBE_VIDEO_STRAM_FAILED),e.screen&&(h=T.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED);const l=E.fromError(c,h);throw this.emit("remoteSubscribeError",l),l}})}subscribeDeleteTracks(e){return v(this,null,function*(){const{audio:t,video:r,screen:s,vMsid:n}=e,o=[];(t||r)&&o.push({audio:t,video:r,vMsid:n}),s&&o.push({screen:s}),o.length!==0&&(yield Promise.all(o.map(c=>this.subscribeDeleteProxy(c))))})}subscribeDeleteProxy(e){return v(this,null,function*(){try{const t=yield this.rtsManager.subscibeDelete({remoteUser:this,options:e}),{stream:r}=t!=null?t:{},s={};e.audio===!0&&(s.audio=!1,this.audioSubState.setState(Z.AliRtcStateNoSubscribe)),e.video===!0&&(s.video=!1,e.vMsid===M.VideoSmall?(this.videoSmallSubState.setState(Z.AliRtcStateNoSubscribe),(this.videoLargeSubState.currentState===Z.AliRtcStateNoSubscribe||this.videoLargeSubState.currentState===Z.AliRtcStateSubscribeIdle)&&this.videoSubState.setState(Z.AliRtcStateNoSubscribe)):(this.videoLargeSubState.setState(Z.AliRtcStateNoSubscribe),(this.videoSmallSubState.currentState===Z.AliRtcStateNoSubscribe||this.videoSmallSubState.currentState===Z.AliRtcStateSubscribeIdle)&&this.videoSubState.setState(Z.AliRtcStateNoSubscribe))),e.screen===!0&&(s.screen=!1,this.screenSubState.setState(Z.AliRtcStateNoSubscribe));const{callid:n,remoteCallid:o}=this,c={callid:n,remoteCallid:o,remoteStream:r};return e.audio&&(this.audioLevelMonitor.stop(),this.stopPlayAudio(),this.audioTrack=void 0),this.streamInfo.updateRemoteTrackSubState({audio:e.audio===!0?!1:void 0,video:e.video===!0?!1:void 0,screen:e.screen===!0?!1:void 0,vMsid:e.vMsid}),c}catch(t){throw E.fromError(t,T.ERR_INNER,"subscribe delete failed")}})}restore(){this.clearStream(),this.clearScreenStream(),this.audioTrack=void 0,this.streamInfo.updateRemoteTrackSubState({audio:!1,video:!1,screen:!1})}resumeAudio(){return v(this,null,function*(){var e;return(e=this.audioElement)==null?void 0:e.play()})}resumeVideo(e){return v(this,null,function*(){if(!e||e===j.AliRtcVideoTrackCamera||e===j.AliRtcVideoTrackBoth)return this.playAll();if(!e||e===j.AliRtcVideoTrackScreen||e===j.AliRtcVideoTrackBoth)return this.playAll(!0)})}resumePlay(){this.playAudio(),this.playAll(),this.playAll(!0)}stopSubscribe(e){return v(this,null,function*(){var l,d,f,m,g,S,b;const{isAudioSubscribing:t=!1,isVideoSubscribing:r=!1,isScreenSubscribing:s=!1}=this,n=t&&!((l=e==null?void 0:e.audio)==null||l),o=r&&!((d=e==null?void 0:e.video)==null||d),c=!1,u=s&&!((f=e==null?void 0:e.screen)==null||f);e?this.reporter.reportSubscribeInvoked(this.userId,o,c,u,n):this.reporter.reportUnsubscribeInvoked(this.userId);let h=new Date().getTime();try{let w;e?w=yield this.subscribeDeleteTracks(e):w=yield this.doStopSubscribe(this.streamUrl),e?this.reporter.reportSubscribe((m=w==null?void 0:w.callid)!=null?m:"",this.userId,o,c,u,n,0,"",new Date().getTime()-h,(g=this.localUserId)!=null?g:""):this.reporter.reportUnsubscribe((S=w==null?void 0:w.callid)!=null?S:"",this.userId,new Date().getTime()-h,0,"")}catch(w){throw e?this.reporter.reportSubscribe("",this.userId,o,c,u,n,w.code,"",new Date().getTime()-h,(b=this.localUserId)!=null?b:""):this.reporter.reportUnsubscribe("",this.userId,new Date().getTime()-h,0,""),w}})}doStopSubscribe(e){return v(this,null,function*(){var s,n,o,c;const{callid:t,remoteCallid:r}=this;if((this.isAudioSubscribing||this.isVideoSubscribing||this.isScreenSubscribing)&&e)try{return yield this.rtsManager.subscibeStop(e),this.restore(),{callid:t,remoteCallid:r,remoteStream:this.stream}}catch(u){if(((c=(o=(n=(s=u==null?void 0:u.extraInfo)==null?void 0:s.parsedData)==null?void 0:n.streams)==null?void 0:o[0])==null?void 0:c.res_code)!==404)throw E.fromError(u,T.ERR_INNER,"subscribe stop failed")}})}updateStream(e,t=!1){return v(this,null,function*(){this.stream&&this.stream.videoTrack&&e.mediaStream&&t&&(yield new Promise(r=>{let s,n;if(e.mediaStream){n=document.createElement("video");const o=()=>{A.event(`uid: ${this.userId} new mediaStream canplay`),n&&n.removeEventListener("canplaythrough",o,!1),n=void 0,clearTimeout(s),r(!0)};n.addEventListener("canplaythrough",o,!1),(n._playPromise||Promise.resolve()).then(()=>{n&&e.mediaStream&&(n.srcObject=e.mediaStream)})}else r(!0);s=window.setTimeout(()=>{A.event(`uid: ${this.userId} new mediaStream timeout`),n=void 0,r(!0)},3e3)}),this.updateSubscribe()),this.stream=e,this.playAll(),!this.subscribed&&e&&(this.subscribed=!0),e.hasAudio&&this.isAudioSubscribing&&e.enableAudio(),e.hasVideo&&this.isVideoSubscribing&&e.enableVideo()})}updateScreenStream(e){this.screenStream=e,this.playAll(!0),!this.subscribed&&e&&(this.subscribed=!0),e.hasVideo&&this.isScreenSubscribing&&e.enableVideo()}clearStream(){var e;(e=this.stream)==null||e.stop(),this.stream=void 0}clearScreenStream(){var e;(e=this.screenStream)==null||e.stop(),this.screenStream=void 0}updateSubscribe(){var r,s,n,o,c,u,h,l;const e={},t={};return this.wantSubAudio&&!this.isAudioSubscribing&&((r=this.streamInfo)!=null&&r.hasAudio)?e.audio=!0:(!this.wantSubAudio||!((s=this.streamInfo)!=null&&s.hasAudio))&&this.isAudioSubscribing&&(t.audio=!0),this.wantSubVideo&&((n=this.streamInfo)!=null&&n.hasVideo)?(this.defaultVideoStreamType===oe.AliRtcVideoStreamTypeLow&&!this.isVideoSmallSubscribing&&((o=this.streamInfo)!=null&&o.hasVideoSmall)?(e.video=!0,e.vMsid=M.VideoSmall):!this.isVideoLargeSubscribing&&((c=this.streamInfo)!=null&&c.hasVideoLarge)&&!(this.defaultVideoStreamType===oe.AliRtcVideoStreamTypeLow&&this.isVideoSmallSubscribing)&&(e.video=!0,e.vMsid=M.VideoLarge),this.defaultVideoStreamType===oe.AliRtcVideoStreamTypeLow&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall?(t.video=!0,t.vMsid=M.VideoLarge):this.defaultVideoStreamType===oe.AliRtcVideoStreamTypeHigh&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&(t.video=!0,t.vMsid=M.VideoSmall)):(!this.wantSubVideo||!((u=this.streamInfo)!=null&&u.hasVideo))&&this.isVideoSubscribing&&(t.video=!0,t.vMsid=this.streamInfo.isVideoSmallSubscribing?M.VideoSmall:M.VideoLarge),this.wantSubScreen&&!this.isScreenSubscribing&&((h=this.streamInfo)!=null&&h.hasScreen)?e.screen=!0:(!this.wantSubScreen||!((l=this.streamInfo)!=null&&l.hasScreen))&&this.isScreenSubscribing&&(t.screen=!0),(e.audio||e.video||e.screen)&&this.subscribe(e),t.audio&&t.video&&t.screen?this.stopSubscribe():(t.audio||t.video||t.screen)&&this.subscribeDeleteTracks(t),{addOption:e,deleteOption:t}}handleAutoPlayFailed(){this.emit("remoteAudioAutoPlayFail",this.uid);const e=()=>{this.resumeAudio().then(()=>{document.removeEventListener("click",e,!1),document.removeEventListener("touchstart",e,!1)})};document.addEventListener("click",e,!1),document.addEventListener("touchstart",e,!1)}handleVideoPlayFailded(e,t){this.emit("remoteVideoAutoPlayFail",this.uid,t);const r=()=>{var n;const s=(n=t===j.AliRtcVideoTrackScreen?this.screenStream:this.stream)==null?void 0:n.mediaStream;e.srcObject===s&&this.play(e,t===j.AliRtcVideoTrackScreen),document.removeEventListener("click",r,!1),document.removeEventListener("touchstart",r,!1)};document.addEventListener("click",r,!1),document.addEventListener("touchstart",r,!1)}playAudio(){return v(this,null,function*(){var t,r;if(!this.audioTrack)return;if(this.toggleAudio(!this.audioMuted),this.audioElement||(this.audioElement=document.createElement("audio"),this.audioElement.volume=this.playoutVolume),((r=(t=this.audioElement.srcObject)==null?void 0:t.getAudioTracks())==null?void 0:r[0])!==this.audioTrack){let s=this.audioElement.srcObject;s?s.getAudioTracks().forEach(n=>{s.removeTrack(n)}):(s=new MediaStream,this.audioElement.srcObject=s),s.addTrack(this.audioTrack)}this.audioElement.play().catch(()=>{this.handleAutoPlayFailed()});const e=this.audioElement;this.audioElement.addEventListener("playing",function s(){e.removeEventListener("playing",s),x.SystemUtil.isIos&&parseInt(x.SystemUtil.systemVersion)<=14&&(e.muted||(e.pause(),e.play()))})})}stopPlayAudio(){this.audioElement&&(this.audioElement.pause(),this.audioElement.srcObject=null)}playAll(e=!1){e?(this.viewMap.screenViews||[]).forEach(t=>{this.play(t,e)}):(this.viewMap.cameraViews||[]).forEach(t=>{this.play(t,e)})}play(e,t=!1){const r=t?this.screenStream:this.stream;!e||!r||!r.mediaStream||Gr(e,r.mediaStream).catch(s=>{s.code===20||s.name==="AbortError"||this.handleVideoPlayFailded(e,t?j.AliRtcVideoTrackScreen:j.AliRtcVideoTrackCamera)})}stopPlayAll(e=!1){e?this.viewMap.screenViews.forEach(t=>{tt(t)}):this.viewMap.cameraViews.forEach(t=>{tt(t)})}toggleAudio(e=!0){this.audioSubState.setEnabled(e),this.audioTrack&&(this.audioTrack.enabled=e)}toggleVideo(e=!0){this.videoSubState.setEnabled(e),this.stream&&(e?this.stream.enableVideo():this.stream.disableVideo())}toggleScreen(e=!0){this.screenSubState.setEnabled(e),this.screenStream&&(e?this.screenStream.enableVideo():this.screenStream.disableVideo())}getStats(){return v(this,null,function*(){var r,s;const e=[];if(this.isAudioSubscribing){const n=yield this.rtsManager.getSubscribeAudioStats(this.streamUrl);n&&e.push({uid:this.uid,track:bt.AliRtcAudioTrackMic,stats:n})}const t=[];if((r=this.streamInfo)!=null&&r.isVideoLargeSubscribing){const n=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,M.VideoLarge);n&&t.push({uid:this.uid,track:j.AliRtcVideoTrackCamera,streamType:oe.AliRtcVideoStreamTypeHigh,stats:n})}if((s=this.streamInfo)!=null&&s.isVideoSmallSubscribing){const n=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,M.VideoSmall);n&&t.push({uid:this.uid,track:j.AliRtcVideoTrackCamera,streamType:oe.AliRtcVideoStreamTypeLow,stats:n})}if(this.isScreenSubscribing){const n=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,M.Screen);n&&t.push({uid:this.uid,track:j.AliRtcVideoTrackScreen,stats:n})}return{audio:e,video:t}})}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.audioTrack&&this.audioLevelMonitor.start(this.audioTrack,e),this.audioVolumeIndicationInterval=e)}};p(gi,"logName","RemoteUser");let re=gi;ce([y()],re.prototype,"clear",1),ce([y()],re.prototype,"updateRemoteUserDeviceStatus",1),ce([y()],re.prototype,"updateRemoteTracks",1),ce([y(I)],re.prototype,"subscribe",1),ce([y()],re.prototype,"subscribeProxy",1),ce([y(I)],re.prototype,"subscribeDeleteProxy",1),ce([y()],re.prototype,"restore",1),ce([y(I)],re.prototype,"stopSubscribe",1),ce([y(I)],re.prototype,"doStopSubscribe",1),ce([y()],re.prototype,"clearStream",1),ce([y()],re.prototype,"clearScreenStream",1),ce([y()],re.prototype,"updateSubscribe",1),ce([y()],re.prototype,"playAudio",1),ce([y()],re.prototype,"stopPlayAudio",1),ce([y(I)],re.prototype,"playAll",1),ce([y()],re.prototype,"play",1),ce([y()],re.prototype,"stopPlayAll",1);var it=(i=>(i[i.AliRtcPluginErrorCodeSuccess=0]="AliRtcPluginErrorCodeSuccess",i[i.AliRtcPluginErrorCodeFailed=-1]="AliRtcPluginErrorCodeFailed",i[i.AliRtcPluginErrorNoFindPlugin=-2]="AliRtcPluginErrorNoFindPlugin",i[i.AliRtcPluginErrorParameterError=-3]="AliRtcPluginErrorParameterError",i[i.AliRtcPluginErrorLoadError=-4]="AliRtcPluginErrorLoadError",i[i.AliRtcPluginErrorCreateError=-5]="AliRtcPluginErrorCreateError",i[i.AliRtcPluginErrorInitError=-6]="AliRtcPluginErrorInitError",i[i.AliRtcPluginErrorInitTokenError=-7]="AliRtcPluginErrorInitTokenError",i))(it||{});class Qa extends X{constructor(){super(...arguments);p(this,"plugins",new Map)}add(e,t){if(this.plugins.has(e.name))throw new E(it.AliRtcPluginErrorCreateError,`Plugin ${e.name} already exists`);this.plugins.set(e.name,e),t&&e.setOptions(t),this.emit("added",e),e.on("enabled",()=>this.emit("added",e)),e.on("disabled",()=>this.emit("removed",e)),e.on("updated",()=>this.emit("updated",e))}remove(e){const t=this.plugins.get(e);if(!t)throw new E(it.AliRtcPluginErrorNoFindPlugin,`Plugin ${e} not founded`);this.plugins.delete(e),t.removeAllListeners(),this.emit("removed",t)}get(e){return this.plugins.get(e)}has(e){return!!this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}}var Za=Object.defineProperty,en=Object.getOwnPropertyDescriptor,ve=(i,a,e,t)=>{for(var r=t>1?void 0:t?en(a,e):a,s=i.length-1,n;s>=0;s--)(n=i[s])&&(r=(t?n(a,e,r):n(r))||r);return t&&r&&Za(a,e,r),r};const Zt=([i])=>{const{remoteUser:a,options:e}=i;return[`user(${a.userId})`,e]},pe=(Te=class extends X{constructor(e){super();p(this,"rts");p(this,"encodedInsertableStreams",!0);p(this,"audioRedEnabled",!1);p(this,"localStreamManager");p(this,"connecting",!1);p(this,"connected",!1);p(this,"connectionResolve");p(this,"connectingPromise");p(this,"dcResolve");p(this,"dcConnectingPromise");p(this,"_publishingTracks",[]);this.rts=D.AliRTS.createClient(),this.localStreamManager=e,this.rts.on("connectStatusChange",t=>{var r,s,n,o;if(A.event(`[${Te.logName}]`,"rts connectStatusChange to:",t.status),t.status===D.EConnectStatus.CONNECT_STATUS_DISCONNECTED)this.emit("disconnected"),this.setConnected(!1);else if(t.status===D.EConnectStatus.CONNECT_STATUS_RECONNECTING)this.emit("reconnecting"),this.setConnected(!1);else if(t.status===D.EConnectStatus.CONNECT_STATUS_CONNECTED){this.setConnected(!0);const c=(o=(n=(s=(r=this.rts.commonController)==null?void 0:r.peerCore)==null?void 0:s.getSignal())==null?void 0:n.getDatachannelCore())==null?void 0:o.readyState;A.event(Te.logName,"dcReadyState:",c),c==="open"&&this.dcResolve&&this.dcResolve(!0),this.emit("connected")}}),this.rts.on("datachannelStatusChange",t=>{A.event(`[${Te.logName}]`,"rts datachannelStatusChange to:",t.status),t.status===D.EDatachannelStatus.DATACHANNEL_STATUS_OPEN?this.dcResolve&&this.dcResolve(!0):t.status===D.EDatachannelStatus.DATACHANNEL_STATUS_CLOSE&&(this.dcConnectingPromise=new Promise(r=>{this.dcResolve=r}),console.warn("DC DisConnected"))}),this.rts.on("receivedSEI",t=>{this.emit("seimessage",t.url,t.sei.payloadType,t.sei.data)})}setEncodedInsertableStreams(e){this.encodedInsertableStreams=e}setAudioRedEnabled(e){var t;if(e!==this.audioRedEnabled){try{const s=[...((t=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:t.codecs)||[]];if(s.length>0){if(e){const n=s.findIndex(c=>c.mimeType==="audio/red"),o=s.findIndex(c=>c.mimeType==="audio/opus");if(n>-1&&o>-1&&n>o){const c=s[o];s[o]=s[n],s[n]=c}}this.rts.setSenderCodecPreferences({audio:s}),this.rts.setReceiverCodecPreferences({audio:s})}}catch(r){}this.audioRedEnabled=e}}destroy(){this.rts.unpublish()}startConnect(){this.connecting=!0,this.connectingPromise=new Promise(e=>{this.connectionResolve=e}),this.dcConnectingPromise=new Promise(e=>{this.dcResolve=e})}setConnected(e){var t;this.connected=e,this.connecting=!1,(t=this.connectionResolve)==null||t.call(this,!0),e||(this.dcConnectingPromise=new Promise(r=>{this.dcResolve=r}))}get isConnecting(){return this.connecting}get isConnected(){return this.connected}get publishingTracks(){return this._publishingTracks}getPubMsid(e,t){const{aMsid:r,vMsid:s}=t!=null?t:{},n={};return e.hasAudio&&(n.aMsid=[r!=null?r:M.Audio]),e.hasScreen&&(n.vMsid=[M.Screen]),e.hasVideo&&(n.vMsid=[s!=null?s:t!=null&&t.isScreen?M.Screen:M.VideoLarge]),n}updatePublishingTracks(e){e&&(this._publishingTracks=e.map(({msid:t,from:r,ssrc:s,codec:n,type:o,trackId:c})=>({msid:t,from:r,type:o,ssrc:`${s}`,codec:n!=null?n:"",trackId:c})))}httpPublish(e,t=!1){return v(this,null,function*(){const{publishStream:r,videoSmallStream:s,screenStream:n,vMsid:o}=yield this.localStreamManager.createHTTPPublishStream();if(!r)return"";const c=this.getPubMsid(r,{vMsid:o});c.retryTimes=0,this.encodedInsertableStreams&&(c.encodedInsertableStreams=!0);let u=!r.hasVideo,h=o;try{this.startConnect();const l=yield this.rts.publish(e,r,c);return this.setConnected(!0),this._publishingTracks=this.rts.getPublishTrackInfoList(),s&&(yield this.publishAdd(e,s,{vMsid:M.VideoSmall},t),u=!1,h=M.VideoSmall),n&&(yield this.publishAdd(e,n,{vMsid:M.Screen},t),u=!1,h=M.Screen),yield this.waitPublishSender(e,u,h),l}catch(l){throw this.setConnected(!1),l}})}waitPublishSender(e,t=!1,r){return v(this,null,function*(){const s=(n,o)=>{let c=0;const u=()=>(t?this.rts.getPublishAudioStats(e,r):this.rts.getPublishVideoStats(e,r)).then(l=>!(l.bytesSent>0)&&c<n?(c++,new Promise(f=>setTimeout(()=>f(u()),o))):Promise.resolve());return u()};return Promise.race([et(1e3),s(5,100)]).catch(()=>{})})}checkSubscribeStats(e,t){return v(this,null,function*(){const r=(s,n)=>{let o=0;const c=()=>{const u=this.rts.getSubscribeVideoStats(e,t);return this.rts.getSubscribeAudioStats(e).then(l=>{var d;A.event(`[${Te.logName}]`,"AudioLevel",((d=l.audioLevel)!=null?d:0).toFixed(2))}),u.then(l=>(A.event(`[${Te.logName}]`,"VideoFramesDecoded",l.framesDecoded),!(l.framesDecoded>0)&&o<s?(o++,new Promise(f=>setTimeout(()=>f(c()),n))):Promise.resolve()))};return c()};return Promise.race([et(1200),r(10,100)]).catch(()=>{})})}getPublishVideoStats(e,t){return v(this,null,function*(){return yield this.rts.getPublishVideoStats(e,t)})}getPublishAudioStats(e,t){return v(this,null,function*(){return yield this.rts.getPublishAudioStats(e,t)})}publishAdd(e,t,r,s=!1,n=0,o=!1){return v(this,null,function*(){try{yield this.dcConnectingPromise;const c=yield this.rts.publishAdd([W({url:e,stream:t,updateSourceStream:!1},this.getPubMsid(t,r))]);if(c){const[u]=c;return this.updatePublishingTracks(u.trackInfoList),o&&(yield this.waitPublishSender(e,!t.hasVideo,t.hasVideo?r==null?void 0:r.vMsid:r==null?void 0:r.aMsid)),u.traceId||""}}catch(c){if(c.errorCode===15006&&n<3)return yield this.publishAdd(e,t,r,s,n+1);throw c}return""})}publishDelete(e,t){return v(this,null,function*(){var h,l,d,f,m,g,S,b;yield this.dcConnectingPromise;const r=(l=(h=this.publishingTracks)==null?void 0:h.find(({msid:w})=>w===M.Audio))==null?void 0:l.msid,s=(f=(d=this.publishingTracks)==null?void 0:d.find(({msid:w})=>w===M.VideoLarge))==null?void 0:f.msid,n=(g=(m=this.publishingTracks)==null?void 0:m.find(({msid:w})=>w===M.Screen))==null?void 0:g.msid,o=[];t.screen&&n?o.push(n):t.video&&o.push(t.vMsid||s);const c=[];t.audio&&r&&c.push(r),A.event(Te.logName,"publishDelete",{streamUrl:e,aMsid:c,vMsid:o});const[u]=(yield this.rts.publishDeleteTracks([{url:e,aMsid:c,vMsid:o}]))||[];return A.event(Te.logName,"publishDelete",{result:u}),u&&this.updatePublishingTracks(u.trackInfoList),((b=(S=u==null?void 0:u.trackInfoList)==null?void 0:S[0])==null?void 0:b.trackId)||""})}publishReplace(e,t,r){return v(this,null,function*(){var u,h;yield this.dcConnectingPromise;const{vMsid:s,aMsid:n}=r!=null?r:{},o=yield this.rts.publishReplaceTracks([{url:e,stream:t,updateSourceStream:!1,vMsid:s,aMsid:n}]),[c]=o;return this.updatePublishingTracks(c.trackInfoList),((h=(u=c==null?void 0:c.trackInfoList)==null?void 0:u[0])==null?void 0:h.trackId)||""})}publishStop(e){return v(this,null,function*(){return yield this.rts.publishStop([{url:e}]),this._publishingTracks=[],""})}unpublish(){return v(this,null,function*(){yield this.rts.unpublish(),this.connecting=!1,this.connected=!1})}getSubConfig(e,t){let r=t!=null?t:{};t||(r={audio:!0,video:!0,screen:!0});const s={};return r.audio&&(s.aMsid=[(e==null?void 0:e.getAudioInfo().msid)||M.Audio]),r.video?r.vMsid?s.vMsid=[r.vMsid]:e!=null&&e.hasVideoLarge?s.vMsid=[(e==null?void 0:e.getVideoLargeInfo().msid)||M.VideoLarge]:e!=null&&e.hasVideoSmall?s.vMsid=[(e==null?void 0:e.getVideoSmallInfo().msid)||M.VideoSmall]:s.vMsid=[M.VideoLarge]:r.screen&&e!=null&&e.hasScreen&&(s.vMsid=[(e==null?void 0:e.getScreenInfo().msid)||M.Screen]),s}httpSubscribe(e){return v(this,null,function*(){const{remoteUser:t,options:r}=e;let s=t.streamUrl;r.video||r.screen?r!=null&&r.audio||(s+="@subaudio=no"):s+="@subvideo=no";const n=this.getSubConfig(t.streamInfo,r);n.retryTimes=0,this.encodedInsertableStreams&&(n.encodedInsertableStreams=!0);try{this.startConnect();const o=yield this.rts.subscribe(s,n);return this.setConnected(!0),{traceId:o.traceId,stream:o}}catch(o){throw this.setConnected(!1),o}})}subscribeAdd(e){return v(this,null,function*(){var n,o,c,u,h;yield this.dcConnectingPromise;const{remoteUser:t,options:r}=e,s=_t(W({url:t.streamUrl,subAudio:!!r.audio,subVideo:!!(r.screen||r.video)},this.getSubConfig(t.streamInfo,r)),{targetStream:r.screen?t.getScreenStream:t.getCameraStream});try{const l=yield this.rts.subscribeAdd([s]);return s.subVideo&&this.checkSubscribeStats(t.streamUrl,(n=s.vMsid)==null?void 0:n[0]).then(()=>{var d;A.info(Te.logName,"checkSubscribeStats",{streamUrl:t.streamUrl,msid:(d=s.vMsid)==null?void 0:d[0]})}),l[0]}catch(l){if(((h=(u=(c=(o=l==null?void 0:l.extraInfo)==null?void 0:o.parsedData)==null?void 0:c.streams)==null?void 0:u[0])==null?void 0:h.res_code)===508)return this.emit("subscribeexceeds"),null;throw E.fromError(l)}return null})}subscibeDelete(e){return v(this,null,function*(){var n,o,c,u;yield this.dcConnectingPromise;const{remoteUser:t,options:r}=e,s=_t(W({url:t.streamUrl,subAudio:!!r.audio,subVideo:!!(r.screen||r.video)},this.getSubConfig(t.streamInfo,r)),{targetStream:r.screen?t.getScreenStream:t.getCameraStream});try{return(yield this.rts.subscribeDeleteTracks([s]))[0]}catch(h){if(((u=(c=(o=(n=h==null?void 0:h.extraInfo)==null?void 0:n.parsedData)==null?void 0:o.streams)==null?void 0:c[0])==null?void 0:u.res_code)===404)return;throw h}})}subscibeStop(e){return v(this,null,function*(){var t,r,s,n;try{yield this.rts.subscribeStop([{url:e}])}catch(o){if(((n=(s=(r=(t=o==null?void 0:o.extraInfo)==null?void 0:t.parsedData)==null?void 0:r.streams)==null?void 0:s[0])==null?void 0:n.res_code)===404)return;throw o}})}publish(e,t=!1){return v(this,null,function*(){let r="";if(this.connecting&&(yield this.connectingPromise),this.connected){yield this.dcConnectingPromise;let s=!1,n;const{audio:o,video:c,videoSmall:u,screen:h}=this.localStreamManager.publishStreams;o&&(r=yield this.publishAdd(e,o,{aMsid:M.Audio},t),s=!0,n=M.Audio,yield et(100)),c&&(r=yield this.publishAdd(e,c,{vMsid:M.VideoLarge},t),s=!1,n=M.VideoLarge,yield et(100)),u&&(r=yield this.publishAdd(e,u,{vMsid:M.VideoSmall},t),s=!1,n=M.VideoSmall,yield et(100)),h&&(r=yield this.publishAdd(e,h,{isScreen:!0,vMsid:M.Screen},t),s=!1,n=M.Screen),n&&(yield this.waitPublishSender(e,s,n))}else r=yield this.httpPublish(e,t);return r})}subscribe(e){return v(this,null,function*(){const{options:t}=e;if(t.video&&t.screen)throw new E(T.ERR_INNER,"subscribe error, video and screen cannot be subscribed at the same time");this.connecting&&(yield this.connectingPromise);let r;return this.connected?(yield this.dcConnectingPromise,r=yield this.subscribeAdd(e)):r=yield this.httpSubscribe(e),r})}getSubscribeVideoStats(e,t){return v(this,null,function*(){return yield this.rts.getSubscribeVideoStats(e,t)})}getSubscribeAudioStats(e,t){return v(this,null,function*(){return yield this.rts.getSubscribeAudioStats(e,t)})}sendSEI(e,t,r,s){return v(this,null,function*(){return this.rts.sendSEI({url:e,vMsid:M.VideoLarge,data:t,repeatCount:r,payloadType:s})})}},p(Te,"logName","RtsManager"),Te);ve([y()],pe.prototype,"updatePublishingTracks",1),ve([y(I,I)],pe.prototype,"httpPublish",1),ve([y(I,I)],pe.prototype,"waitPublishSender",1),ve([y(([i,a,e])=>[i,JSON.stringify(e)],I)],pe.prototype,"publishAdd",1),ve([y(I,I)],pe.prototype,"publishDelete",1),ve([y(([i,a,e])=>[i,JSON.stringify(e)])],pe.prototype,"publishReplace",1),ve([y(I)],pe.prototype,"publishStop",1),ve([y()],pe.prototype,"unpublish",1),ve([y(Zt,({traceId:i})=>i)],pe.prototype,"httpSubscribe",1),ve([y(Zt,({traceId:i})=>i)],pe.prototype,"subscribeAdd",1),ve([y(Zt)],pe.prototype,"subscibeDelete",1),ve([y(I)],pe.prototype,"subscibeStop",1),ve([y(I)],pe.prototype,"publish",1),ve([y(Zt)],pe.prototype,"subscribe",1),ve([y()],pe.prototype,"sendSEI",1);let tn=pe;class qi{constructor(){p(this,"profile");p(this,"profileMap",new Map);p(this,"audioProfile");p(this,"contentHint")}updateProfile(a,e){e&&this.profileMap.set(a,e),this.profile=a}get videoProfile(){return this.profile}updateAudioProfile(a){this.audioProfile=a}setContentHint(a,e){e&&(this.contentHint=e),this.contentHint&&a&&(a.contentHint=this.contentHint)}setVideoProfile(a,e,t=!1){return v(this,null,function*(){if(!this.profile)return;const r=this.profileMap.get(this.profile)||(e==null?void 0:e.VideoProfileMap.get(this.profile));if(r){if(!t&&a&&a.applyConstraints)try{yield a.applyConstraints(r)}catch(s){}e&&(e==null||e.VideoProfileMap.set(this.profile,r),yield e.setVideoProfile(this.profile))}})}}class Gi extends X{constructor(e){super();p(this,"type");p(this,"originVideoTrack");p(this,"videoSource");p(this,"_videoMuted",!1);p(this,"originAudioTrack");p(this,"audioSource");p(this,"_audioMuted",!1);p(this,"_targetVideoTrack");p(this,"_targetDualVideoTrack");p(this,"_targetAudioTrack");p(this,"_publishVideoStream");p(this,"_publishDualVideoStream");p(this,"_publishAudioStream");p(this,"_previewStream");p(this,"plugins",[]);p(this,"_profileManager");p(this,"cameraVideoConstraints");p(this,"micAudioConstraints");p(this,"onVideoTrackEnded",()=>{this.emit("videotrackended")});p(this,"onAudioTrackEnded",()=>{this.emit("audiotrackended")});this.type=e}get profileManager(){return this._profileManager}get audioProfile(){var e;return(e=this.profileManager)==null?void 0:e.audioProfile}updateSource(e,t,r){return v(this,null,function*(){var o,c,u,h,l,d;const{videoTrack:s,audioTrack:n}=e;s&&((o=this.originVideoTrack)==null||o.removeEventListener("ended",this.onVideoTrackEnded)),n&&((c=this.originAudioTrack)==null||c.removeEventListener("ended",this.onAudioTrackEnded)),this.type===ae.AliRtcSdkStreamTypeScreen?this.stop():(s&&((u=this.originVideoTrack)==null||u.stop()),n&&((h=this.originAudioTrack)==null||h.stop())),s&&(this.originVideoTrack=s,(l=this.originVideoTrack)==null||l.addEventListener("ended",this.onVideoTrackEnded),this.videoSource=t||ft.Camera,this.updateVideoTrack(s)),n&&(this.originAudioTrack=n,(d=this.originAudioTrack)==null||d.addEventListener("ended",this.onAudioTrackEnded),this.audioSource=r||Wt.Microphone,this.updateAudioTrack(n))})}get currentProfile(){var e;return(e=this.profileManager)==null?void 0:e.profile}get currentVideoTrack(){return this._targetVideoTrack}get currentDualVideoTrack(){return this._targetDualVideoTrack}get publishVideoStream(){return this._publishVideoStream}get publishDualVideoStream(){return this._publishDualVideoStream}get currentAudioTrack(){return this._targetAudioTrack}get publishAudioStream(){return this._publishAudioStream}get previewStream(){return this._previewStream}updateVideoTrack(e,t=!1){return v(this,null,function*(){(this._targetVideoTrack!==e||t)&&(this._targetVideoTrack=e)})}updateDualVideoTrack(e,t=!1){return v(this,null,function*(){(this._targetDualVideoTrack!==e||t)&&(this._targetDualVideoTrack=e)})}updateAudioTrack(e,t=!1){return v(this,null,function*(){(this._targetAudioTrack!==e||t)&&(this._targetAudioTrack=e)})}setAudioMuted(e){var t,r;this._audioMuted=e,e?(t=this.publishAudioStream)==null||t.disableAudio():(r=this.publishAudioStream)==null||r.enableAudio()}get isAudioMuted(){return this._audioMuted}setVideoMuted(e){var t,r;this._videoMuted=e,e?(t=this.publishVideoStream)==null||t.disableVideo():(r=this.publishVideoStream)==null||r.enableVideo()}get isVideoMuted(){return this._videoMuted}process(e){return v(this,null,function*(){var t,r,s,n,o,c,u,h,l,d,f,m;this._targetAudioTrack=this.originAudioTrack,this._targetVideoTrack=this.originVideoTrack;for(const g of this.plugins)try{yield g.execute(this,e)}catch(S){console.error(`error in plugin-${g.name}, error: ${S}`)}this._targetVideoTrack?((r=(t=this._publishVideoStream)==null?void 0:t.videoTrack)==null?void 0:r.id)!==this._targetVideoTrack.id&&(this._publishVideoStream=yield Mt(this._targetVideoTrack),this.setVideoMuted(this._videoMuted),(s=this.profileManager)==null||s.setVideoProfile(this.originVideoTrack,this._publishVideoStream,!0),(n=this.profileManager)==null||n.setContentHint(this._targetVideoTrack),this.previewStream?(o=this.previewStream)==null||o.mergeStream(this._publishVideoStream):this._previewStream=yield Mt(this._targetVideoTrack)):(this._publishVideoStream=void 0,(c=this.previewStream)==null||c.deleteTracks({video:!0})),this._targetDualVideoTrack?((h=(u=this._publishDualVideoStream)==null?void 0:u.videoTrack)==null?void 0:h.id)!==this._targetDualVideoTrack.id&&(this._publishDualVideoStream=yield Mt(this._targetDualVideoTrack),this._videoMuted?this._publishDualVideoStream.disableVideo():this._publishDualVideoStream.enableVideo()):this._publishDualVideoStream=void 0,this._targetAudioTrack?((d=(l=this._publishAudioStream)==null?void 0:l.audioTrack)==null?void 0:d.id)!==this._targetAudioTrack.id&&(this._publishAudioStream=yield Mt(this._targetAudioTrack),this.setAudioMuted(this._audioMuted),this.previewStream?(f=this.previewStream)==null||f.mergeStream(this._publishAudioStream):this._previewStream=yield Mt(this._targetAudioTrack)):(this._publishAudioStream=void 0,(m=this.previewStream)==null||m.deleteTracks({audio:!0}))})}stopVideo(){var e,t;this.originVideoTrack&&((e=this.originVideoTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originVideoTrack)==null||t.stop(),this.originVideoTrack=void 0),this.updateVideoTrack(void 0)}stopAudio(){var e,t;this.originAudioTrack&&((e=this.originAudioTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originAudioTrack)==null||t.stop(),this.originAudioTrack=void 0),this.updateAudioTrack(void 0)}stop(){this.stopVideo(),this.stopAudio()}updateVideoProfile(e,t){return v(this,null,function*(){this._profileManager||(this._profileManager=new qi),e&&this._profileManager.updateProfile(e,t),yield this._profileManager.setVideoProfile(this.originVideoTrack,this._publishVideoStream,this.type===ae.AliRtcSdkStreamTypeScreen)})}get videoProfile(){var e;return(e=this.profileManager)==null?void 0:e.videoProfile}setVideoContentHint(e){this._profileManager||(this._profileManager=new qi),this._profileManager.setContentHint(this.currentVideoTrack,e)}updateAudioProfile(e){return v(this,null,function*(){this._profileManager||(this._profileManager=new qi),this._profileManager.updateAudioProfile(e)})}cloneVideoProfile(e){return v(this,null,function*(){var t;yield(t=this.profileManager)==null?void 0:t.setVideoProfile(void 0,e)})}addPlugin(e){const t=this.plugins.findIndex(r=>r.zIndex>e.zIndex);t>-1?this.plugins.splice(t,0,e):this.plugins.push(e)}removePlugin(e){const t=this.plugins.indexOf(e);return t>-1?(e.clear(this),this.plugins.splice(t,1),!0):!1}}var rn=Object.defineProperty,sn=Object.getOwnPropertyDescriptor,Oe=(i,a,e,t)=>{for(var r=t>1?void 0:t?sn(a,e):a,s=i.length-1,n;s>=0;s--)(n=i[s])&&(r=(t?n(a,e,r):n(r))||r);return t&&r&&rn(a,e,r),r};const Me=(vt=class extends X{constructor(e){super();p(this,"pluginManager");p(this,"publishingCameraVideoStream");p(this,"publishingScreenVideoStream");p(this,"cameraStreamInfo",new Gi(ae.AliRtcSdkStreamTypeCapture));p(this,"screenStreamInfo",new Gi(ae.AliRtcSdkStreamTypeScreen));p(this,"streamInfos",[this.cameraStreamInfo,this.screenStreamInfo]);p(this,"_audioCaptureDisabled",!1);p(this,"_cameraCaptureDisabled",!1);p(this,"_publishLocalAudioStreamEnabled",!0);p(this,"_publishLocalVideoStreamEnabled",!0);p(this,"_publishLocalScreenStreamEnabled",!0);this.screenStreamInfo.setVideoContentHint("motion"),this.pluginManager=e;const t=r=>v(this,null,function*(){if(A.info(`[${vt.logName}]`,"plugin added",r.name),!r.isSupported("6.11.6-beta.1")){console.warn(`${r.name} is not supported!!!`),r.emit("unsupported");return}try{yield r.init()}catch(s){r.emit("error",E.fromError(s,it.AliRtcPluginErrorInitError))}r.streamType===ae.AliRtcSdkStreamTypeCapture&&(this.cameraStreamInfo.addPlugin(r),yield this.cameraStreamInfo.process(this.streamInfos)),r.streamType===ae.AliRtcSdkStreamTypeScreen&&(this.screenStreamInfo.addPlugin(r),yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")});this.cameraStreamInfo.updateVideoProfile(Kr,kt),this.cameraStreamInfo.on("videotrackended",()=>v(this,null,function*(){yield this.stopLocalStream({video:!0}),this.emit("trackended",ht.VideoTrackEnded)})),this.cameraStreamInfo.on("audiotrackended",()=>v(this,null,function*(){yield this.stopLocalStream({audio:!0}),this.emit("trackended",ht.AudioTrackEnded)})),this.screenStreamInfo.updateVideoProfile(Jr,Ct),this.screenStreamInfo.on("videotrackended",()=>v(this,null,function*(){yield this.stopLocalStream({screen:!0}),this.emit("trackended",ht.ScreenTrackEnded)})),this.pluginManager.on("added",t),this.pluginManager.on("removed",r=>v(this,null,function*(){this.cameraStreamInfo.removePlugin(r)&&(yield this.cameraStreamInfo.process(this.streamInfos)),this.screenStreamInfo.removePlugin(r)&&(yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("updated",()=>v(this,null,function*(){yield this.updateStreams()}))}get hasCamera(){return!!this.cameraStreamInfo.originVideoTrack}get audioCaptureDisabled(){return this._audioCaptureDisabled}set audioCaptureDisabled(e){this._audioCaptureDisabled=e}get cameraCaptureDisabled(){return this._cameraCaptureDisabled}setAudioMuted(e){this.cameraStreamInfo.setAudioMuted(e)}get isAudioMuted(){return this.cameraStreamInfo.isAudioMuted}setCameraMuted(e){this.cameraStreamInfo.setVideoMuted(e)}get isCameraMuted(){return this.cameraStreamInfo.isVideoMuted}setScreenMuted(e){this.screenStreamInfo.setVideoMuted(e)}get isScreenMuted(){return this.screenStreamInfo.isVideoMuted}set cameraCaptureDisabled(e){this._cameraCaptureDisabled=e}get publishLocalAudioStreamEnabled(){return this._publishLocalAudioStreamEnabled}set publishLocalAudioStreamEnabled(e){this._publishLocalAudioStreamEnabled=e}get publishLocalVideoStreamEnabled(){return this._publishLocalVideoStreamEnabled}set publishLocalVideoStreamEnabled(e){this._publishLocalVideoStreamEnabled=e}get publishLocalScreenStreamEnabled(){return this._publishLocalScreenStreamEnabled}set publishLocalScreenStreamEnabled(e){this._publishLocalScreenStreamEnabled=e}updateStreams(){return v(this,null,function*(){yield this.cameraStreamInfo.process(this.streamInfos),yield this.screenStreamInfo.process(this.streamInfos),this.emit("publishupdate")})}setAvailableCameraDeviceId(){return v(this,null,function*(){var e,t,r,s;if((e=this.cameraStreamInfo.cameraVideoConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.cameraVideoConstraints)==null?void 0:t.deviceId;const o=yield D.AliRTS.getCameraList();o.find(c=>c.deviceId===n)||(n=(s=(r=o.find(c=>!!c.deviceId))==null?void 0:r.deviceId)!=null?s:""),this.cameraStreamInfo.cameraVideoConstraints.deviceId=n}})}setAvailableMicrophoneDeviceId(){return v(this,null,function*(){var e,t,r,s;if((e=this.cameraStreamInfo.micAudioConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.micAudioConstraints)==null?void 0:t.deviceId;const o=yield D.AliRTS.getMicList();o.find(c=>c.deviceId===n)||(n=(s=(r=o.find(c=>!!c.deviceId))==null?void 0:r.deviceId)!=null?s:""),this.cameraStreamInfo.micAudioConstraints.deviceId=n}})}createLocalStream(e){return v(this,null,function*(){const{screen:t,mediaStream:r,videoProfile:s,screenProfile:n}=e;let{video:o,audio:c}=e;const u=ja(e);let h;if(u){if(r||(o===!0&&this.cameraStreamInfo.cameraVideoConstraints?(yield this.setAvailableCameraDeviceId(),o=W({},this.cameraStreamInfo.cameraVideoConstraints)):typeof o=="object"&&(yield this.setAvailableCameraDeviceId(),o=W(W({},o),this.cameraStreamInfo.cameraVideoConstraints)),c===void 0&&this.audioCaptureDisabled?c=!1:c&&(c===!0&&this.cameraStreamInfo.micAudioConstraints?(yield this.setAvailableMicrophoneDeviceId(),c=W({},this.cameraStreamInfo.micAudioConstraints)):typeof c=="object"&&(yield this.setAvailableMicrophoneDeviceId(),c=W(W({},c),this.cameraStreamInfo.micAudioConstraints)),this._audioCaptureDisabled=!1)),h=yield D.AliRTS.createStream({audio:c,video:o,screen:t,custom:!!r,mediaStream:r,skipProfile:!0}),t)yield this.screenStreamInfo.updateSource(h,ft.Screen,Wt.Screen),yield this.setScreenProfile(n),this.setScreenContentHint(),this.publishingScreenVideoStream=void 0;else if(yield this.cameraStreamInfo.updateSource(h,ft.Camera,Wt.Microphone),h.hasVideo&&(yield this.setVideoProfile(s),this.setVideoContentHint(),this.publishingCameraVideoStream=void 0),h.hasAudio&&typeof c=="boolean"){const l=this.cameraStreamInfo.audioProfile;l&&(yield h.setAudioProfile(l))}}return D.AliRTS.SystenUtil.isIos&&D.AliRTS.SystenUtil.compareVersion("15.1")&&!D.AliRTS.SystenUtil.compareVersion("15.2")&&(yield et(1e3)),yield this.updateStreams(),h})}stopLocalStream(e){return v(this,null,function*(){const{screen:t,video:r,audio:s}=e!=null?e:{};let n=!1;r&&this.cameraStreamInfo.originVideoTrack&&(n=!0,this.cameraStreamInfo.stopVideo(),this.publishingCameraVideoStream=void 0),s&&this.cameraStreamInfo.originAudioTrack&&(n=!0,this.cameraStreamInfo.stopAudio()),t&&this.screenStreamInfo.originVideoTrack&&(n=!0,this.screenStreamInfo.stop(),this.publishingScreenVideoStream=void 0),n&&(yield this.updateStreams())})}get publishStreams(){const{publishLocalVideoStreamEnabled:e,publishLocalAudioStreamEnabled:t,publishLocalScreenStreamEnabled:r}=this;return{video:e?this.cameraStreamInfo.publishVideoStream:void 0,videoSmall:e?this.cameraStreamInfo.publishDualVideoStream:void 0,audio:t?this.cameraStreamInfo.publishAudioStream:void 0,screen:r?this.screenStreamInfo.publishVideoStream:void 0}}createHTTPPublishStream(){return v(this,null,function*(){var c,u,h,l;let e,t=!1,r,s,n;const o=yield this.publishStreams;try{if(!o.audio&&!o.video&&!o.videoSmall&&!o.screen)throw new E(T.ERR_SDK_PUBLISH_INVAILD,"no tracks founded");const d=new MediaStream;(c=o.audio)!=null&&c.audioTrack&&d.addTrack(o.audio.audioTrack),(u=o.video)!=null&&u.videoTrack?(d.addTrack(o.video.videoTrack),s=o.videoSmall,n=o.screen):(h=o.screen)!=null&&h.videoTrack&&(r=M.Screen,d.addTrack((l=o.screen)==null?void 0:l.videoTrack),t=!0),e=yield Xr(d),t?(this.screenStreamInfo.cloneVideoProfile(e),this.publishingScreenVideoStream=e):(this.cameraStreamInfo.cloneVideoProfile(e),this.publishingCameraVideoStream=e)}catch(d){}return{publishStream:e,videoSmallStream:s,screenStream:n,vMsid:r}})}stop(){this.cameraStreamInfo.stop(),this.screenStreamInfo.stop()}setVideoProfile(e,t){return v(this,null,function*(){yield this.cameraStreamInfo.updateVideoProfile(e,t),this.publishingCameraVideoStream&&this.cameraStreamInfo.cloneVideoProfile(this.publishingCameraVideoStream)})}setVideoContentHint(e){this.cameraStreamInfo.setVideoContentHint(e)}setAudioProfile(e){return v(this,null,function*(){var t;yield this.cameraStreamInfo.updateAudioProfile(e),yield(t=this.publishingCameraVideoStream)==null?void 0:t.setAudioProfile(e)})}setScreenProfile(e,t){return v(this,null,function*(){yield this.screenStreamInfo.updateVideoProfile(e,t),this.publishingScreenVideoStream&&this.screenStreamInfo.cloneVideoProfile(this.publishingScreenVideoStream)})}setScreenContentHint(e){this.screenStreamInfo.setVideoContentHint(e)}setCameraVideoConstraints(e){var t;this.cameraStreamInfo.cameraVideoConstraints=W(W({},(t=this.cameraStreamInfo.cameraVideoConstraints)!=null?t:{}),e)}setMicAudioConstraints(e){var t;this.cameraStreamInfo.micAudioConstraints=W(W({},(t=this.cameraStreamInfo.micAudioConstraints)!=null?t:{}),e)}},p(vt,"logName","LocalStreamManager"),vt);Oe([y(([i])=>{const{audio:a,video:e,screen:t,custom:r,skipProfile:s,videoProfile:n,screenProfile:o}=i;return[{audio:a,video:e,screen:t,custom:r,skipProfile:s,videoProfile:n,screenProfile:o}]})],Me.prototype,"createLocalStream",1),Oe([y(I)],Me.prototype,"stopLocalStream",1),Oe([y()],Me.prototype,"createHTTPPublishStream",1),Oe([y()],Me.prototype,"stop",1),Oe([y(I)],Me.prototype,"setVideoProfile",1),Oe([y(I)],Me.prototype,"setVideoContentHint",1),Oe([y(I)],Me.prototype,"setAudioProfile",1),Oe([y(I)],Me.prototype,"setScreenProfile",1),Oe([y(I)],Me.prototype,"setScreenContentHint",1),Oe([y(I)],Me.prototype,"setCameraVideoConstraints",1),Oe([y(I)],Me.prototype,"setMicAudioConstraints",1);let an=Me;var nn=Object.defineProperty,on=Object.getOwnPropertyDescriptor,Ve=(i,a,e,t)=>{for(var r=t>1?void 0:t?on(a,e):a,s=i.length-1,n;s>=0;s--)(n=i[s])&&(r=(t?n(a,e,r):n(r))||r);return t&&r&&nn(a,e,r),r};class Ee extends X{constructor(e){super();p(this,"self");p(this,"userMap",{});p(this,"usersViewMap",{});p(this,"rtsManager");p(this,"localStreamManager");p(this,"authInfo");p(this,"signalingManager");p(this,"pluginManager");p(this,"reporter");p(this,"webTrackingClient");p(this,"statsMonitorId");p(this,"autoSubAudio",!0);p(this,"autoSubVideo",!0);p(this,"autoSubScreen",!0);p(this,"wantSubAudio",!0);p(this,"wantSubVideo",!0);p(this,"wantSubScreen",!0);p(this,"defaultStreamType",oe.AliRtcVideoStreamTypeHigh);p(this,"audioMuted",!1);p(this,"playoutVolume",1);p(this,"audioVolumeIndicationInterval",0);p(this,"indicationTimer",0);const{signalingManager:t,reporter:r,webTrackingClient:s}=e;this.signalingManager=t,this.addSignalingManagerListener(),this.reporter=r,this.webTrackingClient=s,this.pluginManager=new Qa,this.localStreamManager=new an(this.pluginManager),this.rtsManager=new tn(this.localStreamManager),this.self=new zr({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,reporter:this.reporter,webTrackingClient:this.webTrackingClient,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval})}addSignalingManagerListener(){this.signalingManager.on("onNotifyPublish",e=>{A.event("[Signaling] Notify Publish ",e),e.forEach(t=>{this.onRemotePublishStateChange(t)})})}isAutoSubAudio(){return this.autoSubAudio}setAutoSubAudio(e){this.autoSubAudio=e}isAutoSubVideo(){return this.autoSubVideo}setAutoSubVideo(e){this.autoSubVideo=e}isAutoSubScreen(){return this.autoSubScreen}setAutoSubScreen(e){this.autoSubScreen=e}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e,this.remoteUsers.forEach(t=>{t.setWantSubAudio(e),t.updateSubscribe()})}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e,this.remoteUsers.forEach(t=>{t.setWantSubVideo(e),t.updateSubscribe()})}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e,this.remoteUsers.forEach(t=>{t.setWantSubScreen(e),t.updateSubscribe()})}setRemoteDefaultVideoStreamType(e){this.defaultStreamType=e,this.remoteUsers.forEach(t=>{t.setRemoteDefaultVideoStreamType(e)})}setRemoteUserVideoStreamType(e,t){var r;(r=this.getRemoteUser(e))==null||r.setRemoteDefaultVideoStreamType(t)}setAudioMuted(e){this.audioMuted=e,this.remoteUsers.forEach(t=>{t.setAudioMuted(e)})}setLocalViewConfig(e,t){var s;if(!e)return(s=this.publisher)==null?void 0:s.setViewConfig(null,t);const r=Ji(e);r.length!==0&&r.forEach(n=>{var o,c;(o=this.publisher)==null||o.resetElement(n),Object.values(this.usersViewMap).forEach(({cameraViews:u=[],screenViews:h=[]})=>{u.includes(n)&&u.splice(u.indexOf(n),1),h.includes(n)&&h.splice(h.indexOf(n),1)}),(c=this.publisher)==null||c.setViewConfig(r,t)})}setRemoteViewConfig(e,t,r){var n,o;if(!t)return(n=this.userMap[e])==null?void 0:n.setViewConfig(null,r);const s=Ji(t);s.length!==0&&(s.forEach(c=>{var u;(u=this.publisher)==null||u.resetElement(c),Object.values(this.usersViewMap).forEach(({cameraViews:h=[],screenViews:l=[]})=>{h.includes(c)&&h.splice(h.indexOf(c),1),l.includes(c)&&l.splice(l.indexOf(c),1)})}),(o=this.userMap[e])==null||o.setViewConfig(s,r))}get channel(){var e;return(e=this.authInfo)==null?void 0:e.channelId}get userId(){var e;return(e=this.authInfo)==null?void 0:e.userId}get remoteUsers(){return Object.values(this.userMap)}get publisher(){return this.self}get isSubscribing(){var e;return((e=this.remoteUsers)!=null?e:[]).some(t=>{var c;const{isAudioSubscribing:r,isVideoLargeSubscribing:s,isVideoSmallSubscribing:n,isScreenSubscribing:o}=(c=t.streamInfo)!=null?c:{};return r||s||n||o})}onRemotePublishStateChange(e){var d;const{userid:t,callid:r,subscribe:s,pubid:n="",tracks:o}=e,c=(d=s==null?void 0:s.pullstreamurl)!=null?d:"";let u=this.getRemoteUser(t);if(!u)return;const h=u.streamInfo.audioTrackInfo,l=u.streamInfo.videoTrackInfo;u.updateRemoteTracks(r,c,n,o),u.updateSubscribe(),(h!==u.streamInfo.audioTrackInfo||l!==u.streamInfo.videoTrackInfo)&&this.emit("remoteTrackAvailableChange",t,u.streamInfo.audioTrackInfo,u.streamInfo.videoTrackInfo)}init(e,t){var r;this.authInfo=e,this.self||(this.self=new zr({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,reporter:this.reporter,webTrackingClient:this.webTrackingClient,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval})),this.self.enableAudioVolumeIndication(this.audioVolumeIndicationInterval),(r=this.self)==null||r.initInfo(e,t.pushstreamurl),t.users.forEach(s=>{const n=s.userid;if(n){const o=this.addUser(n,s.displayname),{callid:c,subscribe:u,tracks:h}=s;o.updateRemoteTracks(c,(u==null?void 0:u.pullstreamurl)||"","",h),this.emit("remoteTrackAvailableChange",n,o.streamInfo.audioTrackInfo,o.streamInfo.videoTrackInfo)}}),this.startStatsMonitor()}clear(){return v(this,null,function*(){var e;this.stopStatsMonitor();for(let t in this.userMap)this.userMap[t]&&(yield this.userMap[t].clear(),delete this.userMap[t]);yield(e=this.self)==null?void 0:e.clear(),this.authInfo=void 0})}startStatsMonitor(){this.statsMonitorId=window.setInterval(()=>v(this,null,function*(){if(this.publisher){const{audio:r,video:s}=yield this.publisher.getStats();r&&r.length>0&&this.emit("rtcLocalAudioStats",r),s&&s.length>0&&this.emit("rtcLocalVideoStats",s)}const e=[],t=[];for(const r of this.remoteUsers){const{audio:s,video:n}=yield r.getStats();s&&s.forEach(o=>{e.push(o)}),n&&n.forEach(o=>{t.push(o)})}e.length>0&&this.emit("rtcRemoteAudioStats",e),t.length>0&&this.emit("rtcRemoteVideoStats",t)}),2e3)}stopStatsMonitor(){this.statsMonitorId&&clearInterval(this.statsMonitorId)}getUser(e,t){return this.addUser(e,t),this.userMap[e]}addUser(e,t){return this.userMap[e]||(this.userMap[e]=this.executeAddUser(e,t)),this.userMap[e]}executeAddUser(e,t){var s;const r=new re({userId:e,displayName:t,rtsManager:this.rtsManager,signalingManager:this.signalingManager,usersViewMap:this.usersViewMap,reporter:this.reporter,webTrackingClient:this.webTrackingClient,localUserId:(s=this.userId)!=null?s:"",audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,playoutVolume:this.playoutVolume});return r.on(be.Remote,this.onRemoteDeviceStatusChange.bind(this)),r.on(J.PullStreamStats,this.onRemoteStatReport.bind(this)),r.on(J.RtsSubscribeExceeds,this.onSubscribeExceeds.bind(this)),r.on("audioSubscribeStateChanged",(n,o,c,u)=>{this.emit("audioSubscribeStateChanged",n,o,c,u,this.channel||"")}),r.on("videoSubscribeStateChanged",(n,o,c,u)=>{this.emit("videoSubscribeStateChanged",n,o,c,u,this.channel||"")}),r.on("screenSubscribeStateChanged",(n,o,c,u)=>{this.emit("screenSubscribeStateChanged",n,o,c,u,this.channel||"")}),r.on("remoteAudioAutoPlayFail",n=>{this.emit("remoteAudioAutoPlayFail",n)}),r.on("remoteVideoAutoPlayFail",(n,o)=>{this.emit("remoteVideoAutoPlayFail",n,o)}),r.on("remoteSubscribeError",n=>{this.emit("remoteSubscribeError",n)}),r.setWantSubAudio(this.autoSubAudio&&this.wantSubAudio),r.setWantSubVideo(this.autoSubVideo&&this.wantSubVideo),r.setWantSubScreen(this.autoSubScreen&&this.wantSubScreen),r.setRemoteDefaultVideoStreamType(this.defaultStreamType),r.setAudioMuted(this.audioMuted),(this.autoSubAudio||this.autoSubVideo||this.autoSubScreen)&&r.updateSubscribe(),r}onRemoteDeviceStatusChange(e,t){e===J.MuteAudio?this.emit("userAudioMuted",t,!0):e===J.UnmuteAudio?this.emit("userAudioMuted",t,!1):e===J.MuteVideo?this.emit("userVideoMuted",t,!0):e===J.UnmuteVideo?this.emit("userVideoMuted",t,!1):e===J.MuteScreen?this.emit("userScreenMuted",t,!0):e===J.UnmuteScreen&&this.emit("userScreenMuted",t,!1)}onRemoteStatReport(e,t,r){this.emit(J.PullStreamStats,e,t,r)}onSubscribeExceeds(e,t){this.emit(J.RtsSubscribeExceeds,e,t)}removeLeftUser(e){return v(this,null,function*(){e.userid&&this.userMap[e.userid]&&(yield this.userMap[e.userid].clear(!1),delete this.userMap[e.userid])})}updateUsers(e){const t=[],r=[],s={};e.forEach(c=>{c.userid&&(this.userMap[c.userid]?(r.push(c),s[c.userid]=this.userMap[c.userid]):(t.push(c),s[c.userid]=this.executeAddUser(c.userid,c.displayname)))});const n=Object.keys(this.userMap),o=[];return n.forEach(c=>{s[c]||o.push({userid:c,reason:"",leavecode:Fi.AliRtcUserOfflineQuit})}),this.userMap=s,{joinList:t,leaveList:o,presentList:r}}getRemoteUser(e){return this.userMap[e]}updateRemoteUserDeviceStatus(e){e&&e.userid&&this.userMap[e.userid]&&this.userMap[e.userid].updateRemoteUserDeviceStatus(e.status)}updateAudioWant(e,t){const r=this.userMap[e];if(!r)throw new E(T.ERR_INNER,`no remote user(${e}) founded`);r.setWantSubAudio(t),t?r.updateSubscribe():r.stopSubscribe({audio:!0})}updateVideoWant(e,t){const r=this.userMap[e];if(!r)throw new E(T.ERR_INNER,`no remote user(${e}) founded`);r.setWantSubVideo(t),t?r.updateSubscribe():r.stopSubscribe({video:!0})}updateScreenWant(e,t){const r=this.userMap[e];if(!r)throw new E(T.ERR_INNER,`no remote user(${e}) founded`);r.setWantSubScreen(t),t?r.updateSubscribe():r.stopSubscribe({screen:!0})}stopIndication(){this.indicationTimer&&window.clearInterval(this.indicationTimer)}startIndication(e){this.stopIndication(),this.indicationTimer=window.setInterval(()=>{var r;const t=this.remoteUsers.map(s=>({userId:s.userId,volume:s.getAudioLevel()||0}));t.unshift({userId:"",volume:((r=this.self)==null?void 0:r.getAudioLevel())||0}),this.emit("audioVolume",t)},e)}enableAudioVolumeIndication(e){var t;this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.stopIndication(),e>0&&this.startIndication(e),this.audioVolumeIndicationInterval=e,this.remoteUsers.forEach(r=>{r.enableAudioVolumeIndication(e)}),(t=this.self)==null||t.enableAudioVolumeIndication(e))}setPlayoutVolume(e){this.playoutVolume=e,this.remoteUsers.forEach(t=>{t.setPlayoutVolume(e)})}refreshAuthInfo(e){var t;this.authInfo&&(this.authInfo=W(W({},this.authInfo),e)),e.userId&&((t=this.self)==null||t.refreshUserInfo(e.userId))}setEnableMediaExtensionMsg(e){this.rtsManager.setEncodedInsertableStreams(e)}setAudioRedEnabled(e){this.rtsManager.setAudioRedEnabled(e)}}p(Ee,"logName","UserManager"),Ve([y()],Ee.prototype,"init",1),Ve([y()],Ee.prototype,"clear",1),Ve([y(I)],Ee.prototype,"addUser",1),Ve([y()],Ee.prototype,"removeLeftUser",1),Ve([y()],Ee.prototype,"updateUsers",1),Ve([y(I)],Ee.prototype,"updateAudioWant",1),Ve([y(I)],Ee.prototype,"updateVideoWant",1),Ve([y(I)],Ee.prototype,"updateScreenWant",1),Ve([y()],Ee.prototype,"stopIndication",1),Ve([y()],Ee.prototype,"startIndication",1),Ve([y()],Ee.prototype,"enableAudioVolumeIndication",1);const zi=i=>v(this,null,function*(){const a=new Uint8Array(160).fill(170),e=new TextEncoder().encode(i),t=yield window.crypto.subtle.importKey("raw",a,{name:"HMAC",hash:{name:"SHA-1"}},!1,["sign"]),r=yield window.crypto.subtle.sign("HMAC",t,e);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")});class cn{constructor(){p(this,"authInfo")}doRequest(a,e){var u;const t=this.authInfo;if(!t)return Promise.reject(Fe.LiveTranscodingErrorInvalidParam);const r="https://gw.rtn.aliyuncs.com",s=Pa[a],n={appid:t.appId,userid:t.userId,channelid:t.channelId,timestamp:t.timestamp,token:t.token,nonce:t.nonce?t.nonce:"",requestid:Ye.createCallid(),tokensid:!1,session:(u=t.callid)!=null?u:Ye.createCallid()},o=Object.keys(n).map(h=>`${h}=${encodeURIComponent(n[h])}`).join("&"),c=`${r}${s}?${o}`;return fetch(c,{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:e}).then(h=>h.status!==200?Promise.reject(new E(T.ERR_INNER,`transcoding request failed, status: ${h.status}`)):h)}setAuthInfo(a){this.authInfo=a}clear(){this.authInfo=void 0}startPublishLiveStream(a,e){return v(this,null,function*(){if(!this.authInfo)return Promise.reject(Fe.LiveTranscodingErrorInvalidParam);const t=yield zi(a.split("?")[0]),r=we.MPU_TASK_TRANSACTION_UPDATE,s=e.toJson(r,this.authInfo,t,a);return this.doRequest(r,JSON.stringify(s))})}startPublishLiveStreamWithTaskId(a,e){return v(this,null,function*(){if(!this.authInfo)return Promise.reject(Fe.LiveTranscodingErrorInvalidParam);const t=we.MPU_TASK_TRANSACTION_UPDATE,r=e.toJson(t,this.authInfo,a);return this.doRequest(t,JSON.stringify(r))})}updatePublishLiveStream(a,e){return v(this,null,function*(){if(!this.authInfo)return Promise.reject(Fe.LiveTranscodingErrorInvalidParam);const t=yield zi(a.split("?")[0]),r=we.MPU_TASK_TRANSACTION_UPDATE,s=e.toJson(r,this.authInfo,t,a);return this.doRequest(r,JSON.stringify(s))})}updatePublishLiveStreamWithTaskId(a,e){return v(this,null,function*(){if(!this.authInfo)return Promise.reject(Fe.LiveTranscodingErrorInvalidParam);const t=we.MPU_TASK_TRANSACTION_UPDATE,r=e.toJson(t,this.authInfo,a);return this.doRequest(t,JSON.stringify(r))})}stopPublishLiveStream(a){return v(this,null,function*(){if(!this.authInfo)return Promise.reject(Fe.LiveTranscodingErrorInvalidParam);const e=yield zi(a.split("?")[0]),t=we.MPU_TASK_TRANSACTION_STOP,r=new zt().toJson(t,this.authInfo,e,a);return this.doRequest(t,JSON.stringify(r))})}stopPublishLiveStreamWithTaskId(a){if(!this.authInfo)return Promise.reject(Fe.LiveTranscodingErrorInvalidParam);const e=we.MPU_TASK_TRANSACTION_STOP,t=new zt().toJson(e,this.authInfo,a);return this.doRequest(e,JSON.stringify(t))}refreshAuthInfo(a){this.authInfo&&this.setAuthInfo(W(W({},this.authInfo),a))}}var Qr=(i,a,e)=>{if(!a.has(i))throw TypeError("Cannot "+e)},ei=(i,a,e)=>(Qr(i,a,"read from private field"),e?e.call(i):a.get(i)),Xi=(i,a,e)=>{if(a.has(i))throw TypeError("Cannot add the same private member more than once");a instanceof WeakSet?a.add(i):a.set(i,e)},Yi=(i,a,e,t)=>(Qr(i,a,"write to private field"),t?t.call(i,e):a.set(i,e),e),un=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},N={},lt={};const hn="SLS_CLIENT";var Zr=(i=>(i.ERROR="error",i.LOG="log",i.LOCATION="pv",i.API="api",i.RESOURCE="res",i.RESOURCE_ERROR="res_err",i.PERF="perf",i.CONSOLE_LOG="console",i))(Zr||{}),es=(i=>(i.LOG_SEND="LOG_SEND",i.BROWSER_SEND="BROWSER_SEND",i.BASE_TRANSFORM="BASE_TRANSFORM",i.BROWSER_BASE_TRANSFORM="BROWSER_BASE_TRANSFORM",i.BROWSER_FETCH="BROWSER_FETCH",i.BROWSER_XHR="BROWSER_XHR",i.BROWSER_LOCATION="BROWSER_LOCATION",i.BROWSER_RUNTIME_ERROR="BROWSER_RUNTIME_ERROR",i.BROWSER_CUSTOM_ERROR="BROWSER_CUSTOM_ERROR",i.BROWSER_RESOURCE_ERROR="BROWSER_RESOURCE_ERROR",i.BROWSER_CONSOLE="BROWSER_CONSOLE",i.BROWSER_PERF="BROWSER_PERF",i.BROWSER_RESOURSE="BROWSER_RESOURSE",i.MINI_SEND="MINI_SEND",i.MINI_REQUEST="MINI_REQUEST",i.MINI_BASE_TRANSFORM="MINI_BASE_TRANSFORM",i.MINI_ROUTE="MINI_ROUTE",i))(es||{});const ln={BROWSER_SEND:-1,MINI_SEND:-2,BASE_TRANSFORM:100,BROWSER_BASE_TRANSFORM:100*2,MINI_BASE_TRANSFORM:100*2+1,BROWSER_PERF:100*3+1,BROWSER_FETCH:100*4,BROWSER_XHR:100*4+1,MINI_REQUEST:100*4+2,BROWSER_RUNTIME_ERROR:100*5},dn="sls-trace-uid";var ts=(i=>(i.OK="OK",i.ERROR="ERROR",i.UNSET="UNSET",i))(ts||{});lt.InternalPlugin=es,lt.InternalPluginPriority=ln,lt.OTStatusCode=ts,lt.SLS_CLIENT_NAME=hn,lt.SLS_TRACE_UID_KEY=dn,lt.WebEventType=Zr;var De=lt;function Qi(i,a,e){Object.defineProperty(i,a,{writable:!0,enumerable:!0,configurable:!0,value:e})}function pn(i,a,e,t){t?t(()=>{Qi(i,a,e)}):Qi(i,a,e)}class gn{constructor(a){this.onFirstSubscribe=a,this.observers=[]}subscribe(a){return!this.observers.length&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe()||void 0),this.observers.push(a),{unsubscribe:()=>{this.observers=this.observers.filter(e=>a!==e),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(a){this.observers.forEach(e=>e(a))}}function Lt(i,a,e){try{return i.apply(a,e)}catch(t){return}}function fn(i){return function(){return Lt(i,this,arguments)}}let mn=!1;function Sn(){return mn}function is(...i){}var bn=Object.defineProperty,vn=Object.defineProperties,yn=Object.getOwnPropertyDescriptors,rs=Object.getOwnPropertySymbols,wn=Object.prototype.hasOwnProperty,_n=Object.prototype.propertyIsEnumerable,ss=(i,a,e)=>a in i?bn(i,a,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[a]=e,Rn=(i,a)=>{for(var e in a||(a={}))wn.call(a,e)&&ss(i,e,a[e]);if(rs)for(var e of rs(a))_n.call(a,e)&&ss(i,e,a[e]);return i},In=(i,a)=>vn(i,yn(a));const as=1e3,ns=60*as,os=60*ns,cs=24*os,us=365*cs,En=1024,hs="0.1.0";function An(){}function ls(i){return typeof i=="number"}function Tn(i){return Object.prototype.toString.call(i)==="[object String]"}function Pn(i){return Object.prototype.toString.call(i)==="[object Error]"}function ds(i,a){return+i.toFixed(a)}function kn(i,a){return i.indexOf(a)!==-1}function Cn(i,a){return i==null?a:!!i}function ti(i){return i?(parseInt(i,10)^Math.random()*16>>parseInt(i,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,ti)}function ps(i=20){var a,e;const t=new Array(i),r=Date.now().toString(36).split("");for(;i-- >0;)e=(a=36*Math.random()|0).toString(36),t[i]=a%3?e:e.toUpperCase();for(var s=0;s<8;s++)t.splice(3*s+2,0,r[s]);return t.join("")}function Mn(i){return i!==0&&Math.random()<=i}function ii(i,a){return(...e)=>{try{return i(...e)}catch(t){console.error(a,t)}}}function gs(i){return"https://"+i.project+"."+i.host+"/logstores/"+i.logstore+"/track"}function Nn(i,a){return a?i.includes(gs(a)):i.includes("/track?APIVersion=0.6.0")}const fs=/^(?:([^:\/?#]+):\/\/)?((?:([^\/?#@]*)@)?([^\/?#:]*)(?:\:(\d*))?)?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n)*))?/i;function Ln(i){try{return decodeURIComponent(i)}catch(a){return unescape(i)}}function On(i){return typeof i=="string"&&fs.test(i)}function Vn(i){var a=Ln(i||"").match(fs);if(a==null)return null;var e=(a[3]||"").split(":"),t=e.length?(a[2]||"").replace(/(.*\@)/,""):a[2];return{uri:a[0],protocol:a[1],host:t,hostname:a[4],port:a[5],auth:a[3],user:e[0],password:e[1],path:a[6],search:a[7],hash:a[8]}}function Dn(i,a,e,t){const r={url:i,method:a,status_code:e};return t==null?r:In(Rn({},r),{host:t.host,scheme:t.protocol})}function xn(i,a,...e){return a==null||!Array.isArray(a)?!1:a.some(t=>{if(typeof t=="function")try{return t(i,...e)}catch(r){return console.error("user function callback threw an error:",r),!1}return typeof t=="string"?i.includes(t):Object.prototype.toString.call(t)==="[object RegExp]"?t.test(i):!1})}function Un(i,a,e){return i===!1?!1:i===!0||i==="error"&&!e?!0:typeof i=="function"?ii(i,"call shouldTrackBody failed")(a):!1}function Bn(i){return{relative:i,timeStamp:ms(i)}}function ms(i){const a=Date.now()-performance.now();return a>Ot()?Math.round(a+i):bs(i)}function Hn(){return Math.round(Date.now()-(Ot()+performance.now()))}function Fn(i){return ls(i)?ds(i*1e6,0):i}function Zi(){return Date.now()}function Ss(){return performance.now()}function jn(){return{relative:Ss(),timeStamp:Zi()}}function $n(){return{relative:0,timeStamp:Ot()}}function Wn(i,a){return a-i}function Kn(i){return i-Ot()}function bs(i){return Math.round(Ot()+i)}function Jn(i){return i<us}let ri;function Ot(){return ri===void 0&&(ri=performance.timing.navigationStart),ri}function qn(){ri=void 0}const dt="?";function Vt(i,a){let e;const t=a===void 0?0:+a;try{if(e=zn(i),e)return e}catch(r){}try{if(e=Gn(i),e)return e}catch(r){}try{if(e=Xn(i),e)return e}catch(r){}try{if(e=vs(i,t+1),e)return e}catch(r){}return{message:ge(i,"message"),name:ge(i,"name"),stack:[]}}function Gn(i){const a=ge(i,"stack");if(!a)return;const e=/^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,t=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,r=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;let s;const n=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,o=/\((\S*)(?::(\d+))(?::(\d+))\)/,c=a.split(`
|
|
5
|
+
`),u=[];let h,l,d;for(let f=0,m=c.length;f<m;f+=1){if(e.exec(c[f])){l=e.exec(c[f]);const g=l[2]&&l[2].indexOf("native")===0;s=l[2]&&l[2].indexOf("eval")===0,h=o.exec(l[2]),s&&h&&(l[2]=h[1],l[3]=h[2],l[4]=h[3]),d={args:g?[l[2]]:[],column:l[4]?+l[4]:void 0,func:l[1]||dt,line:l[3]?+l[3]:void 0,url:g?void 0:l[2]}}else if(r.exec(c[f]))l=r.exec(c[f]),d={args:[],column:l[4]?+l[4]:void 0,func:l[1]||dt,line:+l[3],url:l[2]};else if(t.exec(c[f]))l=t.exec(c[f]),s=l[3]&&l[3].indexOf(" > eval")>-1,h=n.exec(l[3]),s&&h?(l[3]=h[1],l[4]=h[2],l[5]=void 0):f===0&&!l[5]&&!Zn(i.columnNumber)&&(u[0].column=i.columnNumber+1),d={args:l[2]?l[2].split(","):[],column:l[5]?+l[5]:void 0,func:l[1]||dt,line:l[4]?+l[4]:void 0,url:l[3]};else continue;!d.func&&d.line&&(d.func=dt),u.push(d)}if(u.length)return{stack:u,message:ge(i,"message"),name:ge(i,"name")}}function zn(i){const a=ge(i,"stacktrace");if(!a)return;const e=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,t=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\((.*)\))? in (.*):\s*$/i,r=a.split(`
|
|
6
|
+
`),s=[];let n;for(let o=0;o<r.length;o+=2){let c;e.exec(r[o])?(n=e.exec(r[o]),c={args:[],column:void 0,func:n[3],line:+n[1],url:n[2]}):t.exec(r[o])&&(n=t.exec(r[o]),c={args:n[5]?n[5].split(","):[],column:+n[2],func:n[3]||n[4],line:+n[1],url:n[6]}),c&&(!c.func&&c.line&&(c.func=dt),c.context=[r[o+1]],s.push(c))}if(s.length)return{stack:s,message:ge(i,"message"),name:ge(i,"name")}}function Xn(i){const a=ge(i,"message");if(!a)return;const e=a.split(`
|
|
7
|
+
`);if(e.length<4)return;const t=/^\s*Line (\d+) of linked script ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i,r=/^\s*Line (\d+) of inline#(\d+) script in ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i,s=/^\s*Line (\d+) of function script\s*$/i,n=[],o=window&&window.document&&window.document.getElementsByTagName("script"),c=[];let u;for(const h in o)Qn(o,h)&&!o[h].src&&c.push(o[h]);for(let h=2;h<e.length;h+=2){let l;t.exec(e[h])?(u=t.exec(e[h]),l={args:[],column:void 0,func:u[3],line:+u[1],url:u[2]}):r.exec(e[h])?(u=r.exec(e[h]),l={args:[],column:void 0,func:u[4],line:+u[1],url:u[3]}):s.exec(e[h])&&(u=s.exec(e[h]),l={url:window.location.href.replace(/#.*$/,""),args:[],column:void 0,func:"",line:+u[1]}),l&&(l.func||(l.func=dt),l.context=[e[h+1]],n.push(l))}if(n.length)return{stack:n,message:e[0],name:ge(i,"name")}}function Yn(i,a,e){const t={url:a,line:e?+e:void 0};if(t.url&&t.line){i.incomplete=!1;const r=i.stack;if(r.length>0&&r[0].url===t.url){if(r[0].line===t.line)return!1;if(!r[0].line&&r[0].func===t.func)return r[0].line=t.line,r[0].context=t.context,!1}return r.unshift(t),i.partial=!0,!0}return i.incomplete=!0,!1}function vs(i,a){const e=/function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i,t=[],r={};let s=!1,n,o;for(let u=vs.caller;u&&!s;u=u.caller)u!==Vt&&(o={args:[],column:void 0,func:dt,line:void 0,url:void 0},n=e.exec(u.toString()),u.name?o.func=u.name:n&&(o.func=n[1]),typeof o.func>"u"&&(o.func=n?n.input.substring(0,n.input.indexOf("{")):void 0),r[u.toString()]?s=!0:r[u.toString()]=!0,t.push(o));a&&t.splice(0,a);const c={stack:t,message:ge(i,"message"),name:ge(i,"name")};return Yn(c,ge(i,"sourceURL")||ge(i,"fileName"),ge(i,"line")||ge(i,"lineNumber")),c}function ge(i,a){if(typeof i!="object"||!i||!(a in i))return;const e=i[a];return typeof e=="string"?e:void 0}function Qn(i,a){return Object.prototype.hasOwnProperty.call(i,a)}function Zn(i){return typeof i>"u"}function ys(i,a,e){const t=i[a];let r=e(t);const s=function(){return r.apply(this,arguments)};return i[a]=s,{stop:()=>{i[a]===s?i[a]=t:r=t}}}function er(i,a,{before:e,after:t}){return ys(i,a,r=>function(){const s=arguments;let n;return e&&Lt(e,this,s),typeof r=="function"&&(n=r.apply(this,s)),t&&Lt(t,this,s),n})}const eo=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/;function to(i){const{stop:a}=io(i),{stop:e}=ro(i);return{stop:()=>{a(),e()}}}function io(i){return er(window,"onerror",{before(a,e,t,r,s){let n;if(s)n=Vt(s),i(n,s);else{const o={url:e,column:r,line:t};let c,u=a;if({}.toString.call(a)==="[object String]"){const h=eo.exec(u);h&&(c=h[1],u=h[2])}n={name:c,message:typeof u=="string"?u:void 0,stack:[o]},i(n,a)}}})}function ro(i){return er(window,"onunhandledrejection",{before(a){const e=a.reason||"Empty reason",t=Vt(e);i(t,e)}})}function ws(i){return`${i.name||"Error"}: ${i.message}`}function _s(i){return i.filter(a=>a.url==null||!a.url.includes("sls-rum.js"))}function tr(i){let a=ws(i);return i.stack.forEach(e=>{const t=e.func==="?"?"<anonymous>":e.func,r=e.args&&e.args.length>0?`(${e.args.join(", ")})`:"",s=e.line?`:${e.line}`:"",n=e.line&&e.column?`:${e.column}`:"";a+=`
|
|
8
|
+
at ${t}${r} @ ${e.url}${s}${n}`}),encodeURIComponent(a)}function so(i,a,e,t=!0){var r;if(!i||i.message===void 0&&!(a instanceof Error))return{message:`${e} ${JSON.stringify(a)}`,stacktrace:"",type:i&&i.name,id:ti()};i!=null&&i.stack&&t&&(i.stack=_s(i.stack));const s=(r=i==null?void 0:i.stack)==null?void 0:r[0];return{message:encodeURIComponent(i.message||"Empty message"),stacktrace:tr(i),type:i.name,col:s?s.column:void 0,line:s?s.line:void 0,file:encodeURIComponent(s&&s.url?s.url:""),id:ti()}}function ao(){const i=new Error;let a;return Lt(()=>{const e=Vt(i);e!=null&&e.stack&&(e.stack=_s(e.stack)),a=tr(e)}),a}const no=8,oo=16,ir="b3",rr="traceparent",sr="uber-trace-id",si=Array(32);function Rs(i){for(let a=0;a<i*2;a++)si[a]=Math.floor(Math.random()*16)+48,si[a]>=58&&(si[a]+=39);return String.fromCharCode.apply(null,si.slice(0,i*2))}function Is(){return Rs(oo)}function ar(){return Rs(no)}function ai(i,a){return`${i}-${a}-1`}function ni(i,a){return`00-${i}-${a}-01`}function oi(i,a){return`${i}:${a}:0:1`}const ci={b3:{name:ir,getter:ai},traceparent:{name:rr,getter:ni},uber:{name:sr,getter:oi}};function co(i,a,e,t){var r;const s=t!=null?t:{};s.headers=(r=s.headers)!=null?r:{},s.headers[ir]=ai(i,a),s.headers[rr]=ni(i,a),s.headers[sr]=oi(i,a);try{if(e)for(const[n,o]of Object.entries(e))ci[o]&&(s.headers[n]=ci[o].getter(i,a))}catch(n){}return s}function uo(i,a,e,t){i.setRequestHeader(ir,ai(a,e)),i.setRequestHeader(rr,ni(a,e)),i.setRequestHeader(sr,oi(a,e));try{if(t)for(const[r,s]of Object.entries(t))ci[s]&&i.setRequestHeader(r,ci[s].getter(a,e))}catch(r){}}function Dt(i,a,e){i!=null&&Object.keys(i).map(t=>{e==null||e==""?a[t]=i[t]:a[`${e}.${t}`]=i[t]})}var ho=Object.defineProperty,lo=Object.defineProperties,po=Object.getOwnPropertyDescriptors,Es=Object.getOwnPropertySymbols,go=Object.prototype.hasOwnProperty,fo=Object.prototype.propertyIsEnumerable,As=(i,a,e)=>a in i?ho(i,a,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[a]=e,mo=(i,a)=>{for(var e in a||(a={}))go.call(a,e)&&As(i,e,a[e]);if(Es)for(var e of Es(a))fo.call(a,e)&&As(i,e,a[e]);return i},So=(i,a)=>lo(i,po(a));function bo(){return{name:De.InternalPlugin.BASE_TRANSFORM,run:function(){this.subscribe("*",(i,a)=>{const{otBase:e,extra:t}=i;e.attribute=So(mo({},e.attribute),{sid:this.session.getSessionId(),pid:this.session.getPageId(),uid:this.options.uid,service:this.options.service}),this.options.nickname&&(e.attribute.nickname=this.options.nickname),Dt(this.options.custom,e.attribute,"custom"),Dt({env:this.options.env,version:this.options.version},e.attribute),Dt({sdk_version:hs,workspace:this.options.workspace},e.resource);const r={otBase:e,extra:t};is(De.InternalPlugin.BASE_TRANSFORM,r),a(r)},De.InternalPluginPriority[De.InternalPlugin.BASE_TRANSFORM])}}}function vo(){return{name:De.InternalPlugin.LOG_SEND,run:function(){}}}function Ts(i,a,e){if(a<0)return;const t=s=>{Ts(i,a-1,s)},r=i[a];ii(()=>{r.callback.call(void 0,e,t)},"plugin notify run error")()}class yo{constructor(a){this.subscribeMap={},this.allNotifiers=[],this.allNotifiers=a}subscribeOne(a,e,t,r){var s;const n=(s=this.subscribeMap[e])!=null?s:[];this.subscribeMap[e]=n,n.push({name:a,priority:r,callback:t}),n.sort((o,c)=>o.priority-c.priority)}notify(a,e){var t;const r=(t=this.subscribeMap[a])!=null?t:[];Ts(r,r.length-1,e)}subscribe(a,e,t,r){if(e==="*")for(let s=0;s<this.allNotifiers.length;s++){const n=this.allNotifiers[s];this.subscribeOne(a,n,t,r)}else this.subscribeOne(a,e,t,r)}getSubscribeMap(){return this.subscribeMap}}function wo(){const i=Is();let a=ar();return{getSessionId:()=>i,getPageId:()=>a,refreshPageId:()=>{a=ar()}}}var _o=Object.defineProperty,Ro=Object.defineProperties,Io=Object.getOwnPropertyDescriptors,Ps=Object.getOwnPropertySymbols,Eo=Object.prototype.hasOwnProperty,Ao=Object.prototype.propertyIsEnumerable,ks=(i,a,e)=>a in i?_o(i,a,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[a]=e,To=(i,a)=>{for(var e in a||(a={}))Eo.call(a,e)&&ks(i,e,a[e]);if(Ps)for(var e of Ps(a))Ao.call(a,e)&&ks(i,e,a[e]);return i},Po=(i,a)=>Ro(i,Io(a));const ko=["uid","nickname","env","service","version","custom"];class Co{constructor(a){this.isInit=!1,this.pendingPlugins=[],this.pluginMap={},this.session=wo();var e,t;this.options=a,this.use(vo()),this.use(bo()),this.options.env=(e=a.env)!=null?e:"prod",this.options.version=(t=a.version)!=null?t:"-"}initPlugin(a){if(a==null||typeof a!="object"){console.error("plugin is not a object");return}if(a.name==null||a.name===""){console.error("plugin name is required.");return}if(this.pluginMap[a.name]){console.error(`plugin name: ${a.name} is conflict`);return}if(typeof a.run!="function"){console.error("plugin.run is not a function");return}const e=Po(To({},this.context),{subscribe:(t,r,s)=>{this.sub.subscribe(a.name,t,r,s)},notify:t=>{this.sub.notify(a.name,t)}});ii(()=>a.run.call(e),`plugin ${a.name} init failed`)()}addLog(a){if(this.isInit){const e={t:De.WebEventType.LOG};Dt(a,e,De.WebEventType.LOG);const t={start:Zi()*1e3,attribute:e,resource:{}};this.sub.notify(De.InternalPlugin.LOG_SEND,{otBase:t,extra:{}})}else console.error("log should call after start")}setOptions(a){this.isInit?ko.forEach(e=>{a[e]!==this.options[e]&&a[e]!=null&&a[e]!=""&&(this.options[e]=a[e],e==="uid"&&typeof this.setLocalStorage=="function"&&this.setLocalStorage(De.SLS_TRACE_UID_KEY,a[e]))}):console.error("setOptions should call after start")}start(){if(!this.isInit){this.isInit=!0;let a=this.options.uid;(a==null||a==="")&&(typeof this.getLocalStorage=="function"&&(a=this.getLocalStorage(De.SLS_TRACE_UID_KEY)),(a==null||a==="")&&(a=ps())),this.options.uid=a,typeof this.setLocalStorage=="function"&&this.setLocalStorage(De.SLS_TRACE_UID_KEY,a);const e=this.pendingPlugins.map(t=>t==null?void 0:t.name).filter(t=>t!=null);this.sub=new yo(e),this.context={options:this.options,session:this.session};for(const t of this.pendingPlugins)this.initPlugin(t)}}use(a){this.isInit?console.error(`plugin: ${a==null?void 0:a.name} use should run before start`):this.pendingPlugins.push(a)}}var Mo=Object.defineProperty,Cs=Object.getOwnPropertySymbols,No=Object.prototype.hasOwnProperty,Lo=Object.prototype.propertyIsEnumerable,Ms=(i,a,e)=>a in i?Mo(i,a,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[a]=e,Oo=(i,a)=>{for(var e in a||(a={}))No.call(a,e)&&Ms(i,e,a[e]);if(Cs)for(var e of Cs(a))Lo.call(a,e)&&Ms(i,e,a[e]);return i};function Vo(i,a){var e;const t={current:void 0},r=[];let s={};return typeof a=="function"&&(s=(e=a(t))!=null?e:{}),Oo({init:n=>{if(t.current!=null)return;t.current=i(n);const o=t.current;r.forEach(c=>{o.use(c)}),o.start()},use:n=>{r.push(n)},addLog:n=>{t.current.addLog(n)},onReady(n){n()},setOptions:n=>{t.current.setOptions(n)}},s)}class Do{constructor(){this.dep=new Map}subscribe(a,e){const t=this.dep.get(a);if(t){this.dep.set(a,t.concat(e));return}this.dep.set(a,[e])}notify(a,e){const t=this.dep.get(a);!a||!t||t.forEach(r=>{try{r(e)}catch(s){console.error(s)}})}}N.ONE_DAY=cs,N.ONE_HOUR=os,N.ONE_KILO_BYTE=En,N.ONE_MINUTE=ns,N.ONE_SECOND=as,N.ONE_YEAR=us,N.Observable=gn,N.SDK_VERSION=hs,N.SLSClient=Co,N.Subscribe=Do,N.assembleOTAttribute=Dt,N.buildHttpInfo=Dn,N.callMonitored=Lt,N.catchUserErrors=ii,N.clocksNow=jn,N.clocksOrigin=$n,N.computeStackTrace=Vt,N.createHandlingStack=ao,N.currentDrift=Hn,N.debugLog=is,N.defineGlobal=pn,N.defineGlobalValue=Qi,N.elapsed=Wn,N.formatErrorMessage=ws,N.formatUnknownError=so,N.genUid=ps,N.generateSpanId=ar,N.generateTraceId=Is,N.generateUUID=ti,N.getB3Header=ai,N.getConsoleLogStatus=Sn,N.getCorrectedTimeStamp=ms,N.getJaegerTraceHeaderr=oi,N.getRelativeTime=Kn,N.getTimeStamp=bs,N.getTrackUrl=gs,N.getW3CTraceHeader=ni,N.includes=kn,N.instrumentMethod=ys,N.instrumentMethodAndCallOriginal=er,N.isError=Pn,N.isInternalUrl=Nn,N.isNumber=ls,N.isString=Tn,N.isURL=On,N.looksLikeRelativeTime=Jn,N.makeWebPublicApi=Vo,N.matchCondition=xn,N.matchSample=Mn,N.matchWithDefault=Cn,N.monitor=fn,N.noop=An,N.parseUri=Vn,N.patchHeaderOnRequest=co,N.patchHeaderOnXhr=uo,N.relativeNow=Ss,N.relativeToClocks=Bn,N.resetNavigationStart=qn,N.round=ds,N.shouldTrackBody=Un,N.startUnhandledErrorCollection=to,N.timeStampNow=Zi,N.toServerDuration=Fn,N.toStackTraceString=tr;var xo=class{constructor(i){this.timer=null,this.time=10,this.count=10,this.arr=[];var a,e;this.time=(a=i.time)!=null?a:10,this.count=(e=i.count)!=null?e:10,this.url="https://"+i.project+"."+i.host+"/logstores/"+i.logstore+"/track",this.opt=i,i.installUnloadHook&&typeof i.installUnloadHook=="function"&&i.installUnloadHook(()=>{this.sendImmediateInner()})}assemblePayload(i=this.arr){const a={__logs__:i};return this.opt.tags&&(a.__tags__=this.opt.tags),this.opt.topic&&(a.__topic__=this.opt.topic),this.opt.source&&(a.__source__=this.opt.source),JSON.stringify(a)}platformSend(){if(this.opt.sendPayload&&typeof this.opt.sendPayload=="function"){const i=this.assemblePayload();this.opt.sendPayload(this.url,i)}}transString(i){let a={};for(let e in i)typeof i[e]=="object"?a[e]=JSON.stringify(i[e]):a[e]=String(i[e]);return a}sendImmediateInner(){this.arr&&this.arr.length>0&&(this.platformSend(),this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.arr=[])}sendInner(){if(this.timer)this.arr.length>=this.count&&(clearTimeout(this.timer),this.timer=null,this.sendImmediateInner());else{const i=this;this.arr.length>=this.count||this.time<=0?this.sendImmediateInner():this.timer=setTimeout(function(){i.sendImmediateInner()},this.time*1e3)}}send(i){const a=this.transString(i);this.arr.push(a),this.sendInner()}sendImmediate(i){const a=this.transString(i);this.arr.push(a),this.sendImmediateInner()}sendBatchLogs(i){const a=i.map(e=>this.transString(e));this.arr.push(...a),this.sendInner()}sendBatchLogsImmediate(i){const a=i.map(e=>this.transString(e));this.arr.push(...a),this.sendImmediateInner()}},Uo=N,Bo=xo;function Ho(i,a){return navigator&&navigator.sendBeacon?navigator.sendBeacon(`${i}?APIVersion=0.6.0`,a):!1}function Fo(i,a){const e=new window.XMLHttpRequest;e.open("POST",i,!0),e.setRequestHeader("x-log-apiversion","0.6.0"),e.setRequestHeader("x-log-bodyrawsize",a.length.toString());const t=new Blob([a],{type:"application/x-protobuf"});e.send(t)}function jo(i,a){try{Ho(i,a)||Fo(i,a)}catch(e){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
|
|
9
|
+
`+e),console.error("Failed log data:",i))}}class Ns extends Bo{constructor(a){const e=Object.assign({},a,{installUnloadHook:t=>{window.addEventListener("beforeunload",()=>{t()})},sendPayload:(t,r)=>{jo(t,r)}});super(e)}}Uo.defineGlobal(window,"SLS_Tracker",Ns);var $o=Ns,ui={},Wo={get exports(){return ui},set exports(i){ui=i}};(function(i,a){(function(e,t){var r="1.0.35",s="",n="?",o="function",c="undefined",u="object",h="string",l="major",d="model",f="name",m="type",g="vendor",S="version",b="architecture",w="console",_="mobile",R="tablet",V="smarttv",K="wearable",F="embedded",O=350,ee="Amazon",Re="Apple",st="ASUS",he="BlackBerry",le="Browser",ye="Chrome",$e="Edge",Ge="Firefox",ze="Google",Ne="Huawei",Pe="LG",xe="Microsoft",Ie="Motorola",fe="Opera",me="Samsung",We="Sharp",Y="Sony",de="Xiaomi",Ke="Zebra",Ut="Facebook",yt="Chromium OS",Bt="Mac OS",gt=function($,z){var H={};for(var Q in $)z[Q]&&z[Q].length%2===0?H[Q]=z[Q].concat($[Q]):H[Q]=$[Q];return H},at=function($){for(var z={},H=0;H<$.length;H++)z[$[H].toUpperCase()]=$[H];return z},Ht=function($,z){return typeof $===h?Ft(z).indexOf(Ft($))!==-1:!1},Ft=function($){return $.toLowerCase()},wc=function($){return typeof $===h?$.replace(/[^\d\.]/g,s).split(".")[0]:t},pr=function($,z){if(typeof $===h)return $=$.replace(/^\s\s*/,s),typeof z===c?$:$.substring(0,O)},jt=function($,z){for(var H=0,Q,nt,Je,G,U,Xe;H<z.length&&!U;){var fr=z[H],Qs=z[H+1];for(Q=nt=0;Q<fr.length&&!U&&fr[Q];)if(U=fr[Q++].exec($),U)for(Je=0;Je<Qs.length;Je++)Xe=U[++nt],G=Qs[Je],typeof G===u&&G.length>0?G.length===2?typeof G[1]==o?this[G[0]]=G[1].call(this,Xe):this[G[0]]=G[1]:G.length===3?typeof G[1]===o&&!(G[1].exec&&G[1].test)?this[G[0]]=Xe?G[1].call(this,Xe,G[2]):t:this[G[0]]=Xe?Xe.replace(G[1],G[2]):t:G.length===4&&(this[G[0]]=Xe?G[3].call(this,Xe.replace(G[1],G[2])):t):this[G]=Xe||t;H+=2}},gr=function($,z){for(var H in z)if(typeof z[H]===u&&z[H].length>0){for(var Q=0;Q<z[H].length;Q++)if(Ht(z[H][Q],$))return H===n?t:H}else if(Ht(z[H],$))return H===n?t:H;return $},_c={"1.0":"/8","1.2":"/1","1.3":"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"},Xs={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"},Ys={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[S,[f,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[S,[f,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[f,S],[/opios[\/ ]+([\w\.]+)/i],[S,[f,fe+" Mini"]],[/\bopr\/([\w\.]+)/i],[S,[f,fe]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[f,S],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[S,[f,"UC"+le]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[S,[f,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[S,[f,"WeChat"]],[/konqueror\/([\w\.]+)/i],[S,[f,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[S,[f,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[S,[f,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[f,/(.+)/,"$1 Secure "+le],S],[/\bfocus\/([\w\.]+)/i],[S,[f,Ge+" Focus"]],[/\bopt\/([\w\.]+)/i],[S,[f,fe+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[S,[f,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[S,[f,"Dolphin"]],[/coast\/([\w\.]+)/i],[S,[f,fe+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[S,[f,"MIUI "+le]],[/fxios\/([-\w\.]+)/i],[S,[f,Ge]],[/\bqihu|(qi?ho?o?|360)browser/i],[[f,"360 "+le]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[f,/(.+)/,"$1 "+le],S],[/(comodo_dragon)\/([\w\.]+)/i],[[f,/_/g," "],S],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[f,S],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[f],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[f,Ut],S],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[f,S],[/\bgsa\/([\w\.]+) .*safari\//i],[S,[f,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[S,[f,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[S,[f,ye+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[f,ye+" WebView"],S],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[S,[f,"Android "+le]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[f,S],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[S,[f,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[S,f],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[f,[S,gr,_c]],[/(webkit|khtml)\/([\w\.]+)/i],[f,S],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[f,"Netscape"],S],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[S,[f,Ge+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[f,S],[/(cobalt)\/([\w\.]+)/i],[f,[S,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[b,"amd64"]],[/(ia32(?=;))/i],[[b,Ft]],[/((?:i[346]|x)86)[;\)]/i],[[b,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[b,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[b,"armhf"]],[/windows (ce|mobile); ppc;/i],[[b,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[b,/ower/,s,Ft]],[/(sun4\w)[;\)]/i],[[b,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[b,Ft]]],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],[d,[g,me],[m,R]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[d,[g,me],[m,_]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[d,[g,Re],[m,_]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[d,[g,Re],[m,R]],[/(macintosh);/i],[d,[g,Re]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[d,[g,We],[m,_]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[d,[g,Ne],[m,R]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[d,[g,Ne],[m,_]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[d,/_/g," "],[g,de],[m,_]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[d,/_/g," "],[g,de],[m,R]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[d,[g,"OPPO"],[m,_]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[d,[g,"Vivo"],[m,_]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[d,[g,"Realme"],[m,_]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[d,[g,Ie],[m,_]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[d,[g,Ie],[m,R]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[d,[g,Pe],[m,R]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[d,[g,Pe],[m,_]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[d,[g,"Lenovo"],[m,R]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[d,/_/g," "],[g,"Nokia"],[m,_]],[/(pixel c)\b/i],[d,[g,ze],[m,R]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[d,[g,ze],[m,_]],[/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],[d,[g,Y],[m,_]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[d,"Xperia Tablet"],[g,Y],[m,R]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[d,[g,"OnePlus"],[m,_]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[d,[g,ee],[m,R]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[d,/(.+)/g,"Fire Phone $1"],[g,ee],[m,_]],[/(playbook);[-\w\),; ]+(rim)/i],[d,g,[m,R]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[d,[g,he],[m,_]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[d,[g,st],[m,R]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[d,[g,st],[m,_]],[/(nexus 9)/i],[d,[g,"HTC"],[m,R]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[g,[d,/_/g," "],[m,_]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[d,[g,"Acer"],[m,R]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[d,[g,"Meizu"],[m,_]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[g,d,[m,_]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[g,d,[m,R]],[/(surface duo)/i],[d,[g,xe],[m,R]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[d,[g,"Fairphone"],[m,_]],[/(u304aa)/i],[d,[g,"AT&T"],[m,_]],[/\bsie-(\w*)/i],[d,[g,"Siemens"],[m,_]],[/\b(rct\w+) b/i],[d,[g,"RCA"],[m,R]],[/\b(venue[\d ]{2,7}) b/i],[d,[g,"Dell"],[m,R]],[/\b(q(?:mv|ta)\w+) b/i],[d,[g,"Verizon"],[m,R]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[d,[g,"Barnes & Noble"],[m,R]],[/\b(tm\d{3}\w+) b/i],[d,[g,"NuVision"],[m,R]],[/\b(k88) b/i],[d,[g,"ZTE"],[m,R]],[/\b(nx\d{3}j) b/i],[d,[g,"ZTE"],[m,_]],[/\b(gen\d{3}) b.+49h/i],[d,[g,"Swiss"],[m,_]],[/\b(zur\d{3}) b/i],[d,[g,"Swiss"],[m,R]],[/\b((zeki)?tb.*\b) b/i],[d,[g,"Zeki"],[m,R]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[g,"Dragon Touch"],d,[m,R]],[/\b(ns-?\w{0,9}) b/i],[d,[g,"Insignia"],[m,R]],[/\b((nxa|next)-?\w{0,9}) b/i],[d,[g,"NextBook"],[m,R]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[g,"Voice"],d,[m,_]],[/\b(lvtel\-)?(v1[12]) b/i],[[g,"LvTel"],d,[m,_]],[/\b(ph-1) /i],[d,[g,"Essential"],[m,_]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[d,[g,"Envizen"],[m,R]],[/\b(trio[-\w\. ]+) b/i],[d,[g,"MachSpeed"],[m,R]],[/\btu_(1491) b/i],[d,[g,"Rotor"],[m,R]],[/(shield[\w ]+) b/i],[d,[g,"Nvidia"],[m,R]],[/(sprint) (\w+)/i],[g,d,[m,_]],[/(kin\.[onetw]{3})/i],[[d,/\./g," "],[g,xe],[m,_]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[d,[g,Ke],[m,R]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[d,[g,Ke],[m,_]],[/smart-tv.+(samsung)/i],[g,[m,V]],[/hbbtv.+maple;(\d+)/i],[[d,/^/,"SmartTV"],[g,me],[m,V]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[g,Pe],[m,V]],[/(apple) ?tv/i],[g,[d,Re+" TV"],[m,V]],[/crkey/i],[[d,ye+"cast"],[g,ze],[m,V]],[/droid.+aft(\w)( bui|\))/i],[d,[g,ee],[m,V]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[d,[g,We],[m,V]],[/(bravia[\w ]+)( bui|\))/i],[d,[g,Y],[m,V]],[/(mitv-\w{5}) bui/i],[d,[g,de],[m,V]],[/Hbbtv.*(technisat) (.*);/i],[g,d,[m,V]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[g,pr],[d,pr],[m,V]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[m,V]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[g,d,[m,w]],[/droid.+; (shield) bui/i],[d,[g,"Nvidia"],[m,w]],[/(playstation [345portablevi]+)/i],[d,[g,Y],[m,w]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[d,[g,xe],[m,w]],[/((pebble))app/i],[g,d,[m,K]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[d,[g,Re],[m,K]],[/droid.+; (glass) \d/i],[d,[g,ze],[m,K]],[/droid.+; (wt63?0{2,3})\)/i],[d,[g,Ke],[m,K]],[/(quest( 2| pro)?)/i],[d,[g,Ut],[m,K]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[g,[m,F]],[/(aeobc)\b/i],[d,[g,ee],[m,F]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[d,[m,_]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[d,[m,R]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[m,R]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[m,_]],[/(android[-\w\. ]{0,9});.+buil/i],[d,[g,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[S,[f,$e+"HTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[S,[f,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[f,S],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[S,f]],os:[[/microsoft (windows) (vista|xp)/i],[f,S],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[f,[S,gr,Xs]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[f,"Windows"],[S,gr,Xs]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/ios;fbsv\/([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[S,/_/g,"."],[f,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[f,Bt],[S,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[S,f],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[f,S],[/\(bb(10);/i],[S,[f,he]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[S,[f,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[S,[f,Ge+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[S,[f,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[S,[f,"watchOS"]],[/crkey\/([\d\.]+)/i],[S,[f,ye+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[f,yt],S],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[f,S],[/(sunos) ?([\w\.\d]*)/i],[[f,"Solaris"],S],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[f,S]]},Ue=function($,z){if(typeof $===u&&(z=$,$=t),!(this instanceof Ue))return new Ue($,z).getResult();var H=typeof e!==c&&e.navigator?e.navigator:t,Q=$||(H&&H.userAgent?H.userAgent:s),nt=H&&H.userAgentData?H.userAgentData:t,Je=z?gt(Ys,z):Ys,G=H&&H.userAgent==Q;return this.getBrowser=function(){var U={};return U[f]=t,U[S]=t,jt.call(U,Q,Je.browser),U[l]=wc(U[S]),G&&H&&H.brave&&typeof H.brave.isBrave==o&&(U[f]="Brave"),U},this.getCPU=function(){var U={};return U[b]=t,jt.call(U,Q,Je.cpu),U},this.getDevice=function(){var U={};return U[g]=t,U[d]=t,U[m]=t,jt.call(U,Q,Je.device),G&&!U[m]&&nt&&nt.mobile&&(U[m]=_),G&&U[d]=="Macintosh"&&H&&typeof H.standalone!==c&&H.maxTouchPoints&&H.maxTouchPoints>2&&(U[d]="iPad",U[m]=R),U},this.getEngine=function(){var U={};return U[f]=t,U[S]=t,jt.call(U,Q,Je.engine),U},this.getOS=function(){var U={};return U[f]=t,U[S]=t,jt.call(U,Q,Je.os),G&&!U[f]&&nt&&nt.platform!="Unknown"&&(U[f]=nt.platform.replace(/chrome os/i,yt).replace(/macos/i,Bt)),U},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 Q},this.setUA=function(U){return Q=typeof U===h&&U.length>O?pr(U,O):U,this},this.setUA(Q),this};Ue.VERSION=r,Ue.BROWSER=at([f,S,l]),Ue.CPU=at([b]),Ue.DEVICE=at([d,g,m,w,_,V,R,K,F]),Ue.ENGINE=Ue.OS=at([f,S]),i.exports&&(a=i.exports=Ue),a.UAParser=Ue;var wt=typeof e!==c&&(e.jQuery||e.Zepto);if(wt&&!wt.ua){var fi=new Ue;wt.ua=fi.getResult(),wt.ua.get=function(){return fi.getUA()},wt.ua.set=function($){fi.setUA($);var z=fi.getResult();for(var H in z)wt.ua[H]=z[H]}}})(typeof window=="object"?window:un)})(Wo,ui);let hi;const Ko=new Uint8Array(16);function Jo(){if(!hi&&(hi=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!hi))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return hi(Ko)}const ue=[];for(let i=0;i<256;++i)ue.push((i+256).toString(16).slice(1));function qo(i,a=0){return(ue[i[a+0]]+ue[i[a+1]]+ue[i[a+2]]+ue[i[a+3]]+"-"+ue[i[a+4]]+ue[i[a+5]]+"-"+ue[i[a+6]]+ue[i[a+7]]+"-"+ue[i[a+8]]+ue[i[a+9]]+"-"+ue[i[a+10]]+ue[i[a+11]]+ue[i[a+12]]+ue[i[a+13]]+ue[i[a+14]]+ue[i[a+15]]).toLowerCase()}const Go=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Ls={randomUUID:Go};function zo(i,a,e){if(Ls.randomUUID&&!a&&!i)return Ls.randomUUID();i=i||{};const t=i.random||(i.rng||Jo)();if(t[6]=t[6]&15|64,t[8]=t[8]&63|128,a){e=e||0;for(let r=0;r<16;++r)a[e+r]=t[r];return a}return qo(t)}var nr={},Xo={get exports(){return nr},set exports(i){nr=i}},or={},Yo={get exports(){return or},set exports(i){or=i}};(function(){var i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a={rotl:function(e,t){return e<<t|e>>>32-t},rotr:function(e,t){return e<<32-t|e>>>t},endian:function(e){if(e.constructor==Number)return a.rotl(e,8)&16711935|a.rotl(e,24)&4278255360;for(var t=0;t<e.length;t++)e[t]=a.endian(e[t]);return e},randomBytes:function(e){for(var t=[];e>0;e--)t.push(Math.floor(Math.random()*256));return t},bytesToWords:function(e){for(var t=[],r=0,s=0;r<e.length;r++,s+=8)t[s>>>5]|=e[r]<<24-s%32;return t},wordsToBytes:function(e){for(var t=[],r=0;r<e.length*32;r+=8)t.push(e[r>>>5]>>>24-r%32&255);return t},bytesToHex:function(e){for(var t=[],r=0;r<e.length;r++)t.push((e[r]>>>4).toString(16)),t.push((e[r]&15).toString(16));return t.join("")},hexToBytes:function(e){for(var t=[],r=0;r<e.length;r+=2)t.push(parseInt(e.substr(r,2),16));return t},bytesToBase64:function(e){for(var t=[],r=0;r<e.length;r+=3)for(var s=e[r]<<16|e[r+1]<<8|e[r+2],n=0;n<4;n++)r*8+n*6<=e.length*8?t.push(i.charAt(s>>>6*(3-n)&63)):t.push("=");return t.join("")},base64ToBytes:function(e){e=e.replace(/[^A-Z0-9+\/]/ig,"");for(var t=[],r=0,s=0;r<e.length;s=++r%4)s!=0&&t.push((i.indexOf(e.charAt(r-1))&Math.pow(2,-2*s+8)-1)<<s*2|i.indexOf(e.charAt(r))>>>6-s*2);return t}};Yo.exports=a})();var cr={utf8:{stringToBytes:function(i){return cr.bin.stringToBytes(unescape(encodeURIComponent(i)))},bytesToString:function(i){return decodeURIComponent(escape(cr.bin.bytesToString(i)))}},bin:{stringToBytes:function(i){for(var a=[],e=0;e<i.length;e++)a.push(i.charCodeAt(e)&255);return a},bytesToString:function(i){for(var a=[],e=0;e<i.length;e++)a.push(String.fromCharCode(i[e]));return a.join("")}}},Os=cr;/*!
|
|
10
10
|
* Determine if an object is a Buffer
|
|
11
11
|
*
|
|
12
12
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
13
13
|
* @license MIT
|
|
14
|
-
*/var Ic=function(t){return t!=null&&(zs(t)||Ec(t)||!!t._isBuffer)};function zs(t){return!!t.constructor&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t)}function Ec(t){return typeof t.readFloatLE=="function"&&typeof t.slice=="function"&&zs(t.slice(0,0))}(function(){var t=br,r=Gs.utf8,e=Ic,i=Gs.bin,s=function(a,n){a.constructor==String?n&&n.encoding==="binary"?a=i.stringToBytes(a):a=r.stringToBytes(a):e(a)?a=Array.prototype.slice.call(a,0):!Array.isArray(a)&&a.constructor!==Uint8Array&&(a=a.toString());for(var o=t.bytesToWords(a),c=a.length*8,h=1732584193,f=-271733879,p=-1732584194,u=271733878,g=0;g<o.length;g++)o[g]=(o[g]<<8|o[g]>>>24)&16711935|(o[g]<<24|o[g]>>>8)&4278255360;o[c>>>5]|=128<<c%32,o[(c+64>>>9<<4)+14]=c;for(var m=s._ff,d=s._gg,S=s._hh,b=s._ii,g=0;g<o.length;g+=16){var w=h,_=f,R=p,x=u;h=m(h,f,p,u,o[g+0],7,-680876936),u=m(u,h,f,p,o[g+1],12,-389564586),p=m(p,u,h,f,o[g+2],17,606105819),f=m(f,p,u,h,o[g+3],22,-1044525330),h=m(h,f,p,u,o[g+4],7,-176418897),u=m(u,h,f,p,o[g+5],12,1200080426),p=m(p,u,h,f,o[g+6],17,-1473231341),f=m(f,p,u,h,o[g+7],22,-45705983),h=m(h,f,p,u,o[g+8],7,1770035416),u=m(u,h,f,p,o[g+9],12,-1958414417),p=m(p,u,h,f,o[g+10],17,-42063),f=m(f,p,u,h,o[g+11],22,-1990404162),h=m(h,f,p,u,o[g+12],7,1804603682),u=m(u,h,f,p,o[g+13],12,-40341101),p=m(p,u,h,f,o[g+14],17,-1502002290),f=m(f,p,u,h,o[g+15],22,1236535329),h=d(h,f,p,u,o[g+1],5,-165796510),u=d(u,h,f,p,o[g+6],9,-1069501632),p=d(p,u,h,f,o[g+11],14,643717713),f=d(f,p,u,h,o[g+0],20,-373897302),h=d(h,f,p,u,o[g+5],5,-701558691),u=d(u,h,f,p,o[g+10],9,38016083),p=d(p,u,h,f,o[g+15],14,-660478335),f=d(f,p,u,h,o[g+4],20,-405537848),h=d(h,f,p,u,o[g+9],5,568446438),u=d(u,h,f,p,o[g+14],9,-1019803690),p=d(p,u,h,f,o[g+3],14,-187363961),f=d(f,p,u,h,o[g+8],20,1163531501),h=d(h,f,p,u,o[g+13],5,-1444681467),u=d(u,h,f,p,o[g+2],9,-51403784),p=d(p,u,h,f,o[g+7],14,1735328473),f=d(f,p,u,h,o[g+12],20,-1926607734),h=S(h,f,p,u,o[g+5],4,-378558),u=S(u,h,f,p,o[g+8],11,-2022574463),p=S(p,u,h,f,o[g+11],16,1839030562),f=S(f,p,u,h,o[g+14],23,-35309556),h=S(h,f,p,u,o[g+1],4,-1530992060),u=S(u,h,f,p,o[g+4],11,1272893353),p=S(p,u,h,f,o[g+7],16,-155497632),f=S(f,p,u,h,o[g+10],23,-1094730640),h=S(h,f,p,u,o[g+13],4,681279174),u=S(u,h,f,p,o[g+0],11,-358537222),p=S(p,u,h,f,o[g+3],16,-722521979),f=S(f,p,u,h,o[g+6],23,76029189),h=S(h,f,p,u,o[g+9],4,-640364487),u=S(u,h,f,p,o[g+12],11,-421815835),p=S(p,u,h,f,o[g+15],16,530742520),f=S(f,p,u,h,o[g+2],23,-995338651),h=b(h,f,p,u,o[g+0],6,-198630844),u=b(u,h,f,p,o[g+7],10,1126891415),p=b(p,u,h,f,o[g+14],15,-1416354905),f=b(f,p,u,h,o[g+5],21,-57434055),h=b(h,f,p,u,o[g+12],6,1700485571),u=b(u,h,f,p,o[g+3],10,-1894986606),p=b(p,u,h,f,o[g+10],15,-1051523),f=b(f,p,u,h,o[g+1],21,-2054922799),h=b(h,f,p,u,o[g+8],6,1873313359),u=b(u,h,f,p,o[g+15],10,-30611744),p=b(p,u,h,f,o[g+6],15,-1560198380),f=b(f,p,u,h,o[g+13],21,1309151649),h=b(h,f,p,u,o[g+4],6,-145523070),u=b(u,h,f,p,o[g+11],10,-1120210379),p=b(p,u,h,f,o[g+2],15,718787259),f=b(f,p,u,h,o[g+9],21,-343485551),h=h+w>>>0,f=f+_>>>0,p=p+R>>>0,u=u+x>>>0}return t.endian([h,f,p,u])};s._ff=function(a,n,o,c,h,f,p){var u=a+(n&o|~n&c)+(h>>>0)+p;return(u<<f|u>>>32-f)+n},s._gg=function(a,n,o,c,h,f,p){var u=a+(n&c|o&~c)+(h>>>0)+p;return(u<<f|u>>>32-f)+n},s._hh=function(a,n,o,c,h,f,p){var u=a+(n^o^c)+(h>>>0)+p;return(u<<f|u>>>32-f)+n},s._ii=function(a,n,o,c,h,f,p){var u=a+(o^(n|~c))+(h>>>0)+p;return(u<<f|u>>>32-f)+n},s._blocksize=16,s._digestsize=16,_c.exports=function(a,n){if(a==null)throw new Error("Illegal argument "+a);var o=t.wordsToBytes(s(a,n));return n&&n.asBytes?o:n&&n.asString?i.bytesToString(o):t.bytesToHex(o)}})();function Ac(t){return t?t.toLowerCase().indexOf("android")>=0||t.toLowerCase().indexOf("ios")>=0?"h5":"pc":"unknown"}function Tc(t){const r=Sr(t),e=localStorage.getItem(r);if(e&&e.length===36)return e;const i=wc();return localStorage.setItem(r,i),i}var Ei,Ai,Xt;class Xs{constructor(r){or(this,Ei,void 0),or(this,Ai,void 0),or(this,Xt,void 0);const c=r,{commonParams:e,version:i}=c,s=fa(c,["commonParams","version"]);cr(this,Ei,new fc(s)),cr(this,Xt,Tc(s.project));const a=new Ri;a.setUA(window.navigator.userAgent);const n=a.getResult(),o=q({av:i,os:n.os.name,ov:n.os.version,bt:n.browser.name,bv:n.browser.version,tt:Ac(n.os.name),uuid:gi(this,Xt),host:window.location.host},e);cr(this,Ai,o)}getUUID(){return gi(this,Xt)}send(r,e,i){gi(this,Ei).send(q(q({msgId:String(r),args:typeof e=="string"?e:new URLSearchParams(e).toString(),pu:window.location.href,ct:Date.now().toString()},gi(this,Ai)),i))}}Ei=new WeakMap,Ai=new WeakMap,Xt=new WeakMap;class Pc{constructor(r){l(this,"index",0);l(this,"tracker");l(this,"enable",!0);l(this,"commonParams",{});if(r===!1){this.enable=!1;return}if(typeof r=="object"&&r.extraParams&&typeof r.extraParams=="string")try{this.commonParams={extra:r.extraParams}}catch(e){}this.tracker=new Xs({version:Dt,host:"cn-hangzhou.log.aliyuncs.com",project:"web-rtc-grtn",logstore:"client",time:5,count:10,source:typeof r=="object"?r.biz:""})}updateAuthInfo(r){var e,i,s;this.commonParams=Lt(q({},this.commonParams),{apid:(e=r==null?void 0:r.appId)!=null?e:"",usrid:(i=r==null?void 0:r.userId)!=null?i:"",channelid:(s=r==null?void 0:r.channelId)!=null?s:""})}reportJoinChannel(r){var i,s,a;const e={jnnonce:(i=r==null?void 0:r.nonce)!=null?i:"",jntoken:(s=r==null?void 0:r.token)!=null?s:"",jntm:(a=r==null?void 0:r.timestamp)!=null?a:""};this.report(70012,e)}reportJoinChannelRes(r,e,i){this.report(70013,{rslt:r,message:e,ct:i})}reportLeaveChannel(){this.report(70015)}reportPush(r,e,i,s,a,n,o,c,h,f,p,u){this.report(10030,{calid:r,isvl:e?1:0,isvs:i?1:0,isvss:s?1:0,isaudio:a?1:0,rslt:n,tid:o,pubtm:c,est:h,dctid:f,httptid:p,url:u})}reportPull(r,e,i,s,a,n,o,c,h,f,p,u){this.report(10050,{calid:r,rmtid:e,isvl:i?1:0,isvs:s?1:0,isvss:a?1:0,isaudio:n?1:0,rslt:o,tid:"",subtm:c,dctid:h,httptid:f,ajsub:1,url:p,est:u})}reportSubscribeAudioStats(r,e){const{ssrc:i,bytesReceived:s,packetsReceived:a,packetsLost:n,jitterBufferDelay:o,trackIdentifier:c,totalSamplesDuration:h,codec:f}=e,p=h,u=s/p,g=a/p,m=n/p,d=n/a;this.report(10080,{calid:"",rmtid:r,tckid:c,ssrc:i,codec:f,rbr:u,pr:g,pl:m,plr:d,jd:o})}reportSubscribeVideoStats(r,e){const{ssrc:i,bytesReceived:s,trackIdentifier:a,framesDecoded:n,framesReceived:o,frameHeight:c,frameWidth:h,nackCount:f,jitterBufferDelay:p,packetsReceived:u,packetsLost:g,totalInterFrameDelay:m,codec:d}=e,S=m,b=s/S,w=n/S,_=o/S,R=u/S,x=g/S,z=g/u;this.report(10080,{calid:"",rmtid:r,tckid:a,ssrc:i,codec:d,rbr:b,dfps:w,rfps:_,rh:c,rw:h,ns:f,jd:p,pr:R,pl:x,plr:z})}report(r,e,i){var s;this.enable&&((s=this.tracker)==null||s.send(r,e,q(q({},this.commonParams),i!=null?i:{})))}static reportCheck(r,e){new Xs({version:Dt,host:"cn-hangzhou.log.aliyuncs.com",project:"web-rtc-grtn",logstore:"client",time:5,count:10,source:e!=null?e:""}).send(100001,r)}}class kc{constructor(){l(this,"reporter");l(this,"param");l(this,"msgCacheArr",[]);l(this,"index",0)}start(r){this.initParam(r),this.reporter=new ii.LogReporter({wsUrl:"wss://logprod.aliyuncs.com/binlog",webtrackingUrl:"",wsConfig:{product:1}});let e=window.setInterval(()=>{this.msgCacheArr.length?this.realSendReport(this.msgCacheArr.shift()):(clearInterval(e),e=0)},200)}stop(){this.reporter&&(this.reporter.close(),this.reporter=void 0)}sendReport(r){E.info("[LogClient]",r),this.msgCacheArr.length===0&&this.param?this.realSendReport(r):this.msgCacheArr.push(r)}initParam(r){this.param||(this.param={osn:D.SystemUtil.systemName,osv:D.SystemUtil.systemVersion,udid:D.LocalStorage.uuid,statsvrs:"0.6.1",sdkvrs:Dt,dm:D.BrowserUtil.domain,bt:D.BrowserUtil.browserName,bv:D.BrowserUtil.browserVersion,envir:"PRODUCT",apid:r.appId,usrid:r.userId,channelid:r.channelId,evetid:0,args:""})}realSendReport(r){var i;let e={};for(let s in this.param)e[s]=this.param[s];for(let s in r)e[s]=r[s];e.idx=this.index,++this.index,(i=this.reporter)==null||i.send(e)}}class Cc{constructor(){l(this,"logClient");this.logClient=new kc}start(r){this.logClient.start(r)}stop(){this.logClient.stop()}reportJoin(r,e,i){this.log({evetid:10010,args:this.data2String({joitm:r,rslt:e,mode:"wss",tid:i,gslbtm:0})})}reportJoinInvoked(r,e,i){this.log({evetid:60010,args:this.data2String({usrid:r,usrn:e,channelid:i,ua:navigator.userAgent})})}reportIceState(r,e,i){this.log({evetid:10011,args:this.data2String({calid:r,icestate:e,evt_seq:i})})}reportLeave(r,e,i){this.log({evetid:10020,args:this.data2String({lvetm:r,rslt:e,tid:i})})}reportLeaveInvoked(){this.log({evetid:60020})}reportPublish(r,e,i,s,a,n,o,c){this.log({evetid:10030,args:this.data2String({callid:r,isvl:e?1:0,isvs:i?1:0,isvss:s?1:0,isaudio:a?1:0,rslt:n,tid:o,pubtm:c})})}reportPublishInvoked(r,e,i,s){this.log({evetid:60030,args:this.data2String({isvl:typeof r=="boolean"?r?1:0:r,isvs:typeof e=="boolean"?e?1:0:e,isvss:typeof i=="boolean"?i?1:0:i,isaudio:typeof s=="boolean"?s?1:0:s})})}reportRepublish(r,e,i,s,a,n,o,c){this.log({evetid:10032,args:this.data2String({calid:r,isvl:e?1:0,isvs:0,isvss:i?1:0,isaudio:s?1:0,rslt:a,tid:n,repubtm:o,msg:c})})}reportRepublishInvoked(r,e,i){this.log({evetid:60032,args:this.data2String({callid:r,st:i,tp:e})})}reportUnpublish(r,e,i,s){this.log({evetid:10040,args:this.data2String({calid:r,unpubtm:e,rslt:i,tid:s})})}reportUnpublishInvoked(){this.log({evetid:60040})}reportSubscribe(r,e,i,s,a,n,o,c,h,f){this.log({evetid:10050,args:this.data2String({calid:r,rmtid:e,isvl:i?1:0,isvs:s?1:0,isvss:a?1:0,isaudio:n?1:0,rslt:o,tid:c,subtm:h,rmtuid:f})})}reportSubscribeInvoked(r="",e,i,s,a){this.log({evetid:60050,args:this.data2String({rmtid:r,isvl:typeof e=="boolean"?e?1:0:e,isvs:typeof i=="boolean"?i?1:0:i,isvss:typeof s=="boolean"?s?1:0:s,isaudio:typeof a=="boolean"?a?1:0:a})})}reportUnsubscribe(r,e,i,s,a){this.log({evetid:10060,args:this.data2String({calid:r,rmtid:e,unsubtm:i,rslt:s,tid:a})})}reportUnsubscribeInvoked(r=""){this.log({evetid:60060,args:this.data2String({rmtid:r})})}reportRoleUpdate(r,e,i,s){this.log({evetid:11040,args:this.data2String({or:r,nr:e,ctm:i,rslt:s})})}reportRoleUpdateInvoked(r){this.log({evetid:61040,args:this.data2String({nr:r})})}reportVideoProfile(r){this.log({evetid:20074,args:this.data2String({pf:r,tckid:"sophon_camera_large"})})}reportScreenProfile(r){this.log({evetid:20074,args:this.data2String({pf:r,tckid:"sophon_screenshare"})})}reportError(r){this.log({evetid:20090,args:this.data2String(r)})}log(r){r&&(r.tm=new Date().getTime()),this.logClient.sendReport(r)}data2String(r){let e="";for(let i in r)e.length&&(e+="&"),e+=i+"="+r[i];return e}}class Ys{constructor(r){l(this,"name","COMMON");this.name=r||this.name}info(...r){}warn(...r){}print(r,...e){const i=r.toLowerCase();i&&console[i](`[${r}][${this.name}]`,...e)}}l(Ys,"LEVEL",0);class Mc{constructor(){l(this,"logger",new Ys("AudioMixer"));l(this,"audioContext",new AudioContext);l(this,"audioDestination",this.audioContext.createMediaStreamDestination());l(this,"audioTrack",ln(this.audioDestination.stream));l(this,"sourceNodeMap",{})}get sourceNodeList(){return Object.values(this.sourceNodeMap).map(r=>r.sourceNode).filter(r=>!!r)}get gainNodeList(){return Object.values(this.sourceNodeMap).map(r=>r.gainNode).filter(r=>!!r)}get sourceCount(){return this.sourceNodeList.length}resume(){var r;return(r=this.audioContext)==null?void 0:r.resume()}addTrack(r){this.connectTrack(r)}hasTrack(r){return!!this.sourceNodeMap[r]}removeTrack(r){const{sourceNode:e,gainNode:i}=this.sourceNodeMap[r]||{};i==null||i.disconnect(),e==null||e.disconnect(),delete this.sourceNodeMap[r],e?this.logger.info("SourceNode disconnected. Active source node:",this.sourceNodeList.length):this.logger.warn(`SourceNode ${r} does not exit. Active source node: ${this.sourceNodeList.length}`)}getAudioTrack(){return this.audioTrack}setVolume(r,e){const{gainNode:i}=this.sourceNodeMap[e]||{};i?(this.logger.info(`Setting node(${e}) volume to ${this.scale(r)}`),i.gain.value=this.scale(r)):this.logger.warn(`GainNode ${e} does not exit.`)}reset(){this.disconnectSourceNode(),this.sourceNodeMap={}}dispose(){var r;this.reset(),(r=this.audioTrack)==null||r.stop(),this.audioDestination.disconnect(),this.audioContext.close()}connectTrack(r){if(!this.audioContext)return this.logger.warn("AudioContext not initialized");let e=new MediaStream;e.addTrack(r);const i=this.audioContext.createMediaStreamSource(e),s=this.audioContext.createGain();s.gain.value=1,i.connect(s),s.connect(this.audioDestination),this.sourceNodeMap[r.id]={track:r,sourceNode:i,gainNode:s},this.logger.info("New sourceNode connected. Active source node:",this.sourceNodeList.length)}disconnectSourceNode(){this.sourceNodeList.forEach(r=>r.disconnect()),this.gainNodeList.forEach(r=>r.disconnect())}scale(r){return r/100}}const Nc=4;class Lc extends Tt{constructor(){super("audioMixer",ce.AliRtcSdkStreamTypeCapture,ni.AUDIO);l(this,"audioMixer");l(this,"primaryAudioTrackId");l(this,"screenAudioTrackId");l(this,"dirty",!1);this.zIndex=8}get initOptions(){return{audio:1,screen:1}}setOptions(e){Object.entries(e).forEach(([i,s])=>{this.isValidVolume(s)&&(this.options[i]=s)}),this.dirty=!0,this.emit("updated")}isSupported(){return"AudioContext"in window}shouldUpdate(e,i){var n,o;if(e.type!==ce.AliRtcSdkStreamTypeCapture)return!1;const s=i.find(c=>c.type===ce.AliRtcSdkStreamTypeCapture),a=i.find(c=>c.type===ce.AliRtcSdkStreamTypeScreen);return!(this.primaryAudioTrackId===((n=s==null?void 0:s.currentAudioTrack)==null?void 0:n.id)&&this.screenAudioTrackId===((o=a==null?void 0:a.currentAudioTrack)==null?void 0:o.id)&&!this.dirty)}process(e,i){return v(this,null,function*(){var o,c;this.dirty=!1;const s=i.find(h=>h.type===ce.AliRtcSdkStreamTypeScreen),a=e.currentAudioTrack,n=s==null?void 0:s.currentAudioTrack;if(!n&&this.options.audio===1){this.audioMixer&&(this.audioMixer.dispose(),this.audioMixer=void 0),this.primaryAudioTrackId=a==null?void 0:a.id,e.updateAudioTrack(a);return}this.audioMixer||(this.audioMixer=new Mc),yield this.audioMixer.resume(),this.primaryAudioTrackId&&(a==null?void 0:a.id)!==this.primaryAudioTrackId&&((o=this.audioMixer)==null||o.removeTrack(this.primaryAudioTrackId)),a&&!this.audioMixer.hasTrack(a==null?void 0:a.id)&&this.audioMixer.addTrack(a),this.primaryAudioTrackId=a==null?void 0:a.id,this.screenAudioTrackId&&(n==null?void 0:n.id)!==this.screenAudioTrackId&&((c=this.audioMixer)==null||c.removeTrack(this.screenAudioTrackId)),n&&!this.audioMixer.hasTrack(n==null?void 0:n.id)&&this.audioMixer.addTrack(n),this.screenAudioTrackId=n==null?void 0:n.id,this.updateVolume(),e.updateAudioTrack(this.audioMixer.getAudioTrack())})}isValidVolume(e){return e!==void 0&&e>=0&&e<=Nc}updateVolume(){this.audioMixer&&(this.primaryAudioTrackId&&this.audioMixer.setVolume(this.options.audio*100,this.primaryAudioTrackId),this.screenAudioTrackId&&this.audioMixer.setVolume(this.options.screen*100,this.screenAudioTrackId))}clear(e){var i;(i=this.audioMixer)==null||i.dispose(),super.clear(e)}}class yr{constructor(r,e){l(this,"originTrack");l(this,"originVideo");l(this,"targetWidth");l(this,"targetHeight");l(this,"targetFrameRate");l(this,"targetCanvas");l(this,"animationFrameId");l(this,"resultTrack");this.targetWidth=e.width,this.targetHeight=e.height,this.targetFrameRate=e.frameRate,this.originTrack=r,this.originVideo=document.createElement("video"),this.originVideo.muted=!0,this.originVideo.autoplay=!0,this.originVideo.controls=!1,this.targetCanvas=document.createElement("canvas"),this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight}updateOptions(r){this.targetWidth=r.width,this.targetHeight=r.height,this.targetFrameRate=r.frameRate,this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight,this.resultTrack&&this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})}dispose(){}getVideoTrack(){return this.resultTrack||(this.resultTrack=this.targetCanvas.captureStream().getVideoTracks()[0],this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})),this.resultTrack}cancelAnimation(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}getPositionAndSize(r,e,i,s){const a=e/r,n=s/i;let o=i,c=s,h=0,f=0;return n>a?(o=Math.round(c/a),h=Math.round((i-o)/2)):n<a&&(c=Math.round(o*a),f=Math.round((s-c)/2)),{x:h,y:f,width:o,height:c}}}class Oc extends yr{constructor(e,i){super(e,i);l(this,"targetCtx");this.targetCtx=this.targetCanvas.getContext("2d"),this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.initStream(e)}initStream(e){const i=new MediaStream;i.addTrack(e),this.originVideo.srcObject=i,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender)}startRender(){this.cancelAnimation();const e=()=>{if(!this.targetCtx)return;const i=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight);this.targetCtx.drawImage(this.originVideo,0,0,this.originVideo.videoWidth,this.originVideo.videoHeight,i.x,i.y,i.width,i.height),!this.originVideo.paused&&!this.originVideo.ended&&(this.animationFrameId=requestAnimationFrame(e))};e()}stopRender(){this.cancelAnimation()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.pause(),this.originVideo.srcObject=null}}const Vc=`
|
|
14
|
+
*/var Qo=function(i){return i!=null&&(Vs(i)||Zo(i)||!!i._isBuffer)};function Vs(i){return!!i.constructor&&typeof i.constructor.isBuffer=="function"&&i.constructor.isBuffer(i)}function Zo(i){return typeof i.readFloatLE=="function"&&typeof i.slice=="function"&&Vs(i.slice(0,0))}(function(){var i=or,a=Os.utf8,e=Qo,t=Os.bin,r=function(s,n){s.constructor==String?n&&n.encoding==="binary"?s=t.stringToBytes(s):s=a.stringToBytes(s):e(s)?s=Array.prototype.slice.call(s,0):!Array.isArray(s)&&s.constructor!==Uint8Array&&(s=s.toString());for(var o=i.bytesToWords(s),c=s.length*8,u=1732584193,h=-271733879,l=-1732584194,d=271733878,f=0;f<o.length;f++)o[f]=(o[f]<<8|o[f]>>>24)&16711935|(o[f]<<24|o[f]>>>8)&4278255360;o[c>>>5]|=128<<c%32,o[(c+64>>>9<<4)+14]=c;for(var m=r._ff,g=r._gg,S=r._hh,b=r._ii,f=0;f<o.length;f+=16){var w=u,_=h,R=l,V=d;u=m(u,h,l,d,o[f+0],7,-680876936),d=m(d,u,h,l,o[f+1],12,-389564586),l=m(l,d,u,h,o[f+2],17,606105819),h=m(h,l,d,u,o[f+3],22,-1044525330),u=m(u,h,l,d,o[f+4],7,-176418897),d=m(d,u,h,l,o[f+5],12,1200080426),l=m(l,d,u,h,o[f+6],17,-1473231341),h=m(h,l,d,u,o[f+7],22,-45705983),u=m(u,h,l,d,o[f+8],7,1770035416),d=m(d,u,h,l,o[f+9],12,-1958414417),l=m(l,d,u,h,o[f+10],17,-42063),h=m(h,l,d,u,o[f+11],22,-1990404162),u=m(u,h,l,d,o[f+12],7,1804603682),d=m(d,u,h,l,o[f+13],12,-40341101),l=m(l,d,u,h,o[f+14],17,-1502002290),h=m(h,l,d,u,o[f+15],22,1236535329),u=g(u,h,l,d,o[f+1],5,-165796510),d=g(d,u,h,l,o[f+6],9,-1069501632),l=g(l,d,u,h,o[f+11],14,643717713),h=g(h,l,d,u,o[f+0],20,-373897302),u=g(u,h,l,d,o[f+5],5,-701558691),d=g(d,u,h,l,o[f+10],9,38016083),l=g(l,d,u,h,o[f+15],14,-660478335),h=g(h,l,d,u,o[f+4],20,-405537848),u=g(u,h,l,d,o[f+9],5,568446438),d=g(d,u,h,l,o[f+14],9,-1019803690),l=g(l,d,u,h,o[f+3],14,-187363961),h=g(h,l,d,u,o[f+8],20,1163531501),u=g(u,h,l,d,o[f+13],5,-1444681467),d=g(d,u,h,l,o[f+2],9,-51403784),l=g(l,d,u,h,o[f+7],14,1735328473),h=g(h,l,d,u,o[f+12],20,-1926607734),u=S(u,h,l,d,o[f+5],4,-378558),d=S(d,u,h,l,o[f+8],11,-2022574463),l=S(l,d,u,h,o[f+11],16,1839030562),h=S(h,l,d,u,o[f+14],23,-35309556),u=S(u,h,l,d,o[f+1],4,-1530992060),d=S(d,u,h,l,o[f+4],11,1272893353),l=S(l,d,u,h,o[f+7],16,-155497632),h=S(h,l,d,u,o[f+10],23,-1094730640),u=S(u,h,l,d,o[f+13],4,681279174),d=S(d,u,h,l,o[f+0],11,-358537222),l=S(l,d,u,h,o[f+3],16,-722521979),h=S(h,l,d,u,o[f+6],23,76029189),u=S(u,h,l,d,o[f+9],4,-640364487),d=S(d,u,h,l,o[f+12],11,-421815835),l=S(l,d,u,h,o[f+15],16,530742520),h=S(h,l,d,u,o[f+2],23,-995338651),u=b(u,h,l,d,o[f+0],6,-198630844),d=b(d,u,h,l,o[f+7],10,1126891415),l=b(l,d,u,h,o[f+14],15,-1416354905),h=b(h,l,d,u,o[f+5],21,-57434055),u=b(u,h,l,d,o[f+12],6,1700485571),d=b(d,u,h,l,o[f+3],10,-1894986606),l=b(l,d,u,h,o[f+10],15,-1051523),h=b(h,l,d,u,o[f+1],21,-2054922799),u=b(u,h,l,d,o[f+8],6,1873313359),d=b(d,u,h,l,o[f+15],10,-30611744),l=b(l,d,u,h,o[f+6],15,-1560198380),h=b(h,l,d,u,o[f+13],21,1309151649),u=b(u,h,l,d,o[f+4],6,-145523070),d=b(d,u,h,l,o[f+11],10,-1120210379),l=b(l,d,u,h,o[f+2],15,718787259),h=b(h,l,d,u,o[f+9],21,-343485551),u=u+w>>>0,h=h+_>>>0,l=l+R>>>0,d=d+V>>>0}return i.endian([u,h,l,d])};r._ff=function(s,n,o,c,u,h,l){var d=s+(n&o|~n&c)+(u>>>0)+l;return(d<<h|d>>>32-h)+n},r._gg=function(s,n,o,c,u,h,l){var d=s+(n&c|o&~c)+(u>>>0)+l;return(d<<h|d>>>32-h)+n},r._hh=function(s,n,o,c,u,h,l){var d=s+(n^o^c)+(u>>>0)+l;return(d<<h|d>>>32-h)+n},r._ii=function(s,n,o,c,u,h,l){var d=s+(o^(n|~c))+(u>>>0)+l;return(d<<h|d>>>32-h)+n},r._blocksize=16,r._digestsize=16,Xo.exports=function(s,n){if(s==null)throw new Error("Illegal argument "+s);var o=i.wordsToBytes(r(s,n));return n&&n.asBytes?o:n&&n.asString?t.bytesToString(o):i.bytesToHex(o)}})();function ec(i){return i?i.toLowerCase().indexOf("android")>=0||i.toLowerCase().indexOf("ios")>=0?"h5":"pc":"unknown"}function tc(i){const a=nr(i),e=localStorage.getItem(a);if(e&&e.length===36)return e;const t=zo();return localStorage.setItem(a,t),t}var li,di,xt;class Ds{constructor(a){Xi(this,li,void 0),Xi(this,di,void 0),Xi(this,xt,void 0);const c=a,{commonParams:e,version:t}=c,r=ta(c,["commonParams","version"]);Yi(this,li,new $o(r)),Yi(this,xt,tc(r.project));const s=new ui;s.setUA(window.navigator.userAgent);const n=s.getResult(),o=W({av:t,os:n.os.name,ov:n.os.version,bt:n.browser.name,bv:n.browser.version,tt:ec(n.os.name),uuid:ei(this,xt),host:window.location.host},e);Yi(this,di,o)}getUUID(){return ei(this,xt)}send(a,e,t){ei(this,li).send(W(W({msgId:String(a),args:typeof e=="string"?e:new URLSearchParams(e).toString(),pu:window.location.href,ct:Date.now().toString()},ei(this,di)),t))}}li=new WeakMap,di=new WeakMap,xt=new WeakMap;class ic{constructor(a){p(this,"index",0);p(this,"tracker");p(this,"enable",!0);p(this,"commonParams",{});if(a===!1){this.enable=!1;return}if(typeof a=="object"&&a.extraParams&&typeof a.extraParams=="string")try{this.commonParams={extra:a.extraParams}}catch(e){}this.tracker=new Ds({version:Rt,host:"cn-hangzhou.log.aliyuncs.com",project:"web-rtc-grtn",logstore:"client",time:5,count:10,source:typeof a=="object"?a.biz:""})}updateAuthInfo(a){var e,t,r;this.commonParams=_t(W({},this.commonParams),{apid:(e=a==null?void 0:a.appId)!=null?e:"",usrid:(t=a==null?void 0:a.userId)!=null?t:"",channelid:(r=a==null?void 0:a.channelId)!=null?r:""})}reportJoinChannel(a){var t,r,s;const e={jnnonce:(t=a==null?void 0:a.nonce)!=null?t:"",jntoken:(r=a==null?void 0:a.token)!=null?r:"",jntm:(s=a==null?void 0:a.timestamp)!=null?s:""};this.report(70012,e)}reportJoinChannelRes(a,e,t){this.report(70013,{rslt:a,message:e,ct:t})}reportLeaveChannel(){this.report(70015)}reportPush(a,e,t,r,s,n,o,c,u,h,l,d){this.report(10030,{calid:a,isvl:e?1:0,isvs:t?1:0,isvss:r?1:0,isaudio:s?1:0,rslt:n,tid:o,pubtm:c,est:u,dctid:h,httptid:l,url:d})}reportPull(a,e,t,r,s,n,o,c,u,h,l,d){this.report(10050,{calid:a,rmtid:e,isvl:t?1:0,isvs:r?1:0,isvss:s?1:0,isaudio:n?1:0,rslt:o,tid:"",subtm:c,dctid:u,httptid:h,ajsub:1,url:l,est:d})}reportSubscribeAudioStats(a,e){const{ssrc:t,bytesReceived:r,packetsReceived:s,packetsLost:n,jitterBufferDelay:o,trackIdentifier:c,totalSamplesDuration:u,codec:h}=e,l=u,d=r/l,f=s/l,m=n/l,g=n/s;this.report(10080,{calid:"",rmtid:a,tckid:c,ssrc:t,codec:h,rbr:d,pr:f,pl:m,plr:g,jd:o})}reportSubscribeVideoStats(a,e){const{ssrc:t,bytesReceived:r,trackIdentifier:s,framesDecoded:n,framesReceived:o,frameHeight:c,frameWidth:u,nackCount:h,jitterBufferDelay:l,packetsReceived:d,packetsLost:f,totalInterFrameDelay:m,codec:g}=e,S=m,b=r/S,w=n/S,_=o/S,R=d/S,V=f/S,K=f/d;this.report(10080,{calid:"",rmtid:a,tckid:s,ssrc:t,codec:g,rbr:b,dfps:w,rfps:_,rh:c,rw:u,ns:h,jd:l,pr:R,pl:V,plr:K})}report(a,e,t){var r;this.enable&&((r=this.tracker)==null||r.send(a,e,W(W({},this.commonParams),t!=null?t:{})))}static reportCheck(a,e){new Ds({version:Rt,host:"cn-hangzhou.log.aliyuncs.com",project:"web-rtc-grtn",logstore:"client",time:5,count:10,source:e!=null?e:""}).send(100001,a)}}class rc{constructor(){p(this,"reporter");p(this,"param");p(this,"msgCacheArr",[]);p(this,"index",0)}start(a){this.initParam(a),this.reporter=new $t.LogReporter({wsUrl:"wss://logprod.aliyuncs.com/binlog",webtrackingUrl:"",wsConfig:{product:1}});let e=window.setInterval(()=>{this.msgCacheArr.length?this.realSendReport(this.msgCacheArr.shift()):(clearInterval(e),e=0)},200)}stop(){this.reporter&&(this.reporter.close(),this.reporter=void 0)}sendReport(a){A.info("[LogClient]",a),this.msgCacheArr.length===0&&this.param?this.realSendReport(a):this.msgCacheArr.push(a)}initParam(a){this.param||(this.param={osn:x.SystemUtil.systemName,osv:x.SystemUtil.systemVersion,udid:x.LocalStorage.uuid,statsvrs:"0.6.1",sdkvrs:Rt,dm:x.BrowserUtil.domain,bt:x.BrowserUtil.browserName,bv:x.BrowserUtil.browserVersion,envir:"PRODUCT",apid:a.appId,usrid:a.userId,channelid:a.channelId,evetid:0,args:""})}realSendReport(a){var t;let e={};for(let r in this.param)e[r]=this.param[r];for(let r in a)e[r]=a[r];e.idx=this.index,++this.index,(t=this.reporter)==null||t.send(e)}}class sc{constructor(){p(this,"logClient");this.logClient=new rc}start(a){this.logClient.start(a)}stop(){this.logClient.stop()}reportJoin(a,e,t){this.log({evetid:10010,args:this.data2String({joitm:a,rslt:e,mode:"wss",tid:t,gslbtm:0})})}reportJoinInvoked(a,e,t){this.log({evetid:60010,args:this.data2String({usrid:a,usrn:e,channelid:t,ua:navigator.userAgent})})}reportIceState(a,e,t){this.log({evetid:10011,args:this.data2String({calid:a,icestate:e,evt_seq:t})})}reportLeave(a,e,t){this.log({evetid:10020,args:this.data2String({lvetm:a,rslt:e,tid:t})})}reportLeaveInvoked(){this.log({evetid:60020})}reportPublish(a,e,t,r,s,n,o,c){this.log({evetid:10030,args:this.data2String({callid:a,isvl:e?1:0,isvs:t?1:0,isvss:r?1:0,isaudio:s?1:0,rslt:n,tid:o,pubtm:c})})}reportPublishInvoked(a,e,t,r){this.log({evetid:60030,args:this.data2String({isvl:typeof a=="boolean"?a?1:0:a,isvs:typeof e=="boolean"?e?1:0:e,isvss:typeof t=="boolean"?t?1:0:t,isaudio:typeof r=="boolean"?r?1:0:r})})}reportRepublish(a,e,t,r,s,n,o,c){this.log({evetid:10032,args:this.data2String({calid:a,isvl:e?1:0,isvs:0,isvss:t?1:0,isaudio:r?1:0,rslt:s,tid:n,repubtm:o,msg:c})})}reportRepublishInvoked(a,e,t){this.log({evetid:60032,args:this.data2String({callid:a,st:t,tp:e})})}reportUnpublish(a,e,t,r){this.log({evetid:10040,args:this.data2String({calid:a,unpubtm:e,rslt:t,tid:r})})}reportUnpublishInvoked(){this.log({evetid:60040})}reportSubscribe(a,e,t,r,s,n,o,c,u,h){this.log({evetid:10050,args:this.data2String({calid:a,rmtid:e,isvl:t?1:0,isvs:r?1:0,isvss:s?1:0,isaudio:n?1:0,rslt:o,tid:c,subtm:u,rmtuid:h})})}reportSubscribeInvoked(a="",e,t,r,s){this.log({evetid:60050,args:this.data2String({rmtid:a,isvl:typeof e=="boolean"?e?1:0:e,isvs:typeof t=="boolean"?t?1:0:t,isvss:typeof r=="boolean"?r?1:0:r,isaudio:typeof s=="boolean"?s?1:0:s})})}reportUnsubscribe(a,e,t,r,s){this.log({evetid:10060,args:this.data2String({calid:a,rmtid:e,unsubtm:t,rslt:r,tid:s})})}reportUnsubscribeInvoked(a=""){this.log({evetid:60060,args:this.data2String({rmtid:a})})}reportRoleUpdate(a,e,t,r){this.log({evetid:11040,args:this.data2String({or:a,nr:e,ctm:t,rslt:r})})}reportRoleUpdateInvoked(a){this.log({evetid:61040,args:this.data2String({nr:a})})}reportVideoProfile(a){this.log({evetid:20074,args:this.data2String({pf:a,tckid:"sophon_camera_large"})})}reportScreenProfile(a){this.log({evetid:20074,args:this.data2String({pf:a,tckid:"sophon_screenshare"})})}reportError(a){this.log({evetid:20090,args:this.data2String(a)})}log(a){a&&(a.tm=new Date().getTime()),this.logClient.sendReport(a)}data2String(a){let e="";for(let t in a)e.length&&(e+="&"),e+=t+"="+a[t];return e}}class xs{constructor(a){p(this,"name","COMMON");this.name=a||this.name}info(...a){}warn(...a){}print(a,...e){const t=a.toLowerCase();t&&console[t](`[${a}][${this.name}]`,...e)}}p(xs,"LEVEL",0);class ac{constructor(){p(this,"logger",new xs("AudioMixer"));p(this,"audioContext",new AudioContext);p(this,"audioDestination",this.audioContext.createMediaStreamDestination());p(this,"audioTrack",Ua(this.audioDestination.stream));p(this,"sourceNodeMap",{})}get sourceNodeList(){return Object.values(this.sourceNodeMap).map(a=>a.sourceNode).filter(a=>!!a)}get gainNodeList(){return Object.values(this.sourceNodeMap).map(a=>a.gainNode).filter(a=>!!a)}get sourceCount(){return this.sourceNodeList.length}resume(){var a;return(a=this.audioContext)==null?void 0:a.resume()}addTrack(a){this.connectTrack(a)}hasTrack(a){return!!this.sourceNodeMap[a]}removeTrack(a){const{sourceNode:e,gainNode:t}=this.sourceNodeMap[a]||{};t==null||t.disconnect(),e==null||e.disconnect(),delete this.sourceNodeMap[a],e?this.logger.info("SourceNode disconnected. Active source node:",this.sourceNodeList.length):this.logger.warn(`SourceNode ${a} does not exit. Active source node: ${this.sourceNodeList.length}`)}getAudioTrack(){return this.audioTrack}setVolume(a,e){const{gainNode:t}=this.sourceNodeMap[e]||{};t?(this.logger.info(`Setting node(${e}) volume to ${this.scale(a)}`),t.gain.value=this.scale(a)):this.logger.warn(`GainNode ${e} does not exit.`)}reset(){this.disconnectSourceNode(),this.sourceNodeMap={}}dispose(){var a;this.reset(),(a=this.audioTrack)==null||a.stop(),this.audioDestination.disconnect(),this.audioContext.close()}connectTrack(a){if(!this.audioContext)return this.logger.warn("AudioContext not initialized");let e=new MediaStream;e.addTrack(a);const t=this.audioContext.createMediaStreamSource(e),r=this.audioContext.createGain();r.gain.value=1,t.connect(r),r.connect(this.audioDestination),this.sourceNodeMap[a.id]={track:a,sourceNode:t,gainNode:r},this.logger.info("New sourceNode connected. Active source node:",this.sourceNodeList.length)}disconnectSourceNode(){this.sourceNodeList.forEach(a=>a.disconnect()),this.gainNodeList.forEach(a=>a.disconnect())}scale(a){return a/100}}const nc=4;class oc extends mt{constructor(){super("audioMixer",ae.AliRtcSdkStreamTypeCapture,Jt.AUDIO);p(this,"audioMixer");p(this,"primaryAudioTrackId");p(this,"screenAudioTrackId");p(this,"dirty",!1);this.zIndex=8}get initOptions(){return{audio:1,screen:1}}setOptions(e){Object.entries(e).forEach(([t,r])=>{this.isValidVolume(r)&&(this.options[t]=r)}),this.dirty=!0,this.emit("updated")}isSupported(){return"AudioContext"in window}shouldUpdate(e,t){var n,o;if(e.type!==ae.AliRtcSdkStreamTypeCapture)return!1;const r=t.find(c=>c.type===ae.AliRtcSdkStreamTypeCapture),s=t.find(c=>c.type===ae.AliRtcSdkStreamTypeScreen);return!(this.primaryAudioTrackId===((n=r==null?void 0:r.currentAudioTrack)==null?void 0:n.id)&&this.screenAudioTrackId===((o=s==null?void 0:s.currentAudioTrack)==null?void 0:o.id)&&!this.dirty)}process(e,t){return v(this,null,function*(){var o,c;this.dirty=!1;const r=t.find(u=>u.type===ae.AliRtcSdkStreamTypeScreen),s=e.currentAudioTrack,n=r==null?void 0:r.currentAudioTrack;if(!n&&this.options.audio===1){this.audioMixer&&(this.audioMixer.dispose(),this.audioMixer=void 0),this.primaryAudioTrackId=s==null?void 0:s.id,e.updateAudioTrack(s);return}this.audioMixer||(this.audioMixer=new ac),yield this.audioMixer.resume(),this.primaryAudioTrackId&&(s==null?void 0:s.id)!==this.primaryAudioTrackId&&((o=this.audioMixer)==null||o.removeTrack(this.primaryAudioTrackId)),s&&!this.audioMixer.hasTrack(s==null?void 0:s.id)&&this.audioMixer.addTrack(s),this.primaryAudioTrackId=s==null?void 0:s.id,this.screenAudioTrackId&&(n==null?void 0:n.id)!==this.screenAudioTrackId&&((c=this.audioMixer)==null||c.removeTrack(this.screenAudioTrackId)),n&&!this.audioMixer.hasTrack(n==null?void 0:n.id)&&this.audioMixer.addTrack(n),this.screenAudioTrackId=n==null?void 0:n.id,this.updateVolume(),e.updateAudioTrack(this.audioMixer.getAudioTrack())})}isValidVolume(e){return e!==void 0&&e>=0&&e<=nc}updateVolume(){this.audioMixer&&(this.primaryAudioTrackId&&this.audioMixer.setVolume(this.options.audio*100,this.primaryAudioTrackId),this.screenAudioTrackId&&this.audioMixer.setVolume(this.options.screen*100,this.screenAudioTrackId))}clear(e){var t;(t=this.audioMixer)==null||t.dispose(),super.clear(e)}}class ur{constructor(a,e){p(this,"originTrack");p(this,"originVideo");p(this,"targetWidth");p(this,"targetHeight");p(this,"targetFrameRate");p(this,"targetCanvas");p(this,"animationFrameId");p(this,"resultTrack");this.targetWidth=e.width,this.targetHeight=e.height,this.targetFrameRate=e.frameRate,this.originTrack=a,this.originVideo=document.createElement("video"),this.originVideo.muted=!0,this.originVideo.autoplay=!0,this.originVideo.controls=!1,this.targetCanvas=document.createElement("canvas"),this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight}updateOptions(a){this.targetWidth=a.width,this.targetHeight=a.height,this.targetFrameRate=a.frameRate,this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight,this.resultTrack&&this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})}dispose(){}getVideoTrack(){return this.resultTrack||(this.resultTrack=this.targetCanvas.captureStream().getVideoTracks()[0],this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})),this.resultTrack}cancelAnimation(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}getPositionAndSize(a,e,t,r){const s=e/a,n=r/t;let o=t,c=r,u=0,h=0;return n>s?(o=Math.round(c/s),u=Math.round((t-o)/2)):n<s&&(c=Math.round(o*s),h=Math.round((r-c)/2)),{x:u,y:h,width:o,height:c}}}class cc extends ur{constructor(e,t){super(e,t);p(this,"targetCtx");this.targetCtx=this.targetCanvas.getContext("2d"),this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.initStream(e)}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender)}startRender(){this.cancelAnimation();const e=()=>{if(!this.targetCtx)return;const t=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight);this.targetCtx.drawImage(this.originVideo,0,0,this.originVideo.videoWidth,this.originVideo.videoHeight,t.x,t.y,t.width,t.height),!this.originVideo.paused&&!this.originVideo.ended&&(this.animationFrameId=requestAnimationFrame(e))};e()}stopRender(){this.cancelAnimation()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.pause(),this.originVideo.srcObject=null}}const uc=`
|
|
15
15
|
attribute vec2 a_position;
|
|
16
16
|
attribute vec2 a_texCoord;
|
|
17
17
|
|
|
@@ -32,7 +32,7 @@ void main() {
|
|
|
32
32
|
|
|
33
33
|
v_texCoord = a_texCoord;
|
|
34
34
|
}
|
|
35
|
-
`,
|
|
35
|
+
`,hc=`
|
|
36
36
|
precision mediump float;
|
|
37
37
|
|
|
38
38
|
varying lowp vec2 v_texCoord;
|
|
@@ -41,7 +41,7 @@ uniform sampler2D u_texture;
|
|
|
41
41
|
void main() {
|
|
42
42
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
43
43
|
}
|
|
44
|
-
`;function
|
|
44
|
+
`;function lc(){let i;try{const a=document.createElement("canvas");a.width=1,a.height=1;const e={alpha:!1,depth:!1,stencil:!1,antialias:!1,preferLowPowerToHighPerformance:!0};i=a.getContext("webgl2",e)}catch(a){return!1}return!!i}function dc(i){const a=i.createTexture();return i.bindTexture(i.TEXTURE_2D,a),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),a}function Us(i,a,e){const t=i.createShader(a);if(!t){console.error("create shader failed");return}return i.shaderSource(t,e),i.compileShader(t),i.getShaderParameter(t,i.COMPILE_STATUS)?t:(console.error(`An error occurred compiling the shaders: ${i.getShaderInfoLog(t)}`),i.deleteShader(t),null)}function pc(i,a,e){const t=Us(i,i.VERTEX_SHADER,a),r=Us(i,i.FRAGMENT_SHADER,e),s=i.createProgram();if(!(!s||!t||!r))return i.attachShader(s,t),i.attachShader(s,r),i.linkProgram(s),i.getProgramParameter(s,i.LINK_STATUS)?s:(console.error(`Unable to initialize the shader program: ${i.getProgramInfoLog(s)}`),null)}function gc(i,a,e,t=0,r=0){const s=i.createBuffer();i.bindBuffer(i.ARRAY_BUFFER,s);const n=t,o=r,c=a+t,u=e+r,h=[n,o,c,o,n,u,n,u,c,o,c,u];return i.bufferData(i.ARRAY_BUFFER,new Float32Array(h),i.STATIC_DRAW),s}class Bs extends ur{constructor(e,t){super(e,t);p(this,"targetCtx");p(this,"targetTexture");p(this,"locationMap");this.targetCtx=this.targetCanvas.getContext("webgl2"),this.locationMap={},this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.updateBuffer=this.updateBuffer.bind(this),this.initGL(),this.initStream(e)}static isSupport(){return lc()}initGL(){const e=this.targetCtx;if(!e)return;this.targetTexture=dc(e);const t=pc(e,uc,hc);if(!t){console.log("[ScalerWebGL] program is null.");return}e.useProgram(t);const r=e.getAttribLocation(t,"a_position"),s=e.getAttribLocation(t,"a_texCoord"),n=e.getUniformLocation(t,"u_resolution");if(!n){console.log("[ScalerWebGL] resolutionLocation is null.");return}const o=e.getUniformLocation(t,"u_texture");if(!o){console.log("[ScalerWebGL] textureLocation is null.");return}this.locationMap={program:t,positionLocation:r,texCoordLocation:s,resolutionLocation:n,textureLocation:o},this.updateBuffer()}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender),this.originVideo.addEventListener("resize",this.updateBuffer)}startRender(){this.cancelAnimation();const e=()=>{this.targetCtx&&(this.renderTexture(),!this.originVideo.paused&&!this.originVideo.ended&&(this.animationFrameId=requestAnimationFrame(e)))};e()}updateBuffer(){const e=this.targetCtx,t=this.locationMap.positionLocation,r=this.locationMap.texCoordLocation,s=this.locationMap.resolutionLocation;if(!e||!this.originVideo.videoWidth||!this.originVideo.videoHeight)return;const n=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight),o=gc(e,n.width,n.height,n.x,n.y);e.enableVertexAttribArray(t),e.bindBuffer(e.ARRAY_BUFFER,o),e.vertexAttribPointer(t,2,e.FLOAT,!1,0,0),e.enableVertexAttribArray(r);const c=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,c),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,c),e.vertexAttribPointer(r,2,e.FLOAT,!1,0,0),e.uniform2f(s,this.targetWidth,this.targetHeight)}renderTexture(){const e=this.targetTexture,t=this.targetCtx,r=this.locationMap.textureLocation;!e||!t||(t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.originVideo),t.useProgram(this.locationMap.program),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e),t.uniform1i(r,0),t.viewport(0,0,t.canvas.width,t.canvas.height),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.drawArrays(t.TRIANGLES,0,6))}stopRender(){this.cancelAnimation()}updateOptions(e){super.updateOptions(e),this.updateBuffer()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.removeEventListener("resize",this.updateBuffer),this.originVideo.pause(),this.originVideo.srcObject=null}}const fc=`
|
|
45
45
|
var targetOptions={
|
|
46
46
|
width: 320,
|
|
47
47
|
height: 180,
|
|
@@ -126,4 +126,4 @@ onmessage = function(evt) {
|
|
|
126
126
|
break;
|
|
127
127
|
}
|
|
128
128
|
}
|
|
129
|
-
`;class ea extends yr{constructor(e,i){super(e,i);l(this,"processor");l(this,"trackGenerator");l(this,"worker");this.processor=new MediaStreamTrackProcessor({track:e}),this.trackGenerator=new MediaStreamTrackGenerator({kind:"video"}),this.startTransform()}static isSupport(){return"MediaStreamTrackProcessor"in window&&"MediaStreamTrackGenerator"in window&&"TransformStream"in window&&"VideoFrame"in window}startTransform(){const e=new Blob([Fc],{type:"text/javascript"}),s=(window.URL||window.webkitURL).createObjectURL(e);this.worker=new Worker(s);const{readable:a}=this.processor,{writable:n}=this.trackGenerator;this.worker.postMessage({type:"startRender",readable:a,writable:n,width:this.targetWidth,height:this.targetHeight,frameRate:this.targetFrameRate},[a,n])}updateOptions(e){super.updateOptions(e),this.worker&&this.worker.postMessage(q({type:"updateOptions"},e))}dispose(){try{this.processor.readable.cancel(),this.trackGenerator.writable.close()}catch(e){}}getVideoTrack(){return this.trackGenerator}}class wr{static isSupport(){return typeof HTMLCanvasElement.prototype.captureStream=="function"}static getInstance(r,e){return ea.isSupport()?new ea(r,e):Zs.isSupport()?new Zs(r,e):new Oc(r,e)}}class jc extends Tt{constructor(){super(...arguments);l(this,"hasVideoTrack",!1);l(this,"videoScaler")}get initOptions(){return{width:320,height:180,frameRate:15}}setOptions(e){var i;this.options=e,(i=this.videoScaler)==null||i.updateOptions(e)}isSupported(){return wr.isSupport()}shouldUpdate(e){return this.hasVideoTrack!==!!e.currentVideoTrack}process(e){return v(this,null,function*(){if(e.currentVideoTrack){if(this.hasVideoTrack=!0,!this.videoScaler){const s=this.options||this.initOptions;this.videoScaler=wr.getInstance(e.currentVideoTrack,s)}const i=this.videoScaler.getVideoTrack();i&&e.updateDualVideoTrack(i)}else e.updateDualVideoTrack(),this.emit("updated"),this.videoScaler&&this.videoScaler.dispose()})}clear(e){super.clear(e),e==null||e.updateDualVideoTrack()}}class _r{static checkString(r){return typeof r=="string"}static checkNumber(r){return typeof r=="number"}static checkHtmlVideoElement(r){return r&&r.nodeName==="VIDEO"}static checkHtmlAudioElement(r){return r&&r.nodeName==="AUDIO"}static checkAuthInfo(r){let e=new C(N.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no authInfo");if(r){if(!r.appId)return e.message="no appId founded",e;if(!r.channelId)return e.message="no channelId founded",e;if(r.timestamp){if(!_r.checkNumber(r.timestamp))return e.message="timestamp should be number",e}else return e.message="no timestamp founded",e;return r.token?r.userId?r.role!==void 0&&!["pub","sub","relay"].includes(r.role)?(e.message="role invalid",e):null:(e.message="no userId founded",e):(e.message="no token founded",e)}else return e}static checkMediaStreamTrack(r){return r instanceof MediaStreamTrack}static checkVideoEncoderConfiguration(r){return r&&(r.width||r.height||r.frameRate||r.bitrateMax)}}class ta{constructor(r){l(this,"taskProfile");l(this,"encodeParam");l(this,"users",[]);l(this,"backgroundColor",0);l(this,"backgrounds",[]);l(this,"watermarks",[]);l(this,"clockWidgets",[]);l(this,"cropMode");l(this,"mediaProcessMode");this.taskProfile=r}}class ia{constructor(r,e,i){l(this,"userId");l(this,"streamType");l(this,"sourceType");this.userId=r,this.streamType=e,this.sourceType=i}}class ra{constructor(r,e,i,s=0,a=16777215,n=Ht.NOTO_SERIF_CJKSC_REGULAR){l(this,"x");l(this,"y");l(this,"fontSize");l(this,"zOrder");l(this,"fontColor");l(this,"fontType");this.x=r,this.y=e,this.fontSize=i,this.zOrder=s,this.fontColor=a,this.fontType=n}toJson(r,e){return{x:Le(this.x,r),y:Le(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:Qi(this.fontColor),zorder:this.zOrder}}}var sa=(t=>(t[t.NOT_DISPLAY=0]="NOT_DISPLAY",t[t.ALWAYS=1]="ALWAYS",t[t.WHEN_NO_VIDEO=2]="WHEN_NO_VIDEO",t))(sa||{});class Rr{constructor(r,e,i,s,a,n=0,o=1,c=1){l(this,"url");l(this,"x");l(this,"y");l(this,"width");l(this,"height");l(this,"alpha");l(this,"display",1);l(this,"zOrder");this.url=r,this.x=e,this.y=i,this.width=s,this.height=a,this.zOrder=n,this.alpha=o,this.display=c}toJson(r,e){return{url:this.url,alpha:this.alpha,display:this.display,x:Le(this.x,r),y:Le(this.y,e),width:Le(this.width,r),height:Le(this.height,e),zorder:this.zOrder}}}l(Rr,"DisplayType",sa);class aa{constructor(r,e,i,s,a=0,n=16777215,o=Ht.NOTO_SERIF_CJKSC_REGULAR){l(this,"text");l(this,"x");l(this,"y");l(this,"fontSize");l(this,"zOrder");l(this,"fontColor");l(this,"fontType");this.text=r,this.x=e,this.y=i,this.fontSize=s,this.zOrder=a,this.fontColor=n,this.fontType=o}toJson(r,e){return{text:this.text,x:Le(this.x,r),y:Le(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:Qi(this.fontColor),zorder:this.zOrder}}}class na{constructor(r,e,i,s,a,n=0,o){l(this,"userId");l(this,"x");l(this,"y");l(this,"width");l(this,"height");l(this,"zOrder");l(this,"sourceType");l(this,"segmentType",Bt.LiveTranscodingNoBody);l(this,"images",[]);l(this,"texts",[]);typeof r=="number"?this.userId=r.toString():this.userId=r,this.x=e,this.y=i,this.width=s,this.height=a,this.zOrder=n,o&&(this.sourceType=o)}toJson(r,e,i,s){const a={paneid:r,majorpane:0,x:Le(this.x,e),y:Le(this.y,i),width:Le(this.width,e),height:Le(this.height,i),zorder:this.zOrder,userid:this.userId,images:this.images.map(n=>n.toJson(e,i)),texts:this.texts.map(n=>n.toJson(e,i))};return this.sourceType&&Ut[this.sourceType]?a.sourcetype=Ut[this.sourceType]:a.sourcetype=Ut[Pt.LiveTranscodingCamera],this.segmentType&&s===ci.LiveTranscodingVirtualBackground?a.segmenttype=this.segmentType:a.segmenttype=Bt.LiveTranscodingNoBody,a}}class $c extends Tt{constructor(){super("AliRtcScreenStandardize",ce.AliRtcSdkStreamTypeScreen);l(this,"canvas");l(this,"lastWidth");l(this,"lastHeight");l(this,"hasScreenTrack",!1)}get initOptions(){return{base:4}}setOptions(e){this.options=e}isSupported(){return!(typeof TransformStream=="undefined"||typeof MediaStreamTrackProcessor=="undefined"||typeof MediaStreamTrackGenerator=="undefined")}updateProcessCanvas(e,i){if(this.canvas&&this.lastWidth===e&&this.lastHeight===i)return;const s=Math.ceil(e/this.options.base)*this.options.base,a=Math.ceil(i/this.options.base)*this.options.base;if(this.canvas||(this.canvas=document.createElement("canvas")),this.canvas.width=s,this.canvas.height=a,this.lastWidth&&e>this.lastWidth||this.lastHeight&&i>this.lastHeight){const n=this.canvas.getContext("2d");n&&n.clearRect(0,0,s,a)}this.lastWidth=e,this.lastHeight=i}shouldUpdate(e){return this.hasScreenTrack!==(!!e.originVideoTrack&&e.videoSource===At.Screen)}handleFrame(e,i){return v(this,null,function*(){var o;const{displayWidth:s,displayHeight:a}=e;if(!s||!a||s%this.options.base===0&&a%this.options.base===0)return this.clear(i),e;this.updateProcessCanvas(s,a);const n=(o=this.canvas)==null?void 0:o.getContext("2d");if(this.canvas&&n){n.drawImage(e,0,0,s,a);const c=new VideoFrame(this.canvas,{timestamp:e.timestamp});return e.close(),c}return e})}process(e){return v(this,null,function*(){var f;if(!e.originVideoTrack||e.videoSource!==At.Screen){this.clear(e),this.hasScreenTrack=!1;return}const i=new MediaStreamTrackProcessor({track:e.originVideoTrack}),s=new MediaStreamTrackGenerator({kind:"video"}),a=new MediaStream([s]),n=this,o=new TransformStream({transform(p,u){return v(this,null,function*(){const g=yield n.handleFrame(p,e);yield u.enqueue(g),g==null||g.close()})}});i.readable.pipeThrough(o).pipeTo(s.writable);const c=(f=a.getVideoTracks())==null?void 0:f[0];e.updateVideoTrack(c),this.hasScreenTrack=!0})}clear(e){this.canvas=void 0,this.lastWidth=void 0,this.lastHeight=void 0,super.clear(e)}}var Wc=Object.defineProperty,Kc=Object.getOwnPropertyDescriptor,P=(t,r,e,i)=>{for(var s=i>1?void 0:i?Kc(r,e):r,a=t.length-1,n;a>=0;a--)(n=t[a])&&(s=(i?n(r,e,s):n(s))||s);return i&&s&&Wc(r,e,s),s};const T=(L=class extends Q{constructor(e){super();l(this,"channelProfile");l(this,"clientRole");l(this,"signalingManager");l(this,"userManager");l(this,"liveTranscoding");l(this,"maxSignalingConnectRetryCount");l(this,"reporter");l(this,"webTrackingClient");l(this,"connectState",G.AliRtcConnectionStatusInit);l(this,"networkError",!1);l(this,"audioMixerPlugin");l(this,"dualVideoPlugin");l(this,"_audioOnlyMode",!1);l(this,"_authInfoWillExpireTimer",null);l(this,"_authInfoExpiredTimer",null);l(this,"_serverCheckAuthInfoTimestamp",null);l(this,"_localCheckAuthInfoTimestamp",null);this.webTrackingClient=new Pc(e==null?void 0:e.webTrack),this.reporter=new Cc,this.channelProfile=Qe.AliRtcSdkCommunication,this.clientRole=st.AliRtcSdkLive,this.liveTranscoding=new On,this.signalingManager=new on(this.channelProfile,this.clientRole,(e==null?void 0:e.env)===rt.pre?rt.pre:rt.prod),this.addSignalingManagerListeners(),this.maxSignalingConnectRetryCount=e==null?void 0:e.maxSignalingConnectRetryCount,this.userManager=new ke({reporter:this.reporter,webTrackingClient:this.webTrackingClient,signalingManager:this.signalingManager}),this.addUserManagerListeners(),this.addPublisherListeners(),this.audioMixerPlugin=new Lc,this.enablePlugin(this.audioMixerPlugin),this.dualVideoPlugin=new jc("dualVideoPlugin"),this.enablePlugin(new $c)}static getSdkVersion(){return Dt}static setLogLevel(e){E.setLogLevel(e)}static getInstance(e){return L._instance||(L._instance=new L(e)),L._instance}destroy(){L._instance=void 0}get channel(){return this.userManager.channel}get userId(){return this.userManager.userId}get remoteUsers(){return this.userManager.remoteUsers}get publisher(){return this.userManager.publisher}get publishAudioStream(){var e;return(e=this.publisher)==null?void 0:e.publishStreams.audio}get isPublishing(){const{publisher:e}=this.userManager;return e?e.isPublishing:!1}get currentRoleCanPublish(){return this.channelProfile===Qe.AliRtcSdkCommunication||this.clientRole===st.AliRtcSdkInteractive}resetState(){return v(this,null,function*(){yield this.userManager.clear(),this.connectState=G.AliRtcConnectionStatusDisconnected,this.networkError=!1,this.signalingManager.reset(),this.liveTranscoding.clear(),this.reporter.stop(),yield this.publishLocalAudioStream(!0),yield this.publishLocalVideoStream(!0),yield this.publishLocalScreenShareStream(!0)})}stopPublish(e){return v(this,null,function*(){var i,s,a;e?yield(i=this.publisher)==null?void 0:i.stopLocalStream(e):(yield(s=this.publisher)==null?void 0:s.publishStop(),(a=this.publisher)==null||a.stopPreview())})}addPublisherListeners(){var e,i,s,a,n,o,c,h,f;(e=this.publisher)==null||e.on(we.Local,p=>{E.event("[Publisher] Device Status Change",p),this.onLocalDeviceStatusChange(p)}),(i=this.publisher)==null||i.on(bt.VideoTrackEnded,()=>{E.event("[Publisher] VideoTrack Ended"),this.emit("localDeviceException",Ke.AliEngineLocalDeviceTypeCamera,re.AliEngineLocalDeviceExceptionTypeCameraInterrupt,"")}),(s=this.publisher)==null||s.on(bt.ScreenTrackEnded,()=>{E.event("[Publisher] ScreenTrack Ended"),this.emit("localDeviceException",Ke.AliEngineLocalDeviceTypeDisplay,re.AliEngineLocalDeviceExceptionTypeDisplayException,"")}),(a=this.publisher)==null||a.on(bt.AudioTrackEnded,()=>{E.event("[Publisher] AudioTrack Ended"),this.emit("localDeviceException",Ke.AliEngineLocalDeviceTypeMic,re.AliEngineLocalDeviceExceptionTypeMicInterrupt,"")}),(n=this.publisher)==null||n.on("localDeviceException",(p,u,g="")=>{this.emit("localDeviceException",p,u,g)}),(o=this.publisher)==null||o.on("audioPublishStateChanged",(p,u,g)=>{var m;this.emit("audioPublishStateChanged",p,u,g,(m=this.channel)!=null?m:"")}),(c=this.publisher)==null||c.on("videoPublishStateChanged",(p,u,g)=>{var m;this.emit("videoPublishStateChanged",p,u,g,(m=this.channel)!=null?m:"")}),(h=this.publisher)==null||h.on("dualStreamPublishStateChanged",(p,u,g)=>{var m;this.emit("dualStreamPublishStateChanged",p,u,g,(m=this.channel)!=null?m:"")}),(f=this.publisher)==null||f.on("screenPublishStateChanged",(p,u,g)=>{var m;this.emit("screenSharePublishStateChanged",p,u,g,(m=this.channel)!=null?m:"")})}addUserManagerListeners(){this.userManager.rtsManager.on("disconnected",()=>v(this,null,function*(){E.event("[UserManager] RTS Disconnected"),(yield it.isNetworkAvailable())?this.onNetworkRecovery():this.onNetworkError()})),this.userManager.rtsManager.on("subscribeexceeds",()=>v(this,null,function*(){yield this.resumePublishForNetworkRecovery(),yield this.resumeSubList()})),this.userManager.rtsManager.on("seimessage",(e,i,s)=>{const a=this.remoteUsers.find(n=>n.streamUrl===e);a&&this.emit("mediaExtensionMsgReceived",a.userId,s,i)}),this.userManager.on(we.Remote,(e,i)=>{E.event("[UserManager] RemoteUser Device Status Change",e,i)}),this.userManager.on("remoteTrackAvailableChange",(e,i,s)=>{this.emit("remoteTrackAvailableNotify",e,i,s)}),this.userManager.on("audioSubscribeStateChanged",(e,i,s,a,n)=>{this.emit("audioSubscribeStateChanged",e,i,s,a,n)}),this.userManager.on("videoSubscribeStateChanged",(e,i,s,a,n)=>{this.emit("videoSubscribeStateChanged",e,i,s,a,n)}),this.userManager.on("screenSubscribeStateChanged",(e,i,s,a,n)=>{this.emit("screenShareSubscribeStateChanged",e,i,s,a,n)}),this.userManager.on("userAudioMuted",(e,i)=>{this.emit("userAudioMuted",e,i)}),this.userManager.on("userVideoMuted",(e,i)=>{this.emit("userVideoMuted",e,i)}),this.userManager.on("userScreenMuted",(e,i)=>{this.emit("userScreenMuted",e,i)}),this.userManager.on("audioVolume",e=>{this.emit("audioVolume",e)}),this.userManager.on("remoteAudioAutoPlayFail",e=>{this.emit("remoteAudioAutoPlayFail",e)}),this.userManager.on("remoteVideoAutoPlayFail",(e,i)=>{this.emit("remoteVideoAutoPlayFail",e,i)}),this.userManager.on("rtcLocalAudioStats",e=>{this.emit("rtcLocalAudioStats",e)}),this.userManager.on("rtcLocalVideoStats",e=>{this.emit("rtcLocalVideoStats",e)}),this.userManager.on("rtcRemoteAudioStats",e=>{this.emit("rtcRemoteAudioStats",e)}),this.userManager.on("rtcRemoteVideoStats",e=>{this.emit("rtcRemoteVideoStats",e)}),this.userManager.on("remoteSubscribeError",e=>{this.emit("onOccurError",e)})}addSignalingManagerListeners(){this.signalingManager.on("onKeepAliveRsp",()=>{this.networkError&&(E.event("[Signaling] Receive KeepAlive Response",`networkError: ${this.networkError}`),this.onNetworkRecovery())}),this.signalingManager.on("onNotifyJoin",e=>{E.event("[Signaling] Notify Join ",e),this.handleUsersJoin(e),e.forEach(i=>{this.emit("remoteUserOnLineNotify",i.userid,0)})}),this.signalingManager.on("onNotifyStatus",e=>{E.event("[Signaling] Notify Status ",e),e.forEach(i=>{this.userManager.updateRemoteUserDeviceStatus(i)})}),this.signalingManager.on("onNotifyLeave",e=>{E.event("[Signaling] Notify Leave ",e),e.forEach(i=>{this.emit("remoteUserOffLineNotify",i.userid,i.leavecode),this.userManager.removeLeftUser(i)})}),this.signalingManager.on("onBye",(e,i)=>{E.event("[Signaling] Bye ",e,i),this.reporter.reportError({message:`reason: ${e}, description: ${i}`}),this.emit("bye",e),this.leaveChannel(!0)}),this.signalingManager.on("onConnectFail",e=>{E.event("[Signaling] Connect Failed ",e),this.onError(e),this.backToUnpublishStatus(),this.connectState=G.AliRtcConnectionStatusFailed,this.emit("connectionStatusChange",G.AliRtcConnectionStatusFailed,mt.AliRtcConnectionChangedNetworkInterrupted)}),this.signalingManager.on("onNetworkError",e=>{E.event("[Signaling] Network error ",e),this.onNetworkError()}),this.signalingManager.on("onAuthInvalid",()=>{E.event("[Signaling] Auth Invalid")}),this.signalingManager.on("onReconnectStart",()=>{E.event("[Signaling] Reconnect Start "),this.connectState=G.AliRtcConnectionStatusReconnecting,this.emit("connectionStatusChange",G.AliRtcConnectionStatusReconnecting,mt.AliRtcConnectionSignalingConnecting)}),this.signalingManager.on("onReconnectSuccess",e=>{E.event("[Signaling] Reconnect Success ",e),this.onNetworkRecovery(e)}),this.signalingManager.on("onReconnectFail",e=>{E.event("[Signaling] Reconnect Failed ",e),e.code===403&&this.emit("authInfoExpired")}),this.signalingManager.on("onError",e=>{E.event("[Signaling] Error ",e),this.onError(e)})}backToUnpublishStatus(){var e,i;this.connectState=G.AliRtcConnectionStatusDisconnected,(e=this.publisher)!=null&&e.isPublishing&&((i=this.publisher)==null||i.clearPublishState()),this.networkError=!1}handleUsersJoin(e){e.forEach(i=>{const s=i.userid;if(s){const a=this.userManager.addUser(s,i.displayname);E.event(`[${L.logName}]`,J.UserJoined,a)}})}onLocalDeviceStatusChange(e){E.event(`[${L.logName}]`,we.Local,e),this.signalingManager.reportStatus(e).then(()=>{E.debug("[signaling] reportStatus suc")}).catch(i=>{E.error("[signaling] reportStatus failed",i)})}resumePublishForNetworkRecovery(){return v(this,null,function*(){var e;try{yield(e=this.publisher)==null?void 0:e.resumePublish()}catch(i){const{code:s}=i;if(s===10205){let n=1;try{yield new Promise((o,c)=>{const h=setInterval(()=>v(this,null,function*(){var f;n>1&&(clearInterval(h),c()),n+=1;try{yield(f=this.publisher)==null?void 0:f.resumePublish(),clearInterval(h),o()}catch(p){const{code:u}=p;u!==10205&&(clearInterval(h),c())}}),1e3)})}catch(o){}}}})}onNetworkRecovery(e){return v(this,null,function*(){var i;E.event(L.logName,"onNetworkRecovery",{users:e}),this.networkError&&(this.networkError=!1,(i=this.publisher)==null||i.reportSelfDeviceStatus(),!this.userManager.rtsManager.isConnected&&this.userManager.rtsManager.isConnecting&&(yield this.resumePublishForNetworkRecovery(),yield this.resumeSubList(e)),this.connectState=G.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",G.AliRtcConnectionStatusConnected,mt.AliRtcConnectionSignalingHeartbeatAlive))})}resumeSubList(e){return v(this,null,function*(){if(e!=null&&e.length){const{joinList:i,leaveList:s,presentList:a}=this.userManager.updateUsers(e);E.info(`[${L.logName}]`,"resumeSubList",{joinList:i,leaveList:s,presentList:a}),this.handleUsersJoin(i),s.forEach(n=>{E.event(L.logName,J.UserLeft,n.userid,n.reason),this.emit("remoteUserOffLineNotify",n.userid,Zi.AliRtcUserOfflineQuit)});for(let n=0;n<a.length;n++){const o=a[n],c=o.userid,h=this.userManager.getRemoteUser(c);this.userManager.onRemotePublishStateChange(o),h==null||h.restore(),h==null||h.updateSubscribe()}}else for(let i=0;i<this.remoteUsers.length;i++){const s=this.remoteUsers[i];try{s.restore(),s.updateSubscribe()}catch(a){}}})}onNetworkError(){this.connectState===G.AliRtcConnectionStatusConnected&&(this.networkError||(this.connectState=G.AliRtcConnectionStatusDisconnected,this.emit("connectionStatusChange",G.AliRtcConnectionStatusDisconnected,mt.AliRtcConnectionChangedNetworkInterrupted)),this.networkError=!0)}onError(e){this.reporter.reportError(e),E.event(L.logName,J.Error,e)}setEnableDualVideoStream(e,i){i&&this.dualVideoPlugin.setOptions(i);const s=this.userManager.pluginManager.has(this.dualVideoPlugin.name);e?!s&&this.enablePlugin(this.dualVideoPlugin):s&&this.removePlugin(this.dualVideoPlugin.name)}hadPushStream(e){if(!(this.publisher&&e))throw new C(N.ERR_INNER,"stream is not publishing")}getCurrentMicDeviceId(){var e;return(e=this.publisher)==null?void 0:e.getCurrentMicDeviceId()}setChannelProfile(e){if(![G.AliRtcConnectionStatusInit,G.AliRtcConnectionStatusDisconnected,G.AliRtcConnectionStatusFailed].includes(this.connectState))throw new C(N.ERR_INNER,"cannot set channel profile in call");this.channelProfile=e,this.channelProfile===Qe.AliRtcSdkCommunication&&(this.clientRole=st.AliRtcSdkLive),this.signalingManager.setChannelProfile(e)}setClientRole(e){return v(this,null,function*(){var i,s,a,n,o;try{if(this.channelProfile===Qe.AliRtcSdkCommunication)return;if(!Object.values(st).includes(e))throw new C(N.ERR_INVALID_ARGUMENTS,`set client role error, role value(${e}) is invalid`);if(this.clientRole===e)return;this.isInCall()?this.clientRole===st.AliRtcSdkInteractive?(this.userManager.isSubscribing?(yield this.stopPublish(),yield(i=this.publisher)==null?void 0:i.clearStream()):yield(s=this.publisher)==null?void 0:s.unPublish(),yield this.signalingManager.setClientRole(e)):(yield this.signalingManager.setClientRole(e),yield this.startDefaultDevicesCapture(),(a=this.publisher)!=null&&a.isPublishing||(yield(n=this.publisher)==null?void 0:n.startPublish()),yield(o=this.publisher)==null?void 0:o.previewAll()):yield this.signalingManager.setClientRole(e),this.clientRole=e}catch(c){throw c.code===403&&this.emit("authInfoExpired"),c}})}getCurrentClientRole(){return this.clientRole}setAudioOnlyMode(e){if(this.isInCall())throw new C(N.ERR_INNER,"cannot not change audioOnly mode in call");this._audioOnlyMode=e}setAudioRedEnabled(e){if(this.isInCall())throw new C(N.ERR_INNER,"cannot not change audioRedEnabled in call");this.userManager.setAudioRedEnabled(e)}setCheckAuthInfoTimer(e,i){const s=(e-i)*1e3;this._authInfoExpiredTimer=window.setTimeout(()=>{this.emit("authInfoExpired")},s),this._authInfoWillExpireTimer=window.setTimeout(()=>{this.emit("authInfoWillExpire")},s-3e4),this._serverCheckAuthInfoTimestamp=i,this._localCheckAuthInfoTimestamp=+Date.now()/1e3}clearCheckAuthInfoTimer(){this._authInfoExpiredTimer&&window.clearTimeout(this._authInfoExpiredTimer),this._authInfoWillExpireTimer&&window.clearTimeout(this._authInfoWillExpireTimer)}startDefaultDevicesCapture(){return v(this,null,function*(){var s,a;let e=[],i;try{this._audioOnlyMode||(e=yield L.getCameraList(),e.length||console.warn("No media neither devices can be captured")),i=yield L.getMicrophoneList(),i.length||console.warn("No media neither devices can be captured");const{hasCamera:n,hasMicrophone:o,hasScreenShare:c,audioCaptureDisabled:h,publishLocalAudioStreamEnabled:f,publishLocalVideoStreamEnabled:p}=(s=this.publisher)!=null?s:{};if(n||o||c)return;!n&&p&&!this._audioOnlyMode&&e.length&&!((a=this.publisher)!=null&&a.cameraCaptureDisabled)&&(yield this.enableLocalVideo(!0)),!o&&f&&!h&&i.length&&(yield this.startAudioCapture())}catch(n){throw n}})}joinChannel(e,i){return v(this,null,function*(){var n,o,c,h,f,p;let s=new Date().getTime(),a=_r.checkAuthInfo(e);if(this.webTrackingClient.updateAuthInfo(e),this.webTrackingClient.reportJoinChannel(e),G.AliRtcConnectionStatusInit===this.connectState||G.AliRtcConnectionStatusDisconnected===this.connectState||G.AliRtcConnectionStatusFailed===this.connectState){if(this.connectState=G.AliRtcConnectionStatusConnecting,a)throw this.connectState=G.AliRtcConnectionStatusFailed,this.webTrackingClient.reportJoinChannelRes(a.code,a.message,0),this.reporter.reportJoin(0,a.code,a.message),a;e.callid=it.createCallid(),this.reporter.start(e);try{const u=yield this.signalingManager.join(e,i,this.maxSignalingConnectRetryCount);this.connectState=G.AliRtcConnectionStatusConnected,(n=this.publisher)==null||n.reportSelfDeviceStatus();let g=new Date().getTime()-s;this.webTrackingClient.reportJoinChannelRes(0,"",g),this.reporter.reportJoin(g,0,u.tid),this.userManager.init(e,u),this.setCheckAuthInfoTimer(e.timestamp,u.timestamp),this.currentRoleCanPublish&&(yield this.startDefaultDevicesCapture(),Object.values((c=(o=this.publisher)==null?void 0:o.publishStreams)!=null?c:{}).some(m=>m)&&(yield(h=this.publisher)==null?void 0:h.startPublish(),yield(f=this.publisher)==null?void 0:f.previewAll())),this.remoteUsers.forEach(m=>{m.updateSubscribe()}),this.liveTranscoding.setAuthInfo(e)}catch(u){let g=new Date().getTime()-s;const m=(p=u.code)!=null?p:-1,d=u.reason||u.message||"";throw this.webTrackingClient.reportJoinChannelRes(m,d,g),this.connectState=G.AliRtcConnectionStatusDisconnected,this.reporter.reportJoin(g,m,""),new C(m,d)}}else{const u=new C(N.ERR_JOIN_ALREADY_JOINED,"already joined");throw this.connectState===G.AliRtcConnectionStatusConnecting&&(u.message="Repeated operation during login"),this.webTrackingClient.reportJoinChannelRes(u.code,u.message,0),this.reporter.reportJoin(0,u.code,""),u}})}leaveChannel(e=!1){return v(this,null,function*(){var s;this.reporter.reportLeaveInvoked(),this.webTrackingClient.reportLeaveChannel();let i=new Date().getTime();if(G.AliRtcConnectionStatusConnected===this.connectState)try{let a;e||(a=yield this.signalingManager.leave()),this.clearCheckAuthInfoTimer(),yield this.resetState(),this.reporter.reportLeave(new Date().getTime()-i,0,(s=a==null?void 0:a.tid)!=null?s:""),E.setFlushMode(!0);return}catch(a){throw this.reporter.reportLeave(new Date().getTime()-i,a.code,a.reason),a}else{yield this.resetState(),this.reporter.reportLeave(0,0,""),E.setFlushMode(!0);return}})}isInCall(){return this.connectState===G.AliRtcConnectionStatusConnected}refreshAuthInfo(e){return v(this,null,function*(){const{userId:i,nonce:s,timestamp:a,token:n,role:o}=e,c={userId:i,nonce:s,timestamp:a,token:n,role:o};try{yield this.signalingManager.refreshAuthInfo(c),this.userManager.refreshAuthInfo(c),this.liveTranscoding.refreshAuthInfo(c),this.clearCheckAuthInfoTimer(),this._serverCheckAuthInfoTimestamp&&this._localCheckAuthInfoTimestamp&&e.timestamp&&this.setCheckAuthInfoTimer(e.timestamp,this._serverCheckAuthInfoTimestamp+(Date.now()-this._localCheckAuthInfoTimestamp))}catch(h){throw h}})}isAudioOnly(){return this._audioOnlyMode}publishLocalAudioStream(e){return v(this,null,function*(){var i,s,a;(i=this.publisher)==null||i.setPublishLocalAudioStreamEnabled(e),this.connectState===G.AliRtcConnectionStatusConnected&&(e?(s=this.publisher)!=null&&s.hasMicrophone?yield(a=this.publisher)==null?void 0:a.publishUpdate():yield this.startAudioCapture():yield this.stopPublish({audio:!0}))})}isLocalAudioStreamPublished(){var e,i;return(i=(e=this.publisher)==null?void 0:e.publishLocalAudioStreamEnabled)!=null?i:!0}setDefaultSubscribeAllRemoteAudioStreams(e){this.userManager.setAutoSubAudio(e)}subscribeAllRemoteAudioStreams(e){this.userManager.setWantSubAudio(e)}subscribeRemoteAudioStream(e,i){if(i&&!this.userManager.isWantSubAudio)throw new C(N.ERR_INVALID_ARGUMENTS,"subscribeAllRemoteAudioStreams(true) must be called first");this.userManager.updateAudioWant(e,i)}resumeRemoteAudioStream(e){const i=this.userManager.getRemoteUser(e);i&&i.resumeAudio()}publishLocalVideoStream(e){return v(this,null,function*(){var i,s,a;(i=this.publisher)==null||i.setPublishLocalVideoStreamEnabled(e),this.connectState===G.AliRtcConnectionStatusConnected&&(e?(s=this.publisher)!=null&&s.hasCamera?yield(a=this.publisher)==null?void 0:a.publishUpdate():yield this.enableLocalVideo():yield this.stopPublish({video:!0}))})}isLocalVideoStreamPublished(){var e,i;return(i=(e=this.publisher)==null?void 0:e.publishLocalVideoStreamEnabled)!=null?i:!0}setRemoteDefaultVideoStreamType(e){[he.AliRtcVideoStreamTypeHigh,he.AliRtcVideoStreamTypeLow].includes(e)&&this.userManager.setRemoteDefaultVideoStreamType(e)}setRemoteUserVideoStreamType(e,i){[he.AliRtcVideoStreamTypeHigh,he.AliRtcVideoStreamTypeLow].includes(i)&&this.userManager.setRemoteUserVideoStreamType(e,i)}setDefaultSubscribeAllRemoteVideoStreams(e){this.userManager.setAutoSubVideo(e),this.userManager.setAutoSubScreen(e)}subscribeAllRemoteVideoStreams(e){this.userManager.setWantSubVideo(e),this.userManager.setWantSubScreen(e)}subscribeRemoteMediaStream(e,i,s,a){const n=this.userManager.getRemoteUser(e);if(!n)throw new C(N.ERR_INNER,`no remote user(${e}) founded`);s&&(i===W.AliRtcVideoTrackScreen||i===W.AliRtcVideoTrackBoth)?n.setWantSubScreen(!0):n.setWantSubScreen(!1),s&&(i===W.AliRtcVideoTrackCamera||i===W.AliRtcVideoTrackBoth)?n.setWantSubVideo(!0):n.setWantSubVideo(!1),n.setWantSubAudio(a),n.updateSubscribe()}resumeRemoteMediaStream(e,i){const s=this.userManager.getRemoteUser(e);s&&s.resumeVideo(i)}getOnlineRemoteUsers(){return this.userManager.remoteUsers.map(e=>e.userId)}getUserInfo(e){var i;return(i=this.userManager.getRemoteUser(e))==null?void 0:i.remoteUserInfo}isUserOnline(e){return!!this.userManager.remoteUsers.find(i=>i.userId===e)}startScreenShare(e){return v(this,null,function*(){var o;const i={video:!1,audio:!1},{audio:s=!1,videoTrack:a,audioTrack:n}=e||{};if(a||n){i.screen=!0;const c=new MediaStream;a&&c.addTrack(a),n&&c.addTrack(n),i.mediaStream=c}else i.screen=s?{audio:!0}:!0;yield(o=this.publisher)==null?void 0:o.createLocalStream(i)})}stopScreenShare(){return v(this,null,function*(){var e;(e=this.publisher)==null||e.stopLocalStream({screen:!0})})}setScreenShareConfiguration(e){return v(this,null,function*(){var a;const{frameRate:i=$t.frameRate,bitrate:s=$t.maxBitrate}=e;yield(a=this.publisher)==null?void 0:a.setScreenProfile(ns,{width:$t.width,height:$t.height,frameRate:i,maxBitrate:s})})}setScreenShareContentHint(e){return v(this,null,function*(){var i;e&&((i=this.publisher)==null||i.setScreenContentHint(e))})}publishLocalScreenShareStream(e,i){return v(this,null,function*(){var s,a,n;(s=this.publisher)==null||s.setPublishLocalScreenStreamEnabled(e),this.connectState===G.AliRtcConnectionStatusConnected&&(e?(a=this.publisher)!=null&&a.hasScreenShare?yield(n=this.publisher)==null?void 0:n.publishUpdate():yield this.startScreenShare(i):yield this.stopPublish({screen:!0}))})}isScreenSharePublished(){var e,i;return(i=(e=this.publisher)==null?void 0:e.publishLocalScreenStreamEnabled)!=null?i:!0}setAudioShareVolume(e){if(typeof e!="number")throw new C(N.ERR_INVALID_ARGUMENTS,"volume must be a number");this.audioMixerPlugin.setOptions({screen:Math.max(0,Math.min(e,400))/100})}enableAudioVolumeIndication(e){this.userManager.enableAudioVolumeIndication(e)}muteLocalMic(e=!1){var i;this.isPublishing&&this.onLocalDeviceStatusChange(e?J.MuteAudio:J.UnmuteAudio),(i=this.publisher)==null||i.muteLocalMic(e)}muteRemoteAudioPlaying(e,i=!1){const s=this.userManager.getRemoteUser(e);if(!s)throw new C(N.ERR_INNER,`no remote user(${e}) founded`);s.setAudioMuted(i)}muteAllRemoteAudioPlaying(e=!1){this.userManager.setAudioMuted(e)}startAudioCapture(e){return v(this,null,function*(){var s;const i={audio:e||!0};yield(s=this.publisher)==null?void 0:s.createLocalStream(i)})}stopAudioCapture(){var e;(e=this.publisher)==null||e.stopAudioCapture()}switchMicrophone(e,i){return v(this,null,function*(){var s,a,n,o;if(yield(s=this.publisher)==null?void 0:s.setMicrophoneDeviceId(e),!((a=this.publisher)!=null&&a.audioCaptureDisabled)){if(i){yield(n=this.publisher)==null?void 0:n.createLocalStream({audio:!0,mediaStream:new MediaStream([i])});return}yield(o=this.publisher)==null?void 0:o.createLocalStream({audio:{deviceId:e}})}})}setRecordingVolume(e){if(typeof e!="number")throw new C(N.ERR_INVALID_ARGUMENTS,"volume must be a number");this.audioMixerPlugin.setOptions({audio:Math.max(0,Math.min(e,400))/100})}setAudioProfile(e){return v(this,null,function*(){var i;yield(i=this.publisher)==null?void 0:i.setAudioProfile(e)})}getAudioTrack(e){return v(this,null,function*(){var s;if(!e)return(s=this.publisher)==null?void 0:s.audioTrack;const i=this.userManager.getRemoteUser(e);return i==null?void 0:i.getAudioTrack})}setLocalViewConfig(e,i){return v(this,null,function*(){var s,a,n;if(this._audioOnlyMode)throw new C(N.ERR_INNER,"Cannot set local view in audio only mode");(s=this.userManager)==null||s.setLocalViewConfig(e,i),i===W.AliRtcVideoTrackCamera&&((a=this.publisher)!=null&&a.hasCamera)?yield this.startPreview():i===W.AliRtcVideoTrackScreen&&((n=this.publisher)!=null&&n.hasScreenShare)&&(yield this.startPreviewScreen())})}setCameraCapturerConfiguration(e){return v(this,null,function*(){var h,f,p;const{width:i=jt.width,height:s=jt.height,frameRate:a=jt.frameRate,bitrate:n=jt.maxBitrate,cameraDirection:o,deviceId:c}=e;yield(h=this.publisher)==null?void 0:h.setVideoProfile(as,{width:i,height:s,frameRate:a,maxBitrate:n}),o!==void 0&&((f=this.publisher)==null||f.setCameraDirection(o)),c&&((p=this.publisher)==null||p.setCameraDeviceId(c))})}setCameraCapturerContentHint(e){return v(this,null,function*(){var i;e&&((i=this.publisher)==null||i.setVideoContentHint(e))})}enableLocalVideo(e=!0){return v(this,null,function*(){var i,s,a,n,o,c,h,f,p,u,g;if(this._audioOnlyMode)throw new C(N.ERR_INNER,"Cannot enable local video in audio only mode");if(e){(s=(i=this.publisher)==null?void 0:i.publishStreams)!=null&&s.video&&((o=(n=(a=this.publisher)==null?void 0:a.publishStreams)==null?void 0:n.video)==null||o.disableVideo(),(p=(f=(h=(c=this.publisher)==null?void 0:c.publishStreams)==null?void 0:h.video)==null?void 0:f.videoTrack)==null||p.stop());const m={video:!0};yield(u=this.publisher)==null?void 0:u.startCameraCapture(m)}else yield(g=this.publisher)==null?void 0:g.stopCameraCapture()})}muteLocalCamera(e){return v(this,null,function*(){var i;this.isPublishing&&this.onLocalDeviceStatusChange(e?J.MuteVideo:J.UnmuteVideo),(i=this.publisher)==null||i.muteLocalCamera(e)})}muteLocalScreen(e){return v(this,null,function*(){var i;this.isPublishing&&this.onLocalDeviceStatusChange(e?J.MuteScreen:J.UnmuteScreen),(i=this.publisher)==null||i.muteLocalScreen(e)})}setRemoteViewConfig(e,i,s){this.userManager.setRemoteViewConfig(i,e,s)}isCameraOn(){var e,i;return(i=(e=this.publisher)==null?void 0:e.hasCamera)!=null?i:!1}switchCamera(e,i){return v(this,null,function*(){var a,n,o,c,h,f,p,u,g,m,d,S;if(this._audioOnlyMode)throw new C(N.ERR_INNER,"Cannot switch camera in audio only mode");const s={};if(e?s.deviceId=e:s.cameraDirection=((a=this.publisher)==null?void 0:a.cameraDirection)==="environment"?Ft.CAMERA_FRONT:Ft.CAMERA_REAR,yield this.setCameraCapturerConfiguration(s),!((n=this.publisher)!=null&&n.cameraCaptureDisabled)){(c=(o=this.publisher)==null?void 0:o.publishStreams)!=null&&c.video&&((p=(f=(h=this.publisher)==null?void 0:h.publishStreams)==null?void 0:f.video)==null||p.disableVideo(),(d=(m=(g=(u=this.publisher)==null?void 0:u.publishStreams)==null?void 0:g.video)==null?void 0:m.videoTrack)==null||d.stop());const b={video:!0};i&&(b.mediaStream=new MediaStream([i])),yield(S=this.publisher)==null?void 0:S.createLocalStream(b)}})}getCurrentCameraDeviceId(){var e;return(e=this.publisher)==null?void 0:e.getCurrentCameraDeviceId()}startPreview(){return v(this,null,function*(){var e,i;if(this._audioOnlyMode)throw new C(N.ERR_INNER,"Cannot start preview camera in audio only mode");(e=this.publisher)!=null&&e.hasCamera||(yield this.enableLocalVideo(!0)),yield(i=this.publisher)==null?void 0:i.previewAll({screen:!1})})}startPreviewScreen(e){return v(this,null,function*(){var i,s;if(this._audioOnlyMode)throw new C(N.ERR_INNER,"Cannot start preview screen share in audio only mode");(i=this.publisher)!=null&&i.hasScreenShare||(yield this.startScreenShare(e)),yield(s=this.publisher)==null?void 0:s.previewAll({primary:!1})})}stopPreview(){return v(this,null,function*(){var e;yield(e=this.publisher)==null?void 0:e.stopPreview({primary:!0,screen:!1})})}stopPreviewScreen(){return v(this,null,function*(){var e;yield(e=this.publisher)==null?void 0:e.stopPreview({primary:!1,screen:!0})})}getVideoTrack(e){return v(this,null,function*(){var n,o,c,h;const{userId:i,streamType:s}=e;if(!i)return s===ce.AliRtcSdkStreamTypeCapture?(n=this.publisher)==null?void 0:n.cameraTrack:(o=this.publisher)==null?void 0:o.screenTrack;const a=this.userManager.getRemoteUser(i);return s===ce.AliRtcSdkStreamTypeCapture?(c=a==null?void 0:a.getCameraStream)==null?void 0:c.videoTrack:(h=a==null?void 0:a.getScreenStream)==null?void 0:h.videoTrack})}startPublishLiveStream(e,i){return v(this,null,function*(){return this.liveTranscoding.startPublishLiveStream(e,i)})}updatePublishLiveStream(e,i){return v(this,null,function*(){return this.liveTranscoding.updatePublishLiveStream(e,i)})}updatePublishLiveStreamWithTaskId(e,i){return this.liveTranscoding.updatePublishLiveStreamWithTaskId(e,i)}stopPublishLiveStream(e){return v(this,null,function*(){return this.liveTranscoding.stopPublishLiveStream(e)})}stopPublishLiveStreamWithTaskId(e){return this.liveTranscoding.stopPublishLiveStreamWithTaskId(e)}setEnableMediaExtensionMsg(e){var i;(i=this.userManager)==null||i.setEnableMediaExtensionMsg(!!e)}sendMediaExtensionMsg(e,i){return v(this,null,function*(){return this.sendMediaExtensionMsgEx(e,i,5)})}sendMediaExtensionMsgEx(e,i,s){return v(this,null,function*(){var a;if(!this.publisher||!this.isPublishing)throw new C(N.ERR_INNER,"you should publish first");return(a=this.publisher)==null?void 0:a.sendSEI(e,i,s)})}enablePlugin(e,i){this.userManager.pluginManager.add(e,i)}removePlugin(e){this.userManager.pluginManager.remove(e)}setPluginOption(e,i){const s=this.userManager.pluginManager.get(e);s&&i&&s.setOptions(i)}getPluginOption(e){const i=this.userManager.pluginManager.get(e);return i==null?void 0:i.getOptions()}isBeautyAvailable(){return this.userManager.pluginManager.has("AliRtcBeauty")}isBeautyEnabled(){const e=this.userManager.pluginManager.get("AliRtcBeauty");if(!e)throw new C(ot.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");return!!(e!=null&&e.isEnable)}setBeautyEffect(e,i){const s=this.userManager.pluginManager.get("AliRtcBeauty");if(!s)throw new C(ot.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");e?s.enable():s.disable(),s.setOptions({basicBeauty:{skinBuffing:Math.max(Math.min(1,+i.smoothnessLevel),0),whitening:Math.max(Math.min(1,+i.whiteningLevel),0)}})}enableBackgroundExchange(e,i){const s=this.userManager.pluginManager.get("AliRtcBeauty");if(!s||!s.isEnable)throw new C(ot.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const a={setSegmentBackgroundImage:{backgroundImgUrl:e?i:""}};e&&(a.segmentBackgroundProcess={enable:!1}),s.setOptions(a)}enableBackgroundBlur(e){const i=this.userManager.pluginManager.get("AliRtcBeauty");if(!i||!i.isEnable)throw new C(ot.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const s={segmentBackgroundProcess:{type:0,enable:e}};e&&(s.setSegmentBackgroundImage={type:0,backgroundImgUrl:""}),i.setOptions(s)}},l(L,"logName","AliRtcEngine"),l(L,"isSupported",Ya),l(L,"isDualVideoStreamSupported",wr.isSupport),l(L,"getCameraList",()=>v(L,null,function*(){return(yield V.AliRTS.getCameraList()).filter(i=>i.deviceId)})),l(L,"getMicrophoneList",()=>v(L,null,function*(){return(yield V.AliRTS.getMicList()).filter(i=>i.deviceId)})),l(L,"getSpeakerList",()=>v(L,null,function*(){return(yield V.AliRTS.getSpeakerList()).filter(i=>i.deviceId)})),l(L,"_instance"),l(L,"AliRtcSdkChannelProfile",Qe),l(L,"AliRtcSdkClientRole",st),l(L,"AliRtcVideoStreamType",he),l(L,"AliRtcVideoTrack",W),l(L,"AliRtcAudioTrack",kt),l(L,"AliRtcPublishState",B),l(L,"AliRtcSubscribeState",te),l(L,"AliRtcRawDataStreamType",ce),l(L,"AliRtcLogLevel",Ki),l(L,"AliRtcEngineLocalDeviceType",Ke),l(L,"AliRtcEngineLocalDeviceExceptionType",re),l(L,"AliRtcConnectionStatus",G),l(L,"AliRtcConnectionStatusChangeReason",mt),l(L,"AliRtcPlugin",Tt),l(L,"AliRtcPluginTrackType",ni),l(L,"AliRtcLiveTranscodingParam",ui),l(L,"AliRtcLiveTranscodingEncodeParam",Yi),l(L,"AliRtcLiveTranscodingMixParam",ta),l(L,"AliRtcLiveTranscodingSingleParam",ia),l(L,"AliRtcTranscodingClockWidget",ra),l(L,"AliRtcTranscodingImage",Rr),l(L,"AliRtcTranscodingText",aa),l(L,"AliRtcTranscodingUser",na),l(L,"AliRtcLiveTranscodingMixMode",xt),l(L,"AliRtcLiveTranscodingStreamType",qi),l(L,"AliRtcLiveTranscodingSourceType",Pt),l(L,"AliRtcLiveTranscodingTaskProfile",Ji),l(L,"AliRtcLiveTranscodingAudioSampleRate",oi),l(L,"AliRtcLiveTranscodingSegmentType",Bt),l(L,"AliRtcLiveTranscodingFontType",Ht),l(L,"AliRtcLiveTranscodingCropMode",Gi),l(L,"AliRtcLiveTranscodingMediaProcessMode",ci),l(L,"AliRtcLiveTranscodingState",zi),l(L,"AliRtcLiveTranscodingErrorCode",We),l(L,"AliRtcTrascodingPublishTaskStatus",Xi),l(L,"Plugin",Tt),L);P([y()],T.prototype,"destroy",1),P([y()],T.prototype,"resetState",1),P([y(I)],T.prototype,"stopPublish",1),P([y()],T.prototype,"backToUnpublishStatus",1),P([y()],T.prototype,"resumePublishForNetworkRecovery",1),P([y()],T.prototype,"onNetworkRecovery",1),P([y()],T.prototype,"resumeSubList",1),P([y(I)],T.prototype,"setEnableDualVideoStream",1),P([y(I)],T.prototype,"setChannelProfile",1),P([y(I)],T.prototype,"setClientRole",1),P([y(I)],T.prototype,"setAudioOnlyMode",1),P([y(I)],T.prototype,"joinChannel",1),P([y(I)],T.prototype,"leaveChannel",1),P([y(I)],T.prototype,"refreshAuthInfo",1),P([y(I)],T.prototype,"publishLocalAudioStream",1),P([y(I)],T.prototype,"setDefaultSubscribeAllRemoteAudioStreams",1),P([y(I)],T.prototype,"subscribeAllRemoteAudioStreams",1),P([y(I)],T.prototype,"subscribeRemoteAudioStream",1),P([y(I)],T.prototype,"resumeRemoteAudioStream",1),P([y(I)],T.prototype,"publishLocalVideoStream",1),P([y(I)],T.prototype,"setRemoteDefaultVideoStreamType",1),P([y(I)],T.prototype,"setRemoteUserVideoStreamType",1),P([y(I)],T.prototype,"setDefaultSubscribeAllRemoteVideoStreams",1),P([y(I)],T.prototype,"subscribeAllRemoteVideoStreams",1),P([y(I)],T.prototype,"subscribeRemoteMediaStream",1),P([y(I)],T.prototype,"resumeRemoteMediaStream",1),P([y(([t])=>[`${t==null?void 0:t.audio}`])],T.prototype,"startScreenShare",1),P([y()],T.prototype,"stopScreenShare",1),P([y(I)],T.prototype,"setScreenShareConfiguration",1),P([y(I)],T.prototype,"setScreenShareContentHint",1),P([y()],T.prototype,"publishLocalScreenShareStream",1),P([y(I)],T.prototype,"setAudioShareVolume",1),P([y(I)],T.prototype,"enableAudioVolumeIndication",1),P([y(I)],T.prototype,"muteLocalMic",1),P([y(I)],T.prototype,"muteRemoteAudioPlaying",1),P([y(I)],T.prototype,"muteAllRemoteAudioPlaying",1),P([y(I)],T.prototype,"startAudioCapture",1),P([y()],T.prototype,"stopAudioCapture",1),P([y(I)],T.prototype,"switchMicrophone",1),P([y(I)],T.prototype,"setRecordingVolume",1),P([y(I)],T.prototype,"setAudioProfile",1),P([y(I)],T.prototype,"getAudioTrack",1),P([y(I)],T.prototype,"setLocalViewConfig",1),P([y(I)],T.prototype,"setCameraCapturerConfiguration",1),P([y(I)],T.prototype,"setCameraCapturerContentHint",1),P([y(I)],T.prototype,"enableLocalVideo",1),P([y(I)],T.prototype,"muteLocalCamera",1),P([y(I)],T.prototype,"muteLocalScreen",1),P([y(I)],T.prototype,"setRemoteViewConfig",1),P([y(I)],T.prototype,"switchCamera",1),P([y()],T.prototype,"startPreview",1),P([y()],T.prototype,"startPreviewScreen",1),P([y()],T.prototype,"stopPreview",1),P([y()],T.prototype,"stopPreviewScreen",1),P([y()],T.prototype,"startPublishLiveStream",1),P([y()],T.prototype,"updatePublishLiveStream",1),P([y()],T.prototype,"updatePublishLiveStreamWithTaskId",1),P([y()],T.prototype,"stopPublishLiveStream",1),P([y()],T.prototype,"stopPublishLiveStreamWithTaskId",1),P([y(I)],T.prototype,"setEnableMediaExtensionMsg",1),P([y(([t,r,e])=>[t.length,r,e])],T.prototype,"sendMediaExtensionMsgEx",1),P([y(([t,r])=>[t.name||"",r])],T.prototype,"enablePlugin",1),P([y(I)],T.prototype,"removePlugin",1),P([y(I)],T.prototype,"setPluginOption",1),P([y(I)],T.prototype,"getPluginOption",1),P([y(I)],T.prototype,"setBeautyEffect",1),P([y(I)],T.prototype,"enableBackgroundExchange",1),P([y(I)],T.prototype,"enableBackgroundBlur",1),P([y(I)],T,"setLogLevel",1);let oa=T;const ca=new $i({businessName:"imp-web-rtc",version:(ua=oa.getSdkVersion())!=null?ua:"unknown",env:"prod"});ca.setReady();const qc=ca.wrap(oa);A.AliRtcConnectionStatus=G,A.AliRtcConnectionStatusChangeReason=mt,A.AliRtcEngineLocalDeviceExceptionType=re,A.AliRtcEngineLocalDeviceType=Ke,A.AliRtcErrorCode=N,A.AliRtcLiveTranscodingAudioSampleRate=oi,A.AliRtcLiveTranscodingCropMode=Gi,A.AliRtcLiveTranscodingEncodeParam=Yi,A.AliRtcLiveTranscodingErrorCode=We,A.AliRtcLiveTranscodingFontType=Ht,A.AliRtcLiveTranscodingMediaProcessMode=ci,A.AliRtcLiveTranscodingMixMode=xt,A.AliRtcLiveTranscodingMixParam=ta,A.AliRtcLiveTranscodingParam=ui,A.AliRtcLiveTranscodingSegmentType=Bt,A.AliRtcLiveTranscodingSingleParam=ia,A.AliRtcLiveTranscodingSourceType=Pt,A.AliRtcLiveTranscodingState=zi,A.AliRtcLiveTranscodingStreamType=qi,A.AliRtcLiveTranscodingTaskProfile=Ji,A.AliRtcLocalStreamInfo=ar,A.AliRtcLogLevel=Ki,A.AliRtcPlugin=Tt,A.AliRtcPluginTrackType=ni,A.AliRtcPluginType=es,A.AliRtcPublishState=B,A.AliRtcRawDataStreamType=ce,A.AliRtcRemoteUserInfo=ls,A.AliRtcSdkChannelProfile=Qe,A.AliRtcSdkClientRole=st,A.AliRtcSubscribeState=te,A.AliRtcTranscodingClockWidget=ra,A.AliRtcTranscodingImage=Rr,A.AliRtcTranscodingText=aa,A.AliRtcTranscodingUser=na,A.AliRtcTrascodingPublishTaskStatus=Xi,A.AliRtcVideoStreamType=he,A.AliRtcVideoTrack=W,A.default=qc,Object.defineProperties(A,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
129
|
+
`;class Hs extends ur{constructor(e,t){super(e,t);p(this,"processor");p(this,"trackGenerator");p(this,"worker");this.processor=new MediaStreamTrackProcessor({track:e}),this.trackGenerator=new MediaStreamTrackGenerator({kind:"video"}),this.startTransform()}static isSupport(){return"MediaStreamTrackProcessor"in window&&"MediaStreamTrackGenerator"in window&&"TransformStream"in window&&"VideoFrame"in window}startTransform(){const e=new Blob([fc],{type:"text/javascript"}),r=(window.URL||window.webkitURL).createObjectURL(e);this.worker=new Worker(r);const{readable:s}=this.processor,{writable:n}=this.trackGenerator;this.worker.postMessage({type:"startRender",readable:s,writable:n,width:this.targetWidth,height:this.targetHeight,frameRate:this.targetFrameRate},[s,n])}updateOptions(e){super.updateOptions(e),this.worker&&this.worker.postMessage(W({type:"updateOptions"},e))}dispose(){try{this.processor.readable.cancel(),this.trackGenerator.writable.close()}catch(e){}}getVideoTrack(){return this.trackGenerator}}class hr{static isSupport(){return typeof HTMLCanvasElement.prototype.captureStream=="function"}static getInstance(a,e){return Hs.isSupport()?new Hs(a,e):Bs.isSupport()?new Bs(a,e):new cc(a,e)}}class mc extends mt{constructor(){super(...arguments);p(this,"hasVideoTrack",!1);p(this,"videoScaler")}get initOptions(){return{width:320,height:180,frameRate:15}}setOptions(e){var t;this.options=e,(t=this.videoScaler)==null||t.updateOptions(e)}isSupported(){return hr.isSupport()}shouldUpdate(e){return this.hasVideoTrack!==!!e.currentVideoTrack}process(e){return v(this,null,function*(){if(e.currentVideoTrack){if(this.hasVideoTrack=!0,!this.videoScaler){const r=this.options||this.initOptions;this.videoScaler=hr.getInstance(e.currentVideoTrack,r)}const t=this.videoScaler.getVideoTrack();t&&e.updateDualVideoTrack(t)}else e.updateDualVideoTrack(),this.emit("updated"),this.videoScaler&&this.videoScaler.dispose()})}clear(e){super.clear(e),e==null||e.updateDualVideoTrack()}}class lr{static checkString(a){return typeof a=="string"}static checkNumber(a){return typeof a=="number"}static checkHtmlVideoElement(a){return a&&a.nodeName==="VIDEO"}static checkHtmlAudioElement(a){return a&&a.nodeName==="AUDIO"}static checkAuthInfo(a){if(!a)return new E(T.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no authInfo founded");if(!a.appId)return new E(T.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no appId founded");if(!a.channelId)return new E(T.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no channelId founded");if(!a.userId)return new E(T.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no userId founded");if(a.timestamp){if(!lr.checkNumber(a.timestamp))return new E(T.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"timestamp is not number")}else return new E(T.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no timestamp founded");return a.token?null:new E(T.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD,"no token founded")}static checkMediaStreamTrack(a){return a instanceof MediaStreamTrack}static checkVideoEncoderConfiguration(a){return a&&(a.width||a.height||a.frameRate||a.bitrateMax)}}class Fs{constructor(a){p(this,"taskProfile");p(this,"encodeParam");p(this,"users",[]);p(this,"backgroundColor",0);p(this,"backgrounds",[]);p(this,"watermarks",[]);p(this,"clockWidgets",[]);p(this,"cropMode");p(this,"mediaProcessMode");this.taskProfile=a}}class js{constructor(a,e,t){p(this,"userId");p(this,"streamType");p(this,"sourceType");this.userId=a,this.streamType=e,this.sourceType=t}}class $s{constructor(a,e,t,r=0,s=16777215,n=Tt.NOTO_SERIF_CJKSC_REGULAR){p(this,"x");p(this,"y");p(this,"fontSize");p(this,"zOrder");p(this,"fontColor");p(this,"fontType");this.x=a,this.y=e,this.fontSize=t,this.zOrder=r,this.fontColor=s,this.fontType=n}toJson(a,e){return{x:Ce(this.x,a),y:Ce(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:Hi(this.fontColor),zorder:this.zOrder}}}var Ws=(i=>(i[i.NOT_DISPLAY=0]="NOT_DISPLAY",i[i.ALWAYS=1]="ALWAYS",i[i.WHEN_NO_VIDEO=2]="WHEN_NO_VIDEO",i))(Ws||{});class dr{constructor(a,e,t,r,s,n=0,o=1,c=1){p(this,"url");p(this,"x");p(this,"y");p(this,"width");p(this,"height");p(this,"alpha");p(this,"display",1);p(this,"zOrder");this.url=a,this.x=e,this.y=t,this.width=r,this.height=s,this.zOrder=n,this.alpha=o,this.display=c}toJson(a,e){return{url:this.url,alpha:this.alpha,display:this.display,x:Ce(this.x,a),y:Ce(this.y,e),width:Ce(this.width,a),height:Ce(this.height,e),zorder:this.zOrder}}}p(dr,"DisplayType",Ws);class Ks{constructor(a,e,t,r,s=0,n=16777215,o=Tt.NOTO_SERIF_CJKSC_REGULAR){p(this,"text");p(this,"x");p(this,"y");p(this,"fontSize");p(this,"zOrder");p(this,"fontColor");p(this,"fontType");this.text=a,this.x=e,this.y=t,this.fontSize=r,this.zOrder=s,this.fontColor=n,this.fontType=o}toJson(a,e){return{text:this.text,x:Ce(this.x,a),y:Ce(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:Hi(this.fontColor),zorder:this.zOrder}}}class Js{constructor(a,e,t,r,s,n=0,o){p(this,"userId");p(this,"x");p(this,"y");p(this,"width");p(this,"height");p(this,"zOrder");p(this,"sourceType");p(this,"segmentType",At.LiveTranscodingNoBody);p(this,"images",[]);p(this,"texts",[]);typeof a=="number"?this.userId=a.toString():this.userId=a,this.x=e,this.y=t,this.width=r,this.height=s,this.zOrder=n,o&&(this.sourceType=o)}toJson(a,e,t,r){const s={paneid:a,majorpane:0,x:Ce(this.x,e),y:Ce(this.y,t),width:Ce(this.width,e),height:Ce(this.height,t),zorder:this.zOrder,userid:this.userId,images:this.images.map(n=>n.toJson(e,t)),texts:this.texts.map(n=>n.toJson(e,t))};return this.sourceType&&Et[this.sourceType]?s.sourcetype=Et[this.sourceType]:s.sourcetype=Et[St.LiveTranscodingCamera],this.segmentType&&r===Gt.LiveTranscodingVirtualBackground?s.segmenttype=this.segmentType:s.segmenttype=At.LiveTranscodingNoBody,s}}class Sc extends mt{constructor(){super("AliRtcScreenStandardize",ae.AliRtcSdkStreamTypeScreen);p(this,"canvas");p(this,"lastWidth");p(this,"lastHeight");p(this,"hasScreenTrack",!1)}get initOptions(){return{base:4}}setOptions(e){this.options=e}isSupported(){return!(typeof TransformStream=="undefined"||typeof MediaStreamTrackProcessor=="undefined"||typeof MediaStreamTrackGenerator=="undefined")}updateProcessCanvas(e,t){if(this.canvas&&this.lastWidth===e&&this.lastHeight===t)return;const r=Math.ceil(e/this.options.base)*this.options.base,s=Math.ceil(t/this.options.base)*this.options.base;if(this.canvas||(this.canvas=document.createElement("canvas")),this.canvas.width=r,this.canvas.height=s,this.lastWidth&&e>this.lastWidth||this.lastHeight&&t>this.lastHeight){const n=this.canvas.getContext("2d");n&&n.clearRect(0,0,r,s)}this.lastWidth=e,this.lastHeight=t}shouldUpdate(e){return this.hasScreenTrack!==(!!e.originVideoTrack&&e.videoSource===ft.Screen)}handleFrame(e,t){return v(this,null,function*(){var o;const{displayWidth:r,displayHeight:s}=e;if(!r||!s||r%this.options.base===0&&s%this.options.base===0)return this.clear(t),e;this.updateProcessCanvas(r,s);const n=(o=this.canvas)==null?void 0:o.getContext("2d");if(this.canvas&&n){n.drawImage(e,0,0,r,s);const c=new VideoFrame(this.canvas,{timestamp:e.timestamp});return e.close(),c}return e})}process(e){return v(this,null,function*(){var h;if(!e.originVideoTrack||e.videoSource!==ft.Screen){this.clear(e),this.hasScreenTrack=!1;return}const t=new MediaStreamTrackProcessor({track:e.originVideoTrack}),r=new MediaStreamTrackGenerator({kind:"video"}),s=new MediaStream([r]),n=this,o=new TransformStream({transform(l,d){return v(this,null,function*(){const f=yield n.handleFrame(l,e);yield d.enqueue(f),f==null||f.close()})}});t.readable.pipeThrough(o).pipeTo(r.writable);const c=(h=s.getVideoTracks())==null?void 0:h[0];e.updateVideoTrack(c),this.hasScreenTrack=!0})}clear(e){this.canvas=void 0,this.lastWidth=void 0,this.lastHeight=void 0,super.clear(e)}}var bc=Object.defineProperty,vc=Object.getOwnPropertyDescriptor,C=(i,a,e,t)=>{for(var r=t>1?void 0:t?vc(a,e):a,s=i.length-1,n;s>=0;s--)(n=i[s])&&(r=(t?n(a,e,r):n(r))||r);return t&&r&&bc(a,e,r),r};const k=(L=class extends X{constructor(e){super();p(this,"channelProfile");p(this,"clientRole");p(this,"signalingManager");p(this,"userManager");p(this,"liveTranscoding");p(this,"maxSignalingConnectRetryCount");p(this,"reporter");p(this,"webTrackingClient");p(this,"connectState",q.AliRtcConnectionStatusInit);p(this,"networkError",!1);p(this,"audioMixerPlugin");p(this,"dualVideoPlugin");p(this,"_audioOnlyMode",!1);p(this,"_authInfoWillExpireTimer",null);p(this,"_authInfoExpiredTimer",null);p(this,"_serverCheckAuthInfoTimestamp",null);p(this,"_localCheckAuthInfoTimestamp",null);this.webTrackingClient=new ic(e==null?void 0:e.webTrack),this.reporter=new sc,this.channelProfile=qe.AliRtcSdkCommunication,this.clientRole=Ze.AliRtcSdkLive,this.liveTranscoding=new cn,this.signalingManager=new Oa(this.channelProfile,this.clientRole,(e==null?void 0:e.env)===Qe.pre?Qe.pre:Qe.prod),this.addSignalingManagerListeners(),this.maxSignalingConnectRetryCount=e==null?void 0:e.maxSignalingConnectRetryCount,this.userManager=new Ee({reporter:this.reporter,webTrackingClient:this.webTrackingClient,signalingManager:this.signalingManager}),this.addUserManagerListeners(),this.addPublisherListeners(),this.audioMixerPlugin=new oc,this.enablePlugin(this.audioMixerPlugin),this.dualVideoPlugin=new mc("dualVideoPlugin"),this.enablePlugin(new Sc)}static getSdkVersion(){return Rt}static setLogLevel(e){A.setLogLevel(e)}static getInstance(e){return L._instance||(L._instance=new L(e)),L._instance}destroy(){L._instance=void 0}get channel(){return this.userManager.channel}get userId(){return this.userManager.userId}get remoteUsers(){return this.userManager.remoteUsers}get publisher(){return this.userManager.publisher}get publishAudioStream(){var e;return(e=this.publisher)==null?void 0:e.publishStreams.audio}get isPublishing(){const{publisher:e}=this.userManager;return e?e.isPublishing:!1}get currentRoleCanPublish(){return this.channelProfile===qe.AliRtcSdkCommunication||this.clientRole===Ze.AliRtcSdkInteractive}resetState(){return v(this,null,function*(){yield this.userManager.clear(),this.connectState=q.AliRtcConnectionStatusDisconnected,this.networkError=!1,this.signalingManager.reset(),this.liveTranscoding.clear(),this.reporter.stop(),yield this.publishLocalAudioStream(!0),yield this.publishLocalVideoStream(!0),yield this.publishLocalScreenShareStream(!0)})}stopPublish(e){return v(this,null,function*(){var t,r,s;e?yield(t=this.publisher)==null?void 0:t.stopLocalStream(e):(yield(r=this.publisher)==null?void 0:r.publishStop(),(s=this.publisher)==null||s.stopPreview())})}addPublisherListeners(){var e,t,r,s,n,o,c,u,h;(e=this.publisher)==null||e.on(be.Local,l=>{A.event("[Publisher] Device Status Change",l),this.onLocalDeviceStatusChange(l)}),(t=this.publisher)==null||t.on(ht.VideoTrackEnded,()=>{A.event("[Publisher] VideoTrack Ended"),this.emit("localDeviceException",je.AliEngineLocalDeviceTypeCamera,te.AliEngineLocalDeviceExceptionTypeCameraInterrupt,"")}),(r=this.publisher)==null||r.on(ht.ScreenTrackEnded,()=>{A.event("[Publisher] ScreenTrack Ended"),this.emit("localDeviceException",je.AliEngineLocalDeviceTypeDisplay,te.AliEngineLocalDeviceExceptionTypeDisplayException,"")}),(s=this.publisher)==null||s.on(ht.AudioTrackEnded,()=>{A.event("[Publisher] AudioTrack Ended"),this.emit("localDeviceException",je.AliEngineLocalDeviceTypeMic,te.AliEngineLocalDeviceExceptionTypeMicInterrupt,"")}),(n=this.publisher)==null||n.on("localDeviceException",(l,d,f="")=>{this.emit("localDeviceException",l,d,f)}),(o=this.publisher)==null||o.on("audioPublishStateChanged",(l,d,f)=>{var m;this.emit("audioPublishStateChanged",l,d,f,(m=this.channel)!=null?m:"")}),(c=this.publisher)==null||c.on("videoPublishStateChanged",(l,d,f)=>{var m;this.emit("videoPublishStateChanged",l,d,f,(m=this.channel)!=null?m:"")}),(u=this.publisher)==null||u.on("dualStreamPublishStateChanged",(l,d,f)=>{var m;this.emit("dualStreamPublishStateChanged",l,d,f,(m=this.channel)!=null?m:"")}),(h=this.publisher)==null||h.on("screenPublishStateChanged",(l,d,f)=>{var m;this.emit("screenSharePublishStateChanged",l,d,f,(m=this.channel)!=null?m:"")})}addUserManagerListeners(){this.userManager.rtsManager.on("disconnected",()=>v(this,null,function*(){A.event("[UserManager] RTS Disconnected"),(yield Ye.isNetworkAvailable())?this.onNetworkRecovery():this.onNetworkError()})),this.userManager.rtsManager.on("subscribeexceeds",()=>v(this,null,function*(){yield this.resumePublishForNetworkRecovery(),yield this.resumeSubList()})),this.userManager.rtsManager.on("seimessage",(e,t,r)=>{const s=this.remoteUsers.find(n=>n.streamUrl===e);s&&this.emit("mediaExtensionMsgReceived",s.userId,r,t)}),this.userManager.on(be.Remote,(e,t)=>{A.event("[UserManager] RemoteUser Device Status Change",e,t)}),this.userManager.on("remoteTrackAvailableChange",(e,t,r)=>{this.emit("remoteTrackAvailableNotify",e,t,r)}),this.userManager.on("audioSubscribeStateChanged",(e,t,r,s,n)=>{this.emit("audioSubscribeStateChanged",e,t,r,s,n)}),this.userManager.on("videoSubscribeStateChanged",(e,t,r,s,n)=>{this.emit("videoSubscribeStateChanged",e,t,r,s,n)}),this.userManager.on("screenSubscribeStateChanged",(e,t,r,s,n)=>{this.emit("screenShareSubscribeStateChanged",e,t,r,s,n)}),this.userManager.on("userAudioMuted",(e,t)=>{this.emit("userAudioMuted",e,t)}),this.userManager.on("userVideoMuted",(e,t)=>{this.emit("userVideoMuted",e,t)}),this.userManager.on("userScreenMuted",(e,t)=>{this.emit("userScreenMuted",e,t)}),this.userManager.on("audioVolume",e=>{this.emit("audioVolume",e)}),this.userManager.on("remoteAudioAutoPlayFail",e=>{this.emit("remoteAudioAutoPlayFail",e)}),this.userManager.on("remoteVideoAutoPlayFail",(e,t)=>{this.emit("remoteVideoAutoPlayFail",e,t)}),this.userManager.on("rtcLocalAudioStats",e=>{this.emit("rtcLocalAudioStats",e)}),this.userManager.on("rtcLocalVideoStats",e=>{this.emit("rtcLocalVideoStats",e)}),this.userManager.on("rtcRemoteAudioStats",e=>{this.emit("rtcRemoteAudioStats",e)}),this.userManager.on("rtcRemoteVideoStats",e=>{this.emit("rtcRemoteVideoStats",e)}),this.userManager.on("remoteSubscribeError",e=>{this.emit("onOccurError",e)})}addSignalingManagerListeners(){this.signalingManager.on("onKeepAliveRsp",()=>{this.networkError&&(A.event("[Signaling] Receive KeepAlive Response",`networkError: ${this.networkError}`),this.onNetworkRecovery())}),this.signalingManager.on("onNotifyJoin",e=>{A.event("[Signaling] Notify Join ",e),this.handleUsersJoin(e),e.forEach(t=>{this.emit("remoteUserOnLineNotify",t.userid,0)})}),this.signalingManager.on("onNotifyStatus",e=>{A.event("[Signaling] Notify Status ",e),e.forEach(t=>{this.userManager.updateRemoteUserDeviceStatus(t)})}),this.signalingManager.on("onNotifyLeave",e=>{A.event("[Signaling] Notify Leave ",e),e.forEach(t=>{this.emit("remoteUserOffLineNotify",t.userid,t.leavecode),this.userManager.removeLeftUser(t)})}),this.signalingManager.on("onBye",(e,t)=>{A.event("[Signaling] Bye ",e,t),this.reporter.reportError({message:`reason: ${e}, description: ${t}`}),this.emit("bye",e),this.leaveChannel(!0)}),this.signalingManager.on("onConnectFail",e=>{A.event("[Signaling] Connect Failed ",e),this.onError(e),this.backToUnpublishStatus(),this.connectState=q.AliRtcConnectionStatusFailed,this.emit("connectionStatusChange",q.AliRtcConnectionStatusFailed,ct.AliRtcConnectionChangedNetworkInterrupted)}),this.signalingManager.on("onNetworkError",e=>{A.event("[Signaling] Network error ",e),this.onNetworkError()}),this.signalingManager.on("onAuthInvalid",()=>{A.event("[Signaling] Auth Invalid")}),this.signalingManager.on("onReconnectStart",()=>{A.event("[Signaling] Reconnect Start "),this.connectState=q.AliRtcConnectionStatusReconnecting,this.emit("connectionStatusChange",q.AliRtcConnectionStatusReconnecting,ct.AliRtcConnectionSignalingConnecting)}),this.signalingManager.on("onReconnectSuccess",e=>{A.event("[Signaling] Reconnect Success ",e),this.onNetworkRecovery(e)}),this.signalingManager.on("onReconnectFail",e=>{A.event("[Signaling] Reconnect Failed ",e),e.code===403&&this.emit("authInfoExpired")}),this.signalingManager.on("onError",e=>{A.event("[Signaling] Error ",e),this.onError(e)})}backToUnpublishStatus(){var e,t;this.connectState=q.AliRtcConnectionStatusDisconnected,(e=this.publisher)!=null&&e.isPublishing&&((t=this.publisher)==null||t.clearPublishState()),this.networkError=!1}handleUsersJoin(e){e.forEach(t=>{const r=t.userid;if(r){const s=this.userManager.addUser(r,t.displayname);A.event(`[${L.logName}]`,J.UserJoined,s)}})}onLocalDeviceStatusChange(e){A.event(`[${L.logName}]`,be.Local,e),this.signalingManager.reportStatus(e).then(()=>{A.debug("[signaling] reportStatus suc")}).catch(t=>{A.error("[signaling] reportStatus failed",t)})}resumePublishForNetworkRecovery(){return v(this,null,function*(){var e;try{yield(e=this.publisher)==null?void 0:e.resumePublish()}catch(t){const{code:r}=t;if(r===10205){let n=1;try{yield new Promise((o,c)=>{const u=setInterval(()=>v(this,null,function*(){var h;n>1&&(clearInterval(u),c()),n+=1;try{yield(h=this.publisher)==null?void 0:h.resumePublish(),clearInterval(u),o()}catch(l){const{code:d}=l;d!==10205&&(clearInterval(u),c())}}),1e3)})}catch(o){}}}})}onNetworkRecovery(e){return v(this,null,function*(){var t;A.event(L.logName,"onNetworkRecovery",{users:e}),this.networkError&&(this.networkError=!1,(t=this.publisher)==null||t.reportSelfDeviceStatus(),!this.userManager.rtsManager.isConnected&&this.userManager.rtsManager.isConnecting&&(yield this.resumePublishForNetworkRecovery(),yield this.resumeSubList(e)),this.connectState=q.AliRtcConnectionStatusConnected,this.emit("connectionStatusChange",q.AliRtcConnectionStatusConnected,ct.AliRtcConnectionSignalingHeartbeatAlive))})}resumeSubList(e){return v(this,null,function*(){if(e!=null&&e.length){const{joinList:t,leaveList:r,presentList:s}=this.userManager.updateUsers(e);A.info(`[${L.logName}]`,"resumeSubList",{joinList:t,leaveList:r,presentList:s}),this.handleUsersJoin(t),r.forEach(n=>{A.event(L.logName,J.UserLeft,n.userid,n.reason),this.emit("remoteUserOffLineNotify",n.userid,Fi.AliRtcUserOfflineQuit)});for(let n=0;n<s.length;n++){const o=s[n],c=o.userid,u=this.userManager.getRemoteUser(c);this.userManager.onRemotePublishStateChange(o),u==null||u.restore(),u==null||u.updateSubscribe()}}else for(let t=0;t<this.remoteUsers.length;t++){const r=this.remoteUsers[t];try{r.restore(),r.updateSubscribe()}catch(s){}}})}onNetworkError(){this.connectState===q.AliRtcConnectionStatusConnected&&(this.networkError||(this.connectState=q.AliRtcConnectionStatusDisconnected,this.emit("connectionStatusChange",q.AliRtcConnectionStatusDisconnected,ct.AliRtcConnectionChangedNetworkInterrupted)),this.networkError=!0)}onError(e){this.reporter.reportError(e),A.event(L.logName,J.Error,e)}setEnableDualVideoStream(e,t){t&&this.dualVideoPlugin.setOptions(t);const r=this.userManager.pluginManager.has(this.dualVideoPlugin.name);e?!r&&this.enablePlugin(this.dualVideoPlugin):r&&this.removePlugin(this.dualVideoPlugin.name)}hadPushStream(e){if(!(this.publisher&&e))throw new E(T.ERR_INNER,"stream is not publishing")}getCurrentMicDeviceId(){var e;return(e=this.publisher)==null?void 0:e.getCurrentMicDeviceId()}setChannelProfile(e){if(![q.AliRtcConnectionStatusInit,q.AliRtcConnectionStatusDisconnected,q.AliRtcConnectionStatusFailed].includes(this.connectState))throw new E(T.ERR_INNER,"cannot set channel profile in call");this.channelProfile=e,this.channelProfile===qe.AliRtcSdkCommunication&&(this.clientRole=Ze.AliRtcSdkLive),this.signalingManager.setChannelProfile(e)}setClientRole(e){return v(this,null,function*(){var t,r,s,n,o;try{if(this.channelProfile===qe.AliRtcSdkCommunication)return;if(!Object.values(Ze).includes(e))throw new E(T.ERR_INVALID_ARGUMENTS,`set client role error, role value(${e}) is invalid`);if(this.clientRole===e)return;this.isInCall()?this.clientRole===Ze.AliRtcSdkInteractive?(this.userManager.isSubscribing?(yield this.stopPublish(),yield(t=this.publisher)==null?void 0:t.clearStream()):yield(r=this.publisher)==null?void 0:r.unPublish(),yield this.signalingManager.setClientRole(e)):(yield this.signalingManager.setClientRole(e),yield this.startDefaultDevicesCapture(),(s=this.publisher)!=null&&s.isPublishing||(yield(n=this.publisher)==null?void 0:n.startPublish()),yield(o=this.publisher)==null?void 0:o.previewAll()):yield this.signalingManager.setClientRole(e),this.clientRole=e}catch(c){throw c.code===403&&this.emit("authInfoExpired"),c}})}getCurrentClientRole(){return this.clientRole}setAudioOnlyMode(e){if(this.isInCall())throw new E(T.ERR_INNER,"can not change audioOnly mode in call");this._audioOnlyMode=e}setAudioRedEnabled(e){if(this.isInCall())throw new E(T.ERR_INNER,"can not change audioRedEnabled in call");this.userManager.setAudioRedEnabled(e)}setCheckAuthInfoTimer(e,t){const r=(e-t)*1e3;this._authInfoExpiredTimer=window.setTimeout(()=>{this.emit("authInfoExpired")},r),this._authInfoWillExpireTimer=window.setTimeout(()=>{this.emit("authInfoWillExpire")},r-3e4),this._serverCheckAuthInfoTimestamp=t,this._localCheckAuthInfoTimestamp=+Date.now()/1e3}clearCheckAuthInfoTimer(){this._authInfoExpiredTimer&&window.clearTimeout(this._authInfoExpiredTimer),this._authInfoWillExpireTimer&&window.clearTimeout(this._authInfoWillExpireTimer)}startDefaultDevicesCapture(){return v(this,null,function*(){var r,s;let e=[],t;try{this._audioOnlyMode||(e=yield L.getCameraList(),e.length||console.warn("No media neither devices can be captured")),t=yield L.getMicrophoneList(),t.length||console.warn("No media neither devices can be captured");const{hasCamera:n,hasMicrophone:o,hasScreenShare:c,audioCaptureDisabled:u,publishLocalAudioStreamEnabled:h,publishLocalVideoStreamEnabled:l}=(r=this.publisher)!=null?r:{};if(n||o||c)return;!n&&l&&!this._audioOnlyMode&&e.length&&!((s=this.publisher)!=null&&s.cameraCaptureDisabled)&&(yield this.enableLocalVideo(!0)),!o&&h&&!u&&t.length&&(yield this.startAudioCapture())}catch(n){throw n}})}joinChannel(e,t,r,s){return v(this,null,function*(){var h,l,d,f,m,g;let n=s,o;if(typeof e=="string"){n=s;try{const S=JSON.parse(window.atob(e));if(o={appId:S.appid,channelId:S.channelid,userId:S.userid,timestamp:S.timestamp,nonce:S.nonce,token:S.token},o.channelId!==t)throw new Error("channelId is not equal");if(o.userId!==r)throw new Error("userId is not equal")}catch(S){throw new E(T.ERR_INVALID_ARGUMENTS,`authInfo is invalid: ${S.message||""}`)}}else o=e,n=t;let c=new Date().getTime(),u=lr.checkAuthInfo(o);if(this.webTrackingClient.updateAuthInfo(o),this.webTrackingClient.reportJoinChannel(o),q.AliRtcConnectionStatusInit===this.connectState||q.AliRtcConnectionStatusDisconnected===this.connectState||q.AliRtcConnectionStatusFailed===this.connectState){if(this.connectState=q.AliRtcConnectionStatusConnecting,u)throw this.connectState=q.AliRtcConnectionStatusFailed,this.webTrackingClient.reportJoinChannelRes(u.code,u.message,0),this.reporter.reportJoin(0,u.code,u.message),u;o.callid=Ye.createCallid(),this.reporter.start(o);try{const S=yield this.signalingManager.join(o,n,this.maxSignalingConnectRetryCount);this.connectState=q.AliRtcConnectionStatusConnected,(h=this.publisher)==null||h.reportSelfDeviceStatus();let b=new Date().getTime()-c;this.webTrackingClient.reportJoinChannelRes(0,"",b),this.reporter.reportJoin(b,0,S.tid),this.userManager.init(o,S),this.setCheckAuthInfoTimer(o.timestamp,S.timestamp),this.currentRoleCanPublish&&(yield this.startDefaultDevicesCapture(),Object.values((d=(l=this.publisher)==null?void 0:l.publishStreams)!=null?d:{}).some(w=>w)&&(yield(f=this.publisher)==null?void 0:f.startPublish(),yield(m=this.publisher)==null?void 0:m.previewAll())),this.remoteUsers.forEach(w=>{w.updateSubscribe()}),this.liveTranscoding.setAuthInfo(o)}catch(S){let b=new Date().getTime()-c;const w=(g=S.code)!=null?g:-1,_=S.reason||S.message||"";throw this.webTrackingClient.reportJoinChannelRes(w,_,b),this.connectState=q.AliRtcConnectionStatusDisconnected,this.reporter.reportJoin(b,w,""),new E(w,_)}}else{const S=new E(T.ERR_JOIN_ALREADY_JOINED,"already joined");throw this.connectState===q.AliRtcConnectionStatusConnecting&&(S.message="Repeated operation during login"),this.webTrackingClient.reportJoinChannelRes(S.code,S.message,0),this.reporter.reportJoin(0,S.code,""),S}})}leaveChannel(e=!1){return v(this,null,function*(){var r;this.reporter.reportLeaveInvoked(),this.webTrackingClient.reportLeaveChannel();let t=new Date().getTime();if(q.AliRtcConnectionStatusConnected===this.connectState)try{let s;e||(s=yield this.signalingManager.leave()),this.clearCheckAuthInfoTimer(),yield this.resetState(),this.reporter.reportLeave(new Date().getTime()-t,0,(r=s==null?void 0:s.tid)!=null?r:""),A.setFlushMode(!0);return}catch(s){throw this.reporter.reportLeave(new Date().getTime()-t,s.code,s.reason),s}else{yield this.resetState(),this.reporter.reportLeave(0,0,""),A.setFlushMode(!0);return}})}isInCall(){return this.connectState===q.AliRtcConnectionStatusConnected}refreshAuthInfo(e){return v(this,null,function*(){const{userId:t,nonce:r,timestamp:s,token:n,role:o}=e,c={userId:t,nonce:r,timestamp:s,token:n,role:o};try{yield this.signalingManager.refreshAuthInfo(c),this.userManager.refreshAuthInfo(c),this.liveTranscoding.refreshAuthInfo(c),this.clearCheckAuthInfoTimer(),this._serverCheckAuthInfoTimestamp&&this._localCheckAuthInfoTimestamp&&e.timestamp&&this.setCheckAuthInfoTimer(e.timestamp,this._serverCheckAuthInfoTimestamp+(Date.now()-this._localCheckAuthInfoTimestamp))}catch(u){throw u}})}isAudioOnly(){return this._audioOnlyMode}publishLocalAudioStream(e){return v(this,null,function*(){var t,r,s;(t=this.publisher)==null||t.setPublishLocalAudioStreamEnabled(e),this.connectState===q.AliRtcConnectionStatusConnected&&(e?(r=this.publisher)!=null&&r.hasMicrophone?yield(s=this.publisher)==null?void 0:s.publishUpdate():yield this.startAudioCapture():yield this.stopPublish({audio:!0}))})}isLocalAudioStreamPublished(){var e,t;return(t=(e=this.publisher)==null?void 0:e.publishLocalAudioStreamEnabled)!=null?t:!0}setDefaultSubscribeAllRemoteAudioStreams(e){this.userManager.setAutoSubAudio(e)}subscribeAllRemoteAudioStreams(e){this.userManager.setWantSubAudio(e)}subscribeRemoteAudioStream(e,t){if(t&&!this.userManager.isWantSubAudio)throw new E(T.ERR_INVALID_ARGUMENTS,"subscribeAllRemoteAudioStreams(true) must be called first");this.userManager.updateAudioWant(e,t)}resumeRemoteAudioStream(e){const t=this.userManager.getRemoteUser(e);t&&t.resumeAudio()}publishLocalVideoStream(e){return v(this,null,function*(){var t,r,s;(t=this.publisher)==null||t.setPublishLocalVideoStreamEnabled(e),this.connectState===q.AliRtcConnectionStatusConnected&&(e?(r=this.publisher)!=null&&r.hasCamera?yield(s=this.publisher)==null?void 0:s.publishUpdate():yield this.enableLocalVideo():yield this.stopPublish({video:!0}))})}isLocalVideoStreamPublished(){var e,t;return(t=(e=this.publisher)==null?void 0:e.publishLocalVideoStreamEnabled)!=null?t:!0}setRemoteDefaultVideoStreamType(e){[oe.AliRtcVideoStreamTypeHigh,oe.AliRtcVideoStreamTypeLow].includes(e)&&this.userManager.setRemoteDefaultVideoStreamType(e)}setRemoteUserVideoStreamType(e,t){[oe.AliRtcVideoStreamTypeHigh,oe.AliRtcVideoStreamTypeLow].includes(t)&&this.userManager.setRemoteUserVideoStreamType(e,t)}setDefaultSubscribeAllRemoteVideoStreams(e){this.userManager.setAutoSubVideo(e),this.userManager.setAutoSubScreen(e)}subscribeAllRemoteVideoStreams(e){this.userManager.setWantSubVideo(e),this.userManager.setWantSubScreen(e)}subscribeRemoteMediaStream(e,t,r,s){const n=this.userManager.getRemoteUser(e);if(!n)throw new E(T.ERR_INNER,`no remote user(${e}) founded`);r&&(t===j.AliRtcVideoTrackScreen||t===j.AliRtcVideoTrackBoth)?n.setWantSubScreen(!0):n.setWantSubScreen(!1),r&&(t===j.AliRtcVideoTrackCamera||t===j.AliRtcVideoTrackBoth)?n.setWantSubVideo(!0):n.setWantSubVideo(!1),n.setWantSubAudio(s),n.updateSubscribe()}resumeRemoteMediaStream(e,t){const r=this.userManager.getRemoteUser(e);r&&r.resumeVideo(t)}getOnlineRemoteUsers(){return this.userManager.remoteUsers.map(e=>e.userId)}getUserInfo(e){var t;return(t=this.userManager.getRemoteUser(e))==null?void 0:t.remoteUserInfo}isUserOnline(e){return!!this.userManager.remoteUsers.find(t=>t.userId===e)}startScreenShare(e){return v(this,null,function*(){var o;const t={video:!1,audio:!1},{audio:r=!1,videoTrack:s,audioTrack:n}=e||{};if(s||n){t.screen=!0;const c=new MediaStream;s&&c.addTrack(s),n&&c.addTrack(n),t.mediaStream=c}else t.screen=r?{audio:!0}:!0;yield(o=this.publisher)==null?void 0:o.createLocalStream(t)})}stopScreenShare(){return v(this,null,function*(){var e;(e=this.publisher)==null||e.stopLocalStream({screen:!0})})}setScreenShareConfiguration(e){return v(this,null,function*(){var s;const{frameRate:t=Ct.frameRate,bitrate:r=Ct.maxBitrate}=e;yield(s=this.publisher)==null?void 0:s.setScreenProfile(Jr,{width:Ct.width,height:Ct.height,frameRate:t,maxBitrate:r})})}setScreenShareContentHint(e){return v(this,null,function*(){var t;e&&((t=this.publisher)==null||t.setScreenContentHint(e))})}publishLocalScreenShareStream(e,t){return v(this,null,function*(){var r,s,n;(r=this.publisher)==null||r.setPublishLocalScreenStreamEnabled(e),this.connectState===q.AliRtcConnectionStatusConnected&&(e?(s=this.publisher)!=null&&s.hasScreenShare?yield(n=this.publisher)==null?void 0:n.publishUpdate():yield this.startScreenShare(t):yield this.stopPublish({screen:!0}))})}isScreenSharePublished(){var e,t;return(t=(e=this.publisher)==null?void 0:e.publishLocalScreenStreamEnabled)!=null?t:!0}setAudioShareVolume(e){if(typeof e!="number")throw new E(T.ERR_INVALID_ARGUMENTS,"volume must be a number");this.audioMixerPlugin.setOptions({screen:Math.max(0,Math.min(e,400))/100})}enableAudioVolumeIndication(e){this.userManager.enableAudioVolumeIndication(e)}muteLocalMic(e=!1){var t;this.isPublishing&&this.onLocalDeviceStatusChange(e?J.MuteAudio:J.UnmuteAudio),(t=this.publisher)==null||t.muteLocalMic(e)}muteRemoteAudioPlaying(e,t=!1){const r=this.userManager.getRemoteUser(e);if(!r)throw new E(T.ERR_INNER,`no remote user(${e}) founded`);r.setAudioMuted(t)}muteAllRemoteAudioPlaying(e=!1){this.userManager.setAudioMuted(e)}startAudioCapture(e){return v(this,null,function*(){var r;const t={audio:e||!0};yield(r=this.publisher)==null?void 0:r.createLocalStream(t)})}stopAudioCapture(){var e;(e=this.publisher)==null||e.stopAudioCapture()}switchMicrophone(e,t){return v(this,null,function*(){var r,s,n,o;if(yield(r=this.publisher)==null?void 0:r.setMicrophoneDeviceId(e),!((s=this.publisher)!=null&&s.audioCaptureDisabled)){if(t){yield(n=this.publisher)==null?void 0:n.createLocalStream({audio:!0,mediaStream:new MediaStream([t])});return}yield(o=this.publisher)==null?void 0:o.createLocalStream({audio:{deviceId:e}})}})}setRecordingVolume(e){if(typeof e!="number")throw new E(T.ERR_INVALID_ARGUMENTS,"volume must be a number");this.audioMixerPlugin.setOptions({audio:Math.max(0,Math.min(e,400))/100})}setPlayoutVolume(e){if(typeof e!="number")throw new E(T.ERR_INVALID_ARGUMENTS,"volume must be a number");this.userManager.setPlayoutVolume(Math.max(0,Math.min(e,100))/100)}setRemoteAudioVolume(e,t){const r=this.userManager.getRemoteUser(e);if(!r)throw new E(T.ERR_INNER,`no remote user(${e}) founded`);if(typeof t!="number")throw new E(T.ERR_INVALID_ARGUMENTS,"volume must be a number");r.setPlayoutVolume(Math.max(0,Math.min(t,100))/100)}setAudioProfile(e){return v(this,null,function*(){var t;yield(t=this.publisher)==null?void 0:t.setAudioProfile(e)})}getAudioTrack(e){return v(this,null,function*(){var r;if(!e)return(r=this.publisher)==null?void 0:r.audioTrack;const t=this.userManager.getRemoteUser(e);return t==null?void 0:t.getAudioTrack})}setLocalViewConfig(e,t){return v(this,null,function*(){var r,s,n;if(this._audioOnlyMode)throw new E(T.ERR_INNER,"Cannot set local view in audio only mode");(r=this.userManager)==null||r.setLocalViewConfig(e,t),t===j.AliRtcVideoTrackCamera&&((s=this.publisher)!=null&&s.hasCamera)?yield this.startPreview():t===j.AliRtcVideoTrackScreen&&((n=this.publisher)!=null&&n.hasScreenShare)&&(yield this.startPreviewScreen())})}setCameraCapturerConfiguration(e){return v(this,null,function*(){var u,h,l;const{width:t=kt.width,height:r=kt.height,frameRate:s=kt.frameRate,bitrate:n=kt.maxBitrate,cameraDirection:o,deviceId:c}=e;yield(u=this.publisher)==null?void 0:u.setVideoProfile(Kr,{width:t,height:r,frameRate:s,maxBitrate:n}),o!==void 0&&((h=this.publisher)==null||h.setCameraDirection(o)),c&&((l=this.publisher)==null||l.setCameraDeviceId(c))})}setCameraCapturerContentHint(e){return v(this,null,function*(){var t;e&&((t=this.publisher)==null||t.setVideoContentHint(e))})}enableLocalVideo(e=!0){return v(this,null,function*(){var t,r,s,n,o,c,u,h,l,d,f;if(this._audioOnlyMode)throw new E(T.ERR_INNER,"Cannot enable local video in audio only mode");if(e){(r=(t=this.publisher)==null?void 0:t.publishStreams)!=null&&r.video&&((o=(n=(s=this.publisher)==null?void 0:s.publishStreams)==null?void 0:n.video)==null||o.disableVideo(),(l=(h=(u=(c=this.publisher)==null?void 0:c.publishStreams)==null?void 0:u.video)==null?void 0:h.videoTrack)==null||l.stop());const m={video:!0};yield(d=this.publisher)==null?void 0:d.startCameraCapture(m)}else yield(f=this.publisher)==null?void 0:f.stopCameraCapture()})}muteLocalCamera(e){return v(this,null,function*(){var t;this.isPublishing&&this.onLocalDeviceStatusChange(e?J.MuteVideo:J.UnmuteVideo),(t=this.publisher)==null||t.muteLocalCamera(e)})}muteLocalScreen(e){return v(this,null,function*(){var t;this.isPublishing&&this.onLocalDeviceStatusChange(e?J.MuteScreen:J.UnmuteScreen),(t=this.publisher)==null||t.muteLocalScreen(e)})}setRemoteViewConfig(e,t,r){this.userManager.setRemoteViewConfig(t,e,r)}isCameraOn(){var e,t;return(t=(e=this.publisher)==null?void 0:e.hasCamera)!=null?t:!1}switchCamera(e,t){return v(this,null,function*(){var s,n,o,c,u,h,l,d,f,m,g,S;if(this._audioOnlyMode)throw new E(T.ERR_INNER,"Cannot switch camera in audio only mode");const r={};if(e?r.deviceId=e:r.cameraDirection=((s=this.publisher)==null?void 0:s.cameraDirection)==="environment"?Pt.CAMERA_FRONT:Pt.CAMERA_REAR,yield this.setCameraCapturerConfiguration(r),!((n=this.publisher)!=null&&n.cameraCaptureDisabled)){(c=(o=this.publisher)==null?void 0:o.publishStreams)!=null&&c.video&&((l=(h=(u=this.publisher)==null?void 0:u.publishStreams)==null?void 0:h.video)==null||l.disableVideo(),(g=(m=(f=(d=this.publisher)==null?void 0:d.publishStreams)==null?void 0:f.video)==null?void 0:m.videoTrack)==null||g.stop());const b={video:!0};t&&(b.mediaStream=new MediaStream([t])),yield(S=this.publisher)==null?void 0:S.createLocalStream(b)}})}getCurrentCameraDeviceId(){var e;return(e=this.publisher)==null?void 0:e.getCurrentCameraDeviceId()}startPreview(){return v(this,null,function*(){var e,t;if(this._audioOnlyMode)throw new E(T.ERR_INNER,"Cannot start preview camera in audio only mode");(e=this.publisher)!=null&&e.hasCamera||(yield this.enableLocalVideo(!0)),yield(t=this.publisher)==null?void 0:t.previewAll({screen:!1})})}startPreviewScreen(e){return v(this,null,function*(){var t,r;if(this._audioOnlyMode)throw new E(T.ERR_INNER,"Cannot start preview screen share in audio only mode");(t=this.publisher)!=null&&t.hasScreenShare||(yield this.startScreenShare(e)),yield(r=this.publisher)==null?void 0:r.previewAll({primary:!1})})}stopPreview(){return v(this,null,function*(){var e;yield(e=this.publisher)==null?void 0:e.stopPreview({primary:!0,screen:!1})})}stopPreviewScreen(){return v(this,null,function*(){var e;yield(e=this.publisher)==null?void 0:e.stopPreview({primary:!1,screen:!0})})}getVideoTrack(e){return v(this,null,function*(){var n,o,c,u;const{userId:t,streamType:r}=e;if(!t)return r===ae.AliRtcSdkStreamTypeCapture?(n=this.publisher)==null?void 0:n.cameraTrack:(o=this.publisher)==null?void 0:o.screenTrack;const s=this.userManager.getRemoteUser(t);return r===ae.AliRtcSdkStreamTypeCapture?(c=s==null?void 0:s.getCameraStream)==null?void 0:c.videoTrack:(u=s==null?void 0:s.getScreenStream)==null?void 0:u.videoTrack})}startPublishLiveStream(e,t){return v(this,null,function*(){return this.liveTranscoding.startPublishLiveStream(e,t)})}updatePublishLiveStream(e,t){return v(this,null,function*(){return this.liveTranscoding.updatePublishLiveStream(e,t)})}updatePublishLiveStreamWithTaskId(e,t){return this.liveTranscoding.updatePublishLiveStreamWithTaskId(e,t)}stopPublishLiveStream(e){return v(this,null,function*(){return this.liveTranscoding.stopPublishLiveStream(e)})}stopPublishLiveStreamWithTaskId(e){return this.liveTranscoding.stopPublishLiveStreamWithTaskId(e)}setEnableMediaExtensionMsg(e){var t;(t=this.userManager)==null||t.setEnableMediaExtensionMsg(!!e)}sendMediaExtensionMsg(e,t){return v(this,null,function*(){return this.sendMediaExtensionMsgEx(e,t,5)})}sendMediaExtensionMsgEx(e,t,r){return v(this,null,function*(){var s;if(!this.publisher||!this.isPublishing)throw new E(T.ERR_INNER,"you should publish first");return(s=this.publisher)==null?void 0:s.sendSEI(e,t,r)})}enablePlugin(e,t){this.userManager.pluginManager.add(e,t)}removePlugin(e){this.userManager.pluginManager.remove(e)}setPluginOption(e,t){const r=this.userManager.pluginManager.get(e);r&&t&&r.setOptions(t)}getPluginOption(e){const t=this.userManager.pluginManager.get(e);return t==null?void 0:t.getOptions()}isBeautyAvailable(){return this.userManager.pluginManager.has("AliRtcBeauty")}isBeautyEnabled(){const e=this.userManager.pluginManager.get("AliRtcBeauty");if(!e)throw new E(it.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");return!!(e!=null&&e.isEnable)}setBeautyEffect(e,t){const r=this.userManager.pluginManager.get("AliRtcBeauty");if(!r)throw new E(it.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");e?r.enable():r.disable(),r.setOptions({basicBeauty:{skinBuffing:Math.max(Math.min(1,+t.smoothnessLevel),0),whitening:Math.max(Math.min(1,+t.whiteningLevel),0)}})}enableBackgroundExchange(e,t){const r=this.userManager.pluginManager.get("AliRtcBeauty");if(!r||!r.isEnable)throw new E(it.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const s={setSegmentBackgroundImage:{backgroundImgUrl:e?t:""}};e&&(s.segmentBackgroundProcess={enable:!1}),r.setOptions(s)}enableBackgroundBlur(e){const t=this.userManager.pluginManager.get("AliRtcBeauty");if(!t||!t.isEnable)throw new E(it.AliRtcPluginErrorNoFindPlugin,"you should enable beautyPlugin first");const r={segmentBackgroundProcess:{type:0,enable:e}};e&&(r.setSegmentBackgroundImage={type:0,backgroundImgUrl:""}),t.setOptions(r)}},p(L,"logName","AliRtcEngine"),p(L,"logError",!0),p(L,"isSupported",Aa),p(L,"isDualVideoStreamSupported",hr.isSupport),p(L,"getCameraList",()=>v(L,null,function*(){return(yield D.AliRTS.getCameraList()).filter(t=>t.deviceId)})),p(L,"getMicrophoneList",()=>v(L,null,function*(){return(yield D.AliRTS.getMicList()).filter(t=>t.deviceId)})),p(L,"getSpeakerList",()=>v(L,null,function*(){return(yield D.AliRTS.getSpeakerList()).filter(t=>t.deviceId)})),p(L,"_instance"),p(L,"AliRtcSdkChannelProfile",qe),p(L,"AliRtcSdkClientRole",Ze),p(L,"AliRtcVideoStreamType",oe),p(L,"AliRtcVideoTrack",j),p(L,"AliRtcAudioTrack",bt),p(L,"AliRtcPublishState",B),p(L,"AliRtcSubscribeState",Z),p(L,"AliRtcRawDataStreamType",ae),p(L,"AliRtcLogLevel",Li),p(L,"AliRtcEngineLocalDeviceType",je),p(L,"AliRtcEngineLocalDeviceExceptionType",te),p(L,"AliRtcConnectionStatus",q),p(L,"AliRtcConnectionStatusChangeReason",ct),p(L,"AliRtcPlugin",mt),p(L,"AliRtcPluginTrackType",Jt),p(L,"AliRtcLiveTranscodingParam",zt),p(L,"AliRtcLiveTranscodingEncodeParam",Bi),p(L,"AliRtcLiveTranscodingMixParam",Fs),p(L,"AliRtcLiveTranscodingSingleParam",js),p(L,"AliRtcTranscodingClockWidget",$s),p(L,"AliRtcTranscodingImage",dr),p(L,"AliRtcTranscodingText",Ks),p(L,"AliRtcTranscodingUser",Js),p(L,"AliRtcLiveTranscodingMixMode",It),p(L,"AliRtcLiveTranscodingStreamType",Oi),p(L,"AliRtcLiveTranscodingSourceType",St),p(L,"AliRtcLiveTranscodingTaskProfile",Vi),p(L,"AliRtcLiveTranscodingAudioSampleRate",qt),p(L,"AliRtcLiveTranscodingSegmentType",At),p(L,"AliRtcLiveTranscodingFontType",Tt),p(L,"AliRtcLiveTranscodingCropMode",Di),p(L,"AliRtcLiveTranscodingMediaProcessMode",Gt),p(L,"AliRtcLiveTranscodingState",xi),p(L,"AliRtcLiveTranscodingErrorCode",Fe),p(L,"AliRtcTrascodingPublishTaskStatus",Ui),p(L,"Plugin",mt),L);C([y()],k.prototype,"destroy",1),C([y()],k.prototype,"resetState",1),C([y(I)],k.prototype,"stopPublish",1),C([y()],k.prototype,"backToUnpublishStatus",1),C([y()],k.prototype,"resumePublishForNetworkRecovery",1),C([y()],k.prototype,"onNetworkRecovery",1),C([y()],k.prototype,"resumeSubList",1),C([y(I)],k.prototype,"setEnableDualVideoStream",1),C([y(I)],k.prototype,"setChannelProfile",1),C([y(I)],k.prototype,"setClientRole",1),C([y(I)],k.prototype,"setAudioOnlyMode",1),C([y(I)],k.prototype,"joinChannel",1),C([y(I)],k.prototype,"leaveChannel",1),C([y(I)],k.prototype,"refreshAuthInfo",1),C([y(I)],k.prototype,"publishLocalAudioStream",1),C([y(I)],k.prototype,"setDefaultSubscribeAllRemoteAudioStreams",1),C([y(I)],k.prototype,"subscribeAllRemoteAudioStreams",1),C([y(I)],k.prototype,"subscribeRemoteAudioStream",1),C([y(I)],k.prototype,"resumeRemoteAudioStream",1),C([y(I)],k.prototype,"publishLocalVideoStream",1),C([y(I)],k.prototype,"setRemoteDefaultVideoStreamType",1),C([y(I)],k.prototype,"setRemoteUserVideoStreamType",1),C([y(I)],k.prototype,"setDefaultSubscribeAllRemoteVideoStreams",1),C([y(I)],k.prototype,"subscribeAllRemoteVideoStreams",1),C([y(I)],k.prototype,"subscribeRemoteMediaStream",1),C([y(I)],k.prototype,"resumeRemoteMediaStream",1),C([y(([i])=>[`${i==null?void 0:i.audio}`])],k.prototype,"startScreenShare",1),C([y()],k.prototype,"stopScreenShare",1),C([y(I)],k.prototype,"setScreenShareConfiguration",1),C([y(I)],k.prototype,"setScreenShareContentHint",1),C([y()],k.prototype,"publishLocalScreenShareStream",1),C([y(I)],k.prototype,"setAudioShareVolume",1),C([y(I)],k.prototype,"enableAudioVolumeIndication",1),C([y(I)],k.prototype,"muteLocalMic",1),C([y(I)],k.prototype,"muteRemoteAudioPlaying",1),C([y(I)],k.prototype,"muteAllRemoteAudioPlaying",1),C([y(I)],k.prototype,"startAudioCapture",1),C([y()],k.prototype,"stopAudioCapture",1),C([y(I)],k.prototype,"switchMicrophone",1),C([y(I)],k.prototype,"setRecordingVolume",1),C([y(I)],k.prototype,"setPlayoutVolume",1),C([y(I)],k.prototype,"setRemoteAudioVolume",1),C([y(I)],k.prototype,"setAudioProfile",1),C([y(I)],k.prototype,"getAudioTrack",1),C([y(I)],k.prototype,"setLocalViewConfig",1),C([y(I)],k.prototype,"setCameraCapturerConfiguration",1),C([y(I)],k.prototype,"setCameraCapturerContentHint",1),C([y(I)],k.prototype,"enableLocalVideo",1),C([y(I)],k.prototype,"muteLocalCamera",1),C([y(I)],k.prototype,"muteLocalScreen",1),C([y(I)],k.prototype,"setRemoteViewConfig",1),C([y(I)],k.prototype,"switchCamera",1),C([y()],k.prototype,"startPreview",1),C([y()],k.prototype,"startPreviewScreen",1),C([y()],k.prototype,"stopPreview",1),C([y()],k.prototype,"stopPreviewScreen",1),C([y()],k.prototype,"startPublishLiveStream",1),C([y()],k.prototype,"updatePublishLiveStream",1),C([y()],k.prototype,"updatePublishLiveStreamWithTaskId",1),C([y()],k.prototype,"stopPublishLiveStream",1),C([y()],k.prototype,"stopPublishLiveStreamWithTaskId",1),C([y(I)],k.prototype,"setEnableMediaExtensionMsg",1),C([y(([i,a,e])=>[i.length,a,e])],k.prototype,"sendMediaExtensionMsgEx",1),C([y(([i,a])=>[i.name||"",a])],k.prototype,"enablePlugin",1),C([y(I)],k.prototype,"removePlugin",1),C([y(I)],k.prototype,"setPluginOption",1),C([y(I)],k.prototype,"getPluginOption",1),C([y(I)],k.prototype,"setBeautyEffect",1),C([y(I)],k.prototype,"enableBackgroundExchange",1),C([y(I)],k.prototype,"enableBackgroundBlur",1),C([y(I)],k,"setLogLevel",1);let qs=k;const Gs=new Mi({businessName:"imp-web-rtc",version:(zs=qs.getSdkVersion())!=null?zs:"unknown",env:"prod"});Gs.setReady();const yc=Gs.wrap(qs);P.AliRtcConnectionStatus=q,P.AliRtcConnectionStatusChangeReason=ct,P.AliRtcEngineLocalDeviceExceptionType=te,P.AliRtcEngineLocalDeviceType=je,P.AliRtcErrorCode=T,P.AliRtcLiveTranscodingAudioSampleRate=qt,P.AliRtcLiveTranscodingCropMode=Di,P.AliRtcLiveTranscodingEncodeParam=Bi,P.AliRtcLiveTranscodingErrorCode=Fe,P.AliRtcLiveTranscodingFontType=Tt,P.AliRtcLiveTranscodingMediaProcessMode=Gt,P.AliRtcLiveTranscodingMixMode=It,P.AliRtcLiveTranscodingMixParam=Fs,P.AliRtcLiveTranscodingParam=zt,P.AliRtcLiveTranscodingSegmentType=At,P.AliRtcLiveTranscodingSingleParam=js,P.AliRtcLiveTranscodingSourceType=St,P.AliRtcLiveTranscodingState=xi,P.AliRtcLiveTranscodingStreamType=Oi,P.AliRtcLiveTranscodingTaskProfile=Vi,P.AliRtcLocalStreamInfo=Gi,P.AliRtcLogLevel=Li,P.AliRtcPlugin=mt,P.AliRtcPluginTrackType=Jt,P.AliRtcPluginType=Hr,P.AliRtcPublishState=B,P.AliRtcRawDataStreamType=ae,P.AliRtcRemoteUserInfo=Yr,P.AliRtcSdkChannelProfile=qe,P.AliRtcSdkClientRole=Ze,P.AliRtcSubscribeState=Z,P.AliRtcTranscodingClockWidget=$s,P.AliRtcTranscodingImage=dr,P.AliRtcTranscodingText=Ks,P.AliRtcTranscodingUser=Js,P.AliRtcTrascodingPublishTaskStatus=Ui,P.AliRtcVideoStreamType=oe,P.AliRtcVideoTrack=j,P.default=yc,Object.defineProperties(P,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|